esp32.js 319 KB

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