38_netatmo.pm 235 KB

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