38_netatmo.pm 188 KB

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