esp32.js 319 KB

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