esp32.js 320 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984
  1. /* additional text */
  2. Blockly.Blocks['text_split_string_by_delimiter'] = {
  3. init: function () {
  4. this.appendValueInput("string_input")
  5. .setCheck(null)
  6. .appendField(Blockly.Msg.text_additional_delimiter_string);
  7. this.appendDummyInput()
  8. .appendField(Blockly.Msg.text_additional_delimiter_deli)
  9. .appendField(new Blockly.FieldTextInput(","), "delimiter")
  10. .appendField(Blockly.Msg.text_additional_delimiter_end);
  11. this.setInputsInline(true);
  12. this.setOutput(true, null);
  13. this.setColour("#33cc99");
  14. this.setTooltip(Blockly.Msg.Text_Split_String_By_Delimiter_TOOLTIP);
  15. this.setHelpUrl("");
  16. }
  17. };
  18. Blockly.Python['text_split_string_by_delimiter'] = function (block) {
  19. var value_string_input = Blockly.Python.valueToCode(block, 'string_input', Blockly.Python.ORDER_ATOMIC);
  20. var text_delimiter = block.getFieldValue('delimiter');
  21. // TODO: Assemble Python into code variable.
  22. var code = value_string_input + '.split("' + text_delimiter + '")';
  23. // TODO: Change ORDER_NONE to the correct strength.
  24. return [code, Blockly.Python.ORDER_NONE];
  25. };
  26. /* additional math */
  27. Blockly.Blocks['math_degrad'] = {
  28. init: function () {
  29. this.appendValueInput("convert")
  30. .setCheck(null)
  31. .appendField(new Blockly.FieldDropdown([
  32. [Blockly.Msg.math_degrad_rad, "radians"],
  33. [Blockly.Msg.math_degrad_deg, "degrees"]
  34. ]), "rad_deg");
  35. this.setOutput(true, null);
  36. this.setColour("#5472ea");
  37. // this.setTooltip("");
  38. this.setHelpUrl("");
  39. var thisBlock = this;
  40. this.setTooltip(function () {
  41. var mode = thisBlock.getFieldValue('rad_deg');
  42. var TOOLTIPS = {
  43. 'radians': Blockly.Msg.Math_Degrad_RAD_TOOLTIP,
  44. 'degrees': Blockly.Msg.Math_Degrad_DEG_TOOLTIP
  45. };
  46. return TOOLTIPS[mode];
  47. });
  48. }
  49. };
  50. Blockly.Python['math_degrad'] = function (block) {
  51. var dropdown_rad_deg = block.getFieldValue('rad_deg');
  52. var value_convert = Blockly.Python.valueToCode(block, 'convert', Blockly.Python.ORDER_ATOMIC);
  53. // TODO: Assemble Python into code variable.
  54. Blockly.Python.definitions_['import_math'] = 'import math\n';
  55. var code = 'math.' + dropdown_rad_deg + '(' + value_convert + ')';
  56. // TODO: Change ORDER_NONE to the correct strength.
  57. return [code, Blockly.Python.ORDER_NONE];
  58. };
  59. /* Serial Comm. */
  60. Blockly.Blocks['serial_comm_print'] = {
  61. init: function () {
  62. this.appendValueInput("serial_comm_input")
  63. .setCheck("String")
  64. .appendField(Blockly.Msg.serialcomm_print);
  65. this.setInputsInline(false);
  66. this.setPreviousStatement(true, null);
  67. this.setNextStatement(true, null);
  68. this.setColour("#22b845");
  69. this.setTooltip(Blockly.Msg.serial_Comm_Print_TOOLTIP);
  70. this.setHelpUrl("");
  71. }
  72. };
  73. Blockly.Python['serial_comm_print'] = function (block) {
  74. var value_name = Blockly.Python.valueToCode(block, 'serial_comm_input', Blockly.Python.ORDER_ATOMIC);
  75. // TODO: Assemble Python into code variable.
  76. var code = 'print(' + value_name + ')\n';
  77. return code;
  78. };
  79. Blockly.Blocks['serial_send_data_to_control_panel'] = {
  80. init: function () {
  81. this.appendDummyInput()
  82. .appendField(new Blockly.FieldImage("blockly/media/control.png", 90, 70, { alt: "*", flipRtl: "FALSE" }));
  83. this.appendDummyInput()
  84. .appendField(Blockly.Msg.serialcomm_write_data_bps_title)
  85. .appendField("9600")
  86. .appendField(Blockly.Msg.serialcomm_write_data_bps_attrib);
  87. this.appendValueInput("NAME")
  88. // .appendField(Blockly.Msg.serial_send_data_on)
  89. .appendField(Blockly.Msg.serial_send_data_on_send_data_control_panel);
  90. this.setInputsInline(false);
  91. this.setColour("#22b845");
  92. this.setPreviousStatement(true, null);
  93. this.setNextStatement(true, null);
  94. this.setHelpUrl("");
  95. this.setTooltip(Blockly.Msg.serial_send_data_on_send_data_control_panel);
  96. }
  97. };
  98. Blockly.Python['serial_send_data_to_control_panel'] = function (block) {
  99. var value_name = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC) || "";
  100. // TODO: Assemble Python into code variable.
  101. Blockly.Python.definitions_["831_import_serial"] = `import serial
  102. SERIAL = serial.Serial("/dev/ttyS1",9600)`
  103. var code = `uart_data = bytes(${value_name}+"\\n","utf-8")
  104. SERIAL.write(uart_data)
  105. `;
  106. return code;
  107. };
  108. /*
  109. INPUT & OUTPUT
  110. */
  111. var ESP32_IO_COLOR = "#ff8027";
  112. Blockly.Blocks['esp32_main_controller_text_print'] = {
  113. init: function () {
  114. this.jsonInit({
  115. "message0": Blockly.Msg.TEXT_PRINT_TITLE,
  116. "args0": [{
  117. "type": "input_value",
  118. "name": "TEXT"
  119. }],
  120. "previousStatement": null,
  121. "nextStatement": null,
  122. "colour": "#33cc99",
  123. "tooltip": Blockly.Msg.TEXT_PRINT_TOOLTIP,
  124. "helpUrl": Blockly.Msg.TEXT_PRINT_HELPURL
  125. });
  126. }
  127. };
  128. Blockly.Python['esp32_main_controller_text_print'] = function (block) {
  129. // Print statement.
  130. var msg = Blockly.Python.valueToCode(block, 'TEXT',
  131. Blockly.Python.ORDER_NONE) || '___';
  132. return 'print(' + msg + ')\n';
  133. };
  134. Blockly.Blocks['esp32_main_controller_text'] = {
  135. init: function () {
  136. this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);
  137. this.setColour("#33cc99");
  138. this.appendDummyInput()
  139. .appendField(this.newQuote_(true))
  140. .appendField(new Blockly.FieldTextInput(''), 'TEXT')
  141. .appendField(this.newQuote_(false));
  142. this.setOutput(true, 'String');
  143. // Assign 'this' to a variable for use in the tooltip closure below.
  144. var thisBlock = this;
  145. // Text block is trivial. Use tooltip of parent block if it exists.
  146. this.setTooltip(function () {
  147. var parent = thisBlock.getParent();
  148. return (parent && parent.getInputsInline() && parent.tooltip) ||
  149. Blockly.Msg.TEXT_TEXT_TOOLTIP;
  150. });
  151. },
  152. newQuote_: function (open) {
  153. if (open == this.RTL) {
  154. var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==';
  155. } else {
  156. var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC';
  157. }
  158. return new Blockly.FieldImage(file, 12, 12, '"');
  159. }
  160. };
  161. Blockly.Python['esp32_main_controller_text'] = function (block) {
  162. // Text value.
  163. var code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
  164. return [code, Blockly.Python.ORDER_ATOMIC];
  165. };
  166. Blockly.Blocks['esp32_main_controller_io_from_digital_pin'] = {
  167. init: function () {
  168. this.appendDummyInput()
  169. .appendField(Blockly.Msg.digital_get)
  170. .appendField(new Blockly.FieldDropdown([
  171. ["S1", "1"],
  172. ["S2", "2"],
  173. ["PH7", "7"],
  174. ["PH8", "8"],
  175. ["PH13", "13"],
  176. ["CLK", "PC0"],
  177. ["CS0", "PC1"],
  178. ["MOSI", "PC2"],
  179. ["MISO", "PC3"],
  180. ["TXD", "PG6"],
  181. ["RXD", "PG7"],
  182. ["P0", "21"],
  183. ["P1", "22"],
  184. ["P2", "23"],
  185. ["P3", "24"],
  186. ["A0", "25"],
  187. ["A1", "26"],
  188. ["A2", "27"],
  189. ["A3", "28"]
  190. // ["12", "12"]
  191. ]), "analog_pin");
  192. this.appendDummyInput()
  193. .appendField(Blockly.Msg.digital_get_value);
  194. this.setInputsInline(true);
  195. this.setOutput(true, null);
  196. this.setColour(ESP32_IO_COLOR);
  197. this.setHelpUrl("");
  198. this.setTooltip("");
  199. }
  200. };
  201. Blockly.Python['esp32_main_controller_io_from_digital_pin'] = function (block) {
  202. var value_name = block.getFieldValue('analog_pin');
  203. // TODO: Assemble Python into code variable.
  204. // TODO: Assemble Python into code variable.
  205. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  206. Blockly.Python.definitions_['v831_import_time'] = `import time`
  207. Blockly.Python.definitions_['v831_import_os'] = `import os`
  208. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  209. sys.path.append("/root/")`
  210. var code = ""
  211. if (value_name == 2 || value_name == 1) {
  212. Blockly.Python.definitions_['v831_import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;
  213. Blockly.Python.addVariable('_Math_gpio_' + value_name, `_Math_gpio_${value_name} = multiFuncGpio(${value_name - 1},2)`, true);
  214. code = `_Math_gpio_${value_name}.digitalRead()`;
  215. } else if (value_name == "PG6" || value_name == "PG7" || value_name == "PC0" || value_name == "PC1" || value_name == "PC2" || value_name == "PC3") {
  216. // Blockly.Python
  217. Blockly.Python.addFunction("pinMode", `def pinMode(pin,mode):
  218. os.system(f"echo {pin} {mode} > /sys/kernel/debug/sunxi_pinctrl/function")
  219. `)
  220. Blockly.Python.addFunction("digitalWrite", `def digitalWrite(pin,level):
  221. if pin == "PC1" or pin == "PC0" or pin == "PC2" or pin == "PC3":
  222. os.system(f"echo {pin} {level} > /sys/kernel/debug/sunxi_pinctrl/function")
  223. os.system(f"echo {pin} {level} > /sys/kernel/debug/sunxi_pinctrl/data")
  224. `)
  225. Blockly.Python.addFunction("digitalRead", `def digitalRead(pin):
  226. if pin == "PC1" or pin == "PC0" or pin == "PC2" or pin == "PC3":
  227. os.system("echo {pin} 2 > /sys/kernel/debug/sunxi_pinctrl/pull")
  228. os.system(f"echo {pin} > /sys/kernel/debug/sunxi_pinctrl/sunxi_pin")
  229. return int(os.popen("cat /sys/kernel/debug/sunxi_pinctrl/data").read()[-2:])
  230. `)
  231. Blockly.Python.addFunction("setToSpi", `def setToSpi():
  232. os.system("echo PC0 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  233. os.system("echo PC1 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  234. os.system("echo PC2 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  235. os.system("echo PC3 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  236. os.system("echo PC0 0 > /sys/kernel/debug/sunxi_pinctrl/pull")
  237. os.system("echo PC1 1 > /sys/kernel/debug/sunxi_pinctrl/pull")
  238. os.system("echo PC2 0 > /sys/kernel/debug/sunxi_pinctrl/pull")
  239. os.system("echo PC3 0 > /sys/kernel/debug/sunxi_pinctrl/pull")
  240. `)
  241. Blockly.Python.addFunction("setToSerial", `def setToSerial():
  242. os.system("echo PG6 5 > /sys/kernel/debug/sunxi_pinctrl/function")
  243. os.system("echo PG7 5 > /sys/kernel/debug/sunxi_pinctrl/function")
  244. `)
  245. Blockly.Python.addVariable(`pinMode${value_name}`,`pinMode("${value_name}","0")`,true)
  246. code = `digitalRead("${value_name}")`
  247. }
  248. else if(value_name == 7 || value_name == 8 || value_name == 13) {
  249. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON `;
  250. Blockly.Python.addFunction("getBUTTONNum",`def getBUTTONNum(data):
  251. if data:
  252. return 1
  253. else:
  254. return 0
  255. `)
  256. Blockly.Python.addVariable('_Math_gpio_' + value_name, `_Math_gpio_${value_name} = BUTTON(${value_name})`, true);
  257. code = `getBUTTONNum(_Math_gpio_${value_name}.is_pressed())`;
  258. }else{
  259. let gpioNum = value_name - 21
  260. Blockly.Python.definitions_['v831_import_CocoPi_extGpio'] = `from CocoPi import extGpio`;
  261. Blockly.Python.definitions_['v831_import_CocoPi_extGpio_init'] = `InputGpio = extGpio()`;
  262. Blockly.Python.addVariable('InputGpio' + value_name, `InputGpio.pinMode(${gpioNum},0)`, true);
  263. code = `InputGpio.digitalRead(${gpioNum})`
  264. }
  265. // TODO: Change ORDER_NONE to the correct strength.
  266. return [code, Blockly.Python.ORDER_CONDITIONAL];
  267. };
  268. Blockly.Blocks['esp32_main_controller_io_high_low'] = {
  269. init: function () {
  270. this.appendDummyInput()
  271. .appendField(new Blockly.FieldDropdown([
  272. [Blockly.Msg.io_high, "1"],
  273. [Blockly.Msg.io_low, "0"]
  274. ]), "high_low");
  275. this.setInputsInline(true);
  276. this.setOutput(true, null);
  277. this.setColour(ESP32_IO_COLOR);
  278. this.setHelpUrl("");
  279. var thisBlock = this;
  280. this.setTooltip(function () {
  281. var mode = thisBlock.getFieldValue('high_low');
  282. var TOOLTIPS = {
  283. '1': Blockly.Msg.Esp32_Main_Controller_Io_High_Low_TOOLTIP.replace('%1', Blockly.Msg.io_high),
  284. '0': Blockly.Msg.Esp32_Main_Controller_Io_High_Low_TOOLTIP.replace('%1', Blockly.Msg.io_low)
  285. };
  286. return TOOLTIPS[mode];
  287. });
  288. }
  289. };
  290. Blockly.Python['esp32_main_controller_io_high_low'] = function (block) {
  291. var dropdown_name = block.getFieldValue('high_low');
  292. // TODO: Assemble Python into code variable.
  293. var code = dropdown_name;
  294. // TODO: Change ORDER_NONE to the correct strength.
  295. return [code, Blockly.Python.ORDER_NONE];
  296. };
  297. Blockly.Blocks['esp32_main_controller_io_analog_pin_1'] = {
  298. init: function () {
  299. this.appendDummyInput()
  300. .appendField(Blockly.Msg.Esp32_Main_Controller_Io_analog_pin_1)
  301. .appendField(new Blockly.FieldDropdown([
  302. ["0", "0"],
  303. ["1", "1"],
  304. ["2", "2"],
  305. ["3", "3"],
  306. ["13", "13"],
  307. ["14", "14"],
  308. ["15", "15"],
  309. ["17", "17"],
  310. ["21", "21"],
  311. ["22", "22"],
  312. ["23", "23"],
  313. ["24", "24"],
  314. ["29", "29"],
  315. ["30", "30"]
  316. ]), "analog_pin");
  317. this.setInputsInline(true);
  318. this.setOutput(true, null);
  319. this.setColour(ESP32_IO_COLOR);
  320. this.setHelpUrl("");
  321. var thisBlock = this;
  322. this.setTooltip(function () {
  323. var mode = thisBlock.getFieldValue('analog_pin');
  324. var TOOLTIPS = {
  325. '0': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '0'),
  326. '1': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '1'),
  327. '2': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '2'),
  328. '3': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '3'),
  329. '13': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '13'),
  330. '14': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '14'),
  331. '15': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '15'),
  332. '17': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '17'),
  333. '21': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '21'),
  334. '22': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '22'),
  335. '23': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '23'),
  336. '24': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '24'),
  337. '29': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '29'),
  338. '30': Blockly.Msg.esp32_main_controller_io_analog_pin_1_TOOLTIP.replace('%1', '30')
  339. };
  340. return TOOLTIPS[mode];
  341. });
  342. }
  343. };
  344. Blockly.Python['esp32_main_controller_io_analog_pin_1'] = function (block) {
  345. var dropdown_name = block.getFieldValue('analog_pin');
  346. // TODO: Assemble Python into code variable.
  347. var code = dropdown_name;
  348. // TODO: Change ORDER_NONE to the correct strength.
  349. return [code, Blockly.Python.ORDER_NONE];
  350. };
  351. Blockly.Blocks['esp32_main_controller_io_analog_pin_2'] = {
  352. init: function () {
  353. this.appendDummyInput()
  354. .appendField(Blockly.Msg.Esp32_Main_Controller_Io_analog_pin_2)
  355. .appendField(new Blockly.FieldDropdown([
  356. ["4", "4"],
  357. ["12", "12"],
  358. ["13", "13"],
  359. ["14", "14"],
  360. ["15", "15"],
  361. ["16", "16"],
  362. ["17", "17"],
  363. ["21", "21"],
  364. ["22", "22"],
  365. ["25", "25"],
  366. ["27", "27"],
  367. ["34", "34"],
  368. ["35", "35"],
  369. ["36", "36"]
  370. ]), "analog_pin");
  371. this.setInputsInline(true);
  372. this.setOutput(true, null);
  373. this.setColour(ESP32_IO_COLOR);
  374. this.setHelpUrl("");
  375. var thisBlock = this;
  376. this.setTooltip(function () {
  377. var mode = thisBlock.getFieldValue('analog_pin');
  378. var TOOLTIPS = {
  379. '4': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '4'),
  380. '12': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '12'),
  381. '13': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '13'),
  382. '14': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '14'),
  383. '15': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '15'),
  384. '16': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '16'),
  385. '17': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '17'),
  386. '21': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '21'),
  387. '22': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '22'),
  388. '25': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '25'),
  389. '27': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '27'),
  390. '34': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '34'),
  391. '35': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '35'),
  392. '36': Blockly.Msg.esp32_main_controller_io_analog_pin_2_TOOLTIP.replace('%1', '36')
  393. };
  394. return TOOLTIPS[mode];
  395. });
  396. }
  397. };
  398. Blockly.Python['esp32_main_controller_io_analog_pin_2'] = function (block) {
  399. var dropdown_name = block.getFieldValue('analog_pin');
  400. // TODO: Assemble Python into code variable.
  401. var code = dropdown_name;
  402. // TODO: Change ORDER_NONE to the correct strength.
  403. return [code, Blockly.Python.ORDER_NONE];
  404. };
  405. Blockly.Blocks['esp32_main_controller_io_set_digital_pin'] = {
  406. init: function () {
  407. this.appendDummyInput()
  408. .appendField("")
  409. .appendField(Blockly.Msg.digital_set);
  410. this.appendDummyInput()
  411. .appendField("")
  412. .appendField(new Blockly.FieldDropdown([
  413. ["S1", "1"],
  414. ["S2", "2"],
  415. ["CLK", "PC0"],
  416. ["CS0", "PC1"],
  417. ["MOSI", "PC2"],
  418. ["MISO", "PC3"],
  419. ["TXD", "PG6"],
  420. ["RXD", "PG7"],
  421. ["P0", "10"],
  422. ["P1", "11"],
  423. ["P2", "12"],
  424. ["P3", "13"],
  425. ["A0", "14"],
  426. ["A1", "15"],
  427. ["A2", "16"],
  428. ["A3", "17"]
  429. ]), "digital_set_type_gpio").appendField("");
  430. this.appendDummyInput()
  431. .appendField(Blockly.Msg.digital_set_as);
  432. this.appendValueInput("high_low")
  433. .setCheck(null);
  434. this.setInputsInline(true);
  435. this.setPreviousStatement(true, null);
  436. this.setNextStatement(true, null);
  437. this.setColour(ESP32_IO_COLOR);
  438. this.setHelpUrl("");
  439. var thisBlock = this;
  440. this.setTooltip(function () {
  441. var mode = thisBlock.getFieldValue('digital_set_type');
  442. var TOOLTIPS = {
  443. '1': Blockly.Msg.Esp32_Main_Controller_Io_Set_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
  444. '2': Blockly.Msg.Esp32_Main_Controller_Io_Set_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
  445. };
  446. return TOOLTIPS[mode];
  447. });
  448. }
  449. };
  450. Blockly.Python['esp32_main_controller_io_set_digital_pin'] = function (block) {
  451. var high_low = Blockly.Python.valueToCode(block, 'high_low', Blockly.Python.ORDER_ATOMIC).slice(1, 2);
  452. // var timer_type = block.getFieldValue('digital_set_type');
  453. let value_name = block.getFieldValue('digital_set_type_gpio');
  454. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  455. Blockly.Python.definitions_['v831_import_time'] = `import time`;
  456. Blockly.Python.definitions_['v831_import_os'] = `import os`
  457. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  458. sys.path.append("/root/")`
  459. var code = ''
  460. if (value_name == 2 || value_name == 1) {
  461. Blockly.Python.definitions_['v831_import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;
  462. Blockly.Python.addVariable('MATHOUT' + value_name, `MATHOUT${value_name} = multiFuncGpio(${value_name - 1},3)`, true);
  463. code = `MATHOUT${value_name}.digitalWrite(${high_low})
  464. `
  465. } else if (value_name == "PG6" || value_name == "PG7" ||value_name == "PC0" || value_name == "PC1" || value_name == "PC2" || value_name == "PC3") {
  466. Blockly.Python.addFunction("pinMode", `def pinMode(pin,mode):
  467. os.system(f"echo {pin} {mode} > /sys/kernel/debug/sunxi_pinctrl/function")
  468. `)
  469. Blockly.Python.addFunction("digitalWrite", `def digitalWrite(pin,level):
  470. if pin == "PC1" or pin == "PC0" or pin == "PC2" or pin == "PC3":
  471. os.system(f"echo {pin} {level} > /sys/kernel/debug/sunxi_pinctrl/function")
  472. os.system(f"echo {pin} {level} > /sys/kernel/debug/sunxi_pinctrl/data")
  473. `)
  474. Blockly.Python.addFunction("digitalRead", `def digitalRead(pin):
  475. if pin == "PC1" or pin == "PC0" or pin == "PC2" or pin == "PC3":
  476. os.system("echo {pin} 2 > /sys/kernel/debug/sunxi_pinctrl/pull")
  477. os.system(f"echo {pin} > /sys/kernel/debug/sunxi_pinctrl/sunxi_pin")
  478. return int(os.popen("cat /sys/kernel/debug/sunxi_pinctrl/data").read()[-2:])
  479. `)
  480. Blockly.Python.addFunction("setToSpi", `def setToSpi():
  481. os.system("echo PC0 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  482. os.system("echo PC1 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  483. os.system("echo PC2 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  484. os.system("echo PC3 4 > /sys/kernel/debug/sunxi_pinctrl/function")
  485. os.system("echo PC0 0 > /sys/kernel/debug/sunxi_pinctrl/pull")
  486. os.system("echo PC1 1 > /sys/kernel/debug/sunxi_pinctrl/pull")
  487. os.system("echo PC2 0 > /sys/kernel/debug/sunxi_pinctrl/pull")
  488. os.system("echo PC3 0 > /sys/kernel/debug/sunxi_pinctrl/pull")
  489. `)
  490. Blockly.Python.addFunction("setToSerial", `def setToSerial():
  491. os.system("echo PG6 5 > /sys/kernel/debug/sunxi_pinctrl/function")
  492. os.system("echo PG7 5 > /sys/kernel/debug/sunxi_pinctrl/function")
  493. `)
  494. Blockly.Python.addVariable(`pinModeOut${value_name}`,`pinMode("${value_name}","1")`,false)
  495. code = `digitalWrite("${value_name}","${high_low}")
  496. `
  497. } else {
  498. let gpioNum = value_name - 10
  499. Blockly.Python.definitions_['v831_import_CocoPi_extGpio'] = `from CocoPi import extGpio`;
  500. Blockly.Python.definitions_['v831_import_CocoPi_extGpio_init'] = `extGpio = extGpio()`;
  501. Blockly.Python.addVariable('ExtGpio' + value_name, `extGpio.pinMode(${gpioNum},1)`, true);
  502. code = `extGpio.digitalWrite(${gpioNum},${high_low})\n`
  503. }
  504. return code;
  505. };
  506. Blockly.Blocks['esp32_main_controller_io_out_pwm'] = {
  507. init: function () {
  508. let types = getLocalStorage("type")
  509. types == 1 ? this.appendDummyInput()
  510. .appendField("")
  511. .appendField(new Blockly.FieldDropdown([
  512. [Blockly.Msg.time_ai_module, "2"],
  513. [Blockly.Msg.time_iot_module, "1"]
  514. ]), "digital_set_type")
  515. .appendField(Blockly.Msg.digital_set) :
  516. this.appendDummyInput()
  517. .appendField("")
  518. .appendField(new Blockly.FieldDropdown([
  519. [Blockly.Msg.time_iot_module, "1"],
  520. [Blockly.Msg.time_ai_module, "2"]
  521. ]), "digital_set_type")
  522. .appendField(Blockly.Msg.digital_set);
  523. this.appendDummyInput()
  524. .appendField("")
  525. .appendField(new Blockly.FieldDropdown([
  526. ['6', '6'],
  527. ['7', '7'],
  528. ['8', '8']
  529. ]), "digital_set_type_gpio").appendField(Blockly.Msg.OUT_PWM);
  530. this.setInputsInline(true);
  531. this.setPreviousStatement(true, null);
  532. this.setNextStatement(true, null);
  533. this.setColour(ESP32_IO_COLOR);
  534. this.setHelpUrl("");
  535. var thisBlock = this;
  536. this.setTooltip(function () {
  537. var mode = thisBlock.getFieldValue('digital_set_type');
  538. var TOOLTIPS = {
  539. '1': Blockly.Msg.Esp32_Main_Controller_Io_Set_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
  540. '2': Blockly.Msg.Esp32_Main_Controller_Io_Set_Digital_Pin_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
  541. };
  542. return TOOLTIPS[mode];
  543. });
  544. }
  545. }
  546. Blockly.Python['esp32_main_controller_io_out_pwm'] = function (block) {
  547. var value_name1 = Blockly.Python.valueToCode(block, 'digital_pin_input', Blockly.Python.ORDER_ATOMIC);
  548. var value_name2 = Blockly.Python.valueToCode(block, 'high_low', Blockly.Python.ORDER_ATOMIC).slice(1, 2);
  549. var timer_type = block.getFieldValue('digital_set_type');
  550. let digital_set_type_gpio = block.getFieldValue('digital_set_type_gpio');
  551. var code = "";
  552. if (timer_type == 1) {
  553. // TODO: Assemble Python into code variable.
  554. Blockly.Python.definitions_['import_main_controller_io_out_pwm'] = '' +
  555. 'from machine import Pin\n' +
  556. '';
  557. let variable = '_PIN_OUT_' + value_name1 + ' = Pin(' + value_name1 + ', Pin.OUT)\n'
  558. Blockly.Python.addVariable('_PIN_OUT_' + value_name1, variable, true);
  559. code = '_PIN_OUT_' + value_name1 + '.value' + value_name2 + '\n';
  560. } else if (timer_type == 2) {
  561. Blockly.Python.definitions_['v831_import_time'] = `import time`
  562. Blockly.Python.definitions_['import_main_controller_io_out_pwm'] = '' +
  563. 'from Maix import pwm\n' +
  564. 'def numberMap(value, leftMin, leftMax, rightMin, rightMax):\n' +
  565. ' leftSpan = leftMax - leftMin\n' +
  566. ' rightSpan = rightMax - rightMin\n' +
  567. ' valueScaled = float(value - leftMin) / float(leftSpan)\n' +
  568. ' return rightMin + (valueScaled * rightSpan)\n' +
  569. '';
  570. // let variable = 'fm.register(' + value_name1 + ',fm.fpioa.GPIOHS' + value_name1 + ')\n' +
  571. // '_set_ai_ext_pin' + value_name1 + ' = GPIO(GPIO.GPIOHS' + value_name1 + ', GPIO.OUT)\n'
  572. // Blockly.Python.addVariable('_set_ai_ext_pin' + value_name1, variable, true);
  573. code = 'pwm6.PWM(' + digital_set_type_gpio + ')\n' + // 配置PWM引脚,可用引脚:6、7、8
  574. 'pwm6.export()\n' +
  575. 'pwm6.period = 20000000 \n' + //表示 pwm 的周期,单位 ns
  576. 'pwm_6_value=0\n' +
  577. 'pwm_6.duty_cycle = numberMap(pwm_6_value,0,1023,0,20000000)\n' + // # 表示占空比,单位 ns,map函数
  578. 'pwm6.duty_cycle = 500000\n' +
  579. 'pwm6.enable = True'; // 表示是否使能 pwm
  580. }
  581. return code;
  582. }
  583. Blockly.Blocks['esp32_main_controller_io_from_analog_pin'] = {
  584. init: function () {
  585. this.appendDummyInput()
  586. .appendField(Blockly.Msg.analog_get)
  587. .appendField(new Blockly.FieldDropdown([
  588. ["S1", "1"],
  589. ["S2", "2"]
  590. // ["3", "3"],
  591. // ["4", "4"],
  592. // ["5", "5"],
  593. // ["6", "6"],
  594. // ["7", "7"],
  595. // ["8", "8"],
  596. // ["9", "9"],
  597. // ["10", "10"],
  598. // ["11", "11"],
  599. // ["12", "12"]
  600. ]), "gpio");
  601. this.appendDummyInput()
  602. .appendField(Blockly.Msg.analog_get_value);
  603. this.setInputsInline(true);
  604. this.setOutput(true, null);
  605. this.setColour(ESP32_IO_COLOR);
  606. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Io_From_Analog_Pin_TOOLTIP);
  607. this.setHelpUrl("");
  608. }
  609. };
  610. Blockly.Python['esp32_main_controller_io_from_analog_pin'] = function (block) {
  611. // var value_name = Blockly.Python.valueToCode(block, 'analog_pin_input', Blockly.Python.ORDER_ATOMIC);
  612. var value_gpio = block.getFieldValue('gpio');
  613. // TODO: Assemble Python into code variable.
  614. //Blockly.Python.addVariable('_PWM_PIN_IN_' + value_name, '_PWM_PIN_IN_' + value_name + '=None', true);
  615. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  616. Blockly.Python.definitions_['v831_import_time'] = `import time`
  617. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  618. sys.path.append("/root/")`
  619. Blockly.Python.definitions_['v831_import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;
  620. if (value_gpio == 1 || value_gpio == 2) {
  621. Blockly.Python.addVariable('_PWN_gpio_' + value_gpio, `_PWN_gpio_${value_gpio} = multiFuncGpio(${value_gpio - 1},4)`, true);
  622. } else {
  623. Blockly.Python.addVariable('_PWN_gpio_' + value_gpio, `_PWN_gpio_${value_gpio} = multiFuncGpio(${value_gpio - 1},4)`, true);
  624. }
  625. var code = `_PWN_gpio_${value_gpio}.analogRead()`;
  626. // TODO: Change ORDER_NONE to the correct strength.
  627. return [code, Blockly.Python.ORDER_CONDITIONAL];
  628. };
  629. Blockly.Blocks['esp32_main_controller_io_set_analog_pin'] = {
  630. init: function () {
  631. this.appendDummyInput()
  632. .appendField(Blockly.Msg.digital_set)
  633. .appendField(new Blockly.FieldDropdown([
  634. ["S1", "1"],
  635. ["S2", "2"]
  636. // ["3", "3"],
  637. // ["4", "4"],
  638. // ["5", "5"],
  639. // ["6", "6"],
  640. // ["7", "7"],
  641. // ["8", "8"],
  642. // ["9", "9"],
  643. // ["10", "10"],
  644. // ["11", "11"],
  645. // ["12", "12"]
  646. ]), "gpio");
  647. this.appendValueInput("pwm")
  648. .appendField(Blockly.Msg.set_pwm)
  649. .setCheck(null);
  650. this.appendDummyInput().appendField(Blockly.Msg.esp32_expand_io_set_analog_pin_digital_set_af)
  651. this.setInputsInline(true);
  652. this.setPreviousStatement(true, null);
  653. this.setNextStatement(true, null);
  654. this.setColour(ESP32_IO_COLOR);
  655. this.setHelpUrl("");
  656. var thisBlock = this;
  657. this.setTooltip(function () {
  658. var mode = thisBlock.getFieldValue('LED');
  659. var TOOLTIPS = {
  660. 'LED': Blockly.Msg.Esp32_Main_Controller_Io_Set_Analog_Pin_TOOLTIP.replace('%1', Blockly.Msg.led)
  661. };
  662. return TOOLTIPS[mode];
  663. });
  664. }
  665. };
  666. Blockly.Python['esp32_main_controller_io_set_analog_pin'] = function (block) {
  667. var value_name1 = block.getFieldValue('gpio');
  668. var value_name2 = Blockly.Python.valueToCode(block, 'pwm', Blockly.Python.ORDER_ATOMIC);
  669. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  670. Blockly.Python.definitions_['v831_import_time'] = `import time`
  671. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  672. sys.path.append("/root/")`
  673. Blockly.Python.definitions_['v831_import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;
  674. Blockly.Python.addVariable('PWNOUT_' + value_name1, `PWNOUT_${value_name1} = multiFuncGpio(${value_name1 - 1},5)`, true);
  675. var code = `PWNOUT_${value_name1}.analogWrite(${value_name2})`;
  676. return code;
  677. };
  678. Blockly.Blocks['ai_main_controller_io_set_analog_pin'] = {
  679. init: function () {
  680. var _en = true;
  681. for (var i = 0; i < ids.length; i++) {
  682. if (!ids[i]) {
  683. _en = false;
  684. }
  685. }
  686. this.disabled = ids.length > 11 && _en ? true : false;
  687. this.appendValueInput("analog_pin_input")
  688. .appendField(Blockly.Msg.analog_set_ai)
  689. .setCheck(null);
  690. // this.appendValueInput("frequency")
  691. // .appendField(Blockly.Msg.analog_set_freq)
  692. // .setCheck(null);
  693. this.appendDummyInput()
  694. .appendField(Blockly.Msg.control)
  695. .appendField(new Blockly.FieldDropdown([
  696. [Blockly.Msg.led, "LED"]
  697. ]), "LED");
  698. this.appendValueInput("pwm")
  699. .appendField(Blockly.Msg.set_pwm)
  700. .setCheck(null);
  701. // this.appendValueInput("timer")
  702. // .appendField(Blockly.Msg.analog_set_timer)
  703. // .setCheck(null);
  704. // this.appendValueInput("channel")
  705. // .appendField(Blockly.Msg.analog_set_timer_channel)
  706. // .setCheck(null);
  707. this.setInputsInline(true);
  708. this.setPreviousStatement(true, null);
  709. this.setNextStatement(true, null);
  710. this.setColour(ESP32_IO_COLOR);
  711. this.setHelpUrl("");
  712. var thisBlock = this;
  713. this.setTooltip(function () {
  714. var mode = thisBlock.getFieldValue('LED');
  715. var TOOLTIPS = {
  716. 'LED': Blockly.Msg.Ai_Main_Controller_Io_Set_Analog_Pin_TOOLTIP.replace('%1', Blockly.Msg.led)
  717. };
  718. return TOOLTIPS[mode];
  719. });
  720. }
  721. };
  722. var ids = [];
  723. Blockly.Python['ai_main_controller_io_set_analog_pin'] = function (block) {
  724. var value_name1 = Blockly.Python.valueToCode(block, 'analog_pin_input', Blockly.Python.ORDER_ATOMIC);
  725. var value_name2 = Blockly.Python.valueToCode(block, 'pwm', Blockly.Python.ORDER_ATOMIC);
  726. var str = '';
  727. var j = 0;
  728. var returnvalue = '';
  729. for (var i = 0; i < ids.length; i++) {
  730. if (ids[i] && !Blockly.getMainWorkspace().getBlockById(ids[i].id)) {
  731. ids[i] = null;
  732. }
  733. }
  734. for (var i = 0; i < ids.length; i++) {
  735. if (ids[i] && ids[i].id == block.id) {
  736. j = i;
  737. break;
  738. } else {
  739. if (j == 0) {
  740. if (!ids[i]) {
  741. j = i;
  742. } else if (i == ids.length - 1) {
  743. j = ids.length;
  744. }
  745. }
  746. }
  747. }
  748. if (!ids[j]) {
  749. ids[j] = { id: block.id, index: j };
  750. }
  751. for (var i = 0; i < ids.length; i++) {
  752. if (ids[i]) {
  753. Blockly.Python.addVariable('_pwm_gpio_tim_' + ids[i].index, '', true);
  754. Blockly.Python.addVariable('_pwm_gpio_control_' + ids[i].index, '', true);
  755. str += '_pwm_gpio_tim_' + ids[i].index + ' = Timer(_io_timer_use[' + ids[i].index + '][0],_io_timer_use[' + ids[i].index + '][1], mode=Timer.MODE_PWM)\n';
  756. str += '_pwm_gpio_control_' + ids[i].index + ' = PWM(_pwm_gpio_tim_' + ids[i].index + ', freq=500000, duty=0, pin=' + value_name1 + ')\n';
  757. }
  758. }
  759. returnvalue += '_pwm_gpio_control_' + ids[j].index + '.duty(int(' + value_name2 + '/10.23))\n';
  760. // TODO: Assemble Python into code variable.
  761. Blockly.Python.definitions_['import_analog_ai_set_setup'] = '' +
  762. 'from machine import Pin,PWM,Timer\n' +
  763. '\n' +
  764. '_io_timer_use = [[Timer.TIMER0, Timer.CHANNEL0],[Timer.TIMER0, Timer.CHANNEL1],[Timer.TIMER0, Timer.CHANNEL2],[Timer.TIMER1, Timer.CHANNEL0],[Timer.TIMER1, Timer.CHANNEL1],[Timer.TIMER1, Timer.CHANNEL2],[Timer.TIMER2, Timer.CHANNEL0],[Timer.TIMER2, Timer.CHANNEL1],[Timer.TIMER2, Timer.CHANNEL2]]\n' + str;
  765. return returnvalue;
  766. // var module_type = block.getFieldValue('digital_set_type');
  767. // var str = '';
  768. // var ss = '';
  769. // if (counts.length != 0) {
  770. // if (ids.indexOf(block.id) == -1) {
  771. // ids.push(block.id);
  772. // count = count + 1;
  773. // counts.push(count);
  774. // Blockly.Python.addVariable('_pwm_gpio_tim_' + count, '', true);
  775. // Blockly.Python.addVariable('_pwm_gpio_control_' + count, '', true);
  776. // str += '_pwm_gpio_tim_' + count + ' = Timer(_io_timer_use[' + count + '][0],_io_timer_use[' + count + '][1], mode=Timer.MODE_PWM)\n';
  777. // str += '_pwm_gpio_control_' + count + ' = PWM(_pwm_gpio_tim_' + count + ', freq=500000, duty=0, pin=' + value_name1 + ')\n';
  778. // ss += '_pwm_gpio_control_' + count + '.duty(int(' + value_name2 + '/10.23))\n';
  779. // }
  780. // else {
  781. // for (var i = 0; i < counts.length; i++) {
  782. // Blockly.Python.addVariable('_pwm_gpio_tim_' + counts[i], '', true);
  783. // Blockly.Python.addVariable('_pwm_gpio_control_' + counts[i], '', true);
  784. // str += '_pwm_gpio_tim_' + counts[i] + ' = Timer(_io_timer_use[' + counts[i] + '][0],_io_timer_use[' + counts[i] + '][1], mode=Timer.MODE_PWM)\n';
  785. // str += '_pwm_gpio_control_' + counts[i] + ' = PWM(_pwm_gpio_tim_' + counts[i] + ', freq=500000, duty=0, pin=' + value_name1 + ')\n';
  786. // ss += '_pwm_gpio_control_' + counts[i] + '.duty(int(' + value_name2 + '/10.23))\n';
  787. // }
  788. // }
  789. // }
  790. // else {
  791. // if (ids.indexOf(block.id) == -1) {
  792. // ids.push(block.id);
  793. // counts.push(count);
  794. // Blockly.Python.addVariable('_pwm_gpio_tim_' + count, '', true);
  795. // Blockly.Python.addVariable('_pwm_gpio_control_' + count, '', true);
  796. // str += '_pwm_gpio_tim_' + count + ' = Timer(_io_timer_use[' + count + '][0],_io_timer_use[' + count + '][1], mode=Timer.MODE_PWM)\n';
  797. // str += '_pwm_gpio_control_' + count + ' = PWM(_pwm_gpio_tim_' + count + ', freq=500000, duty=0, pin=' + value_name1 + ')\n';
  798. // ss += '_pwm_gpio_control_' + count + '.duty(int(' + value_name2 + '/10.23))\n';
  799. // }
  800. // }
  801. // // TODO: Assemble Python into code variable.
  802. // Blockly.Python.definitions_['import_analog_ai_set_setup'] = '' +
  803. // 'from machine import Pin,PWM,Timer\n' +
  804. // '\n' +
  805. // '_io_timer_use = [[Timer.TIMER0, Timer.CHANNEL0],[Timer.TIMER0, Timer.CHANNEL1],[Timer.TIMER0, Timer.CHANNEL2],[Timer.TIMER1, Timer.CHANNEL0],[Timer.TIMER1, Timer.CHANNEL1],[Timer.TIMER1, Timer.CHANNEL2],[Timer.TIMER2, Timer.CHANNEL0],[Timer.TIMER2, Timer.CHANNEL1],[Timer.TIMER2, Timer.CHANNEL2]]\n' + str;
  806. // // code = ss;
  807. // return ss;
  808. };
  809. /*
  810. Button
  811. */
  812. Blockly.Blocks['esp32_main_controller_button_read_pressed'] = {
  813. init: function () {
  814. // this.appendDummyInput()
  815. // .appendField(new Blockly.FieldImage("blockly/media/button_pressed.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  816. this.appendDummyInput()
  817. .appendField(Blockly.Msg.ESP32BUTTON)
  818. .appendField(new Blockly.FieldDropdown([
  819. ["P1", "button_type_1"],
  820. ["P2", "button_type_2"]
  821. ]), "button_type")
  822. .appendField(Blockly.Msg.ESP32PRESSED)
  823. this.setOutput(true, null);
  824. this.setColour("#d42b03");
  825. this.setHelpUrl("");
  826. var thisBlock = this;
  827. this.setTooltip(function () {
  828. var mode = thisBlock.getFieldValue('button_type');
  829. var TOOLTIPS = {
  830. 'button_type_1': Blockly.Msg.Esp32_Main_Controller_Button_Read_Pressed_TOOLTIP.replace('%1', "P1"),
  831. 'button_type_2': Blockly.Msg.Esp32_Main_Controller_Button_Read_Pressed_TOOLTIP.replace('%1', "P2")
  832. };
  833. return TOOLTIPS[mode];
  834. });
  835. }
  836. };
  837. Blockly.Python['esp32_main_controller_button_read_pressed'] = function (block) {
  838. Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  839. var _type = block.getField('button_type').text_;
  840. var _button_state = block.getFieldValue('button_state');
  841. var _num = _type == "P1" ? "34" : "35";
  842. var _upstr = "";
  843. if (_type == "P2") { _upstr = ",Pin.PULL_UP"; }
  844. Blockly.Python.addVariable('_' + _type, '_' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  845. var code = '(_' + _type + '.value() == ' + 1 + ')';
  846. return [code, Blockly.Python.ORDER_CONDITIONAL];
  847. };
  848. Blockly.Blocks['esp32_main_controller_button_read_released'] = {
  849. init: function () {
  850. // this.appendDummyInput()
  851. // .appendField(new Blockly.FieldImage("blockly/media/button_released.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  852. this.appendDummyInput()
  853. .appendField(Blockly.Msg.ESP32BUTTON)
  854. .appendField(new Blockly.FieldDropdown([
  855. ["P1", "button_type_1"],
  856. ["P2", "button_type_2"]
  857. ]), "button_type")
  858. .appendField(Blockly.Msg.ESP32RELEASED)
  859. this.setOutput(true, null);
  860. this.setColour("#d42b03");
  861. var thisBlock = this;
  862. this.setTooltip(function () {
  863. var mode = thisBlock.getFieldValue('button_type');
  864. var TOOLTIPS = {
  865. 'button_type_1': Blockly.Msg.Esp32_Main_Controller_Button_Read_Released_TOOLTIP.replace('%1', "P1"),
  866. 'button_type_2': Blockly.Msg.Esp32_Main_Controller_Button_Read_Released_TOOLTIP.replace('%1', "P2")
  867. };
  868. return TOOLTIPS[mode];
  869. });
  870. this.setHelpUrl("");
  871. }
  872. };
  873. Blockly.Python['esp32_main_controller_button_read_released'] = function (block) {
  874. Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  875. var _type = block.getField('button_type').text_;
  876. var _button_state = block.getFieldValue('button_state');
  877. var _num = _type == "P1" ? "34" : "35";
  878. var _upstr = "";
  879. if (_type == "P2") { _upstr = ",Pin.PULL_UP"; }
  880. Blockly.Python.addVariable('_' + _type, '_' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  881. var code = '(_' + _type + '.value() == ' + 0 + ')';
  882. return [code, Blockly.Python.ORDER_CONDITIONAL];
  883. };
  884. Blockly.Blocks['esp32_main_controller_button_read_value'] = {
  885. init: function () {
  886. this.appendDummyInput()
  887. .appendField(Blockly.Msg.basic_button_read_value)
  888. .appendField(new Blockly.FieldDropdown([
  889. ["P1", "button_type_1"],
  890. ["P2", "button_type_2"]
  891. ]), "button_type")
  892. .appendField(Blockly.Msg.basic_button_read_value_after);
  893. this.setInputsInline(true);
  894. this.setOutput(true, null);
  895. this.setColour("#d42b03");
  896. this.setHelpUrl("");
  897. var thisBlock = this;
  898. this.setTooltip(function () {
  899. var mode = thisBlock.getFieldValue('button_type');
  900. var TOOLTIPS = {
  901. 'button_type_1': Blockly.Msg.Esp32_Main_Controller_Button_Read_Value_TOOLTIP.replace('%1', "P1"),
  902. 'button_type_2': Blockly.Msg.Esp32_Main_Controller_Button_Read_Value_TOOLTIP.replace('%1', "P2")
  903. };
  904. return TOOLTIPS[mode];
  905. });
  906. this.setHelpUrl("");
  907. }
  908. };
  909. Blockly.Python['esp32_main_controller_button_read_value'] = function (block) {
  910. Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  911. var _type = block.getField('button_type').text_;
  912. // TODO: Assemble Python into code variable.
  913. var _num = _type == "P1" ? "34" : "35";
  914. var _upstr = "";
  915. if (_type == "P2") { _upstr = ",Pin.PULL_UP"; }
  916. Blockly.Python.addVariable('_' + _type, '_' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  917. var code = '_' + _type + '.value()';
  918. // TODO: Change ORDER_NONE to the correct strength.
  919. return [code, Blockly.Python.ORDER_NONE];
  920. };
  921. /*
  922. Blockly.Python['esp32_main_controller_button_read'] = function (block) {
  923. Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  924. var _type = block.getField('button_type').text_;
  925. var _button_state = block.getFieldValue('button_state');
  926. var _num = _type == "1" ? "36" : "22";
  927. var _upstr = "";
  928. if (_type == "2") { _upstr = ",Pin.PULL_UP"; }
  929. Blockly.Python.addVariable('p' + _type, 'p' + _type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')', true);
  930. var code = '(p' + _type + '.value() == ' + (_button_state == "button_state_pressed" ? "1" : "0") + ')';
  931. return [code, Blockly.Python.ORDER_CONDITIONAL];
  932. };
  933. */
  934. /*
  935. Dialer
  936. */
  937. Blockly.Blocks['esp32_main_controller_dial_switch_read_pressed'] = {
  938. init: function () {
  939. this.appendDummyInput()
  940. .appendField(Blockly.Msg.ESP32DIALSWITCH)
  941. .appendField(new Blockly.FieldDropdown([
  942. [Blockly.Msg.ESP32DIALER_LEFT, "switch_type_left"],
  943. [Blockly.Msg.ESP32DIALER_MIDDLE, "switch_type_middle"],
  944. [Blockly.Msg.ESP32DIALER_RIGHT, "switch_type_right"]
  945. ]), "switch_type")
  946. .appendField(Blockly.Msg.ESP32PRESSED)
  947. this.setOutput(true, null);
  948. this.setColour("#e8795b");
  949. this.setTooltip("");
  950. this.setHelpUrl("");
  951. }
  952. };
  953. Blockly.Python['esp32_main_controller_dial_switch_read_pressed'] = function (block) {
  954. Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  955. var _type = block.getFieldValue('switch_type');
  956. var _num = "34";
  957. var _upstr = "";
  958. var _button_type = "";
  959. if (_type == "switch_type_left") {
  960. var _num = "34";
  961. _button_type = "Left";
  962. } else if (_type == "switch_type_middle") {
  963. var _num = "19";
  964. _upstr = ", Pin.PULL_UP";
  965. _button_type = "Middle";
  966. } else if (_type == "switch_type_right") {
  967. var _num = "35";
  968. _button_type = "Right";
  969. }
  970. // Blockly.Python.addVariable("dialer_type", 'p' + _button_type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')');
  971. Blockly.Python.addVariable("pLeft", 'pLeft = Pin(38, Pin.IN)');
  972. Blockly.Python.addVariable("pMiddle", 'pMiddle = Pin(19, Pin.IN)');
  973. Blockly.Python.addVariable("pRight", 'pRight = Pin(35, Pin.IN)');
  974. var code = '(p' + _button_type + '.value() == 1)';
  975. return [code, Blockly.Python.ORDER_CONDITIONAL];
  976. };
  977. Blockly.Blocks['esp32_main_controller_dial_switch_read_released'] = {
  978. init: function () {
  979. this.appendDummyInput()
  980. .appendField(Blockly.Msg.ESP32DIALSWITCH)
  981. .appendField(new Blockly.FieldDropdown([
  982. [Blockly.Msg.ESP32DIALER_LEFT, "switch_type_left"],
  983. [Blockly.Msg.ESP32DIALER_MIDDLE, "switch_type_middle"],
  984. [Blockly.Msg.ESP32DIALER_RIGHT, "switch_type_right"]
  985. ]), "switch_type")
  986. .appendField(Blockly.Msg.ESP32RELEASED)
  987. this.setOutput(true, null);
  988. this.setColour("#e8795b");
  989. this.setTooltip("");
  990. this.setHelpUrl("");
  991. }
  992. };
  993. Blockly.Python['esp32_main_controller_dial_switch_read_released'] = function (block) {
  994. Blockly.Python.definitions_['import_Pin'] = 'from machine import Pin';
  995. var _type = block.getFieldValue('switch_type');
  996. var _state = block.getFieldValue('switch_state');
  997. var _num = "34";
  998. var _upstr = "";
  999. var _button_type = "";
  1000. if (_type == "switch_type_left") {
  1001. var _num = "34";
  1002. _button_type = "Left";
  1003. } else if (_type == "switch_type_middle") {
  1004. var _num = "19";
  1005. _upstr = ", Pin.PULL_UP";
  1006. _button_type = "Middle";
  1007. } else if (_type == "switch_type_right") {
  1008. var _num = "35";
  1009. _button_type = "Right";
  1010. }
  1011. Blockly.Python.addVariable('p' + _button_type, 'p' + _button_type + ' = Pin(' + _num + ', Pin.IN' + _upstr + ')');
  1012. var code = '(p' + _button_type + '.value() == 0)';
  1013. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1014. };
  1015. /*
  1016. LED
  1017. */
  1018. Blockly.Blocks['esp32_main_controller_set_led_turnon'] = {
  1019. init: function () {
  1020. // this.appendDummyInput()
  1021. // .appendField(new Blockly.FieldImage("blockly/media/led_on.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1022. this.appendDummyInput()
  1023. .appendField(Blockly.Msg.ESP32TURN + Blockly.Msg.ESP32LED_MONO_TEXT_NO);
  1024. this.appendValueInput("led_type")
  1025. .setCheck(null);
  1026. this.appendDummyInput()
  1027. .appendField(Blockly.Msg.ESP32LED_MONO_TEXT_AFTER + Blockly.Msg.ESP32LED + Blockly.Msg.ESP32LED_TURNON);
  1028. this.setPreviousStatement(true, null);
  1029. this.setNextStatement(true, null);
  1030. this.setColour("#d42b03");
  1031. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Turnon_TOOLTIP);
  1032. this.setHelpUrl("");
  1033. }
  1034. };
  1035. Blockly.Python['esp32_main_controller_set_led_turnon'] = function (block) {
  1036. Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';
  1037. var _type = Blockly.Python.valueToCode(block, 'led_type', Blockly.Python.ORDER_ATOMIC);
  1038. var _state = block.getFieldValue('led_state');
  1039. var _num = "2";
  1040. if (_type == "1") {
  1041. var _num = "2";
  1042. } else if (_type == "2") {
  1043. var _num = "12";
  1044. } else if (_type == "3") {
  1045. var _num = "5";
  1046. } else if (_type == "4") {
  1047. var _num = "13";
  1048. } else if (_type == "5") {
  1049. var _num = "14";
  1050. } else if (_type == "6") {
  1051. var _num = "15";
  1052. } else if (_type == "7") {
  1053. var _num = "18";
  1054. } else if (_type == "8") {
  1055. var _num = "19";
  1056. } else if (_type == "9") {
  1057. var _num = "23";
  1058. } else {
  1059. var _num = "ERROR";
  1060. }
  1061. Blockly.Python.addSetup('iot_led_light_setup', '' +
  1062. '_light = [0,2,12,5,13,14,15,18,19,23]\n' +
  1063. '\n' +
  1064. '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' +
  1065. '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' +
  1066. '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' +
  1067. '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' +
  1068. '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' +
  1069. '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' +
  1070. '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' +
  1071. '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' +
  1072. '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' +
  1073. '\n' +
  1074. 'def _led_light(state, pin):\n' +
  1075. ' if (state == True):\n' +
  1076. ' if pin == 1: _light_1.value(1)\n' +
  1077. ' if pin == 2: _light_2.value(1)\n' +
  1078. ' if pin == 3: _light_3.value(1)\n' +
  1079. ' if pin == 4: _light_4.value(1)\n' +
  1080. ' if pin == 5: _light_5.value(1)\n' +
  1081. ' if pin == 6: _light_6.value(1)\n' +
  1082. ' if pin == 7: _light_7.value(1)\n' +
  1083. ' if pin == 8: _light_8.value(1)\n' +
  1084. ' if pin == 9: _light_9.value(1)\n' +
  1085. ' elif (state == False):\n' +
  1086. ' if pin == 1: _light_1.value(0)\n' +
  1087. ' if pin == 2: _light_2.value(0)\n' +
  1088. ' if pin == 3: _light_3.value(0)\n' +
  1089. ' if pin == 4: _light_4.value(0)\n' +
  1090. ' if pin == 5: _light_5.value(0)\n' +
  1091. ' if pin == 6: _light_6.value(0)\n' +
  1092. ' if pin == 7: _light_7.value(0)\n' +
  1093. ' if pin == 8: _light_8.value(0)\n' +
  1094. ' if pin == 9: _light_9.value(0)\n' +
  1095. '');
  1096. var code = '_led_light(True,' + _type + ')\n';
  1097. return code;
  1098. };
  1099. Blockly.Blocks['esp32_main_controller_set_led_turnoff'] = {
  1100. init: function () {
  1101. // this.appendDummyInput()
  1102. // .appendField(new Blockly.FieldImage("blockly/media/led_off.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1103. this.appendDummyInput()
  1104. .appendField(Blockly.Msg.ESP32TURN + Blockly.Msg.ESP32LED_MONO_TEXT_NO);
  1105. this.appendValueInput("led_type")
  1106. .setCheck(null);
  1107. this.appendDummyInput()
  1108. .appendField(Blockly.Msg.ESP32LED_MONO_TEXT_AFTER + Blockly.Msg.ESP32LED + Blockly.Msg.ESP32LED_TURNOFF);
  1109. this.setPreviousStatement(true, null);
  1110. this.setNextStatement(true, null);
  1111. this.setColour("#d42b03");
  1112. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Turnoff_TOOLTIP);
  1113. this.setHelpUrl("");
  1114. }
  1115. };
  1116. Blockly.Python['esp32_main_controller_set_led_turnoff'] = function (block) {
  1117. Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';
  1118. var _type = Blockly.Python.valueToCode(block, 'led_type', Blockly.Python.ORDER_ATOMIC);
  1119. var _state = block.getFieldValue('led_state');
  1120. var _num = "2";
  1121. if (_type == "1") {
  1122. var _num = "2";
  1123. } else if (_type == "2") {
  1124. var _num = "12";
  1125. } else if (_type == "3") {
  1126. var _num = "5";
  1127. } else if (_type == "4") {
  1128. var _num = "13";
  1129. } else if (_type == "5") {
  1130. var _num = "14";
  1131. } else if (_type == "6") {
  1132. var _num = "15";
  1133. } else if (_type == "7") {
  1134. var _num = "18";
  1135. } else if (_type == "8") {
  1136. var _num = "19";
  1137. } else if (_type == "9") {
  1138. var _num = "23";
  1139. } else {
  1140. var _num = "ERROR";
  1141. }
  1142. Blockly.Python.addSetup('iot_led_light_setup', '' +
  1143. '_light = [0,2,12,5,13,14,15,18,19,23]\n' +
  1144. '\n' +
  1145. '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' +
  1146. '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' +
  1147. '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' +
  1148. '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' +
  1149. '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' +
  1150. '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' +
  1151. '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' +
  1152. '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' +
  1153. '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' +
  1154. '\n' +
  1155. 'def _led_light(state, pin):\n' +
  1156. ' if (state == True):\n' +
  1157. ' if pin == 1: _light_1.value(1)\n' +
  1158. ' if pin == 2: _light_2.value(1)\n' +
  1159. ' if pin == 3: _light_3.value(1)\n' +
  1160. ' if pin == 4: _light_4.value(1)\n' +
  1161. ' if pin == 5: _light_5.value(1)\n' +
  1162. ' if pin == 6: _light_6.value(1)\n' +
  1163. ' if pin == 7: _light_7.value(1)\n' +
  1164. ' if pin == 8: _light_8.value(1)\n' +
  1165. ' if pin == 9: _light_9.value(1)\n' +
  1166. ' elif (state == False):\n' +
  1167. ' if pin == 1: _light_1.value(0)\n' +
  1168. ' if pin == 2: _light_2.value(0)\n' +
  1169. ' if pin == 3: _light_3.value(0)\n' +
  1170. ' if pin == 4: _light_4.value(0)\n' +
  1171. ' if pin == 5: _light_5.value(0)\n' +
  1172. ' if pin == 6: _light_6.value(0)\n' +
  1173. ' if pin == 7: _light_7.value(0)\n' +
  1174. ' if pin == 8: _light_8.value(0)\n' +
  1175. ' if pin == 9: _light_9.value(0)\n' +
  1176. '');
  1177. var code = '_led_light(False,' + _type + ')\n';
  1178. return code;
  1179. };
  1180. Blockly.Blocks['esp32_main_controller_set_led_drawpixel_on'] = {
  1181. init: function () {
  1182. this.appendDummyInput()
  1183. .appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHTUP + Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_INIT_TEXT);
  1184. this.appendValueInput("x")
  1185. .setCheck(null)
  1186. this.appendValueInput("y")
  1187. .setCheck(null)
  1188. .appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_MIDDLE_TEXT);
  1189. this.appendDummyInput()
  1190. .appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_END_TEXT);
  1191. this.setInputsInline(true);
  1192. this.setPreviousStatement(true, null);
  1193. this.setNextStatement(true, null);
  1194. this.setColour("#d42b03");
  1195. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Drawpixel_On_TOOLTIP);
  1196. this.setHelpUrl("");
  1197. }
  1198. };
  1199. Blockly.Python['esp32_main_controller_set_led_drawpixel_on'] = function (block) {
  1200. var value_x = Blockly.Python.valueToCode(block, 'x', Blockly.Python.ORDER_ATOMIC);
  1201. var value_y = Blockly.Python.valueToCode(block, 'y', Blockly.Python.ORDER_ATOMIC);
  1202. // TODO: Assemble Python into code variable.
  1203. Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';
  1204. Blockly.Python.addSetup('iot_led_light_setup', '' +
  1205. '_light = [0,2,12,5,13,14,15,18,19,23]\n' +
  1206. '\n' +
  1207. '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' +
  1208. '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' +
  1209. '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' +
  1210. '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' +
  1211. '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' +
  1212. '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' +
  1213. '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' +
  1214. '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' +
  1215. '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' +
  1216. '\n' +
  1217. 'def _led_light(state, pin):\n' +
  1218. ' if (state == True):\n' +
  1219. ' if pin == 1: _light_1.value(1)\n' +
  1220. ' if pin == 2: _light_2.value(1)\n' +
  1221. ' if pin == 3: _light_3.value(1)\n' +
  1222. ' if pin == 4: _light_4.value(1)\n' +
  1223. ' if pin == 5: _light_5.value(1)\n' +
  1224. ' if pin == 6: _light_6.value(1)\n' +
  1225. ' if pin == 7: _light_7.value(1)\n' +
  1226. ' if pin == 8: _light_8.value(1)\n' +
  1227. ' if pin == 9: _light_9.value(1)\n' +
  1228. ' elif (state == False):\n' +
  1229. ' if pin == 1: _light_1.value(0)\n' +
  1230. ' if pin == 2: _light_2.value(0)\n' +
  1231. ' if pin == 3: _light_3.value(0)\n' +
  1232. ' if pin == 4: _light_4.value(0)\n' +
  1233. ' if pin == 5: _light_5.value(0)\n' +
  1234. ' if pin == 6: _light_6.value(0)\n' +
  1235. ' if pin == 7: _light_7.value(0)\n' +
  1236. ' if pin == 8: _light_8.value(0)\n' +
  1237. ' if pin == 9: _light_9.value(0)\n' +
  1238. '');
  1239. Blockly.Python.addSetup('drawpixel_setup', '' +
  1240. 'def _led_draw_pixel(state, x, y):\n' +
  1241. ' real_pin = (3*y-3+x)\n' +
  1242. ' _led_light(state,real_pin)\n' +
  1243. '\n')
  1244. var code = '_led_draw_pixel(True,' + value_x + ',' + value_y + ')\n';
  1245. return code;
  1246. };
  1247. Blockly.Blocks['esp32_main_controller_set_led_drawpixel_off'] = {
  1248. init: function () {
  1249. this.appendDummyInput()
  1250. .appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHTOFF + Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_INIT_TEXT);
  1251. this.appendValueInput("x")
  1252. .setCheck(null)
  1253. this.appendValueInput("y")
  1254. .setCheck(null)
  1255. .appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_MIDDLE_TEXT);
  1256. this.appendDummyInput()
  1257. .appendField(Blockly.Msg.ESP32LED_CORD_DRAWPIXEL_LIGHT_END_TEXT);
  1258. this.setInputsInline(true);
  1259. this.setPreviousStatement(true, null);
  1260. this.setNextStatement(true, null);
  1261. this.setColour("#d42b03");
  1262. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Led_Drawpixel_Off_TOOLTIP);
  1263. this.setHelpUrl("");
  1264. }
  1265. };
  1266. Blockly.Python['esp32_main_controller_set_led_drawpixel_off'] = function (block) {
  1267. var value_x = Blockly.Python.valueToCode(block, 'x', Blockly.Python.ORDER_ATOMIC);
  1268. var value_y = Blockly.Python.valueToCode(block, 'y', Blockly.Python.ORDER_ATOMIC);
  1269. // TODO: Assemble Python into code variable.
  1270. Blockly.Python.definitions_['import_led_Pin'] = 'from machine import Pin';
  1271. Blockly.Python.addSetup('iot_led_light_setup', '' +
  1272. '_light = [0,2,12,5,13,14,15,18,19,23]\n' +
  1273. '\n' +
  1274. '_light_1 = Pin(_light[1], Pin.OUT, value=0)\n' +
  1275. '_light_2 = Pin(_light[2], Pin.OUT, value=0)\n' +
  1276. '_light_3 = Pin(_light[3], Pin.OUT, value=0)\n' +
  1277. '_light_4 = Pin(_light[4], Pin.OUT, value=0)\n' +
  1278. '_light_5 = Pin(_light[5], Pin.OUT, value=0)\n' +
  1279. '_light_6 = Pin(_light[6], Pin.OUT, value=0)\n' +
  1280. '_light_7 = Pin(_light[7], Pin.OUT, value=0)\n' +
  1281. '_light_8 = Pin(_light[8], Pin.OUT, value=0)\n' +
  1282. '_light_9 = Pin(_light[9], Pin.OUT, value=0)\n' +
  1283. '\n' +
  1284. 'def _led_light(state, pin):\n' +
  1285. ' if (state == True):\n' +
  1286. ' if pin == 1: _light_1.value(1)\n' +
  1287. ' if pin == 2: _light_2.value(1)\n' +
  1288. ' if pin == 3: _light_3.value(1)\n' +
  1289. ' if pin == 4: _light_4.value(1)\n' +
  1290. ' if pin == 5: _light_5.value(1)\n' +
  1291. ' if pin == 6: _light_6.value(1)\n' +
  1292. ' if pin == 7: _light_7.value(1)\n' +
  1293. ' if pin == 8: _light_8.value(1)\n' +
  1294. ' if pin == 9: _light_9.value(1)\n' +
  1295. ' elif (state == False):\n' +
  1296. ' if pin == 1: _light_1.value(0)\n' +
  1297. ' if pin == 2: _light_2.value(0)\n' +
  1298. ' if pin == 3: _light_3.value(0)\n' +
  1299. ' if pin == 4: _light_4.value(0)\n' +
  1300. ' if pin == 5: _light_5.value(0)\n' +
  1301. ' if pin == 6: _light_6.value(0)\n' +
  1302. ' if pin == 7: _light_7.value(0)\n' +
  1303. ' if pin == 8: _light_8.value(0)\n' +
  1304. ' if pin == 9: _light_9.value(0)\n' +
  1305. '');
  1306. Blockly.Python.addSetup('drawpixel_setup', '' +
  1307. 'def _led_draw_pixel(state, x, y):\n' +
  1308. ' real_pin = (3*y-3+x)\n' +
  1309. ' _led_light(state,real_pin)\n' +
  1310. '\n')
  1311. var code = '_led_draw_pixel(False,' + value_x + ',' + value_y + ')\n';
  1312. return code;
  1313. };
  1314. /*
  1315. BUZZER
  1316. */
  1317. Blockly.Blocks['esp32_main_controller_set_buzzer_init'] = {
  1318. init: function () {
  1319. // this.appendDummyInput()
  1320. // .appendField(new Blockly.FieldImage("blockly/media/buzzer.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1321. this.appendDummyInput()
  1322. .appendField( /*Blockly.Msg.ESP32TURNOBAF*/);
  1323. //.appendField(new Blockly.FieldNumber(31, 31, 65535, 1), "buzzer_frequency");
  1324. this.appendDummyInput()
  1325. .appendField(Blockly.Msg.basic_buzzer_set_init)
  1326. .appendField(new Blockly.FieldDropdown([
  1327. ["S1", "0"],
  1328. ["S2", "1"]
  1329. ]), "notes")
  1330. this.setInputsInline(true);
  1331. this.setPreviousStatement(true);
  1332. this.setNextStatement(true);
  1333. // this.setPreviousStatement(true, null);
  1334. // this.setNextStatement(true, null);
  1335. this.setColour("#d42b03");
  1336. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Buzzer_TOOLTIP);
  1337. this.setHelpUrl("");
  1338. }
  1339. };
  1340. Blockly.Python['esp32_main_controller_set_buzzer_init'] = function (block) {
  1341. var notes = block.getFieldValue('notes');
  1342. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  1343. sys.path.append("/root/")`
  1344. Blockly.Python.definitions_['v831_import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;
  1345. Blockly.Python.addVariable('BUZZER' + notes, `BUZZER${notes} = multiFuncGpio(${notes},6)`, true);
  1346. var code = '';
  1347. return code;
  1348. };
  1349. Blockly.Blocks['esp32_main_controller_set_buzzer'] = {
  1350. init: function () {
  1351. // this.appendDummyInput()
  1352. // .appendField(new Blockly.FieldImage("blockly/media/buzzer.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1353. this.appendDummyInput()
  1354. .appendField( /*Blockly.Msg.ESP32TURNOBAF*/);
  1355. //.appendField(new Blockly.FieldNumber(31, 31, 65535, 1), "buzzer_frequency");
  1356. this.appendDummyInput().appendField(new Blockly.FieldDropdown([
  1357. ["S1", "0"],
  1358. ["S2", "1"]
  1359. ]), "notes")
  1360. .appendField(Blockly.Msg.basic_buzzer_set)
  1361. .appendField(new Blockly.FieldNumber(31, 20, 12000), 'esp32_var_num');
  1362. this.setInputsInline(true);
  1363. this.setPreviousStatement(true);
  1364. this.setNextStatement(true);
  1365. // this.setPreviousStatement(true, null);
  1366. // this.setNextStatement(true, null);
  1367. this.setColour("#d42b03");
  1368. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Set_Buzzer_TOOLTIP);
  1369. this.setHelpUrl("");
  1370. }
  1371. };
  1372. Blockly.Python['esp32_main_controller_set_buzzer'] = function (block) {
  1373. var esp32_var_num = block.getFieldValue("esp32_var_num");
  1374. var notes = block.getFieldValue('notes');
  1375. var code = `BUZZER${notes}.beep(${esp32_var_num})
  1376. `;
  1377. return code;
  1378. };
  1379. Blockly.Blocks['esp32_main_controller_turn_off_buzzer'] = {
  1380. init: function () {
  1381. this.appendDummyInput().appendField(new Blockly.FieldDropdown([
  1382. ["S1", "0"],
  1383. ["S2", "1"]
  1384. ]), "notes").appendField(Blockly.Msg.ESP32TURNOB);
  1385. this.setPreviousStatement(true, null);
  1386. this.setNextStatement(true, null);
  1387. this.setColour("#d42b03");
  1388. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Turn_Off_Buzzer_TOOLTIP);
  1389. this.setHelpUrl("");
  1390. }
  1391. };
  1392. Blockly.Python['esp32_main_controller_turn_off_buzzer'] = function (block) {
  1393. var notes = block.getFieldValue('notes');
  1394. var code = `BUZZER${notes}.beep(0)
  1395. `
  1396. return code;
  1397. //return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  1398. };
  1399. Blockly.Blocks['esp32_main_controller_turn_off_buzzer_music'] = {
  1400. init: function () {
  1401. this.appendDummyInput().appendField(new Blockly.FieldDropdown([
  1402. ["S1", "0"],
  1403. ["S2", "1"]
  1404. ]), "type")
  1405. .appendField(Blockly.Msg.esp32_main_controller_turn_off_buzzer_music_lite)
  1406. .appendField(new Blockly.FieldDropdown([
  1407. ["C2", "65"],
  1408. ["D2", "73"],
  1409. ["E2", "82"],
  1410. ["F2", "87"],
  1411. ["G2", "98"],
  1412. ["A2", "110"],
  1413. ["B2", "123"],
  1414. ["C3", "130"],
  1415. ["D3", "146"],
  1416. ["E3", "164"],
  1417. ["F3", "174"],
  1418. ["G3", "196"],
  1419. ["A3", "220"],
  1420. ["B3", "246"],
  1421. ["C4", "261"],
  1422. ["D4", "293"],
  1423. ["E4", "329"],
  1424. ["F4", "349"],
  1425. ["G4", "392"],
  1426. ["A4", "440"],
  1427. ["B4", "493"],
  1428. ["C5", "523"],
  1429. ["D5", "587"],
  1430. ["E5", "659"],
  1431. ["F5", "698"],
  1432. ["G5", "784"],
  1433. ["A5", "880"],
  1434. ["B5", "987"],
  1435. ["C6", "1046"],
  1436. ["D6", "1174"],
  1437. ["E6", "1318"],
  1438. ["F6", "1396"],
  1439. ["G6", "1568"],
  1440. ["A6", "1760"],
  1441. ["B6", "1975"],
  1442. ["C7", "2093"],
  1443. ["D7", "2349"],
  1444. ["E7", "2637"],
  1445. ["F7", "2793"],
  1446. ["G7", "3136"],
  1447. ["A7", "3520"],
  1448. ["B7", "3951"],
  1449. ["C8", "4186"],
  1450. ["D8", "4698"],
  1451. ["E8", "5274"],
  1452. ["F8", "5587"],
  1453. ["G8", "6272"],
  1454. ["A8", "7040"],
  1455. ["B8", "7902"]
  1456. ]), "notes")
  1457. .appendField(Blockly.Msg.esp32_main_controller_turn_off_buzzer_music_lite_2);
  1458. this.appendValueInput("beat")
  1459. .setCheck(null);
  1460. this.appendDummyInput()
  1461. .appendField(Blockly.Msg.esp32_main_controller_turn_off_buzzer_music_lite_3);
  1462. this.setInputsInline(true);
  1463. this.setPreviousStatement(true, null);
  1464. this.setNextStatement(true, null);
  1465. this.setColour("#d42b03");
  1466. this.setTooltip(Blockly.Msg.esp32_main_controller_turn_off_buzzer_music_lite_TOOLTIP);
  1467. this.setHelpUrl("");
  1468. }
  1469. };
  1470. Blockly.Python['esp32_main_controller_turn_off_buzzer_music'] = function (block) {
  1471. Blockly.Python.definitions_['v831_import_time'] = `import time`
  1472. var beat = Blockly.Python.valueToCode(block, 'beat', Blockly.Python.ORDER_ATOMIC).replace("(", "").replace(")", "");
  1473. var type = block.getFieldValue('type');
  1474. var notes = block.getFieldValue('notes');
  1475. // TODO: Assemble Python into code variable.
  1476. // TODO: Assemble Python into code variable.
  1477. var code = `BUZZER${type}.beep(${notes})
  1478. time.sleep(${beat})
  1479. `
  1480. return code;
  1481. };
  1482. Blockly.Blocks['esp32_main_controller_buzzer_set_beat_lite'] = {
  1483. init: function () {
  1484. this.appendDummyInput()
  1485. .appendField(new Blockly.FieldDropdown([
  1486. ["1/2", "0.5"],
  1487. ["1", "1"],
  1488. ["1/4", "0.25"],
  1489. ["1/8", "0.125"],
  1490. ["1/16", "0.063"]
  1491. ]), "beat");
  1492. this.setInputsInline(true);
  1493. this.setOutput(true, null);
  1494. this.setColour("#d42b03");
  1495. this.setHelpUrl("");
  1496. var thisBlock = this;
  1497. this.setTooltip(function () {
  1498. var mode = thisBlock.getFieldValue('beat');
  1499. var TOOLTIPS = {
  1500. "1": "%1".replace("%1", "1"),
  1501. "0.5": "%1".replace("%1", "1/2"),
  1502. "0.25": "%1".replace("%1", "1/4"),
  1503. "0.125": "%1".replace("%1", "1/8"),
  1504. "0.063": "%1".replace("%1", "1/16")
  1505. };
  1506. return TOOLTIPS[mode];
  1507. });
  1508. }
  1509. };
  1510. Blockly.Python['esp32_main_controller_buzzer_set_beat_lite'] = function (block) {
  1511. var value_name1 = block.getFieldValue('beat');
  1512. var code = value_name1;
  1513. return [code, Blockly.Python.ORDER_NONE];
  1514. };
  1515. /*
  1516. TOUCH AREA
  1517. */
  1518. Blockly.Blocks['esp32_main_controller_touch_read_touched'] = {
  1519. init: function () {
  1520. // this.appendDummyInput()
  1521. // .appendField(new Blockly.FieldImage("blockly/media/touched.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1522. this.appendDummyInput()
  1523. .appendField(Blockly.Msg.ESP32TA)
  1524. .appendField(new Blockly.FieldDropdown([
  1525. ["A", "touch_area_type_a"],
  1526. ["B", "touch_area_type_b"]
  1527. ]), "touch_area_type")
  1528. .appendField(Blockly.Msg.ESP32_TOUCHED)
  1529. this.setOutput(true, null);
  1530. this.setColour("#d42b03");
  1531. this.setHelpUrl("");
  1532. var thisBlock = this;
  1533. this.setTooltip(function () {
  1534. var mode = thisBlock.getFieldValue('touch_area_type');
  1535. var TOOLTIPS = {
  1536. 'touch_area_type_a': Blockly.Msg.Esp32_Main_Controller_Touch_Read_Touched_TOOLTIP.replace('%1', "A"),
  1537. 'touch_area_type_b': Blockly.Msg.Esp32_Main_Controller_Touch_Read_Touched_TOOLTIP.replace('%1', "B")
  1538. };
  1539. return TOOLTIPS[mode];
  1540. });
  1541. }
  1542. };
  1543. Blockly.Python['esp32_main_controller_touch_read_touched'] = function (block) {
  1544. Blockly.Python.definitions_['import_touch_esp32'] = 'from machine import TouchPad\n' +
  1545. 'from machine import Pin\n' +
  1546. '\n' +
  1547. '_TOUCH_A = TouchPad(Pin(4))\n' +
  1548. '_TOUCH_B = TouchPad(Pin(27))\n' +
  1549. '\n' +
  1550. 'def GetTouchValue(area):\n' +
  1551. ' try:\n' +
  1552. ' if area == "A":\n' +
  1553. ' return _TOUCH_A.read()\n' +
  1554. ' elif area == "B":\n' +
  1555. ' return _TOUCH_B.read()\n' +
  1556. ' except BaseException as e:\n' +
  1557. ' return False\n' +
  1558. '';
  1559. // var code = '_TOUCH_' + block.getField('touch_area_type').text_ + '.read() ' + "< 100";
  1560. var code = 'GetTouchValue("' + block.getField('touch_area_type').text_ + '") < 100';
  1561. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1562. };
  1563. Blockly.Blocks['esp32_main_controller_touch_read_untouched'] = {
  1564. init: function () {
  1565. // this.appendDummyInput()
  1566. // .appendField(new Blockly.FieldImage("blockly/media/untouched.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1567. this.appendDummyInput()
  1568. .appendField(Blockly.Msg.ESP32TA)
  1569. .appendField(new Blockly.FieldDropdown([
  1570. ["A", "touch_area_type_a"],
  1571. ["B", "touch_area_type_b"]
  1572. ]), "touch_area_type")
  1573. .appendField(Blockly.Msg.ESP32_UNTOUCHED)
  1574. this.setOutput(true, null);
  1575. this.setColour("#d42b03");
  1576. this.setHelpUrl("");
  1577. var thisBlock = this;
  1578. this.setTooltip(function () {
  1579. var mode = thisBlock.getFieldValue('touch_area_type');
  1580. var TOOLTIPS = {
  1581. 'touch_area_type_a': Blockly.Msg.Esp32_Main_Controller_Touch_Read_Untouched_TOOLTIP.replace('%1', "A"),
  1582. 'touch_area_type_b': Blockly.Msg.Esp32_Main_Controller_Touch_Read_Untouched_TOOLTIP.replace('%1', "B")
  1583. };
  1584. return TOOLTIPS[mode];
  1585. });
  1586. }
  1587. };
  1588. Blockly.Python['esp32_main_controller_touch_read_untouched'] = function (block) {
  1589. Blockly.Python.definitions_['import_touch_esp32'] = 'from machine import TouchPad\n' +
  1590. 'from machine import Pin\n' +
  1591. '\n' +
  1592. '_TOUCH_A = TouchPad(Pin(4))\n' +
  1593. '_TOUCH_B = TouchPad(Pin(27))\n' +
  1594. '\n' +
  1595. 'def GetTouchValue(area):\n' +
  1596. ' try:\n' +
  1597. ' if area == "A":\n' +
  1598. ' return _TOUCH_A.read()\n' +
  1599. ' elif area == "B":\n' +
  1600. ' return _TOUCH_B.read()\n' +
  1601. ' except BaseException as e:\n' +
  1602. ' return False\n' +
  1603. '';
  1604. // var code = '_TOUCH_' + block.getField('touch_area_type').text_ + '.read() ' + "< 100";
  1605. var code = 'GetTouchValue("' + block.getField('touch_area_type').text_ + '") >= 100';
  1606. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1607. };
  1608. Blockly.Blocks['esp32_main_controller_touch_read_value'] = {
  1609. init: function () {
  1610. this.appendDummyInput()
  1611. .appendField(Blockly.Msg.ESP32_READ)
  1612. .appendField(new Blockly.FieldDropdown([
  1613. ["A", "touch_area_type_a"],
  1614. ["B", "touch_area_type_b"]
  1615. ]), "touch_area_type")
  1616. .appendField(Blockly.Msg.ESP32_READ_VALUE);
  1617. this.setInputsInline(false);
  1618. this.setOutput(true, null);
  1619. this.setColour("#d42b03");
  1620. this.setHelpUrl("");
  1621. var thisBlock = this;
  1622. this.setTooltip(function () {
  1623. var mode = thisBlock.getFieldValue('touch_area_type');
  1624. var TOOLTIPS = {
  1625. 'touch_area_type_a': Blockly.Msg.Esp32_Main_Controller_Touch_Read_Value_TOOLTIP.replace('%1', "A"),
  1626. 'touch_area_type_b': Blockly.Msg.Esp32_Main_Controller_Touch_Read_Value_TOOLTIP.replace('%1', "B")
  1627. };
  1628. return TOOLTIPS[mode];
  1629. });
  1630. }
  1631. };
  1632. Blockly.Python['esp32_main_controller_touch_read_value'] = function (block) {
  1633. Blockly.Python.definitions_['import_touch_esp32'] = 'from machine import TouchPad\n' +
  1634. 'from machine import Pin\n' +
  1635. '\n' +
  1636. '_TOUCH_A = TouchPad(Pin(4))\n' +
  1637. '_TOUCH_B = TouchPad(Pin(27))\n' +
  1638. '\n' +
  1639. 'def GetTouchValue(area):\n' +
  1640. ' try:\n' +
  1641. ' if area == "A":\n' +
  1642. ' return _TOUCH_A.read()\n' +
  1643. ' elif area == "B":\n' +
  1644. ' return _TOUCH_B.read()\n' +
  1645. ' except BaseException as e:\n' +
  1646. ' return False\n' +
  1647. '';
  1648. // var code = '_TOUCH_' + block.getField('touch_area_type').text_ + '.read() ' + "< 100";
  1649. var code = 'GetTouchValue("' + block.getField('touch_area_type').text_ + '")';
  1650. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1651. };
  1652. /*
  1653. Env Sensor: BME280
  1654. */
  1655. Blockly.Blocks['esp32_main_controller_get_environmental_value'] = {
  1656. init: function () {
  1657. // this.appendDummyInput()
  1658. // .appendField(new Blockly.FieldImage("blockly/media/env_get.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1659. this.appendDummyInput()
  1660. .appendField(Blockly.Msg.ESP32_ENV_GET_TEXT)
  1661. .appendField(new Blockly.FieldDropdown([
  1662. [Blockly.Msg.basic_temperature, "temperature"],
  1663. [Blockly.Msg.basic_humidity, "humidity"]
  1664. // [Blockly.Msg.basic_pressure, "pressure"]
  1665. ]), "env_get_type")
  1666. .appendField(Blockly.Msg.basic_env_value);
  1667. this.setInputsInline(false);
  1668. this.setOutput(true, null);
  1669. this.setColour("#5fcd8e");
  1670. this.setHelpUrl("");
  1671. var thisBlock = this;
  1672. this.setTooltip(function () {
  1673. var mode = thisBlock.getFieldValue('env_get_type');
  1674. var TOOLTIPS = {
  1675. 'temperature': Blockly.Msg.Esp32_Main_Controller_Get_Environmental_Value_TOOLTIP.replace('%1', Blockly.Msg.basic_temperature),
  1676. 'humidity': Blockly.Msg.Esp32_Main_Controller_Get_Environmental_Value_TOOLTIP.replace('%1', Blockly.Msg.basic_humidity)
  1677. };
  1678. return TOOLTIPS[mode];
  1679. });
  1680. }
  1681. };
  1682. Blockly.Python['esp32_main_controller_get_environmental_value'] = function (block) {
  1683. var _type_selected = block.getFieldValue('env_get_type');
  1684. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  1685. sys.path.append("/root/")`
  1686. Blockly.Python.definitions_['v831_import_AHT20'] = `from CocoPi import AHT20`
  1687. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  1688. Blockly.Python.definitions_['v831_import_AHT20_object'] = `aht20 = AHT20(2) `
  1689. Blockly.Python.addVariable('_BME', '');
  1690. let code = ''
  1691. if (_type_selected == 'temperature') {
  1692. code = `aht20.get_temperature()`
  1693. } else if (_type_selected == 'humidity') {
  1694. code = `aht20.get_humidity()`;
  1695. } else {
  1696. code = _type_selected;
  1697. }
  1698. // TODO: Change ORDER_NONE to the correct strength.
  1699. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1700. };
  1701. /*
  1702. Motion Sensor: QMI8658
  1703. */
  1704. Blockly.Blocks['esp32_main_controller_motion_init'] = {
  1705. init: function () {
  1706. //this.appendDummyInput()
  1707. // .appendField(new Blockly.FieldImage("blockly/media/motion_setup.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  1708. this.appendDummyInput()
  1709. .appendField(Blockly.Msg.basic_motion_use);
  1710. this.setInputsInline(false);
  1711. this.setPreviousStatement(true, null);
  1712. this.setNextStatement(true, null);
  1713. this.setColour("#e8795b");
  1714. this.setTooltip("");
  1715. this.setHelpUrl("");
  1716. }
  1717. };
  1718. Blockly.Python['esp32_main_controller_motion_init'] = function (block) {
  1719. // Blockly.Python.addVariable('_SENSOR_MPU_PINS', '');
  1720. Blockly.Python.definitions_['import_QMI8658'] = '' +
  1721. 'from machine import I2C, Pin\n' +
  1722. 'import math\n' +
  1723. 'import QMI8658\n' +
  1724. '_SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' +
  1725. '';
  1726. var code = '' +
  1727. '_MPU = QMI8658.accel(_SENSOR_MPU_PINS)\n' +
  1728. '_MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' +
  1729. '_MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' +
  1730. '_MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' +
  1731. '_MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' +
  1732. '_MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' +
  1733. '_MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' +
  1734. '_MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' +
  1735. '';
  1736. return code;
  1737. };
  1738. Blockly.Blocks['esp32_main_controller_motion_when_shaking'] = {
  1739. init: function () {
  1740. this.appendDummyInput()
  1741. .appendField(Blockly.Msg.basic_when_shaking);
  1742. this.setInputsInline(false);
  1743. this.setOutput(true, null);
  1744. this.setColour("#e8795b");
  1745. this.setTooltip("");
  1746. this.setHelpUrl("");
  1747. }
  1748. };
  1749. Blockly.Python['esp32_main_controller_motion_when_shaking'] = function (block) {
  1750. Blockly.Python.definitions_['shaking_def'] = '' +
  1751. 'def _CHECK_SHAKING():\n' +
  1752. ' if _MPU_SHAKING_OFFSET < 0 and _SSTATE == 0:\n' +
  1753. ' _SSTATE = 1\n' +
  1754. ' return True\n' +
  1755. ' elif _MPU_SHAKING_OFFSET > 0 and _SSTATE == 1:\n' +
  1756. ' _SSTATE = 0\n' +
  1757. ' return False\n' +
  1758. '';
  1759. var code = '(_CHECK_SHAKING() == True)';
  1760. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1761. };
  1762. Blockly.Blocks['esp32_main_controller_motion_when_shaking_STATEMENT'] = {
  1763. init: function () {
  1764. this.appendDummyInput()
  1765. .appendField()
  1766. .appendField(Blockly.Msg.basic_shaking_sensitivity)
  1767. .appendField(new Blockly.FieldDropdown([
  1768. [Blockly.Msg.basic_shaking_sensitivity_high, "high"],
  1769. [Blockly.Msg.basic_shaking_sensitivity_middle, "middle"],
  1770. [Blockly.Msg.basic_shaking_sensitivity_low, "low"]
  1771. ]), "sensitivity")
  1772. .appendField(Blockly.Msg.basic_when_shaking_when_module)
  1773. .appendField(new Blockly.FieldDropdown([
  1774. [Blockly.Msg.basic_when_shaking_when_is_in, "True"],
  1775. [Blockly.Msg.basic_when_shaking_when_is_not_in, "False"]
  1776. ]), "status")
  1777. .appendField(Blockly.Msg.basic_when_shaking_when_shaking);
  1778. this.appendStatementInput("input")
  1779. .setCheck(null)
  1780. .appendField(Blockly.Msg.basic_motion_statement_exec);
  1781. this.setPreviousStatement(true, null);
  1782. this.setNextStatement(true, null);
  1783. this.setColour("#d42b03");
  1784. this.setHelpUrl("");
  1785. var thisBlock = this;
  1786. this.setTooltip(function () {
  1787. var mode = thisBlock.getFieldValue('status');
  1788. var TOOLTIPS = {
  1789. 'True': Blockly.Msg.Esp32_Main_Controller_Motion_When_Shaking_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_shaking_when_is_in),
  1790. 'False': Blockly.Msg.Esp32_Main_Controller_Motion_When_Shaking_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_shaking_when_is_not_in)
  1791. };
  1792. return TOOLTIPS[mode];
  1793. });
  1794. }
  1795. };
  1796. Blockly.Python['esp32_main_controller_motion_when_shaking_STATEMENT'] = function (block) {
  1797. var dropdown_status = block.getFieldValue('status');
  1798. var sensitivity = block.getFieldValue('sensitivity');
  1799. var statements_input = Blockly.Python.statementToCode(block, 'input');
  1800. var temp = 0;
  1801. if (sensitivity == "high") {
  1802. temp = 99;
  1803. }
  1804. else if (sensitivity == "middle") {
  1805. temp = 23;
  1806. }
  1807. else {
  1808. temp = 1;
  1809. }
  1810. Blockly.Python.definitions_['import_QMI8658'] = '' +
  1811. 'from machine import I2C, Pin\n' +
  1812. 'import math\n' +
  1813. 'import QMI8658\n' +
  1814. '\n' +
  1815. 'mpu_lib_version_is_latest = "QMI8658" in dir(QMI8658)\n' +
  1816. 'if mpu_lib_version_is_latest == True:\n' +
  1817. ' mpui2c = I2C(scl=Pin(22), sda=Pin(21))\n' +
  1818. ' QMI8658 = QMI8658.QMI8658(mpui2c)\n' +
  1819. ' mpucal = QMI8658.calibrate()\n' +
  1820. 'elif mpu_lib_version_is_latest == False:\n' +
  1821. ' _SENSOR_MPU_PINS = I2C(scl=Pin(22), sda=Pin(21))\n' +
  1822. ' _MPU = QMI8658.accel(_SENSOR_MPU_PINS)\n' +
  1823. ' _MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' +
  1824. ' _MPU_ACCL_X = _MPU.get_values()[\'AcX\']\n' +
  1825. ' _MPU_ACCL_Y = _MPU.get_values()[\'AcY\']\n' +
  1826. ' _MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' +
  1827. ' _MPU_OFFSET_TILT_X = _MPU_GET_TILT_ANGLE(\'X\')\n' +
  1828. ' _MPU_OFFSET_TILT_Y = _MPU_GET_TILT_ANGLE(\'Y\')\n' +
  1829. ' _MPU_OFFSET_TILT_Z = _MPU_GET_TILT_ANGLE(\'Z\')\n' +
  1830. '\n' +
  1831. '';
  1832. Blockly.Python.definitions_['shaking_def'] = '' +
  1833. 'def _CHECK_SHAKING():\n' +
  1834. ' _MPU = QMI8658.accel(_SENSOR_MPU_PINS)\n' +
  1835. ' _MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' +
  1836. ' _MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' +
  1837. ' _SSTATE = 0\n' +
  1838. ' if _MPU_SHAKING_OFFSET < 0:\n' +
  1839. ' _SSTATE = 1\n' +
  1840. ' return True\n' +
  1841. ' elif _MPU_SHAKING_OFFSET > 0:\n' +
  1842. ' _SSTATE = 0\n' +
  1843. ' return False\n' +
  1844. '';
  1845. var code = '' +
  1846. 'if mpu_lib_version_is_latest == True and (QMI8658.is_shaking(mpucal,' + temp + ') == ' + dropdown_status + '):\n' +
  1847. '' + statements_input + '\n' +
  1848. 'elif mpu_lib_version_is_latest == False and (_CHECK_SHAKING() == ' + dropdown_status + '):\n' +
  1849. ' _MPU = QMI8658.accel(_SENSOR_MPU_PINS)\n' +
  1850. ' _MPU_SHAKING_OFFSET = _MPU.get_values()[\'AcZ\']\n' +
  1851. ' _MPU_ACCL_Z = _MPU.get_values()[\'AcZ\']\n' +
  1852. '' + statements_input + '\n' +
  1853. '';
  1854. return code;
  1855. };
  1856. Blockly.Blocks['esp32_main_controller_motion_when_tilting'] = {
  1857. init: function () {
  1858. this.appendDummyInput()
  1859. .appendField(Blockly.Msg.basic_when_tilting_get)
  1860. .appendField(new Blockly.FieldDropdown([
  1861. [Blockly.Msg.basic_when_tilting_get_left, "L"],
  1862. [Blockly.Msg.basic_when_tilting_get_right, "R"],
  1863. [Blockly.Msg.basic_when_tilting_get_forward, "F"],
  1864. [Blockly.Msg.basic_when_tilting_get_backward, "B"]
  1865. ]), "tilt_type")
  1866. .appendField(Blockly.Msg.basic_when_tilting_get_when);
  1867. this.setInputsInline(false);
  1868. this.setOutput(true, null);
  1869. this.setColour("#e8795b");
  1870. this.setTooltip("");
  1871. this.setHelpUrl("");
  1872. }
  1873. };
  1874. Blockly.Python['esp32_main_controller_motion_when_tilting'] = function (block) {
  1875. var _type_selected = block.getFieldValue('tilt_type');
  1876. Blockly.Python.definitions_['tilting_def'] = '' +
  1877. 'def _CHECK_TILT_LR():\n' +
  1878. ' if _MPU_OFFSET_TILT_X < 160 and _MPU_OFFSET_TILT_X > 0:\n' +
  1879. ' return "R"\n' +
  1880. ' elif _MPU_OFFSET_TILT_X > 200 and _MPU_OFFSET_TILT_X < 360:\n' +
  1881. ' return "L"\n' +
  1882. ' else:\n' +
  1883. ' return None\n' +
  1884. '\n' +
  1885. 'def _CHECK_TILT_FB():\n' +
  1886. ' if _MPU_OFFSET_TILT_Y < 160 and _MPU_OFFSET_TILT_Y > 0:\n' +
  1887. ' return "F"\n' +
  1888. ' elif _MPU_OFFSET_TILT_Y > 200 and _MPU_OFFSET_TILT_Y < 360:\n' +
  1889. ' return "B"\n' +
  1890. ' else:\n' +
  1891. ' return None\n' +
  1892. '';
  1893. if (_type_selected == "L" || _type_selected == "R") {
  1894. _check_function = '(_CHECK_TILT_LR() == "';
  1895. } else if (_type_selected == "F" || _type_selected == "B") {
  1896. _check_function = '(_CHECK_TILT_FB() == "';
  1897. }
  1898. var code = _check_function + _type_selected + '")';
  1899. return [code, Blockly.Python.ORDER_CONDITIONAL];
  1900. };
  1901. Blockly.Blocks['esp32_main_controller_motion_when_tilting_STATEMENT'] = {
  1902. init: function () {
  1903. this.appendDummyInput()
  1904. .appendField(Blockly.Msg.basic_when_tilting_get)
  1905. .appendField(new Blockly.FieldDropdown([
  1906. [Blockly.Msg.basic_when_tilting_get_left, "L"],
  1907. [Blockly.Msg.basic_when_tilting_get_right, "R"],
  1908. [Blockly.Msg.basic_when_tilting_get_forward, "F"],
  1909. [Blockly.Msg.basic_when_tilting_get_backward, "B"],
  1910. // [Blockly.Msg.basic_when_tilting_get_left_and_forward, "LF"],
  1911. // [Blockly.Msg.basic_when_tilting_get_left_and_backward, "LB"],
  1912. // [Blockly.Msg.basic_when_tilting_get_right_and_forward, "RF"],
  1913. // [Blockly.Msg.basic_when_tilting_get_right_and_backward, "RB"],
  1914. // [Blockly.Msg.basic_when_tilting_not_tilting, "N"]
  1915. ]), "tilt_type")
  1916. .appendField(Blockly.Msg.basic_when_tilting_get_when);
  1917. this.appendStatementInput("input")
  1918. .setCheck(null)
  1919. .appendField(Blockly.Msg.basic_motion_statement_exec);
  1920. this.setPreviousStatement(true, null);
  1921. this.setNextStatement(true, null)
  1922. this.setColour("#5fcd8e");
  1923. var thisBlock = this;
  1924. this.setTooltip(function () {
  1925. var mode = thisBlock.getFieldValue('tilt_type');
  1926. var TOOLTIPS = {
  1927. 'L': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_left),
  1928. 'R': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_right),
  1929. 'F': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_forward),
  1930. 'B': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_backward),
  1931. 'LF': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_left_and_forward),
  1932. 'LB': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_left_and_backward),
  1933. 'RF': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_right_and_forward),
  1934. 'RB': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_get_right_and_backward),
  1935. 'N': Blockly.Msg.Esp32_Main_Controller_Motion_When_Tilting_STATEMENT_TOOLTIP.replace('%1', Blockly.Msg.basic_when_tilting_not_tilting)
  1936. };
  1937. return TOOLTIPS[mode];
  1938. });
  1939. this.setHelpUrl("");
  1940. }
  1941. };
  1942. Blockly.Python['esp32_main_controller_motion_when_tilting_STATEMENT'] = function (block) {
  1943. var _type_selected = block.getFieldValue('tilt_type');
  1944. var statements_input = Blockly.Python.statementToCode(block, 'input');
  1945. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  1946. sys.path.append("/root/")`
  1947. Blockly.Python.definitions_['v831_import_QMI8658'] = `from CocoPi import QMI8658`
  1948. Blockly.Python.definitions_['v831_QMI8658_import_path'] = `
  1949. #初始化设置
  1950. qmi8658=QMI8658()
  1951. #校准
  1952. qmi8658.calibrate()
  1953. #标定初始方位
  1954. initData={}
  1955. initData["AcX"]=qmi8658.get_accel(10)["AcX"]
  1956. initData["AcY"]=qmi8658.get_accel(10)["AcY"]
  1957. initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
  1958. initData["GyX"]=qmi8658.get_accel(10)["GyX"]
  1959. initData["GyY"]=qmi8658.get_accel(10)["GyY"]
  1960. initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
  1961. `;
  1962. // Blockly.Python.addVariable('_MPU_ACCL_' + _type_selected, '');
  1963. var code = ``;
  1964. if (_type_selected == "L") {
  1965. code = `if round(qmi8658.getPitchYawRollGxGyGz(initData)[0],2) < -15:
  1966. ${statements_input}`
  1967. } else if (_type_selected == "R") {
  1968. code = `if round(qmi8658.getPitchYawRollGxGyGz(initData)[0],2) > 15:
  1969. ${statements_input}`
  1970. } else if (_type_selected == "B") {
  1971. code = `if round(qmi8658.getPitchYawRollGxGyGz(initData)[1],2) < -15:
  1972. ${statements_input}`
  1973. } else if (_type_selected == "F") {
  1974. code = `if round(qmi8658.getPitchYawRollGxGyGz(initData)[1],2) > 15:
  1975. ${statements_input}`
  1976. }
  1977. return code;
  1978. };
  1979. Blockly.Blocks['esp32_main_controller_motion_acceleration'] = {
  1980. init: function () {
  1981. this.appendDummyInput()
  1982. .appendField(Blockly.Msg.basic_motion_get_along)
  1983. .appendField(new Blockly.FieldDropdown([
  1984. ["X", "4"],
  1985. ["Y", "3"],
  1986. ["Z", "5"]
  1987. ]), "accel_type")
  1988. .appendField(Blockly.Msg.basic_motion_accel);
  1989. // this.appendDummyInput()
  1990. // .appendField(Blockly.Msg.isUnit)
  1991. // .appendField(new Blockly.FieldDropdown([
  1992. // [Blockly.Msg.cancUnit, "N"],
  1993. // [Blockly.Msg.confUnit, "Y"]
  1994. // ]), "isUnit");
  1995. this.setInputsInline(false);
  1996. this.setOutput(true, null);
  1997. this.setColour("#5fcd8e");
  1998. var thisBlock = this;
  1999. this.setTooltip(function () {
  2000. var mode = thisBlock.getFieldValue('accel_type');
  2001. var TOOLTIPS = {
  2002. 'X': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'X'),
  2003. 'Y': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'Y'),
  2004. 'Z': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'Z')
  2005. };
  2006. return TOOLTIPS[mode];
  2007. });
  2008. this.setHelpUrl("");
  2009. }
  2010. };
  2011. Blockly.Python['esp32_main_controller_motion_acceleration'] = function (block) {
  2012. var _type_selected = block.getFieldValue('accel_type');
  2013. // var is_unit = block.getFieldValue('isUnit');
  2014. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  2015. sys.path.append("/root/")`
  2016. Blockly.Python.definitions_['v831_import_QMI8658'] = `from CocoPi import QMI8658`
  2017. Blockly.Python.definitions_['v831_QMI8658_import_path'] = `
  2018. #初始化设置
  2019. qmi8658=QMI8658()
  2020. #校准
  2021. qmi8658.calibrate()
  2022. #标定初始方位
  2023. initData={}
  2024. initData["AcX"]=qmi8658.get_accel(10)["AcX"]
  2025. initData["AcY"]=qmi8658.get_accel(10)["AcY"]
  2026. initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
  2027. initData["GyX"]=qmi8658.get_accel(10)["GyX"]
  2028. initData["GyY"]=qmi8658.get_accel(10)["GyY"]
  2029. initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
  2030. `;
  2031. // Blockly.Python.addVariable('_MPU_ACCL_' + _type_selected, '');
  2032. var code = `round(qmi8658.getPitchYawRollGxGyGz(initData)[${_type_selected}],2)`;
  2033. return [code, Blockly.Python.ORDER_CONDITIONAL];
  2034. };
  2035. Blockly.Blocks['esp32_main_controller_motion_rotation_measurement'] = {
  2036. init: function () {
  2037. this.appendDummyInput()
  2038. .appendField(Blockly.Msg.basic_motion_get_along)
  2039. .appendField(new Blockly.FieldDropdown([
  2040. ["X", "4"],
  2041. ["Y", "3"],
  2042. ["Z", "5"]
  2043. ]), "accel_type")
  2044. .appendField(Blockly.Msg.basic_motion_rotation_measurement);
  2045. // this.appendDummyInput()
  2046. // .appendField(Blockly.Msg.isUnit)
  2047. // .appendField(new Blockly.FieldDropdown([
  2048. // [Blockly.Msg.cancUnit, "N"],
  2049. // [Blockly.Msg.confUnit, "Y"]
  2050. // ]), "isUnit");
  2051. this.setInputsInline(false);
  2052. this.setOutput(true, null);
  2053. this.setColour("#d42b03");
  2054. var thisBlock = this;
  2055. this.setTooltip(function () {
  2056. var mode = thisBlock.getFieldValue('accel_type');
  2057. var TOOLTIPS = {
  2058. 'X': Blockly.Msg.Esp32_Main_Controller_Motion_Rotation_Measurement_TOOLTIP.replace('%1', 'X'),
  2059. 'Y': Blockly.Msg.Esp32_Main_Controller_Motion_Rotation_Measurement_TOOLTIP.replace('%1', 'Y'),
  2060. 'Z': Blockly.Msg.Esp32_Main_Controller_Motion_Rotation_Measurement_TOOLTIP.replace('%1', 'Z')
  2061. };
  2062. return TOOLTIPS[mode];
  2063. });
  2064. this.setHelpUrl("");
  2065. }
  2066. };
  2067. Blockly.Python['esp32_main_controller_motion_rotation_measurement'] = function (block) {
  2068. var _type_selected = block.getFieldValue('accel_type');
  2069. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  2070. sys.path.append("/root/")`
  2071. Blockly.Python.definitions_['v831_import_QMI8658'] = `from CocoPi import QMI8658`
  2072. Blockly.Python.definitions_['v831_QMI8658_import_path'] = `
  2073. #初始化设置
  2074. qmi8658=QMI8658()
  2075. #校准
  2076. qmi8658.calibrate()
  2077. #标定初始方位
  2078. initData={}
  2079. initData["AcX"]=qmi8658.get_accel(10)["AcX"]
  2080. initData["AcY"]=qmi8658.get_accel(10)["AcY"]
  2081. initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
  2082. initData["GyX"]=qmi8658.get_accel(10)["GyX"]
  2083. initData["GyY"]=qmi8658.get_accel(10)["GyY"]
  2084. initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
  2085. `;
  2086. // Blockly.Python.addVariable('_MPU_ACCL_' + _type_selected, '');
  2087. var code = `round(qmi8658.getPitchYawRollGxGyGz(initData)[${_type_selected}],2)`;
  2088. return [code, Blockly.Python.ORDER_CONDITIONAL];
  2089. };
  2090. Blockly.Blocks['esp32_main_controller_motion_tilt_angle'] = {
  2091. init: function () {
  2092. this.appendDummyInput()
  2093. .appendField(Blockly.Msg.basic_motion_get_along)
  2094. .appendField(new Blockly.FieldDropdown([
  2095. ["X", "1"],
  2096. ["Y", "0"],
  2097. // ["Z", "2"]
  2098. ]), "tilt_angle_type")
  2099. .appendField(Blockly.Msg.basic_motion_angle);
  2100. // this.appendDummyInput()
  2101. // .appendField(Blockly.Msg.isUnit)
  2102. // .appendField(new Blockly.FieldDropdown([
  2103. // [Blockly.Msg.cancUnit, "N"],
  2104. // [Blockly.Msg.confUnit, "Y"]
  2105. // ]), "isUnit");
  2106. this.setInputsInline(false);
  2107. this.setOutput(true, null);
  2108. this.setColour("#5fcd8e");
  2109. var thisBlock = this;
  2110. this.setTooltip(function () {
  2111. var mode = thisBlock.getFieldValue('tilt_angle_type');
  2112. var TOOLTIPS = {
  2113. 'X': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'X'),
  2114. 'Y': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'Y')
  2115. };
  2116. return TOOLTIPS[mode];
  2117. });
  2118. this.setHelpUrl("");
  2119. }
  2120. };
  2121. Blockly.Python['esp32_main_controller_motion_tilt_angle'] = function (block) {
  2122. var _type_selected = block.getFieldValue('tilt_angle_type');
  2123. // var is_unit = block.getFieldValue('isUnit');
  2124. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  2125. sys.path.append("/root/")`
  2126. Blockly.Python.definitions_['v831_import_QMI8658'] = `from CocoPi import QMI8658`
  2127. Blockly.Python.definitions_['v831_QMI8658_import_path'] = `
  2128. #初始化设置
  2129. qmi8658=QMI8658()
  2130. #校准
  2131. qmi8658.calibrate()
  2132. #标定初始方位
  2133. initData={}
  2134. initData["AcX"]=qmi8658.get_accel(10)["AcX"]
  2135. initData["AcY"]=qmi8658.get_accel(10)["AcY"]
  2136. initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
  2137. initData["GyX"]=qmi8658.get_accel(10)["GyX"]
  2138. initData["GyY"]=qmi8658.get_accel(10)["GyY"]
  2139. initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
  2140. `
  2141. var code = `round(qmi8658.getPitchYawRollGxGyGz(initData)[${_type_selected}],2)`
  2142. return [code, Blockly.Python.ORDER_CONDITIONAL];
  2143. };
  2144. /*
  2145. LIGHT & SOUND
  2146. */
  2147. Blockly.Blocks['esp32_main_controller_get_light'] = {
  2148. init: function () {
  2149. // this.appendDummyInput()
  2150. // .appendField(new Blockly.FieldImage("blockly/media/light_sensor.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  2151. this.appendDummyInput()
  2152. .appendField(Blockly.Msg.basic_light_get);
  2153. this.setInputsInline(false);
  2154. this.setOutput(true, null);
  2155. this.setColour("#5fcd8e");
  2156. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Get_Light_TOOLTIP);
  2157. this.setHelpUrl("");
  2158. }
  2159. };
  2160. Blockly.Python['esp32_main_controller_get_light'] = function (block) {
  2161. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  2162. sys.path.append("/root/")`
  2163. Blockly.Python.definitions_['v831_import_QMI8658'] = `from CocoPi import LIGHTINTENSITY`
  2164. Blockly.Python.definitions_['v831_import_LIGHTINTENSITY'] = `v831_adc0 = LIGHTINTENSITY()
  2165. `
  2166. var code = 'v831_adc0.value()';
  2167. return [code, Blockly.Python.ORDER_CONDITIONAL];
  2168. };
  2169. /* time */
  2170. var ESP32_TIME_COLOR = "#fabe23";
  2171. Blockly.Blocks['esp32_main_controller_time_timer_init'] = {
  2172. init: function () {
  2173. this.appendDummyInput().appendField(Blockly.Msg.time_init_timer);
  2174. this.setPreviousStatement(true, null);
  2175. this.setNextStatement(true, null);
  2176. this.setColour(ESP32_TIME_COLOR);
  2177. var thisBlock = this;
  2178. this.setTooltip(function () {
  2179. var mode = thisBlock.getFieldValue('type');
  2180. var TOOLTIPS = {
  2181. 'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Init_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
  2182. 'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Init_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
  2183. };
  2184. return TOOLTIPS[mode];
  2185. });
  2186. this.setHelpUrl("");
  2187. }
  2188. };
  2189. Blockly.Python['esp32_main_controller_time_timer_init'] = function (block) {
  2190. var timer_type = block.getFieldValue('type');
  2191. Blockly.Python.definitions_['v831_import_time'] = `import time`
  2192. Blockly.Python.definitions_['counter_start_variable'] = `counter_start = 0
  2193. def counter_start_fun():
  2194. global counter_start
  2195. counter_start = time.perf_counter()
  2196. `;
  2197. var code = `counter_start_fun()
  2198. `
  2199. return code;
  2200. };
  2201. Blockly.Blocks['esp32_main_controller_time_timer_get_current'] = {
  2202. init: function () {
  2203. this.appendDummyInput().appendField(Blockly.Msg.time_timer_get_time);
  2204. this.setOutput(true, null);
  2205. this.setColour(ESP32_TIME_COLOR);
  2206. var thisBlock = this;
  2207. this.setTooltip(function () {
  2208. var mode = thisBlock.getFieldValue('type');
  2209. var TOOLTIPS = {
  2210. 'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Get_Current_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
  2211. 'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Get_Current_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
  2212. };
  2213. return TOOLTIPS[mode];
  2214. });
  2215. this.setHelpUrl("");
  2216. }
  2217. };
  2218. Blockly.Python['esp32_main_controller_time_timer_get_current'] = function (block) {
  2219. var timer_type = block.getFieldValue('type');
  2220. // TODO: Assemble Python into code variable.
  2221. Blockly.Python.definitions_['counter_end'] = `def getcounterEndStart(newDate):
  2222. global counter_start
  2223. return newDate - counter_start
  2224. `
  2225. // '' +
  2226. // 'counter_end=time.perf_counter()\n' +
  2227. // '\n';
  2228. var code = `getcounterEndStart(time.perf_counter())`;
  2229. // TODO: Change ORDER_NONE to the correct strength.
  2230. return [code, Blockly.Python.ORDER_CONDITIONAL];
  2231. };
  2232. Blockly.Blocks['esp32_main_controller_time_timer_clear'] = {
  2233. init: function () {
  2234. this.appendDummyInput().appendField(Blockly.Msg.time_timer_clear);
  2235. this.setPreviousStatement(true, null);
  2236. this.setNextStatement(true, null);
  2237. this.setColour(ESP32_TIME_COLOR);
  2238. var thisBlock = this;
  2239. this.setTooltip(function () {
  2240. var mode = thisBlock.getFieldValue('type');
  2241. var TOOLTIPS = {
  2242. 'on_esp32': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Clear_TOOLTIP.replace('%1', Blockly.Msg.time_iot_module),
  2243. 'on_ai': Blockly.Msg.Esp32_Main_Controller_Time_Timer_Clear_TOOLTIP.replace('%1', Blockly.Msg.time_ai_module)
  2244. };
  2245. return TOOLTIPS[mode];
  2246. });
  2247. this.setHelpUrl("");
  2248. }
  2249. };
  2250. Blockly.Python['esp32_main_controller_time_timer_clear'] = function (block) {
  2251. var timer_type = block.getFieldValue('type');
  2252. // TODO: Assemble Python into code variable.
  2253. var code = `del counter_start
  2254. `;
  2255. return code;
  2256. };
  2257. Blockly.Blocks['esp32_main_controller_time_period_timer'] = {
  2258. init: function () {
  2259. this.appendDummyInput()
  2260. .appendField(Blockly.Msg.time_timer_periodically);
  2261. this.appendDummyInput()
  2262. .appendField(Blockly.Msg.time_timer_every)
  2263. .appendField(new Blockly.FieldTextInput("500"), "period_timer_count")
  2264. .appendField(Blockly.Msg.time_timer_ms);
  2265. this.appendStatementInput("exec_period_timer")
  2266. .setCheck(null)
  2267. .appendField(Blockly.Msg.time_execution);
  2268. this.setPreviousStatement(true, null);
  2269. this.setNextStatement(true, null);
  2270. this.setColour(ESP32_TIME_COLOR);
  2271. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Time_Period_Timer_TOOLTIP.replace('%1', "CocoPi"));
  2272. this.setHelpUrl("");
  2273. }
  2274. };
  2275. Blockly.Python['esp32_main_controller_time_period_timer'] = function (block) {
  2276. var text_period_timer_count = block.getFieldValue('period_timer_count') * 0.001;
  2277. var statements_name = Blockly.Python.statementToCode(block, 'exec_period_timer');
  2278. Blockly.Python.addVariable("STOPTHREAD", "STOPTHREAD = False", true)
  2279. Blockly.Python.definitions_['v831_import_threading'] = `import threading`
  2280. Blockly.Python.definitions_['v831_import_time'] = `import time`
  2281. let allBlocks = block.workspace.getAllBlocks();
  2282. let global = ""
  2283. // console.log('allBlocks',allBlocks)
  2284. try {
  2285. global = allBlocks[0].workspace.variableList.toString()
  2286. }
  2287. catch (e) {
  2288. console.log(e)
  2289. }
  2290. Blockly.Python.definitions_['v831_import_thread_calsss'] = `def period_timer_count(n: int):
  2291. global STOPTHREAD
  2292. while True:
  2293. if STOPTHREAD:
  2294. break
  2295. time.sleep(${text_period_timer_count})
  2296. thread_calsss_fun_timer()
  2297. `
  2298. Blockly.Python.definitions_['v831_import_thread_calsss_fun'] = `def thread_calsss_fun_timer():
  2299. global ${global}
  2300. ${statements_name}
  2301. `
  2302. var code = `CocoPiThread = threading.Thread(target=period_timer_count, args=(1,))
  2303. CocoPiThread.start()
  2304. `
  2305. return code;
  2306. };
  2307. Blockly.Blocks['esp32_main_controller_time_period_timer_clear'] = {
  2308. init: function () {
  2309. this.appendDummyInput()
  2310. .appendField(Blockly.Msg.time_timer_periodically_clear);
  2311. this.setPreviousStatement(true, null);
  2312. this.setNextStatement(true, null);
  2313. this.setColour(ESP32_TIME_COLOR);
  2314. var thisBlock = this;
  2315. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Time_Period_Timer_Clear_TOOLTIP.replace('%1', "CocoPi"));
  2316. this.setHelpUrl("");
  2317. }
  2318. };
  2319. Blockly.Python['esp32_main_controller_time_period_timer_clear'] = function (block) {
  2320. var code = `STOPTHREAD = True
  2321. `
  2322. return code;
  2323. };
  2324. Blockly.Blocks['esp32_get_current_date'] = {
  2325. init: function () {
  2326. this.appendDummyInput()
  2327. .appendField(Blockly.Msg.time_get_current_date_title)
  2328. .appendField(new Blockly.FieldDropdown([
  2329. [Blockly.Msg.time_get_current_date_y, "Y"],
  2330. [Blockly.Msg.time_get_current_date_m, "m"],
  2331. [Blockly.Msg.time_get_current_date_d, "d"],
  2332. [Blockly.Msg.time_get_current_date_hour, "H"],
  2333. [Blockly.Msg.time_get_current_date_min, "M"],
  2334. [Blockly.Msg.time_get_current_date_sec, "S"]
  2335. ]), "type");
  2336. this.setInputsInline(false);
  2337. this.setOutput(true, null);
  2338. this.setColour(ESP32_TIME_COLOR);
  2339. this.setHelpUrl("");
  2340. var thisBlock = this;
  2341. this.setTooltip(function () {
  2342. var mode = thisBlock.getFieldValue('type');
  2343. var TOOLTIPS = {
  2344. '0': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_y),
  2345. '1': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_m),
  2346. '2': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_d),
  2347. '3': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_hour),
  2348. '4': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_min),
  2349. '5': Blockly.Msg.Esp32_Get_Current_Date_TOOLTIP.replace('%1', Blockly.Msg.time_get_current_date_sec)
  2350. };
  2351. return TOOLTIPS[mode];
  2352. });
  2353. }
  2354. };
  2355. Blockly.Python['esp32_get_current_date'] = function (block) {
  2356. var dropdown_type = block.getFieldValue('type');
  2357. // Blockly.Python.definitions_['v831_import_time'] = `from datetime import date`
  2358. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  2359. Blockly.Python.definitions_['v831_get_current_date'] = `def getCurrent_data(type):
  2360. now = datetime.now()
  2361. return now.strftime("%"+type+"")
  2362. `
  2363. // TODO: Assemble Python into code variable.
  2364. var code = `getCurrent_data("${dropdown_type}")`
  2365. // TODO: Change ORDER_NONE to the correct strength.
  2366. return [code, Blockly.Python.ORDER_NONE];
  2367. };
  2368. /*
  2369. LCD
  2370. */
  2371. var ESP32_SCREEN_COLOR = "#5bb2d6";
  2372. Blockly.Blocks['esp32_main_controller_lcd_rotation'] = {
  2373. init: function () {
  2374. this.appendDummyInput()
  2375. .appendField(Blockly.Msg.OLCD_SETROTATION)
  2376. .appendField(new Blockly.FieldDropdown([
  2377. ["0°", "1"],
  2378. ["90°", "2"],
  2379. ["180°", "3"],
  2380. ["270°", "0"]
  2381. ]), "DEGREE")
  2382. .appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE)
  2383. this.setPreviousStatement(true, null);
  2384. this.setNextStatement(true, null);
  2385. this.setColour("#5bb2d6");
  2386. this.setTooltip('');
  2387. this.setHelpUrl('');
  2388. }
  2389. }
  2390. Blockly.Python['esp32_main_controller_lcd_rotation'] = function (block) {
  2391. var degree = block.getFieldValue("DEGREE");
  2392. var code = "tft.rotation(" + degree + ")\n";
  2393. // Blockly.Python.addSetup("setRotation", code);
  2394. return code;
  2395. }
  2396. Blockly.Blocks['esp32_main_controller_clear_screen'] = {
  2397. init: function () {
  2398. this.appendDummyInput()
  2399. .appendField(Blockly.Msg.display_clear_screen);
  2400. this.setInputsInline(true);
  2401. this.setPreviousStatement(true, null);
  2402. this.setNextStatement(true, null);
  2403. this.setColour(ESP32_SCREEN_COLOR);
  2404. this.setTooltip("");
  2405. this.setHelpUrl("");
  2406. }
  2407. };
  2408. Blockly.Python['esp32_main_controller_clear_screen'] = function (block) {
  2409. // TODO: Assemble Python into code variable.
  2410. var code = 'tft.fill(TFT.BLACK)\n';
  2411. return code;
  2412. };
  2413. Blockly.Blocks['esp32_main_controller_lcd_screen_fill'] = {
  2414. init: function () {
  2415. this.appendDummyInput()
  2416. .appendField(Blockly.Msg.display_fill_screen);
  2417. this.appendValueInput("COLOR")
  2418. .setCheck(null)
  2419. this.setInputsInline(true);
  2420. this.setPreviousStatement(true, null);
  2421. this.setNextStatement(true, null);
  2422. this.setColour(ESP32_SCREEN_COLOR);
  2423. this.setTooltip("");
  2424. this.setHelpUrl("");
  2425. }
  2426. };
  2427. Blockly.Python['esp32_main_controller_lcd_screen_fill'] = function (block) {
  2428. var value_lcd_rgb_value = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2429. // TODO: Assemble Python into code variable.
  2430. if (value_lcd_rgb_value.charAt(0) != '#') {
  2431. var code = 'tft.fill(_TFTColor' + value_lcd_rgb_value + ')\n';
  2432. } else if (value_lcd_rgb_value.charAt(0) == '#') {
  2433. var d = 0,
  2434. e = 0,
  2435. f = 0;
  2436. try {
  2437. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  2438. e = parseInt(color.substring(3, 5), 16),
  2439. f = parseInt(color.substring(5, 7), 16))
  2440. } catch (g) { }
  2441. var code = "tft.fill(_TFTColor" + d + "," + e + "," + f + ")\n";
  2442. }
  2443. return code;
  2444. };
  2445. Blockly.Blocks['esp32_main_controller_lcd_drawpixel'] = {
  2446. init: function () {
  2447. this.appendDummyInput()
  2448. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_pixel.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2449. this.appendDummyInput()
  2450. .appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.display_draw_pixel);
  2451. this.appendValueInput("COLOR")
  2452. .setCheck("String")
  2453. .appendField(Blockly.Msg.OLCD_COLOR);
  2454. this.appendValueInput("POS")
  2455. .setCheck("String")
  2456. .appendField(Blockly.Msg.OLCD_COORDINATE);
  2457. this.setInputsInline(false);
  2458. this.setPreviousStatement(true);
  2459. this.setNextStatement(true);
  2460. this.setColour("#5bb2d6");
  2461. this.setTooltip('');
  2462. this.setHelpUrl('');
  2463. }
  2464. };
  2465. Blockly.Python['esp32_main_controller_lcd_drawpixel'] = function (block) {
  2466. // var drawrectcolor = sharpTo565(
  2467. // Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  2468. var drawrectcoord = Blockly.Python.valueToCode(block, 'POS', Blockly.Python.ORDER_ATOMIC);
  2469. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2470. if (color.charAt(0) == '#') {
  2471. var d = 0,
  2472. e = 0,
  2473. f = 0;
  2474. try {
  2475. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  2476. e = parseInt(color.substring(3, 5), 16),
  2477. f = parseInt(color.substring(5, 7), 16))
  2478. } catch (g) { }
  2479. code = "tft.pixel((" + drawrectcoord + "), _TFTColor" + d + "," + e + "," + f + ")\n"
  2480. } else if (color.charAt(0) != '#') {
  2481. code = "tft.pixel((" + drawrectcoord + "), _TFTColor" + color + ")\n"
  2482. }
  2483. return code;
  2484. };
  2485. Blockly.Blocks['esp32_main_controller_lcd_drawline'] = {
  2486. init: function () {
  2487. this.appendDummyInput()
  2488. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2489. // this.appendDummyInput()
  2490. // .appendField(
  2491. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  2492. this.appendDummyInput()
  2493. .appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.OLCD_LINE);
  2494. this.appendValueInput("COLOR")
  2495. .setCheck("String")
  2496. .appendField(Blockly.Msg.OLCD_COLOR);
  2497. this.appendValueInput("POSA")
  2498. .setCheck("String")
  2499. .appendField(Blockly.Msg.OLCD_LINE_START);
  2500. this.appendValueInput("POSB")
  2501. .setCheck("String")
  2502. .appendField(Blockly.Msg.OLCD_LINE_END);
  2503. this.setInputsInline(false);
  2504. this.setPreviousStatement(true);
  2505. this.setNextStatement(true);
  2506. this.setColour("#5bb2d6");
  2507. this.setTooltip('');
  2508. this.setHelpUrl('');
  2509. }
  2510. };
  2511. Blockly.Python['esp32_main_controller_lcd_drawline'] = function (block) {
  2512. // var drawlinecolor = sharpTo565(
  2513. // Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  2514. var drawlinestart = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  2515. var drawlineend = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  2516. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2517. if (color.charAt(0) == '#') {
  2518. var d = 0,
  2519. e = 0,
  2520. f = 0;
  2521. try {
  2522. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  2523. e = parseInt(color.substring(3, 5), 16),
  2524. f = parseInt(color.substring(5, 7), 16))
  2525. } catch (g) { }
  2526. code = "tft.line((" + drawlinestart + "), (" + drawlineend + "), _TFTColor" + d + "," + e + "," + f + ")\n"
  2527. } else if (color.charAt(0) != '#') {
  2528. code = "tft.line((" + drawlinestart + "), (" + drawlineend + "), _TFTColor" + color + ")\n"
  2529. }
  2530. return code;
  2531. };
  2532. Blockly.Blocks['esp32_main_controller_lcd_drawlinelen'] = {
  2533. init: function () {
  2534. this.appendDummyInput()
  2535. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2536. // this.appendDummyInput()
  2537. // .appendField(
  2538. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  2539. this.appendDummyInput()
  2540. .appendField(Blockly.Msg.OLCD_DRAW)
  2541. .appendField(new Blockly.FieldDropdown([
  2542. [Blockly.Msg.display_draw_vertical, "vline"],
  2543. [Blockly.Msg.display_draw_horizontal, "hline"]
  2544. ]), "rect_type")
  2545. .appendField(Blockly.Msg.OLCD_LINE)
  2546. this.appendValueInput("COLOR")
  2547. .setCheck(null)
  2548. .appendField(Blockly.Msg.OLCD_COLOR);
  2549. this.appendValueInput("POS")
  2550. .setCheck(null)
  2551. .appendField(Blockly.Msg.display_start_cord);
  2552. this.appendValueInput("LENGTH")
  2553. .setCheck(null)
  2554. .appendField(Blockly.Msg.display_length);
  2555. this.setInputsInline(false);
  2556. this.setPreviousStatement(true);
  2557. this.setNextStatement(true);
  2558. this.setColour("#5bb2d6");
  2559. this.setTooltip('');
  2560. this.setHelpUrl('');
  2561. }
  2562. };
  2563. Blockly.Python['esp32_main_controller_lcd_drawlinelen'] = function (block) {
  2564. var _type = block.getFieldValue("rect_type");
  2565. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2566. var drawlinestart = Blockly.Python.valueToCode(block, 'POS', Blockly.Python.ORDER_ATOMIC);
  2567. var drawlineend = Blockly.Python.valueToCode(block, 'LENGTH', Blockly.Python.ORDER_ATOMIC);
  2568. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2569. code = "tft." + _type + "((" + drawlinestart + "), " + drawlineend + ", _TFTColor" + color + ")\n"
  2570. return code;
  2571. };
  2572. Blockly.Blocks['esp32_main_controller_lcd_drawrect'] = {
  2573. init: function () {
  2574. this.appendDummyInput()
  2575. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2576. // this.appendDummyInput()
  2577. // .appendField(
  2578. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  2579. this.appendDummyInput()
  2580. .appendField(Blockly.Msg.OLCD_DRAW)
  2581. .appendField(new Blockly.FieldDropdown([
  2582. [Blockly.Msg.OLCD_FULL, "fillrect"],
  2583. [Blockly.Msg.OLCD_CIRCLE, "rect"]
  2584. ]), "rect_type")
  2585. .appendField(Blockly.Msg.display_draw_rectangle);
  2586. this.appendValueInput("COLOR")
  2587. .setCheck("String")
  2588. .appendField(Blockly.Msg.OLCD_COLOR);
  2589. this.appendValueInput("POSA")
  2590. .setCheck("String")
  2591. .appendField(Blockly.Msg.OLCD_COORDINATE);
  2592. this.appendValueInput("POSB")
  2593. .setCheck("String")
  2594. .appendField(Blockly.Msg.OLCD_SIZE);
  2595. this.setInputsInline(false);
  2596. this.setPreviousStatement(true);
  2597. this.setNextStatement(true);
  2598. this.setColour("#5bb2d6");
  2599. this.setTooltip('');
  2600. this.setHelpUrl('');
  2601. }
  2602. };
  2603. Blockly.Python['esp32_main_controller_lcd_drawrect'] = function (block) {
  2604. // var drawlinecolor = sharpTo565(
  2605. // Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  2606. var _type = block.getFieldValue("rect_type");
  2607. var drawlinestart = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  2608. var drawlineend = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  2609. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2610. code = "tft." + _type + "((" + drawlinestart + "), (" + drawlineend + "), _TFTColor" + color + ")\n"
  2611. return code;
  2612. };
  2613. Blockly.Blocks['esp32_main_controller_lcd_drawcircle'] = {
  2614. init: function () {
  2615. this.appendDummyInput()
  2616. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2617. this.appendDummyInput()
  2618. .appendField(Blockly.Msg.OLCD_DRAW)
  2619. .appendField(new Blockly.FieldDropdown([
  2620. [Blockly.Msg.OLCD_FULL, "fillcircle"],
  2621. [Blockly.Msg.OLCD_STROKED, "circle"]
  2622. ]), "circle_type")
  2623. .appendField(Blockly.Msg.OLCD_CIRCLE);
  2624. this.appendValueInput("COLOR")
  2625. .setCheck("String")
  2626. .appendField(Blockly.Msg.OLCD_COLOR);
  2627. this.appendValueInput("POSA")
  2628. .setCheck("String")
  2629. .appendField(Blockly.Msg.OLCD_CENTER_POS);
  2630. this.appendValueInput("RADIUS")
  2631. .setCheck(null)
  2632. .appendField(Blockly.Msg.OLCD_RADIUS);
  2633. this.setInputsInline(false);
  2634. this.setPreviousStatement(true);
  2635. this.setNextStatement(true);
  2636. this.setColour("#5bb2d6");
  2637. this.setTooltip('');
  2638. this.setHelpUrl('');
  2639. }
  2640. };
  2641. Blockly.Python['esp32_main_controller_lcd_drawcircle'] = function (block) {
  2642. // var drawcirclecolor = sharpTo565(
  2643. // Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  2644. var circletype = block.getFieldValue('circle_type');
  2645. var position = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  2646. var radius = Blockly.Python.valueToCode(block, 'RADIUS', Blockly.Python.ORDER_ATOMIC);
  2647. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2648. code = 'tft.' + circletype + '((' + position + '), ' + radius + ', _TFTColor' + color + ')\n';
  2649. return code;
  2650. };
  2651. Blockly.Blocks['esp32_main_controller_lcd_drawqrcode'] = {
  2652. init: function () {
  2653. this.appendDummyInput()
  2654. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_qr.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2655. // this.appendDummyInput()
  2656. // .appendField(
  2657. // new Blockly.FieldImage("./../blockly/media/circle.png", 25, 25, "15"));
  2658. this.appendDummyInput()
  2659. .appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.display_drawqr_text);
  2660. this.appendValueInput("POSA")
  2661. .setCheck("String")
  2662. .appendField(Blockly.Msg.OLCD_SET_POS);
  2663. this.appendValueInput("CONTENT")
  2664. .setCheck("String")
  2665. .appendField(Blockly.Msg.display_drawqr_content);
  2666. this.appendValueInput("WIDTH")
  2667. .setCheck("Number")
  2668. .appendField(Blockly.Msg.display_drawqr_padding);
  2669. this.setInputsInline(false);
  2670. this.setPreviousStatement(true);
  2671. this.setNextStatement(true);
  2672. this.setColour("#5bb2d6");
  2673. this.setTooltip('');
  2674. this.setHelpUrl('');
  2675. }
  2676. };
  2677. Blockly.Python['esp32_main_controller_lcd_drawqrcode'] = function (block) {
  2678. var position = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  2679. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  2680. var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC);
  2681. var code = 'tft.drawqrcode(' + '(' + position + '), ' + content + ', ' + width + ')\n';
  2682. return code;
  2683. };
  2684. Blockly.Blocks['esp32_main_controller_lcd_drawtext'] = {
  2685. init: function () {
  2686. this.appendDummyInput()
  2687. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 42, 42, { alt: "*", flipRtl: "FALSE" }));
  2688. // this.appendDummyInput()
  2689. // .appendField(
  2690. // new Blockly.FieldImage("./../blockly/media/circle.png", 25, 25, "15"));
  2691. this.appendDummyInput()
  2692. .appendField(Blockly.Msg.OLCD_DRAW + Blockly.Msg.display_draw_text);
  2693. this.appendValueInput("COLOR")
  2694. .setCheck("String")
  2695. .appendField(Blockly.Msg.OLCD_COLOR);
  2696. this.appendValueInput("POSA")
  2697. .setCheck("String")
  2698. .appendField(Blockly.Msg.display_start_cord);
  2699. this.appendValueInput("CONTENT")
  2700. .setCheck("String")
  2701. .appendField(Blockly.Msg.display_draw_text_content);
  2702. this.appendValueInput("SIZE")
  2703. .setCheck("Number")
  2704. .appendField(Blockly.Msg.display_draw_text_size);
  2705. this.appendDummyInput()
  2706. .appendField(Blockly.Msg.display_draw_text_return)
  2707. .appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox');
  2708. this.setInputsInline(false);
  2709. this.setPreviousStatement(true);
  2710. this.setNextStatement(true);
  2711. this.setColour("#5bb2d6");
  2712. this.setTooltip('');
  2713. this.setHelpUrl('');
  2714. }
  2715. };
  2716. Blockly.Python['esp32_main_controller_lcd_drawtext'] = function (block) {
  2717. // var drawcirclecolor = sharpTo565(
  2718. // Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC));
  2719. var position = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  2720. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  2721. var size = Blockly.Python.valueToCode(block, 'SIZE', Blockly.Python.ORDER_ATOMIC);
  2722. var box = block.getFieldValue('TextCheckBox') == "TRUE" ? "True" : "False";
  2723. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  2724. code = 'tft.text((' + position + '), ' + content + ', _TFTColor' + color + ', sysfont, ' + size + ', nowrap=' + box + ')\n';
  2725. return code;
  2726. };
  2727. Blockly.Blocks['esp32_main_controller_rgb_value'] = {
  2728. init: function () {
  2729. this.appendValueInput("rgb_value_r")
  2730. .setCheck(null)
  2731. .appendField(Blockly.Msg.display_red);
  2732. this.appendValueInput("rgb_value_g")
  2733. .setCheck(null)
  2734. .appendField(Blockly.Msg.display_green);
  2735. this.appendValueInput("rgb_value_b")
  2736. .setCheck(null)
  2737. .appendField(Blockly.Msg.display_blue);
  2738. this.setInputsInline(true);
  2739. this.setOutput(true, null);
  2740. this.setColour(ESP32_SCREEN_COLOR);
  2741. this.setTooltip("");
  2742. this.setHelpUrl("");
  2743. }
  2744. };
  2745. Blockly.Python['esp32_main_controller_rgb_value'] = function (block) {
  2746. var r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
  2747. var g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
  2748. var b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
  2749. var original_r = parseInt(r, 10);
  2750. var original_g = parseInt(g, 10);
  2751. var original_b = parseInt(b, 10);
  2752. _r = original_r.toString(16);
  2753. _g = original_g.toString(16);
  2754. _b = original_b.toString(16);
  2755. if (_r.length == 1)
  2756. _r = "0" + _r;
  2757. if (_g.length == 1)
  2758. _g = "0" + _g;
  2759. if (_b.length == 1)
  2760. _b = "0" + _b;
  2761. // TODO: Assemble Python into code variable.
  2762. var code = '' + r + ',' + g + ',' + b + '';
  2763. // TODO: Change ORDER_NONE to the correct strength.
  2764. return [code, Blockly.Python.ORDER_NONE];
  2765. };
  2766. Blockly.Blocks['esp32_main_controller_lcd_color_hex_to_rgb'] = {
  2767. init: function () {
  2768. this.appendDummyInput()
  2769. .appendField(Blockly.Msg.COLOR)
  2770. .appendField(new Blockly.FieldColour("#ff0000"), "COLOR");
  2771. this.setOutput(true, null);
  2772. this.setColour("#5bb2d6");
  2773. this.setTooltip('');
  2774. this.setHelpUrl('');
  2775. }
  2776. };
  2777. Blockly.Python['esp32_main_controller_lcd_color_hex_to_rgb'] = function (a) {
  2778. a = a.getFieldValue("COLOR");
  2779. // var d = 0
  2780. // , e = 0
  2781. // , f = 0;
  2782. // try {
  2783. // 7 == a.length && (d = a.substring(1, 3),
  2784. // e = a.substring(3, 5),
  2785. // f = a.substring(5, 7));
  2786. // }
  2787. // catch (g) { }
  2788. var gethex = a;
  2789. function hexToRGB(h) {
  2790. let r = 0,
  2791. g = 0,
  2792. b = 0;
  2793. // 3 digits
  2794. if (h.length == 4) {
  2795. r = "0x" + h[1] + h[1];
  2796. g = "0x" + h[2] + h[2];
  2797. b = "0x" + h[3] + h[3];
  2798. // 6 digits
  2799. } else if (h.length == 7) {
  2800. r = "0x" + h[1] + h[2];
  2801. g = "0x" + h[3] + h[4];
  2802. b = "0x" + h[5] + h[6];
  2803. }
  2804. return "" + +r + "," + +g + "," + +b + "";
  2805. }
  2806. var _code = hexToRGB(gethex);
  2807. //_code += "tft.fill(TFT.TFTColor(FS_COLOR))\n";
  2808. return [_code, Blockly.Python.ORDER_CONDITIONAL];
  2809. };
  2810. /*
  2811. WiFi
  2812. */
  2813. var ESP32_WIFI_COLOR = "#3062c1";
  2814. Blockly.Blocks['esp32_main_controller_wifi_enable_hotspot_mode'] = {
  2815. init: function () {
  2816. this.appendDummyInput()
  2817. .appendField(new Blockly.FieldImage("blockly/media/hotspot_setup.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  2818. this.appendDummyInput()
  2819. .appendField(Blockly.Msg.wifi_setup_hotspot);
  2820. this.appendValueInput("SSID")
  2821. .setCheck(null)
  2822. .appendField(Blockly.Msg.wifi_hotspot_ssid);
  2823. this.appendValueInput("PASSWORD")
  2824. .setCheck(null)
  2825. .appendField(Blockly.Msg.wifi_hotspot_pass);
  2826. this.setInputsInline(false);
  2827. this.setPreviousStatement(true, null);
  2828. this.setNextStatement(true, null);
  2829. this.setColour(ESP32_WIFI_COLOR);
  2830. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Enable_Hotspot_Mode_TOOLTIP);
  2831. this.setHelpUrl("");
  2832. }
  2833. };
  2834. Blockly.Python['esp32_main_controller_wifi_enable_hotspot_mode'] = function (block) {
  2835. var text_ssid = Blockly.Python.valueToCode(block, 'SSID', Blockly.Python.ORDER_ATOMIC);
  2836. var text_password = Blockly.Python.valueToCode(block, 'PASSWORD', Blockly.Python.ORDER_ATOMIC);
  2837. var _code = '' +
  2838. '_WIFI = network.WLAN(network.STA_IF)\n' +
  2839. '_WIFI.active(False)\n' +
  2840. '_WIFI = network.WLAN(network.AP_IF)\n' +
  2841. '_WIFI.active(True)\n';
  2842. Blockly.Python.definitions_['import_network'] = 'import network\n' +
  2843. _code +
  2844. '_WIFI.config(essid=' + text_ssid + ', password=' + text_password + ', authmode=2, channel=11, hidden=0)\n' +
  2845. '\n';
  2846. code = '';
  2847. return code;
  2848. };
  2849. Blockly.Blocks["V831_code_scanning_network"] = {
  2850. init:function(){
  2851. this.appendDummyInput()
  2852. .appendField(Blockly.Msg.V831_code_scanning_network);
  2853. this.setInputsInline(false);
  2854. this.setPreviousStatement(true, null);
  2855. this.setNextStatement(true, null);
  2856. this.setColour(ESP32_WIFI_COLOR);
  2857. this.setTooltip(Blockly.Msg.V831_code_scanning_network);
  2858. this.setHelpUrl("");
  2859. }
  2860. }
  2861. Blockly.Python["V831_code_scanning_network"] = function(block){
  2862. Blockly.Python.definitions_['wifi_is_content'] = `
  2863. def wifi_is_content():
  2864. global getDateNum
  2865. cmd = "ping -c 1 123.58.32.151"
  2866. res = os.popen(cmd).read()
  2867. data = False
  2868. if res.find("round-trip min/avg/max")>-1:
  2869. data = True
  2870. return data
  2871. `
  2872. Blockly.Python.definitions_['v831_wifi_getdate_noexit'] = `def getNetworkDate_noexit():
  2873. global getDateNum
  2874. try:
  2875. coon = http.client.HTTPConnection("www.baidu.com")
  2876. coon.request("GET","/")
  2877. r = coon.getresponse()
  2878. ts = r.getheader("date")
  2879. GMT_time = time.strptime(ts[5:25],"%d %b %Y %H:%M:%S")
  2880. BeiJing_time = time.localtime(time.mktime(GMT_time) + 8*60*60)
  2881. format_time = time.strftime("%Y-%m-%d %H:%M:%S",BeiJing_time)
  2882. command = "date -s "+"\\"{}\\"".format(format_time)
  2883. os.system(command)
  2884. getDateNum = 1
  2885. # sys.exit()
  2886. except:
  2887. pass
  2888. `
  2889. let language = localStorage.getItem('handPyLanguage')
  2890. let str = ""
  2891. if(language == "zh-hant"){
  2892. str = "請掃描平臺Wi-Fi二維碼聯網"
  2893. }else if(language =="en"){
  2894. str = "Please scan the platform Wi-Fi QR code for networking"
  2895. }else{
  2896. str = "请扫描平台Wi-Fi二维码联网"
  2897. }
  2898. Blockly.Python.addFunction("codeScanningNetwork",`def codeScanningNetwork():
  2899. if wifi_is_content():
  2900. stateNetwork = 1
  2901. else:
  2902. stateNetwork = 0
  2903. CODERESULT = ""
  2904. while True:
  2905. if stateNetwork == 0:
  2906. canvas = getLcdRotation(camera.capture())
  2907. qrCode = canvas.find_qrcodes()
  2908. canvas.draw_rectangle(0,0, 0+320,0+ 20, color=(0,0,0), thickness=-1)
  2909. canvas.draw_string(50,0, "${str}", scale = 1, color = (255,255,255) , thickness = 1)
  2910. for i in qrCode:
  2911. canvas.draw_string((i["x"]),(i["y"]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1)
  2912. canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1)
  2913. CODERESULT = (i["payload"]).split(";")
  2914. v831_display_show_canvas(canvas)
  2915. if CODERESULT != "":
  2916. WiFiSSID = CODERESULT[0][5 : ]
  2917. WiFiPSD = CODERESULT[1][5 : ]
  2918. os.system("wifi_disconnect_ap_test")
  2919. os.system("wifi_connect_chinese_ap_test "+WiFiSSID+" "+WiFiPSD+"")
  2920. getNetworkDate_noexit()
  2921. if wifi_is_content():
  2922. stateNetwork = 1
  2923. else:
  2924. stateNetwork = 0
  2925. CODERESULT = ""
  2926. elif stateNetwork == 1:
  2927. break
  2928. `
  2929. )
  2930. var code = "codeScanningNetwork()\n"
  2931. return code;
  2932. }
  2933. Blockly.Blocks['esp32_main_controller_wifi_connect_internet'] = {
  2934. init: function () {
  2935. this.appendDummyInput()
  2936. .appendField(new Blockly.FieldImage("blockly/media/wifi_setup.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  2937. this.appendDummyInput()
  2938. .appendField(Blockly.Msg.wifi_connect_router);
  2939. this.appendValueInput("ssid")
  2940. .setCheck(null)
  2941. .appendField(Blockly.Msg.wifi_router_ssid);
  2942. this.appendValueInput("password")
  2943. .setCheck(null)
  2944. .appendField(Blockly.Msg.wifi_router_pass);
  2945. this.setInputsInline(false);
  2946. this.setPreviousStatement(true, null);
  2947. this.setNextStatement(true, null);
  2948. this.setColour(ESP32_WIFI_COLOR);
  2949. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Connect_Internet_TOOLTIP);
  2950. this.setHelpUrl("");
  2951. }
  2952. };
  2953. Blockly.Python['esp32_main_controller_wifi_connect_internet'] = function (block) {
  2954. var text_ssid = Blockly.Python.valueToCode(block, 'ssid', Blockly.Python.ORDER_ATOMIC);
  2955. var text_password = Blockly.Python.valueToCode(block, 'password', Blockly.Python.ORDER_ATOMIC);
  2956. Blockly.Python.definitions_['v831_import_os'] = `import os`
  2957. // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime`
  2958. // Blockly.Python.definitions_['v831_import_ntplib'] = `import ntplib`
  2959. Blockly.Python.definitions_['v831_wifi_getdate_noexit'] = `def getNetworkDate_noexit():
  2960. global getDateNum
  2961. try:
  2962. coon = http.client.HTTPConnection("www.baidu.com")
  2963. coon.request("GET","/")
  2964. r = coon.getresponse()
  2965. ts = r.getheader("date")
  2966. GMT_time = time.strptime(ts[5:25],"%d %b %Y %H:%M:%S")
  2967. BeiJing_time = time.localtime(time.mktime(GMT_time) + 8*60*60)
  2968. format_time = time.strftime("%Y-%m-%d %H:%M:%S",BeiJing_time)
  2969. command = "date -s "+"\\"{}\\"".format(format_time)
  2970. os.system(command)
  2971. getDateNum = 1
  2972. # sys.exit()
  2973. except:
  2974. pass
  2975. `
  2976. var code = `
  2977. WiFiSSID = ${text_ssid}
  2978. WiFiPSD = ${text_password}
  2979. os.system("wifi_disconnect_ap_test")
  2980. os.system("wifi_connect_chinese_ap_test "+WiFiSSID+" "+WiFiPSD+"")
  2981. getNetworkDate_noexit()
  2982. `;
  2983. return code;
  2984. };
  2985. Blockly.Blocks['esp32_main_controller_wifi_disconnect'] = {
  2986. init: function () {
  2987. this.appendDummyInput()
  2988. .appendField(Blockly.Msg.wifi_router_disconnect);
  2989. this.setInputsInline(false);
  2990. this.setPreviousStatement(true, null);
  2991. this.setNextStatement(true, null);
  2992. this.setColour(ESP32_WIFI_COLOR);
  2993. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Disconnect_TOOLTIP);
  2994. this.setHelpUrl("");
  2995. }
  2996. };
  2997. Blockly.Python['esp32_main_controller_wifi_disconnect'] = function (block) {
  2998. // TODO: Assemble Python into code variable.
  2999. Blockly.Python.definitions_['v831_import_os'] = 'import os\n'
  3000. var code = 'os.system("wifi_disconnect_ap_test")';
  3001. return code;
  3002. };
  3003. Blockly.Blocks['esp32_main_controller_get_wifi_devices_number'] = {
  3004. init: function () {
  3005. this.appendDummyInput()
  3006. .appendField(Blockly.Msg.wifi_hotspot_get_clients);
  3007. this.setOutput(true, null);
  3008. this.setColour(ESP32_WIFI_COLOR);
  3009. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Get_Wifi_Devices_Number_TOOLTIP);
  3010. this.setHelpUrl("");
  3011. }
  3012. };
  3013. Blockly.Python['esp32_main_controller_get_wifi_devices_number'] = function (block) {
  3014. // TODO: Assemble Python into code variable.
  3015. var code = 'len(_WIFI.status("stations"))';
  3016. // TODO: Change ORDER_NONE to the correct strength.
  3017. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3018. };
  3019. Blockly.Blocks['esp32_main_controller_wifi_acquiring_equipment'] = {
  3020. init: function () {
  3021. this.appendDummyInput()
  3022. .appendField(Blockly.Msg.wifi_hotspot_get_list);
  3023. this.setOutput(true, null);
  3024. this.setColour(ESP32_WIFI_COLOR);
  3025. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Acquiring_Equipment_TOOLTIP);
  3026. this.setHelpUrl("");
  3027. }
  3028. };
  3029. Blockly.Python['esp32_main_controller_wifi_acquiring_equipment'] = function (block) {
  3030. // TODO: Assemble Python into code variable.
  3031. var code = '_WIFI.status("stations")';
  3032. // TODO: Change ORDER_NONE to the correct strength.
  3033. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3034. };
  3035. Blockly.Blocks['esp32_main_controller_get_wifi_connection_status'] = {
  3036. init: function () {
  3037. this.appendDummyInput()
  3038. .appendField(Blockly.Msg.wifi_router_connection_status);
  3039. this.setOutput(true, null);
  3040. this.setColour(ESP32_WIFI_COLOR);
  3041. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Get_Wifi_Connection_Status_TOOLTIP);
  3042. this.setHelpUrl("");
  3043. }
  3044. };
  3045. Blockly.Python['esp32_main_controller_get_wifi_connection_status'] = function (block) {
  3046. // TODO: Assemble Python into code variable.
  3047. Blockly.Python.definitions_['v831_import_os'] = `import os`;
  3048. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  3049. sys.path.append("/root/")`
  3050. Blockly.Python.definitions_['v831_import_time'] = `import time`;
  3051. Blockly.Python.definitions_['v831_import_http_client'] = `import http.client`;
  3052. Blockly.Python.definitions_['wifi_is_content'] = `
  3053. def wifi_is_content():
  3054. global getDateNum
  3055. cmd = "ping -c 1 123.58.32.151"
  3056. res = os.popen(cmd).read()
  3057. data = False
  3058. if res.find("round-trip min/avg/max")>-1:
  3059. data = True
  3060. return data
  3061. `
  3062. // TODO: Change ORDER_NONE to the correct strength.
  3063. let code = `wifi_is_content()`
  3064. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3065. };
  3066. Blockly.Blocks['esp32_main_controller_wifi_close'] = {
  3067. init: function () {
  3068. this.appendDummyInput()
  3069. .appendField(Blockly.Msg.wifi_close_hotspot);
  3070. this.setPreviousStatement(true, null);
  3071. this.setNextStatement(true, null);
  3072. this.setColour(ESP32_WIFI_COLOR);
  3073. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Close_TOOLTIP);
  3074. this.setHelpUrl("");
  3075. }
  3076. };
  3077. Blockly.Python['esp32_main_controller_wifi_close'] = function (block) {
  3078. // TODO: Assemble Python into code variable.
  3079. var code = '_WIFI.active(False)';
  3080. // TODO: Change ORDER_NONE to the correct strength.
  3081. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3082. };
  3083. Blockly.Blocks['esp32_main_controller_wifi_get_info'] = {
  3084. init: function () {
  3085. this.appendDummyInput()
  3086. .appendField(Blockly.Msg.wifi_router_get_info)
  3087. .appendField(new Blockly.FieldDropdown([
  3088. [Blockly.Msg.wifi_router_device_ip, "0"],
  3089. // [Blockly.Msg.wifi_router_device_mask, "1"],
  3090. // [Blockly.Msg.wifi_router_device_gateway, "2"],
  3091. // [Blockly.Msg.wifi_router_device_dns, "3"]
  3092. ]), "wifi_info");
  3093. this.setOutput(true, null);
  3094. this.setColour(ESP32_WIFI_COLOR);
  3095. var thisBlock = this;
  3096. this.setTooltip(function () {
  3097. var mode = thisBlock.getFieldValue('wifi_info');
  3098. var TOOLTIPS = {
  3099. '0': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_ip),
  3100. '1': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_mask),
  3101. '2': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_gateway),
  3102. '3': Blockly.Msg.Esp32_Main_Controller_Wifi_Get_Info_TOOLTIP.replace('%1', Blockly.Msg.wifi_router_device_dns)
  3103. };
  3104. return TOOLTIPS[mode];
  3105. });
  3106. this.setHelpUrl("");
  3107. }
  3108. };
  3109. Blockly.Python['esp32_main_controller_wifi_get_info'] = function (block) {
  3110. Blockly.Python.definitions_["v831_import_socket"] = `import socket`
  3111. var dropdown_name = block.getFieldValue('wifi_info');
  3112. Blockly.Python.addFunction("getWifiIP", `def getWifiIP():
  3113. st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  3114. try:
  3115. #st.connect(('10.255.255.255', 1))
  3116. st.connect(('8.8.8.8', 80))
  3117. IP = st.getsockname()[0]
  3118. except Exception:
  3119. IP = '127.0.0.1'
  3120. finally:
  3121. st.close()
  3122. return IP`, true)
  3123. // TODO: Assemble Python into code variable.
  3124. var code = 'getWifiIP()';
  3125. // TODO: Change ORDER_NONE to the correct strength.
  3126. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3127. };
  3128. Blockly.Blocks['esp32_main_controller_wifi_ntptime'] = {
  3129. init: function () {
  3130. this.appendDummyInput()
  3131. .appendField(new Blockly.FieldImage("blockly/media/ntptime_header.png", 38, 38, { alt: "*", flipRtl: "FALSE" }));
  3132. this.appendDummyInput()
  3133. .appendField(Blockly.Msg.wifi_ntptime_title);
  3134. this.setInputsInline(false);
  3135. this.setPreviousStatement(true, null);
  3136. this.setNextStatement(true, null);
  3137. this.setColour(ESP32_WIFI_COLOR);
  3138. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Wifi_Ntptime_TOOLTIP);
  3139. this.setHelpUrl("");
  3140. }
  3141. };
  3142. Blockly.Python['esp32_main_controller_wifi_ntptime'] = function (block) {
  3143. // var dropdown_timezone = block.getFieldValue('timezone');
  3144. // var text_website = block.getFieldValue('website');
  3145. Blockly.Python.definitions_['v831_import_os'] = `import os`;
  3146. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  3147. sys.path.append("/root/")`
  3148. Blockly.Python.definitions_['v831_import_time'] = `import time`;
  3149. Blockly.Python.definitions_['v831_import_http_client'] = `import http.client`;
  3150. Blockly.Python.definitions_['v831_wifi_getdate'] = `def getNetworkDate():
  3151. try:
  3152. coon = http.client.HTTPConnection("www.baidu.com")
  3153. coon.request("GET","/")
  3154. r = coon.getresponse()
  3155. ts = r.getheader("date")
  3156. GMT_time = time.strptime(ts[5:25],"%d %b %Y %H:%M:%S")
  3157. BeiJing_time = time.localtime(time.mktime(GMT_time)+ 8*60*60)
  3158. format_time = time.strftime("%Y-%m-%d %H:%M:%S",BeiJing_time)
  3159. command = "date -s "+"\\"{}\\"".format(format_time)
  3160. os.system(command)
  3161. sys.exit()
  3162. except:
  3163. pass
  3164. `
  3165. // TODO: Assemble Python into code variable.
  3166. var code = 'getNetworkDate()\n';
  3167. return code;
  3168. };
  3169. // web
  3170. // 获取天气
  3171. Blockly.Blocks['v831_get_weather_init'] = {
  3172. init: function () {
  3173. this.appendDummyInput()
  3174. .appendField(Blockly.Msg.v831_get_weather_init)
  3175. this.setInputsInline(false);
  3176. this.setPreviousStatement(true, null);
  3177. this.setNextStatement(true, null);
  3178. this.setColour(ESP32_WIFI_COLOR);
  3179. this.setTooltip(Blockly.Msg.v831_get_weather_init);
  3180. this.setHelpUrl("");
  3181. }
  3182. };
  3183. Blockly.Python['v831_get_weather_init'] = function (block) {
  3184. // var dropdown_timezone = block.getFieldValue('timezone');
  3185. // var text_website = block.getFieldValue('website');
  3186. Blockly.Python.definitions_['v831_import_request'] = `import requests`;
  3187. // TODO: Assemble Python into code variable.
  3188. var code = '';
  3189. return code;
  3190. };
  3191. Blockly.Blocks['v831_set_city_and_time'] = {
  3192. init: function () {
  3193. this.appendDummyInput()
  3194. .appendField(Blockly.Msg.set_weather_city)
  3195. .appendField(new Blockly.FieldDropdown([
  3196. [Blockly.Msg.beijing, "101010100"],
  3197. [Blockly.Msg.shanghai, "101020100"],
  3198. [Blockly.Msg.guangzhou, "101280101"],
  3199. [Blockly.Msg.shenzhen, "101280601"],
  3200. [Blockly.Msg.HongKong, "101320101"],
  3201. ]), "get_city")
  3202. this.setOutput(true, null);
  3203. this.setColour(ESP32_WIFI_COLOR);
  3204. this.setTooltip(Blockly.Msg.set_weather_city_title);
  3205. this.setHelpUrl("");
  3206. }
  3207. };
  3208. Blockly.Python['v831_set_city_and_time'] = function (block) {
  3209. var city = block.getFieldValue('get_city');
  3210. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  3211. Blockly.Python.definitions_['v831_import_bs4'] = `import bs4`;
  3212. // TODO: Assemble Python into code variable.
  3213. Blockly.Python.definitions_['v831_get_weather_fuc'] = `def get_html(url):
  3214. headers = {
  3215. "User-Agent":
  3216. "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
  3217. "ContentType":
  3218. "text/html; charset=utf-8",
  3219. "Accept-Encoding":
  3220. "gzip, deflate, sdch",
  3221. "Accept-Language":
  3222. "zh-CN,zh;q=0.8",
  3223. "Connection":
  3224. "keep-alive",
  3225. }
  3226. try:
  3227. htmlcontet = requests.get(url, headers=headers, timeout=30)
  3228. htmlcontet.raise_for_status()
  3229. htmlcontet.encoding = "utf-8"
  3230. return htmlcontet.text
  3231. except:
  3232. return " 请求失败 "
  3233. def get_content(url):
  3234. weather_list = []
  3235. html = get_html(url)
  3236. soup = bs4.BeautifulSoup(html, "lxml")
  3237. content_ul = soup.find("div", class_="t").find("ul", class_="clearfix").find_all("li")
  3238. for content in content_ul:
  3239. try:
  3240. weather = {}
  3241. weather["D"] = content.find("h1").text
  3242. weather["WEA"] = content.find("p", class_="wea").text
  3243. weather["T"] = content.find(
  3244. "p", class_="tem").span.text + content.find(
  3245. "p", class_="tem").em.text
  3246. weather_list.append(weather)
  3247. except:
  3248. print("查询不到")
  3249. print(weather_list)
  3250. return weather_list
  3251. `
  3252. var code = `get_content("http://www.weather.com.cn/weather1d/${city}.shtml")`;
  3253. // if(title_small === "all"){
  3254. // code = `getCityWeather_AllDay("${city}")['message']`
  3255. // }else{
  3256. // code = `getCityWeather_RealTime("${city}")['message']`
  3257. // }
  3258. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3259. };
  3260. Blockly.Blocks['v831_set_city_and_time_new'] = {
  3261. init: function () {
  3262. this.appendDummyInput()
  3263. .appendField(Blockly.Msg.set_weather_city)
  3264. .appendField(new Blockly.FieldDropdown([
  3265. [Blockly.Msg.beijing, "101010100"],
  3266. [Blockly.Msg.shanghai, "101020100"],
  3267. [Blockly.Msg.guangzhou, "101280101"],
  3268. [Blockly.Msg.shenzhen, "101280601"],
  3269. [Blockly.Msg.HongKong, "101320101"],
  3270. ]), "get_city")
  3271. // .appendField(Blockly.Msg.set_weather_title_small)
  3272. // .appendField(new Blockly.FieldDropdown([
  3273. // [Blockly.Msg.set_weather_All_day_long, 'all'],[Blockly.Msg.set_weather_real_time, "real"]
  3274. // ]), "title_small");
  3275. this.setPreviousStatement(true, null);
  3276. this.setNextStatement(true, null);
  3277. this.setColour(ESP32_WIFI_COLOR);
  3278. this.setTooltip(Blockly.Msg.set_weather_city_title);
  3279. this.setHelpUrl("");
  3280. }
  3281. };
  3282. Blockly.Python['v831_set_city_and_time_new'] = function (block) {
  3283. // var title_small = block.getFieldValue('title_small');
  3284. var city = block.getFieldValue('get_city');
  3285. Blockly.Python.addVariable("getWeatherResult", 'getWeatherResult = ""', true)
  3286. // TODO: Assemble Python into code variable.
  3287. Blockly.Python.definitions_[""] = `def hefengGetWeather(city,lang):
  3288. getWeatherUrl = f"https://devapi.qweather.com/v7/weather/now?location={city}&key=d8d1d01bac3246ee8c34640681c1c9b6&lang={lang}"
  3289. weatherResult = ""
  3290. try:
  3291. responseResult = requests.get(getWeatherUrl)
  3292. if responseResult.status_code == 200:
  3293. weatherResult = responseResult.json()
  3294. except:
  3295. pass
  3296. return weatherResult
  3297. `
  3298. var code = `getWeatherResult = hefengGetWeather(${city},"${localStorage.getItem("handPyLanguage")}")
  3299. `;
  3300. // if(title_small === "all"){
  3301. // code = `getCityWeather_AllDay("${city}")['message']`
  3302. // }else{
  3303. // code = `getCityWeather_RealTime("${city}")['message']`
  3304. // }
  3305. return code;
  3306. };
  3307. Blockly.Blocks['v831_get_weather_result'] = {
  3308. init: function () {
  3309. this.appendDummyInput()
  3310. .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_2)
  3311. .appendField(new Blockly.FieldDropdown([
  3312. [Blockly.Msg.weather_resulet, "result"],
  3313. [Blockly.Msg.image_process_temperature, "temp"],
  3314. [Blockly.Msg.weather_condition, "text"],
  3315. [Blockly.Msg.windDir, "windDir"],
  3316. [Blockly.Msg.windScale, "windScale"],
  3317. [Blockly.Msg.windSpeed, "windSpeed"],
  3318. [Blockly.Msg.image_process_humidity, "humidity"],
  3319. ]), "get_weather")
  3320. this.setOutput(true, null);
  3321. this.setColour(ESP32_WIFI_COLOR);
  3322. this.setTooltip(Blockly.Msg.set_weather_city_title);
  3323. this.setHelpUrl("");
  3324. }
  3325. };
  3326. Blockly.Python['v831_get_weather_result'] = function (block) {
  3327. var weather = block.getFieldValue('get_weather');
  3328. var code = "";
  3329. if (weather == "result") {
  3330. code = `getWeatherResult`
  3331. } else {
  3332. code = `getWeatherResult["now"]["${weather}"]`
  3333. }
  3334. // if(title_small === "all"){
  3335. // code = `getCityWeather_AllDay("${city}")['message']`
  3336. // }else{
  3337. // code = `getCityWeather_RealTime("${city}")['message']`
  3338. // }
  3339. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3340. };
  3341. /*
  3342. IoT Service
  3343. */
  3344. Blockly.Blocks['esp32_main_controller_ThingSpeak_send_data'] = {
  3345. init: function () {
  3346. this.appendDummyInput()
  3347. .appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 190, 50, { alt: "*", flipRtl: "FALSE" }));
  3348. this.appendDummyInput()
  3349. .appendField(Blockly.Msg.iotservice_thingspeak_send_title);
  3350. this.appendDummyInput()
  3351. .appendField(Blockly.Msg.iotservice_thingspeak_send_api_set)
  3352. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_API_KEY"), "key");
  3353. this.appendValueInput("data")
  3354. .setCheck(null)
  3355. .appendField(Blockly.Msg.iotservice_thingspeak_send_data_1);
  3356. this.setPreviousStatement(true, null);
  3357. this.setNextStatement(true, null);
  3358. this.setColour(ESP32_IOT_COLOR);
  3359. this.setTooltip("");
  3360. this.setHelpUrl("");
  3361. }
  3362. };
  3363. Blockly.Python['esp32_main_controller_ThingSpeak_send_data'] = function (block) {
  3364. var text_key = block.getFieldValue('key');
  3365. var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  3366. Blockly.Python.definitions_['import_urequests'] = '' +
  3367. 'import requests\n' +
  3368. 'import json\n'
  3369. '';
  3370. var code = '_THINGSPEAK_CHANNEL_API = "' + text_key + '"\n'
  3371. Blockly.Python.addSetup("esp32_main_controller_ThingSpeak_send_data", code);
  3372. var code = '_THINGSPEAK_DATA1 = ' + data + '\n';
  3373. code += '_THINGSPEAK_ENDPOINT = "http://api.thingspeak.com/update?api_key=" + _THINGSPEAK_CHANNEL_API + "&field1=" + _THINGSPEAK_DATA1\n';
  3374. code += '_THINGSPEAK_REQEUST = requests.get(_THINGSPEAK_ENDPOINT)\n';
  3375. return code;
  3376. };
  3377. Blockly.Blocks['CocoRobo_set_max'] = {
  3378. init: function () {
  3379. this.appendDummyInput()
  3380. .appendField(new Blockly.FieldImage("blockly/media/http_server_header.png", 130, 50, { alt: "*", flipRtl: "FALSE" }));
  3381. this.appendDummyInput()
  3382. .appendField(Blockly.Msg.internet_server_setup);
  3383. this.appendDummyInput()
  3384. .appendField(Blockly.Msg.internet_server_set_max)
  3385. .appendField(new Blockly.FieldTextInput("5"), "number");
  3386. this.setPreviousStatement(true, null);
  3387. this.setNextStatement(true, null);
  3388. this.setColour("#183895");
  3389. this.setTooltip("");
  3390. this.setHelpUrl("");
  3391. }
  3392. };
  3393. Blockly.Python['CocoRobo_set_max'] = function (block) {
  3394. var number = block.getFieldValue('number');
  3395. Blockly.Python.definitions_['import_socket'] = 'import usocket as socket';
  3396. var code = '_S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n';
  3397. code += '_S.bind((_WIFI.ifconfig()[0], 80))\n';
  3398. code += '_S.listen(' + number + ')\n';
  3399. Blockly.Python.addSetup("CocoRobo_set_max", code);
  3400. var code = '_SERVER_CONN, _SERVER_ADDR = _S.accept()\n';
  3401. code += '_SERVER_REQUEST = _CONN.recv(1024)\n';
  3402. return code;
  3403. };
  3404. Blockly.Blocks['CocoRobo_get_source'] = {
  3405. init: function () {
  3406. this.appendDummyInput()
  3407. .appendField(Blockly.Msg.internet_server_set_source);
  3408. this.setOutput(true, null);
  3409. this.setColour("#183895");
  3410. this.setTooltip("");
  3411. this.setHelpUrl("");
  3412. }
  3413. };
  3414. Blockly.Python['CocoRobo_get_source'] = function (block) {
  3415. var code = 'str(_SERVER_ADDR)\n';
  3416. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3417. };
  3418. Blockly.Blocks['CocoRobo_get'] = {
  3419. init: function () {
  3420. this.appendDummyInput()
  3421. .appendField(Blockly.Msg.internet_response_http_content_title)
  3422. .appendField(new Blockly.FieldDropdown([
  3423. [Blockly.Msg.internet_response_text, "text"],
  3424. [Blockly.Msg.internet_response_content, "content"],
  3425. [Blockly.Msg.internet_response_status, "state"],
  3426. [Blockly.Msg.internet_response_json, "json"],
  3427. [Blockly.Msg.internet_response_encode, "code"],
  3428. [Blockly.Msg.internet_response_reason, "reason"]
  3429. ]), "op");
  3430. this.setOutput(true, null);
  3431. this.setColour("#183895");
  3432. // this.setTooltip(Blockly.Msg.CocoRobo_get_TOOLTIP);
  3433. this.setHelpUrl("");
  3434. var thisBlock = this;
  3435. this.setTooltip(function () {
  3436. var mode = thisBlock.getFieldValue('op');
  3437. var TOOLTIPS = {
  3438. 'text': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_text),
  3439. 'content': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_content),
  3440. 'state': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_status),
  3441. 'json': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_json),
  3442. 'code': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_encode),
  3443. 'reason': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_reason)
  3444. };
  3445. return TOOLTIPS[mode];
  3446. });
  3447. }
  3448. };
  3449. Blockly.Python['CocoRobo_get'] = function (block) {
  3450. var op = block.getFieldValue('op');
  3451. var code = '_SEND_HTTP_REQUEST.text';
  3452. if (op == "text") {
  3453. code = '_SEND_HTTP_REQUEST.text';
  3454. } else if (op == "content") {
  3455. code = '_SEND_HTTP_REQUEST.content';
  3456. } else if (op == "state") {
  3457. code = '_SEND_HTTP_REQUEST.status_code';
  3458. } else if (op == "json") {
  3459. code = '_SEND_HTTP_REQUEST.json()';
  3460. } else if (op == "code") {
  3461. code = '_SEND_HTTP_REQUEST.encoding';
  3462. } else if (op == "reason") {
  3463. code = '_SEND_HTTP_REQUEST.reason';
  3464. }
  3465. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3466. };
  3467. Blockly.Blocks['iot_system_run'] = {
  3468. init: function () {
  3469. this.appendDummyInput()
  3470. .appendField(Blockly.Msg.SYSTEM_RUN);
  3471. this.appendValueInput("PATH")
  3472. .setCheck(null)
  3473. .appendField(Blockly.Msg.system_code_path);
  3474. this.setInputsInline(false);
  3475. this.setPreviousStatement(true, null);
  3476. this.setNextStatement(true, null);
  3477. this.setColour(32);
  3478. this.setTooltip(Blockly.Msg.Iot_System_Run_TOOLTIP);
  3479. this.setHelpUrl("");
  3480. }
  3481. };
  3482. Blockly.Python.iot_system_run = function (block) {
  3483. var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);
  3484. var _code = "exec(open(" + _path + ").read())\n";
  3485. return _code;
  3486. }
  3487. Blockly.Blocks['iot_system_create_file'] = {
  3488. init: function () {
  3489. this.appendDummyInput()
  3490. .appendField(Blockly.Msg.SYSTEM_CREATE_FILE);
  3491. this.appendValueInput("filename")
  3492. .setCheck(null)
  3493. .appendField(Blockly.Msg.SYSTEM_CREATE_F);
  3494. this.appendValueInput("PATH")
  3495. .setCheck(null)
  3496. .appendField(Blockly.Msg.SYSTEM_CREATE_F_1);
  3497. this.setInputsInline(false);
  3498. this.setPreviousStatement(true, null);
  3499. this.setNextStatement(true, null);
  3500. this.setColour(32);
  3501. this.setTooltip(Blockly.Msg.Iot_System_Create_File_TOOLTIP);
  3502. this.setHelpUrl("");
  3503. }
  3504. };
  3505. Blockly.Python.iot_system_create_file = function (block) {
  3506. var _filename = Blockly.Python.valueToCode(block, 'filename', Blockly.Python.ORDER_ATOMIC).replace("\"", "").replace("\"", "");
  3507. var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC).replace("\"", "").replace("\"", "");
  3508. var _code = `with open('${_path + _filename}', 'a') as f:
  3509. f.write()
  3510. `;
  3511. return _code;
  3512. }
  3513. Blockly.Blocks['iot_system_open_file'] = {
  3514. init: function () {
  3515. this.appendDummyInput()
  3516. .appendField(Blockly.Msg.SYSTEM_OPEN_FILE);
  3517. this.appendValueInput("filename")
  3518. .setCheck(null)
  3519. .appendField(Blockly.Msg.SYSTEM_WRITE_F);
  3520. this.appendValueInput("PATH")
  3521. .setCheck(null)
  3522. .appendField(Blockly.Msg.SYSTEM_CREATE_F_1);
  3523. this.setInputsInline(false);
  3524. this.setPreviousStatement(true, null);
  3525. this.setNextStatement(true, null);
  3526. this.setColour(32);
  3527. this.setHelpUrl("");
  3528. this.setTooltip(Blockly.Msg.Iot_System_Open_File_TOOLTIP);
  3529. }
  3530. };
  3531. Blockly.Python.iot_system_open_file = function (block) {
  3532. var _filename = Blockly.Python.valueToCode(block, 'filename', Blockly.Python.ORDER_ATOMIC).replace("\"", "").replace("\"", "");
  3533. var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC).replace("\"", "").replace("\"", "");
  3534. var _code = "f = open(\"" + _path + _filename + "\", 'a')\n";
  3535. return _code;
  3536. }
  3537. Blockly.Blocks['iot_system_write_file'] = {
  3538. init: function () {
  3539. this.appendDummyInput()
  3540. .appendField(Blockly.Msg.SYSTEM_WRITE_FILE);
  3541. this.appendValueInput("WPATH")
  3542. .setCheck(null)
  3543. .appendField(Blockly.Msg.SYSTEM_WRITE_W);
  3544. this.appendDummyInput()
  3545. .appendField(Blockly.Msg.SYSTEM_WRITE_S)
  3546. .appendField(new Blockly.FieldDropdown([
  3547. [Blockly.Msg.SYSTEM_WRITE_S_N, "newline"],
  3548. [Blockly.Msg.SYSTEM_WRITE_S_C, "comma"],
  3549. [Blockly.Msg.SYSTEM_WRITE_S_S, "space"],
  3550. [Blockly.Msg.SYSTEM_WRITE_S_SE, "semicolon"]
  3551. ]), "separator");
  3552. this.setInputsInline(false);
  3553. this.setPreviousStatement(true, null);
  3554. this.setNextStatement(true, null);
  3555. this.setColour(32);
  3556. this.setHelpUrl("");
  3557. var thisBlock = this;
  3558. this.setTooltip(function () {
  3559. var mode = thisBlock.getFieldValue('separator');
  3560. var TOOLTIPS = {
  3561. 'newline': Blockly.Msg.Iot_System_Write_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_N),
  3562. 'comma': Blockly.Msg.Iot_System_Write_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_C),
  3563. 'space': Blockly.Msg.Iot_System_Write_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_S),
  3564. 'semicolon': Blockly.Msg.Iot_System_Write_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_SE)
  3565. };
  3566. return TOOLTIPS[mode];
  3567. });
  3568. }
  3569. };
  3570. Blockly.Python.iot_system_write_file = function (block) {
  3571. var _wpath = Blockly.Python.valueToCode(block, 'WPATH', Blockly.Python.ORDER_ATOMIC);
  3572. var _separator = block.getFieldValue('separator');
  3573. var _code = ""
  3574. if (_separator == "newline") {
  3575. _code = "f.write(" + _wpath + " + '\\r\\n')\n";
  3576. } else if (_separator == "comma") {
  3577. _code = "f.write(" + _wpath + " + ',')\n";
  3578. } else if (_separator == "space") {
  3579. _code = "f.write(" + _wpath + " + ' ')\n";
  3580. } else if (_separator == "semicolon") {
  3581. _code = "f.write(" + _wpath + " + ';')\n";
  3582. }
  3583. return _code;
  3584. }
  3585. Blockly.Blocks['iot_system_close_file'] = {
  3586. init: function () {
  3587. this.appendDummyInput()
  3588. .appendField(Blockly.Msg.SYSTEM_CLOSE_FILE);
  3589. this.setInputsInline(false);
  3590. this.setPreviousStatement(true, null);
  3591. this.setNextStatement(true, null);
  3592. this.setColour(32);
  3593. this.setHelpUrl("");
  3594. this.setTooltip(Blockly.Msg.SYSTEM_CLOSE_FILE);
  3595. }
  3596. };
  3597. Blockly.Python.iot_system_close_file = function (block) {
  3598. var _code = "f.close()\n";
  3599. return _code;
  3600. }
  3601. Blockly.Blocks['iot_system_input_file'] = {
  3602. init: function () {
  3603. this.appendDummyInput()
  3604. .appendField(Blockly.Msg.SYSTEM_INPUT_FILE);
  3605. this.appendValueInput("filename")
  3606. .setCheck(null)
  3607. .appendField(Blockly.Msg.SYSTEM_WRITE_F);
  3608. this.appendValueInput("PATH")
  3609. .setCheck(null)
  3610. .appendField(Blockly.Msg.SYSTEM_CREATE_F_1);
  3611. this.appendDummyInput()
  3612. .appendField(Blockly.Msg.SYSTEM_WRITE_S)
  3613. .appendField(new Blockly.FieldDropdown([
  3614. [Blockly.Msg.SYSTEM_WRITE_S_N, "newline"],
  3615. [Blockly.Msg.SYSTEM_WRITE_S_C, "comma"],
  3616. [Blockly.Msg.SYSTEM_WRITE_S_S, "space"],
  3617. [Blockly.Msg.SYSTEM_WRITE_S_SE, "semicolon"]
  3618. ]), "separator");
  3619. this.setInputsInline(false);
  3620. this.setOutput(true, null);
  3621. // this.setPreviousStatement(true, null);
  3622. // this.setNextStatement(true, null);
  3623. this.setColour(32);
  3624. // this.setTooltip("");
  3625. this.setHelpUrl("");
  3626. var thisBlock = this;
  3627. this.setTooltip(function () {
  3628. var mode = thisBlock.getFieldValue('separator');
  3629. var TOOLTIPS = {
  3630. 'newline': Blockly.Msg.Iot_System_Input_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_N),
  3631. 'comma': Blockly.Msg.Iot_System_Input_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_C),
  3632. 'space': Blockly.Msg.Iot_System_Input_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_S),
  3633. 'semicolon': Blockly.Msg.Iot_System_Input_File_TOOLTIP.replace('%1', Blockly.Msg.SYSTEM_WRITE_S_SE)
  3634. };
  3635. return TOOLTIPS[mode];
  3636. });
  3637. }
  3638. };
  3639. Blockly.Python.iot_system_input_file = function (block) {
  3640. var _filename = Blockly.Python.valueToCode(block, 'filename', Blockly.Python.ORDER_ATOMIC).replace("\"", "").replace("\"", "");
  3641. var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC).replace("\"", "").replace("\"", "");
  3642. var _separator = block.getFieldValue('separator');
  3643. var _code = "def _GET_LIST_FROM_FILE(_path, _sep):\n"
  3644. _code += " f = open(_path, 'r')\n"
  3645. _code += " result = f.read().split(_sep)\n"
  3646. _code += " f.close()\n"
  3647. _code += " return result\n"
  3648. Blockly.Python.addFunction("_GET_LIST_FROM_FILE", _code);
  3649. _code = "_GET_LIST_FROM_FILE(\"" + _path + _filename + "\", '\\r\\n')";
  3650. if (_separator == "newline") {
  3651. _code = "_GET_LIST_FROM_FILE(\"" + _path + _filename + "\", '\\r\\n')";
  3652. } else if (_separator == "comma") {
  3653. _code = "_GET_LIST_FROM_FILE(\"" + _path + _filename + "\", ',')";
  3654. } else if (_separator == "space") {
  3655. _code = "_GET_LIST_FROM_FILE(\"" + _path + _filename + "\", ' ')";
  3656. } else if (_separator == "semicolon") {
  3657. _code = "_GET_LIST_FROM_FILE(\"" + _path + _filename + "\", ';')";
  3658. }
  3659. return [_code, Blockly.Python.ORDER_NONE];
  3660. }
  3661. Blockly.Blocks['iot_system_delete_file'] = {
  3662. init: function () {
  3663. this.appendDummyInput()
  3664. .appendField(Blockly.Msg.iot_system_delete);
  3665. this.appendValueInput("PATH")
  3666. .setCheck(null)
  3667. .appendField(Blockly.Msg.SYSTEM_CREATE_F_1);
  3668. this.setInputsInline(false);
  3669. this.setPreviousStatement(true, null);
  3670. this.setNextStatement(true, null);
  3671. this.setColour(32);
  3672. this.setTooltip(Blockly.Msg.iot_system_delete_file_TOOLTIP);
  3673. this.setHelpUrl("");
  3674. }
  3675. };
  3676. Blockly.Python.iot_system_delete_file = function (block) {
  3677. var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);
  3678. Blockly.Python.definitions_['v831_import_os'] = 'import os\n'
  3679. var _code = "os.remove(" + _path + ")\n";
  3680. return _code;
  3681. }
  3682. Blockly.Blocks['iot_system_restart'] = {
  3683. init: function () {
  3684. this.appendDummyInput()
  3685. .appendField(Blockly.Msg.SYSTEM);
  3686. this.setPreviousStatement(true);
  3687. this.setNextStatement(true);
  3688. this.setColour("#22398e");
  3689. this.setTooltip(Blockly.Msg.Iot_System_Restart_TOOLTIP);
  3690. this.setHelpUrl("");
  3691. }
  3692. };
  3693. Blockly.Python.iot_system_restart = function (block) {
  3694. Blockly.Python.definitions_.import_machine = "import machine";
  3695. var _code = "machine.reset()\n"
  3696. return _code;
  3697. }
  3698. Blockly.Blocks['iot_system_get'] = {
  3699. init: function () {
  3700. this.appendDummyInput()
  3701. .appendField(Blockly.Msg.system_get_size);
  3702. this.setOutput(true, null);
  3703. this.setColour("#22398e");
  3704. this.setTooltip(Blockly.Msg.Iot_System_Get_TOOLTIP);
  3705. this.setHelpUrl("");
  3706. }
  3707. };
  3708. Blockly.Python.iot_system_get = function (block) {
  3709. var code = "_MCU_FREESPACE"
  3710. return [code, Blockly.Python.ORDER_CONDITIONAL];
  3711. }
  3712. Blockly.Blocks['iot_system_mac'] = {
  3713. init: function () {
  3714. this.appendDummyInput()
  3715. .appendField(Blockly.Msg.system_get_mac);
  3716. this.setOutput(true, null);
  3717. this.setColour("#22398e");
  3718. this.setTooltip(Blockly.Msg.Iot_System_Mac_TOOLTIP);
  3719. this.setHelpUrl("");
  3720. }
  3721. };
  3722. Blockly.Python.iot_system_mac = function (block) {
  3723. Blockly.Python.definitions_.import_machine_ub = "import machine, ubinascii";
  3724. var _code = "ubinascii.hexlify(machine.unique_id()).decode().upper()"
  3725. return [_code, Blockly.Python.ORDER_CONDITIONAL];
  3726. }
  3727. Blockly.Blocks['iot_system_get_cocorobo_id'] = {
  3728. init: function () {
  3729. this.appendDummyInput()
  3730. .appendField(Blockly.Msg.system_get_cocorobo_cid);
  3731. this.setInputsInline(false);
  3732. this.setOutput(true, null);
  3733. this.setColour("#22398e");
  3734. this.setTooltip(Blockly.Msg.Iot_System_Get_Cocorobo_Id_TOOLTIP);
  3735. this.setHelpUrl("");
  3736. }
  3737. };
  3738. Blockly.Python['iot_system_get_cocorobo_id'] = function (block) {
  3739. Blockly.Python.definitions_['import_cocorobo_cid'] = 'from cocorobo import cid\n';
  3740. // TODO: Assemble Python into code variable.
  3741. var code = 'cid._GET_MACHINE_ID().strip(\'\\n\')';
  3742. // TODO: Change ORDER_NONE to the correct strength.
  3743. return [code, Blockly.Python.ORDER_NONE];
  3744. };
  3745. Blockly.Blocks['iot_system_get_cocorobo_firmware_version'] = {
  3746. init: function () {
  3747. this.appendDummyInput()
  3748. .appendField(Blockly.Msg.iot_system_get_cocorobo_firmware_version);
  3749. this.setInputsInline(false);
  3750. this.setOutput(true, null);
  3751. this.setColour("#22398e");
  3752. this.setTooltip(Blockly.Msg.iot_system_get_cocorobo_firmware_version_TOOLTIP);
  3753. this.setHelpUrl("");
  3754. }
  3755. };
  3756. Blockly.Python['iot_system_get_cocorobo_firmware_version'] = function (block) {
  3757. Blockly.Python.definitions_['import_cocorobo_cid'] = '' +
  3758. 'try:\n' +
  3759. ' from cocorobo import firmware_info\n' +
  3760. 'except BaseException as e:\n' +
  3761. ' print(str(e))\n' +
  3762. ' pass\n' +
  3763. '\n';
  3764. // TODO: Assemble Python into code variable.
  3765. var code = 'firmware_info.iot()';
  3766. // TODO: Change ORDER_NONE to the correct strength.
  3767. return [code, Blockly.Python.ORDER_NONE];
  3768. };
  3769. Blockly.Blocks['iot_system_delete'] = {
  3770. init: function () {
  3771. this.appendDummyInput()
  3772. .appendField(Blockly.Msg.iot_system_delete);
  3773. this.appendValueInput("PATH")
  3774. .setCheck(null)
  3775. .appendField(Blockly.Msg.SYSTEM_CREATE_F);
  3776. this.setInputsInline(false);
  3777. this.setPreviousStatement(true, null);
  3778. this.setNextStatement(true, null);
  3779. this.setColour("#22398e");
  3780. this.setTooltip(Blockly.Msg.iot_system_delete_TOOLTIP);
  3781. this.setHelpUrl("");
  3782. }
  3783. };
  3784. Blockly.Python.iot_system_delete = function (block) {
  3785. var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);
  3786. Blockly.Python.definitions_['v831_import_os'] = 'import os\n'
  3787. var _code = "os.remove(" + _path + ")\n";
  3788. return _code;
  3789. }
  3790. /*
  3791. _____ _____ __ _
  3792. \_ \___/__ \ / _\ ___ _ ____ _(_) ___ ___
  3793. / /\/ _ \ / /\/ \ \ / _ \ '__\ \ / / |/ __/ _ \
  3794. /\/ /_| (_) / / _\ \ __/ | \ V /| | (_| __/
  3795. \____/ \___/\/ \__/\___|_| \_/ |_|\___\___|
  3796. */
  3797. var ESP32_IOT_COLOR = "#3c7683";
  3798. var IFTTT_BLOCK_COLOR = "#ff3b00";
  3799. var ONENET_BLOCK_COLOR = "#00b5ff";
  3800. Blockly.Blocks['esp32_main_controller_onenet_setup'] = {
  3801. init: function () {
  3802. this.appendDummyInput()
  3803. .appendField(new Blockly.FieldImage("blockly/media/onenet_setup_logo.png", 130, 70, { alt: "*", flipRtl: "FALSE" }));
  3804. this.appendDummyInput()
  3805. .appendField(Blockly.Msg.iotservice_onenet_mqtt_setup);
  3806. this.appendDummyInput()
  3807. .appendField(Blockly.Msg.iotservice_onenet_mqtt_server)
  3808. .appendField(new Blockly.FieldTextInput("183.230.40.39"), "server_ip");
  3809. this.appendDummyInput()
  3810. .appendField(Blockly.Msg.iotservice_onenet_mqtt_productid)
  3811. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_PRODUCT_ID"), "product_id");
  3812. this.appendDummyInput()
  3813. .appendField(Blockly.Msg.iotservice_onenet_mqtt_productkey)
  3814. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_PRODUCT_KEY"), "product_api_key");
  3815. this.appendDummyInput()
  3816. .appendField(Blockly.Msg.iotservice_onenet_mqtt_deviceid)
  3817. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_DEVICE_ID"), "device_id");
  3818. this.setPreviousStatement(true, null);
  3819. this.setNextStatement(true, null);
  3820. this.setColour(ONENET_BLOCK_COLOR);
  3821. this.setTooltip("");
  3822. this.setHelpUrl("");
  3823. }
  3824. };
  3825. Blockly.Python['esp32_main_controller_onenet_setup'] = function (block) {
  3826. var text_server_ip = block.getFieldValue('server_ip');
  3827. var text_product_id = block.getFieldValue('product_id');
  3828. var text_product_api_key = block.getFieldValue('product_api_key');
  3829. var text_device_id = block.getFieldValue('device_id');
  3830. // TODO: Assemble Python into code variable.
  3831. var code = '...\n';
  3832. return code;
  3833. };
  3834. Blockly.Blocks['iot_service_onenet'] = {
  3835. init: function () {
  3836. this.appendDummyInput()
  3837. .appendField(new Blockly.FieldImage("blockly/media/onenet_setup_logo.png", 120, 70, { alt: "*", flipRtl: "FALSE" }));
  3838. this.appendDummyInput()
  3839. .appendField(Blockly.Msg.iotservice_onenet_mqtt_send);
  3840. /*this.appendValueInput("first_input")
  3841. .setCheck(null)
  3842. .appendField("Field 0");*/
  3843. this.itemCount_ = 1;
  3844. this.updateShape_();
  3845. this.setMutator(new Blockly.Mutator(['iot_service_onenet_create_with_item']));
  3846. this.setColour(ONENET_BLOCK_COLOR);
  3847. this.setPreviousStatement(true, null);
  3848. this.setNextStatement(true, null);
  3849. this.setTooltip("");
  3850. this.setHelpUrl("");
  3851. },
  3852. mutationToDom: function () {
  3853. var container = document.createElement('mutation');
  3854. container.setAttribute('items', this.itemCount_);
  3855. return container;
  3856. },
  3857. domToMutation: function (xmlElement) {
  3858. this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
  3859. this.updateShape_();
  3860. },
  3861. decompose: function (workspace) {
  3862. var containerBlock = workspace.newBlock('iot_service_onenet_create_with_container');
  3863. containerBlock.initSvg();
  3864. var connection = containerBlock.getInput('STACK').connection;
  3865. for (var i = 0; i < this.itemCount_; i++) {
  3866. var itemBlock = workspace.newBlock('iot_service_onenet_create_with_item');
  3867. itemBlock.initSvg();
  3868. connection.connect(itemBlock.previousConnection);
  3869. connection = itemBlock.nextConnection;
  3870. }
  3871. return containerBlock;
  3872. },
  3873. compose: function (containerBlock) {
  3874. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  3875. // Count number of inputs.
  3876. var connections = [];
  3877. while (itemBlock) {
  3878. connections.push(itemBlock.valueConnection_);
  3879. itemBlock = itemBlock.nextConnection &&
  3880. itemBlock.nextConnection.targetBlock();
  3881. }
  3882. // Disconnect any children that don't belong.
  3883. for (var i = 0; i < this.itemCount_; i++) {
  3884. var connection = this.getInput('ADD' + i).connection.targetConnection;
  3885. if (connection && connections.indexOf(connection) == -1) {
  3886. connection.disconnect();
  3887. }
  3888. }
  3889. this.itemCount_ = connections.length;
  3890. this.updateShape_();
  3891. // Reconnect any child blocks.
  3892. for (var i = 0; i < this.itemCount_; i++) {
  3893. Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
  3894. }
  3895. },
  3896. saveConnections: function (containerBlock) {
  3897. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  3898. var i = 0;
  3899. while (itemBlock) {
  3900. var input = this.getInput('ADD' + i);
  3901. itemBlock.valueConnection_ = input && input.connection.targetConnection;
  3902. i++;
  3903. itemBlock = itemBlock.nextConnection &&
  3904. itemBlock.nextConnection.targetBlock();
  3905. }
  3906. },
  3907. updateShape_: function () {
  3908. for (var i = 0; i < this.itemCount_; i++) {
  3909. if (!this.getInput('ADD' + i)) {
  3910. var input = this.appendValueInput('ADD' + i);
  3911. input.appendField(Blockly.Msg.iotservice_onenet_mqtt_send_item)
  3912. .appendField(new Blockly.FieldTextInput("Property" + i), "field" + i);
  3913. //input.appendField("資料 " + (i + 1) + ":");
  3914. //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
  3915. // input.appendField(new Blockly.FieldTextInput("資料" + (i + 1)), 'FIELD' + i)
  3916. }
  3917. }
  3918. while (this.getInput('ADD' + i)) {
  3919. this.removeInput('ADD' + i);
  3920. i++;
  3921. }
  3922. },
  3923. };
  3924. Blockly.Blocks['iot_service_onenet_create_with_container'] = {
  3925. init: function () {
  3926. this.setColour(ONENET_BLOCK_COLOR);
  3927. this.appendDummyInput()
  3928. .appendField("Items");
  3929. this.appendStatementInput('STACK');
  3930. this.setTooltip('');
  3931. this.contextMenu = false;
  3932. }
  3933. };
  3934. Blockly.Blocks['iot_service_onenet_create_with_item'] = {
  3935. init: function () {
  3936. this.setColour(ONENET_BLOCK_COLOR);
  3937. this.appendDummyInput()
  3938. .appendField("Field");
  3939. this.setPreviousStatement(true);
  3940. this.setNextStatement(true);
  3941. this.setTooltip('');
  3942. this.contextMenu = false;
  3943. }
  3944. };
  3945. Blockly.Python['iot_service_onenet'] = function (block) {
  3946. var code = "";
  3947. // onenet_data_final.slice(0, -3) + '}\''
  3948. return code;
  3949. };
  3950. Blockly.Blocks['esp32_main_controller_onenet_when_receive_msg'] = {
  3951. init: function () {
  3952. this.appendDummyInput()
  3953. .appendField(Blockly.Msg.iotservice_onenet_mqtt_receive);
  3954. this.appendValueInput("content")
  3955. .setCheck(null);
  3956. this.appendDummyInput()
  3957. .appendField(Blockly.Msg.iotservice_onenet_mqtt_receive_when);
  3958. this.appendStatementInput("exec")
  3959. .setCheck(null)
  3960. .appendField(Blockly.Msg.iotservice_onenet_mqtt_receive_exec);
  3961. this.setInputsInline(true);
  3962. this.setPreviousStatement(true, null);
  3963. this.setNextStatement(true, null);
  3964. this.setColour(ONENET_BLOCK_COLOR);
  3965. this.setTooltip("");
  3966. this.setHelpUrl("");
  3967. }
  3968. };
  3969. Blockly.Python['esp32_main_controller_onenet_when_receive_msg'] = function (block) {
  3970. var value_content = Blockly.Python.valueToCode(block, 'content', Blockly.Python.ORDER_ATOMIC);
  3971. var statements_exec = Blockly.Python.statementToCode(block, 'exec');
  3972. // TODO: Assemble Python into code variable.
  3973. var code = '...\n';
  3974. return code;
  3975. };
  3976. Blockly.Blocks['esp32_main_controller_onenet_disconnect'] = {
  3977. init: function () {
  3978. this.appendDummyInput()
  3979. .appendField(Blockly.Msg.iotservice_onenet_mqtt_disconnect);
  3980. this.setInputsInline(true);
  3981. this.setPreviousStatement(true, null);
  3982. this.setNextStatement(true, null);
  3983. this.setColour(ONENET_BLOCK_COLOR);
  3984. this.setTooltip("");
  3985. this.setHelpUrl("");
  3986. }
  3987. };
  3988. Blockly.Python['esp32_main_controller_onenet_disconnect'] = function (block) {
  3989. // TODO: Assemble Python into code variable.
  3990. var code = '\n';
  3991. return code;
  3992. };
  3993. Blockly.Blocks['esp32_main_controller_ifttt_send_data'] = {
  3994. init: function () {
  3995. this.appendDummyInput()
  3996. .appendField(new Blockly.FieldImage("blockly/media/ifttt_webhook.png", 110, 60, { alt: "*", flipRtl: "FALSE" }));
  3997. this.appendDummyInput()
  3998. .appendField(Blockly.Msg.iotservice_ifttt_send_title);
  3999. this.appendDummyInput()
  4000. .appendField(Blockly.Msg.iotservice_ifttt_send_webhook)
  4001. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_API_KEY"), "ifttt_api_key");
  4002. this.appendDummyInput()
  4003. .appendField(Blockly.Msg.iotservice_ifttt_send_eventname)
  4004. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_NAME"), "ifttt_event");
  4005. this.appendValueInput("ifttt_data_1")
  4006. .setCheck(null)
  4007. .appendField(Blockly.Msg.iotservice_ifttt_send_1);
  4008. this.appendValueInput("ifttt_data_2")
  4009. .setCheck(null)
  4010. .appendField(Blockly.Msg.iotservice_ifttt_send_2);
  4011. this.appendValueInput("ifttt_data_3")
  4012. .setCheck(null)
  4013. .appendField(Blockly.Msg.iotservice_ifttt_send_3);
  4014. this.setPreviousStatement(true, null);
  4015. this.setNextStatement(true, null);
  4016. this.setColour(IFTTT_BLOCK_COLOR);
  4017. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Ifttt_Send_Data_TOOLTIP);
  4018. this.setHelpUrl("");
  4019. }
  4020. };
  4021. Blockly.Python['esp32_main_controller_ifttt_send_data'] = function (block) {
  4022. var text_ifttt_api_key = block.getFieldValue('ifttt_api_key');
  4023. var text_ifttt_event = block.getFieldValue('ifttt_event');
  4024. var value_ifttt_data_1 = Blockly.Python.valueToCode(block, 'ifttt_data_1', Blockly.Python.ORDER_ATOMIC);
  4025. var value_ifttt_data_2 = Blockly.Python.valueToCode(block, 'ifttt_data_2', Blockly.Python.ORDER_ATOMIC);
  4026. var value_ifttt_data_3 = Blockly.Python.valueToCode(block, 'ifttt_data_3', Blockly.Python.ORDER_ATOMIC);
  4027. // TODO: Assemble Python into code variable.
  4028. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4029. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  4030. var code = '' +
  4031. '_IFTTT_POST_API_KEY = "' + text_ifttt_api_key + '"\n' +
  4032. '_IFTTT_POST_EVENT_NAME = "' + text_ifttt_event + '"\n' +
  4033. '_IFTTT_POST_ENDPOINT = "http://maker.ifttt.com/trigger/"+ _IFTTT_POST_EVENT_NAME + "/with/key/" + _IFTTT_POST_API_KEY\n' +
  4034. '_IFTTT_POST_DATA = \'{"value1":"\'+ str(' + value_ifttt_data_1 + ') +\'","value2":"\'+ str(' + value_ifttt_data_2 + ') +\'","value3":"\'+ str(' + value_ifttt_data_3 + ') +\'"}\'\n' +
  4035. '_IFTTT_POST_REQUEST = requests.post(_IFTTT_POST_ENDPOINT, data = _IFTTT_POST_DATA , headers = { "Content-type": "application/json" }, timeout=60)\n' +
  4036. '\n';
  4037. return code;
  4038. };
  4039. Blockly.Blocks['esp32_main_controller_ifttt_touched'] = {
  4040. init: function () {
  4041. this.appendDummyInput()
  4042. .appendField(new Blockly.FieldImage("blockly/media/ifttt_webhook.png", 110, 60, { alt: "*", flipRtl: "FALSE" }));
  4043. this.appendDummyInput()
  4044. .appendField(Blockly.Msg.iotservice_ifttt_trigger_title);
  4045. this.appendDummyInput()
  4046. .appendField(Blockly.Msg.iotservice_ifttt_trigger_webhook)
  4047. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_API_KEY"), "key");
  4048. this.appendDummyInput()
  4049. .appendField(Blockly.Msg.iotservice_ifttt_trigger_eventname)
  4050. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_NAME"), "timename");
  4051. this.setPreviousStatement(true, null);
  4052. this.setNextStatement(true, null);
  4053. this.setColour(IFTTT_BLOCK_COLOR);
  4054. this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Ifttt_Touched_TOOLTIP);
  4055. this.setHelpUrl("");
  4056. }
  4057. };
  4058. Blockly.Python['esp32_main_controller_ifttt_touched'] = function (block) {
  4059. var text_ifttt_api_key = block.getFieldValue('key');
  4060. var text_timename = block.getFieldValue('timename');
  4061. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4062. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  4063. var code = '_IFTTT_TRIGGER_EVENT_NAME = "' + text_timename + '"\n'
  4064. code += '_IFTTT_TRIGGER_API_KEY = "' + text_ifttt_api_key + '"\n'
  4065. code += '_IFTTT_TRIGGER_ENDPOINT = "https://maker.ifttt.com/trigger/" + _IFTTT_TRIGGER_EVENT_NAME + "/with/key/" + _IFTTT_TRIGGER_API_KEY\n'
  4066. Blockly.Python.addSetup("esp32_main_controller_ifttt_touched", code);
  4067. var code = '_IFTTT_GET_REQUEST = requests.get(_IFTTT_TRIGGER_ENDPOINT, timeout=60)\n'
  4068. return code;
  4069. };
  4070. IOT_THINGSPEAK_COLOR = "#1b379f";
  4071. // IOT_THINGSPEAK_COLOR = ESP32_IOT_COLOR;
  4072. Blockly.Blocks['iot_service_thingspeak'] = {
  4073. init: function () {
  4074. this.appendDummyInput()
  4075. .appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 170, 45, { alt: "*", flipRtl: "FALSE" }));
  4076. this.appendDummyInput()
  4077. .appendField(Blockly.Msg.iotservice_thingspeak_send_title);
  4078. this.appendDummyInput()
  4079. .appendField(Blockly.Msg.iotservice_thingspeak_send_api)
  4080. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_WRITE_API_KEY"), "t_api");
  4081. /*this.appendValueInput("first_input")
  4082. .setCheck(null)
  4083. .appendField("Field 0");*/
  4084. this.itemCount_ = 1;
  4085. this.updateShape_();
  4086. this.setMutator(new Blockly.Mutator(['iot_service_thingspeak_create_with_item']));
  4087. this.setColour(IOT_THINGSPEAK_COLOR);
  4088. this.setPreviousStatement(true, null);
  4089. this.setNextStatement(true, null);
  4090. this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_TOOLTIP);
  4091. this.setHelpUrl("");
  4092. },
  4093. mutationToDom: function () {
  4094. var container = document.createElement('mutation');
  4095. container.setAttribute('items', this.itemCount_);
  4096. return container;
  4097. },
  4098. domToMutation: function (xmlElement) {
  4099. this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
  4100. this.updateShape_();
  4101. },
  4102. decompose: function (workspace) {
  4103. var containerBlock = workspace.newBlock('iot_service_thingspeak_create_with_container');
  4104. containerBlock.initSvg();
  4105. var connection = containerBlock.getInput('STACK').connection;
  4106. for (var i = 0; i < this.itemCount_; i++) {
  4107. var itemBlock = workspace.newBlock('iot_service_thingspeak_create_with_item');
  4108. itemBlock.initSvg();
  4109. connection.connect(itemBlock.previousConnection);
  4110. connection = itemBlock.nextConnection;
  4111. }
  4112. return containerBlock;
  4113. },
  4114. compose: function (containerBlock) {
  4115. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  4116. // Count number of inputs.
  4117. var connections = [];
  4118. while (itemBlock) {
  4119. connections.push(itemBlock.valueConnection_);
  4120. itemBlock = itemBlock.nextConnection &&
  4121. itemBlock.nextConnection.targetBlock();
  4122. }
  4123. // Disconnect any children that don't belong.
  4124. for (var i = 0; i < this.itemCount_; i++) {
  4125. var connection = this.getInput('ADD' + i).connection.targetConnection;
  4126. if (connection && connections.indexOf(connection) == -1) {
  4127. connection.disconnect();
  4128. }
  4129. }
  4130. this.itemCount_ = connections.length;
  4131. this.updateShape_();
  4132. // Reconnect any child blocks.
  4133. for (var i = 0; i < this.itemCount_; i++) {
  4134. Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
  4135. }
  4136. },
  4137. saveConnections: function (containerBlock) {
  4138. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  4139. var i = 0;
  4140. while (itemBlock) {
  4141. var input = this.getInput('ADD' + i);
  4142. itemBlock.valueConnection_ = input && input.connection.targetConnection;
  4143. i++;
  4144. itemBlock = itemBlock.nextConnection &&
  4145. itemBlock.nextConnection.targetBlock();
  4146. }
  4147. },
  4148. updateShape_: function () {
  4149. for (var i = 0; i < this.itemCount_; i++) {
  4150. if (!this.getInput('ADD' + i)) {
  4151. var input = this.appendValueInput('ADD' + i);
  4152. input.appendField("Field " + (i + 1) + ":");
  4153. //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
  4154. // input.appendField(new Blockly.FieldTextInput("field" + (i + 1)), 'FIELD' + i)
  4155. }
  4156. }
  4157. while (this.getInput('ADD' + i)) {
  4158. this.removeInput('ADD' + i);
  4159. i++;
  4160. }
  4161. },
  4162. };
  4163. Blockly.Blocks['iot_service_thingspeak_create_with_container'] = {
  4164. init: function () {
  4165. this.setColour(IOT_THINGSPEAK_COLOR);
  4166. this.appendDummyInput()
  4167. .appendField("Items");
  4168. this.appendStatementInput('STACK');
  4169. this.setTooltip('');
  4170. this.contextMenu = false;
  4171. }
  4172. };
  4173. Blockly.Blocks['iot_service_thingspeak_create_with_item'] = {
  4174. init: function () {
  4175. this.setColour(IOT_THINGSPEAK_COLOR);
  4176. this.appendDummyInput()
  4177. .appendField("Field");
  4178. this.setPreviousStatement(true);
  4179. this.setNextStatement(true);
  4180. this.setTooltip('');
  4181. this.contextMenu = false;
  4182. }
  4183. };
  4184. Blockly.Python['iot_service_thingspeak'] = function (block) {
  4185. var first_input = Blockly.Python.valueToCode(block, 'first_input', Blockly.Python.ORDER_ATOMIC);
  4186. var api = block.getFieldValue('t_api');
  4187. Blockly.Python.addVariable('_THINGSPEAK_REQUEST', '', true);
  4188. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4189. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  4190. // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";
  4191. var item_field = '',
  4192. item_value = '';
  4193. var thingspeak_url = "http://api.thingspeak.com/update?api_key=" + api;
  4194. for (var n = 0; n < this.itemCount_; n++) {
  4195. item_field = "field" + (n + 1);
  4196. item_value = Blockly.Python.valueToCode(this, 'ADD' + n,
  4197. Blockly.Python.ORDER_NONE) || '';
  4198. thingspeak_url += '&' + item_field + '=\"+str(' + item_value + ')+\"';
  4199. }
  4200. var code = '' +
  4201. '_THINGSPEAK_ENDPOINT = "' + thingspeak_url + '"\n' +
  4202. '_THINGSPEAK_REQUEST = requests.get(_THINGSPEAK_ENDPOINT,timeout=60)\n' +
  4203. '';
  4204. return code;
  4205. };
  4206. Blockly.Blocks['iot_service_thingspeak_read'] = {
  4207. init: function () {
  4208. this.appendDummyInput()
  4209. .appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 170, 45, { alt: "*", flipRtl: "FALSE" }));
  4210. this.appendDummyInput()
  4211. .appendField(Blockly.Msg.iotservice_thingspeak_query_title);
  4212. this.appendDummyInput()
  4213. .appendField(Blockly.Msg.iotservice_thingspeak_query_api)
  4214. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_READ_API_KEY"), "api_key");
  4215. this.appendDummyInput()
  4216. .appendField(Blockly.Msg.iotservice_thingspeak_channel_id)
  4217. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_ID"), "id");
  4218. this.setInputsInline(false);
  4219. this.setPreviousStatement(true, null);
  4220. this.setNextStatement(true, null);
  4221. this.setColour(IOT_THINGSPEAK_COLOR);
  4222. this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_TOOLTIP);
  4223. this.setHelpUrl("");
  4224. }
  4225. };
  4226. Blockly.Python['iot_service_thingspeak_read'] = function (block) {
  4227. var text_api_key = block.getFieldValue('api_key');
  4228. var text_id = block.getFieldValue('id');
  4229. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4230. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  4231. Blockly.Python.addVariable('_THINGSPEAK_READ_REQUEST', '', true);
  4232. // TODO: Assemble Python into code variable.
  4233. var code = '_THINGSPEAK_READ_REQUEST = requests.get("https://api.thingspeak.com/channels/" + "' + text_id + '" + "/feeds.json?api_key=" + "' + text_api_key + '",timeout=60)\n';
  4234. return code;
  4235. };
  4236. Blockly.Blocks['iot_service_thingspeak_read_total'] = {
  4237. init: function () {
  4238. this.appendDummyInput()
  4239. .appendField(Blockly.Msg.iotservice_thingspeak_read_total);
  4240. this.setInputsInline(false);
  4241. this.setOutput(true, null);
  4242. this.setColour(IOT_THINGSPEAK_COLOR);
  4243. this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_Total_TOOLTIP);
  4244. this.setHelpUrl("");
  4245. }
  4246. };
  4247. Blockly.Python['iot_service_thingspeak_read_total'] = function (block) {
  4248. // TODO: Assemble Python into code variable.
  4249. var code = '_THINGSPEAK_READ_REQUEST.json()[\'channel\'][\'last_entry_id\']';
  4250. // TODO: Change ORDER_NONE to the correct strength.
  4251. return [code, Blockly.Python.ORDER_NONE];
  4252. };
  4253. Blockly.Blocks['iot_service_thingspeak_read_specific'] = {
  4254. init: function () {
  4255. this.appendDummyInput()
  4256. .appendField(Blockly.Msg.iotservice_thingspeak_get_title);
  4257. this.appendValueInput("entry")
  4258. .setCheck(null);
  4259. this.appendDummyInput()
  4260. .appendField(Blockly.Msg.iotservice_thingspeaK_get_field);
  4261. this.appendValueInput("field")
  4262. .setCheck(null);
  4263. this.appendDummyInput()
  4264. .appendField(Blockly.Msg.iotservice_thingspeaK_get_value);
  4265. this.setInputsInline(true);
  4266. this.setOutput(true, null);
  4267. this.setColour(IOT_THINGSPEAK_COLOR);
  4268. this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_Specific_TOOLTIP);
  4269. this.setHelpUrl("");
  4270. }
  4271. };
  4272. Blockly.Python['iot_service_thingspeak_read_specific'] = function (block) {
  4273. var value_entry = Blockly.Python.valueToCode(block, 'entry', Blockly.Python.ORDER_ATOMIC);
  4274. var value_field = Blockly.Python.valueToCode(block, 'field', Blockly.Python.ORDER_ATOMIC);
  4275. // TODO: Assemble Python into code variable.
  4276. var code = '_THINGSPEAK_READ_REQUEST.json()[\'feeds\'][' + value_entry + '][\'field' + value_field + '\']';
  4277. // TODO: Change ORDER_NONE to the correct strength.
  4278. return [code, Blockly.Python.ORDER_NONE];
  4279. };
  4280. // KUJU
  4281. var KUJU_BLOCK_COLOR = "#00b5ff";
  4282. Blockly.Blocks['iot_service_KUJU_setup'] = {
  4283. init: function () {
  4284. this.appendDummyInput()
  4285. .appendField(new Blockly.FieldImage("blockly/media/KUJU.png", 110, 65, { alt: "*", flipRtl: "FALSE" }));
  4286. this.appendDummyInput()
  4287. .appendField(Blockly.Msg.KUJU_title);
  4288. this.appendValueInput("username")
  4289. .setCheck(null)
  4290. .appendField(Blockly.Msg.KUJU_username);
  4291. this.appendValueInput("password")
  4292. .setCheck(null)
  4293. .appendField(Blockly.Msg.KUJU_password);
  4294. this.setPreviousStatement(true, null);
  4295. this.setNextStatement(true, null);
  4296. this.setColour(ONENET_BLOCK_COLOR);
  4297. this.setTooltip(Blockly.Msg.iot_service_KUJU_setup_TOOLTIP);
  4298. this.setHelpUrl("");
  4299. }
  4300. };
  4301. Blockly.Python['iot_service_KUJU_setup'] = function (block) {
  4302. var username = Blockly.Python.valueToCode(block, 'username', Blockly.Python.ORDER_ATOMIC);
  4303. var password = Blockly.Python.valueToCode(block, 'password', Blockly.Python.ORDER_ATOMIC);
  4304. Blockly.Python.addVariable('_COCOCLOUD_SEND_REQUEST', '_COCOCLOUD_SEND_REQUEST = None', true);
  4305. Blockly.Python.addVariable('token', 'token = ""', true);
  4306. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4307. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  4308. Blockly.Python.definitions_['import_iot_service_KUJU_get_sensor_data'] = '' +
  4309. 'def GetSensorValue(typeCode):\n' +
  4310. ' _COCOCLOUD_SEND_ENDPOINT = "http://ssl.kujuportal.com/apps/get_info"\n' +
  4311. ' _COCOCLOUD_SEND_DATA = \'{"token":"\' + token + \'","type":"device_list"}\'\n' +
  4312. ' try:\n' +
  4313. ' _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, data = _COCOCLOUD_SEND_DATA, headers = { "Content-type": "application/json" }, timeout = 60)\n' +
  4314. ' a = json.loads(str(_COCOCLOUD_SEND_REQUEST.content.decode("utf-8")).replace("\'","").replace("\'",""))\n' +
  4315. ' if a["result"] == "1":\n' +
  4316. ' info = a["info"]\n' +
  4317. ' for i in range(len(info)):\n' +
  4318. ' if info[i]["type_code"] == typeCode:\n' +
  4319. ' _COCOCLOUD_SEND_ENDPOINT = "http://ssl.kujuportal.com/apps/get_info"\n' +
  4320. ' _COCOCLOUD_SEND_DATA = \'{"token":"\' + token + \'","type":"device_status","gateway_sn":"\' + info[i]["gateway_sn"] + \'","system_id":"\' + info[i]["system_id"] + \'","type_code":"\' + info[i]["type_code"] + \'"}\'\n' +
  4321. ' _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, data = _COCOCLOUD_SEND_DATA, headers = { "Content-type": "application/json" }, timeout = 60)\n' +
  4322. ' a = json.loads(str(_COCOCLOUD_SEND_REQUEST.content.decode("utf-8")).replace("\'","").replace("\'",""))\n' +
  4323. ' if a["result"] == "1":\n' +
  4324. ' return a["info"]["value"]\n' +
  4325. ' except BaseException as e:\n' +
  4326. ' return 0\n' +
  4327. '';
  4328. var cococloud_data = "'{\"username\":" + username + ",\"password\":\"" + hex_md5(password.replace('"', '').replace('"', '')) + "\",\"type\":\"token\"}'";
  4329. var code = '' +
  4330. '_COCOCLOUD_SEND_ENDPOINT = "http://ssl.kujuportal.com/apps/user_token"\n' +
  4331. '_COCOCLOUD_SEND_DATA = ' + cococloud_data + '\n' +
  4332. 'try:\n' +
  4333. ' _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, data = _COCOCLOUD_SEND_DATA , headers = { "Content-type": "application/json" }, timeout = 60)\n' +
  4334. ' token = json.loads(str(_COCOCLOUD_SEND_REQUEST.content.decode("utf-8")).replace("\'","").replace("\'",""))["info"]["token"]\n' +
  4335. // ' print(token)\n' +
  4336. 'except BaseException as e:\n' +
  4337. ' print(e)\n' +
  4338. 'pass\n' +
  4339. '';
  4340. return code;
  4341. };
  4342. Blockly.Blocks['iot_service_KUJU_controll'] = {
  4343. init: function () {
  4344. this.appendDummyInput()
  4345. .appendField(new Blockly.FieldImage("blockly/media/KUJU.png", 110, 65, { alt: "*", flipRtl: "FALSE" }));
  4346. this.appendDummyInput()
  4347. .appendField(Blockly.Msg.KUJU_controll_title);
  4348. this.appendDummyInput()
  4349. .appendField(Blockly.Msg.KUJU_controll_content)
  4350. .appendField(new Blockly.FieldDropdown([
  4351. [Blockly.Msg.KUJU_controll_action_0, "0"],
  4352. [Blockly.Msg.KUJU_controll_action_1, "1"]
  4353. ]), "type");
  4354. this.setPreviousStatement(true, null);
  4355. this.setNextStatement(true, null);
  4356. this.setColour(ONENET_BLOCK_COLOR);
  4357. this.setTooltip(Blockly.Msg.iot_service_KUJU_controll_TOOLTIP);
  4358. this.setHelpUrl("");
  4359. }
  4360. };
  4361. Blockly.Python['iot_service_KUJU_controll'] = function (block) {
  4362. var dropdown_type = block.getFieldValue('type');
  4363. var code = '' +
  4364. '_COCOCLOUD_SEND_ENDPOINT = "http://ssl.kujuportal.com/apps/get_info"\n' +
  4365. '_COCOCLOUD_SEND_DATA = \'{"token":"\' + token + \'","type":"device_list"}\'\n' +
  4366. 'try:\n' +
  4367. ' _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, data = _COCOCLOUD_SEND_DATA, headers = { "Content-type": "application/json" }, timeout = 60)\n' +
  4368. ' a = json.loads(str(_COCOCLOUD_SEND_REQUEST.content.decode("utf-8")).replace("\'","").replace("\'",""))\n' +
  4369. ' if a["result"] == "1":\n' +
  4370. ' info = a["info"]\n' +
  4371. ' for i in range(len(info)):\n' +
  4372. ' if info[i]["type_code"] == "0010001":\n' +
  4373. ' _COCOCLOUD_SEND_ENDPOINT = "http://ssl.kujuportal.com/apps/ctrl_device"\n' +
  4374. ' _COCOCLOUD_SEND_DATA = \'{"token":"\' + token + \'","type":"device","gateway_sn":"\' + info[i]["gateway_sn"] + \'","system_id":"\' + info[i]["system_id"] + \'","type_code":"\' + info[i]["type_code"] + \'","value":' + dropdown_type + '}\'\n' +
  4375. ' _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, data = _COCOCLOUD_SEND_DATA, headers = { "Content-type": "application/json" }, timeout = 60)\n' +
  4376. 'except BaseException as e:\n' +
  4377. ' print(e)\n' +
  4378. 'pass\n' +
  4379. '';
  4380. return code;
  4381. };
  4382. Blockly.Blocks['iot_service_KUJU_get_temperature_humidity_data'] = {
  4383. init: function () {
  4384. this.appendDummyInput()
  4385. .appendField(new Blockly.FieldImage("blockly/media/KUJU.png", 110, 65, { alt: "*", flipRtl: "FALSE" }));
  4386. this.appendDummyInput()
  4387. .appendField(Blockly.Msg.KUJU_get_temperature_humidity_data_title)
  4388. .appendField(new Blockly.FieldDropdown([
  4389. [Blockly.Msg.basic_temperature, "temperature"],
  4390. [Blockly.Msg.basic_humidity, "humidity"]
  4391. // [Blockly.Msg.basic_pressure, "pressure"]
  4392. ]), "env_get_type")
  4393. .appendField(Blockly.Msg.basic_env_value);
  4394. this.setInputsInline(false);
  4395. this.setOutput(true, null);
  4396. this.setColour(ONENET_BLOCK_COLOR);
  4397. this.setTooltip(Blockly.Msg.iot_service_KUJU_get_temperature_humidity_data_TOOLTIP);
  4398. this.setHelpUrl("");
  4399. }
  4400. };
  4401. Blockly.Python['iot_service_KUJU_get_temperature_humidity_data'] = function (block) {
  4402. var dropdown_type = block.getFieldValue('env_get_type');
  4403. var code = '';
  4404. if (dropdown_type == "temperature") {
  4405. code = "GetSensorValue(\"0320101\")";
  4406. }
  4407. if (dropdown_type == "humidity") {
  4408. code = "GetSensorValue(\"0320201\")";
  4409. }
  4410. return [code, Blockly.Python.ORDER_CONDITIONAL];
  4411. };
  4412. Blockly.Blocks['iot_service_KUJU_get_motion_data'] = {
  4413. init: function () {
  4414. this.appendDummyInput()
  4415. .appendField(new Blockly.FieldImage("blockly/media/KUJU.png", 110, 65, { alt: "*", flipRtl: "FALSE" }));
  4416. this.appendDummyInput()
  4417. .appendField(Blockly.Msg.KUJU_get_motion_data_title)
  4418. .appendField(new Blockly.FieldDropdown([
  4419. [Blockly.Msg.basic_motion_data, "move"],
  4420. [Blockly.Msg.basic_illumination_intensity, "Illumination intensity"]
  4421. // [Blockly.Msg.basic_pressure, "pressure"]
  4422. ]), "env_get_type")
  4423. .appendField(Blockly.Msg.basic_env_value);
  4424. this.setInputsInline(false);
  4425. this.setOutput(true, null);
  4426. this.setColour(ONENET_BLOCK_COLOR);
  4427. this.setTooltip(Blockly.Msg.iot_service_KUJU_get_motion_data_TOOLTIP);
  4428. this.setHelpUrl("");
  4429. }
  4430. };
  4431. Blockly.Python['iot_service_KUJU_get_motion_data'] = function (block) {
  4432. var dropdown_type = block.getFieldValue('env_get_type');
  4433. var code = '';
  4434. if (dropdown_type == "move") {
  4435. code = "GetSensorValue(\"0300101\")";
  4436. }
  4437. if (dropdown_type == "Illumination intensity") {
  4438. code = "GetSensorValue(\"0300201\")";
  4439. }
  4440. return [code, Blockly.Python.ORDER_CONDITIONAL];
  4441. };
  4442. Blockly.Blocks['iot_service_KUJU_get_sensor_data'] = {
  4443. init: function () {
  4444. this.appendDummyInput()
  4445. .appendField(new Blockly.FieldImage("blockly/media/KUJU.png", 110, 65, { alt: "*", flipRtl: "FALSE" }));
  4446. this.appendDummyInput()
  4447. .appendField(Blockly.Msg.KUJU_get_sensor_data_title)
  4448. .appendField(new Blockly.FieldDropdown([
  4449. [Blockly.Msg.basic_water_sensor, "water sensor"],
  4450. [Blockly.Msg.basic_door_sensor, "door sensor"]
  4451. // [Blockly.Msg.basic_pressure, "pressure"]
  4452. ]), "env_get_type")
  4453. .appendField(Blockly.Msg.basic_env_value);
  4454. this.setInputsInline(false);
  4455. this.setOutput(true, null);
  4456. this.setColour(ONENET_BLOCK_COLOR);
  4457. this.setTooltip(Blockly.Msg.iot_service_KUJU_get_sensor_data_TOOLTIP);
  4458. this.setHelpUrl("");
  4459. }
  4460. };
  4461. Blockly.Python['iot_service_KUJU_get_sensor_data'] = function (block) {
  4462. var dropdown_type = block.getFieldValue('env_get_type');
  4463. var code = '';
  4464. if (dropdown_type == "water sensor") {
  4465. code = "GetSensorValue(\"0120001\")";
  4466. }
  4467. if (dropdown_type == "door sensor") {
  4468. code = "GetSensorValue(\"0080001\")";
  4469. }
  4470. return [code, Blockly.Python.ORDER_CONDITIONAL];
  4471. };
  4472. // Wetech
  4473. var WETECH_COLOR = "#3CB371";
  4474. Blockly.Blocks['wifiServices_WeTech_setup'] = {
  4475. init: function () {
  4476. this.appendDummyInput()
  4477. .appendField(new Blockly.FieldImage("blockly/media/wetech_header.png", 150, 60, "15"));
  4478. this.appendDummyInput()
  4479. .appendField(Blockly.Msg.wifiServices_WeTech_title);
  4480. this.appendValueInput("username")
  4481. .setCheck(null)
  4482. .appendField(Blockly.Msg.wifiServices_WeTech_username);
  4483. this.appendValueInput("password")
  4484. .setCheck(null)
  4485. .appendField(Blockly.Msg.wifiServices_WeTech_password);
  4486. this.appendValueInput("gateway_id")
  4487. .setCheck(null)
  4488. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY7)
  4489. this.appendValueInput("mac_address")
  4490. .setCheck(null)
  4491. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY12)
  4492. this.setPreviousStatement(true, null);
  4493. this.setNextStatement(true, null);
  4494. this.setColour(WETECH_COLOR);
  4495. this.setTooltip(Blockly.Msg.wifiServices_WeTech_setup_TOOLTIP);
  4496. this.setHelpUrl("");
  4497. }
  4498. };
  4499. Blockly.Python['wifiServices_WeTech_setup'] = function (block) {
  4500. var username = Blockly.Python.valueToCode(block, 'username', Blockly.Python.ORDER_ATOMIC);
  4501. var password = Blockly.Python.valueToCode(block, 'password', Blockly.Python.ORDER_ATOMIC);
  4502. var gateway_id = Blockly.Python.valueToCode(block, 'gateway_id', Blockly.Python.ORDER_ATOMIC);
  4503. var mac_address = Blockly.Python.valueToCode(block, 'mac_address', Blockly.Python.ORDER_ATOMIC);
  4504. Blockly.Python.addVariable('_wetech_username', '_wetech_username = ' + username, true);
  4505. Blockly.Python.addVariable('_wetech_password', '_wetech_password = ' + password, true);
  4506. Blockly.Python.addVariable('_wetech_gateway_id', '_wetech_gateway_id = ' + gateway_id, true);
  4507. Blockly.Python.addVariable('_wetech_mac_address', '_wetech_mac_address = ' + mac_address, true);
  4508. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4509. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  4510. Blockly.Python.definitions_['import_urequests'] = '' +
  4511. 'from umqtt_simple import MQTTClient\n' +
  4512. 'import ubinascii\n' +
  4513. 'import machine' +
  4514. '';
  4515. Blockly.Python.definitions_['import_wifiServices_WeTech_setup'] = '' +
  4516. '\n' +
  4517. '_wetech_mqtt_server = ""\n' +
  4518. '_wetech_mqtt_username = ""\n' +
  4519. '_wetech_mqtt_pw = ""\n' +
  4520. '_WeTech_CLIENT_ID = ubinascii.hexlify(machine.unique_id())\n' +
  4521. 'isMqttConnect = False\n' +
  4522. 'MQTT_Data = None\n' +
  4523. 'client = None\n' +
  4524. '\n' +
  4525. 'def restart_and_reconnect():\n' +
  4526. ' print(\'Failed to connect to MQTT broker. Reconnecting...\')\n' +
  4527. ' time.sleep(10)\n' +
  4528. ' machine.reset()\n' +
  4529. '\n' +
  4530. 'def connect_and_subscribe(CLIENT_ID,server,TOPIC,username,password):\n' +
  4531. ' c = MQTTClient(CLIENT_ID, server,1883,username,password,keepalive=60)\n' +
  4532. ' c.set_callback(sub_cb) #set callback\n' +
  4533. ' c.connect() #connect mqtt\n' +
  4534. ' c.subscribe(TOPIC) #client subscribes to a topic\n' +
  4535. ' time.sleep(0.1)\n' +
  4536. ' return c\n' +
  4537. '\n' +
  4538. 'def sub_cb(topic, msg):\n' +
  4539. ' global MQTT_Data\n' +
  4540. ' MQTT_Data = json.loads(msg)[\'StatusList\']\n' +
  4541. '\n' +
  4542. 'def setup_mqtt(url, username, password):\n' +
  4543. ' global _wetech_mqtt_server,_wetech_mqtt_username,_wetech_mqtt_pw\n' +
  4544. ' if _wetech_mqtt_server == "" and _wetech_mqtt_username == "" and _wetech_mqtt_pw == "":\n' +
  4545. ' _WeTech_SEND_DATA = \"language=en&pf=ios&username=\"+ username + \"&password=\" + password\n' +
  4546. ' try:\n' +
  4547. ' _WeTech_SEND_REQUEST = requests.post(url, data = _WeTech_SEND_DATA , headers = { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, timeout = 60)\n' +
  4548. ' #print(str(_WeTech_SEND_REQUEST.status_code)+", "+str(_WeTech_SEND_REQUEST.content))\n' +
  4549. ' _wetech_mqtt_server = _WeTech_SEND_REQUEST.json()[\'mqtt_url\']\n' +
  4550. ' _wetech_mqtt_username = _WeTech_SEND_REQUEST.json()[\'mqtt_username\']\n' +
  4551. ' _wetech_mqtt_pw = _WeTech_SEND_REQUEST.json()[\'mqtt_pw\']\n' +
  4552. ' except BaseException as e:\n' +
  4553. ' print(e)\n' +
  4554. ' pass\n' +
  4555. '\n' +
  4556. 'def getStatusDeviceById(device_id):\n' +
  4557. ' global _wetech_mqtt_server,_wetech_mqtt_username,_wetech_mqtt_pw,client, _wetech_mac_address, MQTT_Data,isMqttConnect\n' +
  4558. ' data = \'{"SourceID":"\' + str(_WeTech_CLIENT_ID).replace("b\'","").replace("\'","") + \'", "DestID": "gateway/"\' + str(_wetech_mac_address) + \', "Cmd": "13", "DeviceID":"0"}\'\n' +
  4559. ' setup_mqtt("http://ihouse.janwit.cn/ha/ios/process/checkLogin.php", _wetech_username, _wetech_password)\n' +
  4560. ' if _wetech_mqtt_server != "" and _wetech_mqtt_username != "" and _wetech_mqtt_pw != "":\n' +
  4561. ' if isMqttConnect == False:\n' +
  4562. ' try:\n' +
  4563. ' client = connect_and_subscribe(str(_WeTech_CLIENT_ID).replace("b\'","").replace("\'",""), _wetech_mqtt_server, "gateway/" + str(_wetech_mac_address) + "/" + str(_WeTech_CLIENT_ID).replace("b\'","").replace("\'",""), _wetech_mqtt_username, _wetech_mqtt_pw)\n' +
  4564. ' time.sleep(0.1)\n' +
  4565. ' isMqttConnect = True\n' +
  4566. ' client.publish("gateway/" + str(_wetech_mac_address) , data, 1)\n' +
  4567. ' time.sleep(0.1)\n' +
  4568. ' client.wait_msg()\n' +
  4569. ' return stringToHex(MQTT_Data,device_id)\n' +
  4570. ' except OSError as e:\n' +
  4571. ' restart_and_reconnect()\n' +
  4572. ' else:\n' +
  4573. ' try:\n' +
  4574. ' client.publish("gateway/" + str(_wetech_mac_address) , data, 1)\n' +
  4575. ' time.sleep(0.1)\n' +
  4576. ' client.wait_msg()\n' +
  4577. ' return stringToHex(MQTT_Data,device_id)\n' +
  4578. ' except OSError as e:\n' +
  4579. ' restart_and_reconnect()\n' +
  4580. '\n' +
  4581. 'def stringToHex(msg,device_id):\n' +
  4582. ' status = None\n' +
  4583. ' for item in msg:\n' +
  4584. ' if str(item[\'id\']) == device_id:\n' +
  4585. ' status = item[\'status\']\n' +
  4586. ' break\n' +
  4587. ' status_value =status[6:] + status[4:6] + status[2:4] + status[0:2]\n' +
  4588. ' return round(float(int(status_value,16) / 100),2)\n' +
  4589. '\n' +
  4590. 'def decToHexstring(x):\n' +
  4591. ' hex_str = \'{:04X}\'.format(data*100)\n' +
  4592. ' data_h, data_l = hex_str[0:2], hex_str[2:4]\n' +
  4593. ' return str(data_l) + str(data_h)\n' +
  4594. '\n' +
  4595. 'def controllDeviceById(url, username, password, gateway_id, device_id, status):\n' +
  4596. ' _WeTech_SEND_DATA = \"language=en&pf=ios&username=\"+ username + \"&password=\" + password +\"&cmd=control_device_req&gateway_id="+ gateway_id +"&controlList=[{\\\"DeviceID\\\":\\\"" + device_id + "\\\",\\\"Status\\\":\\\""+ status +"\\\",\\\"delayTime\\\":\\\"0\\\"}]\"\n' +
  4597. ' try:\n' +
  4598. ' _WeTech_SEND_REQUEST = requests.post(url, data = _WeTech_SEND_DATA , headers = { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, timeout = 60)\n' +
  4599. ' print(str(_WeTech_SEND_REQUEST.status_code)+", "+str(_WeTech_SEND_REQUEST.content))\n' +
  4600. ' except BaseException as e:\n' +
  4601. ' print(e)\n' +
  4602. ' pass\n' +
  4603. '\n' +
  4604. '';
  4605. var code = '';
  4606. return code;
  4607. };
  4608. Blockly.Blocks['wifiServices_WeTech_controll_derail'] = {
  4609. init: function () {
  4610. this.appendDummyInput()
  4611. .appendField(Blockly.Msg.WeTech_controll_title);
  4612. this.appendValueInput("device_id")
  4613. .setCheck(null)
  4614. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY6)
  4615. this.appendDummyInput()
  4616. .appendField(Blockly.Msg.WeTech_controll_content)
  4617. .appendField(new Blockly.FieldDropdown([
  4618. [Blockly.Msg.WeTech_controll_action_0, "0"],
  4619. [Blockly.Msg.WeTech_controll_action_1, "1"]
  4620. ]), "type");
  4621. this.setInputsInline(false);
  4622. this.setPreviousStatement(true, null);
  4623. this.setNextStatement(true, null);
  4624. this.setColour(WETECH_COLOR);
  4625. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_TOOLTIP);
  4626. this.setHelpUrl("");
  4627. }
  4628. };
  4629. Blockly.Python['wifiServices_WeTech_controll_derail'] = function (block) {
  4630. var dropdown_type = block.getFieldValue('type');
  4631. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4632. var code = '';
  4633. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4634. if (dropdown_type == 0) {
  4635. code += "" +
  4636. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"FF000000\")\n";
  4637. }
  4638. else {
  4639. code += "" +
  4640. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"00000000\")\n";
  4641. }
  4642. return code;
  4643. };
  4644. Blockly.Blocks['wifiServices_WeTech_controll_derail_second_way'] = {
  4645. init: function () {
  4646. this.appendDummyInput()
  4647. .appendField(Blockly.Msg.WeTech_controll_title);
  4648. this.appendValueInput("device_id")
  4649. .setCheck(null)
  4650. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY8)
  4651. this.appendDummyInput()
  4652. .appendField(Blockly.Msg.WeTech_controll_content)
  4653. .appendField(new Blockly.FieldDropdown([
  4654. [Blockly.Msg.WeTech_controll_action_0, "0"],
  4655. [Blockly.Msg.WeTech_controll_action_1, "1"]
  4656. ]), "type");
  4657. this.setInputsInline(false);
  4658. this.setPreviousStatement(true, null);
  4659. this.setNextStatement(true, null);
  4660. this.setColour(WETECH_COLOR);
  4661. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_second_way_TOOLTIP);
  4662. this.setHelpUrl("");
  4663. }
  4664. };
  4665. Blockly.Python['wifiServices_WeTech_controll_derail_second_way'] = function (block) {
  4666. var dropdown_type = block.getFieldValue('type');
  4667. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4668. var code = '';
  4669. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4670. if (dropdown_type == 0) {
  4671. code += "" +
  4672. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"FF000000\")\n";
  4673. }
  4674. else {
  4675. code += "" +
  4676. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"00000000\")\n";
  4677. }
  4678. return code;
  4679. };
  4680. Blockly.Blocks['wifiServices_WeTech_controll_derail_curtain_sensor'] = {
  4681. init: function () {
  4682. this.appendDummyInput()
  4683. .appendField(Blockly.Msg.WeTech_controll_title);
  4684. this.appendValueInput("device_id")
  4685. .setCheck(null)
  4686. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY9)
  4687. this.appendDummyInput()
  4688. .appendField(Blockly.Msg.WeTech_controll_content)
  4689. .appendField(new Blockly.FieldDropdown([
  4690. [Blockly.Msg.WeTech_controll_action_0, "0"],
  4691. [Blockly.Msg.WeTech_controll_action_1, "1"],
  4692. [Blockly.Msg.WeTech_controll_action_2, "2"]
  4693. ]), "type");
  4694. this.setInputsInline(false);
  4695. this.setPreviousStatement(true, null);
  4696. this.setNextStatement(true, null);
  4697. this.setColour(WETECH_COLOR);
  4698. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_curtain_sensor_TOOLTIP);
  4699. this.setHelpUrl("");
  4700. }
  4701. };
  4702. Blockly.Python['wifiServices_WeTech_controll_derail_curtain_sensor'] = function (block) {
  4703. var dropdown_type = block.getFieldValue('type');
  4704. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4705. var code = "";
  4706. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4707. if (dropdown_type == 0) {
  4708. code += "" +
  4709. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"01000000\")\n";
  4710. }
  4711. else if (dropdown_type == 1) {
  4712. code += "" +
  4713. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"00000000\")\n";
  4714. }
  4715. else {
  4716. code += "" +
  4717. "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"02000000\")\n";
  4718. }
  4719. return code;
  4720. };
  4721. Blockly.Blocks['wifiServices_WeTech_controll_derail_air_conditioning_mode'] = {
  4722. init: function () {
  4723. this.appendDummyInput()
  4724. .appendField(Blockly.Msg.WeTech_controll_title);
  4725. this.appendValueInput("device_id")
  4726. .setCheck(null)
  4727. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY10)
  4728. this.appendDummyInput()
  4729. .appendField(Blockly.Msg.WeTech_controll_air_content)
  4730. .appendField(new Blockly.FieldDropdown([
  4731. [Blockly.Msg.WeTech_controll_mode_0, "00FFFFFF"],
  4732. [Blockly.Msg.WeTech_controll_mode_1, "01FFFFFF"],
  4733. [Blockly.Msg.WeTech_controll_mode_2, "03FFFFFF"],
  4734. [Blockly.Msg.WeTech_controll_mode_3, "04FFFFFF"],
  4735. [Blockly.Msg.WeTech_controll_mode_4, "05FFFFFF"],
  4736. [Blockly.Msg.WeTech_controll_mode_5, "06FFFFFF"],
  4737. [Blockly.Msg.WeTech_controll_mode_6, "07FFFFFF"],
  4738. [Blockly.Msg.WeTech_controll_mode_7, "08FFFFFF"],
  4739. [Blockly.Msg.WeTech_controll_mode_8, "09FFFFFF"],
  4740. // [Blockly.Msg.WeTech_controll_mode_9, "F0FFFFFF"]
  4741. ]), "type");
  4742. this.setInputsInline(false);
  4743. this.setPreviousStatement(true, null);
  4744. this.setNextStatement(true, null);
  4745. this.setColour(WETECH_COLOR);
  4746. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_air_conditioning_mode_TOOLTIP);
  4747. this.setHelpUrl("");
  4748. }
  4749. };
  4750. Blockly.Python['wifiServices_WeTech_controll_derail_air_conditioning_mode'] = function (block) {
  4751. var dropdown_type = block.getFieldValue('type');
  4752. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4753. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4754. var code = "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"" + dropdown_type + "\")\n";
  4755. return code;
  4756. };
  4757. Blockly.Blocks['wifiServices_WeTech_controll_derail_wind_speed_mode'] = {
  4758. init: function () {
  4759. this.appendDummyInput()
  4760. .appendField(Blockly.Msg.WeTech_controll_title);
  4761. this.appendValueInput("device_id")
  4762. .setCheck(null)
  4763. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY10)
  4764. this.appendDummyInput()
  4765. .appendField(Blockly.Msg.WeTech_controll_wind_speed_content)
  4766. .appendField(new Blockly.FieldDropdown([
  4767. [Blockly.Msg.WeTech_controll_action_0, "FF00FFFF"],
  4768. [Blockly.Msg.WeTech_controll_mode_10, "FF01FFFF"],
  4769. [Blockly.Msg.WeTech_controll_mode_11, "FF02FFFF"],
  4770. [Blockly.Msg.WeTech_controll_mode_12, "FF03FFFF"],
  4771. [Blockly.Msg.WeTech_controll_mode_13, "FF05FFFF"]
  4772. ]), "type");
  4773. this.setInputsInline(false);
  4774. this.setPreviousStatement(true, null);
  4775. this.setNextStatement(true, null);
  4776. this.setColour(WETECH_COLOR);
  4777. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_wind_speed_mode_TOOLTIP);
  4778. this.setHelpUrl("");
  4779. }
  4780. };
  4781. Blockly.Python['wifiServices_WeTech_controll_derail_wind_speed_mode'] = function (block) {
  4782. var dropdown_type = block.getFieldValue('type');
  4783. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4784. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4785. var code = "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"" + dropdown_type + "\")\n";
  4786. return code;
  4787. };
  4788. Blockly.Blocks['wifiServices_WeTech_controll_derail_temp'] = {
  4789. init: function () {
  4790. this.appendDummyInput()
  4791. .appendField(Blockly.Msg.WeTech_controll_title);
  4792. this.appendValueInput("device_id")
  4793. .setCheck(null)
  4794. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY10)
  4795. this.appendValueInput("ADD0")
  4796. .setCheck(null)
  4797. .appendField(Blockly.Msg.WeTech_controll_temp_content)
  4798. this.setInputsInline(false);
  4799. this.setPreviousStatement(true, null);
  4800. this.setNextStatement(true, null);
  4801. this.setColour(WETECH_COLOR);
  4802. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_temp_TOOLTIP);
  4803. this.setHelpUrl("");
  4804. },
  4805. onchange: function () {
  4806. var num = this.getChildren()[1].getFieldValue("NUM");
  4807. if (num > 30) {
  4808. this.getChildren()[1].getField("NUM").setValue("30");
  4809. }
  4810. else if (num < 16) {
  4811. this.getChildren()[1].getField("NUM").setValue("16");
  4812. }
  4813. }
  4814. };
  4815. Blockly.Python['wifiServices_WeTech_controll_derail_temp'] = function (block) {
  4816. var ADD0 = Blockly.Python.valueToCode(block, 'ADD0', Blockly.Python.ORDER_ATOMIC);
  4817. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4818. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4819. var code = "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"FFFF\" + decToHexstring(" + ADD0 + "))\n";
  4820. return code;
  4821. };
  4822. Blockly.Blocks['wifiServices_WeTech_controll_derail_all_mode'] = {
  4823. init: function () {
  4824. this.appendDummyInput()
  4825. .appendField(Blockly.Msg.WeTech_controll_title);
  4826. this.appendValueInput("device_id")
  4827. .setCheck(null)
  4828. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY10)
  4829. this.appendDummyInput()
  4830. .appendField(Blockly.Msg.WeTech_controll_air_content)
  4831. .appendField(new Blockly.FieldDropdown([
  4832. [Blockly.Msg.WeTech_controll_mode_0, "00"],
  4833. [Blockly.Msg.WeTech_controll_mode_1, "01"],
  4834. [Blockly.Msg.WeTech_controll_mode_2, "03"],
  4835. [Blockly.Msg.WeTech_controll_mode_3, "04"],
  4836. [Blockly.Msg.WeTech_controll_mode_4, "05"],
  4837. [Blockly.Msg.WeTech_controll_mode_5, "06"],
  4838. [Blockly.Msg.WeTech_controll_mode_6, "07"],
  4839. [Blockly.Msg.WeTech_controll_mode_7, "08"],
  4840. [Blockly.Msg.WeTech_controll_mode_8, "09"],
  4841. // [Blockly.Msg.WeTech_controll_mode_9, "9"]
  4842. ]), "air_conditioning_mode_type");
  4843. this.appendDummyInput()
  4844. .appendField(Blockly.Msg.WeTech_controll_wind_speed_content)
  4845. .appendField(new Blockly.FieldDropdown([
  4846. [Blockly.Msg.WeTech_controll_action_0, "00"],
  4847. [Blockly.Msg.WeTech_controll_mode_10, "01"],
  4848. [Blockly.Msg.WeTech_controll_mode_11, "02"],
  4849. [Blockly.Msg.WeTech_controll_mode_12, "03"],
  4850. [Blockly.Msg.WeTech_controll_mode_13, "05"]
  4851. ]), "speed_mode_type");
  4852. this.appendValueInput("ADD0")
  4853. .setCheck(null)
  4854. .appendField(Blockly.Msg.WeTech_controll_temp_content)
  4855. this.setInputsInline(false);
  4856. this.setPreviousStatement(true, null);
  4857. this.setNextStatement(true, null);
  4858. this.setColour(WETECH_COLOR);
  4859. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_all_mode_TOOLTIP);
  4860. this.setHelpUrl("");
  4861. },
  4862. onchange: function () {
  4863. var num = this.getChildren()[1].getFieldValue("NUM");
  4864. if (num > 30) {
  4865. this.getChildren()[1].getField("NUM").setValue("30");
  4866. }
  4867. else if (num < 16) {
  4868. this.getChildren()[1].getField("NUM").setValue("16");
  4869. }
  4870. }
  4871. };
  4872. Blockly.Python['wifiServices_WeTech_controll_derail_all_mode'] = function (block) {
  4873. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4874. var air_conditioning_mode_type = block.getFieldValue('air_conditioning_mode_type');
  4875. var speed_mode_type = block.getFieldValue('speed_mode_type');
  4876. var ADD0 = Blockly.Python.valueToCode(block, 'ADD0', Blockly.Python.ORDER_ATOMIC);
  4877. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4878. var code = "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", \"" + air_conditioning_mode_type + speed_mode_type + "\" + decToHexstring(" + ADD0 + "))\n";
  4879. return code;
  4880. };
  4881. Blockly.Blocks['wifiServices_WeTech_controll_derail_IR'] = {
  4882. init: function () {
  4883. this.appendDummyInput()
  4884. .appendField(Blockly.Msg.WeTech_controll_title);
  4885. this.appendValueInput("device_id")
  4886. .setCheck(null)
  4887. .appendField(Blockly.Msg.WIFIEASYMODE_WeTech_KEY11)
  4888. this.appendValueInput("ADD0")
  4889. .setCheck(null)
  4890. .appendField(Blockly.Msg.WeTech_controll_IR_content)
  4891. this.setInputsInline(false);
  4892. this.setPreviousStatement(true, null);
  4893. this.setNextStatement(true, null);
  4894. this.setColour(WETECH_COLOR);
  4895. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_IR_TOOLTIP);
  4896. this.setHelpUrl("");
  4897. },
  4898. onchange: function () {
  4899. var num = this.getChildren()[1].getFieldValue("NUM");
  4900. if (num > 255) {
  4901. this.getChildren()[1].getField("NUM").setValue("255");
  4902. }
  4903. else if (num < 0) {
  4904. this.getChildren()[1].getField("NUM").setValue("0");
  4905. }
  4906. }
  4907. };
  4908. Blockly.Python['wifiServices_WeTech_controll_derail_IR'] = function (block) {
  4909. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4910. var ADD0 = Blockly.Python.valueToCode(block, 'ADD0', Blockly.Python.ORDER_ATOMIC);
  4911. var item_url = "http://ihouse.janwit.cn/ha/ios/bsInterface.php";
  4912. var code = "controllDeviceById(\"" + item_url + "\", _wetech_username, _wetech_password, _wetech_gateway_id, " + device_id + ", str('{:02X}'.format(" + ADD0 + ")) + \"000000\");\n";
  4913. return code;
  4914. };
  4915. Blockly.Blocks['wifiServices_WeTech_controll_derail_get_power_meter'] = {
  4916. init: function () {
  4917. this.appendDummyInput()
  4918. .appendField(Blockly.Msg.WeTech_controll_power_meter);
  4919. this.appendValueInput("device_id")
  4920. .setCheck(null)
  4921. .appendField(Blockly.Msg.WeTech_controll_power_meter_1)
  4922. this.setOutput(true);
  4923. this.setInputsInline(false);
  4924. this.setColour(WETECH_COLOR);
  4925. this.setTooltip(Blockly.Msg.wifiServices_WeTech_controll_derail_get_power_meter_TOOLTIP);
  4926. this.setHelpUrl("");
  4927. }
  4928. };
  4929. Blockly.Python['wifiServices_WeTech_controll_derail_get_power_meter'] = function (block) {
  4930. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4931. var code = "getStatusDeviceById(" + device_id + ")";
  4932. return [code, Blockly.Python.ORDER_ATOMIC];
  4933. }
  4934. Blockly.Blocks['wifiServices_WeTech_controll_derail_get_sensor_number'] = {
  4935. init: function () {
  4936. this.appendDummyInput()
  4937. .appendField(Blockly.Msg.WeTech_controll_power_meter);
  4938. this.appendValueInput("device_id")
  4939. .setCheck(null)
  4940. .appendField(new Blockly.FieldDropdown([
  4941. [Blockly.Msg.Wetech_controll_pm25_sensor, "0"],
  4942. [Blockly.Msg.Wetech_controll_CO2_sensor, "1"],
  4943. [Blockly.Msg.Wetech_controll_Temperature_sensor, "2"],
  4944. [Blockly.Msg.Wetech_controll_Humidity_sensor, "3"]
  4945. ]), "type")
  4946. .appendField(Blockly.Msg.Wetech_controll_sensor_title);
  4947. this.setOutput(true);
  4948. this.setInputsInline(false);
  4949. this.setColour(WETECH_COLOR);
  4950. var thisBlock = this;
  4951. this.setTooltip(function () {
  4952. var mode = thisBlock.getFieldValue('type');
  4953. var TOOLTIPS = {
  4954. '0': Blockly.Msg.wifiServices_WeTech_controll_derail_get_sensor_number_TOOLTIP.replace('%1', Blockly.Msg.Wetech_controll_pm25_sensor),
  4955. '1': Blockly.Msg.wifiServices_WeTech_controll_derail_get_sensor_number_TOOLTIP.replace('%1', Blockly.Msg.Wetech_controll_CO2_sensor),
  4956. '2': Blockly.Msg.wifiServices_WeTech_controll_derail_get_sensor_number_TOOLTIP.replace('%1', Blockly.Msg.Wetech_controll_Temperature_sensor),
  4957. '3': Blockly.Msg.wifiServices_WeTech_controll_derail_get_sensor_number_TOOLTIP.replace('%1', Blockly.Msg.Wetech_controll_Humidity_sensor)
  4958. };
  4959. return TOOLTIPS[mode];
  4960. });
  4961. this.setHelpUrl("");
  4962. }
  4963. };
  4964. Blockly.Python['wifiServices_WeTech_controll_derail_get_sensor_number'] = function (block) {
  4965. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  4966. var type = block.getFieldValue('type');
  4967. var code = "getStatusDeviceById(" + device_id + ")";
  4968. return [code, Blockly.Python.ORDER_ATOMIC];
  4969. };
  4970. // tuya
  4971. var tuya_BLOCK_COLOR = "#FF5500";
  4972. Blockly.Blocks['iot_service_tuya_setup'] = {
  4973. init: function () {
  4974. this.appendDummyInput()
  4975. .appendField(Blockly.Msg.iot_service_tuya_title);
  4976. this.appendValueInput("access_id")
  4977. .setCheck(null)
  4978. .appendField(Blockly.Msg.iot_service_tuya_access_id);
  4979. this.appendValueInput("access_secret")
  4980. .setCheck(null)
  4981. .appendField(Blockly.Msg.iot_service_tuya_access_secret);
  4982. this.setInputsInline(false);
  4983. this.setPreviousStatement(true, null);
  4984. this.setNextStatement(true, null);
  4985. this.setColour(tuya_BLOCK_COLOR);
  4986. this.setTooltip(Blockly.Msg.iot_service_tuya_TOOLTIP);
  4987. this.setHelpUrl("");
  4988. }
  4989. };
  4990. Blockly.Python['iot_service_tuya_setup'] = function (block) {
  4991. var access_id = Blockly.Python.valueToCode(block, 'access_id', Blockly.Python.ORDER_ATOMIC);
  4992. var access_secret = Blockly.Python.valueToCode(block, 'access_secret', Blockly.Python.ORDER_ATOMIC);
  4993. Blockly.Python.definitions_['import_iot_service_tuya_setup'] = '' +
  4994. '\n' +
  4995. 'import tuya\n' +
  4996. 'import json\n' +
  4997. '\n' +
  4998. '\n' +
  4999. 'access_id = ' + access_id + '\n' +
  5000. 'access_secret = ' + access_secret + '\n' +
  5001. '\n' +
  5002. 'def getAccessToken():\n' +
  5003. ' global access_id, access_secret\n' +
  5004. ' return tuya.setToken(access_id,access_secret)\n' +
  5005. '\n' +
  5006. '\n' +
  5007. 'def getTuyaDeviceList():\n' +
  5008. ' deviceList = tuya.getData(\"/v1.0/iot-01/associated-users/devices\")\n' +
  5009. ' dlist = []\n' +
  5010. ' for i in range(len(deviceList["result"]["devices"])):\n' +
  5011. ' dlist.append({\"id\":deviceList[\"result\"][\"devices\"][i][\"id\"],\"name\":deviceList[\"result\"][\"devices\"][i][\"name\"]})\n' +
  5012. ' return dlist\n' +
  5013. '\n' +
  5014. '\n' +
  5015. 'def getTuyaTempAndHumValue(url,sign):\n' +
  5016. ' deviceInfo = tuya.getData(url)\n' +
  5017. ' tuyaValue = 0.0\n' +
  5018. ' for i in range(3):\n' +
  5019. ' if sign == 0 and deviceInfo["result"][i]["code"] == \"va_temperature\":\n' +
  5020. ' tuyaValue = deviceInfo["result"][i]["value"] / 100\n' +
  5021. ' break\n' +
  5022. ' if sign == 1 and deviceInfo["result"][i]["code"] == \"va_humidity\":\n' +
  5023. ' tuyaValue = deviceInfo["result"][i]["value"] / 100\n' +
  5024. ' break\n' +
  5025. ' return tuyaValue\n' +
  5026. '\n' +
  5027. '\n' +
  5028. 'def rgb2hsv(r, g, b):\n' +
  5029. ' r, g, b = r/255.0, g/255.0, b/255.0\n' +
  5030. ' mx = max(r, g, b)\n' +
  5031. ' mn = min(r, g, b)\n' +
  5032. ' m = mx-mn\n' +
  5033. ' if mx == mn:\n' +
  5034. ' h = 1\n' +
  5035. ' elif mx == r:\n' +
  5036. ' if g >= b:\n' +
  5037. ' h = ((g-b)/m)*60\n' +
  5038. ' else:\n' +
  5039. ' h = ((g-b)/m)*60 + 360\n' +
  5040. ' elif mx == g:\n' +
  5041. ' h = ((b-r)/m)*60 + 120\n' +
  5042. ' elif mx == b:\n' +
  5043. ' h = ((r-g)/m)*60 + 240\n' +
  5044. ' if mx == 0:\n' +
  5045. ' s = 1\n' +
  5046. ' else:\n' +
  5047. ' s = m/mx\n' +
  5048. ' v = mx\n' +
  5049. ' H = h * 1.0\n' +
  5050. ' S = s * 255.0\n' +
  5051. ' V = v * 255.0\n' +
  5052. ' return str({\"h\":H,\"s\":S,\"v\":V})\n' +
  5053. '\n' +
  5054. '';
  5055. var code = '';
  5056. return code;
  5057. };
  5058. Blockly.Blocks['iot_service_tuya_setToken'] = {
  5059. init: function () {
  5060. this.appendDummyInput()
  5061. .appendField(Blockly.Msg.iot_service_tuya_setToken_text);
  5062. this.appendStatementInput("NAME")
  5063. .setCheck(null)
  5064. .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  5065. this.setPreviousStatement(true, null);
  5066. this.setNextStatement(true, null);
  5067. this.setColour(tuya_BLOCK_COLOR);
  5068. this.setTooltip(Blockly.Msg.iot_service_tuya_setToken_TOOLTIP);
  5069. this.setHelpUrl("");
  5070. }
  5071. };
  5072. Blockly.Python['iot_service_tuya_setToken'] = function (block) {
  5073. var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  5074. var code = '' +
  5075. 'if (getAccessToken() == True):\n' +
  5076. statements_name +
  5077. '';
  5078. return code;
  5079. };
  5080. Blockly.Blocks['iot_service_tuya_getDeviceList'] = {
  5081. init: function () {
  5082. this.appendDummyInput()
  5083. .appendField(Blockly.Msg.iot_service_tuya_getDeviceList_text);
  5084. this.setOutput(true, null);
  5085. this.setColour(tuya_BLOCK_COLOR);
  5086. this.setTooltip(Blockly.Msg.iot_service_tuya_setToken_TOOLTIP);
  5087. this.setHelpUrl("");
  5088. }
  5089. };
  5090. Blockly.Python['iot_service_tuya_getDeviceList'] = function (block) {
  5091. var code = 'getTuyaDeviceList()';
  5092. return [code, Blockly.Python.ORDER_NONE];
  5093. };
  5094. Blockly.Blocks['iot_service_tuya_controll_light_belt'] = {
  5095. init: function () {
  5096. this.appendDummyInput()
  5097. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_title);
  5098. this.appendValueInput("device_id")
  5099. .setCheck(null)
  5100. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_device_id);
  5101. this.appendDummyInput()
  5102. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_des)
  5103. .appendField(new Blockly.FieldDropdown([
  5104. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_0, "0"],
  5105. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_1, "1"],
  5106. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_2, "2"],
  5107. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_3, "3"],
  5108. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_4, "4"],
  5109. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_5, "5"],
  5110. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_6, "6"],
  5111. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_7, "7"],
  5112. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_8, "8"],
  5113. [Blockly.Msg.iot_service_tuya_controll_light_belt_status_9, "9"]
  5114. ]), "status");
  5115. this.setInputsInline(false);
  5116. this.setPreviousStatement(true, null);
  5117. this.setNextStatement(true, null);
  5118. this.setColour(tuya_BLOCK_COLOR);
  5119. this.setTooltip(Blockly.Msg.iot_service_tuya_controll_light_belt_TOOLTIP);
  5120. this.setHelpUrl("");
  5121. }
  5122. };
  5123. Blockly.Python['iot_service_tuya_controll_light_belt'] = function (block) {
  5124. var dropdown_type = block.getFieldValue('status');
  5125. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  5126. var code = '';
  5127. if (dropdown_type == "0") {
  5128. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"switch_led\",\"value\": false}]}')\n";
  5129. }
  5130. else if (dropdown_type == "1") {
  5131. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"switch_led\",\"value\": true}]}')\n";
  5132. }
  5133. else if (dropdown_type == "2") {
  5134. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"flash_scene_1\",\"value\": {\"bright\":255,\"frequency\":80,\"hsv\":[{\"h\":120.0,\"s\":255.0,\"v\":255.0}],\"temperature\":255}}]}')\n";
  5135. }
  5136. else if (dropdown_type == "3") {
  5137. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"flash_scene_2\",\"value\": {\"bright\":255,\"frequency\":190,\"hsv\":[{\"h\":0.0,\"s\":255.0,\"v\":255.0},{\"h\":120.0,\"s\":255.0,\"v\":255.0},{\"h\":240.0,\"s\":255.0,\"v\":255.0},{\"h\":54.8,\"s\":255.0,\"v\":255.0},{\"h\":183.1,\"s\":255.0,\"v\":255.0},{\"h\":288.0,\"s\":255.0,\"v\":255.0}],\"temperature\":255}}]}')\n";
  5138. }
  5139. else if (dropdown_type == "4") {
  5140. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"flash_scene_3\",\"value\": {\"bright\":255,\"frequency\":80,\"hsv\":[{\"h\":0.0,\"s\":255.0,\"v\":255.0}],\"temperature\":255}}]}')\n";
  5141. }
  5142. else if (dropdown_type == "5") {
  5143. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"flash_scene_4\",\"value\": {\"bright\":255,\"frequency\":55,\"hsv\":[{\"h\":0.0,\"s\":255.0,\"v\":255.0},{\"h\":120.0,\"s\":255.0,\"v\":255.0},{\"h\":60.0,\"s\":255.0,\"v\":255.0},{\"h\":300.0,\"s\":255.0,\"v\":255.0},{\"h\":240.0,\"s\":255.0,\"v\":255.0},{\"h\":0.0,\"s\":255.0,\"v\":255.0}],\"temperature\":255}}]}')\n";
  5144. }
  5145. else if (dropdown_type == "6") {
  5146. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"scene_data\",\"value\": {\"h\":37.5,\"s\":255.0,\"v\":189.0}}]}')\n";
  5147. }
  5148. else if (dropdown_type == "7") {
  5149. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"scene_data\",\"value\": {\"h\":37.5,\"s\":8.0,\"v\":255.0}}]}')\n";
  5150. }
  5151. else if (dropdown_type == "8") {
  5152. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"scene_data\",\"value\": {\"h\":16.2,\"s\":255.0,\"v\":207.0}}]}')\n";
  5153. }
  5154. else {
  5155. code += "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"scene_data\",\"value\": {\"h\":226.0,\"s\":175.7,\"v\":180.0}}]}')\n";
  5156. }
  5157. return code;
  5158. };
  5159. Blockly.Blocks['iot_service_tuya_controll_light_belt_color_value'] = {
  5160. init: function () {
  5161. this.appendDummyInput()
  5162. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_color_value_title);
  5163. this.appendValueInput("device_id")
  5164. .setCheck(null)
  5165. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_device_id);
  5166. this.appendValueInput("COLOR")
  5167. .setCheck(null)
  5168. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_color_value_title1);
  5169. this.setInputsInline(false);
  5170. this.setPreviousStatement(true, null);
  5171. this.setNextStatement(true, null);
  5172. this.setColour(tuya_BLOCK_COLOR);
  5173. this.setTooltip(Blockly.Msg.iot_service_tuya_controll_light_belt_color_value_TOOLTIP);
  5174. this.setHelpUrl("");
  5175. }
  5176. };
  5177. Blockly.Python['iot_service_tuya_controll_light_belt_color_value'] = function (block) {
  5178. var COLOR = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC).split("(")[2].split(")")[0];
  5179. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  5180. // TODO: Assemble Python into code variable.
  5181. var code = "tuya.postData(\"/v1.0/devices/\"+" + device_id + "+\"/commands\",'{\"commands\": [{\"code\": \"work_mode\",\"value\": \"colour\"},{\"code\": \"colour_data\",\"value\": '+ rgb2hsv(" + COLOR + ") + '}]}')\n";
  5182. // TODO: Change ORDER_NONE to the correct strength.
  5183. return code;
  5184. };
  5185. Blockly.Blocks['iot_service_tuya_get_temperature_humidity_data'] = {
  5186. init: function () {
  5187. this.appendDummyInput()
  5188. .appendField(Blockly.Msg.KUJU_get_temperature_humidity_data_title)
  5189. .appendField(new Blockly.FieldDropdown([
  5190. [Blockly.Msg.basic_temperature, "temperature"],
  5191. [Blockly.Msg.basic_humidity, "humidity"]
  5192. // [Blockly.Msg.basic_pressure, "pressure"]
  5193. ]), "env_get_type")
  5194. .appendField(Blockly.Msg.basic_env_value);
  5195. this.appendValueInput("device_id")
  5196. .setCheck(null)
  5197. .appendField(Blockly.Msg.iot_service_tuya_controll_light_belt_device_id);
  5198. this.setInputsInline(false);
  5199. this.setOutput(true, null);
  5200. this.setColour(tuya_BLOCK_COLOR);
  5201. this.setTooltip(Blockly.Msg.iot_service_KUJU_get_temperature_humidity_data_TOOLTIP);
  5202. this.setHelpUrl("");
  5203. }
  5204. };
  5205. Blockly.Python['iot_service_tuya_get_temperature_humidity_data'] = function (block) {
  5206. var dropdown_type = block.getFieldValue('env_get_type');
  5207. var device_id = Blockly.Python.valueToCode(block, 'device_id', Blockly.Python.ORDER_ATOMIC);
  5208. var code = '';
  5209. if (dropdown_type == "temperature") {
  5210. code = "getTuyaTempAndHumValue(\"/v1.0/devices/\"+" + device_id + "+\"/status\",0)";
  5211. }
  5212. if (dropdown_type == "humidity") {
  5213. code = "getTuyaTempAndHumValue(\"/v1.0/devices/\"+" + device_id + "+\"/status\",1)";
  5214. }
  5215. return [code, Blockly.Python.ORDER_CONDITIONAL];
  5216. };
  5217. // cococloud
  5218. var COCOCLOUD_BLOCK_COLOR = "#4085de";
  5219. Blockly.Blocks['iot_service_cococloud'] = {
  5220. init: function () {
  5221. this.appendDummyInput()
  5222. .appendField(new Blockly.FieldImage("blockly/media/cococloud_send.png", 180, 65, { alt: "*", flipRtl: "FALSE" }));
  5223. this.appendDummyInput()
  5224. .appendField(Blockly.Msg.iotservice_cococloud_send_title);
  5225. this.appendDummyInput()
  5226. .appendField(Blockly.Msg.iotservice_cococloud_send_title_api)
  5227. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_API_KEY"), "t_api");
  5228. /*this.appendValueInput("first_input")
  5229. .setCheck(null)
  5230. .appendField("Field 0");*/
  5231. this.itemCount_ = 1;
  5232. this.updateShape_();
  5233. this.setMutator(new Blockly.Mutator(['iot_service_cococloud_create_with_item']));
  5234. this.setColour(COCOCLOUD_BLOCK_COLOR);
  5235. this.setPreviousStatement(true, null);
  5236. this.setNextStatement(true, null);
  5237. this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_TOOLTIP);
  5238. this.setHelpUrl("");
  5239. },
  5240. mutationToDom: function () {
  5241. var container = document.createElement('mutation');
  5242. container.setAttribute('items', this.itemCount_);
  5243. return container;
  5244. },
  5245. domToMutation: function (xmlElement) {
  5246. this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
  5247. this.updateShape_();
  5248. },
  5249. decompose: function (workspace) {
  5250. var containerBlock = workspace.newBlock('iot_service_cococloud_create_with_container');
  5251. containerBlock.initSvg();
  5252. var connection = containerBlock.getInput('STACK').connection;
  5253. for (var i = 0; i < this.itemCount_; i++) {
  5254. var itemBlock = workspace.newBlock('iot_service_cococloud_create_with_item');
  5255. itemBlock.initSvg();
  5256. connection.connect(itemBlock.previousConnection);
  5257. connection = itemBlock.nextConnection;
  5258. }
  5259. return containerBlock;
  5260. },
  5261. compose: function (containerBlock) {
  5262. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  5263. // Count number of inputs.
  5264. var connections = [];
  5265. while (itemBlock) {
  5266. connections.push(itemBlock.valueConnection_);
  5267. itemBlock = itemBlock.nextConnection &&
  5268. itemBlock.nextConnection.targetBlock();
  5269. }
  5270. // Disconnect any children that don't belong.
  5271. for (var i = 0; i < this.itemCount_; i++) {
  5272. var connection = this.getInput('ADD' + i).connection.targetConnection;
  5273. if (connection && connections.indexOf(connection) == -1) {
  5274. connection.disconnect();
  5275. }
  5276. }
  5277. this.itemCount_ = connections.length;
  5278. this.updateShape_();
  5279. // Reconnect any child blocks.
  5280. for (var i = 0; i < this.itemCount_; i++) {
  5281. Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
  5282. }
  5283. },
  5284. saveConnections: function (containerBlock) {
  5285. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  5286. var i = 0;
  5287. while (itemBlock) {
  5288. var input = this.getInput('ADD' + i);
  5289. itemBlock.valueConnection_ = input && input.connection.targetConnection;
  5290. i++;
  5291. itemBlock = itemBlock.nextConnection &&
  5292. itemBlock.nextConnection.targetBlock();
  5293. }
  5294. },
  5295. updateShape_: function () {
  5296. for (var i = 0; i < this.itemCount_; i++) {
  5297. if (!this.getInput('ADD' + i)) {
  5298. var input = this.appendValueInput('ADD' + i);
  5299. input.appendField(Blockly.Msg.iotservice_cococloud_send_property)
  5300. .appendField(new Blockly.FieldTextInput("Property" + i), "field" + i);
  5301. //input.appendField("資料 " + (i + 1) + ":");
  5302. //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
  5303. // input.appendField(new Blockly.FieldTextInput("資料" + (i + 1)), 'FIELD' + i)
  5304. }
  5305. }
  5306. while (this.getInput('ADD' + i)) {
  5307. this.removeInput('ADD' + i);
  5308. i++;
  5309. }
  5310. },
  5311. };
  5312. Blockly.Blocks['iot_service_cococloud_create_with_container'] = {
  5313. init: function () {
  5314. this.setColour(COCOCLOUD_BLOCK_COLOR);
  5315. this.appendDummyInput()
  5316. .appendField("Items");
  5317. this.appendStatementInput('STACK');
  5318. this.setTooltip('');
  5319. this.contextMenu = false;
  5320. }
  5321. };
  5322. Blockly.Blocks['iot_service_cococloud_create_with_item'] = {
  5323. init: function () {
  5324. this.setColour(COCOCLOUD_BLOCK_COLOR);
  5325. this.appendDummyInput()
  5326. .appendField("Field");
  5327. this.setPreviousStatement(true);
  5328. this.setNextStatement(true);
  5329. this.setTooltip('');
  5330. this.contextMenu = false;
  5331. }
  5332. };
  5333. Blockly.Python['iot_service_cococloud'] = function (block) {
  5334. var api = block.getFieldValue('t_api');
  5335. Blockly.Python.addVariable('_COCOCLOUD_SEND_REQUEST', '_COCOCLOUD_SEND_REQUEST = None', true);
  5336. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5337. // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";
  5338. var item_field = '',
  5339. item_value = '';
  5340. var cococloud_data = cococloud_data = '{';
  5341. for (var n = 0; n < this.itemCount_; n++) {
  5342. console.log(block.getFieldValue("field" + n))
  5343. item_field = block.getFieldValue("field" + n);
  5344. item_value = Blockly.Python.valueToCode(this, 'ADD' + n, Blockly.Python.ORDER_NONE) || '';
  5345. cococloud_data += `"${item_field}":${item_value},`
  5346. // cococloud_data += "+ item_field + '":"\' + str(' + item_value + ') + \'",';
  5347. }
  5348. var cococloud_data_final = cococloud_data.slice(0, -1) + '}';
  5349. var code = `
  5350. _COCOCLOUD_SEND_ENDPOINT = "http://api.cocorobo.cn/iot/data/eventAPIKeyJson/${api}"
  5351. _COCOCLOUD_SEND_DATA = ${cococloud_data_final}
  5352. try:
  5353. _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, json = _COCOCLOUD_SEND_DATA , headers = { "Content-type": "application/json" }, timeout = 60)
  5354. print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
  5355. except BaseException as e:
  5356. print(e)
  5357. pass
  5358. `
  5359. return code;
  5360. };
  5361. Blockly.Blocks['v831_service_cococloud'] = {
  5362. init: function () {
  5363. this.appendDummyInput()
  5364. .appendField(new Blockly.FieldImage("blockly/media/cococloud_send.png", 180, 65, { alt: "*", flipRtl: "FALSE" }));
  5365. this.appendDummyInput()
  5366. .appendField(Blockly.Msg.iotservice_cococloud_send_title);
  5367. this.appendDummyInput()
  5368. .appendField(Blockly.Msg.iotservice_cococloud_send_title_api)
  5369. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_API_KEY"), "t_api");
  5370. /*this.appendValueInput("first_input")
  5371. .setCheck(null)
  5372. .appendField("Field 0");*/
  5373. this.itemCount_ = 1;
  5374. this.updateShape_();
  5375. this.setMutator(new Blockly.Mutator(['iot_service_cococloud_create_with_item']));
  5376. this.setColour(COCOCLOUD_BLOCK_COLOR);
  5377. this.setPreviousStatement(true, null);
  5378. this.setNextStatement(true, null);
  5379. this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_TOOLTIP);
  5380. this.setHelpUrl("");
  5381. },
  5382. mutationToDom: function () {
  5383. var container = document.createElement('mutation');
  5384. container.setAttribute('items', this.itemCount_);
  5385. return container;
  5386. },
  5387. domToMutation: function (xmlElement) {
  5388. this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
  5389. this.updateShape_();
  5390. },
  5391. decompose: function (workspace) {
  5392. var containerBlock = workspace.newBlock('iot_service_cococloud_create_with_container');
  5393. containerBlock.initSvg();
  5394. var connection = containerBlock.getInput('STACK').connection;
  5395. for (var i = 0; i < this.itemCount_; i++) {
  5396. var itemBlock = workspace.newBlock('iot_service_cococloud_create_with_item');
  5397. itemBlock.initSvg();
  5398. connection.connect(itemBlock.previousConnection);
  5399. connection = itemBlock.nextConnection;
  5400. }
  5401. return containerBlock;
  5402. },
  5403. compose: function (containerBlock) {
  5404. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  5405. // Count number of inputs.
  5406. var connections = [];
  5407. while (itemBlock) {
  5408. connections.push(itemBlock.valueConnection_);
  5409. itemBlock = itemBlock.nextConnection &&
  5410. itemBlock.nextConnection.targetBlock();
  5411. }
  5412. // Disconnect any children that don't belong.
  5413. for (var i = 0; i < this.itemCount_; i++) {
  5414. var connection = this.getInput('KEY' + i).connection.targetConnection;
  5415. if (connection && connections.indexOf(connection) == -1) {
  5416. connection.disconnect();
  5417. }
  5418. }
  5419. this.itemCount_ = connections.length;
  5420. this.updateShape_();
  5421. // Reconnect any child blocks.
  5422. for (var i = 0; i < this.itemCount_; i++) {
  5423. Blockly.Mutator.reconnect(connections[i], this, 'KEY' + i);
  5424. }
  5425. },
  5426. saveConnections: function (containerBlock) {
  5427. var itemBlock = containerBlock.getInputTargetBlock('STACK');
  5428. var i = 0;
  5429. while (itemBlock) {
  5430. var input = this.getInput('KEY' + i);
  5431. itemBlock.valueConnection_ = input && input.connection.targetConnection;
  5432. i++;
  5433. itemBlock = itemBlock.nextConnection &&
  5434. itemBlock.nextConnection.targetBlock();
  5435. }
  5436. },
  5437. updateShape_: function () {
  5438. for (var i = 0; i < this.itemCount_; i++) {
  5439. if (!this.getInput('KEY' + i) && !this.getInput('ADD' + i)) {
  5440. var input = this.appendValueInput('KEY' + i);
  5441. input.appendField(Blockly.Msg.iotservice_cococloud_send_property)
  5442. // .appendField(new Blockly.FieldValueInput("KEY" + i));
  5443. var ADD = this.appendValueInput("ADD" + i)
  5444. ADD.appendField(Blockly.Msg.iotservice_cococloud_send_property_1)
  5445. }
  5446. }
  5447. while (this.getInput('KEY' + i) && this.getInput('ADD' + i)) {
  5448. this.removeInput('KEY' + i);
  5449. this.removeInput('ADD' + i);
  5450. i++;
  5451. }
  5452. },
  5453. };
  5454. Blockly.Python['v831_service_cococloud'] = function (block) {
  5455. var api = block.getFieldValue('t_api');
  5456. Blockly.Python.addVariable('_COCOCLOUD_SEND_REQUEST', '_COCOCLOUD_SEND_REQUEST = None', true);
  5457. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5458. // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";
  5459. var item_field = '',
  5460. item_value = '';
  5461. var cococloud_data = cococloud_data = '{';
  5462. for (var n = 0; n < this.itemCount_; n++) {
  5463. item_field = Blockly.Python.valueToCode(this, 'KEY' + n, Blockly.Python.ORDER_NONE) || '';
  5464. item_value = Blockly.Python.valueToCode(this, 'ADD' + n, Blockly.Python.ORDER_NONE) || '';
  5465. cococloud_data += `${item_field}:${item_value},`
  5466. // cococloud_data += "+ item_field + '":"\' + str(' + item_value + ') + \'",';
  5467. }
  5468. var cococloud_data_final = cococloud_data.slice(0, -1) + '}';
  5469. console.log(cococloud_data_final)
  5470. var code = `
  5471. _COCOCLOUD_SEND_ENDPOINT = "http://api.cocorobo.cn/iot/data/eventAPIKeyJson/${api}"
  5472. _COCOCLOUD_SEND_DATA = ${cococloud_data_final}
  5473. try:
  5474. _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, json = _COCOCLOUD_SEND_DATA , headers = { "Content-type": "application/json" }, timeout = 60)
  5475. print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
  5476. except BaseException as e:
  5477. print(e)
  5478. pass
  5479. `;
  5480. return code;
  5481. };
  5482. Blockly.Blocks['iot_service_cococloud_read'] = {
  5483. init: function () {
  5484. this.appendDummyInput()
  5485. .appendField(new Blockly.FieldImage("blockly/media/cococloud_get.png", 200, 70, { alt: "*", flipRtl: "FALSE" }));
  5486. this.appendDummyInput()
  5487. .appendField(Blockly.Msg.iotservice_cococloud_get_title);
  5488. this.appendDummyInput()
  5489. .appendField(Blockly.Msg.iotservice_cococloud_get_api)
  5490. .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_API_KEY"), "api");
  5491. this.setInputsInline(false);
  5492. this.setPreviousStatement(true, null);
  5493. this.setNextStatement(true, null);
  5494. this.setColour(COCOCLOUD_BLOCK_COLOR);
  5495. this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_Read_TOOLTIP);
  5496. this.setHelpUrl("");
  5497. }
  5498. };
  5499. Blockly.Python['iot_service_cococloud_read'] = function (block) {
  5500. var api = block.getFieldValue('api');
  5501. Blockly.Python.addVariable('_COCOCLOUD_READ_REQUEST', '_COCOCLOUD_READ_REQUEST = None', true);
  5502. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5503. // TODO: Assemble Python into code variable.
  5504. var code = '_COCOCLOUD_READ_REQUEST = requests.get("http://api.cocorobo.cn/iot/data/eventAPIKeyJson/" + "' + api + '", timeout=60)\n';
  5505. return code;
  5506. };
  5507. Blockly.Blocks['iot_service_cococloud_read_data'] = {
  5508. init: function () {
  5509. this.appendDummyInput()
  5510. .appendField(Blockly.Msg.iotservice_cococloud_get_property);
  5511. this.appendValueInput("property")
  5512. .setCheck(null);
  5513. this.appendDummyInput()
  5514. .appendField(Blockly.Msg.iotservice_cococloud_get_data);
  5515. this.setInputsInline(true);
  5516. this.setOutput(true, null);
  5517. this.setColour(COCOCLOUD_BLOCK_COLOR);
  5518. this.setTooltip(Blockly.Msg.Iot_Service_Cococloud_Read_Data_TOOLTIP);
  5519. this.setHelpUrl("");
  5520. }
  5521. };
  5522. Blockly.Python['iot_service_cococloud_read_data'] = function (block) {
  5523. var property = Blockly.Python.valueToCode(block, 'property', Blockly.Python.ORDER_ATOMIC);
  5524. // TODO: Assemble Python into code variable.
  5525. var code = '_COCOCLOUD_READ_REQUEST.json()[\'data\'][0][' + property + ']';
  5526. // TODO: Change ORDER_NONE to the correct strength.
  5527. return [code, Blockly.Python.ORDER_NONE];
  5528. };
  5529. /*
  5530. __ _ _ __ _
  5531. /\ \ \___| |___ _____ _ __| | __ /__\ ___ __ _ _ _ ___ ___| |_
  5532. / \/ / _ \ __\ \ /\ / / _ \| '__| |/ / / \/// _ \/ _` | | | |/ _ \/ __| __|
  5533. / /\ / __/ |_ \ V V / (_) | | | < / _ \ __/ (_| | |_| | __/\__ \ |_
  5534. \_\ \/ \___|\__| \_/\_/ \___/|_| |_|\_\ \/ \_/\___|\__, |\__,_|\___||___/\__|
  5535. |_|
  5536. */
  5537. var NETWORK_BLOCK_COLOR = "#16318a";
  5538. Blockly.Blocks['esp32_network_http_get'] = {
  5539. init: function () {
  5540. this.appendDummyInput()
  5541. .appendField(new Blockly.FieldImage("blockly/media/http_header_get.png", 180, 50, { alt: "*", flipRtl: "FALSE" }));
  5542. this.appendDummyInput()
  5543. .appendField(Blockly.Msg.internet_http_get_title);
  5544. this.appendValueInput("http_get_url")
  5545. .setCheck(null)
  5546. .appendField(Blockly.Msg.internet_http_get_url);
  5547. this.setInputsInline(false);
  5548. this.setPreviousStatement(true, null);
  5549. this.setNextStatement(true, null);
  5550. this.setColour(NETWORK_BLOCK_COLOR);
  5551. this.setTooltip(Blockly.Msg.Esp32_Network_Http_Get_TOOLTIP);
  5552. this.setHelpUrl("");
  5553. }
  5554. };
  5555. Blockly.Python['esp32_network_http_get'] = function (block) {
  5556. var url = Blockly.Python.valueToCode(block, 'http_get_url', Blockly.Python.ORDER_ATOMIC);
  5557. Blockly.Python.addVariable('_SEND_HTTP_GET_ENDPOINT', '', true);
  5558. Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);
  5559. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5560. Blockly.Python.definitions_['v831_import_json'] = `import json`;
  5561. Blockly.Python.definitions_['v831_import_SEND_HTTP'] = `_SEND_HTTP_GET_ENDPOINT = ${url}`;
  5562. // TODO: Assemble Python into code variable.
  5563. var code = '_SEND_HTTP_REQUEST = requests.get(_SEND_HTTP_GET_ENDPOINT)\n';
  5564. return code;
  5565. };
  5566. Blockly.Blocks['esp32_network_http_post'] = {
  5567. init: function () {
  5568. this.appendDummyInput()
  5569. .appendField(new Blockly.FieldImage("blockly/media/http_header_post.png", 180, 50, { alt: "*", flipRtl: "FALSE" }));
  5570. this.appendDummyInput()
  5571. .appendField(Blockly.Msg.internet_http_post_title);
  5572. this.appendValueInput("http_post_url")
  5573. .setCheck(null)
  5574. .appendField(Blockly.Msg.internet_http_post_url);
  5575. this.appendValueInput("data")
  5576. .setCheck(null)
  5577. .appendField(Blockly.Msg.internet_http_post_json);
  5578. this.setInputsInline(false);
  5579. this.setPreviousStatement(true, null);
  5580. this.setNextStatement(true, null);
  5581. this.setColour(NETWORK_BLOCK_COLOR);
  5582. this.setTooltip(Blockly.Msg.Esp32_Network_Http_Post_TOOLTIP);
  5583. this.setHelpUrl("");
  5584. }
  5585. };
  5586. Blockly.Python['esp32_network_http_post'] = function (block) {
  5587. var url = Blockly.Python.valueToCode(block, 'http_post_url', Blockly.Python.ORDER_ATOMIC);
  5588. var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  5589. Blockly.Python.addVariable('_SEND_HTTP_POST_ENDPOINT', '', true);
  5590. Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);
  5591. Blockly.Python.definitions_['831_import_requests'] = `import requests`
  5592. Blockly.Python.definitions_['831_import_json'] = `import json`
  5593. Blockly.Python.definitions_['import_urequests'] = '' +
  5594. '_SEND_HTTP_POST_ENDPOINT = ' + url + '\n' +
  5595. '';
  5596. // TODO: Assemble Python into code variable.
  5597. // var code = '' +
  5598. // '_SEND_HTTP_POST_DATA = \'' + data + '\'\n' +
  5599. // '_SEND_HTTP_REQUEST = requests.post(_SEND_HTTP_POST_ENDPOINT, data = _SEND_HTTP_POST_DATA , headers = { "Content-type": "application/json" })\n' +
  5600. // '';
  5601. var code = `_SEND_HTTP_POST_DATA = ${data}
  5602. _SEND_HTTP_REQUEST = requests.post(_SEND_HTTP_POST_ENDPOINT, json = _SEND_HTTP_POST_DATA , headers = { "Content-type": "application/json" })
  5603. `
  5604. return code;
  5605. };
  5606. Blockly.Blocks['esp32_network_http_get_data_from_local_server'] = {
  5607. init: function () {
  5608. this.appendDummyInput()
  5609. .appendField(Blockly.Msg.internet_http_get_server_data_title);
  5610. this.appendDummyInput()
  5611. .appendField(Blockly.Msg.internet_http_get_server_data_type)
  5612. .appendField(new Blockly.FieldDropdown([
  5613. [Blockly.Msg.internet_http_get_server_data_json, "json"],
  5614. [Blockly.Msg.internet_http_get_server_data_text, "text"]
  5615. ]), "type");
  5616. this.setInputsInline(false);
  5617. this.setOutput(true, null);
  5618. this.setColour(NETWORK_BLOCK_COLOR);
  5619. var thisBlock = this;
  5620. this.setTooltip(function () {
  5621. var mode = thisBlock.getFieldValue('type');
  5622. var TOOLTIPS = {
  5623. 'json': Blockly.Msg.Esp32_Network_Http_Get_Data_From_Local_Server_TOOLTIP.replace('%1', Blockly.Msg.internet_http_get_server_data_json),
  5624. 'text': Blockly.Msg.Esp32_Network_Http_Get_Data_From_Local_Server_TOOLTIP.replace('%1', Blockly.Msg.internet_http_get_server_data_text)
  5625. };
  5626. return TOOLTIPS[mode];
  5627. });
  5628. this.setHelpUrl("");
  5629. }
  5630. };
  5631. Blockly.Python['esp32_network_http_get_data_from_local_server'] = function (block) {
  5632. var dropdown_type = block.getFieldValue('type');
  5633. // TODO: Assemble Python into code variable.
  5634. if (dropdown_type == "text") {
  5635. var request_code = "_SEND_HTTP_REQUEST.text";
  5636. } else if (dropdown_type == "json") {
  5637. var request_code = "eval(_SEND_HTTP_REQUEST.text)";
  5638. }
  5639. var code = request_code;
  5640. // TODO: Change ORDER_NONE to the correct strength.
  5641. return [code, Blockly.Python.ORDER_NONE];
  5642. };
  5643. Blockly.Blocks['esp32_network_http_server_setup'] = {
  5644. init: function () {
  5645. this.appendDummyInput()
  5646. .appendField(new Blockly.FieldImage("blockly/media/http_server_header.png", 130, 40, { alt: "*", flipRtl: "FALSE" }));
  5647. this.appendDummyInput()
  5648. .appendField(Blockly.Msg.wifi_web_http_server_setup);
  5649. this.setInputsInline(false);
  5650. this.setPreviousStatement(true, null);
  5651. this.setNextStatement(true, null);
  5652. this.setColour(NETWORK_BLOCK_COLOR);
  5653. this.setTooltip(Blockly.Msg.Esp32_Network_Http_Server_Setup_TOOLTIP);
  5654. this.setHelpUrl("");
  5655. }
  5656. };
  5657. Blockly.Python['esp32_network_http_server_setup'] = function (block) {
  5658. // TODO: Assemble Python into code variable.
  5659. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5660. Blockly.Python.definitions_['esp32_network_http_server_setup_def_setup'] = '' +
  5661. 'from microWebSrv import MicroWebSrv\n' +
  5662. '';
  5663. var code = '';
  5664. return code;
  5665. };
  5666. Blockly.Blocks['esp32_network_http_server_route'] = {
  5667. init: function () {
  5668. this.appendDummyInput()
  5669. .appendField(Blockly.Msg.wifi_web_http_server_route_setting_title);
  5670. this.appendDummyInput()
  5671. .appendField(Blockly.Msg.wifi_web_http_server_route_setting_path)
  5672. .appendField(new Blockly.FieldTextInput("/"), "path")
  5673. .appendField(Blockly.Msg.wifi_web_http_server_route_setting_being_requested);
  5674. this.appendDummyInput()
  5675. .appendField(Blockly.Msg.wifi_web_http_server_route_setting_property)
  5676. .appendField(new Blockly.FieldDropdown([
  5677. [Blockly.Msg.wifi_web_http_server_route_setting_get, "get"],
  5678. [Blockly.Msg.wifi_web_http_server_route_setting_post, "post"]
  5679. ]), "response_type");
  5680. this.appendStatementInput("exec")
  5681. .setCheck(null)
  5682. .appendField(Blockly.Msg.wifi_web_http_server_route_setting_do);
  5683. this.setInputsInline(false);
  5684. this.setPreviousStatement(true, null);
  5685. this.setNextStatement(true, null);
  5686. this.setColour(NETWORK_BLOCK_COLOR);
  5687. // this.setTooltip("");
  5688. this.setHelpUrl("");
  5689. var thisBlock = this;
  5690. this.setTooltip(function () {
  5691. var mode = thisBlock.getFieldValue('response_type');
  5692. var TOOLTIPS = {
  5693. 'get': Blockly.Msg.Esp32_Network_Http_Server_Route_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_route_setting_get),
  5694. 'post': Blockly.Msg.Esp32_Network_Http_Server_Route_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_route_setting_post)
  5695. };
  5696. return TOOLTIPS[mode];
  5697. });
  5698. }
  5699. };
  5700. Blockly.Python['esp32_network_http_server_route'] = function (block) {
  5701. var dropdown_response_type = block.getFieldValue('response_type');
  5702. var text_path = block.getFieldValue('path');
  5703. var statements_exec = Blockly.Python.statementToCode(block, 'exec');
  5704. var response_type = "";
  5705. var response_writeok = "";
  5706. if (dropdown_response_type == "get") {
  5707. response_type = "";
  5708. } else if (dropdown_response_type == "post") {
  5709. response_type = ", 'POST'";
  5710. }
  5711. /*Blockly.Python.addVariable('', '' +
  5712. '' +
  5713. '@MicroWebSrv.route(\'' + text_path + '\'' + response_type + ')\n' +
  5714. 'def _httpHandlerTestGet(httpClient, httpResponse):\n' +
  5715. statements_exec +
  5716. '', true);*/
  5717. Blockly.Python.definitions_['esp32_network_http_server_route_def_' + text_path.substring(1)] = '' +
  5718. '@MicroWebSrv.route(\'' + text_path + '\'' + response_type + ')\n' +
  5719. 'def _httpHandler' + text_path.substring(1) + 'Get(httpClient, httpResponse):\n' +
  5720. statements_exec +
  5721. '\n';
  5722. Blockly.Python.addSetup("server_route_setup", '' +
  5723. 'def _acceptWebSocketCallback(webSocket, httpClient) :\n' +
  5724. ' print("WS ACCEPT")\n' +
  5725. ' webSocket.RecvTextCallback = _recvTextCallback\n' +
  5726. ' webSocket.RecvBinaryCallback = _recvBinaryCallback\n' +
  5727. ' webSocket.ClosedCallback = _closedCallback\n' +
  5728. '\n' +
  5729. 'def _recvTextCallback(webSocket, msg) :\n' +
  5730. ' print("WS RECV TEXT : %s" % msg)\n' +
  5731. ' webSocket.SendText("Reply for %s" % msg)\n' +
  5732. '\n' +
  5733. 'def _recvBinaryCallback(webSocket, data) :\n' +
  5734. ' print("WS RECV DATA : %s" % data)\n' +
  5735. '\n' +
  5736. 'def _closedCallback(webSocket) :\n' +
  5737. ' print("WS CLOSED")\n' +
  5738. '\n' +
  5739. 'try:\n' +
  5740. ' srv = MicroWebSrv()\n' +
  5741. ' srv.Stop()\n' +
  5742. ' srv.MaxWebSocketRecvLen = 1024\n' +
  5743. ' srv.WebSocketThreaded = False\n' +
  5744. ' srv.AcceptWebSocketCallback = _acceptWebSocketCallback\n' +
  5745. ' srv.Start(threaded=True)\n' +
  5746. 'except BaseException as e:\n' +
  5747. ' print(str(e))\n' +
  5748. ' srv = MicroWebSrv()\n' +
  5749. ' srv.MaxWebSocketRecvLen = 1024\n' +
  5750. ' srv.WebSocketThreaded = False\n' +
  5751. ' srv.AcceptWebSocketCallback = _acceptWebSocketCallback\n' +
  5752. ' srv.Start(threaded=True)\n' +
  5753. '');
  5754. // TODO: Assemble Python into code variable.
  5755. var code = '';
  5756. return code;
  5757. };
  5758. Blockly.Blocks['esp32_network_http_server_route_respond'] = {
  5759. init: function () {
  5760. this.appendValueInput("exec")
  5761. .setCheck(null)
  5762. .appendField(Blockly.Msg.wifi_web_http_server_respond_title);
  5763. this.appendDummyInput()
  5764. .appendField(Blockly.Msg.wifi_web_http_server_respond_type)
  5765. .appendField(new Blockly.FieldDropdown([
  5766. [Blockly.Msg.wifi_web_http_server_respond_text, "text/plain"],
  5767. [Blockly.Msg.wifi_web_http_server_respond_json, "application/json"],
  5768. [Blockly.Msg.wifi_web_http_server_respond_html, "text/html"]
  5769. ]), "response_type");
  5770. this.setInputsInline(false);
  5771. this.setPreviousStatement(true, null);
  5772. this.setNextStatement(true, null);
  5773. this.setColour(NETWORK_BLOCK_COLOR);
  5774. var thisBlock = this;
  5775. this.setTooltip(function () {
  5776. var mode = thisBlock.getFieldValue('response_type');
  5777. var TOOLTIPS = {
  5778. 'text/plain': Blockly.Msg.Esp32_Network_Http_Server_Route_Respond_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_respond_text),
  5779. 'application/json': Blockly.Msg.Esp32_Network_Http_Server_Route_Respond_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_respond_json),
  5780. 'text/html': Blockly.Msg.Esp32_Network_Http_Server_Route_Respond_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_respond_html)
  5781. };
  5782. return TOOLTIPS[mode];
  5783. });
  5784. this.setHelpUrl("");
  5785. }
  5786. };
  5787. Blockly.Python['esp32_network_http_server_route_respond'] = function (block) {
  5788. var dropdown_response_type = block.getFieldValue('response_type');
  5789. var statements_exec = Blockly.Python.valueToCode(block, 'exec', Blockly.Python.ORDER_ATOMIC);
  5790. // TODO: Assemble Python into code variable.
  5791. var code = '' +
  5792. 'content = ' + statements_exec + '\n' +
  5793. 'httpResponse.WriteResponseOk( headers = None,\n' +
  5794. ' contentType = "' + dropdown_response_type + '",\n' +
  5795. ' contentCharset = "UTF-8",\n' +
  5796. ' content = str(content) )\n' +
  5797. '';
  5798. return code;
  5799. };
  5800. Blockly.Blocks['esp32_network_http_server_get_data'] = {
  5801. init: function () {
  5802. this.appendDummyInput()
  5803. .appendField(Blockly.Msg.wifi_web_http_server_get_title)
  5804. .appendField(new Blockly.FieldDropdown([
  5805. [Blockly.Msg.wifi_web_http_server_get_as_json, "json"],
  5806. [Blockly.Msg.wifi_web_http_server_get_as_text, "text"]
  5807. ]), "type");
  5808. this.setInputsInline(false);
  5809. this.setOutput(true, null);
  5810. this.setColour(NETWORK_BLOCK_COLOR);
  5811. var thisBlock = this;
  5812. this.setTooltip(function () {
  5813. var mode = thisBlock.getFieldValue('type');
  5814. var TOOLTIPS = {
  5815. 'json': Blockly.Msg.Esp32_Network_Http_Server_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_get_as_json),
  5816. 'text': Blockly.Msg.Esp32_Network_Http_Server_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_get_as_text)
  5817. };
  5818. return TOOLTIPS[mode];
  5819. });
  5820. this.setHelpUrl("");
  5821. }
  5822. };
  5823. Blockly.Python['esp32_network_http_server_get_data'] = function (block) {
  5824. var dropdown_type = block.getFieldValue('type');
  5825. if (dropdown_type == "json") {
  5826. var as_type = "ReadRequestContentAsJSON()";
  5827. } else if (dropdown_type == "text") {
  5828. var as_type = "ReadRequestContent(size=None)";
  5829. }
  5830. // TODO: Assemble Python into code variable.
  5831. var code = 'httpClient.' + as_type;
  5832. // TODO: Change ORDER_NONE to the correct strength.
  5833. return [code, Blockly.Python.ORDER_NONE];
  5834. };
  5835. var WS_BLOCK_COLOR = "#83178a";
  5836. Blockly.Blocks['esp32_web_ws_setup_send'] = {
  5837. init: function () {
  5838. this.appendDummyInput()
  5839. .appendField(new Blockly.FieldImage("blockly/media/ws_header_send.png", 220, 50, { alt: "*", flipRtl: "FALSE" }));
  5840. this.appendDummyInput()
  5841. .appendField(Blockly.Msg.internet_ws_setup_send_text);
  5842. this.appendDummyInput()
  5843. .appendField(Blockly.Msg.internet_ws_setup_send_ip)
  5844. .appendField(new Blockly.FieldTextInput("192.168.4.1"), "ip");
  5845. this.setInputsInline(false);
  5846. this.setPreviousStatement(true, null);
  5847. this.setNextStatement(true, null);
  5848. this.setColour(WS_BLOCK_COLOR);
  5849. this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Setup_Send_TOOLTIP);
  5850. this.setHelpUrl("");
  5851. }
  5852. };
  5853. Blockly.Python['esp32_web_ws_setup_send'] = function (block) {
  5854. var text_ip = block.getFieldValue('ip');
  5855. Blockly.Python.definitions_['ws_setup_send'] = '' +
  5856. 'import uwebsockets.client\n' +
  5857. '\n';
  5858. // TODO: Assemble Python into code variable.
  5859. var code = '_client_websocket = uwebsockets.client.connect("ws://' + text_ip + ':80")\n';
  5860. return code;
  5861. };
  5862. Blockly.Blocks['esp32_web_ws_send'] = {
  5863. init: function () {
  5864. this.appendValueInput("command")
  5865. .setCheck(null)
  5866. .appendField(Blockly.Msg.internet_ws_send_msg);
  5867. this.setInputsInline(true);
  5868. this.setPreviousStatement(true, null);
  5869. this.setNextStatement(true, null);
  5870. this.setColour(WS_BLOCK_COLOR);
  5871. this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Send_TOOLTIP);
  5872. this.setHelpUrl("");
  5873. }
  5874. };
  5875. Blockly.Python['esp32_web_ws_send'] = function (block) {
  5876. var value_command = Blockly.Python.valueToCode(block, 'command', Blockly.Python.ORDER_ATOMIC);
  5877. // TODO: Assemble Python into code variable.
  5878. var code = '' +
  5879. 'message = ' + value_command + '\n' +
  5880. '_client_websocket.send(message)\n';
  5881. return code;
  5882. };
  5883. Blockly.Blocks['esp32_web_ws_setup_receive'] = {
  5884. init: function () {
  5885. this.appendDummyInput()
  5886. .appendField(new Blockly.FieldImage("blockly/media/ws_header_receive.png", 220, 50, { alt: "*", flipRtl: "FALSE" }));
  5887. this.appendDummyInput()
  5888. .appendField(Blockly.Msg.internet_ws_setup_recv);
  5889. this.setInputsInline(false);
  5890. this.setPreviousStatement(true, null);
  5891. this.setNextStatement(true, null);
  5892. this.setColour(WS_BLOCK_COLOR);
  5893. this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Setup_Receive_TOOLTIP);
  5894. this.setHelpUrl("");
  5895. }
  5896. };
  5897. Blockly.Python['esp32_web_ws_setup_receive'] = function (block) {
  5898. Blockly.Python.definitions_['ws_setup_receive'] = '' +
  5899. 'import uasyncio, logging\n' +
  5900. 'from uasyncio.websocket.server import WSReader, WSWriter\n' +
  5901. 'logging.basicConfig(level=logging.DEBUG)\n' +
  5902. '\n';
  5903. // TODO: Assemble Python into code variable.
  5904. var code = '';
  5905. return code;
  5906. };
  5907. Blockly.Blocks['esp32_web_ws_receive_statement'] = {
  5908. init: function () {
  5909. this.appendDummyInput()
  5910. .appendField(Blockly.Msg.internet_ws_setup_receiving);
  5911. this.appendStatementInput("command")
  5912. .setCheck(null)
  5913. .appendField(Blockly.Msg.internet_ws_setup_recv_exec);
  5914. this.setInputsInline(false);
  5915. this.setPreviousStatement(true, null);
  5916. this.setNextStatement(true, null);
  5917. this.setColour(WS_BLOCK_COLOR);
  5918. this.setTooltip(Blockly.Msg.Esp32_Web_Ws_Receive_Statement_TOOLTIP);
  5919. this.setHelpUrl("");
  5920. }
  5921. };
  5922. Blockly.Python['esp32_web_ws_receive_statement'] = function (block) {
  5923. var statements_command = Blockly.Python.statementToCode(block, 'command');
  5924. Blockly.Python.definitions_['ws_setup_receive_statement'] = '' +
  5925. 'def _ws_exec(msg):\n' +
  5926. '' + statements_command +
  5927. '\n' +
  5928. 'def _ws_echo(reader, writer):\n' +
  5929. ' yield from reader.readline()\n' +
  5930. '\n' +
  5931. ' reader = yield from WSReader(reader, writer)\n' +
  5932. ' writer = WSWriter(reader, writer)\n' +
  5933. '\n' +
  5934. ' while 1:\n' +
  5935. ' _ws_l = yield from reader.read(1024)\n' +
  5936. ' print(_ws_l)\n' +
  5937. ' _ws_exec(_ws_l)\n' +
  5938. '\n' +
  5939. ' if _ws_l == b"\\r":\n' +
  5940. ' await writer.awrite(b"\\r\\n")\n' +
  5941. ' else:\n' +
  5942. ' await writer.awrite(_ws_l)\n' +
  5943. '\n' +
  5944. '_ws_loop = uasyncio.get_event_loop()\n' +
  5945. '_ws_loop.create_task(uasyncio.start_server(_ws_echo, "0.0.0.0", 80))\n' +
  5946. '_ws_loop.run_forever()\n' +
  5947. '_ws_loop.close()\n' +
  5948. '';
  5949. // TODO: Assemble Python into code variable.
  5950. var code = '\n';
  5951. return code;
  5952. };
  5953. Blockly.Blocks['esp32_web_ws_receive_get_data'] = {
  5954. init: function () {
  5955. this.appendDummyInput()
  5956. .appendField(Blockly.Msg.internet_ws_setup_get_msg);
  5957. this.appendDummyInput()
  5958. .appendField(Blockly.Msg.internet_ws_setup_get_msg_type)
  5959. .appendField(new Blockly.FieldDropdown([
  5960. [Blockly.Msg.internet_ws_setup_get_msg_text, "text"],
  5961. [Blockly.Msg.internet_ws_setup_get_msg_json, "json"]
  5962. ]), "type");
  5963. this.setInputsInline(false);
  5964. this.setOutput(true, null);
  5965. this.setColour(WS_BLOCK_COLOR);
  5966. var thisBlock = this;
  5967. this.setTooltip(function () {
  5968. var mode = thisBlock.getFieldValue('type');
  5969. var TOOLTIPS = {
  5970. 'text': Blockly.Msg.Esp32_Web_Ws_Receive_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.internet_ws_setup_get_msg_text),
  5971. 'json': Blockly.Msg.Esp32_Web_Ws_Receive_Get_Data_TOOLTIP.replace('%1', Blockly.Msg.internet_ws_setup_get_msg_json)
  5972. };
  5973. return TOOLTIPS[mode];
  5974. });
  5975. this.setHelpUrl("");
  5976. }
  5977. };
  5978. Blockly.Python['esp32_web_ws_receive_get_data'] = function (block) {
  5979. var dropdown_type = block.getFieldValue('type');
  5980. // TODO: Assemble Python into code variable.
  5981. if (dropdown_type == "text") {
  5982. var code = "msg.decode(\"utf-8\")";
  5983. } else if (dropdown_type == "json") {
  5984. var code = "eval(msg.decode(\"utf-8\"))";
  5985. }
  5986. // TODO: Change ORDER_NONE to the correct strength.
  5987. return [code, Blockly.Python.ORDER_NONE];
  5988. };
  5989. /*
  5990. ____ _ _____
  5991. | __ )| | | ____|
  5992. | _ \| | | _|
  5993. | |_) | |___| |___
  5994. |____/|_____|_____|
  5995. */
  5996. var BLE_BLOCK_COLOR = "#629978";
  5997. Blockly.Blocks['esp32_ble_setup_sender'] = {
  5998. init: function () {
  5999. this.appendDummyInput()
  6000. .appendField(new Blockly.FieldImage("blockly/media/header_ble_setup.png", 100, 60, { alt: "*", flipRtl: "FALSE" }));
  6001. this.appendDummyInput()
  6002. .appendField(Blockly.Msg.esp32_ble_setup_sender_msg + " " + Blockly.Msg.esp32_ble_setup_sender);
  6003. this.appendDummyInput()
  6004. .appendField(Blockly.Msg.esp32_ble_set_uuid)
  6005. .appendField(new Blockly.FieldTextInput("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"), "uuid");
  6006. this.setInputsInline(false);
  6007. this.setPreviousStatement(true, null);
  6008. this.setNextStatement(true, null);
  6009. this.setColour(BLE_BLOCK_COLOR);
  6010. this.setTooltip(Blockly.Msg.esp32_ble_setup_sender_TOOLTIP);
  6011. this.setHelpUrl("https://www.uuidgenerator.net/version1");
  6012. }
  6013. };
  6014. Blockly.Python['esp32_ble_setup_sender'] = function (block) {
  6015. var text_uuid = block.getFieldValue('uuid');
  6016. Blockly.Python.definitions_['esp32_ble_setup_sender_def'] = '' +
  6017. '# Generate UUID via: https://www.uuidgenerator.net/version1\n' +
  6018. 'import ble_simple_central, bluetooth, time, machine\n' +
  6019. 'from ble_simple_central import BLESimpleCentral\n' +
  6020. '\n' +
  6021. 'ble, ble_read, not_found = bluetooth.BLE(), \'\', False\n' +
  6022. 'central = BLESimpleCentral(ble, uuid = "' + text_uuid + '")\n' +
  6023. '\n' +
  6024. 'def ble_on_rx(v):\n' +
  6025. ' global ble_read\n' +
  6026. ' ble_read = v.decode("utf-8")\n' +
  6027. '\n' +
  6028. 'def ble_on_scan(addr_type, addr, name):\n' +
  6029. ' if addr_type is not None:\n' +
  6030. ' print("Found peripheral:", addr_type, addr, name)\n' +
  6031. ' central.connect()\n' +
  6032. ' else:\n' +
  6033. ' global not_found\n' +
  6034. ' not_found = True\n' +
  6035. ' print("\\nNo peripheral found.")\n' +
  6036. '\n' +
  6037. 'def ble_scan_and_connect():\n' +
  6038. ' central.scan(callback=ble_on_scan)\n' +
  6039. ' print("Connecting...",end="")\n' +
  6040. ' failed = 0\n' +
  6041. ' while not central.is_connected():\n' +
  6042. ' time.sleep_ms(100)\n' +
  6043. ' if not_found: return\n' +
  6044. ' print("Connected")\n' +
  6045. '\n' +
  6046. 'central.on_notify(ble_on_rx)\n' +
  6047. 'with_response = False\n' +
  6048. '';
  6049. // TODO: Assemble Python into code variable.
  6050. var code = '' +
  6051. 'try: ble_scan_and_connect()\n' +
  6052. 'except BaseException as e: print(e)\n' +
  6053. '\n';
  6054. return code;
  6055. };
  6056. Blockly.Blocks['esp32_ble_send_data'] = {
  6057. init: function () {
  6058. this.appendValueInput("data")
  6059. .setCheck(null)
  6060. .appendField(Blockly.Msg.esp32_ble_send_data_msg);
  6061. this.setInputsInline(true);
  6062. this.setPreviousStatement(true, null);
  6063. this.setNextStatement(true, null);
  6064. this.setColour(BLE_BLOCK_COLOR);
  6065. this.setTooltip(Blockly.Msg.esp32_ble_send_data_TOOLTIP);
  6066. this.setHelpUrl("");
  6067. }
  6068. };
  6069. Blockly.Python['esp32_ble_send_data'] = function (block) {
  6070. var value_data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  6071. var code = '';
  6072. let allBlocks = block.workspace.getAllBlocks();
  6073. let isReceiver = allBlocks.findIndex(item => {
  6074. return item.type == "esp32_ble_setup_receiver";
  6075. });
  6076. let isReceiverAndDisabled = allBlocks.findIndex(item => {
  6077. return item.type == "esp32_ble_setup_receiver" && item.disabled == true;
  6078. });
  6079. // TODO: Assemble Python into code variable.
  6080. if (isReceiver == -1 || (isReceiver != -1 && isReceiverAndDisabled != -1)) {
  6081. code = 'central_write_value = str(' + value_data + ')\n' +
  6082. 'central.write(central_write_value, with_response)\n' +
  6083. 'time.sleep_ms(400 if with_response else 30)\n' +
  6084. '';
  6085. }
  6086. else if (isReceiver != -1 && isReceiverAndDisabled == -1) {
  6087. code = 'central_send_value = str(' + value_data + ')\n' +
  6088. 'ble_p.send(central_send_value)\n' +
  6089. 'time.sleep_ms(400)\n' +
  6090. '';
  6091. }
  6092. return code;
  6093. };
  6094. Blockly.Blocks['esp32_ble_setup_receiver'] = {
  6095. init: function () {
  6096. this.appendDummyInput()
  6097. .appendField(new Blockly.FieldImage("blockly/media/header_ble_setup.png", 100, 60, { alt: "*", flipRtl: "FALSE" }));
  6098. this.appendDummyInput()
  6099. .appendField(Blockly.Msg.esp32_ble_setup_receiver_msg + " " + Blockly.Msg.esp32_ble_setup_receiver);
  6100. this.appendDummyInput()
  6101. .appendField(Blockly.Msg.esp32_ble_set_uuid)
  6102. .appendField(new Blockly.FieldTextInput("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"), "uuid");
  6103. this.appendDummyInput()
  6104. .appendField(Blockly.Msg.esp32_ble_set_name)
  6105. .appendField(new Blockly.FieldTextInput("coco-ble"), "name")
  6106. .appendField(Blockly.Msg.esp32_ble_set_name_limit);
  6107. this.setInputsInline(false);
  6108. this.setPreviousStatement(true, null);
  6109. this.setNextStatement(true, null);
  6110. this.setColour(BLE_BLOCK_COLOR);
  6111. this.setTooltip(Blockly.Msg.esp32_ble_setup_receiver_TOOLTIP);
  6112. this.setHelpUrl("https://www.uuidgenerator.net/version1");
  6113. }
  6114. };
  6115. Blockly.Python['esp32_ble_setup_receiver'] = function (block) {
  6116. var text_uuid = block.getFieldValue('uuid');
  6117. var text_name = block.getFieldValue('name');
  6118. // TODO: Assemble Python into code variable.
  6119. Blockly.Python.definitions_['esp32_ble_setup_receiver_def'] = '' +
  6120. 'import ble_simple_peripheral, machine\n' +
  6121. 'from ble_simple_peripheral import BLESimplePeripheral\n' +
  6122. 'import bluetooth, time\n' +
  6123. '\n' +
  6124. 'ble = bluetooth.BLE()\n' +
  6125. 'ble_p = BLESimplePeripheral(ble,uuid="' + text_uuid + '",name="' + text_name + '")\n' +
  6126. 'ble_read = \'\'\n' +
  6127. '\n' +
  6128. 'def ble_on_rx(v):\n' +
  6129. ' global ble_read\n' +
  6130. ' ble_read = v.decode("utf-8")\n' +
  6131. '\n' +
  6132. '';
  6133. var code = 'ble_p.on_write(ble_on_rx)\n';
  6134. return code;
  6135. };
  6136. Blockly.Blocks['esp32_ble_get_data'] = {
  6137. init: function () {
  6138. this.appendDummyInput()
  6139. .appendField(Blockly.Msg.esp32_ble_get_data_msg);
  6140. this.setInputsInline(false);
  6141. this.setOutput(true, null);
  6142. this.setColour(BLE_BLOCK_COLOR);
  6143. this.setTooltip(Blockly.Msg.esp32_ble_get_data_TOOLTIP);
  6144. this.setHelpUrl("");
  6145. }
  6146. };
  6147. Blockly.Python['esp32_ble_get_data'] = function (block) {
  6148. // TODO: Assemble Python into code variable.
  6149. var code = 'ble_read';
  6150. // TODO: Change ORDER_NONE to the correct strength.
  6151. return [code, Blockly.Python.ORDER_NONE];
  6152. };
  6153. Blockly.Blocks['esp32_ble_sender_connected'] = {
  6154. init: function () {
  6155. this.appendDummyInput()
  6156. .appendField(Blockly.Msg.esp32_ble_sender_connected_msg);
  6157. this.setOutput(true, null);
  6158. this.setColour(BLE_BLOCK_COLOR);
  6159. this.setTooltip(Blockly.Msg.esp32_ble_sender_connected_TOOLTIP);
  6160. this.setHelpUrl("");
  6161. }
  6162. };
  6163. Blockly.Python['esp32_ble_sender_connected'] = function (block) {
  6164. // TODO: Assemble Python into code variable.
  6165. var code = 'central.is_connected()';
  6166. // TODO: Change ORDER_NONE to the correct strength.
  6167. return [code, Blockly.Python.ORDER_NONE];
  6168. };
  6169. Blockly.Blocks['esp32_ble_receiver_connected'] = {
  6170. init: function () {
  6171. this.appendDummyInput()
  6172. .appendField(Blockly.Msg.esp32_ble_receiver_connected_msg);
  6173. this.setOutput(true, null);
  6174. this.setColour(BLE_BLOCK_COLOR);
  6175. this.setTooltip(Blockly.Msg.esp32_ble_receiver_connected_TOOLTIP);
  6176. this.setHelpUrl("");
  6177. }
  6178. };
  6179. Blockly.Python['esp32_ble_receiver_connected'] = function (block) {
  6180. // TODO: Assemble Python into code variable.
  6181. var code = 'ble_p.is_connected()';
  6182. // TODO: Change ORDER_NONE to the correct strength.
  6183. return [code, Blockly.Python.ORDER_NONE];
  6184. };
  6185. var EXPAND_COLOR = "#3163ed";
  6186. Blockly.Blocks['esp32_expand_io_from_digital_pin'] = {
  6187. init: function () {
  6188. this.appendDummyInput()
  6189. .appendField(Blockly.Msg.esp32_expand_io_from_digital_pin)
  6190. .appendField(new Blockly.FieldDropdown([
  6191. ["4", "4"],
  6192. ["12", "12"],
  6193. ["13", "13"],
  6194. ["14", "14"],
  6195. ["15", "15"],
  6196. ["16", "16"],
  6197. ["17", "17"],
  6198. ["21", "21"],
  6199. ["22", "22"],
  6200. ["25", "25"],
  6201. ["27", "27"]
  6202. ]), "type")
  6203. .appendField(Blockly.Msg.digital_get_value);
  6204. this.setOutput(true, null);
  6205. this.setColour(EXPAND_COLOR);
  6206. this.setHelpUrl("");
  6207. var thisBlock = this;
  6208. this.setTooltip(function () {
  6209. var mode = thisBlock.getFieldValue('type');
  6210. var TOOLTIPS = {
  6211. '4': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "4"),
  6212. '12': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "12"),
  6213. '13': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "13"),
  6214. '14': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "14"),
  6215. '15': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "15"),
  6216. '16': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "16"),
  6217. '17': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "17"),
  6218. '21': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "21"),
  6219. '22': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "22"),
  6220. '25': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "25"),
  6221. '27': Blockly.Msg.esp32_expand_io_from_digital_pin_TOOLTIP.replace('%1', "27")
  6222. };
  6223. return TOOLTIPS[mode];
  6224. });
  6225. }
  6226. };
  6227. Blockly.Python['esp32_expand_io_from_digital_pin'] = function (block) {
  6228. var type = block.getFieldValue('type');
  6229. Blockly.Python.definitions_['import_esp32_expand_io_from_digital_pin_setup'] = '' +
  6230. 'from machine import Pin\n' +
  6231. '';
  6232. let aa = 'p' + type + ' = Pin(' + type + ', Pin.IN)\n';
  6233. Blockly.Python.addVariable('p' + type, aa, true);
  6234. var code = 'p' + type + '.value()'
  6235. // TODO: Change ORDER_NONE to the correct strength.
  6236. return [code, Blockly.Python.ORDER_CONDITIONAL];
  6237. };
  6238. Blockly.Blocks['esp32_expand_io_set_digital_pin'] = {
  6239. init: function () {
  6240. this.appendDummyInput()
  6241. .appendField(Blockly.Msg.esp32_expand_io_set_digital_pin)
  6242. .appendField(new Blockly.FieldDropdown([
  6243. ["4", "4"],
  6244. ["12", "12"],
  6245. ["13", "13"],
  6246. ["14", "14"],
  6247. ["15", "15"],
  6248. ["16", "16"],
  6249. ["17", "17"],
  6250. ["21", "21"],
  6251. ["22", "22"],
  6252. ["25", "25"],
  6253. ["27", "27"]
  6254. ]), "type");
  6255. this.appendDummyInput()
  6256. .appendField(Blockly.Msg.digital_set_as);
  6257. this.appendValueInput("high_low")
  6258. .setCheck(null);
  6259. this.setInputsInline(true);
  6260. this.setPreviousStatement(true, null);
  6261. this.setNextStatement(true, null);
  6262. this.setColour(EXPAND_COLOR);
  6263. this.setHelpUrl("");
  6264. var thisBlock = this;
  6265. this.setTooltip(function () {
  6266. var mode = thisBlock.getFieldValue('type');
  6267. var TOOLTIPS = {
  6268. '4': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "4"),
  6269. '12': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "12"),
  6270. '13': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "13"),
  6271. '14': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "14"),
  6272. '15': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "15"),
  6273. '16': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "16"),
  6274. '17': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "17"),
  6275. '21': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "21"),
  6276. '22': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "22"),
  6277. '25': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "25"),
  6278. '27': Blockly.Msg.esp32_expand_io_set_digital_pin_TOOLTIP.replace('%1', "27")
  6279. };
  6280. return TOOLTIPS[mode];
  6281. });
  6282. }
  6283. };
  6284. Blockly.Python['esp32_expand_io_set_digital_pin'] = function (block) {
  6285. var type = block.getFieldValue('type');
  6286. var value_name2 = Blockly.Python.valueToCode(block, 'high_low', Blockly.Python.ORDER_ATOMIC);
  6287. Blockly.Python.definitions_['import_esp32_expand_io_set_digital_pin_setup'] = '' +
  6288. 'from machine import Pin\n' +
  6289. '';
  6290. let aa = '_PIN_OUT_' + type + ' = Pin(' + type + ', Pin.OUT)\n';
  6291. Blockly.Python.addVariable('_PIN_OUT_' + type, aa, true);
  6292. var code = '_PIN_OUT_' + type + '.value' + value_name2 + '\n';
  6293. // TODO: Change ORDER_NONE to the correct strength.
  6294. return code;
  6295. };
  6296. Blockly.Blocks['esp32_expand_io_set_analog_pin'] = {
  6297. init: function () {
  6298. this.appendDummyInput()
  6299. .appendField(Blockly.Msg.esp32_expand_io_set_analog_pin)
  6300. .appendField(new Blockly.FieldDropdown([
  6301. ["4", "4"],
  6302. ["12", "12"],
  6303. ["13", "13"],
  6304. ["14", "14"],
  6305. ["15", "15"],
  6306. ["16", "16"],
  6307. ["17", "17"],
  6308. ["21", "21"],
  6309. ["22", "22"],
  6310. ["25", "25"],
  6311. ["27", "27"]
  6312. ]), "type");
  6313. this.appendDummyInput()
  6314. .appendField(Blockly.Msg.esp32_expand_io_set_analog_pin_digital_set_as);
  6315. this.appendValueInput("digital_pin_input")
  6316. .setCheck(null);
  6317. this.appendDummyInput()
  6318. .appendField(Blockly.Msg.esp32_expand_io_set_analog_pin_digital_set_af);
  6319. this.setInputsInline(true);
  6320. this.setPreviousStatement(true, null);
  6321. this.setNextStatement(true, null);
  6322. this.setColour(EXPAND_COLOR);
  6323. this.setHelpUrl("");
  6324. var thisBlock = this;
  6325. this.setTooltip(function () {
  6326. var mode = thisBlock.getFieldValue('type');
  6327. var TOOLTIPS = {
  6328. '4': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "4"),
  6329. '12': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "12"),
  6330. '13': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "13"),
  6331. '14': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "14"),
  6332. '15': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "15"),
  6333. '16': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "16"),
  6334. '17': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "17"),
  6335. '21': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "21"),
  6336. '22': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "22"),
  6337. '25': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "25"),
  6338. '27': Blockly.Msg.esp32_expand_io_set_analog_pin_TOOLTIP.replace('%1', "27")
  6339. };
  6340. return TOOLTIPS[mode];
  6341. });
  6342. }
  6343. };
  6344. Blockly.Python['esp32_expand_io_set_analog_pin'] = function (block) {
  6345. var type = block.getFieldValue('type');
  6346. var value_name1 = Blockly.Python.valueToCode(block, 'digital_pin_input', Blockly.Python.ORDER_ATOMIC);
  6347. Blockly.Python.addVariable('pwm' + type, '', true);
  6348. // TODO: Assemble Python into code variable.
  6349. Blockly.Python.definitions_['import_esp32_expand_io_set_analog_pin_setup'] = '' +
  6350. 'from machine import Pin, PWM\n' +
  6351. '';
  6352. var code = 'pwm' + type + ' = PWM(Pin(' + type + '), freq = 80000, duty = 4 * ' + value_name1 + ')\n';
  6353. return code;
  6354. };
  6355. /**
  6356. * Turtles!
  6357. */
  6358. var Turtle_HUE = "#5cb2d6";
  6359. Blockly.Blocks['turtle_create'] = {
  6360. init: function () {
  6361. this.appendDummyInput()
  6362. .appendField(Blockly.Msg.TURTLE_CREATE_NE_TURTLE);
  6363. this.setPreviousStatement(true);
  6364. this.setNextStatement(true);
  6365. this.setOutput(false);
  6366. this.setInputsInline(true);
  6367. this.setColour(Turtle_HUE);
  6368. this.setTooltip(Blockly.Msg.TURTLE_CREATE_NE_TURTLE_TLTLE_TOOLTIP);
  6369. this.setHelpUrl('');
  6370. }
  6371. };
  6372. Blockly.Python['turtle_create'] = function (block) {
  6373. Blockly.Python.definitions_['import_turtle_setup'] = '' +
  6374. 'import turtle\n' +
  6375. '';
  6376. // TODO: Assemble Python into code variable.
  6377. var code = 'turtle.initTurtle()\n';
  6378. return code;
  6379. };
  6380. Blockly.Blocks['turtle_color_set'] = {
  6381. init: function () {
  6382. this.appendDummyInput()
  6383. .appendField(new Blockly.FieldDropdown([
  6384. // [Blockly.Msg.image_process_set_filled_screen_color_black, "black"],
  6385. [Blockly.Msg.image_process_set_filled_screen_color_red, "red"],
  6386. [Blockly.Msg.image_process_set_filled_screen_color_blue, "blue"],
  6387. [Blockly.Msg.image_process_set_filled_screen_color_cyan, "cyan"],
  6388. [Blockly.Msg.image_process_set_filled_screen_color_yellow, "yellow"],
  6389. [Blockly.Msg.image_process_set_filled_screen_color_white, "white"]
  6390. ]), "COLOR");
  6391. this.setOutput(true, "String");
  6392. this.setInputsInline(true);
  6393. this.setColour(Turtle_HUE);
  6394. this.setTooltip('');
  6395. this.setHelpUrl('');
  6396. }
  6397. }
  6398. Blockly.Python['turtle_color_set'] = function (block) {
  6399. var color = block.getFieldValue('COLOR');
  6400. var code = '(\"' + color + '\")';
  6401. // TODO: Assemble Python into code variable.
  6402. return [code, Blockly.Python.ORDER_NONE];
  6403. };
  6404. Blockly.Blocks['turtle_color'] = {
  6405. init: function () {
  6406. this.appendDummyInput()
  6407. .appendField(Blockly.Msg.TURTLE_MAKE_TURRLE_COLOR);
  6408. this.appendValueInput("COLOR")
  6409. .setCheck(null)
  6410. .appendField("");
  6411. this.setPreviousStatement(true);
  6412. this.setNextStatement(true);
  6413. this.setOutput(false);
  6414. this.setInputsInline(true);
  6415. this.setColour(Turtle_HUE);
  6416. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURRLE_COLOR_TOOLTIP);
  6417. this.setHelpUrl('');
  6418. }
  6419. };
  6420. Blockly.Python['turtle_color'] = function (block) {
  6421. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  6422. // TODO: Assemble Python into code variable.
  6423. var code = 'turtle.pencolor(' + color + ')\n';
  6424. return code;
  6425. };
  6426. Blockly.Blocks['turtle_forward'] = {
  6427. init: function () {
  6428. this.appendValueInput("DISTANCE")
  6429. .setCheck(null)
  6430. .appendField(Blockly.Msg.TURTLE_MAKE_TURTLE_MOVE_FORWARD_BY);
  6431. this.setPreviousStatement(true);
  6432. this.setNextStatement(true);
  6433. this.setInputsInline(true);
  6434. this.setOutput(false);
  6435. this.setColour(Turtle_HUE);
  6436. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURTLE_MOVE_FORWARD_TOOLTIP);
  6437. this.setHelpUrl('');
  6438. }
  6439. };
  6440. Blockly.Python['turtle_forward'] = function (block) {
  6441. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6442. var distance = Blockly.Python.valueToCode(block, 'DISTANCE', Blockly.Python.ORDER_ATOMIC);
  6443. // TODO: Assemble Python into code variable.
  6444. var code = 'turtle' + '.forward(' + distance + ')\n';
  6445. return code;
  6446. };
  6447. Blockly.Blocks['turtle_backward'] = {
  6448. init: function () {
  6449. this.appendValueInput("DISTANCE")
  6450. .setCheck(null)
  6451. .appendField(Blockly.Msg.TURTLE_MAKE_TURTLE_MOVE_BACKWARD_BY);
  6452. this.setPreviousStatement(true);
  6453. this.setInputsInline(true);
  6454. this.setNextStatement(true);
  6455. this.setOutput(false);
  6456. this.setColour(Turtle_HUE);
  6457. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURTLE_MOVE_BACKWARD_TOOLTIP);
  6458. this.setHelpUrl('');
  6459. }
  6460. };
  6461. Blockly.Python['turtle_backward'] = function (block) {
  6462. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6463. var distance = Blockly.Python.valueToCode(block, 'DISTANCE', Blockly.Python.ORDER_ATOMIC);
  6464. // TODO: Assemble Python into code variable.
  6465. var code = 'turtle.backward(' + distance + ')\n';
  6466. return code;
  6467. };
  6468. Blockly.Blocks['turtle_left'] = {
  6469. init: function () {
  6470. this.appendValueInput("ANGLE")
  6471. .setCheck(null)
  6472. .appendField(Blockly.Msg.TURTLE_MAKE_TURN_LEFT_BY);
  6473. this.appendDummyInput("")
  6474. .appendField(Blockly.Msg.TURTLE_DEGREE);
  6475. this.setPreviousStatement(true);
  6476. this.setNextStatement(true);
  6477. this.setInputsInline(true);
  6478. this.setOutput(false);
  6479. this.setColour(Turtle_HUE);
  6480. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURN_LEFT_TOOLTIP);
  6481. this.setHelpUrl('');
  6482. }
  6483. };
  6484. Blockly.Python['turtle_left'] = function (block) {
  6485. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6486. var angle = Blockly.Python.valueToCode(block, 'ANGLE', Blockly.Python.ORDER_ATOMIC);
  6487. // TODO: Assemble Python into code variable.
  6488. var code = 'turtle.left(' + angle + ')\n';
  6489. return code;
  6490. };
  6491. Blockly.Blocks['turtle_right'] = {
  6492. init: function () {
  6493. this.appendValueInput("ANGLE")
  6494. .setCheck(null)
  6495. .appendField(Blockly.Msg.TURTLE_MAKE_TURN_RIGHT_BY);
  6496. this.appendDummyInput("")
  6497. .appendField(Blockly.Msg.TURTLE_DEGREE);
  6498. this.setPreviousStatement(true);
  6499. this.setNextStatement(true);
  6500. this.setInputsInline(true);
  6501. this.setOutput(false);
  6502. this.setColour(Turtle_HUE);
  6503. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURN_RIGHT_TOOLTIP);
  6504. this.setHelpUrl('');
  6505. }
  6506. };
  6507. Blockly.Python['turtle_right'] = function (block) {
  6508. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6509. var angle = Blockly.Python.valueToCode(block, 'ANGLE', Blockly.Python.ORDER_ATOMIC);
  6510. // TODO: Assemble Python into code variable.
  6511. var code = 'turtle.right(' + angle + ')\n';
  6512. return code;
  6513. };
  6514. Blockly.Blocks['turtle_pen'] = {
  6515. init: function () {
  6516. this.appendDummyInput()
  6517. .appendField(Blockly.Msg.TURTLE_MAKE_TURRLE_PEN)
  6518. .appendField(new Blockly.FieldDropdown([[Blockly.Msg.TURTLE_PEN_UP, "up"], [Blockly.Msg.TURTLE_PEN_DOWN, "down"]]), "Pen");
  6519. this.setInputsInline(true);
  6520. this.setPreviousStatement(true, null);
  6521. this.setNextStatement(true, null);
  6522. this.setColour(Turtle_HUE);
  6523. this.setHelpUrl("");
  6524. var thisBlock = this;
  6525. this.setTooltip(function () {
  6526. var mode = thisBlock.getFieldValue('Pen');
  6527. var TOOLTIPS = {
  6528. 'up': Blockly.Msg.TURTLE_MAKE_TURRLE_PEN_TOOLTIP.replace('%1', Blockly.Msg.TURTLE_PEN_UP),
  6529. 'down': Blockly.Msg.TURTLE_MAKE_TURRLE_PEN_TOOLTIP.replace('%1', Blockly.Msg.TURTLE_PEN_DOWN)
  6530. };
  6531. return TOOLTIPS[mode];
  6532. });
  6533. }
  6534. };
  6535. Blockly.Python['turtle_pen'] = function (block) {
  6536. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6537. var pen = block.getFieldValue('Pen');
  6538. // TODO: Assemble Python into code variable.
  6539. var code = 'turtle.pen' + pen + '()\n';
  6540. return code;
  6541. };
  6542. Blockly.Blocks['turtle_goto'] = {
  6543. init: function () {
  6544. this.appendValueInput("X")
  6545. .setCheck("Number")
  6546. .appendField(Blockly.Msg.TURTLE_MAKE_TURTLE_GOTO_LOCATION_X);
  6547. this.appendValueInput("Y")
  6548. .setCheck("Number")
  6549. .appendField(", Y:");
  6550. this.setInputsInline(true);
  6551. this.setPreviousStatement(true, null);
  6552. this.setNextStatement(true, null);
  6553. this.setColour(Turtle_HUE);
  6554. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURTLE_GOTO_LOCATION_X_TOOLTIP);
  6555. this.setHelpUrl("");
  6556. }
  6557. };
  6558. Blockly.Python['turtle_goto'] = function (block) {
  6559. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6560. var x_coordinate = Blockly.Python.valueToCode(block, 'X', Blockly.Python.ORDER_ATOMIC);
  6561. var y_coordinate = Blockly.Python.valueToCode(block, 'Y', Blockly.Python.ORDER_ATOMIC);
  6562. // TODO: Assemble Python into code variable.
  6563. var code = 'turtle.goto(' + x_coordinate + ',' + y_coordinate + ')\n';
  6564. return code;
  6565. };
  6566. Blockly.Blocks['turtle_set_pos'] = {
  6567. init: function () {
  6568. this.appendValueInput("X")
  6569. .setCheck("Number")
  6570. .appendField(Blockly.Msg.TURTLE_MAKE_TURTLE_SET_POSITION);
  6571. this.appendValueInput("Y")
  6572. .setCheck("Number")
  6573. .appendField(", Y:");
  6574. this.setInputsInline(true);
  6575. this.setPreviousStatement(true, null);
  6576. this.setNextStatement(true, null);
  6577. this.setColour(Turtle_HUE);
  6578. this.setTooltip(Blockly.Msg.TURTLE_MAKE_TURTLE_SET_POSITION_TOOLTIP);
  6579. this.setHelpUrl("");
  6580. }
  6581. };
  6582. Blockly.Python['turtle_set_pos'] = function (block) {
  6583. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6584. var x_coordinate = Blockly.Python.valueToCode(block, 'X', Blockly.Python.ORDER_ATOMIC);
  6585. var y_coordinate = Blockly.Python.valueToCode(block, 'Y', Blockly.Python.ORDER_ATOMIC);
  6586. // TODO: Assemble Python into code variable.
  6587. var code = 'turtle.setPosition(' + x_coordinate + ',' + y_coordinate + ')\n';
  6588. return code;
  6589. };
  6590. Blockly.Blocks['turtle_setheading'] = {
  6591. init: function () {
  6592. this.appendValueInput("ANGLE")
  6593. .setCheck(null)
  6594. .appendField(Blockly.Msg.TURTLE_MAKE_SET_HEADING);
  6595. this.appendDummyInput("")
  6596. .appendField(Blockly.Msg.TURTLE_DEGREE);
  6597. this.setPreviousStatement(true);
  6598. this.setNextStatement(true);
  6599. this.setInputsInline(true);
  6600. this.setOutput(false);
  6601. this.setColour(Turtle_HUE);
  6602. this.setTooltip(Blockly.Msg.TURTLE_MAKE_SET_HEADING_TOOLTIP);
  6603. this.setHelpUrl('');
  6604. }
  6605. };
  6606. Blockly.Python['turtle_setheading'] = function (block) {
  6607. //var turtle = Blockly.Python.valueToCode(block, 'TURTLE', Blockly.Python.ORDER_ATOMIC);
  6608. var angle = Blockly.Python.valueToCode(block, 'ANGLE', Blockly.Python.ORDER_ATOMIC);
  6609. // TODO: Assemble Python into code variable.
  6610. var code = 'turtle.setheading(' + angle + ')\n';
  6611. return code;
  6612. };
  6613. Blockly.Blocks['turtle_reset'] = {
  6614. init: function () {
  6615. this.appendDummyInput("")
  6616. .appendField(Blockly.Msg.TURTLE_RESET);
  6617. this.setPreviousStatement(true);
  6618. this.setNextStatement(true);
  6619. this.setInputsInline(true);
  6620. this.setOutput(false);
  6621. this.setColour(Turtle_HUE);
  6622. this.setTooltip(Blockly.Msg.TURTLE_RESET_TOOLTIP);
  6623. this.setHelpUrl('');
  6624. }
  6625. };
  6626. Blockly.Python['turtle_reset'] = function (block) {
  6627. // TODO: Assemble Python into code variable.
  6628. var code = 'turtle.reset()\n';
  6629. return code;
  6630. };
  6631. Blockly.Blocks['turtle_clear'] = {
  6632. init: function () {
  6633. this.appendDummyInput("")
  6634. .appendField(Blockly.Msg.TURTLE_CLEAR);
  6635. this.setPreviousStatement(true);
  6636. this.setNextStatement(true);
  6637. this.setInputsInline(true);
  6638. this.setOutput(false);
  6639. this.setColour(Turtle_HUE);
  6640. this.setTooltip(Blockly.Msg.TURTLE_CLEAR_TOOLTIP);
  6641. this.setHelpUrl('');
  6642. }
  6643. };
  6644. Blockly.Python['turtle_clear'] = function (block) {
  6645. // TODO: Assemble Python into code variable.
  6646. var code = 'turtle.clear()\n';
  6647. return code;
  6648. };
  6649. // 室温传感器
  6650. Blockly.Blocks['v831_room_water_temperature'] = {
  6651. init: function () {
  6652. this.appendDummyInput("")
  6653. .appendField("IIC"+Blockly.Msg.room_water_temperature_text);
  6654. // this.setInputsInline(true);
  6655. this.setOutput(true);
  6656. this.setColour("#d42b03");
  6657. this.setTooltip(Blockly.Msg.room_water_temperature_text);
  6658. this.setHelpUrl('');
  6659. }
  6660. };
  6661. Blockly.Python['v831_room_water_temperature'] = function (block) {
  6662. // TODO: Assemble Python into code variable.
  6663. Blockly.Python.definitions_['v831_import_sys'] = 'import sys';
  6664. Blockly.Python.definitions_['v831_import_serial'] = 'import serial';
  6665. Blockly.Python.definitions_['v831_room_water_temperature_init'] = `class Ds18b20():
  6666. SEARCH_ROM = 0xf0
  6667. READ_ROM = 0x33
  6668. MATCH_ROM = 0x55
  6669. SKIP_ROM_BROADCAST = 0xcc
  6670. ALARM_SEARCH = 0xec
  6671. TEMPERATURE_READ = 0x44
  6672. READ_SCRATCHPAD = 0xbe
  6673. WRITE_SCRATCHPAD = 0x4e
  6674. COPY_SCRATCHPAD = 0x48
  6675. RECALL_EEPROM = 0xb8
  6676. READ_POWER_SUPPLY = 0xb4
  6677. def __init__(self, port=None):
  6678. self.ser = None
  6679. if port is not None:
  6680. self.port = port
  6681. else:
  6682. self.port = None
  6683. self.connect()
  6684. def connect(self):
  6685. self.port="/dev/ttyS1"
  6686. self.ser = serial.Serial()
  6687. self.ser.port = self.port
  6688. self.ser.baudrate = 115200
  6689. self.ser.bytesize = 8
  6690. self.ser.parity = 'N'
  6691. self.ser.stopbits = 1
  6692. self.ser.timeout = 0.1
  6693. self.ser.open()
  6694. if not self.ser.is_open:
  6695. print("Failed to open serial port")
  6696. sys.exit(1)
  6697. def close(self):
  6698. self.ser.close()
  6699. def reset(self):
  6700. self.ser.baudrate = 9600
  6701. self.ser.write(b'\\xF0')
  6702. output = self.ser.read()
  6703. if output == b'\\xF0':
  6704. raise Exception("No devices found")
  6705. elif output == b'\\x00':
  6706. raise Exception("Shorted?")
  6707. elif output == b'\\xe0':
  6708. # print("Single device")
  6709. pass
  6710. else:
  6711. # print("Multiple devices?")
  6712. pass
  6713. self.ser.baudrate = 115200
  6714. def send_byte(self, data):
  6715. output = 0
  6716. for i in range(8):
  6717. bit = (data >> i) & 1
  6718. if bit == 1:
  6719. self.ser.write(b'\\xff')
  6720. else:
  6721. self.ser.write(b'\\x00')
  6722. outbit = self.ser.read()
  6723. if outbit == b'\\xFF':
  6724. output += (1 << i)
  6725. return output
  6726. def send_command(self, target, command):
  6727. self.reset()
  6728. self.send_byte(target)
  6729. return self.send_byte(command)
  6730. def do_a_temperature_read(self):
  6731. self.send_command(Ds18b20.SKIP_ROM_BROADCAST, Ds18b20.TEMPERATURE_READ)
  6732. while True:
  6733. if self.send_byte(0xFF) > 0:
  6734. break
  6735. time.sleep(0.5)
  6736. def get_scratchpad(self):
  6737. output = {}
  6738. self.send_command(Ds18b20.SKIP_ROM_BROADCAST, Ds18b20.READ_SCRATCHPAD)
  6739. scratchpad = []
  6740. scratchpad.append(self.send_byte(0xFF))
  6741. scratchpad.append(self.send_byte(0xFF))
  6742. scratchpad.append(self.send_byte(0xFF))
  6743. scratchpad.append(self.send_byte(0xFF))
  6744. scratchpad.append(self.send_byte(0xFF))
  6745. scratchpad.append(self.send_byte(0xFF))
  6746. scratchpad.append(self.send_byte(0xFF))
  6747. scratchpad.append(self.send_byte(0xFF))
  6748. scratchpad.append(self.send_byte(0xFF))
  6749. output["temperature_lsb"] = scratchpad[0]
  6750. output["temperature_msb"] = scratchpad[1]
  6751. output["th_register"] = scratchpad[2]
  6752. output["tl_register"] = scratchpad[3]
  6753. output["configuration"] = scratchpad[4]
  6754. output["reserved_ff"] = scratchpad[5]
  6755. output["reserved_xx"] = scratchpad[6]
  6756. output["reserved_10"] = scratchpad[7]
  6757. output["crc"] = scratchpad[8]
  6758. r0 = (output["configuration"] >> 5) & 1
  6759. r1 = (output["configuration"] >> 6) & 1
  6760. r = r0 + (r1 << 1)
  6761. output["resolution"] = 9 + r
  6762. return output
  6763. def write_scratchpad(self, th, tl, config):
  6764. self.send_command(Ds18b20.SKIP_ROM_BROADCAST, Ds18b20.WRITE_SCRATCHPAD)
  6765. self.send_byte(th)
  6766. self.send_byte(tl)
  6767. self.send_byte(config)
  6768. def get_temperature(self):
  6769. self.do_a_temperature_read()
  6770. self.send_command(Ds18b20.SKIP_ROM_BROADCAST, Ds18b20.READ_SCRATCHPAD)
  6771. temperature = self.send_byte(0xFF)
  6772. temperature += self.send_byte(0xFF) << 8
  6773. temperature *= 0.0625
  6774. return temperature
  6775. def get_single_rom_code(self):
  6776. rom_code = []
  6777. rom_code_bytes = b''
  6778. self.reset()
  6779. self.send_byte(Ds18b20.READ_ROM)
  6780. for _ in range(8):
  6781. abyte = self.send_byte(0xff)
  6782. rom_code_bytes = bytes([abyte]) + rom_code_bytes
  6783. rom_code = [abyte] + rom_code
  6784. crc = rom_code[0]
  6785. serial = rom_code[1:7]
  6786. serial_bytes = rom_code_bytes[1:7]
  6787. family_code = rom_code[7]
  6788. return serial_bytes
  6789. def get_power_supply(self):
  6790. self.send_command(Ds18b20.SKIP_ROM_BROADCAST, Ds18b20.READ_POWER_SUPPLY)
  6791. if self.send_byte(0xff) == 0xff:
  6792. print("All devices connected to proper power")
  6793. else:
  6794. print("Some devices connected as parasitic")
  6795. def set_accuracy(self, accuracy):
  6796. if accuracy < 9 or accuracy > 12:
  6797. raise Exception("Only an accuracy of 9-12 bits is allowed")
  6798. scratchpad = ds.get_scratchpad() # get the current scratchpad data so we can pass tl and th the same as currently set
  6799. set_accuracy = accuracy - 9
  6800. set_accuracy = set_accuracy << 5
  6801. new_config = (scratchpad["configuration"] & 0b10011111) | set_accuracy
  6802. ds.write_scratchpad(th=scratchpad["th_register"], tl=scratchpad["tl_register"], config=new_config)
  6803. ds = Ds18b20("/dev/ttyS1")
  6804. `;
  6805. // Blockly.Python.addFunction("getRoomWaterTemperature", `def getRoomWaterTemperature():
  6806. // serial_num = ds.get_single_rom_code()
  6807. // temperature = ds.get_temperature()
  6808. // return temperature
  6809. // `, true)
  6810. var code = 'ds.get_temperature()';
  6811. return [code, Blockly.Python.ORDER_ATOMIC];
  6812. };
  6813. Blockly.Blocks['v831_set_real_time_clock'] = {
  6814. init: function () {
  6815. let nowDate = new Date();
  6816. this.appendDummyInput()
  6817. .appendField("IIC"+Blockly.Msg.time_set_current_date_title)
  6818. .appendField(new Blockly.FieldTextInput(nowDate.getFullYear()), "year")
  6819. .appendField(Blockly.Msg.time_get_current_date_y)
  6820. .appendField(new Blockly.FieldTextInput(nowDate.getMonth()+1), "month")
  6821. .appendField(Blockly.Msg.time_get_current_date_m)
  6822. .appendField(new Blockly.FieldTextInput(nowDate.getDate()), "day")
  6823. .appendField(Blockly.Msg.time_get_current_date_d)
  6824. .appendField(Blockly.Msg.time_get_current_date_week)
  6825. .appendField(new Blockly.FieldTextInput(nowDate.getDay()), "week")
  6826. .appendField(new Blockly.FieldTextInput(nowDate.getHours()), "hour")
  6827. .appendField(Blockly.Msg.time_get_current_date_hour)
  6828. .appendField(new Blockly.FieldTextInput(nowDate.getMinutes()), "minutes")
  6829. .appendField(Blockly.Msg.time_get_current_date_min)
  6830. .appendField(new Blockly.FieldTextInput(nowDate.getSeconds()), "seconds")
  6831. .appendField(Blockly.Msg.time_get_current_date_sec);
  6832. this.setNextStatement(true);
  6833. this.setPreviousStatement(true);
  6834. this.setColour("#d42b03");
  6835. this.setHelpUrl("");
  6836. this.setTooltip(Blockly.Msg.time_set_current_date_title);
  6837. }
  6838. };
  6839. Blockly.Python['v831_set_real_time_clock'] = function (block) {
  6840. var year = block.getFieldValue('year');
  6841. var month = block.getFieldValue('month');
  6842. var day = block.getFieldValue('day');
  6843. var week = block.getFieldValue('week');
  6844. var hour = block.getFieldValue('hour');
  6845. var minutes = block.getFieldValue('minutes');
  6846. var seconds = block.getFieldValue('seconds');
  6847. // TODO: Assemble Python into code variable.
  6848. Blockly.Python.definitions_['v831_import_smbus2'] = 'import smbus2';
  6849. Blockly.Python.definitions_['v831_import_math'] = 'import math';
  6850. Blockly.Python.definitions_['v831_import_time'] = 'import time';
  6851. Blockly.Python.definitions_['v831_real_time_clock_init'] = `class DS3231(object):
  6852. # create RTC instance
  6853. def __init__(self):
  6854. self.bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  6855. self.address = 0x68
  6856. def bcd_to_int(self,bcd, n=2):
  6857. """Decode n least significant packed binary coded decimal digits to binary.
  6858. Return binary result.
  6859. n defaults to 2 (BCD digits).
  6860. n=0 decodes all digits.
  6861. """
  6862. return int(('%x' % bcd)[-n:])
  6863. def int_to_bcd(self,x, n=2):
  6864. """
  6865. Encode the n least significant decimal digits of x
  6866. to packed binary coded decimal (BCD).
  6867. Return packed BCD value.
  6868. n defaults to 2 (digits).
  6869. n=0 encodes all digits.
  6870. """
  6871. return int(str(x)[-n:], 0x10)
  6872. def read(self, addr):
  6873. for i in range(0, 3):
  6874. try:
  6875. tmp = self.bus.read_byte_data(self.address, addr)
  6876. time.sleep(0.001) # 1ms
  6877. # print(addr, tmp) # debug
  6878. return tmp
  6879. except Exception:
  6880. time.sleep(0.01)
  6881. continue
  6882. return None
  6883. def write(self, addr, val):
  6884. for i in range(0, 3):
  6885. try:
  6886. self.bus.write_byte_data(self.address, addr, val)
  6887. #time.sleep(0.001) # 1ms
  6888. # print(addr, val) # debug
  6889. return True
  6890. except Exception:
  6891. time.sleep(0.001)
  6892. continue
  6893. return False
  6894. # set times functions ---------------------------------------------------------------------
  6895. def setYear(self, year):
  6896. # only last two digits (last two digits are used if longer)
  6897. self.write(0x06, self.int_to_bcd(year%100))
  6898. def setMonth(self, month):
  6899. if not 1 <= month <= 12:
  6900. raise ValueError('Month is out of range [1,12].')
  6901. self.write(0x05,self.int_to_bcd(month))
  6902. def setDay(self, day):
  6903. if not 1 <= day <= 31:
  6904. raise ValueError('Day is out of range [1,31].')
  6905. self.write(0x04,self.int_to_bcd(day))
  6906. def setDayOfWeek(self, dayOfWeek):
  6907. if not 1 <= dayOfWeek <= 7:
  6908. raise ValueError('Day of week is out of range [1,7].')
  6909. self.write(0x03,self.int_to_bcd(dayOfWeek))
  6910. def setHour(self, hour):
  6911. if not 0 <= hour < 24:
  6912. raise ValueError('Hour is out of range [0,23].')
  6913. self.write(0x02,self.int_to_bcd(hour)& 0x3F)
  6914. def setMinutes(self, minutes):
  6915. if not 0 <= minutes < 59:
  6916. raise ValueError('Minutes is out of range [0,59].')
  6917. self.write(0x01,self.int_to_bcd(minutes))
  6918. def setSeconds(self, seconds):
  6919. if not 0 <= seconds < 60:
  6920. raise ValueError('Seconds is out of range [0,59].')
  6921. self.write(0x00,self.int_to_bcd(seconds))
  6922. def setDateTime(self, year, month, day, dayOfWeek, hour, minutes, seconds):
  6923. # set all the date and times (year is last two digits of year)
  6924. self.setYear(year)
  6925. self.setMonth(month)
  6926. self.setDay(day)
  6927. self.setDayOfWeek(dayOfWeek)
  6928. self.setHour(hour)
  6929. self.setMinutes(minutes)
  6930. self.setSeconds(seconds)
  6931. # get times functions -------------------------------------------------
  6932. def getYear(self):
  6933. return self.bcd_to_int(self.read(0x06))
  6934. def getMonth(self):
  6935. temp = self.read(0x05)
  6936. return self.bcd_to_int((temp<<4>>4) &0x7F)
  6937. #return temp[0] & 0x7F
  6938. def getDay(self):
  6939. # 0 - 31
  6940. return self.bcd_to_int(self.read(0x04))
  6941. def getDayOfWeek(self):
  6942. # 1 - 7
  6943. return self.bcd_to_int(self.read(0x03))
  6944. def getHour(self):
  6945. temp = self.read(0x02)
  6946. if temp==0x64: #if hour is 24:00,convert it to 00:00
  6947. temp=0x40
  6948. return self.bcd_to_int((temp<< 4 >>4)& 0x3F)
  6949. #return temp[0] & 0x3F
  6950. def getMinutes(self):
  6951. return self.bcd_to_int(self.read(0x01))
  6952. def getSeconds(self):
  6953. return self.bcd_to_int(self.read(0x00))
  6954. def getDateTime(self):
  6955. # returns whole date and time as list
  6956. # (last two digits of year, month, day, day of week, hour, minutes, seconds)
  6957. dateTime = [0, 0, 0, 0, 0, 0, 0]
  6958. dateTime[0] = self.getYear()
  6959. dateTime[1] = self.getMonth()
  6960. dateTime[2] = self.getDay()
  6961. dateTime[3] = self.getDayOfWeek()
  6962. dateTime[4] = self.getHour()
  6963. dateTime[5] = self.getMinutes()
  6964. dateTime[6] = self.getSeconds()
  6965. return dateTime
  6966. def convertToByteType(self,number):
  6967. return bytes([number])
  6968. def decodeToDec(self,byte):
  6969. return ((byte[0] >> 4) * 10) + (byte[0] & 0x0F)
  6970. def encodeToByte(self,dec):
  6971. tens = math.floor(dec / 10)
  6972. ones = dec - tens*10
  6973. return (tens << 4) + ones
  6974. def decodeAlarmType(self,alarmTime):
  6975. if(len(alarmTime) > 4):
  6976. m1Bit = (alarmTime[3] & 0x80) >> 7
  6977. else:
  6978. m1Bit = False
  6979. m2Bit = (alarmTime[2] & 0x80) >> 7
  6980. m3Bit = (alarmTime[1] & 0x80) >> 7
  6981. m4Bit = (alarmTime[0] & 0x80) >> 7
  6982. dayBit = (alarmTime[0] & 0x40) >> 6
  6983. if(m1Bit and m2Bit and m3Bit and m4Bit):
  6984. return "everySecond"
  6985. elif(not m1Bit and m2Bit and m3Bit and m4Bit):
  6986. return "everyMinute"
  6987. elif(not m1Bit and not m2Bit and m3Bit and m4Bit):
  6988. return "everyHour"
  6989. elif(not m1Bit and not m2Bit and not m3Bit and m4Bit):
  6990. return "everyDay"
  6991. elif(not dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  6992. return "everyMonth"
  6993. elif(dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  6994. return "everyWeek"
  6995. else:
  6996. return "noValidAlarmType"
  6997. def decodeAlarmTime(self,alarmTime):
  6998. alarmTime[0] = decodeToDec(convertToByteType(alarmTime[0] & 0x3F))
  6999. alarmTime[1] = decodeToDec(convertToByteType(alarmTime[1] & 0x3F))
  7000. alarmTime[2] = decodeToDec(convertToByteType(alarmTime[2] & 0x7F))
  7001. if(len(alarmTime) > 4):
  7002. alarmTime[3] = decodeToDec(convertToByteType(alarmTime[3] & 0x7F))
  7003. return alarmTime
  7004. def encodeAlarmType(self,alarmType):
  7005. if(alarmType == "everySecond"):
  7006. return 15 #0b01111
  7007. elif(alarmType == "everyMinute"):
  7008. return 14 #0b01110
  7009. elif(alarmType == "everyHour"):
  7010. return 12 #0b01100
  7011. elif(alarmType == "everyDay"):
  7012. return 8 #0b01000
  7013. elif(alarmType == "everyMonth"):
  7014. return 0 #0b00000
  7015. elif(alarmType == "everyWeek"):
  7016. return 16 #0b10000
  7017. else:
  7018. raise ValueError("""Not a supported alarmType. Options are:
  7019. 'everySecond' (only Alarm 1), 'everyMinute', 'everyHour', 'everyDay', 'everyMonth', 'everyWeek'""")
  7020. def encodeDateTime(self,day, hour, minutes, seconds, alarmType):
  7021. alarmBits = encodeAlarmType(alarmType)
  7022. alarmTime = [0, 0, 0, 0]
  7023. alarmTime[0] = (encodeToByte(day) & 0x3F) | ((alarmBits & 0x10) << 2) | ((alarmBits & 0x08) << 4)
  7024. alarmTime[1] = (encodeToByte(hour) & 0x3F) | ((alarmBits & 0x04) << 5)
  7025. alarmTime[2] = (encodeToByte(minutes) & 0x7F) | ((alarmBits & 0x02) << 6)
  7026. alarmTime[3] = (encodeToByte(seconds) & 0x7F) | ((alarmBits & 0x01) << 7)
  7027. return alarmTime
  7028. rtc=DS3231()
  7029. `;
  7030. var code = `rtc.setYear(${year})
  7031. rtc.setMonth(${month})
  7032. rtc.setDay(${day})
  7033. rtc.setDayOfWeek(${week})
  7034. rtc.setHour(${hour})
  7035. rtc.setMinutes(${minutes})
  7036. rtc.setSeconds(${seconds})\n`;
  7037. return code;
  7038. };
  7039. // v831_real_time_clock
  7040. Blockly.Blocks['v831_real_time_clock'] = {
  7041. init: function () {
  7042. this.appendDummyInput()
  7043. .appendField("IIC"+Blockly.Msg.RTC_getDateTime)
  7044. .appendField(new Blockly.FieldDropdown([
  7045. [Blockly.Msg.time_get_current_date_y, "getYear"],
  7046. [Blockly.Msg.time_get_current_date_m, "getMonth"],
  7047. [Blockly.Msg.time_get_current_date_d, "getDay"],
  7048. [Blockly.Msg.RTC_SETWEEK, "getDayOfWeek"],
  7049. [Blockly.Msg.time_get_current_date_hour, "getHour"],
  7050. [Blockly.Msg.time_get_current_date_min, "getMinutes"],
  7051. [Blockly.Msg.time_get_current_date_sec, "getSeconds"]
  7052. ]), "type");
  7053. this.setInputsInline(false);
  7054. this.setOutput(true, null);
  7055. this.setColour("#d42b03");
  7056. this.setHelpUrl("");
  7057. this.setTooltip(Blockly.Msg.RTC_getDateTime);
  7058. }
  7059. };
  7060. Blockly.Python['v831_real_time_clock'] = function (block) {
  7061. var dropdown_type = block.getFieldValue('type');
  7062. // TODO: Assemble Python into code variable.
  7063. Blockly.Python.definitions_['v831_import_smbus2'] = 'import smbus2';
  7064. Blockly.Python.definitions_['v831_import_math'] = 'import math';
  7065. Blockly.Python.definitions_['v831_import_time'] = 'import time';
  7066. Blockly.Python.definitions_['v831_real_time_clock_init'] = `class DS3231(object):
  7067. # create RTC instance
  7068. def __init__(self):
  7069. self.bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  7070. self.address = 0x68
  7071. def bcd_to_int(self,bcd, n=2):
  7072. """Decode n least significant packed binary coded decimal digits to binary.
  7073. Return binary result.
  7074. n defaults to 2 (BCD digits).
  7075. n=0 decodes all digits.
  7076. """
  7077. return int(('%x' % bcd)[-n:])
  7078. def int_to_bcd(self,x, n=2):
  7079. """
  7080. Encode the n least significant decimal digits of x
  7081. to packed binary coded decimal (BCD).
  7082. Return packed BCD value.
  7083. n defaults to 2 (digits).
  7084. n=0 encodes all digits.
  7085. """
  7086. return int(str(x)[-n:], 0x10)
  7087. def read(self, addr):
  7088. for i in range(0, 3):
  7089. try:
  7090. tmp = self.bus.read_byte_data(self.address, addr)
  7091. time.sleep(0.001) # 1ms
  7092. # print(addr, tmp) # debug
  7093. return tmp
  7094. except Exception:
  7095. time.sleep(0.01)
  7096. continue
  7097. return None
  7098. def write(self, addr, val):
  7099. for i in range(0, 3):
  7100. try:
  7101. self.bus.write_byte_data(self.address, addr, val)
  7102. #time.sleep(0.001) # 1ms
  7103. # print(addr, val) # debug
  7104. return True
  7105. except Exception:
  7106. time.sleep(0.001)
  7107. continue
  7108. return False
  7109. # set times functions ---------------------------------------------------------------------
  7110. def setYear(self, year):
  7111. # only last two digits (last two digits are used if longer)
  7112. self.write(0x06, self.int_to_bcd(year%100))
  7113. def setMonth(self, month):
  7114. if not 1 <= month <= 12:
  7115. raise ValueError('Month is out of range [1,12].')
  7116. self.write(0x05,self.int_to_bcd(month))
  7117. def setDay(self, day):
  7118. if not 1 <= day <= 31:
  7119. raise ValueError('Day is out of range [1,31].')
  7120. self.write(0x04,self.int_to_bcd(day))
  7121. def setDayOfWeek(self, dayOfWeek):
  7122. if not 1 <= dayOfWeek <= 7:
  7123. raise ValueError('Day of week is out of range [1,7].')
  7124. self.write(0x03,self.int_to_bcd(dayOfWeek))
  7125. def setHour(self, hour):
  7126. if not 0 <= hour < 24:
  7127. raise ValueError('Hour is out of range [0,23].')
  7128. self.write(0x02,self.int_to_bcd(hour)& 0x3F)
  7129. def setMinutes(self, minutes):
  7130. if not 0 <= minutes < 59:
  7131. raise ValueError('Minutes is out of range [0,59].')
  7132. self.write(0x01,self.int_to_bcd(minutes))
  7133. def setSeconds(self, seconds):
  7134. if not 0 <= seconds < 60:
  7135. raise ValueError('Seconds is out of range [0,59].')
  7136. self.write(0x00,self.int_to_bcd(seconds))
  7137. def setDateTime(self, year, month, day, dayOfWeek, hour, minutes, seconds):
  7138. # set all the date and times (year is last two digits of year)
  7139. self.setYear(year)
  7140. self.setMonth(month)
  7141. self.setDay(day)
  7142. self.setDayOfWeek(dayOfWeek)
  7143. self.setHour(hour)
  7144. self.setMinutes(minutes)
  7145. self.setSeconds(seconds)
  7146. # get times functions -------------------------------------------------
  7147. def getYear(self):
  7148. return self.bcd_to_int(self.read(0x06))
  7149. def getMonth(self):
  7150. temp = self.read(0x05)
  7151. return self.bcd_to_int((temp<<4>>4) &0x7F)
  7152. #return temp[0] & 0x7F
  7153. def getDay(self):
  7154. # 0 - 31
  7155. return self.bcd_to_int(self.read(0x04))
  7156. def getDayOfWeek(self):
  7157. # 1 - 7
  7158. return self.bcd_to_int(self.read(0x03))
  7159. def getHour(self):
  7160. temp = self.read(0x02)
  7161. if temp==0x64: #if hour is 24:00,convert it to 00:00
  7162. temp=0x40
  7163. return self.bcd_to_int((temp<< 4 >>4)& 0x3F)
  7164. #return temp[0] & 0x3F
  7165. def getMinutes(self):
  7166. return self.bcd_to_int(self.read(0x01))
  7167. def getSeconds(self):
  7168. return self.bcd_to_int(self.read(0x00))
  7169. def getDateTime(self):
  7170. # returns whole date and time as list
  7171. # (last two digits of year, month, day, day of week, hour, minutes, seconds)
  7172. dateTime = [0, 0, 0, 0, 0, 0, 0]
  7173. dateTime[0] = self.getYear()
  7174. dateTime[1] = self.getMonth()
  7175. dateTime[2] = self.getDay()
  7176. dateTime[3] = self.getDayOfWeek()
  7177. dateTime[4] = self.getHour()
  7178. dateTime[5] = self.getMinutes()
  7179. dateTime[6] = self.getSeconds()
  7180. return dateTime
  7181. def convertToByteType(self,number):
  7182. return bytes([number])
  7183. def decodeToDec(self,byte):
  7184. return ((byte[0] >> 4) * 10) + (byte[0] & 0x0F)
  7185. def encodeToByte(self,dec):
  7186. tens = math.floor(dec / 10)
  7187. ones = dec - tens*10
  7188. return (tens << 4) + ones
  7189. def decodeAlarmType(self,alarmTime):
  7190. if(len(alarmTime) > 4):
  7191. m1Bit = (alarmTime[3] & 0x80) >> 7
  7192. else:
  7193. m1Bit = False
  7194. m2Bit = (alarmTime[2] & 0x80) >> 7
  7195. m3Bit = (alarmTime[1] & 0x80) >> 7
  7196. m4Bit = (alarmTime[0] & 0x80) >> 7
  7197. dayBit = (alarmTime[0] & 0x40) >> 6
  7198. if(m1Bit and m2Bit and m3Bit and m4Bit):
  7199. return "everySecond"
  7200. elif(not m1Bit and m2Bit and m3Bit and m4Bit):
  7201. return "everyMinute"
  7202. elif(not m1Bit and not m2Bit and m3Bit and m4Bit):
  7203. return "everyHour"
  7204. elif(not m1Bit and not m2Bit and not m3Bit and m4Bit):
  7205. return "everyDay"
  7206. elif(not dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  7207. return "everyMonth"
  7208. elif(dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  7209. return "everyWeek"
  7210. else:
  7211. return "noValidAlarmType"
  7212. def decodeAlarmTime(self,alarmTime):
  7213. alarmTime[0] = decodeToDec(convertToByteType(alarmTime[0] & 0x3F))
  7214. alarmTime[1] = decodeToDec(convertToByteType(alarmTime[1] & 0x3F))
  7215. alarmTime[2] = decodeToDec(convertToByteType(alarmTime[2] & 0x7F))
  7216. if(len(alarmTime) > 4):
  7217. alarmTime[3] = decodeToDec(convertToByteType(alarmTime[3] & 0x7F))
  7218. return alarmTime
  7219. def encodeAlarmType(self,alarmType):
  7220. if(alarmType == "everySecond"):
  7221. return 15 #0b01111
  7222. elif(alarmType == "everyMinute"):
  7223. return 14 #0b01110
  7224. elif(alarmType == "everyHour"):
  7225. return 12 #0b01100
  7226. elif(alarmType == "everyDay"):
  7227. return 8 #0b01000
  7228. elif(alarmType == "everyMonth"):
  7229. return 0 #0b00000
  7230. elif(alarmType == "everyWeek"):
  7231. return 16 #0b10000
  7232. else:
  7233. raise ValueError("""Not a supported alarmType. Options are:
  7234. 'everySecond' (only Alarm 1), 'everyMinute', 'everyHour', 'everyDay', 'everyMonth', 'everyWeek'""")
  7235. def encodeDateTime(self,day, hour, minutes, seconds, alarmType):
  7236. alarmBits = encodeAlarmType(alarmType)
  7237. alarmTime = [0, 0, 0, 0]
  7238. alarmTime[0] = (encodeToByte(day) & 0x3F) | ((alarmBits & 0x10) << 2) | ((alarmBits & 0x08) << 4)
  7239. alarmTime[1] = (encodeToByte(hour) & 0x3F) | ((alarmBits & 0x04) << 5)
  7240. alarmTime[2] = (encodeToByte(minutes) & 0x7F) | ((alarmBits & 0x02) << 6)
  7241. alarmTime[3] = (encodeToByte(seconds) & 0x7F) | ((alarmBits & 0x01) << 7)
  7242. return alarmTime
  7243. rtc=DS3231()
  7244. `;
  7245. var code = `rtc.${dropdown_type}()`;
  7246. return [code, Blockly.Python.ORDER_ATOMIC];
  7247. };