38_netatmo.pm 229 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458
  1. ##############################################################################
  2. # $Id: 38_netatmo.pm 16324 2018-03-03 22:39:33Z moises $
  3. #
  4. # 38_netatmo.pm
  5. #
  6. # 2018 Markus Moises < vorname at nachname . de >
  7. #
  8. # Based on original code by justme1968
  9. #
  10. # https://forum.fhem.de/index.php/topic,53500.0.html
  11. #
  12. #
  13. ##############################################################################
  14. # Release 17 / 2018-03-03
  15. package main;
  16. use strict;
  17. use warnings;
  18. use Encode qw(encode_utf8 decode_utf8);
  19. use JSON;
  20. use Math::Trig;
  21. use HttpUtils;
  22. use Data::Dumper; #debugging
  23. use MIME::Base64;
  24. use vars qw($FW_ME);
  25. use vars qw($FW_CSRF);
  26. my %health_index = ( 0 => "healthy",
  27. 1 => "fine",
  28. 2 => "fair",
  29. 3 => "poor",
  30. 4 => "unhealthy",
  31. 5 => "unknown", );
  32. sub
  33. netatmo_Initialize($)
  34. {
  35. my ($hash) = @_;
  36. $hash->{DefFn} = "netatmo_Define";
  37. $hash->{NotifyFn} = "netatmo_Notify";
  38. $hash->{UndefFn} = "netatmo_Undefine";
  39. $hash->{SetFn} = "netatmo_Set";
  40. $hash->{GetFn} = "netatmo_Get";
  41. $hash->{DbLog_splitFn} = "netatmo_DbLog_splitFn";
  42. $hash->{AttrFn} = "netatmo_Attr";
  43. $hash->{AttrList} = "IODev ".
  44. "disable:0,1 ".
  45. "interval ".
  46. "videoquality:poor,low,medium,high ".
  47. "ignored_device_ids ".
  48. "setpoint_duration ".
  49. "webhookURL webhookPoll:0,1 ".
  50. "addresslimit ".
  51. "serverAPI ";
  52. $hash->{AttrList} .= $readingFnAttributes;
  53. }
  54. #####################################
  55. sub
  56. netatmo_Define($$)
  57. {
  58. my ($hash, $def) = @_;
  59. my @a = split("[ \t][ \t]*", $def);
  60. my $name = $a[0];
  61. $hash->{status} = "initialized";
  62. $hash->{helper}{last_status_store} = 0;
  63. my $subtype;
  64. if($a[2] eq "WEBHOOK") {
  65. $subtype = "WEBHOOK";
  66. my $d = $modules{$hash->{TYPE}}{defptr}{"WEBHOOK"};
  67. return "Netatmo webkook already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  68. $modules{$hash->{TYPE}}{defptr}{"WEBHOOK"} = $hash;
  69. readingsBeginUpdate($hash);
  70. readingsBulkUpdate( $hash, "webhook", "initialized" );
  71. readingsEndUpdate( $hash, 1 );
  72. my $account = $modules{$hash->{TYPE}}{defptr}{"account"};
  73. $hash->{IODev} = $account;
  74. $attr{$name}{IODev} = $account->{NAME} if( !defined($attr{$name}{IODev}) && $account);
  75. }
  76. elsif( @a == 3 ) {
  77. $subtype = "DEVICE";
  78. my $device = $a[2];
  79. $hash->{Device} = $device;
  80. $hash->{openRequests} = 0;
  81. $hash->{helper}{INTERVAL} = 60*15 if( !$hash->{helper}{INTERVAL} );
  82. my $d = $modules{$hash->{TYPE}}{defptr}{"D$device"};
  83. return "device $device already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  84. $modules{$hash->{TYPE}}{defptr}{"D$device"} = $hash;
  85. }
  86. elsif( ($a[2] eq "PUBLIC" && @a > 3 ) )
  87. {
  88. $hash->{openRequests} = 0;
  89. Log3 $name, 5, "$name: pub ".Dumper(@a);
  90. if( $a[3] && $a[3] =~ m/[\da-f]{2}(:[\da-f]{2}){5}/ )
  91. {
  92. my $device = $a[3];
  93. $hash->{Device} = $device;
  94. if( $a[4] && $a[4] =~ m/[\da-f]{2}(:[\da-f]{2}){5}/ )
  95. {
  96. $subtype = "MODULE";
  97. my $module = "";
  98. my $readings = "";
  99. my @a = splice( @a, 4 );
  100. while( @a ) {
  101. $module .= " " if( $module );
  102. $module .= shift( @a );
  103. $readings .= " " if( $readings );
  104. $readings .= shift( @a );
  105. }
  106. $hash->{Module} = $module;
  107. $hash->{dataTypes} = $readings if($readings);
  108. $hash->{dataTypes} = "Temperature,CO2,Humidity,Noise,Pressure,Rain,WindStrength,WindAngle,GustStrength,GustAngle,Sp_Temperature,BoilerOn,BoilerOff" if( !$readings );
  109. my $d = $modules{$hash->{TYPE}}{defptr}{"M$module"};
  110. return "module $module already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  111. $modules{$hash->{TYPE}}{defptr}{"M$module"} = $hash;
  112. my $state_format;
  113. if( $readings =~ m/temperature/ ) {
  114. $state_format .= " " if( $state_format );
  115. $state_format .= "T: temperature";
  116. }
  117. if( $readings =~ m/humidity/ ) {
  118. $state_format .= " " if( $state_format );
  119. $state_format .= "H: humidity";
  120. }
  121. $attr{$name}{stateFormat} = $state_format if( !defined($attr{$name}{stateFormat}) && defined($state_format) && defined($name) );
  122. $attr{$name}{room} = "netatmo" if( !defined($attr{$name}{room}) && defined($name));
  123. $attr{$name}{devStateIcon} = ".*:no-icon" if( !defined($attr{$name}{devStateIcon}) && defined($name));
  124. }
  125. $subtype = "DEVICE";
  126. my $d = $modules{$hash->{TYPE}}{defptr}{"D$device"};
  127. return "device $device already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  128. $modules{$hash->{TYPE}}{defptr}{"D$device"} = $hash;
  129. delete( $hash->{LAST_POLL} );
  130. }
  131. else
  132. {
  133. my ($lat, $lon, $rad);
  134. if($a[3] =~ m/,/){
  135. Log3 $name, 5, "$name: latlng 2 ".$a[3];
  136. my @latlon = split( ',', $a[3] );
  137. $lat = $latlon[0];
  138. $lon = $latlon[1];
  139. $rad = $a[4];
  140. }
  141. else {
  142. $lat = $a[3];
  143. $lon = $a[4];
  144. $rad = $a[5];
  145. }
  146. $rad = 0.02 if( !$rad );
  147. $hash->{Lat} = $lat;
  148. $hash->{Lon} = $lon;
  149. $hash->{Rad} = $rad;
  150. $subtype = "PUBLIC";
  151. $modules{$hash->{TYPE}}{defptr}{$hash->{Lat}.$hash->{Lon}.$hash->{Rad}} = $hash;
  152. my $account = $modules{$hash->{TYPE}}{defptr}{"account"};
  153. $hash->{IODev} = $account;
  154. $attr{$name}{IODev} = $account->{NAME} if( !defined($attr{$name}{IODev}) && $account);
  155. }
  156. $hash->{helper}{INTERVAL} = 60*30 if( !$hash->{helper}{INTERVAL} );
  157. $attr{$name}{room} = "netatmo" if( !defined($attr{$name}{room}) && defined($name));
  158. $attr{$name}{devStateIcon} = ".*:no-icon" if( !defined($attr{$name}{devStateIcon}) && defined($name));
  159. } elsif( ($a[2] eq "MODULE" && @a == 5 ) ) {
  160. $subtype = "MODULE";
  161. my $device = $a[@a-2];
  162. my $module = $a[@a-1];
  163. $hash->{Device} = $device;
  164. $hash->{Module} = $module;
  165. $hash->{openRequests} = 0;
  166. $hash->{helper}{INTERVAL} = 60*15 if( !$hash->{helper}{INTERVAL} );
  167. my $d = $modules{$hash->{TYPE}}{defptr}{"M$module"};
  168. return "module $module already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  169. $modules{$hash->{TYPE}}{defptr}{"M$module"} = $hash;
  170. } elsif( ($a[2] eq "FORECAST" && @a == 4 ) ) {
  171. $subtype = "FORECAST";
  172. my $device = $a[3];
  173. $hash->{Station} = $device;
  174. $hash->{openRequests} = 0;
  175. $hash->{helper}{INTERVAL} = 60*60 if( !$hash->{helper}{INTERVAL} );
  176. $attr{$name}{room} = "netatmo" if( !defined($attr{$name}{room}) && defined($name));
  177. $attr{$name}{devStateIcon} = ".*:no-icon" if( !defined($attr{$name}{devStateIcon}) && defined($name));
  178. $attr{$name}{'event-on-change-reading'} = ".*" if( !defined($attr{$name}{'event-on-change-reading'}) && defined($name));
  179. my $d = $modules{$hash->{TYPE}}{defptr}{"F$device"};
  180. return "forecast $device already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  181. $modules{$hash->{TYPE}}{defptr}{"F$device"} = $hash;
  182. my $account = $modules{$hash->{TYPE}}{defptr}{"account"};
  183. $hash->{IODev} = $account;
  184. $attr{$name}{IODev} = $account->{NAME} if( !defined($attr{$name}{IODev}) && $account);
  185. } elsif( ($a[2] eq "RELAY" && @a == 4 ) ) {
  186. $subtype = "RELAY";
  187. my $device = $a[3];
  188. $hash->{Relay} = $device;
  189. $hash->{openRequests} = 0;
  190. $hash->{helper}{INTERVAL} = 60*30 if( !$hash->{helper}{INTERVAL} );
  191. my $d = $modules{$hash->{TYPE}}{defptr}{"R$device"};
  192. return "relay $device already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  193. $modules{$hash->{TYPE}}{defptr}{"R$device"} = $hash;
  194. } elsif( ($a[2] eq "THERMOSTAT" && @a == 5 ) ) {
  195. $subtype = "THERMOSTAT";
  196. my $device = $a[@a-2];
  197. my $module = $a[@a-1];
  198. $hash->{Relay} = $device;
  199. $hash->{Thermostat} = $module;
  200. $hash->{openRequests} = 0;
  201. $hash->{dataTypes} = "Temperature,Sp_Temperature,BoilerOn,BoilerOff";
  202. $hash->{helper}{INTERVAL} = 60*30 if( !$hash->{helper}{INTERVAL} );
  203. my $d = $modules{$hash->{TYPE}}{defptr}{"T$module"};
  204. return "thermostat $module already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  205. $modules{$hash->{TYPE}}{defptr}{"T$module"} = $hash;
  206. } elsif( ($a[2] eq "HEATINGHOME" && @a == 4 ) ) {
  207. $subtype = "HEATINGHOME";
  208. my $home = $a[@a-1];
  209. $hash->{Home} = $home;
  210. $hash->{openRequests} = 0;
  211. #$hash->{dataTypes} = "Temperature,Sp_Temperature,BoilerOn,BoilerOff";
  212. $hash->{helper}{INTERVAL} = 60*30 if( !$hash->{helper}{INTERVAL} );
  213. my $d = $modules{$hash->{TYPE}}{defptr}{"E$home"};
  214. return "heating home $home already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  215. $modules{$hash->{TYPE}}{defptr}{"E$home"} = $hash;
  216. } elsif( ($a[2] eq "HEATINGROOM" && @a == 5 ) ) {
  217. $subtype = "HEATINGROOM";
  218. my $room = $a[@a-1];
  219. my $home = $a[@a-2];
  220. $hash->{Home} = $home;
  221. $hash->{Room} = $room;
  222. $hash->{openRequests} = 0;
  223. $hash->{dataTypes} = "Temperature,Sp_Temperature,heating_power_request,BoilerOn,BoilerOff";
  224. $hash->{helper}{INTERVAL} = 60*30 if( !$hash->{helper}{INTERVAL} );
  225. my $d = $modules{$hash->{TYPE}}{defptr}{"O$room"};
  226. return "heating room $room already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  227. $modules{$hash->{TYPE}}{defptr}{"O$room"} = $hash;
  228. } elsif( ($a[2] eq "HOME" && @a == 4 ) ) {
  229. $subtype = "HOME";
  230. my $home = $a[@a-1];
  231. $hash->{Home} = $home;
  232. $hash->{helper}{INTERVAL} = 60*15 if( !$hash->{helper}{INTERVAL} );
  233. $attr{$name}{videoquality} = "medium" if( !defined($attr{$name}{videoquality}) && defined($name));
  234. my $d = $modules{$hash->{TYPE}}{defptr}{"H$home"};
  235. return "home $home already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  236. $modules{$hash->{TYPE}}{defptr}{"H$home"} = $hash;
  237. } elsif( ($a[2] eq "PERSON" && @a == 5 ) ) {
  238. $subtype = "PERSON";
  239. my $home = $a[@a-2];
  240. my $person = $a[@a-1];
  241. $hash->{Home} = $home;
  242. $hash->{Person} = $person;
  243. $hash->{helper}{INTERVAL} = 60*15 if( !$hash->{helper}{INTERVAL} );
  244. my $d = $modules{$hash->{TYPE}}{defptr}{"P$person"};
  245. return "person $person already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  246. $modules{$hash->{TYPE}}{defptr}{"P$person"} = $hash;
  247. } elsif( ($a[2] eq "CAMERA" && @a == 5 ) ) {
  248. $subtype = "CAMERA";
  249. my $home = $a[@a-2];
  250. my $camera = $a[@a-1];
  251. $hash->{Home} = $home;
  252. $hash->{Camera} = $camera;
  253. $hash->{helper}{INTERVAL} = 60*15 if( !$hash->{helper}{INTERVAL} );
  254. my $d = $modules{$hash->{TYPE}}{defptr}{"C$camera"};
  255. return "camera $camera already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  256. $modules{$hash->{TYPE}}{defptr}{"C$camera"} = $hash;
  257. } elsif( ($a[2] eq "TAG" && @a == 5 ) ) {
  258. $subtype = "TAG";
  259. my $camera = $a[@a-2];
  260. my $tag = $a[@a-1];
  261. $hash->{Tag} = $tag;
  262. $hash->{Camera} = $camera;
  263. #$hash->{helper}{INTERVAL} = 60*15 if( !$hash->{helper}{INTERVAL} );
  264. my $d = $modules{$hash->{TYPE}}{defptr}{"G$tag"};
  265. return "tag $tag already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  266. $modules{$hash->{TYPE}}{defptr}{"G$tag"} = $hash;
  267. } elsif( @a == 6 || ($a[2] eq "ACCOUNT" && @a == 7 ) ) {
  268. $subtype = "ACCOUNT";
  269. $hash->{network} = "ok";
  270. delete($hash->{access_token});
  271. delete($hash->{access_token_app});
  272. delete($hash->{refresh_token});
  273. delete($hash->{refresh_token_app});
  274. delete($hash->{expires_at});
  275. delete($hash->{expires_at_app});
  276. delete($hash->{csrf_token});
  277. my $user = $a[@a-4];
  278. my $pass = $a[@a-3];
  279. my $username = netatmo_encrypt($user);
  280. my $password = netatmo_encrypt($pass);
  281. Log3 $name, 2, "$name: encrypt $user/$pass to $username/$password" if($user ne $username || $pass ne $password);
  282. my $client_id = $a[@a-2];
  283. my $client_secret = $a[@a-1];
  284. #$hash->{DEF} =~ s/$user/$username/g;
  285. #$hash->{DEF} =~ s/$pass/$password/g;
  286. $hash->{DEF} = "ACCOUNT $username $password $client_id $client_secret";
  287. $hash->{Clients} = ":netatmo:";
  288. $hash->{helper}{username} = $username;
  289. $hash->{helper}{password} = $password;
  290. $hash->{helper}{client_id} = $client_id;
  291. $hash->{helper}{client_secret} = $client_secret;
  292. $hash->{helper}{INTERVAL} = 60*60 if( !$hash->{helper}{INTERVAL} );
  293. $attr{$name}{room} = "netatmo" if( !defined($attr{$name}{room}) && defined($name));
  294. $modules{$hash->{TYPE}}{defptr}{"account"} = $hash;
  295. $hash->{helper}{apiserver} = AttrVal($name, "serverAPI", "api.netatmo.com");
  296. } else {
  297. return "Usage: define <name> netatmo device\
  298. define <name> netatmo userid publickey\
  299. define <name> netatmo PUBLIC latitude longitude [radius]\
  300. define <name> netatmo [ACCOUNT] username password" if(@a < 3 || @a > 5);
  301. }
  302. $hash->{NAME} = $name;
  303. $hash->{SUBTYPE} = $subtype;
  304. $hash->{STATE} = "Initialized";
  305. $hash->{NOTIFYDEV} = "global";
  306. if( $init_done ) {
  307. netatmo_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
  308. netatmo_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
  309. netatmo_initDevice($hash) if( $hash->{SUBTYPE} eq "MODULE" );
  310. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "PUBLIC" );
  311. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "FORECAST" );
  312. netatmo_initHome($hash) if( $hash->{SUBTYPE} eq "HOME" );
  313. netatmo_pingCamera($hash) if( $hash->{SUBTYPE} eq "CAMERA" );
  314. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "RELAY" );
  315. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "THERMOSTAT" );
  316. netatmo_initHeatingHome($hash) if( $hash->{SUBTYPE} eq "HEATINGHOME" );
  317. #netatmo_initHeatingRoom($hash) if( $hash->{SUBTYPE} eq "HEATINGROOM" );
  318. netatmo_addExtension($hash) if( $hash->{SUBTYPE} eq "WEBHOOK" );
  319. }
  320. else
  321. {
  322. InternalTimer(gettimeofday()+120, "netatmo_InitWait", $hash);
  323. }
  324. return undef;
  325. }
  326. sub netatmo_InitWait($) {
  327. my ($hash) = @_;
  328. my $name = $hash->{NAME};
  329. Log3 "netatmo", 5, "netatmo: initwait ".$init_done;
  330. RemoveInternalTimer($hash);
  331. if( $init_done ) {
  332. netatmo_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
  333. netatmo_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
  334. netatmo_initDevice($hash) if( $hash->{SUBTYPE} eq "MODULE" );
  335. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "PUBLIC" );
  336. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "FORECAST" );
  337. netatmo_initHome($hash) if( $hash->{SUBTYPE} eq "HOME" );
  338. netatmo_pingCamera($hash) if( $hash->{SUBTYPE} eq "CAMERA" );
  339. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "RELAY" );
  340. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "THERMOSTAT" );
  341. netatmo_initHeatingHome($hash) if( $hash->{SUBTYPE} eq "HEATINGHOME" );
  342. #netatmo_initHeatingRoom($hash) if( $hash->{SUBTYPE} eq "HEATINGROOM" );
  343. netatmo_addExtension($hash) if( $hash->{SUBTYPE} eq "WEBHOOK" );
  344. }
  345. else
  346. {
  347. InternalTimer(gettimeofday()+120, "netatmo_InitWait", $hash);
  348. }
  349. return undef;
  350. }
  351. sub
  352. netatmo_Notify($$)
  353. {
  354. my ($hash,$dev) = @_;
  355. my $name = $hash->{NAME};
  356. return if($dev->{NAME} ne "global");
  357. return if(!grep(m/^INITIALIZED|REREADCFG$/, @{$dev->{CHANGED}}));
  358. RemoveInternalTimer($hash);
  359. netatmo_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
  360. netatmo_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
  361. netatmo_initDevice($hash) if( $hash->{SUBTYPE} eq "MODULE" );
  362. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "PUBLIC" );
  363. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "FORECAST" );
  364. netatmo_initHome($hash) if( $hash->{SUBTYPE} eq "HOME" );
  365. netatmo_pingCamera($hash) if( $hash->{SUBTYPE} eq "CAMERA" );
  366. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "RELAY" );
  367. netatmo_poll($hash) if( $hash->{SUBTYPE} eq "THERMOSTAT" );
  368. netatmo_initHeatingHome($hash) if( $hash->{SUBTYPE} eq "HEATINGHOME" );
  369. #netatmo_initHeatingRoom($hash) if( $hash->{SUBTYPE} eq "HEATINGROOM" );
  370. netatmo_addExtension($hash) if( $hash->{SUBTYPE} eq "WEBHOOK" );
  371. return undef;
  372. }
  373. sub
  374. netatmo_Undefine($$)
  375. {
  376. my ($hash, $arg) = @_;
  377. RemoveInternalTimer($hash);
  378. delete( $modules{$hash->{TYPE}}{defptr}{"D$hash->{Device}"} ) if( $hash->{SUBTYPE} eq "DEVICE" );
  379. delete( $modules{$hash->{TYPE}}{defptr}{"M$hash->{Module}"} ) if( $hash->{SUBTYPE} eq "MODULE" );
  380. delete( $modules{$hash->{TYPE}}{defptr}{$hash->{Lat}.$hash->{Lon}.$hash->{Rad}} ) if( $hash->{SUBTYPE} eq "PUBLIC" );
  381. delete( $modules{$hash->{TYPE}}{defptr}{"F$hash->{Station}"} ) if( $hash->{SUBTYPE} eq "FORECAST" );
  382. delete( $modules{$hash->{TYPE}}{defptr}{"H$hash->{Home}"} ) if( $hash->{SUBTYPE} eq "HOME" );
  383. delete( $modules{$hash->{TYPE}}{defptr}{"C$hash->{Camera}"} ) if( $hash->{SUBTYPE} eq "CAMERA" );
  384. delete( $modules{$hash->{TYPE}}{defptr}{"P$hash->{Person}"} ) if( $hash->{SUBTYPE} eq "PERSON" );
  385. delete( $modules{$hash->{TYPE}}{defptr}{"R$hash->{Relay}"} ) if( $hash->{SUBTYPE} eq "RELAY" );
  386. delete( $modules{$hash->{TYPE}}{defptr}{"T$hash->{Thermostat}"} ) if( $hash->{SUBTYPE} eq "THERMOSTAT" );
  387. delete( $modules{$hash->{TYPE}}{defptr}{"E$hash->{Home}"} ) if( $hash->{SUBTYPE} eq "HEATINGHOME" );
  388. delete( $modules{$hash->{TYPE}}{defptr}{"O$hash->{Room}"} ) if( $hash->{SUBTYPE} eq "HEATINGROOM" );
  389. netatmo_removeExtension($hash) if( $hash->{SUBTYPE} eq "WEBHOOK" );
  390. return undef;
  391. }
  392. sub
  393. netatmo_Set($$@)
  394. {
  395. my ($hash, $name, $cmd, @parameters) = @_;
  396. $hash->{SUBTYPE} = "unknown" if(!defined($hash->{SUBTYPE}));
  397. my $list = "";
  398. $list = "autocreate:noArg autocreate_homes:noArg autocreate_thermostats:noArg autocreate_homecoachs:noArg" if( $hash->{SUBTYPE} eq "ACCOUNT" );
  399. #$list .= " unban:noArg" if( $hash->{SUBTYPE} eq "ACCOUNT" );
  400. $list = "home:noArg away:noArg" if ($hash->{SUBTYPE} eq "PERSON");
  401. $list = "empty:noArg notify_movements:never,empty,always notify_unknowns:empty,always record_movements:never,empty,always record_alarms:never,empty,always presence_record_humans:ignore,record,record_and_notify presence_record_vehicles:ignore,record,record_and_notify presence_record_animals:ignore,record,record_and_notify presence_record_movements:ignore,record,record_and_notify presence_record_alarms:ignore,record,record_and_notify gone_after presence_enable_notify_from_to:empty,always presence_notify_from presence_notify_to smart_notifs:on,off" if ($hash->{SUBTYPE} eq "HOME");
  402. $list = "enable disable irmode:auto,always,never led_on_live:on,off mirror:off,on audio:on,off" if ($hash->{SUBTYPE} eq "CAMERA");
  403. $list = "enable disable light_mode:auto,on,off floodlight intensity:slider,0,1,100 night_always:true,false night_person:true,false night_vehicle:true,false night_animal:true,false night_movement:true,false" if ($hash->{SUBTYPE} eq "CAMERA" && defined($hash->{model}) && $hash->{model} eq "NOC");
  404. $list = "calibrate:noArg" if ($hash->{SUBTYPE} eq "TAG");
  405. if ($hash->{SUBTYPE} eq "THERMOSTAT" || $hash->{SUBTYPE} eq "HEATINGROOM")
  406. {
  407. $list = "setpoint_mode:off,hg,away,program,manual,max setpoint_temp:5.0,5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.0,10.5,11.0,11.5,12.0,12.5,13.0,13.5,14.0,14.5,15.0,15.5,16.0,16.5,17.0,17.5,18.0,18.5,19.0,19.5,20.0,20.5,21.0,21.5,22.0,22.5,23.0,23.5,24.0,24.5,25.0,25.5,26.0,26.5,27.0,27.5,28.0,28.5,29.0,29.5,30.0";
  408. $list = "setpoint_mode:off,hg,away,program,manual,max program:".$hash->{schedulenames}." setpoint_temp:5.0,5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.0,10.5,11.0,11.5,12.0,12.5,13.0,13.5,14.0,14.5,15.0,15.5,16.0,16.5,17.0,17.5,18.0,18.5,19.0,19.5,20.0,20.5,21.0,21.5,22.0,22.5,23.0,23.5,24.0,24.5,25.0,25.5,26.0,26.5,27.0,27.5,28.0,28.5,29.0,29.5,30.0" if(defined($hash->{schedulenames}));
  409. }
  410. $list = "clear:noArg webhook:add,drop" if ($hash->{SUBTYPE} eq "WEBHOOK");
  411. return undef if( $list eq "" );
  412. if( $cmd eq "autocreate" ) {
  413. return netatmo_autocreate($hash, 1 );
  414. return undef;
  415. }
  416. elsif( $cmd eq "autocreate_homes" ) {
  417. return netatmo_autocreatehome($hash, 1 );
  418. return undef;
  419. }
  420. elsif( $cmd eq "autocreate_thermostats" ) {
  421. return netatmo_autocreatethermostat($hash, 1 );
  422. return undef;
  423. }
  424. elsif( $cmd eq "autocreate_homecoachs" ) {
  425. return netatmo_autocreatehomecoach($hash, 1 );
  426. return undef;
  427. }
  428. elsif( $cmd eq "home" ) {
  429. return netatmo_setPresence($hash, "home");
  430. return undef;
  431. }
  432. elsif( $cmd eq "away" ) {
  433. return netatmo_setPresence($hash, "away");
  434. return undef;
  435. }
  436. elsif( $cmd eq "empty" ) {
  437. return netatmo_setPresence($hash, "empty");
  438. return undef;
  439. }
  440. elsif( $cmd =~ /^notify_/ || $cmd =~ /^record_/ || $cmd =~ /^presence_/ || $cmd eq "gone_after" || $cmd eq "smart_notifs" ) {
  441. return netatmo_setNotifications($hash, $cmd, $parameters[0]);
  442. return undef;
  443. }
  444. elsif( $cmd eq "enable" ) {
  445. my $pin = $parameters[0];
  446. $pin = "0000" if(!defined($pin) || length($pin) != 4);
  447. return netatmo_setCamera($hash, "on", $pin);
  448. return undef;
  449. }
  450. elsif( $cmd eq "disable" ) {
  451. my $pin = $parameters[0];
  452. $pin = "0000" if(!defined($pin) || length($pin) != 4);
  453. $hash->{pin} = $pin;
  454. return netatmo_setCamera($hash, "off", $pin);
  455. return undef;
  456. }
  457. elsif( $cmd eq "irmode" || $cmd eq "led_on_live" || $cmd eq "mirror" || $cmd eq "audio" ) {
  458. my $setting = $parameters[0];
  459. return "You have to define a value" if(!defined($setting) || $setting eq "");
  460. readingsSingleUpdate($hash, $cmd, $setting, 1);
  461. return netatmo_setCameraSetting($hash, $cmd, $setting);
  462. return undef;
  463. }
  464. elsif( $cmd eq "light_mode" ) {
  465. my $setting = $parameters[0];
  466. return "You have to define a value" if(!defined($setting) || $setting eq "");
  467. return netatmo_setFloodlight($hash, $setting);
  468. return undef;
  469. }
  470. elsif( $cmd eq "floodlight" ) {
  471. my $setting = $parameters[0];
  472. $setting = 100 if(!defined($setting) || $setting eq "");
  473. $setting = int($setting);
  474. return netatmo_setIntensity($hash, $setting);
  475. return undef;
  476. }
  477. elsif( $cmd eq "intensity" || $cmd eq "night_always" || $cmd eq "night_person" || $cmd eq "night_vehicle" || $cmd eq "night_animal" || $cmd eq "night_movement" ) {
  478. my $setting = $parameters[0];
  479. return "You have to define a value" if(!defined($setting) || $setting eq "");
  480. readingsSingleUpdate($hash, $cmd, $setting, 1);
  481. return netatmo_setPresenceConfig($hash, $setting);
  482. return undef;
  483. }
  484. elsif( $cmd eq "calibrate" ) {
  485. return netatmo_setTagCalibration($hash, $cmd);
  486. return undef;
  487. }
  488. elsif( $cmd eq "setpoint_mode" ) {
  489. my $setting = $parameters[0];
  490. my $duration = $parameters[1];
  491. return "You have to define a mode" if(!defined($setting) || $setting eq "");
  492. return netatmo_setRoomMode($hash,$setting,$duration) if($hash->{SUBTYPE} eq "HEATINGROOM");
  493. return netatmo_setThermostatMode($hash,$setting,$duration);
  494. return undef;
  495. }
  496. elsif( $cmd eq "setpoint_temp" ) {
  497. my $setting = $parameters[0];
  498. my $duration = $parameters[1];
  499. return "You have to define a temperature" if(!defined($setting) || $setting eq "");
  500. return netatmo_setRoomTemp($hash,$setting,$duration) if($hash->{SUBTYPE} eq "HEATINGROOM");
  501. return netatmo_setThermostatTemp($hash,$setting,$duration);
  502. return undef;
  503. }
  504. elsif( $cmd eq "program" ) {
  505. my $setting = $parameters[0];
  506. return "You have to define a program" if(!defined($setting) || $setting eq "");
  507. return netatmo_setThermostatProgram($hash,$setting);
  508. return undef;
  509. }
  510. elsif( $cmd eq "clear" ) {
  511. delete $hash->{READINGS};
  512. return undef;
  513. }
  514. elsif( $cmd eq "webhook" ) {
  515. if($parameters[0] eq "drop")
  516. {
  517. netatmo_dropWebhook($hash);
  518. } else {
  519. netatmo_registerWebhook($hash);
  520. }
  521. return undef;
  522. }
  523. if( $cmd eq 'unban' )# unban:noArg
  524. {
  525. return netatmo_Unban($hash);
  526. }
  527. return "Unknown argument $cmd, choose one of $list";
  528. }
  529. sub
  530. netatmo_getToken($)
  531. {
  532. my ($hash) = @_;
  533. my $name = $hash->{NAME};
  534. return Log3 $name, 1, "$name: No client id was found! (getToken)" if(!defined($hash->{helper}{client_id}));
  535. return Log3 $name, 1, "$name: No client secret was found! (getToken)" if(!defined($hash->{helper}{client_secret}));
  536. return Log3 $name, 1, "$name: No username was found! (getToken)" if(!defined($hash->{helper}{username}));
  537. return Log3 $name, 1, "$name: No password was found! (getToken)" if(!defined($hash->{helper}{password}));
  538. my($err,$data) = HttpUtils_BlockingGet({
  539. url => "https://".$hash->{helper}{apiserver}."/oauth2/token",
  540. timeout => 5,
  541. noshutdown => 1,
  542. data => {grant_type => 'password', client_id => $hash->{helper}{client_id}, client_secret=> $hash->{helper}{client_secret}, username => netatmo_decrypt($hash->{helper}{username}), password => netatmo_decrypt($hash->{helper}{password}), scope => 'read_station read_thermostat write_thermostat write_camera read_camera access_camera read_presence write_presence access_presence read_homecoach'},
  543. });
  544. netatmo_dispatch( {hash=>$hash,type=>'token'},$err,$data );
  545. }
  546. sub
  547. netatmo_getAppToken($)
  548. {
  549. my ($hash) = @_;
  550. my $name = $hash->{NAME};
  551. return Log3 $name, 1, "$name: No username was found! (getAppToken)" if(!defined($hash->{helper}{username}));
  552. return Log3 $name, 1, "$name: No password was found! (getAppToken)" if(!defined($hash->{helper}{password}));
  553. #my $auth = "QXV0aG9yaXphdGlvbjogQmFzaWMgYm1GZlkyeHBaVzUwWDJsdmMxOTNaV3hqYjIxbE9qaGhZalU0TkdRMk1tTmhNbUUzTjJVek4yTmpZelppTW1NM1pUUm1Namxs";
  554. my $auth = "QXV0aG9yaXphdGlvbjogQmFzaWMgYm1GZlkyeHBaVzUwWDJsdmN6bzFObU5qTmpSaU56azBOak5oT1RrMU9HSTNOREF4TkRjeVpEbGxNREUxT0E9PQ==";
  555. $auth = decode_base64($auth);
  556. my($err,$data) = HttpUtils_BlockingGet({
  557. url => "https://app.netatmo.net/oauth2/token",
  558. method => "POST",
  559. timeout => 5,
  560. noshutdown => 1,
  561. header => "$auth",
  562. data => {app_identifier=>'com.netatmo.camera', grant_type => 'password', password => netatmo_decrypt($hash->{helper}{password}), scope => 'write_camera read_camera access_camera read_presence write_presence access_presence read_station', username => netatmo_decrypt($hash->{helper}{username})},
  563. });
  564. netatmo_dispatch( {hash=>$hash,type=>'apptoken'},$err,$data );
  565. }
  566. sub
  567. netatmo_refreshToken($;$)
  568. {
  569. my ($hash,$nonblocking) = @_;
  570. my $name = $hash->{NAME};
  571. if( defined($hash->{access_token}) && defined($hash->{expires_at}) ) {
  572. my ($seconds) = gettimeofday();
  573. return undef if( $seconds < $hash->{expires_at} - 300 );
  574. }
  575. Log3 $name, 3, "$name: refreshing token";
  576. my $resolve = inet_aton($hash->{helper}{apiserver});
  577. if(!defined($resolve))
  578. {
  579. $hash->{STATE} = "DNS error";
  580. $hash->{network} = "dns" if($hash->{SUBTYPE} eq "ACCOUNT");
  581. delete($hash->{access_token});
  582. delete($hash->{access_token_app});
  583. InternalTimer( gettimeofday() + 1800, "netatmo_refreshTokenTimer", $hash);
  584. Log3 $name, 1, "$name: DNS error, cannot resolve ".$hash->{helper}{apiserver};
  585. return undef;
  586. } else {
  587. $hash->{network} = "ok";
  588. }
  589. if( !$hash->{refresh_token} ) {
  590. netatmo_getToken($hash);
  591. return undef;
  592. }
  593. if( $nonblocking ) {
  594. HttpUtils_NonblockingGet({
  595. url => "https://".$hash->{helper}{apiserver}."/oauth2/token",
  596. timeout => 20,
  597. noshutdown => 1,
  598. data => {grant_type => 'refresh_token', client_id => $hash->{helper}{client_id}, client_secret=> $hash->{helper}{client_secret}, refresh_token => $hash->{refresh_token}},
  599. hash => $hash,
  600. type => 'token',
  601. callback => \&netatmo_dispatch,
  602. });
  603. } else {
  604. my($err,$data) = HttpUtils_BlockingGet({
  605. url => "https://".$hash->{helper}{apiserver}."/oauth2/token",
  606. timeout => 5,
  607. noshutdown => 1,
  608. data => {grant_type => 'refresh_token', client_id => $hash->{helper}{client_id}, client_secret=> $hash->{helper}{client_secret}, refresh_token => $hash->{refresh_token}},
  609. });
  610. netatmo_dispatch( {hash=>$hash,type=>'token'},$err,$data );
  611. }
  612. }
  613. sub
  614. netatmo_refreshAppToken($;$)
  615. {
  616. my ($hash,$nonblocking) = @_;
  617. my $name = $hash->{NAME};
  618. if($hash->{network} eq "dns")
  619. {
  620. Log3 $name, 2, "$name: app token dns error, update postponed!";
  621. InternalTimer( gettimeofday() + 600, "netatmo_refreshAppTokenTimer", $hash);
  622. return undef;
  623. }
  624. if( defined($hash->{access_token_app}) && defined($hash->{expires_at_app}) ) {
  625. my ($seconds) = gettimeofday();
  626. return undef if( $seconds < $hash->{expires_at_app} - 300 );
  627. } elsif( !defined($hash->{refresh_token_app}) ) {
  628. Log3 $name, 2, "$name: missing app refresh token!";
  629. netatmo_getAppToken($hash);
  630. return undef;
  631. }
  632. delete($hash->{csrf_token});
  633. Log3 $name, 3, "$name: refreshing app token";
  634. my $auth = "QXV0aG9yaXphdGlvbjogQmFzaWMgYm1GZlkyeHBaVzUwWDJsdmN6bzFObU5qTmpSaU56azBOak5oT1RrMU9HSTNOREF4TkRjeVpEbGxNREUxT0E9PQ==";
  635. $auth = decode_base64($auth);
  636. if( $nonblocking ) {
  637. HttpUtils_NonblockingGet({
  638. url => "https://app.netatmo.net/oauth2/token",
  639. timeout => 20,
  640. noshutdown => 1,
  641. header => "$auth",
  642. data => {grant_type => 'refresh_token', refresh_token => $hash->{refresh_token_app}},
  643. hash => $hash,
  644. type => 'apptoken',
  645. callback => \&netatmo_dispatch,
  646. });
  647. } else {
  648. my($err,$data) = HttpUtils_BlockingGet({
  649. url => "https://app.netatmo.net/oauth2/token",
  650. timeout => 5,
  651. noshutdown => 1,
  652. header => "$auth",
  653. data => {grant_type => 'refresh_token', refresh_token => $hash->{refresh_token_app}},
  654. });
  655. netatmo_dispatch( {hash=>$hash,type=>'apptoken'},$err,$data );
  656. }
  657. }
  658. sub
  659. netatmo_refreshTokenTimer($)
  660. {
  661. my ($hash) = @_;
  662. my $name = $hash->{NAME};
  663. if(!defined($name))
  664. {
  665. Log3 "netatmo", 1, "error ".Dumper($hash);
  666. return undef;
  667. }
  668. Log3 $name, 5, "$name: refreshing token (timer)";
  669. netatmo_refreshToken($hash, 1);
  670. }
  671. sub
  672. netatmo_refreshAppTokenTimer($)
  673. {
  674. my ($hash) = @_;
  675. my $name = $hash->{NAME};
  676. Log3 $name, 5, "$name: refreshing app token (timer)";
  677. netatmo_refreshAppToken($hash, 1);
  678. }
  679. sub
  680. netatmo_checkConnection($)
  681. {
  682. my ($hash) = @_;
  683. my $name = $hash->{NAME};
  684. return undef if($hash->{network} eq "ok");
  685. Log3 $name, 3, "$name: refreshing connection information";
  686. HttpUtils_NonblockingGet({
  687. url => "https://".$hash->{helper}{apiserver}."/api/readtimeline",
  688. timeout => 5,
  689. hash => $hash,
  690. callback => \&netatmo_parseConnection,
  691. });
  692. return undef;
  693. }
  694. sub
  695. netatmo_parseConnection($$$)
  696. {
  697. my ($param,$err,$data) = @_;
  698. my $hash = $param->{hash};
  699. my $name = $hash->{NAME};
  700. if( $err ) {
  701. Log3 $name, 1, "$name: connection check failed: $err";
  702. if($err =~ /refused/ ){
  703. RemoveInternalTimer($hash);
  704. $hash->{status} = "banned";
  705. $hash->{network} = "banned";
  706. }
  707. elsif($err =~ /Bad hostname/ || $err =~ /gethostbyname/){
  708. $hash->{status} = "timeout";
  709. $hash->{network} = "dns";
  710. }
  711. elsif($err =~ /timed out/){
  712. $hash->{status} = "timeout";
  713. $hash->{network} = "timeout";
  714. }
  715. elsif($err =~ /Can't connect/){
  716. $hash->{status} = "timeout";
  717. $hash->{network} = "disconnected";
  718. }
  719. return undef;
  720. } elsif( $data ) {
  721. $data =~ s/\n//g;
  722. if( $data !~ m/^{.*}$/ ) {
  723. Log3 $name, 2, "$name: invalid json on connection check";
  724. return undef;
  725. }
  726. my $json = eval { JSON->new->utf8(0)->decode($data) };
  727. if($@)
  728. {
  729. Log3 $name, 2, "$name: invalid json evaluation on connection check ".$@;
  730. return undef;
  731. }
  732. $hash->{network} = "ok" if($json->{status} eq "ok");
  733. }
  734. return undef;
  735. }
  736. sub
  737. netatmo_connect($)
  738. {
  739. my ($hash) = @_;
  740. netatmo_getToken($hash);
  741. #netatmo_getAppToken($hash);
  742. InternalTimer(gettimeofday()+90, "netatmo_poll", $hash);
  743. }
  744. sub
  745. netatmo_Unban($)
  746. {
  747. my ($hash) = @_;
  748. my $name = $hash->{NAME};
  749. HttpUtils_NonblockingGet({
  750. url => "https://dev.netatmo.com/",
  751. timeout => 20,
  752. noshutdown => 1,
  753. hash => $hash,
  754. type => 'unban',
  755. callback => \&netatmo_parseUnban,
  756. });
  757. return undef;
  758. }
  759. sub
  760. netatmo_parseUnban($$$)
  761. {
  762. my ($param,$err,$data) = @_;
  763. my $hash = $param->{hash};
  764. my $name = $hash->{NAME};
  765. #Log3 $name, 1, "$name unban\n".Dumper($param->{httpheader});
  766. $data =~ /csrf_value: "(.*)"/;
  767. my $csrf_token = $1;
  768. # https://auth.netatmo.com/en-US/access/login?next_url=https://dev.netatmo.com/dev/myaccount
  769. Log3 $name, 1, "$name unban ".$csrf_token;
  770. HttpUtils_NonblockingGet({
  771. url => "https://auth.netatmo.com/en-US/access/login?next_url=https://dev.netatmo.com/dev/myaccount",
  772. timeout => 5,
  773. hash => $hash,
  774. ignoreredirects => 1,
  775. type => 'unban',
  776. header => "Cookie: netatmocomci_csrf_cookie_na=".$csrf_token."; netatmocomlocale=en-US",
  777. data => {ci_csrf_netatmo => $csrf_token, mail => netatmo_decrypt($hash->{helper}{username}), pass => netatmo_decrypt($hash->{helper}{password}), log_submit => 'Log+in', stay_logged => 'accept'},
  778. callback => \&netatmo_parseUnban2,
  779. });
  780. return undef;
  781. }
  782. sub
  783. netatmo_parseUnban2($$$)
  784. {
  785. my ($param,$err,$data) = @_;
  786. my $hash = $param->{hash};
  787. my $name = $hash->{NAME};
  788. Log3 $name, 1, "$name header\n".Dumper($param->{httpheader});
  789. my $header1 = $param->{httpheader};
  790. my $header2 = $param->{httpheader};
  791. my $header3 = $param->{httpheader};
  792. $header1 =~ s/=deleted/x=deleted/g;
  793. $header2 =~ s/=deleted/x=deleted/g;
  794. $header3 =~ s/=deleted/x=deleted/g;
  795. $header1 =~ /Set-Cookie: netatmocomci_csrf_cookie_na=(.*); expires/;
  796. my $csrf_token = $1;
  797. $hash->{helper}{csrf_token} = $csrf_token;
  798. $header2 =~ /Set-Cookie: netatmocomaccess_token=(.*); path/;
  799. my $accesstoken = $1;
  800. $accesstoken =~ s/%7C/|/g;
  801. $hash->{helper}{access_token} = $accesstoken;
  802. $header3 =~ /Set-Cookie: netatmocomrefresh_token=(.*); expires/;
  803. my $refreshtoken = $1;
  804. $hash->{helper}{refresh_token} = $refreshtoken;
  805. Log3 $name, 1, "$name csrftoken ".$csrf_token;
  806. Log3 $name, 1, "$name accesstoken ".$accesstoken;
  807. Log3 $name, 1, "$name refreshtoken ".$refreshtoken;
  808. my $json = '{"application_id":"'.$hash->{helper}{client_id}.'"}';
  809. HttpUtils_NonblockingGet({
  810. url => "https://dev.netatmo.com/api/unbanapp",
  811. timeout => 5,
  812. hash => $hash,
  813. type => 'unban',
  814. header => "Referer: https://dev.netatmo.com/dev/myaccount\r\nAuthorization: Bearer ".$accesstoken."\r\nContent-Type: application/json;charset=utf-8\r\nCookie: netatmocomci_csrf_cookie_na=".$csrf_token."; netatmocomlocale=en-US; netatmocomacces_token=".$accesstoken,
  815. data => $json,
  816. callback => \&netatmo_parseUnban3,
  817. });
  818. return undef;
  819. }
  820. sub
  821. netatmo_parseUnban3($$$)
  822. {
  823. my ($param,$err,$data) = @_;
  824. my $hash = $param->{hash};
  825. my $name = $hash->{NAME};
  826. Log3 $name, 1, "$name header\n".Dumper($param->{httpheader});
  827. Log3 $name, 1, "$name data\n".Dumper($data);
  828. Log3 $name, 1, "$name err\n".Dumper($err);
  829. return undef;
  830. }
  831. sub
  832. netatmo_initDevice($)
  833. {
  834. my ($hash) = @_;
  835. my $name = $hash->{NAME};
  836. AssignIoPort($hash);
  837. if(defined($hash->{IODev}->{NAME})) {
  838. Log3 $name, 3, "$name: I/O device is " . $hash->{IODev}->{NAME};
  839. } else {
  840. Log3 $name, 1, "$name: no I/O device";
  841. }
  842. my $device;
  843. if( $hash->{Module} ) {
  844. $device = netatmo_getDeviceDetail( $hash, $hash->{Module} );
  845. } else {
  846. $device = netatmo_getDeviceDetail( $hash, $hash->{Device} );
  847. }
  848. $hash->{stationName} = encode_utf8($device->{station_name}) if( $device->{station_name} );
  849. $hash->{moduleName} = encode_utf8($device->{module_name}) if( $device->{module_name} );
  850. $hash->{name} = encode_utf8($device->{name}) if( $device->{name} );
  851. $hash->{model} = $device->{type} if(defined($device->{type}));
  852. $hash->{firmware} = $device->{firmware} if(defined($device->{firmware}));
  853. $hash->{co2_calibrating} = $device->{co2_calibrating} if(defined($device->{co2_calibrating}));
  854. $hash->{last_upgrade} = FmtDateTime($device->{last_upgrade}) if(defined($device->{last_upgrade}));
  855. $hash->{date_setup} = FmtDateTime($device->{date_setup}) if(defined($device->{date_setup}));
  856. $hash->{last_setup} = FmtDateTime($device->{last_setup}) if(defined($device->{last_setup}));
  857. $hash->{last_status_store} = FmtDateTime($device->{last_status_store}) if(defined($device->{last_status_store}));
  858. $hash->{helper}{last_status_store} = $device->{last_status_store} if(defined($device->{last_status_store}) && $device->{last_status_store} > $hash->{helper}{last_status_store});
  859. $hash->{last_message} = FmtDateTime($device->{last_message}) if(defined($device->{last_message}));
  860. $hash->{last_seen} = FmtDateTime($device->{last_seen}) if(defined($device->{last_seen}));
  861. $hash->{wifi_status} = $device->{wifi_status} if(defined($device->{wifi_status}));
  862. $hash->{rf_status} = $device->{rf_status} if(defined($device->{rf_status}));
  863. $hash->{battery_percent} = $device->{battery_percent} if(defined($device->{battery_percent}));
  864. $hash->{battery_vp} = $device->{battery_vp} if(defined($device->{battery_vp}));
  865. if( $device->{place} ) {
  866. $hash->{country} = $device->{place}{country};
  867. $hash->{bssid} = $device->{place}{bssid} if(defined($device->{place}{bssid}));
  868. $hash->{altitude} = $device->{place}{altitude} if(defined($device->{place}{altitude}));
  869. $hash->{city} = encode_utf8($device->{place}{geoip_city}) if(defined($device->{place}{geoip_city}));
  870. $hash->{city} = encode_utf8($device->{place}{city}) if(defined($device->{place}{city}));;
  871. $hash->{location} = $device->{place}{location}[1] .",". $device->{place}{location}[0];
  872. }
  873. readingsSingleUpdate($hash, "battery", ($device->{battery_percent} > 20) ? "ok" : "low", 1) if(defined($device->{battery_percent}));
  874. readingsSingleUpdate($hash, "battery_percent", $device->{battery_percent}, 1) if(defined($device->{battery_percent}));
  875. my $state_format;
  876. if( $device->{data_type} ) {
  877. my $newdatatypes = "";
  878. my @reading_names = ();
  879. foreach my $type (@{$device->{data_type}}) {
  880. $newdatatypes = "" if ( !defined($newdatatypes) );
  881. $newdatatypes .= "," if ( $newdatatypes );
  882. $type = "WindStrength,WindAngle,GustStrength,GustAngle" if($type eq "Wind");
  883. $newdatatypes .= $type;
  884. push @reading_names, lc($type);
  885. if( $type eq "Temperature" ) {
  886. $state_format .= " " if( $state_format );
  887. $state_format .= "T: temperature";
  888. } elsif( $type eq "Humidity" ) {
  889. $state_format .= " " if( $state_format );
  890. $state_format .= "H: humidity";
  891. }
  892. }
  893. if($newdatatypes ne "")
  894. {
  895. delete($hash->{dataTypes});
  896. $hash->{dataTypes} = $newdatatypes;
  897. }
  898. $hash->{helper}{readingNames} = \@reading_names;
  899. }
  900. $attr{$name}{stateFormat} = $state_format if( !defined($attr{$name}{stateFormat}) && defined($state_format) && defined($name) );
  901. return undef if(IsDisabled($name) || !defined($name));
  902. InternalTimer(gettimeofday()+90, "netatmo_poll", $hash);
  903. }
  904. sub
  905. netatmo_getDevices($;$)
  906. {
  907. my ($hash,$blocking) = @_;
  908. my $name = $hash->{NAME};
  909. netatmo_refreshToken($hash, defined($hash->{access_token}));
  910. Log3 $name, 3, "$name getDevices (devicelist)";
  911. return Log3 $name, 1, "$name: No access token was found! (getDevices)" if(!defined($hash->{access_token}));
  912. if( $blocking ) {
  913. my($err,$data) = HttpUtils_BlockingGet({
  914. url => "https://".$hash->{helper}{apiserver}."/api/getstationsdata",
  915. timeout => 5,
  916. noshutdown => 1,
  917. data => { access_token => $hash->{access_token}, },
  918. });
  919. netatmo_dispatch( {hash=>$hash,type=>'devicelist'},$err,$data );
  920. return $hash->{helper}{devices};
  921. } else {
  922. HttpUtils_NonblockingGet({
  923. url => "https://".$hash->{helper}{apiserver}."/api/getstationsdata",
  924. timeout => 20,
  925. noshutdown => 1,
  926. data => { access_token => $hash->{access_token}, },
  927. hash => $hash,
  928. type => 'devicelist',
  929. callback => \&netatmo_dispatch,
  930. });
  931. }
  932. }
  933. sub
  934. netatmo_getHomes($;$)
  935. {
  936. my ($hash,$blocking) = @_;
  937. my $name = $hash->{NAME};
  938. netatmo_refreshToken($hash, defined($hash->{access_token}));
  939. Log3 $name, 3, "$name getHomes (homelist)";
  940. return Log3 $name, 1, "$name: No access token was found! (getHomes)" if(!defined($hash->{access_token}));
  941. if( $blocking ) {
  942. my($err,$data) = HttpUtils_BlockingGet({
  943. url => "https://".$hash->{helper}{apiserver}."/api/gethomedata",
  944. timeout => 5,
  945. noshutdown => 1,
  946. data => { access_token => $hash->{access_token}, },
  947. });
  948. netatmo_dispatch( {hash=>$hash,type=>'homelist'},$err,$data );
  949. return $hash->{helper}{homes};
  950. } else {
  951. HttpUtils_NonblockingGet({
  952. url => "https://".$hash->{helper}{apiserver}."/api/gethomedata",
  953. timeout => 20,
  954. noshutdown => 1,
  955. data => { access_token => $hash->{access_token}, },
  956. hash => $hash,
  957. type => 'homelist',
  958. callback => \&netatmo_dispatch,
  959. });
  960. }
  961. }
  962. sub
  963. netatmo_getThermostats($;$)
  964. {
  965. my ($hash,$blocking) = @_;
  966. my $name = $hash->{NAME};
  967. netatmo_refreshToken($hash, defined($hash->{access_token}));
  968. Log3 $name, 3, "$name getThermostats (thermostatlist)";
  969. return Log3 $name, 1, "$name: No access token was found! (getThermostats)" if(!defined($hash->{access_token}));
  970. # url => "https://".$hash->{helper}{apiserver}."/api/getthermostatsdata",
  971. if( $blocking ) {
  972. my($err,$data) = HttpUtils_BlockingGet({
  973. url => "https://".$hash->{helper}{apiserver}."/api/gethomesdata",
  974. timeout => 5,
  975. noshutdown => 1,
  976. data => { access_token => $hash->{access_token}, },
  977. });
  978. netatmo_dispatch( {hash=>$hash,type=>'thermostatlist'},$err,$data );
  979. return $hash->{helper}{thermostats};
  980. } else {
  981. HttpUtils_NonblockingGet({
  982. url => "https://".$hash->{helper}{apiserver}."/api/gethomesdata",
  983. timeout => 20,
  984. noshutdown => 1,
  985. data => { access_token => $hash->{access_token}, },
  986. hash => $hash,
  987. type => 'thermostatlist',
  988. callback => \&netatmo_dispatch,
  989. });
  990. }
  991. }
  992. sub
  993. netatmo_getHomecoachs($;$)
  994. {
  995. my ($hash,$blocking) = @_;
  996. my $name = $hash->{NAME};
  997. netatmo_refreshToken($hash, defined($hash->{access_token}));
  998. Log3 $name, 3, "$name getHomecoachs (homecoachlist)";
  999. return Log3 $name, 1, "$name: No access token was found! (getHomecoachs)" if(!defined($hash->{access_token}));
  1000. if( $blocking ) {
  1001. my($err,$data) = HttpUtils_BlockingGet({
  1002. url => "https://".$hash->{helper}{apiserver}."/api/gethomecoachsdata",
  1003. timeout => 5,
  1004. noshutdown => 1,
  1005. data => { access_token => $hash->{access_token}, },
  1006. });
  1007. netatmo_dispatch( {hash=>$hash,type=>'homecoachlist'},$err,$data );
  1008. return $hash->{helper}{homecoachs};
  1009. } else {
  1010. HttpUtils_NonblockingGet({
  1011. url => "https://".$hash->{helper}{apiserver}."/api/gethomecoachsdata",
  1012. timeout => 20,
  1013. noshutdown => 1,
  1014. data => { access_token => $hash->{access_token}, },
  1015. hash => $hash,
  1016. type => 'homecoachlist',
  1017. callback => \&netatmo_dispatch,
  1018. });
  1019. }
  1020. }
  1021. sub
  1022. netatmo_pingCamera($;$)
  1023. {
  1024. my ($hash,$blocking) = @_;
  1025. my $name = $hash->{NAME};
  1026. my $iohash = $hash->{IODev};
  1027. netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1028. return Log3 $name, 1, "$name: No access token was found! (pingCamera)" if(!defined($iohash->{access_token}));
  1029. my $pingurl = ReadingsVal( $name, "vpn_url", undef );
  1030. return undef if(!defined($pingurl));
  1031. Log3 $name, 3, "$name pingCamera (cameraping)";
  1032. $pingurl .= "/command/ping";
  1033. Log3 $name, 5, "$name pingCamera ".$pingurl;
  1034. if( $blocking ) {
  1035. my($err,$data) = HttpUtils_BlockingGet({
  1036. url => $pingurl,
  1037. timeout => 10,
  1038. sslargs => { SSL_hostname => '', },
  1039. data => { access_token => $iohash->{access_token}, },
  1040. });
  1041. netatmo_dispatch( {hash=>$hash,type=>'cameraping'},$err,$data );
  1042. return undef;
  1043. } else {
  1044. HttpUtils_NonblockingGet({
  1045. url => $pingurl,
  1046. timeout => 10,
  1047. sslargs => { SSL_hostname => '', },
  1048. data => { access_token => $iohash->{access_token}, },
  1049. hash => $hash,
  1050. type => 'cameraping',
  1051. callback => \&netatmo_dispatch,
  1052. });
  1053. }
  1054. }
  1055. sub
  1056. netatmo_getCameraVideo($$;$)
  1057. {
  1058. my ($hash,$videoid,$local) = @_;
  1059. my $name = $hash->{NAME};
  1060. $local = ($local eq "video_local" ? "_local" : "");
  1061. #my $iohash = $hash->{IODev};
  1062. #netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1063. my $commandurl = ReadingsVal( $name, "local_url", undef);
  1064. if(!defined($commandurl)) {
  1065. ReadingsVal( $name, "vpn_url", undef );
  1066. } else {
  1067. $local = "";
  1068. }
  1069. return undef if(!defined($commandurl));
  1070. my $quality = AttrVal($name,"videoquality","medium");
  1071. $commandurl .= "/vod/".$videoid."/files/".$quality."/index".$local.".m3u8";
  1072. Log3 $name, 3, "$name getCameraVideo ".$commandurl;
  1073. # HttpUtils_BlockingGet({
  1074. # url => $cmdurl,
  1075. # noshutdown => 1,
  1076. # data => { access_token => $iohash->{access_token}, },
  1077. # hash => $hash,
  1078. # type => 'cameravideo',
  1079. # callback => \&netatmo_dispatch,
  1080. # });
  1081. return $commandurl;
  1082. }
  1083. sub
  1084. netatmo_getCameraLive($;$)
  1085. {
  1086. my ($hash,$local) = @_;
  1087. my $name = $hash->{NAME};
  1088. $local = ($local eq "live_local" ? "_local" : "");
  1089. #my $iohash = $hash->{IODev};
  1090. #netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1091. my $commandurl = ReadingsVal( $name, "local_url", undef);
  1092. if(!defined($commandurl)) {
  1093. ReadingsVal( $name, "vpn_url", undef );
  1094. } else {
  1095. $local = "";
  1096. }
  1097. return undef if(!defined($commandurl));
  1098. my $quality = AttrVal($name,"videoquality","medium");
  1099. $commandurl .= "/live/files/".$quality."/index".$local.".m3u8";
  1100. Log3 $name, 3, "$name getCameraLive ".$commandurl;
  1101. # HttpUtils_BlockingGet({
  1102. # url => $cmdurl,
  1103. # noshutdown => 1,
  1104. # data => { access_token => $iohash->{access_token}, },
  1105. # hash => $hash,
  1106. # type => 'cameravideo',
  1107. # callback => \&netatmo_dispatch,
  1108. # });
  1109. return $commandurl;
  1110. }
  1111. sub
  1112. netatmo_getCameraTimelapse($)
  1113. {
  1114. my ($hash) = @_;
  1115. my $name = $hash->{NAME};
  1116. #my $iohash = $hash->{IODev};
  1117. #netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1118. my $cmdurl = ReadingsVal( $name, "local_url", undef );
  1119. return undef if(!defined($cmdurl));
  1120. $cmdurl .= "/command/dl/timelapse";
  1121. Log3 $name, 3, "$name getCameraTimelapse ".$cmdurl;
  1122. # HttpUtils_BlockingGet({
  1123. # url => $cmdurl,
  1124. # noshutdown => 1,
  1125. # data => { access_token => $iohash->{access_token}, },
  1126. # hash => $hash,
  1127. # type => 'cameravideo',
  1128. # callback => \&netatmo_dispatch,
  1129. # });
  1130. return $cmdurl;
  1131. }
  1132. sub
  1133. netatmo_getCameraSnapshot($;$)
  1134. {
  1135. my ($hash,$local) = @_;
  1136. my $name = $hash->{NAME};
  1137. #my $iohash = $hash->{IODev};
  1138. #netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1139. my $commandurl = ReadingsVal( $name, "local_url", ReadingsVal( $name, "vpn_url", undef ) );
  1140. return undef if(!defined($commandurl));
  1141. $commandurl .= "/live/snapshot_720.jpg";
  1142. Log3 $name, 3, "$name getCameraSnapshot ".$commandurl;
  1143. # HttpUtils_BlockingGet({
  1144. # url => $cmdurl,
  1145. # noshutdown => 1,
  1146. # data => { access_token => $iohash->{access_token}, },
  1147. # hash => $hash,
  1148. # type => 'cameravideo',
  1149. # callback => \&netatmo_dispatch,
  1150. # });
  1151. return $commandurl;
  1152. }
  1153. sub
  1154. netatmo_getEvents($)
  1155. {
  1156. my ($hash) = @_;
  1157. my $name = $hash->{NAME};
  1158. my $iohash = $hash->{IODev};
  1159. netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1160. Log3 $name, 3, "$name getEvents (homeevents)";
  1161. return Log3 $name, 1, "$name: No access token was found! (getEvents)" if(!defined($iohash->{access_token}));
  1162. HttpUtils_NonblockingGet({
  1163. url => "https://".$iohash->{helper}{apiserver}."/api/getnextevents",
  1164. timeout => 20,
  1165. noshutdown => 1,
  1166. data => { access_token => $iohash->{access_token}, home_id => $hash->{Home}, event_id => $hash->{lastevent}, },
  1167. hash => $hash,
  1168. type => 'homeevents',
  1169. callback => \&netatmo_dispatch,
  1170. });
  1171. }
  1172. sub
  1173. netatmo_getPublicDevices($$;$$$$)
  1174. {
  1175. my ($hash,$blocking,$lat1,$lon1,$lat2,$lon2) = @_;
  1176. my $name = $hash->{NAME};
  1177. my $iohash = $hash->{IODev};
  1178. $iohash = $hash if( !defined($iohash) );
  1179. #Log3 $name, 5, "$name getPublicDevices $lat1,$lon1,$lat2,$lon2";
  1180. if( !defined($lon1) ) {
  1181. my $s = $lat1;
  1182. $s = 0.025 if ( !defined($s) );
  1183. my $lat = AttrVal("global","latitude", 50.112);
  1184. my $lon = AttrVal("global","longitude", 8.686);
  1185. $lat1 = $lat + $s;
  1186. $lon1 = $lon + $s;
  1187. $lat2 = $lat - $s;
  1188. $lon2 = $lon - $s;
  1189. } elsif( !defined($lon2) ) {
  1190. my $lat = $lat1;
  1191. my $lon = $lon1;
  1192. my $s = $lat2;
  1193. $s = 0.025 if ( !defined($s) );
  1194. $lat1 = $lat + $s;
  1195. $lon1 = $lon + $s;
  1196. $lat2 = $lat - $s;
  1197. $lon2 = $lon - $s;
  1198. }
  1199. my $lat_ne = ($lat1 > $lat2) ? $lat1 : $lat2;
  1200. my $lon_ne = ($lon1 > $lon2) ? $lon1 : $lon2;
  1201. my $lat_sw = ($lat1 > $lat2) ? $lat2 : $lat1;
  1202. my $lon_sw = ($lon1 > $lon2) ? $lon2 : $lon1;
  1203. Log3 $name, 3, "$name getPublicDevices ($lat_ne,$lon_ne / $lat_sw,$lon_sw)";
  1204. netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  1205. return Log3 $name, 1, "$name: No access token was found! (getPublicDevices)" if(!defined($iohash->{access_token}));
  1206. if( $blocking ) {
  1207. my($err,$data) = HttpUtils_BlockingGet({
  1208. url => "https://".$iohash->{helper}{apiserver}."/api/getpublicdata",
  1209. timeout => 5,
  1210. noshutdown => 1,
  1211. data => { access_token => $iohash->{access_token}, lat_ne => $lat_ne, lon_ne => $lon_ne, lat_sw => $lat_sw, lon_sw => $lon_sw },
  1212. });
  1213. return netatmo_dispatch( {hash=>$hash,type=>'publicdata'},$err,$data );
  1214. } else {
  1215. HttpUtils_NonblockingGet({
  1216. url => "https://".$iohash->{helper}{apiserver}."/api/getpublicdata",
  1217. timeout => 20,
  1218. noshutdown => 1,
  1219. data => { access_token => $iohash->{access_token}, lat_ne => $lat_ne, lon_ne => $lon_ne, lat_sw => $lat_sw, lon_sw => $lon_sw, filter => 'true' },
  1220. hash => $hash,
  1221. type => 'publicdata',
  1222. callback => \&netatmo_dispatch,
  1223. });
  1224. }
  1225. }
  1226. sub
  1227. netatmo_getAddress($$$$)
  1228. {
  1229. my ($hash,$blocking,$lat,$lon) = @_;
  1230. my $name = $hash->{NAME};
  1231. my $iohash = $hash->{IODev};
  1232. $iohash = $hash if( !defined($iohash) );
  1233. Log3 $name, 5, "$name getAddress ($lat,$lon)";
  1234. if( $blocking ) {
  1235. my($err,$data) = HttpUtils_BlockingGet({
  1236. url => "https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon",
  1237. noshutdown => 1,
  1238. });
  1239. return netatmo_dispatch( {hash=>$hash,type=>'address'},$err,$data );
  1240. } else {
  1241. HttpUtils_NonblockingGet({
  1242. url => "https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon",
  1243. noshutdown => 1,
  1244. hash => $hash,
  1245. type => 'address',
  1246. callback => \&netatmo_dispatch,
  1247. });
  1248. }
  1249. }
  1250. sub
  1251. netatmo_getLatLong($$$)
  1252. {
  1253. my ($hash,$blocking,$addr) = @_;
  1254. my $name = $hash->{NAME};
  1255. my $iohash = $hash->{IODev};
  1256. $iohash = $hash if( !defined($iohash) );
  1257. Log3 $name, 5, "$name getLatLong ($addr)";
  1258. if( $blocking ) {
  1259. my($err,$data) = HttpUtils_BlockingGet({
  1260. url => "https://maps.googleapis.com/maps/api/geocode/json?address=germany+$addr",
  1261. noshutdown => 1,
  1262. });
  1263. return netatmo_dispatch( {hash=>$hash,type=>'latlng'},$err,$data );
  1264. } else {
  1265. HttpUtils_NonblockingGet({
  1266. url => "https://maps.googleapis.com/maps/api/geocode/json?address=germany+$addr",
  1267. noshutdown => 1,
  1268. hash => $hash,
  1269. type => 'latlng',
  1270. callback => \&netatmo_dispatch,
  1271. });
  1272. }
  1273. }
  1274. sub
  1275. netatmo_getDeviceDetail($$)
  1276. {
  1277. my ($hash,$id) = @_;
  1278. my $name = $hash->{NAME};
  1279. $hash = $hash->{IODev} if( defined($hash->{IODev}) );
  1280. Log3 $name, 5, "$name getDeviceDetail ($id)";
  1281. netatmo_getDevices($hash,1) if( !$hash->{helper}{devices} );
  1282. netatmo_getHomecoachs($hash,1) if( !$hash->{helper}{homecoachs} );
  1283. foreach my $device (@{$hash->{helper}{devices}}) {
  1284. return $device if( $device->{_id} eq $id );
  1285. }
  1286. foreach my $device (@{$hash->{helper}{homecoachs}}) {
  1287. return $device if( $device->{_id} eq $id );
  1288. }
  1289. return undef;
  1290. }
  1291. sub
  1292. netatmo_requestDeviceReadings($@)
  1293. {
  1294. my ($hash,$id,$type,$module) = @_;
  1295. my $name = $hash->{NAME};
  1296. return undef if( !defined($hash->{IODev}) );
  1297. Log3 $name, 5, "$name: requestDeviceReadings ($id ".(!$type?"-":$type)." ".(!$module?"-":$module).")";
  1298. my $iohash = $hash->{IODev};
  1299. $type = $hash->{dataTypes} if( !$type );
  1300. $type = "Temperature,CO2,Humidity,Noise,Pressure,health_idx" if( !$type && $hash->{SUBTYPE} eq "DEVICE" );
  1301. $type = "Temperature,CO2,Humidity,Noise,Pressure,Rain,WindStrength,WindAngle,GustStrength,GustAngle,Sp_Temperature,BoilerOn,BoilerOff,health_idx" if( !$type );
  1302. $type = "WindAngle,WindStrength,GustStrength,GustAngle" if ($type eq "Wind");
  1303. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1304. return Log3 $name, 1, "$name: No access token was found! (requestDeviceReadings)" if(!defined($iohash->{access_token}));
  1305. my %data = (access_token => $iohash->{access_token}, device_id => $id, scale => "max", type => $type);
  1306. $data{"module_id"} = $module if( $module );
  1307. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1308. $data{"date_begin"} = $lastupdate if( defined($lastupdate) );
  1309. Log3 $name, 3, "$name: requestDeviceReadings ($type)";
  1310. HttpUtils_NonblockingGet({
  1311. url => "https://".$iohash->{helper}{apiserver}."/api/getmeasure",
  1312. timeout => 20,
  1313. noshutdown => 1,
  1314. data => \%data,
  1315. hash => $hash,
  1316. type => 'getmeasure',
  1317. requested => $type,
  1318. callback => \&netatmo_dispatch,
  1319. });
  1320. }
  1321. sub
  1322. netatmo_initHome($@)
  1323. {
  1324. my ($hash) = @_;
  1325. my $name = $hash->{NAME};
  1326. return undef if( !defined($hash->{IODev}) );
  1327. my $iohash = $hash->{IODev};
  1328. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1329. return Log3 $name, 1, "$name: No access token was found! (initHome)" if(!defined($iohash->{access_token}));
  1330. my %data = (access_token => $iohash->{access_token}, home_id => $hash->{Home});
  1331. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1332. Log3 $name, 3, "$name initHome (gethomedata)";
  1333. # url => "https://".$iohash->{helper}{apiserver}."/api/gethomedata",
  1334. # data => \%data,
  1335. HttpUtils_NonblockingGet({
  1336. url => "https://app.netatmo.net/api/gethomesdata",
  1337. timeout => 20,
  1338. noshutdown => 1,
  1339. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token_app},
  1340. hash => $hash,
  1341. type => 'gethomedata',
  1342. callback => \&netatmo_dispatch,
  1343. });
  1344. InternalTimer(gettimeofday()+$hash->{helper}{INTERVAL}, "netatmo_poll", $hash);
  1345. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+$hash->{helper}{INTERVAL};
  1346. }
  1347. sub
  1348. netatmo_requestHomeReadings($@)
  1349. {
  1350. my ($hash,$id) = @_;
  1351. my $name = $hash->{NAME};
  1352. return undef if( !defined($hash->{IODev}) );
  1353. my $iohash = $hash->{IODev};
  1354. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1355. return undef if(!defined($iohash->{access_token}));
  1356. netatmo_refreshAppToken( $iohash, defined($iohash->{access_token_app}) );
  1357. return undef if(!defined($iohash->{access_token_app}));
  1358. my %data = (access_token => $iohash->{access_token}, home_id => $id, size => 50);
  1359. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1360. #$data{"size"} = 1;#$lastupdate if( defined($lastupdate) );
  1361. Log3 $name, 3, "$name requestHomeReadings (gethomedata)";
  1362. # url => "https://".$iohash->{helper}{apiserver}."/api/gethomedata",
  1363. # data => \%data,
  1364. HttpUtils_NonblockingGet({
  1365. url => "https://app.netatmo.net/api/gethomesdata",
  1366. timeout => 20,
  1367. noshutdown => 1,
  1368. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token_app},
  1369. hash => $hash,
  1370. type => 'gethomedata',
  1371. callback => \&netatmo_dispatch,
  1372. });
  1373. }
  1374. sub
  1375. netatmo_requestThermostatReadings($@)
  1376. {
  1377. my ($hash,$id) = @_;
  1378. my $name = $hash->{NAME};
  1379. return undef if( !defined($hash->{IODev}) );
  1380. Log3 $name, 3, "$name: requestThermostatReadings ($id)";
  1381. my $iohash = $hash->{IODev};
  1382. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1383. return Log3 $name, 1, "$name: No access token was found! (requestThermostatReadings)" if(!defined($iohash->{access_token}));
  1384. my %data = (access_token => $iohash->{access_token}, device_id => $id);
  1385. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1386. #$data{"size"} = 1;#$lastupdate if( defined($lastupdate) );
  1387. HttpUtils_NonblockingGet({
  1388. url => "https://".$iohash->{helper}{apiserver}."/api/getthermostatsdata",
  1389. timeout => 20,
  1390. noshutdown => 1,
  1391. data => \%data,
  1392. hash => $hash,
  1393. type => 'getthermostatsdata',
  1394. callback => \&netatmo_dispatch,
  1395. });
  1396. }
  1397. sub
  1398. netatmo_initHeatingHome($@)
  1399. {
  1400. my ($hash) = @_;
  1401. my $name = $hash->{NAME};
  1402. return undef if( !defined($hash->{IODev}) );
  1403. my $iohash = $hash->{IODev};
  1404. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1405. netatmo_refreshAppToken( $iohash, defined($iohash->{access_token_app}) );
  1406. return Log3 $name, 1, "$name: No access token was found! (initHeatingHome)" if(!defined($iohash->{access_token}));
  1407. return Log3 $name, 1, "$name: No app access token was found! (initHeatingHome)" if(!defined($iohash->{access_token_app}));
  1408. my %data = (app_type => 'app_thermostat', home_id => $hash->{Home});
  1409. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1410. #$data{"size"} = 1;#$lastupdate if( defined($lastupdate) );
  1411. Log3 $name, 3, "$name initHeatingHome (gethomedata)";
  1412. # url => "https://".$iohash->{helper}{apiserver}."/api/gethomedata",
  1413. # data => \%data,
  1414. HttpUtils_NonblockingGet({
  1415. url => "https://app.netatmo.net/api/gethomesdata",
  1416. timeout => 20,
  1417. noshutdown => 1,
  1418. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token_app},
  1419. data => \%data,
  1420. hash => $hash,
  1421. type => 'gethomedata',
  1422. callback => \&netatmo_dispatch,
  1423. });
  1424. InternalTimer(gettimeofday()+$hash->{helper}{INTERVAL}, "netatmo_poll", $hash);
  1425. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+$hash->{helper}{INTERVAL};
  1426. }
  1427. sub
  1428. netatmo_pollHeatingHome($@)
  1429. {
  1430. my ($hash) = @_;
  1431. my $name = $hash->{NAME};
  1432. return undef if( !defined($hash->{IODev}) );
  1433. my $iohash = $hash->{IODev};
  1434. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1435. return Log3 $name, 1, "$name: No app access token was found! (pollHeatingHome)" if(!defined($iohash->{access_token_app}));
  1436. my %data = (home_id => $hash->{Home});
  1437. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1438. #$data{"size"} = 1;#$lastupdate if( defined($lastupdate) );
  1439. my $json = encode_json( { home_id => $hash->{Home} } );
  1440. $json =~s/\"true\"/true/g;
  1441. $json =~s/\"false\"/false/g;
  1442. Log3 $name, 3, "$name pollHeatingHome (getheatinghomedata)";
  1443. # url => "https://".$iohash->{helper}{apiserver}."/api/gethomedata",
  1444. # data => \%data,
  1445. HttpUtils_NonblockingGet({
  1446. url => "https://my.netatmo.com/syncapi/v1/gethomestatus",
  1447. timeout => 20,
  1448. noshutdown => 1,
  1449. header => "Content-Type: application/json;charset=utf-8\r\nAuthorization: Bearer ".$iohash->{access_token},
  1450. data => $json,
  1451. hash => $hash,
  1452. type => 'getheatinghomedata',
  1453. callback => \&netatmo_dispatch,
  1454. });
  1455. InternalTimer(gettimeofday()+$hash->{helper}{INTERVAL}, "netatmo_poll", $hash);
  1456. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+$hash->{helper}{INTERVAL};
  1457. return undef;
  1458. }
  1459. sub
  1460. netatmo_pollHeatingRoom($@)
  1461. {
  1462. my ($hash) = @_;
  1463. my $name = $hash->{NAME};
  1464. return undef if( !defined($hash->{IODev}) );
  1465. my $iohash = $hash->{IODev};
  1466. netatmo_refreshAppToken( $iohash, defined($iohash->{access_token_app}) );
  1467. return Log3 $name, 1, "$name: No app access token was found! (pollHeatingRoom)" if(!defined($iohash->{access_token_app}));
  1468. $hash->{openRequests} = 0 if ( !defined( $hash->{openRequests}) );
  1469. Log3 $name, 4, "$name: pollHeatingRoom types [".$hash->{dataTypes} . "] for room [".$hash->{Room}."]" if(defined($hash->{dataTypes}));
  1470. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1471. $lastupdate = (time-7*24*60*60) if(!$lastupdate);
  1472. $lastupdate += 10;
  1473. $hash->{openRequests} += 1;
  1474. my $now = int(time);
  1475. my $json = encode_json( { home_id => $hash->{Home},
  1476. room_id => $hash->{Room},
  1477. scale => "max",
  1478. type => $hash->{dataTypes},
  1479. date_begin => "$lastupdate",
  1480. date_end => "$now",
  1481. real_time => "true" } );
  1482. $json =~s/\"true\"/true/g;
  1483. $json =~s/\"false\"/false/g;
  1484. Log3 $name, 3, "$name pollHeatingRoom (getheatinghomedata)";
  1485. # url => "https://".$iohash->{helper}{apiserver}."/api/gethomedata",
  1486. # data => \%data,
  1487. HttpUtils_NonblockingGet({
  1488. url => "https://app.netatmo.net/api/getroommeasure",
  1489. timeout => 20,
  1490. noshutdown => 1,
  1491. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token_app},
  1492. data => $json,
  1493. hash => $hash,
  1494. requested => $hash->{dataTypes},
  1495. type => 'getmeasure',
  1496. callback => \&netatmo_dispatch,
  1497. });
  1498. InternalTimer(gettimeofday()+$hash->{helper}{INTERVAL}, "netatmo_poll", $hash);
  1499. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+$hash->{helper}{INTERVAL};
  1500. return undef;
  1501. }
  1502. sub
  1503. netatmo_setRoomMode($$;$)
  1504. {
  1505. my ($hash,$set,$duration) = @_;
  1506. my $name = $hash->{NAME};
  1507. return undef if( !defined($hash->{IODev}) );
  1508. my $iohash = $hash->{IODev};
  1509. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1510. return Log3 $name, 1, "$name: No access token was found! (setRoomMode)" if(!defined($iohash->{access_token}));
  1511. my $json = encode_json( { home_id => $hash->{Home},
  1512. room_id => $hash->{Room},
  1513. mode => "$set" } );
  1514. if(defined($duration) || $set eq "max")
  1515. {
  1516. $duration = AttrVal($name,"setpoint_duration",60) if(!defined($duration));
  1517. my $endpoint = time + (60 * $duration);
  1518. my $json = encode_json( { home_id => $hash->{Home},
  1519. room_id => $hash->{Room},
  1520. mode => "$set",
  1521. endtime => $endpoint } );
  1522. }
  1523. $json =~s/\"true\"/true/g;
  1524. $json =~s/\"false\"/false/g;
  1525. Log3 $name, 3, "$name: setRoomMode ($set)";
  1526. HttpUtils_NonblockingGet({
  1527. url => "https://".$iohash->{helper}{apiserver}."/syncapi/v1/setthermpoint",
  1528. timeout => 20,
  1529. noshutdown => 1,
  1530. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token},
  1531. data => $json,
  1532. hash => $hash,
  1533. type => 'setroom',
  1534. callback => \&netatmo_dispatch,
  1535. });
  1536. }
  1537. sub
  1538. netatmo_setRoomTemp($$;$)
  1539. {
  1540. my ($hash,$set,$duration) = @_;
  1541. my $name = $hash->{NAME};
  1542. return undef if( !defined($hash->{IODev}) );
  1543. my $iohash = $hash->{IODev};
  1544. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1545. return Log3 $name, 1, "$name: No access token was found! (setRoomTemp)" if(!defined($iohash->{access_token}));
  1546. $duration = AttrVal($name,"setpoint_duration",60) if(!defined($duration));
  1547. my $endpoint = time + (60 * $duration);
  1548. my $json = encode_json( { home_id => $hash->{Home},
  1549. room_id => $hash->{Room},
  1550. mode => "manual",
  1551. endtime => $endpoint,
  1552. temp => $set } );
  1553. Log3 $name, 3, "$name: setRoomTemp ($set)";
  1554. HttpUtils_NonblockingGet({
  1555. url => "https://".$iohash->{helper}{apiserver}."/syncapi/v1/setthermpoint",
  1556. timeout => 20,
  1557. noshutdown => 1,
  1558. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token},
  1559. data => $json,
  1560. hash => $hash,
  1561. type => 'setroom',
  1562. callback => \&netatmo_dispatch,
  1563. });
  1564. }
  1565. sub
  1566. netatmo_requestPersonReadings($)
  1567. {
  1568. my ($hash) = @_;
  1569. my $name = $hash->{NAME};
  1570. return undef if( !defined($hash->{IODev}) );
  1571. return undef if( !defined($hash->{Home}) );
  1572. my $iohash = $hash->{IODev};
  1573. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1574. return Log3 $name, 1, "$name: No access token was found! (requestPersonReadings)" if(!defined($iohash->{access_token}));
  1575. Log3 $name, 3, "$name: requestPersonReadings (getpersondata)";
  1576. my %data = (access_token => $iohash->{access_token}, home_id => $hash->{Home}, person_id => $hash->{Person}, offset => '20');
  1577. my $lastupdate = ReadingsVal( $name, ".lastupdate", undef );
  1578. HttpUtils_NonblockingGet({
  1579. url => "https://".$iohash->{helper}{apiserver}."/api/getlasteventof",
  1580. timeout => 20,
  1581. noshutdown => 1,
  1582. data => \%data,
  1583. hash => $hash,
  1584. type => 'getpersondata',
  1585. callback => \&netatmo_dispatch,
  1586. });
  1587. }
  1588. sub
  1589. netatmo_setPresence($$)
  1590. {
  1591. my ($hash,$status) = @_;
  1592. my $name = $hash->{NAME};
  1593. return undef if( !defined($hash->{IODev}) );
  1594. my $iohash = $hash->{IODev};
  1595. netatmo_refreshAppToken($iohash, defined($iohash->{access_token_app}));
  1596. return Log3 $name, 1, "$name: No access token was found! (setPresence)" if(!defined($iohash->{access_token_app}));
  1597. my $personid = $hash->{Person};
  1598. my $urlstatus = $status;
  1599. my $json;
  1600. if($status eq "home")
  1601. {
  1602. $json = '{"home_id":"'.$hash->{Home}.'","person_ids":["'.$hash->{Person}.'"]}';
  1603. }
  1604. elsif($status eq "away")
  1605. {
  1606. $json = '{"home_id":"'.$hash->{Home}.'","person_id":"'.$hash->{Person}.'"}';
  1607. }
  1608. elsif($status eq "empty")
  1609. {
  1610. $json = '{"home_id":"'.$hash->{Home}.'"}';
  1611. $urlstatus = "away";
  1612. }
  1613. Log3 $name, 5, "$name: setPresence ($status)";
  1614. HttpUtils_NonblockingGet({
  1615. url => "https://app.netatmo.net/api/setpersons".$urlstatus,
  1616. timeout => 20,
  1617. noshutdown => 1,
  1618. method => "POST",
  1619. header => "Content-Type: application/json\r\nAuthorization: Bearer ".$iohash->{access_token_app},
  1620. data => $json,
  1621. hash => $hash,
  1622. type => 'setpersonsstatus_'.$status,
  1623. callback => \&netatmo_dispatch,
  1624. });
  1625. }
  1626. sub
  1627. netatmo_setNotifications($$$)
  1628. {
  1629. my ($hash,$setting,$value) = @_;
  1630. my $name = $hash->{NAME};
  1631. return undef if( !defined($hash->{IODev}) );
  1632. my $iohash = $hash->{IODev};
  1633. netatmo_refreshAppToken($iohash, defined($iohash->{access_token_app}));
  1634. return Log3 $name, 1, "$name: No access token was found! (setNotifications)" if(!defined($iohash->{access_token_app}));
  1635. if( !defined($iohash->{csrf_token}) )
  1636. {
  1637. my($err0,$data0) = HttpUtils_BlockingGet({
  1638. url => "https://auth.netatmo.com/access/checklogin",
  1639. timeout => 10,
  1640. noshutdown => 1,
  1641. });
  1642. if($err0 || !defined($data0))
  1643. {
  1644. Log3 $name, 1, "$name: csrf call failed! ".$err0;
  1645. return undef;
  1646. }
  1647. $data0 =~ /ci_csrf_netatmo" value="(.*)"/;
  1648. my $tmptoken = $1;
  1649. $iohash->{csrf_token} = $tmptoken;
  1650. if(!defined($iohash->{csrf_token})) {
  1651. Log3 $name, 1, "$name: CSRF ERROR ";
  1652. return undef;
  1653. }
  1654. Log3 $name, 4, "$name: csrf_token ".$iohash->{csrf_token};
  1655. }
  1656. my $homeid = $hash->{Home};
  1657. my %data;
  1658. if($setting eq "presence_notify_from" || $setting eq "presence_notify_to" || $setting eq "gone_after")
  1659. {
  1660. my @timevalue = split(":",$value);
  1661. if(defined($timevalue[1]))
  1662. {
  1663. $value = int($timevalue[0])*3600 + int($timevalue[1])*60;
  1664. }
  1665. else
  1666. {
  1667. $value *= 60;
  1668. }
  1669. $value = 0 if($value < 0);
  1670. $value = 86400 if($value > 86400 && $setting ne "gone_after");
  1671. }
  1672. elsif($setting eq "smart_notifs")
  1673. {
  1674. $value = (($value eq "on") ? "true" : "false");
  1675. }
  1676. if($setting eq "presence_enable_notify_from_to" || $setting =~ /^presence_record_/ || $setting =~ /^presence_notify_/ )
  1677. {
  1678. %data = (home_id => $homeid, 'presence_settings['.$setting.']' => $value, ci_csrf_netatmo => $iohash->{csrf_token});
  1679. }
  1680. else
  1681. {
  1682. %data = (home_id => $homeid, $setting => $value, ci_csrf_netatmo => $iohash->{csrf_token});
  1683. }
  1684. Log3 $name, 5, "$name: setNotifications ($setting $value)";
  1685. HttpUtils_NonblockingGet({
  1686. url => "https://my.netatmo.com/api/updatehome",
  1687. timeout => 20,
  1688. noshutdown => 1,
  1689. method => "POST",
  1690. header => "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\nAuthorization: Bearer ".$iohash->{access_token_app},
  1691. data => \%data,
  1692. hash => $hash,
  1693. type => 'sethomesettings',
  1694. callback => \&netatmo_dispatch,
  1695. });
  1696. }
  1697. sub
  1698. netatmo_setCamera($$$)
  1699. {
  1700. my ($hash,$status,$pin) = @_;
  1701. my $name = $hash->{NAME};
  1702. my $commandurl = ReadingsVal( $name, "local_url", ReadingsVal( $name, "vpn_url", undef ) );
  1703. return undef if(!defined($commandurl));
  1704. $commandurl .= "/command/changestatus?status=$status&pin=$pin";
  1705. Log3 $name, 3, "$name: setCamera ".$commandurl;
  1706. HttpUtils_NonblockingGet({
  1707. url => $commandurl,
  1708. timeout => 20,
  1709. noshutdown => 1,
  1710. verify_hostname => 0,
  1711. hash => $hash,
  1712. type => 'camerastatus',
  1713. callback => \&netatmo_dispatch,
  1714. });
  1715. }
  1716. sub
  1717. netatmo_setCameraSetting($$$)
  1718. {
  1719. my ($hash,$setting,$newvalue) = @_;
  1720. my $name = $hash->{NAME};
  1721. #netatmo_pingCamera( $hash );
  1722. my $commandurl = ReadingsVal( $name, "vpn_url", undef );
  1723. return undef if(!defined($commandurl));
  1724. $commandurl .= "/command/changesetting?$setting=$newvalue";
  1725. Log3 $name, 3, "$name: setCameraSetting ".$commandurl;
  1726. HttpUtils_NonblockingGet({
  1727. url => $commandurl,
  1728. timeout => 20,
  1729. noshutdown => 1,
  1730. verify_hostname => 0,
  1731. hash => $hash,
  1732. type => 'camerastatus',
  1733. callback => \&netatmo_dispatch,
  1734. });
  1735. }
  1736. sub
  1737. netatmo_setFloodlight($$)
  1738. {
  1739. my ($hash,$setting) = @_;
  1740. my $name = $hash->{NAME};
  1741. #netatmo_pingCamera( $hash );
  1742. my $commandurl = ReadingsVal( $name, "local_url", ReadingsVal( $name, "vpn_url", undef ) );
  1743. return undef if(!defined($commandurl));
  1744. $commandurl .= "/command/floodlight_set_config?config=%7B%22mode%22:%22$setting%22%7D";
  1745. Log3 $name, 3, "$name: setFloodlight ".$commandurl;
  1746. HttpUtils_NonblockingGet({
  1747. url => $commandurl,
  1748. timeout => 20,
  1749. noshutdown => 1,
  1750. verify_hostname => 0,
  1751. hash => $hash,
  1752. type => 'camerastatus',
  1753. callback => \&netatmo_dispatch,
  1754. });
  1755. }
  1756. sub
  1757. netatmo_setIntensity($$)
  1758. {
  1759. my ($hash,$setting) = @_;
  1760. my $name = $hash->{NAME};
  1761. #netatmo_pingCamera( $hash );
  1762. my $commandurl = ReadingsVal( $name, "local_url", ReadingsVal( $name, "vpn_url", undef ) );
  1763. return undef if(!defined($commandurl));
  1764. $commandurl .= "/command/floodlight_interactive_config?intensity=$setting";
  1765. Log3 $name, 3, "$name: setIntensity ".$commandurl;
  1766. HttpUtils_NonblockingGet({
  1767. url => $commandurl,
  1768. timeout => 20,
  1769. noshutdown => 1,
  1770. verify_hostname => 0,
  1771. hash => $hash,
  1772. type => 'camerastatus',
  1773. callback => \&netatmo_dispatch,
  1774. });
  1775. }
  1776. sub
  1777. netatmo_setPresenceConfig($$)
  1778. {
  1779. my ($hash,$setting) = @_;
  1780. my $name = $hash->{NAME};
  1781. #netatmo_pingCamera( $hash );
  1782. my $commandurl = ReadingsVal( $name, "local_url", ReadingsVal( $name, "vpn_url", undef ) );
  1783. return undef if(!defined($commandurl));
  1784. $commandurl .= "/command/floodlight_set_config?config=%7B%22intensity%22:".ReadingsVal( $name, "intensity", 50 ).",%22night%22:%7B%22always%22:".ReadingsVal( $name, "night_always", "false" ).",%22animal%22:".ReadingsVal( $name, "night_animal", "false" ).",%22movement%22:".ReadingsVal( $name, "night_movement", "false" ).",%22person%22:".ReadingsVal( $name, "night_person", "true" ).",%22vehicle%22:".ReadingsVal( $name, "night_vehicle", "false" )."%7D%7D";
  1785. Log3 $name, 3, "$name: setPresenceConfig ".$commandurl;
  1786. HttpUtils_NonblockingGet({
  1787. url => $commandurl,
  1788. timeout => 20,
  1789. noshutdown => 1,
  1790. verify_hostname => 0,
  1791. hash => $hash,
  1792. type => 'camerastatus',
  1793. callback => \&netatmo_dispatch,
  1794. });
  1795. }
  1796. sub
  1797. netatmo_getPresenceConfig($)
  1798. {
  1799. my ($hash) = @_;
  1800. my $name = $hash->{NAME};
  1801. #netatmo_pingCamera( $hash );
  1802. my $commandurl = ReadingsVal( $name, "local_url", ReadingsVal( $name, "vpn_url", undef ) );
  1803. return undef if(!defined($commandurl));
  1804. $commandurl .= "/command/floodlight_get_config";
  1805. Log3 $name, 3, "$name: getPresenceConfig ".$commandurl;
  1806. HttpUtils_NonblockingGet({
  1807. url => $commandurl,
  1808. timeout => 20,
  1809. noshutdown => 1,
  1810. verify_hostname => 0,
  1811. hash => $hash,
  1812. type => 'cameraconfig',
  1813. callback => \&netatmo_dispatch,
  1814. });
  1815. }
  1816. sub
  1817. netatmo_setTagCalibration($$)
  1818. {
  1819. my ($hash,$setting) = @_;
  1820. my $name = $hash->{NAME};
  1821. return undef if( !defined($hash->{Camera}) );
  1822. my $camerahash = $modules{$hash->{TYPE}}{defptr}{"C$hash->{Camera}"};
  1823. return undef if( !defined($camerahash));
  1824. #netatmo_pingCamera( $hash );
  1825. my $commandurl = ReadingsVal( $camerahash->{NAME}, "local_url", ReadingsVal( $camerahash->{NAME}, "vpn_url", undef ) );
  1826. return undef if(!defined($commandurl));
  1827. $commandurl .= "/command/dtg_cal?id=".$hash->{Tag};
  1828. Log3 $name, 3, "$name: setTagCalibration ".$commandurl;
  1829. HttpUtils_NonblockingGet({
  1830. url => $commandurl,
  1831. timeout => 20,
  1832. noshutdown => 1,
  1833. verify_hostname => 0,
  1834. hash => $hash,
  1835. type => 'tagstatus',
  1836. callback => \&netatmo_dispatch,
  1837. });
  1838. }
  1839. sub
  1840. netatmo_setThermostatMode($$;$)
  1841. {
  1842. my ($hash,$set,$duration) = @_;
  1843. my $name = $hash->{NAME};
  1844. return undef if( !defined($hash->{IODev}) );
  1845. my $iohash = $hash->{IODev};
  1846. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1847. return Log3 $name, 1, "$name: No access token was found! (setThermostatMode)" if(!defined($iohash->{access_token}));
  1848. my %data;
  1849. %data = (access_token => $iohash->{access_token}, device_id => $hash->{Relay}, module_id => $hash->{Thermostat}, setpoint_mode => $set);
  1850. if(defined($duration) || $set eq "max")
  1851. {
  1852. $duration = AttrVal($name,"setpoint_duration",60) if(!defined($duration));
  1853. my $endpoint = time + (60 * $duration);
  1854. %data = (access_token => $iohash->{access_token}, device_id => $hash->{Relay}, module_id => $hash->{Thermostat}, setpoint_mode => $set, setpoint_endtime => $endpoint);
  1855. }
  1856. Log3 $name, 3, "$name: setThermostatMode ($set)";
  1857. HttpUtils_NonblockingGet({
  1858. url => "https://".$iohash->{helper}{apiserver}."/api/setthermpoint",
  1859. timeout => 20,
  1860. noshutdown => 1,
  1861. data => \%data,
  1862. hash => $hash,
  1863. type => 'setthermostat',
  1864. callback => \&netatmo_dispatch,
  1865. });
  1866. }
  1867. sub
  1868. netatmo_setThermostatTemp($$;$$)
  1869. {
  1870. my ($hash,$set,$duration) = @_;
  1871. my $name = $hash->{NAME};
  1872. return undef if( !defined($hash->{IODev}) );
  1873. my $iohash = $hash->{IODev};
  1874. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1875. return Log3 $name, 1, "$name: No access token was found! (setThermostatTemp)" if(!defined($iohash->{access_token}));
  1876. $duration = AttrVal($name,"setpoint_duration",60) if(!defined($duration));
  1877. my $endpoint = time + (60 * $duration);
  1878. my %data = (access_token => $iohash->{access_token}, device_id => $hash->{Relay}, module_id => $hash->{Thermostat}, setpoint_mode => 'manual', setpoint_temp => $set, setpoint_endtime => $endpoint);
  1879. Log3 $name, 3, "$name: setThermostatTemp ($set)";
  1880. HttpUtils_NonblockingGet({
  1881. url => "https://".$iohash->{helper}{apiserver}."/api/setthermpoint",
  1882. timeout => 20,
  1883. noshutdown => 1,
  1884. data => \%data,
  1885. hash => $hash,
  1886. type => 'setthermostat',
  1887. callback => \&netatmo_dispatch,
  1888. });
  1889. }
  1890. sub
  1891. netatmo_setThermostatProgram($$)
  1892. {
  1893. my ($hash,$set) = @_;
  1894. my $name = $hash->{NAME};
  1895. return undef if( !defined($hash->{IODev}) );
  1896. my $iohash = $hash->{IODev};
  1897. netatmo_refreshToken( $iohash, defined($iohash->{access_token}) );
  1898. return Log3 $name, 1, "$name: No access token was found! (setThermostatProgram)" if(!defined($iohash->{access_token}));
  1899. my $schedule_id = 0;
  1900. foreach my $scheduledata ( @{$hash->{schedules}})
  1901. {
  1902. $schedule_id = @{$scheduledata}[1] if($set eq @{$scheduledata}[0]);
  1903. }
  1904. my %data = (access_token => $iohash->{access_token}, device_id => $hash->{Relay}, module_id => $hash->{Thermostat}, schedule_id => $schedule_id);
  1905. Log3 $name, 3, "$name: setThermostatProgram ($set / $schedule_id)";
  1906. HttpUtils_NonblockingGet({
  1907. url => "https://".$iohash->{helper}{apiserver}."/api/switchschedule",
  1908. timeout => 20,
  1909. noshutdown => 1,
  1910. data => \%data,
  1911. hash => $hash,
  1912. type => 'setthermostat',
  1913. callback => \&netatmo_dispatch,
  1914. });
  1915. }
  1916. sub
  1917. netatmo_poll($)
  1918. {
  1919. my ($hash) = @_;
  1920. my $name = $hash->{NAME};
  1921. return undef if(IsDisabled($name) || !defined($name));
  1922. # my $resolve = inet_aton($hash->{helper}{apiserver});
  1923. # if(!defined($resolve))
  1924. # {
  1925. # Log3 $name, 1, "$name: DNS error on poll";
  1926. # InternalTimer( gettimeofday() + 1800, "netatmo_poll", $hash);
  1927. # return undef;
  1928. # }
  1929. $hash->{helper}{INTERVAL} = 3600 if(!defined($hash->{helper}{INTERVAL}));
  1930. if(defined($hash->{status}) && ($hash->{status} =~ /usage/ || $hash->{status} =~ /too_many_connections/)) {
  1931. RemoveInternalTimer($hash);
  1932. InternalTimer(gettimeofday()+$hash->{helper}{INTERVAL}+1800, "netatmo_poll", $hash);
  1933. Log3 $name, 1, "$name: API usage limit reached";
  1934. $hash->{status} = "postponed update";
  1935. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  1936. return undef;
  1937. }
  1938. $hash->{status} = "ok";
  1939. if( $hash->{SUBTYPE} eq "ACCOUNT" && defined($hash->{network}) && $hash->{network} eq "timeout" ) {
  1940. RemoveInternalTimer($hash);
  1941. InternalTimer(gettimeofday()+300, "netatmo_poll", $hash);
  1942. $hash->{status} = "recovering timeout";
  1943. netatmo_checkConnection($hash);
  1944. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  1945. return undef;
  1946. } elsif( $hash->{SUBTYPE} eq "ACCOUNT" && defined($hash->{network}) && $hash->{network} ne "ok" ) {
  1947. RemoveInternalTimer($hash);
  1948. InternalTimer(gettimeofday()+600, "netatmo_poll", $hash);
  1949. $hash->{status} = "recovering network";
  1950. netatmo_checkConnection($hash);
  1951. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  1952. Log3 $name, 5, "$name: ACCOUNT network error: ".$hash->{network};
  1953. return undef;
  1954. } elsif( $hash->{SUBTYPE} ne "ACCOUNT" && defined($hash->{IODev}->{network}) && $hash->{IODev}->{network} ne "ok" ) {
  1955. RemoveInternalTimer($hash);
  1956. InternalTimer(gettimeofday()+150, "netatmo_poll", $hash);
  1957. $hash->{status} = "delayed update";
  1958. #netatmo_checkConnection($hash->{IODev});
  1959. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  1960. Log3 $name, 5, "$name: DEVICE network error: ".$hash->{IODev}->{network};
  1961. return undef;
  1962. }
  1963. Log3 $name, 3, "$name: poll ($hash->{SUBTYPE})";
  1964. if( $hash->{SUBTYPE} eq "ACCOUNT" ) {
  1965. netatmo_pollGlobal($hash);
  1966. netatmo_pollGlobalHealth($hash);
  1967. } elsif( $hash->{SUBTYPE} eq "DEVICE" ) {
  1968. netatmo_pollDevice($hash);
  1969. } elsif( $hash->{SUBTYPE} eq "MODULE" ) {
  1970. netatmo_pollDevice($hash);
  1971. } elsif( $hash->{SUBTYPE} eq "PUBLIC" ) {
  1972. netatmo_pollDevice($hash);
  1973. } elsif( $hash->{SUBTYPE} eq "FORECAST" ) {
  1974. netatmo_pollForecast($hash);
  1975. } elsif( $hash->{SUBTYPE} eq "HOME" ) {
  1976. netatmo_pollHome($hash);
  1977. } elsif( $hash->{SUBTYPE} eq "CAMERA" ) {
  1978. netatmo_pingCamera($hash);
  1979. } elsif( $hash->{SUBTYPE} eq "RELAY" ) {
  1980. netatmo_pollRelay($hash);
  1981. } elsif( $hash->{SUBTYPE} eq "THERMOSTAT" ) {
  1982. netatmo_pollThermostat($hash);
  1983. } elsif( $hash->{SUBTYPE} eq "HEATINGHOME" ) {
  1984. netatmo_pollHeatingHome($hash);
  1985. } elsif( $hash->{SUBTYPE} eq "HEATINGROOM" ) {
  1986. netatmo_pollHeatingRoom($hash);
  1987. } elsif( $hash->{SUBTYPE} eq "PERSON" ) {
  1988. netatmo_pollPerson($hash);
  1989. } else {
  1990. Log3 $name, 1, "$name: unknown netatmo type $hash->{SUBTYPE} on poll";
  1991. return undef;
  1992. }
  1993. if( defined($hash->{helper}{update_count}) && $hash->{helper}{update_count} > 1024 ) {
  1994. InternalTimer(gettimeofday()+30, "netatmo_poll", $hash);
  1995. } else {
  1996. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+$hash->{helper}{INTERVAL};
  1997. InternalTimer(gettimeofday()+$hash->{helper}{INTERVAL}, "netatmo_poll", $hash);
  1998. }
  1999. }
  2000. sub
  2001. netatmo_dispatch($$$)
  2002. {
  2003. my ($param, $err, $data) = @_;
  2004. my $hash = $param->{hash};
  2005. my $name = $hash->{NAME};
  2006. if(!defined($param->{hash})){
  2007. Log3 "netatmo", 2, "netatmo: ".$param->{type}."dispatch fail (hash missing)";
  2008. return undef;
  2009. }
  2010. if(!defined($hash->{NAME})){
  2011. Log3 "netatmo", 2, "netatmo: ".$param->{type}."dispatch fail (name missing)";
  2012. return undef;
  2013. }
  2014. Log3 $name, 4, "$name: dispatch ($param->{type})";
  2015. $hash->{openRequests} -= 1 if( $param->{type} eq 'getmeasure' );
  2016. if( $err ) {
  2017. Log3 $name, 2, "$name: http request failed: $err";
  2018. if($err =~ /refused/ ){
  2019. RemoveInternalTimer($hash);
  2020. InternalTimer(gettimeofday()+3600, "netatmo_poll", $hash);
  2021. Log3 $name, 1, "$name: Possible IP Ban by Netatmo servers, try to change your IP and increase your request interval";
  2022. $hash->{status} = "banned";
  2023. $hash->{network} = "banned" if($hash->{SUBTYPE} eq "ACCOUNT");
  2024. }
  2025. elsif($err =~ /Invalid access token/){
  2026. RemoveInternalTimer($hash);
  2027. InternalTimer(gettimeofday()+300, "netatmo_poll", $hash);
  2028. $hash->{status} = "token";
  2029. $hash->{expires_at} = int(gettimeofday()) if($hash->{SUBTYPE} eq "ACCOUNT");
  2030. $hash->{IODev}->{expires_at} = int(gettimeofday()) if($hash->{SUBTYPE} ne "ACCOUNT");
  2031. }
  2032. elsif($err =~ /Bad hostname/ || $err =~ /gethostbyname/){
  2033. RemoveInternalTimer($hash);
  2034. InternalTimer(gettimeofday()+600, "netatmo_poll", $hash);
  2035. $hash->{status} = "timeout";
  2036. $hash->{network} = "dns" if($hash->{SUBTYPE} eq "ACCOUNT");
  2037. }
  2038. elsif($err =~ /timed out/){
  2039. RemoveInternalTimer($hash);
  2040. InternalTimer(gettimeofday()+300, "netatmo_poll", $hash);
  2041. $hash->{status} = "timeout";
  2042. $hash->{network} = "timeout" if($hash->{SUBTYPE} eq "ACCOUNT");
  2043. }
  2044. elsif($err =~ /Can't connect/){
  2045. RemoveInternalTimer($hash);
  2046. InternalTimer(gettimeofday()+300, "netatmo_poll", $hash);
  2047. $hash->{status} = "timeout";
  2048. $hash->{network} = "disconnected" if($hash->{SUBTYPE} eq "ACCOUNT");
  2049. #CommandDeleteReading( undef, "$hash->{NAME} vpn_url" ) if($hash->{SUBTYPE} eq "CAMERA");
  2050. }
  2051. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  2052. return undef;
  2053. } elsif( $data ) {
  2054. $data =~ s/\n//g;
  2055. if( $data !~ m/^{.*}$/ ) {
  2056. RemoveInternalTimer($hash);
  2057. InternalTimer(gettimeofday()+300, "netatmo_poll", $hash);
  2058. Log3 $name, 2, "$name: invalid json detected";
  2059. Log3 $name, 5, "$name: $data";
  2060. $hash->{status} = "error";
  2061. $hash->{network} = "ok" if($hash->{SUBTYPE} eq "ACCOUNT");
  2062. $hash->{IODev}->{network} = "ok" if($hash->{SUBTYPE} ne "ACCOUNT");
  2063. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  2064. return undef;
  2065. }
  2066. $hash->{network} = "ok" if($hash->{SUBTYPE} eq "ACCOUNT");
  2067. $hash->{IODev}->{network} = "ok" if($hash->{SUBTYPE} ne "ACCOUNT");
  2068. my $json = eval { JSON->new->utf8(0)->decode($data) };
  2069. if($@)
  2070. {
  2071. Log3 $name, 2, "$name: invalid json evaluation on dispatch type ".$param->{type}." ".$@;
  2072. return undef;
  2073. }
  2074. Log3 "unknown", 2, "unknown (no name) ".Dumper($hash) if(!defined($name));
  2075. Log3 $name, 4, "$name: dispatch return: ".$param->{type};
  2076. Log3 $name, 5, Dumper($json);
  2077. if( $json->{error} ) {
  2078. if(ref($json->{error}) ne "HASH") {
  2079. $hash->{STATE} = "LOGIN FAILED" if($hash->{SUBTYPE} eq "ACCOUNT");
  2080. $hash->{status} = $json->{error};
  2081. Log3 $name, 2, "$name: json message error: ".$json->{error};
  2082. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  2083. return undef;
  2084. }
  2085. $hash->{status} = $json->{error}{message} if(defined($json->{error}{message}));
  2086. InternalTimer(gettimeofday()+1800, "netatmo_poll", $hash, 0) if($hash->{status} =~ /usage/ || $hash->{status} =~ /too_many_connections/);
  2087. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  2088. return undef if($hash->{status} =~ /usage/ || $hash->{status} =~ /too_many_connections/);
  2089. }
  2090. if( $param->{type} eq 'token' ) {
  2091. netatmo_parseToken($hash,$json);
  2092. } elsif( $param->{type} eq 'apptoken' ) {
  2093. netatmo_parseAppToken($hash,$json);
  2094. } elsif( $param->{type} eq 'devicelist' ) {
  2095. netatmo_parseDeviceList($hash,$json);
  2096. } elsif( $param->{type} eq 'stationsdata' ) {
  2097. netatmo_parseGlobal($hash,$json);
  2098. } elsif( $param->{type} eq 'forecastdata' ) {
  2099. netatmo_parseForecast($hash,$json);
  2100. } elsif( $param->{type} eq 'getmeasure' ) {
  2101. netatmo_parseReadings($hash,$json,$param->{requested});
  2102. } elsif( $param->{type} eq 'homelist' ) {
  2103. netatmo_parseHomeList($hash,$json);
  2104. } elsif( $param->{type} eq 'gethomedata' ) {
  2105. netatmo_parseHomeReadings($hash,$json);
  2106. } elsif( $param->{type} eq 'cameraping' ) {
  2107. netatmo_parseCameraPing($hash,$json);
  2108. } elsif( $param->{type} eq 'camerastatus' ) {
  2109. netatmo_parseCameraStatus($hash,$json);
  2110. } elsif( $param->{type} eq 'cameraconfig' ) {
  2111. netatmo_parseCameraConfig($hash,$json);
  2112. } elsif( $param->{type} eq 'tagstatus' ) {
  2113. netatmo_parseTagStatus($hash,$json);
  2114. } elsif( $param->{type} eq 'cameravideo' ) {
  2115. netatmo_parseCameraVideo($hash,$json);
  2116. } elsif( $param->{type} =~ /setpersonsstatus_/ ) {
  2117. netatmo_parsePersonsStatus($hash,$json,$param->{type});
  2118. } elsif( $param->{type} eq 'homecoachlist' ) {
  2119. netatmo_parseHomecoachList($hash,$json);
  2120. } elsif( $param->{type} eq 'thermostatlist' ) {
  2121. netatmo_parseThermostatList($hash,$json);
  2122. } elsif( $param->{type} eq 'getthermostatsdata' ) {
  2123. netatmo_parseThermostatReadings($hash,$json);
  2124. } elsif( $param->{type} eq 'setthermostat' ) {
  2125. netatmo_parseThermostatStatus($hash,$json);
  2126. } elsif( $param->{type} eq 'getheatinghomedata' ) {
  2127. netatmo_parseHeatingHomeStatus($hash,$json);
  2128. } elsif( $param->{type} eq 'getpersondata' ) {
  2129. netatmo_parsePersonReadings($hash,$json);
  2130. } elsif( $param->{type} eq 'publicdata' ) {
  2131. return netatmo_parsePublic($hash,$json);
  2132. } elsif( $param->{type} eq 'address' ) {
  2133. return netatmo_parseAddress($hash,$json);
  2134. } elsif( $param->{type} eq 'latlng' ) {
  2135. return netatmo_parseLatLng($hash,$json);
  2136. } elsif( $param->{type} eq 'addwebhook' ) {
  2137. return netatmo_webhookStatus($hash,$json,"added");
  2138. } elsif( $param->{type} eq 'dropwebhook' ) {
  2139. return netatmo_webhookStatus($hash,$json,"dropped");
  2140. } elsif( $param->{type} eq 'sethomesettings' ) {
  2141. return netatmo_refreshHomeSettings($hash);
  2142. } else {
  2143. Log3 $name, 1, "$name: unknown '$param->{type}' ".Dumper($json);
  2144. }
  2145. }
  2146. }
  2147. sub
  2148. netatmo_parsePersonsStatus($$$)
  2149. {
  2150. my ($hash, $json, $param) = @_;
  2151. my $name = $hash->{NAME};
  2152. Log3 $name, 5, "$name: parsePersonsStatus ($param)\n".Dumper($json);
  2153. return if(!defined($json->{status}) || $json->{status} ne "ok");
  2154. if($hash->{SUBTYPE} eq "PERSON")
  2155. {
  2156. if($param =~ /away/)
  2157. {
  2158. readingsSingleUpdate( $hash, "status", "away", 1 );
  2159. }
  2160. else{
  2161. readingsSingleUpdate( $hash, "status", "home", 1 );
  2162. }
  2163. }
  2164. elsif($hash->{SUBTYPE} eq "HOME")
  2165. {
  2166. readingsSingleUpdate( $hash, "event", "Everyone left", 1 );
  2167. }
  2168. }
  2169. sub
  2170. netatmo_autocreate($;$)
  2171. {
  2172. my($hash,$force) = @_;
  2173. my $name = $hash->{NAME};
  2174. if( !$hash->{helper}{devices} ) {
  2175. netatmo_getDevices($hash,1);
  2176. return undef if( !$force );
  2177. }
  2178. if( !$force ) {
  2179. foreach my $d (keys %defs) {
  2180. next if(!defined($defs{$d}));
  2181. next if($defs{$d}{TYPE} ne "autocreate");
  2182. return undef if(IsDisabled($defs{$d}{NAME}));
  2183. }
  2184. }
  2185. my $autocreated = 0;
  2186. my $devices = $hash->{helper}{devices};
  2187. foreach my $device (@{$devices}) {
  2188. if( defined($modules{$hash->{TYPE}}{defptr}{"D$device->{_id}"}) ) {
  2189. Log3 $name, 4, "$name: device '$device->{_id}' already defined";
  2190. next;
  2191. }
  2192. if( defined($modules{$hash->{TYPE}}{defptr}{"M$device->{_id}"}) ) {
  2193. Log3 $name, 4, "$name: module '$device->{_id}' already defined";
  2194. next;
  2195. }
  2196. if(AttrVal($name,"ignored_device_ids","") =~ /$device->{_id}/) {
  2197. Log3 $name, 4, "$name: '$device->{_id}' ignored for autocreate";
  2198. next;
  2199. }
  2200. my $id = $device->{_id};
  2201. my $devname = "netatmo_D". $id;
  2202. $devname =~ s/:/_/g;
  2203. my $define= "$devname netatmo $id";
  2204. if( $device->{main_device} ) {
  2205. $devname = "netatmo_M". $id;
  2206. $devname =~ s/:/_/g;
  2207. $define= "$devname netatmo MODULE $device->{main_device} $id";
  2208. }
  2209. Log3 $name, 3, "$name: create new device '$devname' for device '$id'";
  2210. my $cmdret= CommandDefine(undef,$define);
  2211. if($cmdret) {
  2212. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  2213. } else {
  2214. $cmdret= CommandAttr(undef,"$devname alias ".encode_utf8($device->{module_name})) if( defined($device->{module_name}) );
  2215. $cmdret= CommandAttr(undef,"$devname room netatmo");
  2216. $cmdret= CommandAttr(undef,"$devname IODev $name");
  2217. $cmdret= CommandAttr(undef,"$devname devStateIcon .*:no-icon");
  2218. $autocreated++;
  2219. }
  2220. }
  2221. CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
  2222. return "created $autocreated devices";
  2223. }
  2224. sub
  2225. netatmo_autocreatehome($;$)
  2226. {
  2227. my($hash,$force) = @_;
  2228. my $name = $hash->{NAME};
  2229. if( !$hash->{helper}{homes} ) {
  2230. return undef if( !$force );
  2231. netatmo_getHomes($hash,1);
  2232. }
  2233. if( !$force ) {
  2234. foreach my $d (keys %defs) {
  2235. next if(!defined($defs{$d}));
  2236. next if($defs{$d}{TYPE} ne "autocreate");
  2237. return undef if(IsDisabled($defs{$d}{NAME}));
  2238. }
  2239. }
  2240. my $autocreated = 0;
  2241. my $homes = $hash->{helper}{homes};
  2242. foreach my $home (@{$homes}) {
  2243. if( defined($modules{$hash->{TYPE}}{defptr}{"H$home->{id}"}) ) {
  2244. Log3 $name, 4, "$name: home '$home->{id}' already defined";
  2245. next;
  2246. }
  2247. if( defined($modules{$hash->{TYPE}}{defptr}{"P$home->{id}"}) ) {
  2248. Log3 $name, 4, "$name: person '$home->{id}' already defined";
  2249. next;
  2250. }
  2251. foreach my $module (@{$home->{modules}}) {
  2252. if( defined($modules{$hash->{TYPE}}{defptr}{"G$module->{id}"}) ) {
  2253. Log3 $name, 4, "$name: tag '$module->{id}' already defined";
  2254. next;
  2255. }
  2256. my $tagid = $module->{id};
  2257. my $tagdevname = "netatmo_G". $tagid;
  2258. $tagdevname =~ s/:/_/g;
  2259. my $tagdefine= "$tagdevname netatmo TAG $home->{id} $tagid";
  2260. Log3 $name, 3, "$name: create new tag '$tagdevname' for camera '$home->{id}'";
  2261. my $tagcmdret= CommandDefine(undef,$tagdefine);
  2262. if($tagcmdret) {
  2263. Log3 $name, 1, "$name: Autocreate: An error occurred while creating tag for id '$tagid': $tagcmdret";
  2264. } else {
  2265. $tagcmdret= CommandAttr(undef,"$tagdevname alias ".encode_utf8($module->{name})) if( defined($module->{name}) );
  2266. $tagcmdret= CommandAttr(undef,"$tagdevname devStateIcon .*:no-icon");
  2267. $tagcmdret= CommandAttr(undef,"$tagdevname room netatmo");
  2268. $tagcmdret= CommandAttr(undef,"$tagdevname stateFormat status");
  2269. $tagcmdret= CommandAttr(undef,"$tagdevname IODev $name");
  2270. $autocreated++;
  2271. }
  2272. }
  2273. if( defined($modules{$hash->{TYPE}}{defptr}{"C$home->{id}"}) ) {
  2274. Log3 $name, 4, "$name: camera '$home->{id}' already defined";
  2275. next;
  2276. }
  2277. if(AttrVal($name,"ignored_device_ids","") =~ /$home->{id}/) {
  2278. Log3 $name, 4, "$name: '$home->{id}' ignored for autocreate";
  2279. next;
  2280. }
  2281. my $id = $home->{id};
  2282. my $devname = "netatmo_H". $id;
  2283. $devname =~ s/-/_/g;
  2284. my $define= "$devname netatmo HOME $id";
  2285. if( $home->{sd_status} ) {
  2286. $devname = "netatmo_C". $id;
  2287. $devname =~ s/:/_/g;
  2288. $devname =~ s/-/_/g;
  2289. $define= "$devname netatmo CAMERA $home->{home} $id";
  2290. }
  2291. elsif( $home->{face} ) {
  2292. next if(!defined($home->{pseudo})); #ignore unassigned faces
  2293. Log3 $name, 5, "$name: create new home/person '$devname' for home '$home->{home}'".Dumper($home);
  2294. $devname = "netatmo_P". $id;
  2295. $devname =~ s/-/_/g;
  2296. $define= "$devname netatmo PERSON $home->{home} $id";
  2297. }
  2298. $home->{home} = "?" if(!defined($home->{home}));
  2299. Log3 $name, 3, "$name: create new home/person '$devname' for home '$home->{home}'";
  2300. my $cmdret= CommandDefine(undef,$define);
  2301. if($cmdret) {
  2302. Log3 $name, 1, "$name: Autocreate: An error occurred while creating home for id '$id': $cmdret";
  2303. } else {
  2304. $cmdret= CommandAttr(undef,"$devname alias Unknown") if( defined($home->{face}) );
  2305. $cmdret= CommandAttr(undef,"$devname alias ".encode_utf8($home->{pseudo})) if( defined($home->{pseudo}) );
  2306. $cmdret= CommandAttr(undef,"$devname alias ".encode_utf8($home->{name})) if( defined($home->{name}) );
  2307. $cmdret= CommandAttr(undef,"$devname devStateIcon .*:no-icon");
  2308. $cmdret= CommandAttr(undef,"$devname room netatmo");
  2309. $cmdret= CommandAttr(undef,"$devname stateFormat status");
  2310. $cmdret= CommandAttr(undef,"$devname IODev $name");
  2311. $autocreated++;
  2312. }
  2313. }
  2314. CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
  2315. return "created $autocreated devices";
  2316. }
  2317. sub
  2318. netatmo_autocreatethermostat($;$)
  2319. {
  2320. my($hash,$force) = @_;
  2321. my $name = $hash->{NAME};
  2322. if( !$hash->{helper}{thermostats} ) {
  2323. netatmo_getThermostats($hash,1);
  2324. return undef if( !$force );
  2325. }
  2326. if( !$force ) {
  2327. foreach my $d (keys %defs) {
  2328. next if(!defined($defs{$d}));
  2329. next if($defs{$d}{TYPE} ne "autocreate");
  2330. return undef if(IsDisabled($defs{$d}{NAME}));
  2331. }
  2332. }
  2333. my $autocreated = 0;
  2334. my $devices = $hash->{helper}{thermostats};
  2335. #Log3 $name, 1, "$name: autocreating ".Dumper($devices);
  2336. foreach my $device (@{$devices}) {
  2337. if( defined($modules{$hash->{TYPE}}{defptr}{"R$device->{id}"}) ) {
  2338. Log3 $name, 4, "$name: relay '$device->{id}' already defined";
  2339. next;
  2340. }
  2341. if( defined($modules{$hash->{TYPE}}{defptr}{"T$device->{id}"}) ) {
  2342. Log3 $name, 4, "$name: thermostat '$device->{id}' already defined";
  2343. next;
  2344. }
  2345. if( defined($modules{$hash->{TYPE}}{defptr}{"E$device->{id}"}) ) {
  2346. Log3 $name, 4, "$name: heating home '$device->{id}' already defined";
  2347. next;
  2348. }
  2349. if( defined($modules{$hash->{TYPE}}{defptr}{"O$device->{id}"}) ) {
  2350. Log3 $name, 4, "$name: heating room '$device->{id}' already defined";
  2351. next;
  2352. }
  2353. if(AttrVal($name,"ignored_device_ids","") =~ /$device->{id}/) {
  2354. Log3 $name, 4, "$name: '$device->{id}' ignored for autocreate";
  2355. next;
  2356. }
  2357. my $id = $device->{id};
  2358. my $devname = "netatmo_R". $id;
  2359. $devname =~ s/:/_/g;
  2360. my $define= "$devname netatmo RELAY $id";
  2361. if( $device->{type} eq "Home" ) {
  2362. $devname = "netatmo_E". $id;
  2363. $devname =~ s/:/_/g;
  2364. $define= "$devname netatmo HEATINGHOME $id";
  2365. }
  2366. elsif( $device->{type} eq "Room" ) {
  2367. $devname = "netatmo_O". $id;
  2368. $devname =~ s/:/_/g;
  2369. $define= "$devname netatmo HEATINGROOM $device->{Home} $id";
  2370. }
  2371. elsif( $device->{main_device} ) {
  2372. $devname = "netatmo_T". $id;
  2373. $devname =~ s/:/_/g;
  2374. $define= "$devname netatmo THERMOSTAT $device->{main_device} $id";
  2375. }
  2376. Log3 $name, 3, "$name: create new device '$devname' for device '$id'";
  2377. my $cmdret= CommandDefine(undef,$define);
  2378. if($cmdret) {
  2379. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  2380. } else {
  2381. $cmdret= CommandAttr(undef,"$devname alias ".encode_utf8($device->{name})) if( defined($device->{name}) );
  2382. #$cmdret= CommandAttr(undef,"$devname alias ".encode_utf8($device->{module_name})) if( defined($device->{module_name}) );
  2383. $cmdret= CommandAttr(undef,"$devname room netatmo");
  2384. $cmdret= CommandAttr(undef,"$devname IODev $name");
  2385. $cmdret= CommandAttr(undef,"$devname devStateIcon .*:no-icon");
  2386. $cmdret= CommandAttr(undef,"$devname stateFormat setpoint|temperature") if( $device->{main_device} );
  2387. $cmdret= CommandAttr(undef,"$devname stateFormat active") if( !$device->{main_device} );
  2388. $autocreated++;
  2389. }
  2390. }
  2391. CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
  2392. return "created $autocreated devices";
  2393. }
  2394. sub
  2395. netatmo_autocreatehomecoach($;$)
  2396. {
  2397. my($hash,$force) = @_;
  2398. my $name = $hash->{NAME};
  2399. if( !$hash->{helper}{homecoachs} ) {
  2400. netatmo_getHomecoachs($hash,1);
  2401. return undef if( !$force );
  2402. }
  2403. if( !$force ) {
  2404. foreach my $d (keys %defs) {
  2405. next if(!defined($defs{$d}));
  2406. next if($defs{$d}{TYPE} ne "autocreate");
  2407. return undef if(IsDisabled($defs{$d}{NAME}));
  2408. }
  2409. }
  2410. my $autocreated = 0;
  2411. my $devices = $hash->{helper}{homecoachs};
  2412. foreach my $device (@{$devices}) {
  2413. if( defined($modules{$hash->{TYPE}}{defptr}{"D$device->{_id}"}) ) {
  2414. Log3 $name, 4, "$name: homecoach '$device->{_id}' already defined";
  2415. next;
  2416. }
  2417. if(AttrVal($name,"ignored_device_ids","") =~ /$device->{_id}/) {
  2418. Log3 $name, 4, "$name: '$device->{_id}' ignored for autocreate";
  2419. next;
  2420. }
  2421. my $id = $device->{_id};
  2422. my $devname = "netatmo_D". $id;
  2423. $devname =~ s/:/_/g;
  2424. my $define= "$devname netatmo $id";
  2425. Log3 $name, 3, "$name: create new device '$devname' for device '$id'";
  2426. my $cmdret= CommandDefine(undef,$define);
  2427. if($cmdret) {
  2428. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  2429. } else {
  2430. $cmdret= CommandAttr(undef,"$devname alias ".encode_utf8($device->{name})) if( defined($device->{name}) );
  2431. $cmdret= CommandAttr(undef,"$devname room netatmo");
  2432. $cmdret= CommandAttr(undef,"$devname IODev $name");
  2433. $cmdret= CommandAttr(undef,"$devname devStateIcon .*:no-icon");
  2434. $cmdret= CommandAttr(undef,"$devname stateFormat health_idx");
  2435. $autocreated++;
  2436. }
  2437. }
  2438. CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
  2439. return "created $autocreated devices";
  2440. }
  2441. sub
  2442. netatmo_parseToken($$)
  2443. {
  2444. my($hash, $json) = @_;
  2445. my $name = $hash->{NAME};
  2446. my $had_token = $hash->{access_token};
  2447. $hash->{access_token} = $json->{access_token};
  2448. $hash->{refresh_token} = $json->{refresh_token};
  2449. if( $hash->{access_token} ) {
  2450. $hash->{STATE} = "Connected";
  2451. $hash->{network} = "ok";
  2452. $hash->{expires_at} = int(gettimeofday());
  2453. $hash->{expires_at} += int($json->{expires_in}*0.8);
  2454. netatmo_getDevices($hash) if( !$had_token );
  2455. InternalTimer($hash->{expires_at}, "netatmo_refreshTokenTimer", $hash);
  2456. } else {
  2457. $hash->{expires_at} = int(gettimeofday());
  2458. $hash->{STATE} = "Error" if( !$hash->{access_token} );
  2459. Log3 $name, 1, "$name: token error ".Dumper($json);
  2460. InternalTimer(gettimeofday()+600, "netatmo_refreshTokenTimer", $hash);
  2461. }
  2462. }
  2463. sub
  2464. netatmo_parseAppToken($$)
  2465. {
  2466. my($hash, $json) = @_;
  2467. my $name = $hash->{NAME};
  2468. $hash->{access_token_app} = $json->{access_token};
  2469. $hash->{refresh_token_app} = $json->{refresh_token};
  2470. if( $hash->{access_token_app} ) {
  2471. $hash->{expires_at_app} = int(gettimeofday());
  2472. $hash->{expires_at_app} += int($json->{expires_in}*0.8);
  2473. InternalTimer($hash->{expires_at_app}, "netatmo_refreshAppTokenTimer", $hash);
  2474. } else {
  2475. $hash->{expires_at_app} = int(gettimeofday());
  2476. $hash->{STATE} = "Error" if( !$hash->{access_token_app} );
  2477. Log3 $name, 1, "$name: app token error ".Dumper($json);
  2478. InternalTimer(gettimeofday()+600, "netatmo_refreshAppTokenTimer", $hash);
  2479. }
  2480. }
  2481. sub
  2482. netatmo_parseDeviceList($$)
  2483. {
  2484. my($hash, $json) = @_;
  2485. my $name = $hash->{NAME};
  2486. Log3 $name, 4, "$name: parsedevicelist ";
  2487. #my $do_autocreate = 1;
  2488. #$do_autocreate = 0 if( !defined($hash->{helper}{devices}) ); #autocreate
  2489. my @devices = ();
  2490. foreach my $device (@{$json->{body}{devices}}) {
  2491. push( @devices, $device );
  2492. foreach my $module (@{$device->{modules}}) {
  2493. $module->{main_device} = $device->{_id};
  2494. push( @devices, $module );
  2495. }
  2496. }
  2497. $hash->{helper}{devices} = \@devices;
  2498. #netatmo_autocreate($hash) if( $do_autocreate );
  2499. }
  2500. sub
  2501. netatmo_parseHomeList($$)
  2502. {
  2503. my($hash, $json) = @_;
  2504. my $name = $hash->{NAME};
  2505. #my $do_autocreate = 1;
  2506. #$do_autocreate = 0 if( !defined($hash->{helper}{homes}) ); #autocreate
  2507. Log3 $name, 5, "$name: parsehomelist";
  2508. my @homes = ();
  2509. foreach my $home (@{$json->{body}{homes}}) {
  2510. push( @homes, $home ) if(defined($home->{cameras}) && @{$home->{cameras}});
  2511. foreach my $camera (@{$home->{cameras}}) {
  2512. $camera->{home} = $home->{id};
  2513. push( @homes, $camera ) if(defined($camera->{status}));
  2514. }
  2515. foreach my $person (@{$home->{persons}}) {
  2516. $person->{home} = $home->{id};
  2517. push( @homes, $person ) if(defined($person->{face}));
  2518. }
  2519. }
  2520. $hash->{helper}{homes} = \@homes;
  2521. #netatmo_autocreatehome($hash) if( $do_autocreate );
  2522. }
  2523. sub
  2524. netatmo_parseThermostatList($$)
  2525. {
  2526. my($hash, $json) = @_;
  2527. my $name = $hash->{NAME};
  2528. Log3 $name, 4, "$name: parsethermostatlist ";
  2529. #my $do_autocreate = 1;
  2530. #$do_autocreate = 0 if( !defined($hash->{helper}{devices}) ); #autocreate
  2531. my @devices = ();
  2532. foreach my $home (@{$json->{body}{homes}}) {
  2533. next if(!defined($home->{devices}) || !@{$home->{devices}});
  2534. $home->{type} = "Home";
  2535. $home->{firmware} = "-";
  2536. push( @devices, $home );
  2537. foreach my $room (@{$home->{rooms}}) {
  2538. next if(!defined($room->{modules}) || !@{$room->{modules}});
  2539. $room->{Home} = $home->{id};
  2540. $room->{type} = "Room";
  2541. $room->{firmware} = "-";
  2542. push( @devices, $room );
  2543. }
  2544. foreach my $device (@{$home->{devices}}) {
  2545. push( @devices, $device );
  2546. foreach my $module (@{$device->{modules}}) {
  2547. $module->{main_device} = $device->{id};
  2548. push( @devices, $module );
  2549. }
  2550. }
  2551. }
  2552. $hash->{helper}{thermostats} = \@devices;
  2553. #netatmo_autocreate($hash) if( $do_autocreate );
  2554. }
  2555. sub
  2556. netatmo_parseHomecoachList($$)
  2557. {
  2558. my($hash, $json) = @_;
  2559. my $name = $hash->{NAME};
  2560. Log3 $name, 4, "$name: parsehomecoachlist ";
  2561. #my $do_autocreate = 1;
  2562. #$do_autocreate = 0 if( !defined($hash->{helper}{devices}) ); #autocreate
  2563. my @devices = ();
  2564. foreach my $device (@{$json->{body}{devices}}) {
  2565. push( @devices, $device );
  2566. foreach my $module (@{$device->{modules}}) {
  2567. $module->{main_device} = $device->{_id};
  2568. push( @devices, $module );
  2569. }
  2570. }
  2571. $hash->{helper}{homecoachs} = \@devices;
  2572. #netatmo_autocreate($hash) if( $do_autocreate );
  2573. }
  2574. sub
  2575. netatmo_updateReadings($$)
  2576. {
  2577. my($hash, $readings) = @_;
  2578. my $name = $hash->{NAME};
  2579. my ($seconds) = gettimeofday();
  2580. my $latest = 0;
  2581. if( $readings && @{$readings} ) {
  2582. my $i = 0;
  2583. foreach my $reading (sort { $a->[0] <=> $b->[0] } @{$readings}) {
  2584. if(!defined($reading->[0]) || !defined($reading->[1]) || !defined($reading->[2]))
  2585. {
  2586. Log3 $name, 1, "$name: invalid readings set: ".Dumper($reading);
  2587. next;
  2588. }
  2589. readingsBeginUpdate($hash);
  2590. $hash->{".updateTimestamp"} = FmtDateTime($reading->[0]);
  2591. readingsBulkUpdate( $hash, $reading->[1], $reading->[2] );
  2592. $hash->{CHANGETIME}[0] = FmtDateTime($reading->[0]);
  2593. readingsEndUpdate($hash,1);
  2594. $latest = $reading->[0] if( $reading->[0] > $latest );
  2595. }
  2596. readingsSingleUpdate( $hash, ".lastupdate", $seconds, 0 );
  2597. Log3 $name, 4, "$name: updatereadings";
  2598. }
  2599. return ($seconds,$latest);
  2600. }
  2601. sub
  2602. netatmo_parseReadings($$;$)
  2603. {
  2604. my($hash, $json, $requested) = @_;
  2605. my $name = $hash->{NAME};
  2606. Log3 $name, 4, "$name: parsereadings ".$requested;
  2607. my $reading_names = $hash->{helper}{readingNames};
  2608. if( $requested ) {
  2609. my @readings = split( ',', $requested );
  2610. $reading_names = \@readings;
  2611. }
  2612. if( $json ) {
  2613. $hash->{status} = $json->{status} if($json->{status});
  2614. $hash->{status} = $json->{error}{message} if( $json->{error} );
  2615. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  2616. my @r = ();
  2617. my $readings = \@r;
  2618. $readings = $hash->{readings} if( defined($hash->{readings}) );
  2619. my ($time,$step_time,$last_time) = 0;
  2620. if( $hash->{status} eq "ok" )
  2621. {
  2622. if(scalar(@{$json->{body}}) == 0)
  2623. {
  2624. $hash->{status} = "no data";
  2625. readingsSingleUpdate( $hash, "active", "dead", 1 ) if($hash->{helper}{last_status_store} > 0 && $hash->{helper}{last_status_store} < (int(time) - 7200) );
  2626. }
  2627. foreach my $values ( @{$json->{body}}) {
  2628. $time = $values->{beg_time};
  2629. $step_time = $values->{step_time};
  2630. foreach my $value (@{$values->{value}}) {
  2631. my $i = 0;
  2632. foreach my $reading (@{$value}) {
  2633. #my $rname = $hash->{helper}{readingNames}[$i++];
  2634. my $rname = lc($reading_names->[$i++]);
  2635. if( !defined($reading) )
  2636. {
  2637. $reading = "undefined";#next;
  2638. }
  2639. if(lc($requested) =~ /wind/ && ($rname eq "temperature" || $rname eq "humidity"))
  2640. {
  2641. Log3 $name, 3, "$name netatmo - wind sensor $rname reading: $reading ($time)";
  2642. next;# if($reading == 0);
  2643. }
  2644. if($reading ne "undefined" && (($rname eq "noise" && int($reading) > 150) || ($rname eq "temperature" && int($reading) > 60) || ($rname eq "humidity" && int($reading) > 100) || ($rname eq "pressure" && int($reading) < 500)))
  2645. {
  2646. Log3 $name, 1, "$name netatmo - invalid reading: $rname: ".Dumper($reading)." \n ".Dumper($reading_names);
  2647. next;
  2648. }
  2649. if($reading ne "undefined" && $rname eq "health_idx"){
  2650. $reading = $health_index{$reading};
  2651. }
  2652. if($reading ne "undefined" && $rname =~ /temperature/){
  2653. $reading = sprintf( "%.1f", $reading);
  2654. }
  2655. if($reading ne "undefined" && $rname eq "rain" && $reading > 0)
  2656. {
  2657. my $rain_sum = ReadingsVal($name,"rain_sum",0);
  2658. $rain_sum += $reading;
  2659. readingsSingleUpdate($hash,"rain_sum",$rain_sum,1);
  2660. Log3 $name, 1, $name.": summed rain ".$reading." (to ".$rain_sum.")";
  2661. }
  2662. push(@{$readings}, [$time, $rname, $reading]) if($reading ne "undefined");
  2663. }
  2664. $last_time = $time if(defined($time));
  2665. $time += $step_time if( $step_time );
  2666. }
  2667. $hash->{helper}{last_status_store} = $last_time if($last_time > $hash->{helper}{last_status_store});
  2668. }
  2669. if( $hash->{openRequests} > 1 ) {
  2670. $hash->{readings} = $readings;
  2671. } else {
  2672. my ($seconds,undef) = netatmo_updateReadings( $hash, $readings );
  2673. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  2674. delete $hash->{readings};
  2675. # readingsSingleUpdate($hash, ".lastupdate", $last_time, 0);
  2676. }
  2677. if(defined(AttrVal($name, "interval", undef))){
  2678. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+$hash->{helper}{INTERVAL};
  2679. RemoveInternalTimer($hash, "netatmo_poll");
  2680. InternalTimer($hash->{helper}{NEXT_POLL}, "netatmo_poll", $hash);
  2681. Log3 $name, 3, "$name: next fixed interval update for device ($requested) at ".FmtDateTime($hash->{helper}{NEXT_POLL});
  2682. } elsif(defined($last_time) && int($last_time) > 0 && defined($step_time)) {
  2683. my $nextdata = $last_time + 2*$step_time + 10 + int(rand(20));
  2684. if($hash->{SUBTYPE} eq "MODULE")
  2685. {
  2686. my $devicehash = $modules{$hash->{TYPE}}{defptr}{"D$hash->{Device}"};
  2687. if(defined($devicehash) && defined($devicehash->{helper}{NEXT_POLL}))
  2688. {
  2689. $nextdata = ($devicehash->{helper}{NEXT_POLL} + 10 + int(rand(20)) ) if($devicehash->{helper}{NEXT_POLL} >= gettimeofday()+150);
  2690. if($nextdata >= (gettimeofday()+155))
  2691. {
  2692. RemoveInternalTimer($hash, "netatmo_poll");
  2693. InternalTimer($nextdata, "netatmo_poll", $hash);
  2694. $hash->{helper}{NEXT_POLL} = $nextdata;
  2695. Log3 $name, 3, "$name: next dynamic update from device ($requested) at ".FmtDateTime($nextdata);
  2696. } else {
  2697. $nextdata += $step_time;
  2698. if($nextdata >= (gettimeofday()+155))
  2699. {
  2700. RemoveInternalTimer($hash, "netatmo_poll");
  2701. InternalTimer($nextdata, "netatmo_poll", $hash);
  2702. $hash->{helper}{NEXT_POLL} = $nextdata;
  2703. Log3 $name, 3, "$name: next extended dynamic update from device ($requested) at ".FmtDateTime($nextdata);
  2704. } else {
  2705. Log3 $name, 2, "$name: invalid time for dynamic update from device ($requested): ".FmtDateTime($nextdata);
  2706. }
  2707. }
  2708. }
  2709. }
  2710. elsif($nextdata >= (gettimeofday()+280))
  2711. {
  2712. $nextdata = $nextdata + 10 + int(rand(20));
  2713. RemoveInternalTimer($hash, "netatmo_poll");
  2714. InternalTimer($nextdata, "netatmo_poll", $hash);
  2715. $hash->{helper}{NEXT_POLL} = $nextdata;
  2716. Log3 $name, 3, "$name: next dynamic update ($requested) at ".FmtDateTime($nextdata);
  2717. } else {
  2718. $nextdata += $step_time;
  2719. if($nextdata >= (gettimeofday()+280))
  2720. {
  2721. RemoveInternalTimer($hash, "netatmo_poll");
  2722. InternalTimer($nextdata, "netatmo_poll", $hash);
  2723. $hash->{helper}{NEXT_POLL} = $nextdata;
  2724. Log3 $name, 3, "$name: next extended dynamic update ($requested) at ".FmtDateTime($nextdata);
  2725. } else {
  2726. Log3 $name, 2, "$name: invalid time for dynamic update ($requested): ".FmtDateTime($nextdata);
  2727. }
  2728. }
  2729. } elsif(defined($last_time) && int($last_time) > 0) {
  2730. my $nextdata = int($last_time)+(12*60);
  2731. $nextdata = int(gettimeofday()+280) if($nextdata <= (gettimeofday()+280));
  2732. RemoveInternalTimer($hash, "netatmo_poll");
  2733. InternalTimer($nextdata, "netatmo_poll", $hash);
  2734. $hash->{helper}{NEXT_POLL} = $nextdata;
  2735. Log3 $name, 3, "$name: next predictive update for device ($requested) at ".FmtDateTime($nextdata);
  2736. } else {
  2737. $hash->{helper}{NEXT_POLL} = int(gettimeofday())+(12*60);
  2738. RemoveInternalTimer($hash, "netatmo_poll");
  2739. InternalTimer($hash->{helper}{NEXT_POLL}, "netatmo_poll", $hash);
  2740. Log3 $name, 3, "$name: next fixed update for device ($requested) at ".FmtDateTime($hash->{helper}{NEXT_POLL});
  2741. }
  2742. }
  2743. }
  2744. else
  2745. {
  2746. $hash->{status} = "error";
  2747. }
  2748. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  2749. }
  2750. sub
  2751. netatmo_parseGlobal($$)
  2752. {
  2753. my($hash, $json) = @_;
  2754. my $name = $hash->{NAME};
  2755. Log3 $name, 4, "$name: parseGlobal";
  2756. if( $json )
  2757. {
  2758. Log3 $name, 5, "$name: ".Dumper($json);
  2759. $hash->{status} = $json->{status};
  2760. $hash->{status} = $json->{error}{message} if( $json->{error} );
  2761. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  2762. my @r = ();
  2763. my $readings = \@r;
  2764. $readings = $hash->{readings} if( defined($hash->{readings}) );
  2765. if( $hash->{status} eq "ok" )
  2766. {
  2767. $hash->{STATE} = "Connected";
  2768. foreach my $devicedata ( @{$json->{body}{devices}})
  2769. {
  2770. #Log3 $name, 5, "$name: device " . "D$devicedata->{_id} " .Dumper($devicedata);
  2771. my $device = $modules{$hash->{TYPE}}{defptr}{"D$devicedata->{_id}"};
  2772. next if (!defined($device));
  2773. #Log3 $name, 4, "$name: device " . "D$devicedata->{_id} found";
  2774. if(defined($devicedata->{dashboard_data}{AbsolutePressure}) && $devicedata->{dashboard_data}{AbsolutePressure} ne $devicedata->{dashboard_data}{Pressure})
  2775. {
  2776. readingsBeginUpdate($device);
  2777. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2778. readingsBulkUpdate( $device, "pressure_abs", $devicedata->{dashboard_data}{AbsolutePressure}, 1 );
  2779. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2780. readingsEndUpdate($device,1);
  2781. }
  2782. if(defined($devicedata->{dashboard_data}{pressure_trend}))
  2783. {
  2784. readingsBeginUpdate($device);
  2785. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2786. readingsBulkUpdate( $device, "pressure_trend", $devicedata->{dashboard_data}{pressure_trend}, 1 );
  2787. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2788. readingsEndUpdate($device,1);
  2789. }
  2790. if(defined($devicedata->{dashboard_data}{temp_trend}))
  2791. {
  2792. readingsBeginUpdate($device);
  2793. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2794. readingsBulkUpdate( $device, "temp_trend", $devicedata->{dashboard_data}{temp_trend}, 1 );
  2795. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2796. readingsEndUpdate($device,1);
  2797. }
  2798. if(defined($devicedata->{dashboard_data}{max_temp}) && $devicedata->{type} ne "NAModule2")
  2799. {
  2800. readingsBeginUpdate($device);
  2801. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{date_max_temp});
  2802. readingsBulkUpdate( $device, "temp_max", $devicedata->{dashboard_data}{max_temp}, 1 );
  2803. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{date_max_temp});
  2804. readingsEndUpdate($device,1);
  2805. }
  2806. if(defined($devicedata->{dashboard_data}{min_temp}) && $devicedata->{type} ne "NAModule2")
  2807. {
  2808. readingsBeginUpdate($device);
  2809. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{date_min_temp});
  2810. readingsBulkUpdate( $device, "temp_min", $devicedata->{dashboard_data}{min_temp}, 1 );
  2811. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{date_min_temp});
  2812. readingsEndUpdate($device,1);
  2813. }
  2814. if(defined($devicedata->{dashboard_data}{sum_rain_1}))
  2815. {
  2816. readingsBeginUpdate($device);
  2817. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2818. readingsBulkUpdate( $device, "rain_hour", $devicedata->{dashboard_data}{sum_rain_1}, 1 );
  2819. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2820. readingsEndUpdate($device,1);
  2821. }
  2822. if(defined($devicedata->{dashboard_data}{sum_rain_24}))
  2823. {
  2824. my $rain_day = ReadingsVal($device->{NAME},"rain_day",0);
  2825. if($devicedata->{dashboard_data}{sum_rain_24} < $rain_day)
  2826. {
  2827. my $rain_total = ReadingsVal($device->{NAME},"rain_total",0);
  2828. $rain_total += $rain_day;
  2829. readingsSingleUpdate($device,"rain_total",$rain_total,1);
  2830. Log3 $name, 1, $device->{NAME}.": added rain ".$rain_day." (to ".$rain_total.")";
  2831. }
  2832. readingsBeginUpdate($device);
  2833. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2834. readingsBulkUpdate( $device, "rain_day", $devicedata->{dashboard_data}{sum_rain_24}, 1 );
  2835. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{time_utc});
  2836. readingsEndUpdate($device,1);
  2837. }
  2838. if(defined($devicedata->{dashboard_data}{max_wind_str}))
  2839. {
  2840. readingsBeginUpdate($device);
  2841. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{date_max_wind_str});
  2842. readingsBulkUpdate( $device, "windstrength_max", $devicedata->{dashboard_data}{max_wind_str}, 1 );
  2843. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{date_max_wind_str});
  2844. readingsEndUpdate($device,1);
  2845. }
  2846. if(defined($devicedata->{dashboard_data}{max_wind_angle}))
  2847. {
  2848. readingsBeginUpdate($device);
  2849. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{date_max_wind_str});
  2850. readingsBulkUpdate( $device, "windangle_max", $devicedata->{dashboard_data}{max_wind_angle}, 1 );
  2851. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{date_max_wind_str});
  2852. readingsEndUpdate($device,1);
  2853. }
  2854. if(defined($devicedata->{dashboard_data}{health_idx}) && $devicedata->{type} ne "NHC")
  2855. {
  2856. readingsBeginUpdate($device);
  2857. $device->{".updateTimestamp"} = FmtDateTime($devicedata->{dashboard_data}{health_idx});
  2858. readingsBulkUpdate( $device, "health_idx", $devicedata->{dashboard_data}{health_idx}, 1 );
  2859. $device->{CHANGETIME}[0] = FmtDateTime($devicedata->{dashboard_data}{health_idx});
  2860. readingsEndUpdate($device,1);
  2861. }
  2862. $device->{co2_calibrating} = $devicedata->{co2_calibrating} if(defined($devicedata->{co2_calibrating}));
  2863. $device->{last_status_store} = FmtDateTime($devicedata->{last_status_store}) if(defined($devicedata->{last_status_store}));
  2864. $device->{helper}{last_status_store} = $devicedata->{last_status_store} if(defined($devicedata->{last_status_store}) && $devicedata->{last_status_store} > $device->{helper}{last_status_store});
  2865. $device->{last_message} = FmtDateTime($devicedata->{last_message}) if(defined($devicedata->{last_message}));
  2866. $device->{last_seen} = FmtDateTime($devicedata->{last_seen}) if(defined($devicedata->{last_seen}));
  2867. $device->{wifi_status} = $devicedata->{wifi_status} if(defined($devicedata->{wifi_status}));
  2868. $device->{rf_status} = $devicedata->{rf_status} if(defined($devicedata->{rf_status}));
  2869. #$device->{battery_percent} = $devicedata->{battery_percent} if(defined($devicedata->{battery_percent}));
  2870. $device->{battery_vp} = $devicedata->{battery_vp} if(defined($devicedata->{battery_vp}));
  2871. readingsSingleUpdate($device, "battery", ($devicedata->{battery_percent} > 20) ? "ok" : "low", 1) if(defined($devicedata->{battery_percent}));
  2872. readingsSingleUpdate($device, "battery_percent", $devicedata->{battery_percent}, 1) if(defined($devicedata->{battery_percent}));
  2873. if(defined($devicedata->{modules}))
  2874. {
  2875. foreach my $moduledata ( @{$devicedata->{modules}})
  2876. {
  2877. #Log3 $name, 5, "$name: module "."M$moduledata->{_id} ".Dumper($moduledata);
  2878. my $module = $modules{$hash->{TYPE}}{defptr}{"M$moduledata->{_id}"};
  2879. next if (!defined($module));
  2880. if(defined($moduledata->{dashboard_data}{AbsolutePressure}))
  2881. {
  2882. readingsBeginUpdate($module);
  2883. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2884. readingsBulkUpdate( $module, "pressure_abs", $moduledata->{dashboard_data}{AbsolutePressure}, 1 );
  2885. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2886. readingsEndUpdate($module,1);
  2887. }
  2888. if(defined($moduledata->{dashboard_data}{pressure_trend}))
  2889. {
  2890. readingsBeginUpdate($module);
  2891. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2892. readingsBulkUpdate( $module, "pressure_trend", $moduledata->{dashboard_data}{pressure_trend}, 1 );
  2893. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2894. readingsEndUpdate($module,1);
  2895. }
  2896. if(defined($moduledata->{dashboard_data}{temp_trend}))
  2897. {
  2898. readingsBeginUpdate($module);
  2899. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2900. readingsBulkUpdate( $module, "temp_trend", $moduledata->{dashboard_data}{temp_trend}, 1 );
  2901. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2902. readingsEndUpdate($module,1);
  2903. }
  2904. if(defined($moduledata->{dashboard_data}{max_temp}) && $moduledata->{type} ne "NAModule2")
  2905. {
  2906. readingsBeginUpdate($module);
  2907. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{date_max_temp});
  2908. readingsBulkUpdate( $module, "temp_max", $moduledata->{dashboard_data}{max_temp}, 1 );
  2909. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{date_max_temp});
  2910. readingsEndUpdate($module,1);
  2911. }
  2912. if(defined($moduledata->{dashboard_data}{min_temp}) && $moduledata->{type} ne "NAModule2")
  2913. {
  2914. readingsBeginUpdate($module);
  2915. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{date_min_temp});
  2916. readingsBulkUpdate( $module, "temp_min", $moduledata->{dashboard_data}{min_temp}, 1 );
  2917. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{date_min_temp});
  2918. readingsEndUpdate($module,1);
  2919. }
  2920. if(defined($moduledata->{dashboard_data}{sum_rain_1}))
  2921. {
  2922. readingsBeginUpdate($module);
  2923. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2924. readingsBulkUpdate( $module, "rain_hour", $moduledata->{dashboard_data}{sum_rain_1}, 1 );
  2925. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2926. readingsEndUpdate($module,1);
  2927. }
  2928. if(defined($moduledata->{dashboard_data}{sum_rain_24}))
  2929. {
  2930. my $rain_day = ReadingsVal($module->{NAME},"rain_day",0);
  2931. if($moduledata->{dashboard_data}{sum_rain_24} < $rain_day)
  2932. {
  2933. my $rain_total = ReadingsVal($module->{NAME},"rain_total",0);
  2934. $rain_total += $rain_day;
  2935. readingsSingleUpdate($module,"rain_total",$rain_total,1);
  2936. Log3 $name, 1, $module->{NAME}.":_added rain ".$rain_day." (to ".$rain_total.")";
  2937. }
  2938. readingsBeginUpdate($module);
  2939. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2940. readingsBulkUpdate( $module, "rain_day", $moduledata->{dashboard_data}{sum_rain_24}, 1 );
  2941. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{time_utc});
  2942. readingsEndUpdate($module,1);
  2943. }
  2944. if(defined($moduledata->{dashboard_data}{max_wind_str}))
  2945. {
  2946. readingsBeginUpdate($module);
  2947. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{date_max_wind_str});
  2948. readingsBulkUpdate( $module, "windstrength_max", $moduledata->{dashboard_data}{max_wind_str}, 1 );
  2949. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{date_max_wind_str});
  2950. readingsEndUpdate($module,1);
  2951. }
  2952. if(defined($moduledata->{dashboard_data}{max_wind_angle}))
  2953. {
  2954. readingsBeginUpdate($module);
  2955. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{dashboard_data}{date_max_wind_str});
  2956. readingsBulkUpdate( $module, "windangle_max", $moduledata->{dashboard_data}{max_wind_angle}, 1 );
  2957. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{dashboard_data}{date_max_wind_str});
  2958. readingsEndUpdate($module,1);
  2959. }
  2960. $module->{co2_calibrating} = $moduledata->{co2_calibrating} if(defined($moduledata->{co2_calibrating}));
  2961. $module->{last_status_store} = FmtDateTime($moduledata->{last_status_store}) if(defined($moduledata->{last_status_store}));
  2962. $module->{helper}{last_status_store} = $moduledata->{last_status_store} if(defined($moduledata->{last_status_store}) && $moduledata->{last_status_store} > $module->{helper}{last_status_store});
  2963. $module->{last_message} = FmtDateTime($moduledata->{last_message}) if(defined($moduledata->{last_message}));
  2964. $module->{last_seen} = FmtDateTime($moduledata->{last_seen}) if(defined($moduledata->{last_seen}));
  2965. $module->{wifi_status} = $moduledata->{wifi_status} if(defined($moduledata->{wifi_status}));
  2966. $module->{rf_status} = $moduledata->{rf_status} if(defined($moduledata->{rf_status}));
  2967. #$module->{battery_percent} = $moduledata->{battery_percent} if(defined($moduledata->{battery_percent}));
  2968. $module->{battery_vp} = $moduledata->{battery_vp} if(defined($moduledata->{battery_vp}));
  2969. readingsSingleUpdate($module, "battery", ($moduledata->{battery_percent} > 20) ? "ok" : "low", 1) if(defined($moduledata->{battery_percent}));
  2970. readingsSingleUpdate($module, "battery_percent", $moduledata->{battery_percent}, 1) if(defined($moduledata->{battery_percent}));
  2971. }#foreach module
  2972. }#defined modules
  2973. }#foreach devices
  2974. }#ok
  2975. }#json
  2976. else
  2977. {
  2978. $hash->{status} = "error";
  2979. }
  2980. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  2981. return undef;
  2982. }
  2983. sub
  2984. netatmo_parseForecast($$)
  2985. {
  2986. my($hash, $json) = @_;
  2987. my $name = $hash->{NAME};
  2988. Log3 $name, 4, "$name: parseForecast";
  2989. if( $json )
  2990. {
  2991. Log3 $name, 5, "$name: ".Dumper($json);
  2992. $hash->{status} = $json->{status};
  2993. $hash->{status} = $json->{error}{message} if( $json->{error} );
  2994. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  2995. if( $hash->{status} eq "ok" )
  2996. {
  2997. #$hash->{STATE} = "Connected";
  2998. my $datatime = time;
  2999. my $forecasttime = time;
  3000. $hash->{stationname} = encode_utf8($json->{body}{stationname}) if(defined($json->{body}{stationname}));
  3001. $hash->{city} = encode_utf8($json->{body}{cityname}) if(defined($json->{body}{cityname}));
  3002. if(defined($json->{body}{current_temp_time}))
  3003. {
  3004. $hash->{time_data} = FmtDateTime($json->{body}{current_temp_time});
  3005. $datatime = $json->{body}{current_temp_time};
  3006. }
  3007. if(defined($json->{body}{time_current_symbol}))
  3008. {
  3009. $hash->{time_forecast} = FmtDateTime($json->{body}{time_current_symbol});
  3010. $forecasttime = $json->{body}{time_current_symbol};
  3011. }
  3012. return undef if($datatime <= $lastupdate);
  3013. readingsSingleUpdate($hash, ".lastupdate", $datatime, 0);
  3014. if($json->{body}{airqdata})
  3015. {
  3016. if(defined($json->{body}{airqdata}{data}))
  3017. {
  3018. #CommandDeleteReading( undef, "$hash->{NAME} air_.*" );
  3019. foreach my $airdata ( @{$json->{body}{airqdata}{data}})
  3020. {
  3021. my $timestamp = $airdata->{beg_time};
  3022. foreach my $airvalue ( @{$airdata->{value}})
  3023. {
  3024. readingsBeginUpdate($hash);
  3025. $hash->{".updateTimestamp"} = FmtDateTime($timestamp);
  3026. readingsBulkUpdate( $hash, "air_".@{$airvalue}[1], @{$airvalue}[0], 1 );
  3027. $hash->{CHANGETIME}[0] = FmtDateTime($timestamp);
  3028. readingsEndUpdate($hash,1);
  3029. next if(!defined(@{$airvalue}[2]));
  3030. readingsBeginUpdate($hash);
  3031. $hash->{".updateTimestamp"} = FmtDateTime($timestamp);
  3032. readingsBulkUpdate( $hash, "air_".@{$airvalue}[1]."_message", @{$airvalue}[2], 1 );
  3033. $hash->{CHANGETIME}[0] = FmtDateTime($timestamp);
  3034. readingsEndUpdate($hash,1);
  3035. }
  3036. }
  3037. }
  3038. }#airqdata
  3039. if(defined($json->{body}{current_windgust}))
  3040. {
  3041. readingsBeginUpdate($hash);
  3042. $hash->{".updateTimestamp"} = FmtDateTime($datatime);
  3043. readingsBulkUpdate( $hash, "windgust", $json->{body}{current_windgust}, 1 );
  3044. $hash->{CHANGETIME}[0] = FmtDateTime($datatime);
  3045. readingsEndUpdate($hash,1);
  3046. }
  3047. if(defined($json->{body}{current_windstrength}))
  3048. {
  3049. readingsBeginUpdate($hash);
  3050. $hash->{".updateTimestamp"} = FmtDateTime($datatime);
  3051. readingsBulkUpdate( $hash, "windstrength", $json->{body}{current_windstrength}, 1 );
  3052. $hash->{CHANGETIME}[0] = FmtDateTime($datatime);
  3053. readingsEndUpdate($hash,1);
  3054. }
  3055. if(defined($json->{body}{current_temp}))
  3056. {
  3057. readingsBeginUpdate($hash);
  3058. $hash->{".updateTimestamp"} = FmtDateTime($datatime);
  3059. readingsBulkUpdate( $hash, "temperature", $json->{body}{current_temp}, 1 );
  3060. $hash->{CHANGETIME}[0] = FmtDateTime($datatime);
  3061. readingsEndUpdate($hash,1);
  3062. }
  3063. if(defined($json->{body}{current_symbol}))
  3064. {
  3065. readingsBeginUpdate($hash);
  3066. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3067. readingsBulkUpdate( $hash, "symbol", $json->{body}{current_symbol}, 1 );
  3068. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3069. readingsEndUpdate($hash,1);
  3070. }
  3071. if(defined($json->{body}{forecastDays}))
  3072. {
  3073. my $i = 0;
  3074. foreach my $forecastdata ( @{$json->{body}{forecastDays}})
  3075. {
  3076. next if(ref($forecastdata) ne "HASH");
  3077. if(defined($forecastdata->{rain}))
  3078. {
  3079. readingsBeginUpdate($hash);
  3080. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3081. readingsBulkUpdate( $hash, "fc".$i."_rain", $forecastdata->{rain}, 1 );
  3082. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3083. readingsEndUpdate($hash,1);
  3084. }
  3085. if(defined($forecastdata->{max_temp}))
  3086. {
  3087. readingsBeginUpdate($hash);
  3088. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3089. readingsBulkUpdate( $hash, "fc".$i."_temp_max", $forecastdata->{max_temp}, 1 );
  3090. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3091. readingsEndUpdate($hash,1);
  3092. }
  3093. if(defined($forecastdata->{min_temp}))
  3094. {
  3095. readingsBeginUpdate($hash);
  3096. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3097. readingsBulkUpdate( $hash, "fc".$i."_temp_min", $forecastdata->{min_temp}, 1 );
  3098. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3099. readingsEndUpdate($hash,1);
  3100. }
  3101. if(defined($forecastdata->{windangle}))
  3102. {
  3103. readingsBeginUpdate($hash);
  3104. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3105. readingsBulkUpdate( $hash, "fc".$i."_windangle", $forecastdata->{windangle}, 1 );
  3106. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3107. readingsEndUpdate($hash,1);
  3108. }
  3109. if(defined($forecastdata->{wind_direction}))
  3110. {
  3111. readingsBeginUpdate($hash);
  3112. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3113. readingsBulkUpdate( $hash, "fc".$i."_wind_direction", $forecastdata->{wind_direction}, 1 );
  3114. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3115. readingsEndUpdate($hash,1);
  3116. }
  3117. if(defined($forecastdata->{windgust}))
  3118. {
  3119. readingsBeginUpdate($hash);
  3120. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3121. readingsBulkUpdate( $hash, "fc".$i."_windgust", $forecastdata->{windgust}, 1 );
  3122. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3123. readingsEndUpdate($hash,1);
  3124. }
  3125. if(defined($forecastdata->{sun}))
  3126. {
  3127. readingsBeginUpdate($hash);
  3128. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3129. readingsBulkUpdate( $hash, "fc".$i."_sun", $forecastdata->{sun}, 1 );
  3130. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3131. readingsEndUpdate($hash,1);
  3132. }
  3133. if(defined($forecastdata->{uv}))
  3134. {
  3135. readingsBeginUpdate($hash);
  3136. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3137. readingsBulkUpdate( $hash, "fc".$i."_uv", $forecastdata->{uv}, 1 );
  3138. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3139. readingsEndUpdate($hash,1);
  3140. }
  3141. if(defined($forecastdata->{sunset}))
  3142. {
  3143. readingsBeginUpdate($hash);
  3144. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3145. readingsBulkUpdate( $hash, "fc".$i."_sunset", FmtDateTime($forecastdata->{sunset}), 1 );
  3146. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3147. readingsEndUpdate($hash,1);
  3148. }
  3149. if(defined($forecastdata->{sunrise}))
  3150. {
  3151. readingsBeginUpdate($hash);
  3152. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3153. readingsBulkUpdate( $hash, "fc".$i."_sunrise", FmtDateTime($forecastdata->{sunrise}), 1 );
  3154. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3155. readingsEndUpdate($hash,1);
  3156. }
  3157. if(defined($forecastdata->{day_locale}))
  3158. {
  3159. readingsBeginUpdate($hash);
  3160. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3161. readingsBulkUpdate( $hash, "fc".$i."_day", encode_utf8($forecastdata->{day_locale}), 1 );
  3162. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3163. readingsEndUpdate($hash,1);
  3164. }
  3165. if(defined($forecastdata->{weather_symbol_day}))
  3166. {
  3167. readingsBeginUpdate($hash);
  3168. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3169. readingsBulkUpdate( $hash, "fc".$i."_symbol_day", $forecastdata->{weather_symbol_day}, 1 );
  3170. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3171. readingsEndUpdate($hash,1);
  3172. }
  3173. if(defined($forecastdata->{weather_symbol_night}))
  3174. {
  3175. readingsBeginUpdate($hash);
  3176. $hash->{".updateTimestamp"} = FmtDateTime($forecasttime);
  3177. readingsBulkUpdate( $hash, "fc".$i."_symbol_night", $forecastdata->{weather_symbol_night}, 1 );
  3178. $hash->{CHANGETIME}[0] = FmtDateTime($forecasttime);
  3179. readingsEndUpdate($hash,1);
  3180. }
  3181. $i++;
  3182. }#foreach forecast
  3183. }#defined forecastdays
  3184. }#ok
  3185. }#json
  3186. else
  3187. {
  3188. $hash->{status} = "error";
  3189. }
  3190. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3191. return undef;
  3192. }
  3193. sub
  3194. netatmo_parseHomeReadings($$;$)
  3195. {
  3196. my($hash, $json) = @_;
  3197. my $name = $hash->{NAME};
  3198. Log3 $name, 4, "$name: parseHomeReadings";
  3199. if( $json ) {
  3200. Log3 $name, 5, "$name: ".Dumper($json);
  3201. $hash->{status} = "ok";
  3202. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3203. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  3204. my @r = ();
  3205. my $readings = \@r;
  3206. $readings = $hash->{readings} if( defined($hash->{readings}) );
  3207. if( $hash->{status} eq "ok" )
  3208. {
  3209. #$hash->{STATE} = "Connected";
  3210. return undef if(!defined($json->{body}{homes}));
  3211. foreach my $homedata ( @{$json->{body}{homes}})
  3212. {
  3213. next if($homedata->{id} ne $hash->{Home});
  3214. readingsSingleUpdate($hash, "name", encode_utf8($homedata->{name}), 1) if(defined($homedata->{name}));
  3215. readingsSingleUpdate($hash, "presence_record_humans", $homedata->{presence_record_humans}, 1) if(defined($homedata->{presence_record_humans}));
  3216. readingsSingleUpdate($hash, "presence_record_vehicles", $homedata->{presence_record_vehicles}, 1) if(defined($homedata->{presence_record_vehicles}));
  3217. readingsSingleUpdate($hash, "presence_record_animals", $homedata->{presence_record_animals}, 1) if(defined($homedata->{presence_record_animals}));
  3218. readingsSingleUpdate($hash, "presence_record_movements", $homedata->{presence_record_movements}, 1) if(defined($homedata->{presence_record_movements}));
  3219. readingsSingleUpdate($hash, "presence_record_alarms", $homedata->{presence_record_alarms}, 1) if(defined($homedata->{presence_record_alarms}));
  3220. readingsSingleUpdate($hash, "gone_after", sprintf("%02d",(int($homedata->{gone_after}/60)/60)).":".sprintf("%02d",(int($homedata->{gone_after}/60)%60)), 1) if(defined($homedata->{gone_after}));
  3221. readingsSingleUpdate($hash, "smart_notifs", ($homedata->{smart_notifs} eq "1")?"on":"off", 1) if(defined($homedata->{smart_notifs}));
  3222. readingsSingleUpdate($hash, "presence_enable_notify_from_to", $homedata->{presence_enable_notify_from_to}, 1) if(defined($homedata->{presence_enable_notify_from_to}));
  3223. readingsSingleUpdate($hash, "presence_notify_from", sprintf("%02d",(int($homedata->{presence_notify_from}/60)/60)).":".sprintf("%02d",(int($homedata->{presence_notify_from}/60)%60)), 1) if(defined($homedata->{presence_notify_from}));
  3224. readingsSingleUpdate($hash, "presence_notify_to", sprintf("%02d",(int($homedata->{presence_notify_to}/60)/60)).":".sprintf("%02d",(int($homedata->{presence_notify_to}/60)%60)), 1) if(defined($homedata->{presence_notify_to}));
  3225. readingsSingleUpdate($hash, "notify_unknowns", $homedata->{notify_unknowns}, 1) if(defined($homedata->{notify_unknowns}));
  3226. readingsSingleUpdate($hash, "notify_movements", $homedata->{notify_movements}, 1) if(defined($homedata->{notify_movements}));
  3227. readingsSingleUpdate($hash, "record_alarms", $homedata->{record_alarms}, 1) if(defined($homedata->{record_alarms}));
  3228. readingsSingleUpdate($hash, "record_movements", $homedata->{record_movements}, 1) if(defined($homedata->{record_movements}));
  3229. if( $homedata->{place} ) {
  3230. $hash->{country} = encode_utf8($homedata->{place}{country}) if(defined($homedata->{place}{country}));
  3231. $hash->{bssid} = $homedata->{place}{bssid} if(defined($homedata->{place}{bssid}));
  3232. $hash->{altitude} = $homedata->{place}{altitude} if(defined($homedata->{place}{altitude}));
  3233. $hash->{city} = encode_utf8($homedata->{place}{geoip_city}) if(defined($homedata->{place}{geoip_city}));
  3234. $hash->{city} = encode_utf8($homedata->{place}{city}) if(defined($homedata->{place}{city}));;
  3235. $hash->{location} = $homedata->{place}{location}[1] .",". $homedata->{place}{location}[0] if(defined($homedata->{place}{location}));
  3236. $hash->{timezone} = encode_utf8($homedata->{place}{timezone}) if(defined($homedata->{place}{timezone}));
  3237. }
  3238. if(defined($homedata->{persons}))
  3239. {
  3240. foreach my $persondata ( @{$homedata->{persons}})
  3241. {
  3242. my $person = $modules{$hash->{TYPE}}{defptr}{"P$persondata->{id}"};
  3243. next if (!defined($person));
  3244. readingsSingleUpdate($person, "pseudo", encode_utf8($persondata->{pseudo}), 1) if(defined($persondata->{pseudo}));
  3245. readingsSingleUpdate($person, "last_seen", FmtDateTime($persondata->{last_seen}), 1) if(defined($persondata->{last_seen}));
  3246. readingsSingleUpdate($person, "out_of_sight", $persondata->{out_of_sight}, 1) if(defined($persondata->{out_of_sight}));
  3247. readingsSingleUpdate($person, "status", (($persondata->{out_of_sight} eq "0") ? "home" : "away"), 1) if(defined($persondata->{out_of_sight}));
  3248. #$person->{STATE} = ($persondata->{out_of_sight} eq "0") ? "home" : "away";
  3249. readingsSingleUpdate($person, "face_id", $persondata->{face}{id}, 0) if(defined($persondata->{face}{id}));
  3250. readingsSingleUpdate($person, "face_key", $persondata->{face}{key}, 0) if(defined($persondata->{face}{key}));
  3251. readingsSingleUpdate($person, "face_version", $persondata->{face}{version}, 1) if(defined($persondata->{face}{version}));
  3252. }
  3253. }
  3254. if(defined($homedata->{cameras}))
  3255. {
  3256. foreach my $cameradata ( @{$homedata->{cameras}})
  3257. {
  3258. my $camera = $modules{$hash->{TYPE}}{defptr}{"C$cameradata->{id}"};
  3259. next if (!defined($camera));
  3260. readingsSingleUpdate($camera, "name", encode_utf8($cameradata->{name}), 1) if(defined($cameradata->{name}));
  3261. readingsSingleUpdate($camera, "status", $cameradata->{status}, 1) if(defined($cameradata->{status}));
  3262. #$camera->{STATE} = ($cameradata->{status} eq "on") ? "online" : "offline";
  3263. readingsSingleUpdate($camera, "sd_status", $cameradata->{sd_status}, 0) if(defined($cameradata->{sd_status}));
  3264. readingsSingleUpdate($camera, "alim_status", $cameradata->{alim_status}, 0) if(defined($cameradata->{alim_status}));
  3265. readingsSingleUpdate($camera, "is_local", $cameradata->{is_local}, 1) if(defined($cameradata->{is_local}));
  3266. readingsSingleUpdate($camera, "vpn_url", $cameradata->{vpn_url}, 1) if(defined($cameradata->{vpn_url}));
  3267. CommandDeleteReading( undef, "$camera->{NAME} vpn_url" ) if(!defined($cameradata->{vpn_url}));
  3268. CommandDeleteReading( undef, "$camera->{NAME} local_url" ) if(!defined($cameradata->{vpn_url}));
  3269. readingsSingleUpdate($camera, "light_mode", $cameradata->{light_mode_status}, 1) if(defined($cameradata->{light_mode_status}));
  3270. readingsSingleUpdate($camera, "timelapse_available", $cameradata->{timelapse_available}, 0) if(defined($cameradata->{timelapse_available}));
  3271. delete($camera->{pin}) if($cameradata->{status} eq "on");
  3272. $camera->{model} = $cameradata->{type} if(defined($cameradata->{type}));
  3273. $camera->{firmware} = $cameradata->{firmware} if(defined($cameradata->{firmware}));
  3274. foreach my $tagdata ( @{$cameradata->{modules}})
  3275. {
  3276. my $tag = $modules{$hash->{TYPE}}{defptr}{"G$tagdata->{id}"};
  3277. next if (!defined($tag));
  3278. readingsSingleUpdate($tag, "name", encode_utf8($tagdata->{name}), 1) if(defined($tagdata->{name}));
  3279. readingsSingleUpdate($tag, "status", $tagdata->{status}, 1) if(defined($tagdata->{status}));
  3280. readingsSingleUpdate($tag, "category", $tagdata->{category}, 1) if(defined($tagdata->{category}));
  3281. $tag->{model} = $tagdata->{type};
  3282. $tag->{last_activity} = FmtDateTime($tagdata->{last_activity}) if(defined($tagdata->{last_activity}));
  3283. $tag->{last_seen} = FmtDateTime($tagdata->{last_seen}) if(defined($tagdata->{last_seen}));
  3284. $tag->{rf} = $tagdata->{rf};
  3285. $tag->{notify_rule} = $tagdata->{notify_rule};
  3286. $tag->{notify_rule} = $tagdata->{notify_rule};
  3287. readingsSingleUpdate($tag, "battery", ($tagdata->{battery_percent} > 20) ? "ok" : "low", 1) if(defined($tagdata->{battery_percent}));
  3288. readingsSingleUpdate($tag, "battery_percent", $tagdata->{battery_percent}, 1) if(defined($tagdata->{battery_percent}));
  3289. }
  3290. }
  3291. }
  3292. if(defined($homedata->{events}))
  3293. {
  3294. my @eventslist = @{$homedata->{events}};
  3295. my $eventdata;
  3296. while ($eventdata = pop( @eventslist ))
  3297. {
  3298. $eventdata->{time} = time() if(!defined($eventdata->{time}));
  3299. next if($eventdata->{time} <= $lastupdate);
  3300. readingsSingleUpdate($hash, ".lastupdate", $eventdata->{time}, 0);
  3301. Log3 $name, 4, "$name: new event: ".FmtDateTime($eventdata->{time});
  3302. if(defined($eventdata->{event_list}))
  3303. {
  3304. my @singleeventslist = @{$eventdata->{event_list}};
  3305. my $singleeventdata;
  3306. while ($singleeventdata = pop( @singleeventslist ))
  3307. {
  3308. if(defined($singleeventdata->{message}))
  3309. {
  3310. my $eventmessage = $singleeventdata->{message};
  3311. $eventmessage = "-" if(!defined($singleeventdata->{message}));
  3312. $eventmessage =~ s/<\/b>//g;
  3313. $eventmessage =~ s/<b>//g;
  3314. readingsBeginUpdate($hash);
  3315. $hash->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3316. readingsBulkUpdate( $hash, "event", encode_utf8($eventmessage), 1 );
  3317. $hash->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3318. readingsEndUpdate($hash,1);
  3319. }
  3320. if(defined($singleeventdata->{snapshot}{key}))
  3321. {
  3322. readingsBeginUpdate($hash);
  3323. $hash->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3324. readingsBulkUpdate( $hash, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$singleeventdata->{snapshot}{id}."&key=".$singleeventdata->{snapshot}{key}, 1 );
  3325. $hash->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3326. readingsEndUpdate($hash,1);
  3327. }
  3328. }
  3329. }
  3330. else
  3331. {
  3332. my $eventmessage = $eventdata->{message};
  3333. $eventmessage = "-" if(!defined($eventdata->{message}));
  3334. $eventmessage =~ s/<\/b>//g;
  3335. $eventmessage =~ s/<b>//g;
  3336. if(defined($eventdata->{message}))
  3337. {
  3338. readingsBeginUpdate($hash);
  3339. $hash->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3340. readingsBulkUpdate( $hash, "event", encode_utf8($eventmessage), 1 );
  3341. $hash->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3342. readingsEndUpdate($hash,1);
  3343. }
  3344. if(defined($eventdata->{snapshot}))
  3345. {
  3346. readingsBeginUpdate($hash);
  3347. $hash->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3348. readingsBulkUpdate( $hash, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$eventdata->{snapshot}{id}."&key=".$eventdata->{snapshot}{key}, 1 );
  3349. $hash->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3350. readingsEndUpdate($hash,1);
  3351. }
  3352. }
  3353. my $camera = $modules{$hash->{TYPE}}{defptr}{"C$eventdata->{camera_id}"};
  3354. my $tag = $modules{$hash->{TYPE}}{defptr}{"G$eventdata->{module_id}"} if(defined($eventdata->{module_id}));
  3355. my $person = $modules{$hash->{TYPE}}{defptr}{"P$eventdata->{person_id}"} if(defined($eventdata->{person_id}));
  3356. if (defined($camera))
  3357. {
  3358. my $lastupdate = ReadingsVal( $camera->{NAME}, ".lastupdate", 0 );
  3359. next if($eventdata->{time} <= $lastupdate);
  3360. readingsSingleUpdate($camera, ".lastupdate", $eventdata->{time}, 0);
  3361. if(defined($eventdata->{event_list}))
  3362. {
  3363. my @singleeventslist = @{$eventdata->{event_list}};
  3364. my $singleeventdata;
  3365. while ($singleeventdata = pop( @singleeventslist ))
  3366. {
  3367. if(defined($singleeventdata->{message}))
  3368. {
  3369. my $cameraname = ReadingsVal( $camera->{NAME}, "name", "Welcome" );
  3370. my $eventmessage = $singleeventdata->{message};
  3371. $eventmessage =~ s/<b>//g;
  3372. $eventmessage =~ s/<\/b>//g;
  3373. $eventmessage =~ s/$cameraname: //g;
  3374. $eventmessage =~ s/$cameraname /Camera /g;
  3375. readingsBeginUpdate($camera);
  3376. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3377. readingsBulkUpdate( $camera, "event", encode_utf8($eventmessage), 1 );
  3378. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3379. readingsEndUpdate($camera,1);
  3380. }
  3381. if(defined($singleeventdata->{time}))
  3382. {
  3383. readingsBeginUpdate($camera);
  3384. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3385. readingsBulkUpdate( $camera, "event_time", FmtDateTime($singleeventdata->{time}), 1 );
  3386. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3387. readingsEndUpdate($camera,1);
  3388. }
  3389. if(defined($singleeventdata->{type}))
  3390. {
  3391. readingsBeginUpdate($camera);
  3392. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3393. readingsBulkUpdate( $camera, "event_type", $singleeventdata->{type}, 1 );
  3394. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3395. readingsEndUpdate($camera,1);
  3396. }
  3397. if(defined($singleeventdata->{id}))
  3398. {
  3399. readingsBeginUpdate($camera);
  3400. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3401. readingsBulkUpdate( $camera, "event_id", $singleeventdata->{id}, 1 );
  3402. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3403. readingsEndUpdate($camera,1);
  3404. }
  3405. if(defined($singleeventdata->{snapshot}{filename}))
  3406. {
  3407. readingsBeginUpdate($camera);
  3408. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3409. readingsBulkUpdate( $camera, "filename", $singleeventdata->{snapshot}{filename}, 1 );
  3410. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3411. readingsEndUpdate($camera,1);
  3412. }
  3413. if(defined($singleeventdata->{snapshot}{key}))
  3414. {
  3415. readingsBeginUpdate($camera);
  3416. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3417. readingsBulkUpdate( $camera, "snapshot", $singleeventdata->{snapshot}{id}."|".$singleeventdata->{snapshot}{key}, 1 );
  3418. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3419. readingsEndUpdate($camera,1);
  3420. }
  3421. if(defined($singleeventdata->{snapshot}{key}))
  3422. {
  3423. readingsBeginUpdate($camera);
  3424. $camera->{".updateTimestamp"} = FmtDateTime($singleeventdata->{time});
  3425. readingsBulkUpdate( $camera, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$singleeventdata->{snapshot}{id}."&key=".$singleeventdata->{snapshot}{key}, 1 );
  3426. $camera->{CHANGETIME}[0] = FmtDateTime($singleeventdata->{time});
  3427. readingsEndUpdate($camera,1);
  3428. }
  3429. }
  3430. }
  3431. else
  3432. {
  3433. if(defined($eventdata->{message}))
  3434. {
  3435. my $cameraname = ReadingsVal( $camera->{NAME}, "name", "Welcome" );
  3436. my $eventmessage = $eventdata->{message};
  3437. $eventmessage =~ s/<b>//g;
  3438. $eventmessage =~ s/<\/b>//g;
  3439. $eventmessage =~ s/$cameraname: //g;
  3440. $eventmessage =~ s/$cameraname /Camera /g;
  3441. readingsBeginUpdate($camera);
  3442. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3443. readingsBulkUpdate( $camera, "event", encode_utf8($eventmessage), 1 );
  3444. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3445. readingsEndUpdate($camera,1);
  3446. }
  3447. if(defined($eventdata->{time}))
  3448. {
  3449. readingsBeginUpdate($camera);
  3450. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3451. readingsBulkUpdate( $camera, "event_time", FmtDateTime($eventdata->{time}), 1 );
  3452. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3453. readingsEndUpdate($camera,1);
  3454. }
  3455. if(defined($eventdata->{type}))
  3456. {
  3457. readingsBeginUpdate($camera);
  3458. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3459. readingsBulkUpdate( $camera, "event_type", $eventdata->{type}, 1 );
  3460. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3461. readingsEndUpdate($camera,1);
  3462. }
  3463. if(defined($eventdata->{id}))
  3464. {
  3465. readingsBeginUpdate($camera);
  3466. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3467. readingsBulkUpdate( $camera, "event_id", $eventdata->{id}, 1 );
  3468. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3469. readingsEndUpdate($camera,1);
  3470. }
  3471. if(defined($person))
  3472. {
  3473. readingsBeginUpdate($camera);
  3474. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3475. readingsBulkUpdate( $camera, "person_seen", ReadingsVal($person->{NAME},"pseudo","Unknown"), 1 );
  3476. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3477. readingsEndUpdate($camera,1);
  3478. }
  3479. if(defined($eventdata->{snapshot}))
  3480. {
  3481. readingsBeginUpdate($camera);
  3482. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3483. readingsBulkUpdate( $camera, "snapshot", $eventdata->{snapshot}{id}."|".$eventdata->{snapshot}{key}, 1 );
  3484. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3485. readingsEndUpdate($camera,1);
  3486. }
  3487. if(defined($eventdata->{snapshot}))
  3488. {
  3489. readingsBeginUpdate($camera);
  3490. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3491. readingsBulkUpdate( $camera, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$eventdata->{snapshot}{id}."&key=".$eventdata->{snapshot}{key}, 1 );
  3492. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3493. readingsEndUpdate($camera,1);
  3494. }
  3495. }
  3496. if(defined($eventdata->{video_status}))
  3497. {
  3498. readingsBeginUpdate($camera);
  3499. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3500. readingsBulkUpdate( $camera, "video_status", $eventdata->{video_status}, 1 );
  3501. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3502. readingsEndUpdate($camera,1);
  3503. }
  3504. if(defined($eventdata->{video_id}))
  3505. {
  3506. readingsBeginUpdate($camera);
  3507. $camera->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3508. readingsBulkUpdate( $camera, "video_id", $eventdata->{video_id}, 1 );
  3509. $camera->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3510. readingsEndUpdate($camera,1);
  3511. }
  3512. }
  3513. if (defined($tag))
  3514. {
  3515. my $lastupdate = ReadingsVal( $tag->{NAME}, ".lastupdate", 0 );
  3516. next if($eventdata->{time} <= $lastupdate);
  3517. readingsSingleUpdate($tag, ".lastupdate", $eventdata->{time}, 0);
  3518. if(defined($eventdata->{message}))
  3519. {
  3520. my $tagname = ReadingsVal( $tag->{NAME}, "name", "Tag" );
  3521. my $eventmessage = $eventdata->{message};
  3522. $eventmessage =~ s/<b>//g;
  3523. $eventmessage =~ s/<\/b>//g;
  3524. $eventmessage =~ s/ by $tagname//g;
  3525. $eventmessage =~ s/$tagname /Tag /g;
  3526. readingsBeginUpdate($tag);
  3527. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3528. readingsBulkUpdate( $tag, "event", encode_utf8($eventmessage), 1 );
  3529. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3530. readingsEndUpdate($tag,1);
  3531. }
  3532. if(defined($eventdata->{time}))
  3533. {
  3534. readingsBeginUpdate($tag);
  3535. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3536. readingsBulkUpdate( $tag, "event_time", FmtDateTime($eventdata->{time}), 1 );
  3537. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3538. readingsEndUpdate($tag,1);
  3539. }
  3540. if(defined($eventdata->{type}))
  3541. {
  3542. readingsBeginUpdate($tag);
  3543. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3544. readingsBulkUpdate( $tag, "event_type", $eventdata->{type}, 1 );
  3545. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3546. readingsEndUpdate($tag,1);
  3547. }
  3548. if(defined($eventdata->{id}))
  3549. {
  3550. readingsBeginUpdate($tag);
  3551. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3552. readingsBulkUpdate( $tag, "event_id", $eventdata->{id}, 1 );
  3553. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3554. readingsEndUpdate($tag,1);
  3555. }
  3556. if(defined($eventdata->{snapshot}))
  3557. {
  3558. readingsBeginUpdate($tag);
  3559. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3560. readingsBulkUpdate( $tag, "snapshot", $eventdata->{snapshot}{id}."|".$eventdata->{snapshot}{key}, 1 );
  3561. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3562. readingsEndUpdate($tag,1);
  3563. }
  3564. if(defined($eventdata->{video_status}))
  3565. {
  3566. readingsBeginUpdate($tag);
  3567. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3568. readingsBulkUpdate( $tag, "video_status", $eventdata->{video_status}, 1 );
  3569. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3570. readingsEndUpdate($tag,1);
  3571. }
  3572. if(defined($eventdata->{video_id}))
  3573. {
  3574. readingsBeginUpdate($tag);
  3575. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3576. readingsBulkUpdate( $tag, "video_id", $eventdata->{video_id}, 1 );
  3577. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3578. readingsEndUpdate($tag,1);
  3579. }
  3580. if(defined($eventdata->{snapshot}))
  3581. {
  3582. readingsBeginUpdate($tag);
  3583. $tag->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3584. readingsBulkUpdate( $tag, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$eventdata->{snapshot}{id}."&key=".$eventdata->{snapshot}{key}, 1 );
  3585. $tag->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3586. readingsEndUpdate($tag,1);
  3587. }
  3588. }
  3589. if (defined($person))
  3590. {
  3591. my $lastupdate = ReadingsVal( $person->{NAME}, ".lastupdate", 0 );
  3592. next if($eventdata->{time} <= $lastupdate);
  3593. readingsSingleUpdate($person, ".lastupdate", $eventdata->{time}, 0);
  3594. readingsSingleUpdate($person, "last_seen", FmtDateTime($eventdata->{time}), 1) if(defined($eventdata->{time}));
  3595. readingsSingleUpdate($person, "last_arrival", FmtDateTime($eventdata->{time}), 1) if(defined($eventdata->{time}) && defined($eventdata->{is_arrival}) && $eventdata->{is_arrival} eq "1");
  3596. if(defined($camera))
  3597. {
  3598. readingsBeginUpdate($person);
  3599. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3600. readingsBulkUpdate( $person, "camera", ReadingsVal($camera->{NAME},"name","Unknown"), 1 );
  3601. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3602. readingsEndUpdate($person,1);
  3603. }
  3604. if(defined($eventdata->{id}))
  3605. {
  3606. readingsBeginUpdate($person);
  3607. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3608. readingsBulkUpdate( $person, "event_id", $eventdata->{id}, 1 );
  3609. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3610. readingsEndUpdate($person,1);
  3611. }
  3612. if(defined($eventdata->{video_status}))
  3613. {
  3614. readingsBeginUpdate($person);
  3615. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3616. readingsBulkUpdate( $person, "video_status", $eventdata->{video_status}, 1 );
  3617. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3618. readingsEndUpdate($person,1);
  3619. }
  3620. if(defined($eventdata->{video_id}))
  3621. {
  3622. readingsBeginUpdate($person);
  3623. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3624. readingsBulkUpdate( $person, "video_id", $eventdata->{video_id}, 1 );
  3625. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3626. readingsEndUpdate($person,1);
  3627. }
  3628. if(defined($eventdata->{snapshot}))
  3629. {
  3630. readingsBeginUpdate($person);
  3631. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3632. readingsBulkUpdate( $person, "snapshot", $eventdata->{snapshot}{id}."|".$eventdata->{snapshot}{key}, 1 );
  3633. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3634. readingsEndUpdate($person,1);
  3635. }
  3636. if(defined($eventdata->{snapshot}))
  3637. {
  3638. readingsBeginUpdate($person);
  3639. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3640. readingsBulkUpdate( $person, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$eventdata->{snapshot}{id}."&key=".$eventdata->{snapshot}{key}, 1 );
  3641. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3642. readingsEndUpdate($person,1);
  3643. }
  3644. }
  3645. }
  3646. }
  3647. my $time = $homedata->{time_server};
  3648. }
  3649. }
  3650. }
  3651. else
  3652. {
  3653. $hash->{status} = "error";
  3654. }
  3655. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3656. }
  3657. sub
  3658. netatmo_refreshHomeSettings($)
  3659. {
  3660. my($hash) = @_;
  3661. my $name = $hash->{NAME};
  3662. InternalTimer(gettimeofday()+5, "netatmo_poll", $hash);
  3663. return undef;
  3664. }
  3665. sub
  3666. netatmo_parseCameraPing($$;$)
  3667. {
  3668. my($hash, $json) = @_;
  3669. my $name = $hash->{NAME};
  3670. Log3 $name, 4, "$name: parseCameraPing";
  3671. if( $json ) {
  3672. Log3 $name, 5, "$name: ".Dumper($json);
  3673. $hash->{status} = $json->{status};
  3674. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3675. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  3676. readingsSingleUpdate($hash, "local_url", $json->{local_url}, 1) if(defined($json->{local_url}));
  3677. CommandDeleteReading( undef, "$hash->{NAME} local_url" ) if(!defined($json->{local_url}));
  3678. }
  3679. else
  3680. {
  3681. $hash->{status} = "error";
  3682. if(ReadingsVal( $name, "status", "ok" ) eq "disconnected"){
  3683. $hash->{status} = "disconnected";
  3684. RemoveInternalTimer($hash);
  3685. }
  3686. }
  3687. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if(defined($hash->{status}) && $hash->{status} ne "no data");
  3688. }
  3689. sub
  3690. netatmo_parseCameraStatus($$;$)
  3691. {
  3692. my($hash, $json) = @_;
  3693. my $name = $hash->{NAME};
  3694. Log3 $name, 4, "$name: parseCameraStatus";
  3695. my $home = $modules{$hash->{TYPE}}{defptr}{"H$hash->{Home}"};
  3696. if( $json ) {
  3697. Log3 $name, 5, "$name: ".Dumper($json);
  3698. $hash->{status} = "ok";
  3699. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3700. InternalTimer( gettimeofday() + 10, "netatmo_pollHome", $home) if($hash->{status} eq "ok" );
  3701. }
  3702. else{
  3703. netatmo_pollHome($home) if($home->{status} !~ /usage/ && $home->{status} !~ /too_many_connections/ && $home->{status} !~ /postponed/);
  3704. }
  3705. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3706. }
  3707. sub
  3708. netatmo_parseCameraConfig($$;$)
  3709. {
  3710. my($hash, $json) = @_;
  3711. my $name = $hash->{NAME};
  3712. Log3 $name, 4, "$name: parseCameraConfig";
  3713. my $home = $modules{$hash->{TYPE}}{defptr}{"H$hash->{Home}"};
  3714. if( $json ) {
  3715. Log3 $name, 5, "$name: ".Dumper($json);
  3716. $hash->{status} = "ok";
  3717. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3718. return undef if($hash->{status} ne "ok");
  3719. readingsBeginUpdate($hash);
  3720. readingsBulkUpdate( $hash, "intensity", $json->{intensity}, 1 ) if( $json->{intensity} );
  3721. readingsBulkUpdate( $hash, "light_mode", $json->{mode}, 1 ) if( $json->{mode} );
  3722. readingsBulkUpdate( $hash, "night_always", ($json->{night}{always}?"true":"false"), 1 ) if( $json->{night} );
  3723. readingsBulkUpdate( $hash, "night_person", ($json->{night}{person}?"true":"false"), 1 ) if( $json->{night} );
  3724. readingsBulkUpdate( $hash, "night_vehicle", ($json->{night}{vehicle}?"true":"false"), 1 ) if( $json->{night} );
  3725. readingsBulkUpdate( $hash, "night_animal", ($json->{night}{animal}?"true":"false"), 1 ) if( $json->{night} );
  3726. readingsBulkUpdate( $hash, "night_movement", ($json->{night}{movement}?"true":"false"), 1 ) if( $json->{night} );
  3727. readingsEndUpdate( $hash, 1);
  3728. InternalTimer( gettimeofday() + 10, "netatmo_pollHome", $home) if($hash->{status} eq "ok" );
  3729. }
  3730. else{
  3731. netatmo_pollHome($home) if($home->{status} !~ /usage/ && $home->{status} !~ /too_many_connections/ && $home->{status} !~ /postponed/);
  3732. }
  3733. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3734. }
  3735. sub
  3736. netatmo_parseTagStatus($$;$)
  3737. {
  3738. my($hash, $json) = @_;
  3739. my $name = $hash->{NAME};
  3740. Log3 $name, 4, "$name: parseTagStatus";
  3741. if( $json ) {
  3742. Log3 $name, 5, "$name: ".Dumper($json);
  3743. $hash->{status} = $json->{status};
  3744. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3745. readingsSingleUpdate($hash, "status", "calibrating", 1) if($hash->{status} eq "ok");
  3746. }
  3747. else
  3748. {
  3749. $hash->{status} = "error";
  3750. }
  3751. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3752. }
  3753. sub
  3754. netatmo_parseCameraVideo($$;$)
  3755. {
  3756. my($hash, $json) = @_;
  3757. my $name = $hash->{NAME};
  3758. Log3 $name, 4, "$name: parseCameraVideo";
  3759. if( $json ) {
  3760. Log3 $name, 5, "$name: ".Dumper($json);
  3761. $hash->{status} = $json->{status};
  3762. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3763. return undef if($hash->{status} ne "ok");
  3764. return undef if($hash->{status} ne "ok");
  3765. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  3766. readingsSingleUpdate($hash, "local_url", $json->{local_url}, 1) if(defined($json->{local_url}));
  3767. }
  3768. else
  3769. {
  3770. $hash->{status} = "error";
  3771. }
  3772. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3773. }
  3774. sub
  3775. netatmo_parsePersonReadings($$;$)
  3776. {
  3777. my($hash, $json) = @_;
  3778. my $name = $hash->{NAME};
  3779. Log3 $name, 4, "$name: parsePersonReadings";
  3780. if( $json ) {
  3781. Log3 $name, 5, "$name: ".Dumper($json);
  3782. $hash->{status} = $json->{status};
  3783. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3784. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  3785. if( $hash->{status} eq "ok" )
  3786. {
  3787. #$hash->{STATE} = "Connected";
  3788. if(defined($json->{body}{events_list}))
  3789. {
  3790. my @eventslist = @{$json->{body}{events_list}};
  3791. my $eventdata;
  3792. while ($eventdata = pop( @eventslist ))
  3793. {
  3794. next if(!defined($eventdata->{person_id}));
  3795. next if($eventdata->{time} <= $lastupdate);
  3796. next if($eventdata->{person_id} ne $hash->{Person});
  3797. $eventdata->{time} = time() if(!defined($eventdata->{time}));
  3798. readingsSingleUpdate($hash, ".lastupdate", $eventdata->{time}, 0);
  3799. Log3 $name, 4, "$name: new event: ".FmtDateTime($eventdata->{time});
  3800. my $camera = $modules{$hash->{TYPE}}{defptr}{"C$eventdata->{camera_id}"};
  3801. my $person = $modules{$hash->{TYPE}}{defptr}{"P$eventdata->{person_id}"} if(defined($eventdata->{person_id}));
  3802. if (defined($person))
  3803. {
  3804. readingsSingleUpdate($person, "last_seen", FmtDateTime($eventdata->{time}), 1) if(defined($eventdata->{time}));
  3805. readingsSingleUpdate($person, "last_arrival", FmtDateTime($eventdata->{time}), 1) if(defined($eventdata->{time}) && defined($eventdata->{is_arrival}) && $eventdata->{is_arrival} eq "1");
  3806. if(defined($camera))
  3807. {
  3808. readingsBeginUpdate($person);
  3809. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3810. readingsBulkUpdate( $person, "camera", ReadingsVal($camera->{NAME},"name","Unknown"), 1 );
  3811. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3812. readingsEndUpdate($person,1);
  3813. }
  3814. if(defined($eventdata->{id}))
  3815. {
  3816. readingsBeginUpdate($person);
  3817. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3818. readingsBulkUpdate( $person, "event_id", $eventdata->{id}, 1 );
  3819. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3820. readingsEndUpdate($person,1);
  3821. }
  3822. if(defined($eventdata->{video_status}))
  3823. {
  3824. readingsBeginUpdate($person);
  3825. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3826. readingsBulkUpdate( $person, "video_status", $eventdata->{video_status}, 1 );
  3827. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3828. readingsEndUpdate($person,1);
  3829. }
  3830. if(defined($eventdata->{video_id}))
  3831. {
  3832. readingsBeginUpdate($person);
  3833. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3834. readingsBulkUpdate( $person, "video_id", $eventdata->{video_id}, 1 );
  3835. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3836. readingsEndUpdate($person,1);
  3837. }
  3838. if(defined($eventdata->{snapshot}))
  3839. {
  3840. readingsBeginUpdate($person);
  3841. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3842. readingsBulkUpdate( $person, "snapshot", $eventdata->{snapshot}{id}."|".$eventdata->{snapshot}{key}, 1 );
  3843. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3844. readingsEndUpdate($person,1);
  3845. }
  3846. if(defined($eventdata->{snapshot}))
  3847. {
  3848. readingsBeginUpdate($person);
  3849. $person->{".updateTimestamp"} = FmtDateTime($eventdata->{time});
  3850. readingsBulkUpdate( $person, "last_snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$eventdata->{snapshot}{id}."&key=".$eventdata->{snapshot}{key}, 1 );
  3851. $person->{CHANGETIME}[0] = FmtDateTime($eventdata->{time});
  3852. readingsEndUpdate($person,1);
  3853. }
  3854. }
  3855. }
  3856. }
  3857. }
  3858. }
  3859. else
  3860. {
  3861. $hash->{status} = "error";
  3862. }
  3863. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  3864. }
  3865. sub
  3866. netatmo_parseThermostatReadings($$;$)
  3867. {
  3868. my($hash, $json) = @_;
  3869. my $name = $hash->{NAME};
  3870. Log3 $name, 4, "$name: parseThermostatReadings";
  3871. if( $json ) {
  3872. Log3 $name, 5, "$name: ".Dumper($json);
  3873. $hash->{status} = $json->{status};
  3874. $hash->{status} = $json->{error}{message} if( $json->{error} );
  3875. my $lastupdate = ReadingsVal( $name, ".lastupdate", 0 );
  3876. my @r = ();
  3877. my $readings = \@r;
  3878. $readings = $hash->{readings} if( defined($hash->{readings}) );
  3879. if( $hash->{status} eq "ok" )
  3880. {
  3881. foreach my $devicedata ( @{$json->{body}{devices}})
  3882. {
  3883. my $hash = $modules{$hash->{TYPE}}{defptr}{"R$devicedata->{_id}"};
  3884. next if (!defined($hash));
  3885. next if($devicedata->{_id} ne $hash->{Relay});
  3886. #$hash->{STATE} = "Connected";
  3887. readingsSingleUpdate($hash, "name", encode_utf8($devicedata->{station_name}), 1) if(defined($devicedata->{station_name}));
  3888. $hash->{stationName} = encode_utf8($devicedata->{station_name}) if( $devicedata->{station_name} );
  3889. $hash->{moduleName} = encode_utf8($devicedata->{module_name}) if( $devicedata->{module_name} );
  3890. $hash->{model} = $devicedata->{type} if(defined($devicedata->{type}));
  3891. $hash->{firmware} = $devicedata->{firmware} if(defined($devicedata->{firmware}));
  3892. $hash->{last_upgrade} = FmtDateTime($devicedata->{last_upgrade}) if(defined($devicedata->{last_upgrade}));
  3893. $hash->{date_setup} = FmtDateTime($devicedata->{date_setup}) if(defined($devicedata->{date_setup}));
  3894. $hash->{last_setup} = FmtDateTime($devicedata->{last_setup}) if(defined($devicedata->{last_setup}));
  3895. $hash->{last_status_store} = FmtDateTime($devicedata->{last_status_store}) if(defined($devicedata->{last_status_store}));
  3896. $hash->{helper}{last_status_store} = $devicedata->{last_status_store} if(defined($devicedata->{last_status_store}) && $devicedata->{last_status_store} > $hash->{helper}{last_status_store});
  3897. $hash->{last_message} = FmtDateTime($devicedata->{last_message}) if(defined($devicedata->{last_message}));
  3898. $hash->{last_seen} = FmtDateTime($devicedata->{last_seen}) if(defined($devicedata->{last_seen}));
  3899. $hash->{last_plug_seen} = FmtDateTime($devicedata->{last_plug_seen}) if(defined($devicedata->{last_plug_seen}));
  3900. $hash->{last_therm_seen} = FmtDateTime($devicedata->{last_therm_seen}) if(defined($devicedata->{last_therm_seen}));
  3901. $hash->{wifi_status} = $devicedata->{wifi_status} if(defined($devicedata->{wifi_status}));
  3902. $hash->{rf_status} = $devicedata->{rf_status} if(defined($devicedata->{rf_status}));
  3903. #$hash->{battery_percent} = $devicedata->{battery_percent} if(defined($devicedata->{battery_percent}));
  3904. $hash->{battery_vp} = $devicedata->{battery_vp} if(defined($devicedata->{battery_vp}));
  3905. $hash->{therm_orientation} = $devicedata->{therm_orientation} if(defined($devicedata->{therm_orientation}));
  3906. $hash->{therm_relay_cmd} = $devicedata->{therm_relay_cmd} if(defined($devicedata->{therm_relay_cmd}));
  3907. $hash->{udp_conn} = $devicedata->{udp_conn} if(defined($devicedata->{udp_conn}));
  3908. $hash->{plug_connected_boiler} = $devicedata->{plug_connected_boiler} if(defined($devicedata->{plug_connected_boiler}));
  3909. $hash->{syncing} = $devicedata->{syncing} if(defined($devicedata->{syncing}));
  3910. $hash->{room} = $devicedata->{room} if(defined($devicedata->{room}));
  3911. if( $devicedata->{place} ) {
  3912. $hash->{country} = encode_utf8($devicedata->{place}{country});
  3913. $hash->{bssid} = $devicedata->{place}{bssid} if(defined($devicedata->{place}{bssid}));
  3914. $hash->{altitude} = $devicedata->{place}{altitude} if(defined($devicedata->{place}{altitude}));
  3915. $hash->{city} = encode_utf8($devicedata->{place}{geoip_city}) if(defined($devicedata->{place}{geoip_city}));
  3916. $hash->{city} = encode_utf8($devicedata->{place}{city}) if(defined($devicedata->{place}{city}));;
  3917. $hash->{location} = $devicedata->{place}{location}[1] .",". $devicedata->{place}{location}[0];
  3918. $hash->{timezone} = encode_utf8($devicedata->{place}{timezone});
  3919. }
  3920. readingsSingleUpdate($hash, "battery", ($devicedata->{battery_percent} > 20) ? "ok" : "low", 1) if(defined($devicedata->{battery_percent}));
  3921. readingsSingleUpdate($hash, "battery_percent", $devicedata->{battery_percent}, 1) if(defined($devicedata->{battery_percent}));
  3922. if(defined($devicedata->{modules}))
  3923. {
  3924. foreach my $moduledata ( @{$devicedata->{modules}})
  3925. {
  3926. my $module = $modules{$hash->{TYPE}}{defptr}{"T$moduledata->{_id}"};
  3927. next if (!defined($module));
  3928. $module->{stationName} = encode_utf8($moduledata->{station_name}) if( $moduledata->{station_name} );
  3929. $module->{moduleName} = encode_utf8($moduledata->{module_name}) if( $moduledata->{module_name} );
  3930. $module->{model} = $moduledata->{type} if(defined($moduledata->{type}));
  3931. $module->{firmware} = $moduledata->{firmware} if(defined($moduledata->{firmware}));
  3932. $module->{last_upgrade} = FmtDateTime($moduledata->{last_upgrade}) if(defined($moduledata->{last_upgrade}));
  3933. $module->{date_setup} = FmtDateTime($moduledata->{date_setup}) if(defined($moduledata->{date_setup}));
  3934. $module->{last_setup} = FmtDateTime($moduledata->{last_setup}) if(defined($moduledata->{last_setup}));
  3935. $module->{last_status_store} = FmtDateTime($moduledata->{last_status_store}) if(defined($moduledata->{last_status_store}));
  3936. $module->{helper}{last_status_store} = $moduledata->{last_status_store} if(defined($moduledata->{last_status_store}) && $moduledata->{last_status_store} > $module->{helper}{last_status_store});
  3937. $module->{last_message} = FmtDateTime($moduledata->{last_message}) if(defined($moduledata->{last_message}));
  3938. $module->{last_seen} = FmtDateTime($moduledata->{last_seen}) if(defined($moduledata->{last_seen}));
  3939. $module->{last_plug_seen} = FmtDateTime($moduledata->{last_plug_seen}) if(defined($moduledata->{last_plug_seen}));
  3940. $module->{last_therm_seen} = FmtDateTime($moduledata->{last_therm_seen}) if(defined($moduledata->{last_therm_seen}));
  3941. $module->{wifi_status} = $moduledata->{wifi_status} if(defined($moduledata->{wifi_status}));
  3942. $module->{rf_status} = $moduledata->{rf_status} if(defined($moduledata->{rf_status}));
  3943. #$module->{battery_percent} = $moduledata->{battery_percent} if(defined($moduledata->{battery_percent}));
  3944. $module->{battery_vp} = $moduledata->{battery_vp} if(defined($moduledata->{battery_vp}));
  3945. $module->{therm_orientation} = $moduledata->{therm_orientation} if(defined($moduledata->{therm_orientation}));
  3946. #$module->{therm_relay_cmd} = $moduledata->{therm_relay_cmd} if(defined($moduledata->{therm_relay_cmd}));
  3947. $module->{udp_conn} = $moduledata->{udp_conn} if(defined($moduledata->{udp_conn}));
  3948. $module->{plug_connected_boiler} = $moduledata->{plug_connected_boiler} if(defined($moduledata->{plug_connected_boiler}));
  3949. $module->{syncing} = $moduledata->{syncing} if(defined($moduledata->{syncing}));
  3950. $module->{room} = $moduledata->{room} if(defined($moduledata->{room}));
  3951. if( $moduledata->{place} ) {
  3952. $module->{country} = $moduledata->{place}{country};
  3953. $module->{bssid} = $moduledata->{place}{bssid} if(defined($moduledata->{place}{bssid}));
  3954. $module->{altitude} = $moduledata->{place}{altitude} if(defined($moduledata->{place}{altitude}));
  3955. $module->{city} = encode_utf8($moduledata->{place}{geoip_city}) if(defined($moduledata->{place}{geoip_city}));
  3956. $module->{city} = encode_utf8($moduledata->{place}{city}) if(defined($moduledata->{place}{city}));;
  3957. $module->{location} = $moduledata->{place}{location}[1] .",". $moduledata->{place}{location}[0];
  3958. $module->{timezone} = encode_utf8($moduledata->{place}{timezone});
  3959. }
  3960. readingsSingleUpdate($module, "battery", ($moduledata->{battery_percent} > 20) ? "ok" : "low", 1) if(defined($moduledata->{battery_percent}));
  3961. readingsSingleUpdate($module, "battery_percent", $moduledata->{battery_percent}, 1) if(defined($moduledata->{battery_percent}));
  3962. #readingsSingleUpdate($module, "name", encode_utf8($moduledata->{module_name}), 1) if(defined($moduledata->{module_name}));
  3963. my $setmode = "manual";
  3964. if(defined($moduledata->{setpoint}))
  3965. {
  3966. readingsSingleUpdate($module, "setpoint_mode", $moduledata->{setpoint}{setpoint_mode}, 1) if(defined($moduledata->{setpoint}{setpoint_mode}));
  3967. readingsSingleUpdate($module, "setpoint_endtime", FmtDateTime($moduledata->{setpoint}{setpoint_endtime}), 1) if(defined($moduledata->{setpoint}{setpoint_endtime}));
  3968. CommandDeleteReading( undef, "$module->{NAME} setpoint_endtime" ) if(!defined($moduledata->{setpoint}{setpoint_endtime}));
  3969. $setmode = $moduledata->{setpoint}{setpoint_mode} if(defined($moduledata->{setpoint}{setpoint_mode}));
  3970. }
  3971. readingsSingleUpdate($module, "therm_relay_cmd", $moduledata->{therm_relay_cmd}, 1) if(defined($moduledata->{therm_relay_cmd}));
  3972. if(defined($moduledata->{measured}{setpoint_temp}))
  3973. {
  3974. readingsBeginUpdate($module);
  3975. $module->{".updateTimestamp"} = FmtDateTime($moduledata->{measured}{time});
  3976. readingsBulkUpdate( $module, "setpoint_temp", sprintf( "%.1f", $moduledata->{measured}{setpoint_temp}), 1 );
  3977. $module->{CHANGETIME}[0] = FmtDateTime($moduledata->{measured}{time});
  3978. readingsEndUpdate($module,1);
  3979. $setmode = sprintf( "%.1f", $moduledata->{measured}{setpoint_temp}) if($setmode ne "max" && $setmode ne "off");
  3980. }
  3981. readingsSingleUpdate($module, "setpoint", $setmode, 1);
  3982. my @s = ();
  3983. my $schedules = \@s;
  3984. my @schedulelist;
  3985. foreach my $scheduledata ( @{$moduledata->{therm_program_list}})
  3986. {
  3987. my $program = encode_utf8($scheduledata->{name});
  3988. $program =~ s/ /_/g;
  3989. push(@{$schedules}, [$program, $scheduledata->{program_id}]);
  3990. push(@schedulelist, $program);
  3991. if(defined($scheduledata->{selected}))
  3992. {
  3993. readingsSingleUpdate($module, "program", $program, 1);
  3994. }
  3995. }
  3996. $module->{schedules} = $schedules;
  3997. $module->{schedulenames} = join(',', @schedulelist);
  3998. }
  3999. }
  4000. #my $time = $devicedata->{time_server};
  4001. }
  4002. }
  4003. }
  4004. else
  4005. {
  4006. $hash->{status} = "error";
  4007. }
  4008. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  4009. }
  4010. sub
  4011. netatmo_parseThermostatStatus($$;$)
  4012. {
  4013. my($hash, $json) = @_;
  4014. my $name = $hash->{NAME};
  4015. Log3 $name, 4, "$name: parseThermostatStatus";
  4016. my $thermostat = $modules{$hash->{TYPE}}{defptr}{"T$hash->{Thermostat}"};
  4017. if( $json ) {
  4018. Log3 $name, 5, "$name: ".Dumper($json);
  4019. $hash->{status} = $json->{status};
  4020. $hash->{status} = $json->{error}{message} if( $json->{error} );
  4021. InternalTimer( gettimeofday() + 10, "netatmo_pollRelay", $thermostat) if($hash->{status} eq "ok");
  4022. } else {
  4023. netatmo_pollRelay($thermostat) if($thermostat->{status} !~ /usage/ && $thermostat->{status} !~ /too_many_connections/ && $thermostat->{status} !~ /postponed/);;
  4024. }
  4025. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  4026. }
  4027. sub
  4028. netatmo_parseHeatingHomeStatus($$)
  4029. {
  4030. my($hash, $json) = @_;
  4031. my $name = $hash->{NAME};
  4032. Log3 $name, 4, "$name: parseHeatingHomeStatus";
  4033. my $thermostat = $modules{$hash->{TYPE}}{defptr}{"E$hash->{Home}"};
  4034. Log3 $name, 5, "$name: parseHeatingHomeStatus ".Dumper($json);
  4035. return undef;
  4036. }
  4037. sub
  4038. netatmo_parsePublic($$)
  4039. {
  4040. my($hash, $json) = @_;
  4041. my $name = $hash->{NAME};
  4042. Log3 $name, 5, "$name: parsepublic ".Dumper($json);
  4043. if( $json ) {
  4044. $hash->{status} = $json->{status};
  4045. $hash->{status} = $json->{error}{message} if( $json->{error} );
  4046. if( $hash->{status} eq "ok" ) {
  4047. if( $hash->{Lat} && $hash->{Lon} )
  4048. {
  4049. my $found = 0;
  4050. my @readings = ();
  4051. my @readings_temperature = ();
  4052. my @readings_humidity = ();
  4053. my @readings_pressure = ();
  4054. my @readings_rain = ();
  4055. my @readings_rain_1 = ();
  4056. my @readings_rain_24 = ();
  4057. my @readings_wind_angle = ();
  4058. my @readings_wind_strength = ();
  4059. my @readings_gust_angle = ();
  4060. my @readings_gust_strength = ();
  4061. my @timestamps_temperature = ();
  4062. my @timestamps_pressure = ();
  4063. my @timestamps_rain = ();
  4064. my @timestamps_wind = ();
  4065. my @readings_altitude = ();
  4066. my @readings_latitude = ();
  4067. my @readings_longitude = ();
  4068. my $devices = $json->{body};
  4069. if( ref($devices) eq "ARRAY" ) {
  4070. foreach my $device (@{$devices}) {
  4071. $found++;
  4072. #next if( $device->{_id} ne $hash->{Device} );
  4073. next if( ref($device->{measures}) ne "HASH" );
  4074. if(defined($device->{place}))
  4075. {
  4076. push(@readings_altitude, $device->{place}{altitude}) if(defined($device->{place}{altitude}));
  4077. push(@readings_latitude, $device->{place}{location}[1]) if(defined($device->{place}{location}));
  4078. push(@readings_longitude, $device->{place}{location}[0]) if(defined($device->{place}{location}));
  4079. }
  4080. foreach my $module ( keys %{$device->{measures}}) {
  4081. #next if( ref($device->{measures}->{$module}->{res}) ne "HASH" );
  4082. if(defined($device->{measures}->{$module}->{rain_live}))
  4083. {
  4084. push(@readings_rain, $device->{measures}->{$module}->{rain_live});
  4085. push(@readings_rain_1, $device->{measures}->{$module}->{rain_60min});
  4086. push(@readings_rain_24, $device->{measures}->{$module}->{rain_24h});
  4087. push(@timestamps_rain, $device->{measures}->{$module}->{rain_timeutc});
  4088. next;
  4089. }
  4090. if(defined($device->{measures}->{$module}->{wind_strength}))
  4091. {
  4092. push(@readings_wind_angle, $device->{measures}->{$module}->{wind_angle});
  4093. push(@readings_wind_strength, $device->{measures}->{$module}->{wind_strength});
  4094. push(@readings_gust_angle, $device->{measures}->{$module}->{gust_angle});
  4095. push(@readings_gust_strength, $device->{measures}->{$module}->{gust_strength});
  4096. push(@timestamps_wind, $device->{measures}->{$module}->{wind_timeutc});
  4097. next;
  4098. }
  4099. foreach my $timestamp ( keys %{$device->{measures}->{$module}->{res}} ) {
  4100. #next if( $hash->{LAST_POLL} && $timestamp <= $hash->{LAST_POLL} );
  4101. my $i = 0;
  4102. foreach my $value ( @{$device->{measures}->{$module}->{res}->{$timestamp}} ) {
  4103. my $type = $device->{measures}->{$module}->{type}[$i];
  4104. ++$i;
  4105. if(lc($type) eq "pressure")
  4106. {
  4107. push(@timestamps_pressure, $timestamp);
  4108. push(@readings_pressure, $value);
  4109. next;
  4110. }
  4111. else
  4112. {
  4113. push(@timestamps_temperature, $timestamp) if(lc($type) eq "temperature");
  4114. push(@readings_temperature, $value) if(lc($type) eq "temperature");
  4115. push(@readings_humidity, $value) if(lc($type) eq "humidity");
  4116. next;
  4117. }
  4118. }
  4119. }
  4120. }
  4121. #$found = 1;
  4122. #last;
  4123. }
  4124. }
  4125. @readings_temperature = sort {$a <=> $b} @readings_temperature;
  4126. @readings_humidity = sort {$a <=> $b} @readings_humidity;
  4127. @readings_pressure = sort {$a <=> $b} @readings_pressure;
  4128. @readings_rain = sort {$a <=> $b} @readings_rain;
  4129. @readings_rain_1 = sort {$a <=> $b} @readings_rain_1;
  4130. @readings_rain_24 = sort {$a <=> $b} @readings_rain_24;
  4131. @readings_wind_angle = sort {$a <=> $b} @readings_wind_angle;
  4132. @readings_wind_strength = sort {$a <=> $b} @readings_wind_strength;
  4133. @readings_gust_angle = sort {$a <=> $b} @readings_gust_angle;
  4134. @readings_gust_strength = sort {$a <=> $b} @readings_gust_strength;
  4135. @timestamps_temperature = sort {$a <=> $b} @timestamps_temperature;
  4136. @timestamps_pressure = sort {$a <=> $b} @timestamps_pressure;
  4137. @timestamps_rain = sort {$a <=> $b} @timestamps_rain;
  4138. @timestamps_wind = sort {$a <=> $b} @timestamps_wind;
  4139. @readings_altitude = sort {$a <=> $b} @readings_altitude;
  4140. @readings_latitude = sort {$a <=> $b} @readings_latitude;
  4141. @readings_longitude = sort {$a <=> $b} @readings_longitude;
  4142. if(scalar(@readings_temperature) > 4)
  4143. {
  4144. for (my $i=0;$i<scalar(@readings_temperature)/10;$i++)
  4145. {
  4146. pop @readings_temperature;
  4147. pop @readings_humidity;
  4148. pop @timestamps_temperature;
  4149. shift @readings_temperature;
  4150. shift @readings_humidity;
  4151. shift @timestamps_temperature;
  4152. }
  4153. }
  4154. if(scalar(@readings_pressure) > 4)
  4155. {
  4156. for (my $i=0;$i<scalar(@readings_pressure)/10;$i++)
  4157. {
  4158. pop @readings_pressure;
  4159. pop @timestamps_pressure;
  4160. shift @readings_pressure;
  4161. shift @timestamps_pressure;
  4162. }
  4163. }
  4164. if(scalar(@readings_rain) > 4)
  4165. {
  4166. for (my $i=0;$i<scalar(@readings_rain)/20;$i++)
  4167. {
  4168. pop @readings_rain;
  4169. pop @readings_rain_1;
  4170. pop @readings_rain_24;
  4171. pop @timestamps_rain;
  4172. shift @readings_rain;
  4173. shift @readings_rain_1;
  4174. shift @readings_rain_24;
  4175. shift @timestamps_rain;
  4176. }
  4177. }
  4178. if(scalar(@readings_wind_strength) > 4)
  4179. {
  4180. for (my $i=0;$i<scalar(@readings_wind_strength)/25;$i++)
  4181. {
  4182. pop @readings_wind_strength;
  4183. pop @readings_gust_strength;
  4184. pop @timestamps_wind;
  4185. shift @readings_wind_strength;
  4186. shift @readings_gust_strength;
  4187. shift @timestamps_wind;
  4188. }
  4189. }
  4190. if(scalar(@readings_pressure) > 4)
  4191. {
  4192. for (my $i=0;$i<scalar(@readings_pressure)/20;$i++)
  4193. {
  4194. pop @readings_altitude;
  4195. pop @readings_latitude;
  4196. pop @readings_longitude;
  4197. shift @readings_altitude;
  4198. shift @readings_latitude;
  4199. shift @readings_longitude;
  4200. }
  4201. }
  4202. my $avg_temperature = 0;
  4203. my $min_temperature = 100;
  4204. my $max_temperature = -100;
  4205. foreach my $val (@readings_temperature)
  4206. {
  4207. $avg_temperature += $val / scalar(@readings_temperature);
  4208. $min_temperature = $val if($val < $min_temperature);
  4209. $max_temperature = $val if($val > $max_temperature);
  4210. }
  4211. my $avg_humidity = 0;
  4212. my $min_humidity = 100;
  4213. my $max_humidity = -100;
  4214. foreach my $val (@readings_humidity)
  4215. {
  4216. $avg_humidity += $val / scalar(@readings_humidity);
  4217. $min_humidity = $val if($val < $min_humidity);
  4218. $max_humidity = $val if($val > $max_humidity);
  4219. }
  4220. my $avgtime_temperature = 0;
  4221. foreach my $val (@timestamps_temperature)
  4222. {
  4223. $avgtime_temperature += $val / scalar(@timestamps_temperature);
  4224. }
  4225. my $avg_pressure = 0;
  4226. my $min_pressure = 2000;
  4227. my $max_pressure = -2000;
  4228. foreach my $val (@readings_pressure)
  4229. {
  4230. $avg_pressure += $val / scalar(@readings_pressure);
  4231. $min_pressure = $val if($val < $min_pressure);
  4232. $max_pressure = $val if($val > $max_pressure);
  4233. }
  4234. my $avgtime_pressure = 0;
  4235. foreach my $val (@timestamps_pressure)
  4236. {
  4237. $avgtime_pressure += $val / scalar(@timestamps_pressure);
  4238. }
  4239. my $avg_rain = 0;
  4240. my $min_rain = 1000;
  4241. my $max_rain = -1000;
  4242. foreach my $val (@readings_rain)
  4243. {
  4244. $avg_rain += $val / scalar(@readings_rain);
  4245. $min_rain = $val if($val < $min_rain);
  4246. $max_rain = $val if($val > $max_rain);
  4247. }
  4248. my $avg_rain_1 = 0;
  4249. my $min_rain_1 = 1000;
  4250. my $max_rain_1 = -1000;
  4251. foreach my $val (@readings_rain_1)
  4252. {
  4253. $avg_rain_1 += $val / scalar(@readings_rain_1);
  4254. $min_rain_1 = $val if($val < $min_rain_1);
  4255. $max_rain_1 = $val if($val > $max_rain_1);
  4256. }
  4257. my $avg_rain_24 = 0;
  4258. my $min_rain_24 = 1000;
  4259. my $max_rain_24 = -1000;
  4260. foreach my $val (@readings_rain_24)
  4261. {
  4262. $avg_rain_24 += $val / scalar(@readings_rain_24);
  4263. $min_rain_24 = $val if($val < $min_rain_24);
  4264. $max_rain_24 = $val if($val > $max_rain_24);
  4265. }
  4266. my $avgtime_rain = 0;
  4267. foreach my $val (@timestamps_rain)
  4268. {
  4269. $avgtime_rain += $val / scalar(@timestamps_rain);
  4270. }
  4271. my $avg_wind = 0;
  4272. my $min_wind = 100;
  4273. my $max_wind = -100;
  4274. foreach my $val (@readings_wind_strength)
  4275. {
  4276. $avg_wind += $val / scalar(@readings_wind_strength);
  4277. $min_wind = $val if($val < $min_wind);
  4278. $max_wind = $val if($val > $max_wind);
  4279. }
  4280. my $avg_gust = 0;
  4281. my $min_gust = 100;
  4282. my $max_gust = -100;
  4283. foreach my $val (@readings_gust_strength)
  4284. {
  4285. $avg_gust += $val / scalar(@readings_gust_strength);
  4286. $min_gust = $val if($val < $min_gust);
  4287. $max_gust = $val if($val > $max_gust);
  4288. }
  4289. my $angle_wind_x = 0;
  4290. my $angle_wind_y = 0;
  4291. foreach my $val (@readings_wind_angle)
  4292. {
  4293. next if($val == -1);
  4294. Log3 $name, 5, "$name: wind angle ".$val;
  4295. $angle_wind_x += cos($val);
  4296. $angle_wind_y += sin($val);
  4297. }
  4298. my $angle_wind = atan2($angle_wind_x,$angle_wind_y);
  4299. $angle_wind = ($angle_wind >= 0 ? $angle_wind : (2* pi + $angle_wind)) * 180/ pi;
  4300. Log3 $name, 4, "$name: wind angle avg ".$angle_wind;
  4301. my $angle_gust_x = 0;
  4302. my $angle_gust_y = 0;
  4303. foreach my $val (@readings_gust_angle)
  4304. {
  4305. next if($val == -1);
  4306. Log3 $name, 5, "$name: gust angle ".$val;
  4307. $angle_gust_x += cos($val);
  4308. $angle_gust_y += sin($val);
  4309. }
  4310. my $angle_gust = atan2($angle_gust_x,$angle_gust_y);
  4311. $angle_gust = ($angle_gust >= 0 ? $angle_gust : (2* pi + $angle_gust)) * 180/ pi;
  4312. Log3 $name, 4, "$name: gust angle avg ".$angle_gust;
  4313. my $avgtime_wind = 0;
  4314. foreach my $val (@timestamps_wind)
  4315. {
  4316. $avgtime_wind += $val / scalar(@timestamps_wind);
  4317. }
  4318. my $avg_altitude = 0;
  4319. my $min_altitude = 10000;
  4320. my $max_altitude = -10000;
  4321. foreach my $val (@readings_altitude)
  4322. {
  4323. $avg_altitude += $val / scalar(@readings_altitude);
  4324. $min_altitude = $val if($val < $min_altitude);
  4325. $max_altitude = $val if($val > $max_altitude);
  4326. }
  4327. my $avg_latitude = 0;
  4328. foreach my $val (@readings_latitude)
  4329. {
  4330. $avg_latitude += $val / scalar(@readings_latitude);
  4331. }
  4332. my $avg_longitude = 0;
  4333. foreach my $val (@readings_longitude)
  4334. {
  4335. $avg_longitude += $val / scalar(@readings_longitude);
  4336. }
  4337. $avg_temperature = sprintf( "%.2f", $avg_temperature );
  4338. $avg_humidity = sprintf( "%.2f", $avg_humidity );
  4339. $avg_pressure = sprintf( "%.2f", $avg_pressure );
  4340. $avg_rain = sprintf( "%.2f", $avg_rain );
  4341. $avg_rain_1 = sprintf( "%.2f", $avg_rain_1 );
  4342. $avg_rain_24 = sprintf( "%.2f", $avg_rain_24 );
  4343. $avg_wind = sprintf( "%.1f", $avg_wind );
  4344. $avg_gust = sprintf( "%.1f", $avg_gust );
  4345. $angle_wind = sprintf( "%i", $angle_wind );
  4346. $angle_gust = sprintf( "%i", $angle_gust );
  4347. $avgtime_temperature = sprintf( "%i", $avgtime_temperature );
  4348. $avgtime_pressure = sprintf( "%i", $avgtime_pressure );
  4349. $avgtime_rain = sprintf( "%i", $avgtime_rain );
  4350. $avgtime_wind = sprintf( "%i", $avgtime_wind );
  4351. $avg_altitude = sprintf( "%.2f", $avg_altitude );
  4352. $avg_latitude = sprintf( "%.8f", $avg_latitude );
  4353. $avg_longitude = sprintf( "%.8f", $avg_longitude );
  4354. if(scalar(@readings_temperature) > 0)
  4355. {
  4356. push(@readings, [$avgtime_temperature, 'temperature', $avg_temperature]);
  4357. push(@readings, [$avgtime_temperature, 'temperature_min', $min_temperature]);
  4358. push(@readings, [$avgtime_temperature, 'temperature_max', $max_temperature]);
  4359. push(@readings, [$avgtime_temperature, 'humidity', $avg_humidity]);
  4360. push(@readings, [$avgtime_temperature, 'humidity_min', $min_humidity]);
  4361. push(@readings, [$avgtime_temperature, 'humidity_max', $max_humidity]);
  4362. }
  4363. if(scalar(@readings_pressure) > 0)
  4364. {
  4365. push(@readings, [$avgtime_pressure, 'pressure', $avg_pressure]);
  4366. push(@readings, [$avgtime_pressure, 'pressure_min', $min_pressure]);
  4367. push(@readings, [$avgtime_pressure, 'pressure_max', $max_pressure]);
  4368. }
  4369. if(scalar(@readings_rain) > 0)
  4370. {
  4371. push(@readings, [$avgtime_rain, 'rain', $avg_rain]);
  4372. push(@readings, [$avgtime_rain, 'rain_min', $min_rain]);
  4373. push(@readings, [$avgtime_rain, 'rain_max', $max_rain]);
  4374. push(@readings, [$avgtime_rain, 'rain_hour', $avg_rain_1]);
  4375. push(@readings, [$avgtime_rain, 'rain_hour_min', $min_rain_1]);
  4376. push(@readings, [$avgtime_rain, 'rain_hour_max', $max_rain_1]);
  4377. push(@readings, [$avgtime_rain, 'rain_day', $avg_rain_24]);
  4378. push(@readings, [$avgtime_rain, 'rain_day_min', $min_rain_24]);
  4379. push(@readings, [$avgtime_rain, 'rain_day_max', $max_rain_24]);
  4380. }
  4381. if(scalar(@readings_wind_strength) > 0)
  4382. {
  4383. push(@readings, [$avgtime_wind, 'wind', $avg_wind]);
  4384. push(@readings, [$avgtime_wind, 'wind_min', $min_wind]);
  4385. push(@readings, [$avgtime_wind, 'wind_max', $max_wind]);
  4386. push(@readings, [$avgtime_wind, 'gust', $avg_gust]);
  4387. push(@readings, [$avgtime_wind, 'gust_min', $min_gust]);
  4388. push(@readings, [$avgtime_wind, 'gust_max', $max_gust]);
  4389. push(@readings, [$avgtime_wind, 'wind_angle', $angle_wind]);
  4390. push(@readings, [$avgtime_wind, 'gust_angle', $angle_gust]);
  4391. }
  4392. if(scalar(@readings_altitude) > 0)
  4393. {
  4394. $hash->{altitude} = $avg_altitude;
  4395. $hash->{location} = $avg_latitude.",".$avg_longitude;
  4396. }
  4397. $hash->{stations_indoor} = scalar(@readings_pressure);
  4398. $hash->{stations_outdoor} = scalar(@readings_temperature);
  4399. $hash->{stations_rain} = scalar(@readings_rain);
  4400. $hash->{stations_wind} = scalar(@readings_wind_strength);
  4401. my (undef,$latest) = netatmo_updateReadings( $hash, \@readings );
  4402. $hash->{LAST_POLL} = FmtDateTime( $latest ) if( @readings );
  4403. #$hash->{STATE} = "Error: device not found" if( !$found );
  4404. } else {
  4405. return $json->{body};
  4406. }
  4407. } #else {
  4408. #return $hash->{status};
  4409. #}
  4410. }
  4411. else
  4412. {
  4413. $hash->{status} = "error";
  4414. }
  4415. readingsSingleUpdate( $hash, "active", $hash->{status}, 1 ) if($hash->{status} ne "no data");
  4416. }
  4417. sub
  4418. netatmo_parseAddress($$)
  4419. {
  4420. my($hash, $json) = @_;
  4421. my $name = $hash->{NAME};
  4422. Log3 $name, 4, "$name: parseAddress";
  4423. if( $json ) {
  4424. Log3 $name, 5, "$name: ".Dumper($json);
  4425. $hash->{status} = $json->{status};
  4426. $hash->{status} = $json->{error}{message} if( $json->{error} );
  4427. if( $hash->{status} eq "OK" ) {
  4428. if( $json->{results} ) {
  4429. return $json->{results}->[0]->{formatted_address};
  4430. }
  4431. } else {
  4432. return $hash->{status};
  4433. }
  4434. }
  4435. }
  4436. sub
  4437. netatmo_parseLatLng($$)
  4438. {
  4439. my($hash, $json) = @_;
  4440. my $name = $hash->{NAME};
  4441. Log3 $name, 4, "$name: parseLatLng";
  4442. if( $json ) {
  4443. Log3 $name, 5, "$name: ".Dumper($json);
  4444. $hash->{status} = $json->{status};
  4445. $hash->{status} = $json->{error}{message} if( $json->{error} );
  4446. if( $hash->{status} eq "OK" ) {
  4447. if( $json->{results} ) {
  4448. return $json->{results}->[0]->{geometry}->{bounds};
  4449. }
  4450. } else {
  4451. return $hash->{status};
  4452. }
  4453. }
  4454. }
  4455. sub
  4456. netatmo_pollDevice($)
  4457. {
  4458. my ($hash) = @_;
  4459. my $name = $hash->{NAME};
  4460. $hash->{openRequests} = 0 if ( !defined( $hash->{openRequests}) );
  4461. if( $hash->{Module} )
  4462. {
  4463. my @types = split( ' ', $hash->{dataTypes} ) if(defined($hash->{dataTypes}));
  4464. Log3 $name, 4, "$name: pollDevice types [".$hash->{dataTypes} . "] for modules [".$hash->{Module}."]" if(defined($hash->{dataTypes}));
  4465. my $lastupdate = ReadingsVal( $hash->{NAME}, ".lastupdate", undef );
  4466. $lastupdate = (time-7*24*60*60) if(!$lastupdate and !$hash->{model});
  4467. $hash->{openRequests} += int(@types);
  4468. $hash->{openRequests} += 1 if(int(@types)==0);
  4469. readingsSingleUpdate($hash, ".lastupdate", $lastupdate, 0) if(int(@types)>0);
  4470. foreach my $module (split( ' ', $hash->{Module} ) ) {
  4471. my $type = shift(@types) if( $module and @types);
  4472. netatmo_requestDeviceReadings( $hash, $hash->{Device}, $type, ($module ne $hash->{Device})?$module:undef );# if($type);
  4473. }
  4474. }
  4475. elsif( defined($hash->{Lat}) )
  4476. {
  4477. #$hash->{openRequests} += 1;
  4478. netatmo_getPublicDevices($hash, 0, $hash->{Lat}, $hash->{Lon}, $hash->{Rad} );
  4479. } elsif( $hash->{Device} ) {
  4480. $hash->{openRequests} += 1;
  4481. netatmo_requestDeviceReadings( $hash, $hash->{Device} );
  4482. }
  4483. }
  4484. sub
  4485. netatmo_pollThermostat($)
  4486. {
  4487. my ($hash) = @_;
  4488. my $name = $hash->{NAME};
  4489. $hash->{openRequests} = 0 if ( !defined( $hash->{openRequests}) );
  4490. if( $hash->{Thermostat} )
  4491. {
  4492. Log3 $name, 4, "$name: pollThermostat types [".$hash->{dataTypes} . "] for thermostat [".$hash->{Thermostat}."]" if(defined($hash->{dataTypes}));
  4493. my $lastupdate = ReadingsVal( $hash->{NAME}, ".lastupdate", undef );
  4494. $lastupdate = (time-7*24*60*60) if(!$lastupdate and !$hash->{model});
  4495. $hash->{openRequests} += 1;
  4496. my $type = $hash->{dataTypes};
  4497. readingsSingleUpdate($hash, ".lastupdate", $lastupdate, 0) if($type);
  4498. netatmo_requestDeviceReadings( $hash, $hash->{Relay}, $type, $hash->{Thermostat} );# if($type);
  4499. }
  4500. elsif( $hash->{Relay} )
  4501. {
  4502. $hash->{openRequests} += 1;
  4503. netatmo_requestDeviceReadings( $hash, $hash->{Relay} );
  4504. }
  4505. }
  4506. sub
  4507. netatmo_pollGlobal($)
  4508. {
  4509. my ($hash) = @_;
  4510. my $name = $hash->{NAME};
  4511. netatmo_refreshToken($hash, defined($hash->{access_token}));
  4512. return undef if(!defined($hash->{access_token}));
  4513. Log3 $name, 4, "$name: pollGlobal";
  4514. HttpUtils_NonblockingGet({
  4515. url => "https://".$hash->{helper}{apiserver}."/api/getstationsdata",
  4516. timeout => 20,
  4517. noshutdown => 1,
  4518. data => { access_token => $hash->{access_token}, },
  4519. hash => $hash,
  4520. type => 'stationsdata',
  4521. callback => \&netatmo_dispatch,
  4522. });
  4523. return undef;
  4524. }
  4525. sub
  4526. netatmo_pollGlobalHealth($)
  4527. {
  4528. my ($hash) = @_;
  4529. my $name = $hash->{NAME};
  4530. netatmo_refreshToken($hash, defined($hash->{access_token}));
  4531. return undef if(!defined($hash->{access_token}));
  4532. Log3 $name, 4, "$name: pollGlobalHealth";
  4533. HttpUtils_NonblockingGet({
  4534. url => "https://".$hash->{helper}{apiserver}."/api/gethomecoachsdata",
  4535. timeout => 20,
  4536. noshutdown => 1,
  4537. data => { access_token => $hash->{access_token}, },
  4538. hash => $hash,
  4539. type => 'stationsdata',
  4540. callback => \&netatmo_dispatch,
  4541. });
  4542. return undef;
  4543. }
  4544. sub
  4545. netatmo_pollForecast($)
  4546. {
  4547. my ($hash) = @_;
  4548. my $name = $hash->{NAME};
  4549. if(!defined($hash->{Station}))
  4550. {
  4551. Log3 $name, 1, "$name: device missing the definition! please redefine it.";
  4552. return undef;
  4553. }
  4554. return undef if( !defined($hash->{IODev}) );
  4555. my $iohash = $hash->{IODev};
  4556. netatmo_refreshAppToken($iohash, defined($iohash->{access_token_app}));
  4557. return undef if(!defined($iohash->{access_token_app}));
  4558. if(!defined($iohash->{access_token_app}))
  4559. {
  4560. Log3 $name, 1, "$name: pollForecast - missing app token!";
  4561. return undef;
  4562. }
  4563. Log3 $name, 4, "$name: pollForecast (forecastdata)";
  4564. HttpUtils_NonblockingGet({
  4565. url => "https://app.netatmo.net/api/simplifiedfuturemeasure",
  4566. timeout => 20,
  4567. noshutdown => 1,
  4568. data => { device_id => $hash->{Station}, },
  4569. header => "Authorization: Bearer ".$iohash->{access_token_app},
  4570. hash => $hash,
  4571. type => 'forecastdata',
  4572. callback => \&netatmo_dispatch,
  4573. });
  4574. return undef;
  4575. }
  4576. sub
  4577. netatmo_pollHome($)
  4578. {
  4579. my ($hash) = @_;
  4580. my $name = $hash->{NAME};
  4581. Log3 $name, 3, "$name: pollHome (".$hash->{Home}.")";
  4582. if( $hash->{Home} ) {
  4583. return undef if($hash->{status} =~ /usage/ || $hash->{status} =~ /too_many_connections/ || $hash->{status} =~ /postponed/);
  4584. my $lastupdate = ReadingsVal( $hash->{NAME}, ".lastupdate", undef );
  4585. $lastupdate = (time-7*24*60*60) if(!$lastupdate);
  4586. readingsSingleUpdate($hash, ".lastupdate", $lastupdate, 0);
  4587. netatmo_requestHomeReadings( $hash, $hash->{Home} );
  4588. }
  4589. }
  4590. sub
  4591. netatmo_pollRelay($)
  4592. {
  4593. my ($hash) = @_;
  4594. my $name = $hash->{NAME};
  4595. Log3 $name, 5, "$name: pollRelay (".$hash->{Relay}.")";
  4596. if( $hash->{Relay} ) {
  4597. return undef if(defined($hash->{status}) && ($hash->{status} =~ /usage/ || $hash->{status} =~ /too_many_connections/ || $hash->{status} =~ /postponed/));
  4598. my $lastupdate = ReadingsVal( $hash->{NAME}, ".lastupdate", undef );
  4599. $lastupdate = (time-7*24*60*60) if(!$lastupdate);
  4600. readingsSingleUpdate($hash, ".lastupdate", $lastupdate, 0);
  4601. netatmo_requestThermostatReadings( $hash, $hash->{Relay} );
  4602. }
  4603. }
  4604. sub
  4605. netatmo_pollPerson($)
  4606. {
  4607. my ($hash) = @_;
  4608. my $name = $hash->{NAME};
  4609. Log3 $name, 5, "$name: pollPerson";
  4610. return undef if(defined($hash->{status}) && ($hash->{status} =~ /usage/ || $hash->{status} =~ /too_many_connections/ || $hash->{status} =~ /postponed/));
  4611. if( $hash->{Home} ) {
  4612. my $lastupdate = ReadingsVal( $hash->{NAME}, ".lastupdate", undef );
  4613. $lastupdate = (time-7*24*60*60) if(!$lastupdate);
  4614. readingsSingleUpdate($hash, ".lastupdate", $lastupdate, 0);
  4615. netatmo_requestPersonReadings( $hash );
  4616. }
  4617. }
  4618. sub
  4619. netatmo_Get($$@)
  4620. {
  4621. my ($hash, $name, $cmd, @args) = @_;
  4622. my $list = "";
  4623. if( $hash->{SUBTYPE} eq "DEVICE"
  4624. || $hash->{SUBTYPE} eq "MODULE"
  4625. || $hash->{SUBTYPE} eq "PUBLIC"
  4626. || $hash->{SUBTYPE} eq "FORECAST"
  4627. || $hash->{SUBTYPE} eq "HOME"
  4628. || $hash->{SUBTYPE} eq "CAMERA"
  4629. || $hash->{SUBTYPE} eq "PERSON"
  4630. || $hash->{SUBTYPE} eq "RELAY"
  4631. || $hash->{SUBTYPE} eq "THERMOSTAT"
  4632. || $hash->{SUBTYPE} eq "HEATINGHOME"
  4633. || $hash->{SUBTYPE} eq "HEATINGROOM" ) {
  4634. $list = "update:noArg";
  4635. $list = " ping:noArg video video_local live live_local snapshot" if($hash->{SUBTYPE} eq "CAMERA");
  4636. $list .= " config:noArg timelapse:noArg" if($hash->{SUBTYPE} eq "CAMERA" && defined($hash->{model}) && $hash->{model} eq "NOC");
  4637. #$list .= " weathericon" if($hash->{SUBTYPE} eq "FORECAST");
  4638. if( $cmd eq "weathericon" ) {
  4639. return "no weather code was passed" if($args[0] eq "");
  4640. return netatmo_weatherIcon();
  4641. }
  4642. if( $cmd eq "ping" ) {
  4643. netatmo_pingCamera($hash);
  4644. return undef;
  4645. }
  4646. if( $cmd eq "video" || $cmd eq "video_local" ) {
  4647. return "no video_id was passed" if(!defined($args[0]) || $args[0] eq "");
  4648. return netatmo_getCameraVideo($hash,$args[0],$cmd);
  4649. }
  4650. elsif( $cmd eq "live" || $cmd eq "live_local" ) {
  4651. return netatmo_getCameraLive($hash,$cmd);
  4652. }
  4653. elsif($cmd eq "timelapse") {
  4654. return netatmo_getCameraTimelapse($hash);
  4655. }
  4656. elsif( $cmd eq "snapshot" ) {
  4657. return netatmo_getCameraSnapshot($hash);
  4658. }
  4659. elsif( $cmd eq "config" ) {
  4660. return netatmo_getPresenceConfig($hash);
  4661. }
  4662. if( $cmd eq "updateAll" ) {
  4663. $cmd = "update";
  4664. CommandDeleteReading( undef, "$name .*" );
  4665. }
  4666. if( $cmd eq "update" ) {
  4667. netatmo_poll($hash);
  4668. return undef;
  4669. }
  4670. } elsif( $hash->{SUBTYPE} eq "ACCOUNT" ) {
  4671. $list = "update:noArg devices:noArg homes:noArg thermostats:noArg homecoachs:noArg public showAccount:noArg";
  4672. if( $cmd eq "update" ) {
  4673. netatmo_poll($hash);
  4674. return undef;
  4675. }
  4676. if( $cmd eq 'showAccount' )
  4677. {
  4678. my $username = $hash->{helper}{username};
  4679. my $password = $hash->{helper}{password};
  4680. return 'no username set' if( !$username );
  4681. return 'no password set' if( !$password );
  4682. $username = netatmo_decrypt( $username );
  4683. $password = netatmo_decrypt( $password );
  4684. return "username: $username\npassword: $password";
  4685. }
  4686. if( $cmd eq "devices" ) {
  4687. my $devices = netatmo_getDevices($hash,1);
  4688. my $ret;
  4689. foreach my $device (@{$devices}) {
  4690. $ret .= "\n" if( $ret );
  4691. $ret .= "$device->{_id}\t$device->{firmware}\t$device->{type}\t".($device->{type} !~ /Module/ ? "\t" : "")."$device->{module_name}";
  4692. }
  4693. $ret = "id\t\t\tfw\ttype\t\tname\n" . $ret if( $ret );
  4694. $ret = "no devices found" if( !$ret );
  4695. return $ret;
  4696. } elsif( $cmd eq "homes" ) {
  4697. my $homes = netatmo_getHomes($hash,1);
  4698. Log3 $name, 5, "$name: homes ".Dumper($homes);
  4699. my $ret;
  4700. foreach my $home (@{$homes}) {
  4701. $ret .= "\n" if( $ret );
  4702. $ret .= "$home->{id} \t\tHome\t".encode_utf8($home->{name}) if(defined($home->{cameras}) && @{$home->{cameras}});;
  4703. if(defined($home->{status}))
  4704. {
  4705. $ret .= "$home->{id} \t\t\tCamera\t".encode_utf8($home->{name});
  4706. foreach my $tag (@{$home->{modules}}) {
  4707. $ret .= "\n$tag->{id} \t\t\tTag\t".encode_utf8($tag->{name}) if(defined($tag->{name}));
  4708. }
  4709. }
  4710. $ret .= "$home->{id} \tPerson\t".encode_utf8($home->{pseudo}) if(defined($home->{pseudo}));
  4711. $ret .= "$home->{id} \tPerson\t(Unknown)" if(defined($home->{face}) && !defined($home->{pseudo}));
  4712. }
  4713. $ret = "id\t\t\t\t\ttype\tname\n" . $ret if( $ret );
  4714. $ret = "no homes found" if( !$ret );
  4715. return $ret;
  4716. } elsif( $cmd eq "thermostats" ) {
  4717. my $thermostats = netatmo_getThermostats($hash,1);
  4718. Log3 $name, 5, "$name: thermostats ".Dumper($thermostats);
  4719. my $ret;
  4720. foreach my $thermostat (@{$thermostats}) {
  4721. $ret .= "\n" if( $ret );
  4722. $ret .= "$thermostat->{id}\t$thermostat->{firmware}\t$thermostat->{type}\t ".$thermostat->{name};
  4723. }
  4724. $ret = "id\t\t\tfw\ttype\t name\n" . $ret if( $ret );
  4725. $ret = "no thermostats found" if( !$ret );
  4726. return $ret;
  4727. } elsif( $cmd eq "homecoachs" ) {
  4728. my $homecoachs = netatmo_getHomecoachs($hash,1);
  4729. Log3 $name, 5, "$name: homecoachs ".Dumper($homecoachs);
  4730. my $ret;
  4731. foreach my $homecoach (@{$homecoachs}) {
  4732. $ret .= "\n" if( $ret );
  4733. $ret .= "$homecoach->{_id}\t$homecoach->{firmware}\t$homecoach->{type}\t$homecoach->{name}";
  4734. }
  4735. $ret = "id\t\t\tfw\ttype\t name\n" . $ret if( $ret );
  4736. $ret = "no homecoachs found" if( !$ret );
  4737. return $ret;
  4738. } elsif( $cmd eq "public" ) {
  4739. my $station = '';
  4740. my $addr = '';
  4741. $station = shift @args if( $args[0] && $args[0] =~ m/[\da-f]{2}(:[\da-f]{2}){5}/ );
  4742. if( @args && defined($args[0]) && ( $args[0] =~ m/^\d{5}$/
  4743. || $args[0] =~ m/^a:/ ) ) {
  4744. $addr = shift @args;
  4745. $addr = substr($addr,2) if( $addr =~ m/^a:/ );
  4746. my $bounds = netatmo_getLatLong( $hash,1,$addr );
  4747. $args[0] = $bounds->{northeast}->{lat};
  4748. $args[1] = $bounds->{northeast}->{lng};
  4749. $args[2] = $bounds->{southwest}->{lat};
  4750. $args[3] = $bounds->{southwest}->{lng};
  4751. } elsif(defined($args[0]) && $args[0] =~ m/,/) {
  4752. my @latlon1 = split( ',', $args[0] );
  4753. if($args[1] !~ m/,/){
  4754. $args[3] = undef;
  4755. $args[2] = $args[1];
  4756. } else {
  4757. my @latlon2 = split( ',', $args[1] );
  4758. $args[3] = $latlon2[1];
  4759. $args[2] = $latlon2[0];
  4760. }
  4761. $args[1] = $latlon1[1];
  4762. $args[0] = $latlon1[0];
  4763. }
  4764. my $devices = netatmo_getPublicDevices($hash, 1, $args[0], $args[1], $args[2], $args[3] );
  4765. my $ret;
  4766. my $addresscount = 0;
  4767. if( ref($devices) eq "ARRAY" ) {
  4768. my $csrftoken = (defined($FW_CSRF) ? $FW_CSRF : "&nocsrf");
  4769. foreach my $device (@{$devices}) {
  4770. next if(!defined($device->{_id}));
  4771. next if( $station && $station ne $device->{_id} );
  4772. my $idname = $device->{_id};
  4773. $idname =~ s/:/_/g;
  4774. next if(AttrVal("netatmo_D".$idname, "IODev", undef));
  4775. next if(AttrVal("netatmo_D".$device->{_id}, "IODev", undef));
  4776. next if(defined($modules{$hash->{TYPE}}{defptr}{"D$idname"}));
  4777. next if(defined($modules{$hash->{TYPE}}{defptr}{"D$device->{_id}"}));
  4778. $ret .= "\n" if( $ret );
  4779. $ret .= sprintf( "%s<a href=\"https://www.google.com/maps/@%.8f,%.8f,19z\" target=\"gmaps\"> %.6f,%.6f %i m</a>", $device->{_id},
  4780. $device->{place}->{location}->[1], $device->{place}->{location}->[0],
  4781. $device->{place}->{location}->[1], $device->{place}->{location}->[0],
  4782. $device->{place}->{altitude} );
  4783. #$ret .= "\t";
  4784. $addr = '';
  4785. $addr .= netatmo_getAddress( $hash, 1, $device->{place}->{location}->[1], $device->{place}->{location}->[0] ) if($addresscount++ < AttrVal($name,"addresslimit",10));
  4786. $addr .= " (address limit reached, " if($addresscount == AttrVal($name,"addresslimit",10)+2);
  4787. $addr .= " change attribute addresslimit to see more) " if($addresscount == AttrVal($name,"addresslimit",10)+3);
  4788. next if( ref($device->{measures}) ne "HASH" );
  4789. my $ext;
  4790. my $got_temp;
  4791. my $got_press;
  4792. foreach my $module ( sort keys %{$device->{measures}}) {
  4793. next if( ref($device->{measures}->{$module}->{res}) ne "HASH" );
  4794. $ext .= "$module ";
  4795. $ext .= join(',', @{$device->{measures}->{$module}->{type}});
  4796. $ext .= " ";
  4797. foreach my $timestamp ( keys %{$device->{measures}->{$module}->{res}} ) {
  4798. my $i = 0;
  4799. foreach my $value ( @{$device->{measures}->{$module}->{res}->{$timestamp}} ) {
  4800. my $type = $device->{measures}->{$module}->{type}[$i];
  4801. if( $type eq "temperature" ) {
  4802. $ret .= "\t";
  4803. $ret .= " " if(int($value)<10);
  4804. $ret .= sprintf( "%.1f \xc2\xb0C", $value );
  4805. $got_temp = 1;
  4806. } elsif( $type eq "humidity" ) {
  4807. $ret .= "\t";
  4808. $ret .= " " if(int($value)<10);
  4809. $value = 99 if(int($value)>99);
  4810. $ret .= sprintf( "%i %%", $value );
  4811. } elsif( $type eq "pressure" ) {
  4812. $ret .= "\t\t" if( !$got_temp );
  4813. $ret .= "\t";
  4814. $ret .= " " if(int($value)<1000);
  4815. $ret .= sprintf( "%i hPa", $value );
  4816. $got_press = 1;
  4817. } elsif( $type eq "rain" ) {
  4818. $ret .= "\t" if( !$got_temp );
  4819. $ret .= "\t\t" if( !$got_press );
  4820. #$ret .= "\t";
  4821. $ret .= " ";
  4822. $ret .= " " if(int($value)<10);
  4823. $ret .= sprintf( "%i mm", $value );
  4824. }
  4825. else
  4826. {
  4827. Log3 $name, 2, "$name: unknown type ".$type;
  4828. }
  4829. ++$i;
  4830. }
  4831. last;
  4832. }
  4833. }
  4834. my $got_rain = 0;
  4835. foreach my $module ( keys %{$device->{measures}}) {
  4836. my $value = $device->{measures}->{$module}->{rain_24h};
  4837. if( defined($value) ) {
  4838. $got_rain = 1;
  4839. $ext .= "$module ";
  4840. $ext .= "rain";
  4841. $ext .= " ";
  4842. if( defined($value) )
  4843. {
  4844. $ret .= "\t\t\t " if( !$got_press );
  4845. $ret .= "\t ";
  4846. $ret .= " " if(int($value)<10);
  4847. $value = 99 if(int($value)>99);
  4848. $ret .= sprintf( "%.1f mm", $value );
  4849. }
  4850. }
  4851. }
  4852. $ret .= "\t\t" if( !$got_rain );
  4853. my $got_wind = 0;
  4854. foreach my $module ( keys %{$device->{measures}}) {
  4855. my $value = $device->{measures}->{$module}->{gust_strength};
  4856. if( defined($value) ) {
  4857. $got_wind = 1;
  4858. $ext .= "$module ";
  4859. $ext .= "windstrength,windangle,guststrength,gustangle";
  4860. $ext .= " ";
  4861. if( defined($value) )
  4862. {
  4863. $ret .= " ";
  4864. $ret .= " " if(int($value)<10);
  4865. $value = 99 if(int($value)>99);
  4866. $ret .= sprintf( "%i km/h", $value );
  4867. }
  4868. }
  4869. }
  4870. $ret .= "\t" if( !$got_wind );
  4871. $ret .= "\t $addr" if(defined($addr));
  4872. #$ret .= "\n\tdefine netatmo_P$device->{_id} netatmo PUBLIC $device->{_id} $ext" if( $station );
  4873. my $definelink = "<a href=\"#\" onclick=\"javascript:window.open((\'".$FW_ME."?cmd=define netatmo_D".$idname." net+++atmo PUBLIC ".$device->{_id}." ".$ext.$csrftoken."\').replace('+++',''), 'definewindow');\">=&gt; </a>";
  4874. $ret =~ s/$device->{_id}/$definelink/;
  4875. }
  4876. } else {
  4877. $ret = $devices if( !ref($devices) );
  4878. }
  4879. $ret = " latitude,longitude alt\ttemp\thum\tpressure\t rain\t\twind\t address\n" . $ret if( $ret );
  4880. $ret = "no devices found" if( !$ret );
  4881. return $ret;
  4882. }
  4883. }
  4884. return "Unknown argument $cmd, choose one of $list";
  4885. }
  4886. #########################
  4887. sub
  4888. netatmo_addExtension($) {
  4889. my ($hash) = @_;
  4890. my $name = $hash->{NAME};
  4891. #netatmo_removeExtension() ;
  4892. my $url = "/netatmo";
  4893. delete $data{FWEXT}{$url} if($data{FWEXT}{$url});
  4894. Log3 $name, 1, "Starting Netatmo webhook for $name";
  4895. $data{FWEXT}{$url}{deviceName} = $name;
  4896. $data{FWEXT}{$url}{FUNC} = "netatmo_Webhook";
  4897. $data{FWEXT}{$url}{LINK} = "netatmo";
  4898. netatmo_registerWebhook($hash);
  4899. }
  4900. #########################
  4901. sub
  4902. netatmo_removeExtension($) {
  4903. my ($hash) = @_;
  4904. netatmo_dropWebhook($hash);
  4905. my $url = "/netatmo";
  4906. my $name = $data{FWEXT}{$url}{deviceName};
  4907. Log3 $name, 3, "Stopping Netatmo webhook for $name";
  4908. delete $data{FWEXT}{$url};
  4909. }
  4910. sub
  4911. netatmo_registerWebhook($)
  4912. {
  4913. my ($hash) = @_;
  4914. my $name = $hash->{NAME};
  4915. return undef if( !defined($hash->{IODev}) );
  4916. my $iohash = $hash->{IODev};
  4917. netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  4918. return undef if(!defined($iohash->{access_token}));
  4919. Log3 $name, 3, "Registering Netatmo webhook";
  4920. my $webhookurl = AttrVal($name,"webhookURL",undef);
  4921. return undef if(!defined($webhookurl));
  4922. HttpUtils_NonblockingGet({
  4923. url => "https://".$iohash->{helper}{apiserver}."/api/addwebhook",
  4924. timeout => 20,
  4925. noshutdown => 1,
  4926. data => { access_token => $iohash->{access_token}, url => $webhookurl, app_type => 'app_security', },
  4927. hash => $hash,
  4928. type => 'addwebhook',
  4929. callback => \&netatmo_dispatch,
  4930. });
  4931. }
  4932. sub
  4933. netatmo_dropWebhook($)
  4934. {
  4935. my ($hash) = @_;
  4936. my $name = $hash->{NAME};
  4937. return undef if( !defined($hash->{IODev}) );
  4938. my $iohash = $hash->{IODev};
  4939. netatmo_refreshToken($iohash, defined($iohash->{access_token}));
  4940. return undef if(!defined($iohash->{access_token}));
  4941. Log3 $name, 3, "Dropping Netatmo webhook";
  4942. HttpUtils_NonblockingGet({
  4943. url => "https://".$iohash->{helper}{apiserver}."/api/dropwebhook",
  4944. timeout => 20,
  4945. noshutdown => 1,
  4946. data => { access_token => $iohash->{access_token}, app_type => 'app_security', },
  4947. hash => $hash,
  4948. type => 'dropwebhook',
  4949. callback => \&netatmo_dispatch,
  4950. });
  4951. }
  4952. sub
  4953. netatmo_webhookStatus($$$)
  4954. {
  4955. my($hash, $json, $hookstate) = @_;
  4956. my $name = $hash->{NAME};
  4957. Log3 $name, 4, "$name: webhookStatus ($hookstate)";
  4958. if( $json ) {
  4959. $hash->{status} = $json->{status};
  4960. $hash->{status} = $json->{error}{message} if( $json->{error} );
  4961. $hookstate = "error" if( $json->{error} );
  4962. readingsSingleUpdate($hash, "webhook", $hookstate, 1);
  4963. }
  4964. else
  4965. {
  4966. $hash->{status} = "error";
  4967. readingsSingleUpdate($hash, "webhook", "error", 1);
  4968. }
  4969. return ( "text/plain; charset=utf-8",
  4970. "JSON" );
  4971. }
  4972. sub netatmo_Webhook() {
  4973. my ($request) = @_;
  4974. my $hash = $modules{"netatmo"}{defptr}{"WEBHOOK"};
  4975. if(!defined($hash)){
  4976. Log3 "netatmo", 1, "Netatmo webhook hash not defined!";
  4977. return ( "text/plain; charset=utf-8",
  4978. "HASH" );
  4979. }
  4980. my $name = $hash->{NAME};
  4981. my ($link,$data);
  4982. if ( $request =~ m,^(\/[^/]+?)(?:\&|\?|\/\?|\/)(.*)?$, ) {
  4983. $link = $1;
  4984. $data = $2;
  4985. } else {
  4986. Log3 "netatmo", 1, "Netatmo webhook no data received!";
  4987. return ( "text/plain; charset=utf-8",
  4988. "NO" );
  4989. }
  4990. Log3 $name, 5, "Netatmo webhook JSON:\n".$data;
  4991. my $json = eval { JSON->new->utf8(0)->decode($data) };
  4992. if($@)
  4993. {
  4994. Log3 $name, 2, "$name: invalid json evaluation for webhook ".$@;
  4995. return undef;
  4996. }
  4997. readingsBeginUpdate($hash);
  4998. if(defined($json->{message})){
  4999. my $eventmessage = $json->{message};
  5000. $eventmessage =~ s/<\/b>//g;
  5001. $eventmessage =~ s/<\/b>//g;
  5002. readingsBulkUpdate( $hash, "state", $eventmessage );
  5003. }
  5004. readingsBulkUpdate( $hash, "event_type", $json->{event_type} ) if(defined($json->{event_type}));
  5005. readingsBulkUpdate( $hash, "camera_id", $json->{camera_id} ) if(defined($json->{camera_id}));
  5006. readingsBulkUpdate( $hash, "module_id", $json->{module_id} ) if(defined($json->{module_id}));
  5007. readingsBulkUpdate( $hash, "person_id", $json->{persons}[0]{id} ) if(defined($json->{persons}[0]{id}));
  5008. if(defined($json->{snapshot_id})) {
  5009. readingsBulkUpdate( $hash, "snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$json->{snapshot_id}."&key=".$json->{snapshot_key}, 1 );
  5010. }
  5011. elsif(defined($json->{persons}[0]{face_id})) {
  5012. readingsBulkUpdate( $hash, "snapshot", "https://api.netatmo.com/api/getcamerapicture?image_id=".$json->{persons}[0]{face_id}."&key=".$json->{persons}[0]{face_key}, 1 );
  5013. }
  5014. readingsEndUpdate( $hash, 1 );
  5015. if(AttrVal($name,"webhookPoll","0") eq "1" && defined($json->{home_id}))
  5016. {
  5017. my $home = $modules{$hash->{TYPE}}{defptr}{"H$json->{home_id}"};
  5018. netatmo_poll($home) if($home->{status} !~ /usage/ && $home->{status} !~ /too_many_connections/ && $home->{status} !~ /postponed/);;
  5019. }
  5020. return ( "text/plain; charset=utf-8",
  5021. "{\"status\":\"ok\"}" );
  5022. }
  5023. sub netatmo_Attr($$$)
  5024. {
  5025. my ($cmd, $name, $attrName, $attrVal) = @_;
  5026. my $orig = $attrVal;
  5027. $attrVal = int($attrVal) if($attrName eq "interval" || $attrName eq "setpoint_duration");
  5028. $attrVal = 15 if($attrName eq "setpoint_duration" && $attrVal < 15 && $attrVal != 0);
  5029. return undef if(!defined($defs{$name}));
  5030. if( $attrName eq "interval" ) {
  5031. my $hash = $defs{$name};
  5032. $attrVal = 60*5 if($hash->{SUBTYPE} ne "HOME" && $attrVal < 60*5 && $attrVal != 0);
  5033. #\$attrVal = 2700 if(($attrVal < 2700 && ($hash->{SUBTYPE} eq "ACCOUNT" || $hash->{SUBTYPE} eq "FORECAST");
  5034. $hash->{helper}{INTERVAL} = $attrVal if($attrVal);
  5035. $hash->{helper}{INTERVAL} = 60*30 if( !$hash->{helper}{INTERVAL} );
  5036. } elsif( $attrName eq "setpoint_duration" ) {
  5037. my $hash = $defs{$name};
  5038. #$hash->{SETPOINT_DURATION} = $attrVal;
  5039. #$hash->{SETPOINT_DURATION} = 60 if( !$hash->{SETPOINT_DURATION} );
  5040. } elsif( $attrName eq "serverAPI" ) {
  5041. my $hash = $defs{$name};
  5042. if( $cmd eq "set" && $attrVal ne "" ) {
  5043. $hash->{helper}{apiserver} = $attrVal;
  5044. } else {
  5045. $hash->{helper}{apiserver} = "api.netatmo.com";
  5046. }
  5047. } elsif( $attrName eq "disable" ) {
  5048. my $hash = $defs{$name};
  5049. RemoveInternalTimer($hash);
  5050. if( $cmd eq "set" && $attrVal ne "0" ) {
  5051. } else {
  5052. $attr{$name}{$attrName} = 0;
  5053. netatmo_poll($hash);
  5054. }
  5055. }
  5056. if( $cmd eq "set" ) {
  5057. if( $orig ne $attrVal ) {
  5058. $attr{$name}{$attrName} = $attrVal;
  5059. return $attrName ." set to ". $attrVal;
  5060. }
  5061. }
  5062. return;
  5063. }
  5064. sub netatmo_encrypt($)
  5065. {
  5066. my ($decoded) = @_;
  5067. my $key = getUniqueId();
  5068. my $encoded;
  5069. return $decoded if( $decoded =~ /crypt:/ );
  5070. for my $char (split //, $decoded) {
  5071. my $encode = chop($key);
  5072. $encoded .= sprintf("%.2x",ord($char)^ord($encode));
  5073. $key = $encode.$key;
  5074. }
  5075. return 'crypt:'.$encoded;
  5076. }
  5077. sub netatmo_decrypt($)
  5078. {
  5079. my ($encoded) = @_;
  5080. my $key = getUniqueId();
  5081. my $decoded;
  5082. return $encoded if( $encoded !~ /crypt:/ );
  5083. $encoded = $1 if( $encoded =~ /crypt:(.*)/ );
  5084. for my $char (map { pack('C', hex($_)) } ($encoded =~ /(..)/g)) {
  5085. my $decode = chop($key);
  5086. $decoded .= chr(ord($char)^ord($decode));
  5087. $key = $decode.$key;
  5088. }
  5089. return $decoded;
  5090. }
  5091. ##########################
  5092. sub netatmo_DbLog_splitFn($)
  5093. {
  5094. my ($event) = @_;
  5095. my ($reading, $value, $unit) = "";
  5096. my @parts = split(/ /,$event,3);
  5097. $reading = $parts[0];
  5098. $reading =~ tr/://d;
  5099. $value = $parts[1];
  5100. if($event =~ m/T: / && $event =~ m/H: /)
  5101. {
  5102. return undef; #dewpoint workaround - no logging
  5103. }
  5104. elsif($event =~ m/symbol/ || $event =~ m/message/)
  5105. {
  5106. $unit = ''; #symbols & text
  5107. }
  5108. elsif($event =~ m/trend/)
  5109. {
  5110. $unit = ''; #trends
  5111. }
  5112. elsif($event =~ m/date/ || $event =~ m/sunrise/ || $event =~ m/sunset/)
  5113. {
  5114. $unit = ''; #dates
  5115. }
  5116. elsif($event =~ m/temp/ || $event =~ m/dewpoint/)
  5117. {
  5118. $unit = "˚C";
  5119. }
  5120. elsif($event =~ m/humidity/)
  5121. {
  5122. $unit = '%';
  5123. }
  5124. elsif($event =~ m/pressure/)
  5125. {
  5126. $unit = 'mbar';
  5127. }
  5128. elsif($event =~ m/co2/)
  5129. {
  5130. $unit = 'ppm';
  5131. }
  5132. elsif($event =~ m/noise/)
  5133. {
  5134. $unit = 'dB';
  5135. }
  5136. elsif($event =~ m/rain/)
  5137. {
  5138. $unit = 'mm';
  5139. }
  5140. elsif($event =~ m/angle/ || $event =~ m/direction/)
  5141. {
  5142. $unit = "deg";
  5143. }
  5144. elsif($event =~ m/strength/ || $event =~ m/gust/)
  5145. {
  5146. $unit = 'km/h';
  5147. }
  5148. elsif($event =~ m/boilero/)
  5149. {
  5150. $unit = 'sec';
  5151. }
  5152. elsif($event =~ m/percent/)
  5153. {
  5154. $unit = '%';
  5155. }
  5156. elsif($event =~ m/sun/)
  5157. {
  5158. $unit = 'h';
  5159. }
  5160. elsif($event =~ m/air_/)
  5161. {
  5162. $unit = "ug/m3";
  5163. }
  5164. else
  5165. {
  5166. $value = $parts[1];
  5167. $value = $value." ".$parts[2] if(defined($parts[2]));
  5168. }
  5169. return ($reading, $value, $unit);
  5170. }
  5171. sub netatmo_weatherIcon()
  5172. {
  5173. my $svgheader = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">';
  5174. my $svgcontent = '<path id="smallcloud" opacity="1.0" fill="#000000" d="M162.8,46.7c-7.4-5.8-16.5-9.5-26.5-9.5C128.8,14.8,108.1,0,84.3,0h-1.6';
  5175. $svgcontent .= ' c-1.1,0-2.2,0-3.3,0.1C71.4,0.7,62,3.1,58,6.9V6.6c0,0.1-0.2,0.2-0.3,0.3c-12.2,6.9-21.2,18-25.4,32.3C13.2,45.1-0.1,62.1-0.1,82.8';
  5176. $svgcontent .= ' c0,25.5,20.7,46.2,46.2,46.2h88.6c25.5,0,45.6-20.8,45.6-46.2c0-5.3-0.5-10.6-2.7-15.9C173.5,56.2,171.8,52.7,162.8,46.7z';
  5177. $svgcontent .= ' M134.7,104H46.1c-11.7,0-20.7-9.6-20.7-21.2c0-10.6,8-19.6,18.6-20.7l8-1.1c2.1,0,2.7-0.5,2.7-2.7l1.1-7.4';
  5178. $svgcontent .= ' c1.6-14.8,13.8-26,28.6-26c15.4,0,27.6,11.1,29.2,26l1.1,8.5c0.5,1.6,1.6,2.6,3.2,2.6h17c11.1,0,20.7,9.6,20.7,20.7';
  5179. $svgcontent .= ' C155.3,94.4,145.8,104,134.7,104z"/>';
  5180. my $svgfooter = '</svg>';
  5181. return $svgheader . $svgcontent . $svgfooter;
  5182. }
  5183. 1;
  5184. =pod
  5185. =item device
  5186. =item summary Netatmo weather stations, thermostats and cameras connected via the official API
  5187. =begin html
  5188. <a name="netatmo"></a>
  5189. <h3>netatmo</h3>
  5190. <ul>
  5191. FHEM module for netatmo weather stations, thermostats and cameras.<br><br>
  5192. Notes:
  5193. <ul>
  5194. <li>JSON has to be installed on the FHEM host.</li>
  5195. <li>You need to create an app <u><a href="https://dev.netatmo.com/dev/createanapp">here</a></u> to get your <i>client_id / client_secret</i>.<br />Request the full access scope including cameras and thermostats.</li>
  5196. </ul><br>
  5197. <a name="netatmo_Define"></a>
  5198. <b>Define</b>
  5199. <ul>
  5200. <code>define &lt;name&gt; netatmo [ACCOUNT] &lt;username&gt; &lt;password&gt; &lt;client_id&gt; &lt;client_secret&gt;</code><br>
  5201. <code>define &lt;name&gt; netatmo &lt;device&gt;</code><br>
  5202. <br>
  5203. Defines a netatmo device.<br><br>
  5204. If a netatmo device of the account type is created all fhem devices for the netatmo devices are automaticaly created
  5205. (if autocreate is not disabled).
  5206. <br>
  5207. Examples:
  5208. <ul>
  5209. <code>define netatmo netatmo ACCOUNT abc@test.com myPassword 2134123412399119d4123134 AkqcOIHqrasfdaLKcYgZasd987123asd</code><br>
  5210. <code>define netatmo netatmo 2f:13:2b:93:12:31</code><br>
  5211. <code>define netatmo netatmo MODULE 2f:13:2b:93:12:31 f1:32:b9:31:23:11</code><br>
  5212. <code>define netatmo netatmo HOME 1234567890abcdef12345678</code><br>
  5213. <code>define netatmo netatmo CAMERA 1234567890abcdef12345678 70:ee:12:34:56:78</code><br>
  5214. <code>define netatmo netatmo PERSON 1234567890abcdef12345678 01234567-89ab-cdef-0123-456789abcdef</code><br>
  5215. </ul>
  5216. </ul><br>
  5217. <a name="netatmo_Webhook"></a>
  5218. <b>Webhook</b><br>
  5219. <ul>
  5220. <code>define netatmo netatmo WEBHOOK</code><br><br>
  5221. Set your URL in attribute webhookURL, events from cameras will be received insantly
  5222. </ul><br>
  5223. <a name="netatmo_Readings"></a>
  5224. <b>Readings</b>
  5225. <ul>
  5226. </ul><br>
  5227. <a name="netatmo_Set"></a>
  5228. <b>Set</b>
  5229. <ul>
  5230. <li>autocreate<br>
  5231. Create fhem devices for all netatmo weather devices.</li>
  5232. <li>autocreate_homes<br>
  5233. Create fhem devices for all netatmo homes, cameras and persons.</li>
  5234. <li>autocreate_thermostats<br>
  5235. Create fhem devices for all netatmo relays and thermostats.</li>
  5236. <li>autocreate_homecoachs<br>
  5237. Create fhem devices for all netatmo homecoachs.</li>
  5238. </ul><br>
  5239. <a name="netatmo_Get"></a>
  5240. <b>Get</b><br />
  5241. ACCOUNT
  5242. <ul>
  5243. <li>devices<br>
  5244. list the netatmo weather devices for this account</li>
  5245. <li>home<br>
  5246. list the netatmo home devices for this account</li>
  5247. <li>update<br>
  5248. trigger a global update for dashboard data</li>
  5249. <li>public [&lt;address&gt;] &lt;args&gt;<br>
  5250. no arguments -> get all public stations in a radius of 0.025&deg; around global fhem latitude/longitude<br>
  5251. &lt;rad&gt; -> get all public stations in a radius of &lt;rad&gt;&deg; around global fhem latitude/longitude<br>
  5252. &lt;lat&gt; &lt;lon&gt; [&lt;rad&gt;] -> get all public stations in a radius of 0.025&deg; or &lt;rad&gt;&deg; around &lt;lat&gt;/&lt;lon&gt;<br>
  5253. &lt;lat1&gt; &lt;lon1&gt; &lt;lat2&gt; &lt;lon2&gt; -> get all public stations in the area of &lt;lat1&gt; &lt;lon2&gt; &lt;lat2&gt; &lt;lon2&gt;<br>
  5254. if &lt;address&gt; is given then list stations in the area of this address. can be given as 5 digit german postal code or a: followed by a textual address. all spaces have to be replaced by a +.<br>
  5255. &lt;lat&gt; &lt;lon&gt; values can also be entered as a single coordinates parameter &lt;lat&gt;,&lt;lon&gt;<br></li>
  5256. </ul><br>
  5257. DEVICE/MODULE
  5258. <ul>
  5259. <li>update<br>
  5260. update the device readings</li>
  5261. <li>updateAll<br>
  5262. update the device readings after deleting all current readings</li>
  5263. </ul><br>
  5264. HOME
  5265. <ul>
  5266. <li>update<br>
  5267. update the home events and all camera and person readings</li>
  5268. </ul><br>
  5269. CAMERA
  5270. <ul>
  5271. <li>ping<br>
  5272. ping the camera and get the local command url</li>
  5273. <li>live/_local<br>
  5274. get the playlist for live video (internet or local network)</li>
  5275. <li>video/_local &lt;video_id&gt;<br>
  5276. get the playlist for a video id (internet or local network)</li>
  5277. </ul><br>
  5278. PRESENCE
  5279. <ul>
  5280. <li>config<br>
  5281. read the camera config</li>
  5282. <li>timelapse<br>
  5283. get the link for a timelapse video (local network)</li>
  5284. </ul><br>
  5285. PERSON
  5286. <ul>
  5287. <li>update<br>
  5288. n/a</li>
  5289. </ul><br>
  5290. <a name="netatmo_Attr"></a>
  5291. <b>Attributes</b>
  5292. <ul>
  5293. <li>interval<br>
  5294. the interval in seconds used to check for new values.</li>
  5295. <li>disable<br>
  5296. 1 -> stop polling</li>
  5297. <li>addresslimit<br>
  5298. maximum number of addresses to resolve in public station searches (ACCOUNT - default: 10)</li>
  5299. <li>setpoint_duration<br>
  5300. setpoint duration in minutes (THERMOSTAT - default: 60)</li>
  5301. <li>videoquality<br>
  5302. video quality for playlists (HOME - default: medium)</li>
  5303. <li>webhookURL<br>
  5304. webhook URL - can include basic auth and ports: http://user:pass@your.url:8080/fhem/netatmo (WEBHOOK)</li>
  5305. <li>webhookPoll<br>
  5306. poll home after event from webhook (WEBHOOK - default: 0)</li>
  5307. <li>ignored_device_ids<br>
  5308. ids of devices/persons ignored on autocrate (ACCOUNT - comma separated)</li>
  5309. </ul>
  5310. </ul>
  5311. =end html
  5312. =cut