32_withings.pm 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595
  1. ##############################################################################
  2. # $Id: 32_withings.pm 14576 2017-06-25 22:46:20Z moises $
  3. #
  4. # 32_withings.pm
  5. #
  6. # 2017 Markus M.
  7. # Based on original code by justme1968
  8. #
  9. # https://forum.fhem.de/index.php/topic,64944.0.html
  10. #
  11. #
  12. ##############################################################################
  13. # Release 04 / 2017-06-25
  14. package main;
  15. use strict;
  16. use warnings;
  17. use HttpUtils;
  18. use JSON;
  19. use POSIX qw( strftime );
  20. use Time::Local qw(timelocal);
  21. use Digest::SHA qw(hmac_sha1_base64);
  22. #use Encode qw(encode);
  23. #use LWP::Simple;
  24. #use HTTP::Request;
  25. #use HTTP::Cookies;
  26. #use URI::Escape qw(uri_escape);
  27. use Data::Dumper;
  28. #use Digest::MD5 qw(md5 md5_hex md5_base64);
  29. my %device_types = ( 0 => "User related",
  30. 1 => "Body Scale",
  31. 2 => "Camera",
  32. 4 => "Blood Pressure Monitor",
  33. 16 => "Activity Tracker",
  34. 32 => "Sleep Monitor",
  35. 64 => "Thermometer", );
  36. my %device_models = ( 1 => { 1 => "Smart Scale", 2 => "Wireless Scale", 3 => "Smart Kid Scale", 4 => "Smart Body Analyzer", 5 => "WiFi Body Scale", 6 => "Cardio Scale", 7 => "Body Scale", },
  37. 2 => { 21 => "Smart Baby Monitor", 22 => "Withings Home", },
  38. 4 => { 41 => "iOS Blood Pressure Monitor", 42 => "Wireless Blood Pressure Monitor", },
  39. 16 => { 51 => "Pulse Ox", 52 => "Activite", 53 => "Activite v2", 54 => "Withings Go", 55 => "Withings Steel HR", },
  40. 32 => { 60 => "Withings Aura", 61 => "Aura Sleep Sensor", },
  41. 64 => { 70 => "Withings Thermo", }, );
  42. #Firmware files: cdnfw_withings_net
  43. #Smart Body Analyzer: /wbs02/wbs02_1521.bin
  44. #Blood Pressure Monitor: /wpm02/wpm02_251.bin
  45. #Pulse: /wam01/wam01_1761.bin
  46. #Aura: /wsd01/wsd01_607.bin
  47. #Aura Mat: /wsm01/wsm01_711.bin
  48. #Home: /wbp02/wbp02_168.bin
  49. #Activite: /hwa01/hwa01_1070.bin
  50. my %measure_types = ( 1 => { name => "Weight (kg)", reading => "weight", },
  51. 4 => { name => "Height (meter)", reading => "height", },
  52. 5 => { name => "Lean Mass (kg)", reading => "fatFreeMass", },
  53. 6 => { name => "Fat Mass (%)", reading => "fatRatio", },
  54. 7 => { name => "Lean Mass (%)", reading => "fatFreeRatio", },
  55. 8 => { name => "Fat Mass (kg)", reading => "fatMassWeight", },
  56. 9 => { name => "Diastolic Blood Pressure (mmHg)", reading => "diastolicBloodPressure", },
  57. 10 => { name => "Systolic Blood Pressure (mmHg)", reading => "systolicBloodPressure", },
  58. 11 => { name => "Heart Rate (bpm)", reading => "heartPulse", },
  59. 12 => { name => "Temperature (°C)", reading => "temperature", },
  60. 13 => { name => "Humidity (%)", reading => "humidity", },
  61. 14 => { name => "unknown 14", reading => "unknown14", }, #device? event home - peak sound level?
  62. 15 => { name => "Noise (dB)", reading => "noise", },
  63. 18 => { name => "Weight Objective Speed", reading => "weightObjectiveSpeed", },
  64. 19 => { name => "Breastfeeding (s)", reading => "breastfeeding", }, #baby
  65. 20 => { name => "Bottle (ml)", reading => "bottle", }, #baby
  66. 22 => { name => "BMI", reading => "bmi", }, #user? goals
  67. 35 => { name => "CO2 (ppm)", reading => "co2", },
  68. 36 => { name => "Steps", reading => "steps", dailyreading => "dailySteps", }, #aggregate
  69. 37 => { name => "Elevation (m)", reading => "elevation", dailyreading => "dailyElevation", }, #aggregate
  70. 38 => { name => "Active Calories (kcal)", reading => "calories", dailyreading => "dailyCalories", }, #aggregate
  71. 39 => { name => "Intensity", reading => "intensity", }, #intraday only
  72. 40 => { name => "Distance (m)", reading => "distance", dailyreading => "dailyDistance", }, #aggregate #measure
  73. 41 => { name => "Descent (m)", reading => "descent", dailyreading => "dailyDescent", }, #descent #aggregate #measure ??sleepreading!
  74. 42 => { name => "Activity Type", reading => "activityType", }, #intraday only 1:walk 2:run
  75. 43 => { name => "Duration (s)", reading => "duration", }, #intraday only
  76. 44 => { name => "Sleep State", reading => "sleepstate", }, #intraday #aura mat
  77. 47 => { name => "MyFitnessPal Calories (kcal)", reading => "caloriesMFP", },
  78. 48 => { name => "Active Calories (kcal)", reading => "caloriesActive", dailyreading => "dailyCaloriesActive", }, #day summary
  79. 49 => { name => "Idle Calories (kcal)", reading => "caloriesPassive", dailyreading => "dailyCaloriesPassive", }, #aggregate
  80. 50 => { name => "unknown 50", reading => "unknown50", dailyreading => "dailyUnknown50", }, #day summary pulse 60k-80k #aggregate
  81. 51 => { name => "Light Activity (s)", reading => "durationLight", dailyreading => "dailyDurationLight", }, #aggregate
  82. 52 => { name => "Moderate Activity (s)", reading => "durationModerate", dailyreading => "dailyDurationModerate", }, #aggregate
  83. 53 => { name => "Intense Activity (s)", reading => "durationIntense", dailyreading => "dailyDurationIntense", }, #aggregate
  84. 54 => { name => "SpO2 (%)", reading => "spo2", },
  85. 56 => { name => "Ambient light (lux)", reading => "light", }, # aura device
  86. 57 => { name => "Respiratory rate", reading => "breathing", }, # aura mat #measure vasistas
  87. 58 => { name => "Air Quality (ppm)", reading => "voc", }, # Home Air Quality
  88. 59 => { name => "unknown 59", reading => "unknown59", }, #
  89. 60 => { name => "unknown 60", reading => "unknown60", }, # aura mat #measure vasistas 20-200 peak 800
  90. 61 => { name => "unknown 61", reading => "unknown61", }, # aura mat #measure vasistas 10-60 peak 600
  91. 62 => { name => "unknown 62", reading => "unknown62", }, # aura mat #measure vasistas 20-100
  92. 63 => { name => "unknown 63", reading => "unknown63", }, # aura mat #measure vasistas 0-100
  93. 64 => { name => "unknown 64", reading => "unknown64", }, # aura mat #measure vasistas 800-1300
  94. 65 => { name => "unknown 65", reading => "unknown65", }, # aura mat #measure vasistas 3000-4500 peak 5000
  95. 66 => { name => "unknown 66", reading => "unknown66", }, # aura mat #measure vasistas 4000-7000
  96. 67 => { name => "unknown 67", reading => "unknown67", }, # aura mat #measure vasistas 0-500 peak 1500
  97. 68 => { name => "unknown 68", reading => "unknown68", }, # aura mat #measure vasistas 0-1500
  98. 69 => { name => "unknown 69", reading => "unknown69", }, # aura mat #measure vasistas 0-6000 peak 10000
  99. 70 => { name => "unknown 70", reading => "unknown70", }, #?
  100. 71 => { name => "Body Temperature (°C)", reading => "bodyTemperature", }, #thermo
  101. 73 => { name => "Skin Temperature (°C)", reading => "skinTemperature", }, #thermo
  102. 76 => { name => "Muscle Mass (kg)", reading => "muscleMass", }, # cardio scale
  103. 77 => { name => "Water Mass (kg)", reading => "waterMass", }, # cardio scale
  104. 78 => { name => "unknown 78", reading => "unknown78", }, # cardio scale
  105. 79 => { name => "unknown 79", reading => "unknown79", }, # body scale
  106. 80 => { name => "unknown 80", reading => "unknown80", }, # body scale
  107. 86 => { name => "unknown 86", reading => "unknown86", }, # body scale
  108. 87 => { name => "Active Calories (kcal)", reading => "caloriesActive", dailyreading => "dailyCaloriesActive", }, # measures list sleepreading!
  109. 88 => { name => "Bone Mass (kg)", reading => "boneMassWeight", },
  110. 89 => { name => "unknown 89", reading => "unknown89", },
  111. 90 => { name => "unknown 90", reading => "unknown90", }, #pulse
  112. 91 => { name => "Pulse Wave Velocity (m/s)", reading => "pulseWave", }, # new weight
  113. 93 => { name => "Muscle Mass (%)", reading => "muscleRatio", }, # cardio scale
  114. 94 => { name => "Bone Mass (%)", reading => "boneRatio", }, # cardio scale
  115. 95 => { name => "Hydration (%)", reading => "hydration", }, # body water
  116. #-10 => { name => "Speed", reading => "speed", },
  117. #-11 => { name => "Pace", reading => "pace", },
  118. #-12 => { name => "Altitude", reading => "altitude", },
  119. );
  120. my %activity_types = ( 0 => "None",
  121. 1 => "Walking",
  122. 2 => "Running",
  123. 3 => "Hiking",
  124. 4 => "Skating",
  125. 5 => "BMX",
  126. 6 => "Cycling",
  127. 7 => "Swimming",
  128. 8 => "Surfing",
  129. 9 => "Kitesurfing",
  130. 10 => "Windsurfing",
  131. 11 => "Bodyboard",
  132. 12 => "Tennis",
  133. 13 => "Ping Pong",
  134. 14 => "Squash",
  135. 15 => "Badminton",
  136. 16 => "Weights",
  137. 17 => "Calisthenics",
  138. 18 => "Elliptical",
  139. 19 => "Pilates",
  140. 20 => "Basketball",
  141. 21 => "Soccer",
  142. 22 => "Football",
  143. 23 => "Rugby",
  144. 24 => "Vollyball",
  145. 25 => "Water Polo",
  146. 26 => "Horse Riding",
  147. 27 => "Golf",
  148. 28 => "Yoga",
  149. 29 => "Dancing",
  150. 30 => "Boxing",
  151. 31 => "Fencing",
  152. 32 => "Wrestling",
  153. 33 => "Martial Arts",
  154. 34 => "Skiing",
  155. 35 => "Snowboarding",
  156. 36 => "Other",
  157. 37 => "Sleep",
  158. 127 => "Sleep Debug",
  159. 128 => "No Activity",
  160. 187 => "Rowing",
  161. 188 => "Zumba",
  162. 190 => "Base",
  163. 191 => "Baseball",
  164. 192 => "Handball",
  165. 193 => "Hockey",
  166. 194 => "Ice Hockey",
  167. 195 => "Climbing",
  168. 196 => "Ice Skating",
  169. 271 => "Multi Sports",
  170. 272 => "Multi Sport", );
  171. my %sleep_state = ( 0 => "awake",
  172. 1 => "light sleep",
  173. 2 => "deep sleep",
  174. 3 => "REM sleep", );
  175. my %weight_units = ( 1 => { name => "kg (metric)", unit => "kg", },
  176. 2 => { name => "lb (US imperial)", unit => "lb", },
  177. 5 => { name => "stlb (UK imperial)", unit => "st", },
  178. 14 => { name => "stlb (UK imperial)", unit => "st", }, );
  179. my %distance_units = ( 6 => { name => "km", unit => "km", },
  180. 7 => { name => "miles", unit => "mi", }, );
  181. my %temperature_units = ( 11 => { name => "Celsius", unit => "˚C", },
  182. 13 => { name => "Fahrenheit", unit => "˚F", }, );
  183. my %height_units = ( 6 => { name => "cm", unit => "cm", },
  184. 7 => { name => "ft", unit => "ft", }, );
  185. my %aggregate_range = ( 1 => "day",
  186. 2 => "week",
  187. 3 => "month",
  188. 4 => "year",
  189. 5 => "alltime", );
  190. my %event_types = ( 10 => { name => "Noise", reading => "alertNoise", threshold => "levelNoise", duration => "durationNoise", unit => 0, },
  191. 11 => { name => "Motion", reading => "alertMotion", threshold => "levelMotion", duration => "durationMotion", unit => -2, },
  192. 12 => { name => "Low Temperature", reading => "alertTemperatureLow", threshold => "levelTemperatureLow", duration => "dummy", unit => -2, },
  193. 13 => { name => "High Temperature", reading => "alertTemperatureHigh", threshold => "levelTemperatureHigh", duration => "dummy", unit => -2, },
  194. 14 => { name => "Low Humidity", reading => "alertHumidityLow", threshold => "levelHumidityLow", duration => "dummy", unit => -2, },
  195. 15 => { name => "High Humidity", reading => "alertHumidityHigh", threshold => "levelHumidityHigh", duration => "dummy", unit => -2, },
  196. 20 => { name => "Disconnection", reading => "alertDisconnection", threshold => "levelDisconnected", duration => "dummy", unit => 0, },
  197. );
  198. #
  199. my %timeline_classes = ( 'noise_detected' => { name => "Noise", reading => "alertNoise", unit => 0, },
  200. 'movement_detected' => { name => "Motion", reading => "alertMotion", unit => 0, },
  201. 'alert_environment' => { name => "Air Quality Alert", reading => "alertEnvironment", unit => 0, },
  202. 'period_activity' => { name => "Activity Period", reading => "periodActivity", unit => 0, },
  203. 'period_activity_start' => { name => "Activity Period Start", reading => "periodActivityStart", unit => 0, },
  204. 'period_activity_cancel' => { name => "Activity Period Cancel", reading => "periodActivityCancel", unit => 0, },
  205. 'period_offline' => { name => "Offline Period", reading => "periodDisconnection", unit => 0, },
  206. 'offline' => { name => "Disconnection", reading => "alertDisconnection", unit => 0, },
  207. 'online' => { name => "Connection", reading => "alertConnection", unit => 0, },
  208. 'deleted' => { name => "Deleted", reading => "alertDeleted", unit => 0, },
  209. 'snapshot' => { name => "Snapshot", reading => "alertSnapshot", unit => 0, },
  210. );
  211. my %sleep_readings = ( 'lightsleepduration' => { name => "Light Sleep", reading => "sleepDurationLight", unit => "s", },
  212. 'deepsleepduration' => { name => "Deep Sleep", reading => "sleepDurationDeep", unit => "s", },
  213. 'remsleepduration' => { name => "REM Sleep", reading => "sleepDurationREM", unit => "s", },
  214. 'wakeupduration' => { name => "Awake In Bed", reading => "sleepDurationAwake", unit => "s", },
  215. 'wakeupcount' => { name => "Wakeup Count", reading => "wakeupCount", unit => 0, },
  216. 'durationtosleep' => { name => "Duration To Sleep", reading => "durationToSleep", unit => "s", },
  217. 'durationtowakeup' => { name => "Duration To Wake Up", reading => "durationToWakeUp", unit => "s", },
  218. 'sleepscore' => { name => "Sleep Score", reading => "sleepScore", unit => 0, },
  219. 'wsdid' => { name => "wsdid", reading => "wsdid", unit => 0, },
  220. 'hr_resting' => { name => "Resting HR", reading => "heartrateResting", unit => "bpm", },
  221. 'hr_min' => { name => "Minimum HR", reading => "heartrateMinimum", unit => "bpm", },
  222. 'hr_average' => { name => "Average HR", reading => "heartrateAverage", unit => "bpm", },
  223. 'hr_max' => { name => "Maximum HR", reading => "heartrateMaximum", unit => "bpm", },
  224. );
  225. my %alarm_sound = ( 0 => "Unknown",
  226. 1 => "Cloud Flakes",
  227. 2 => "Desert Wave",
  228. 3 => "Moss Forest",
  229. 4 => "Morning Smile",
  230. 5 => "Spotify",
  231. 6 => "Internet radio", );
  232. my %alarm_song = ( 'Unknown' => 0,
  233. 'Cloud Flakes' => 1,
  234. 'Desert Wave' => 2,
  235. 'Moss Forest' => 3,
  236. 'Morning Smile' => 4,
  237. 'Spotify' => 5,
  238. 'Internet radio' => 6, );
  239. my %nap_sound = ( 0 => "Unknown",
  240. 1 => "Celestial Piano (20 min)",
  241. 2 => "Cotton Cloud (10 min)",
  242. 3 => "Deep Smile (10 min)",
  243. 4 => "Sacred Forest (20 min)", );
  244. my %sleep_sound = ( 0 => "Unknown",
  245. 1 => "Moonlight Waves",
  246. 2 => "Siren's Whisper",
  247. 3 => "Celestial Piano",
  248. 4 => "Cloud Flakes",
  249. 5 => "Spotify",
  250. 6 => "Internet radio", );
  251. sub withings_Initialize($) {
  252. my ($hash) = @_;
  253. $hash->{DefFn} = "withings_Define";
  254. $hash->{SetFn} = "withings_Set";
  255. $hash->{GetFn} = "withings_Get";
  256. $hash->{NOTIFYDEV} = "global";
  257. $hash->{NotifyFn} = "withings_Notify";
  258. $hash->{UndefFn} = "withings_Undefine";
  259. $hash->{DbLog_splitFn} = "withings_DbLog_splitFn";
  260. $hash->{AttrFn} = "withings_Attr";
  261. $hash->{AttrList} = "IODev ".
  262. "disable:0,1 ".
  263. "intervalAlert ".
  264. "intervalData ".
  265. "intervalDebug ".
  266. "intervalProperties ".
  267. "intervalDaily ".
  268. "nossl:1 ".
  269. "IP ".
  270. "videoLinkEvents:1 ";
  271. $hash->{AttrList} .= $readingFnAttributes;
  272. Log3 "withings", 5, "withings: initialize";
  273. }
  274. #####################################
  275. sub withings_Define($$) {
  276. my ($hash, $def) = @_;
  277. Log3 "withings", 5, "withings: define ".$def;
  278. my @a = split("[ \t][ \t]*", $def);
  279. my $subtype;
  280. my $name = $a[0];
  281. if( @a == 3 ) {
  282. $subtype = "DEVICE";
  283. my $device = $a[2];
  284. $hash->{Device} = $device;
  285. my $d = $modules{$hash->{TYPE}}{defptr}{"D$device"};
  286. return "device $device already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  287. $modules{$hash->{TYPE}}{defptr}{"D$device"} = $hash;
  288. } elsif( @a == 5 && $a[2] =~ m/^\D+$/ && $a[3] =~ m/^\d+$/ ) {
  289. $subtype = "DUMMY";
  290. my $device = $a[2];
  291. my $user = $a[3];
  292. $hash->{Device} = $device;
  293. $hash->{typeID} = '16';
  294. $hash->{modelID} = '0';
  295. $hash->{User} = $user;
  296. CommandAttr(undef,"$name IODev $a[4]");
  297. } elsif( @a == 4 && $a[2] =~ m/^\d+$/ && $a[3] =~ m/^[\w-]+$/i ) {
  298. $subtype = "USER";
  299. my $user = $a[2];
  300. my $key = $a[3];
  301. $hash->{User} = $user;
  302. $hash->{Key} = $key;
  303. my $d = $modules{$hash->{TYPE}}{defptr}{"U$user"};
  304. return "device $user already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
  305. $modules{$hash->{TYPE}}{defptr}{"U$user"} = $hash;
  306. } elsif( @a == 4 || ($a[2] eq "ACCOUNT" && @a == 5 ) ) {
  307. $subtype = "ACCOUNT";
  308. my $user = $a[@a-2];
  309. my $pass = $a[@a-1];
  310. my $username = withings_encrypt($user);
  311. my $password = withings_encrypt($pass);
  312. Log3 $name, 3, "$name: encrypt $user/$pass to $username/$password" if($user ne $username || $pass ne $password);
  313. #$hash->{DEF} =~ s/$user/$username/g;
  314. #$hash->{DEF} =~ s/$pass/$password/g;
  315. $hash->{DEF} = "$username $password";
  316. $hash->{Clients} = ":withings:";
  317. $hash->{helper}{username} = $username;
  318. $hash->{helper}{password} = $password;
  319. $hash->{helper}{appliver} = '9855c478';
  320. $hash->{helper}{csrf_token} = '9855c478';
  321. } else {
  322. return "Usage: define <name> withings ACCOUNT <login> <password>" if(@a < 3 || @a > 5);
  323. }
  324. $hash->{NAME} = $name;
  325. $hash->{SUBTYPE} = $subtype;
  326. #CommandAttr(undef,"$name DbLogExclude .*");
  327. my $resolve = inet_aton("healthmate.withings.com");
  328. if(!defined($resolve))
  329. {
  330. $hash->{STATE} = "DNS error";
  331. InternalTimer( gettimeofday() + 900, "withings_InitWait", $hash, 0);
  332. return undef;
  333. }
  334. $hash->{STATE} = "Initialized";
  335. if( $init_done ) {
  336. withings_initUser($hash) if( $hash->{SUBTYPE} eq "USER" );
  337. withings_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
  338. withings_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
  339. InternalTimer(gettimeofday()+60, "withings_poll", $hash, 0) if( $hash->{SUBTYPE} eq "DUMMY" );
  340. }
  341. else
  342. {
  343. InternalTimer(gettimeofday()+15, "withings_InitWait", $hash, 0);
  344. }
  345. return undef;
  346. }
  347. sub withings_InitWait($) {
  348. my ($hash) = @_;
  349. Log3 "withings", 5, "withings: initwait ".$init_done;
  350. RemoveInternalTimer($hash);
  351. my $resolve = inet_aton("healthmate.withings.com");
  352. if(!defined($resolve))
  353. {
  354. $hash->{STATE} = "DNS error";
  355. InternalTimer( gettimeofday() + 1800, "withings_InitWait", $hash, 0);
  356. return undef;
  357. }
  358. if( $init_done ) {
  359. withings_initUser($hash) if( $hash->{SUBTYPE} eq "USER" );
  360. withings_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
  361. withings_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
  362. InternalTimer(gettimeofday()+60, "withings_poll", $hash, 0) if( $hash->{SUBTYPE} eq "DUMMY" );
  363. }
  364. else
  365. {
  366. InternalTimer(gettimeofday()+30, "withings_InitWait", $hash, 0);
  367. }
  368. return undef;
  369. }
  370. sub withings_Notify($$) {
  371. my ($hash,$dev) = @_;
  372. return if($dev->{NAME} ne "global");
  373. return if(!grep(m/^INITIALIZED|REREADCFG$/, @{$dev->{CHANGED}}));
  374. Log3 "withings", 5, "withings: notify";
  375. my $resolve = inet_aton("healthmate.withings.com");
  376. if(!defined($resolve))
  377. {
  378. $hash->{STATE} = "DNS error";
  379. InternalTimer( gettimeofday() + 3600, "withings_InitWait", $hash, 0);
  380. return undef;
  381. }
  382. withings_initUser($hash) if( $hash->{SUBTYPE} eq "USER" );
  383. withings_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
  384. withings_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
  385. }
  386. sub withings_Undefine($$) {
  387. my ($hash, $arg) = @_;
  388. Log3 "withings", 5, "withings: undefine";
  389. RemoveInternalTimer($hash);
  390. delete( $modules{$hash->{TYPE}}{defptr}{"U$hash->{User}"} ) if( $hash->{SUBTYPE} eq "USER" );
  391. delete( $modules{$hash->{TYPE}}{defptr}{"D$hash->{Device}"} ) if( $hash->{SUBTYPE} eq "DEVICE" );
  392. return undef;
  393. }
  394. sub withings_getToken($) {
  395. my ($hash) = @_;
  396. Log3 "withings", 5, "withings: gettoken";
  397. my $resolve = inet_aton("auth.withings.com");
  398. if(!defined($resolve))
  399. {
  400. Log3 "withings", 1, "withings: DNS error on getToken";
  401. return undef;
  402. }
  403. my ($err,$data) = HttpUtils_BlockingGet({
  404. url => $hash->{'.https'}."://auth.withings.com/index/service/once?action=get",
  405. timeout => 10,
  406. noshutdown => 1,
  407. data => {action => 'get'},
  408. });
  409. #my $URL = 'http://auth.withings.com/index/service/once?action=get';
  410. #my $agent = LWP::UserAgent->new(env_proxy => 1,keep_alive => 1, timeout => 30);
  411. #my $header = HTTP::Request->new(GET => $URL);
  412. #my $request = HTTP::Request->new('GET', $URL, $header);
  413. #my $response = $agent->request($request);
  414. return undef if(!defined($data));
  415. my $json = eval { JSON->new->utf8(0)->decode($data) };
  416. if($@)
  417. {
  418. Log3 "withings", 2, "withings: json evaluation error on getToken ".$@;
  419. return undef;
  420. }
  421. my $once = $json->{body}{once};
  422. $hash->{Once} = $once;
  423. my $hashstring = withings_decrypt($hash->{helper}{username}).':'.md5_hex(withings_decrypt($hash->{helper}{password})).':'.$once;
  424. $hash->{Hash} = md5_hex($hashstring);
  425. }
  426. sub withings_getSessionKey($) {
  427. my ($hash) = @_;
  428. my $name = $hash->{NAME};
  429. return if( $hash->{SUBTYPE} ne "ACCOUNT" );
  430. return if( $hash->{SessionKey} && $hash->{SessionTimestamp} && gettimeofday() - $hash->{SessionTimestamp} < (60*60*24*7-3600) );
  431. my $resolve = inet_aton("account.health.nokia.com");
  432. if(!defined($resolve))
  433. {
  434. $hash->{SessionTimestamp} = 0;
  435. Log3 "withings", 1, "$name: DNS error on getSessionData";
  436. return undef;
  437. }
  438. $hash->{'.https'} = "https" if(!defined($hash->{'.https'}));
  439. # my $data1;
  440. # if( !defined($hash->{helper}{appliver}) || !defined($hash->{helper}{csrf_token}) || !defined($hash->{SessionTimestamp}) || gettimeofday() - $hash->{SessionTimestamp} > (30*60) )#!defined($hash->{helper}{appliver}) || !defined($hash->{helper}{csrf_token}))
  441. # {
  442. # my($err0,$data0) = HttpUtils_BlockingGet({
  443. # url => $hash->{'.https'}."://healthmate.withings.com/",
  444. # timeout => 10,
  445. # noshutdown => 1,
  446. # });
  447. # if($err0 || !defined($data0))
  448. # {
  449. # Log3 "withings", 1, "$name: appliver call failed! ".$err0;
  450. # return undef;
  451. # }
  452. # $data1 = $data0;
  453. # $data0 =~ /appliver=([^.*]+)\&/;
  454. # $hash->{helper}{appliver} = $1;
  455. # if(!defined($hash->{helper}{appliver})) {
  456. # Log3 "withings", 1, "$name: APPLIVER ERROR ";
  457. # $hash->{STATE} = "APPLIVER error";
  458. # return undef;
  459. # }
  460. # Log3 "withings", 4, "$name: appliver ".$hash->{helper}{appliver};
  461. # #}
  462. #
  463. #
  464. # #if( !defined($hash->{helper}{csrf_token}) )
  465. # #{
  466. # $data1 =~ /csrf_token" value="(.*)"/;
  467. # $hash->{helper}{csrf_token} = $1;
  468. #
  469. # if(!defined($hash->{helper}{csrf_token})) {
  470. # Log3 "withings", 1, "$name: CSRF ERROR ";
  471. # $hash->{STATE} = "CSRF error";
  472. # return undef;
  473. # }
  474. # Log3 "withings", 4, "$name: csrf_token ".$hash->{helper}{csrf_token};
  475. #}
  476. #my $ua = LWP::UserAgent->new;
  477. #my $request = HTTP::Request->new(POST => $hash->{'.https'}.'://account.withings.com/connectionuser/account_login?appname=my2&appliver='.$hash->{helper}{appliver}.'&r=https%3A%2F%2Fhealthmate.withings.com%2F',[email => withings_decrypt($hash->{helper}{username}), password => withings_decrypt($hash->{helper}{password}), is_admin => '',]);
  478. #my $get_data = 'use_authy=&is_admin=&email='.uri_escape(withings_decrypt($hash->{helper}{username})).'&password='.uri_escape(withings_decrypt($hash->{helper}{password}));
  479. #$request->content($get_data);
  480. #my $response = $ua->request($request);
  481. # $resolve = inet_aton("account.health.nokia.com");
  482. # if(!defined($resolve))
  483. # {
  484. # Log3 "withings", 1, "$name: DNS error on getSessionKey.";
  485. # return undef;
  486. # }
  487. my $datahash = {
  488. url => $hash->{'.https'}."://account.health.nokia.com/connectionwou/account_login?r=https://dashboard.health.nokia.com/",
  489. timeout => 10,
  490. noshutdown => 1,
  491. ignoreredirects => 1,
  492. data => { email=> withings_decrypt($hash->{helper}{username}), password => withings_decrypt($hash->{helper}{password}), is_admin => '' },
  493. };
  494. my($err,$data) = HttpUtils_BlockingGet($datahash);
  495. if ($err || !defined($data) || $data =~ /Authentification failed/ || $data =~ /not a valid/)
  496. {
  497. Log3 "withings", 1, "$name: LOGIN ERROR ";
  498. $hash->{STATE} = "Login error";
  499. return undef;
  500. }
  501. else
  502. {
  503. if ($datahash->{httpheader} =~ /session_key=(.*?);/)
  504. {
  505. $hash->{SessionKey} = $1;
  506. $hash->{SessionTimestamp} = (gettimeofday())[0] if( $hash->{SessionKey} );
  507. $hash->{STATE} = "Connected" if( $hash->{SessionKey} );
  508. $hash->{STATE} = "Session error" if( !$hash->{SessionKey} );
  509. Log3 "withings", 4, "$name: sessionkey ".$hash->{SessionKey};
  510. }
  511. else
  512. {
  513. $hash->{STATE} = "Cookie error";
  514. Log3 "withings", 1, "$name: COOKIE ERROR ";
  515. $hash->{helper}{appliver} = '9855c478';
  516. $hash->{helper}{csrf_token} = '9855c478';
  517. return undef;
  518. }
  519. }
  520. if( !$hash->{AccountID} || length($hash->{AccountID} < 2 ) ) {
  521. ($err,$data) = HttpUtils_BlockingGet({
  522. url => $hash->{'.https'}."://healthmate.withings.com/index/service/account",
  523. timeout => 10,
  524. noshutdown => 1,
  525. data => {sessionid => $hash->{SessionKey}, appname => 'my2', appliver=> $hash->{helper}{appliver}, apppfm => 'web', action => 'get'},
  526. });
  527. return undef if(!defined($data));
  528. if( $data =~ m/^{.*}$/ )
  529. {
  530. my $json = eval { JSON->new->utf8(0)->decode($data) };
  531. if($@)
  532. {
  533. Log3 $name, 2, "$name: json evaluation error on getSessionKey ".$@;
  534. return undef;
  535. }
  536. foreach my $account (@{$json->{body}{account}}) {
  537. next if( !defined($account->{id}) );
  538. if($account->{email} eq withings_decrypt($hash->{helper}{username}))
  539. {
  540. $hash->{AccountID} = $account->{id};
  541. }
  542. else
  543. {
  544. Log3 "withings", 4, "$name: account email: ".$account->{email};
  545. }
  546. }
  547. Log3 "withings", 4, "$name: accountid ".$hash->{AccountID};
  548. }
  549. else
  550. {
  551. $hash->{STATE} = "Account error";
  552. Log3 "withings", 1, "$name: ACCOUNT ERROR ";
  553. return undef;
  554. }
  555. }
  556. }
  557. sub withings_connect($) {
  558. my ($hash) = @_;
  559. my $name = $hash->{NAME};
  560. Log3 "withings", 5, "$name: connect";
  561. $hash->{'.https'} = "https";
  562. $hash->{'.https'} = "http" if( AttrVal($name, "nossl", 0) );
  563. #my $cmdret= CommandAttr(undef,"$name room WithingsTest");
  564. #$cmdret= CommandAttr(undef,"$name verbose 5");
  565. withings_getSessionKey( $hash );
  566. foreach my $d (keys %defs) {
  567. next if(!defined($defs{$d}));
  568. next if($defs{$d}{TYPE} ne "autocreate");
  569. return undef if(AttrVal($defs{$d}{NAME},"disable",undef));
  570. }
  571. my $autocreated = 0;
  572. my $users = withings_getUsers($hash);
  573. foreach my $user (@{$users}) {
  574. if( defined($modules{$hash->{TYPE}}{defptr}{"U$user->{id}"}) ) {
  575. Log3 $name, 2, "$name: user '$user->{id}' already defined";
  576. next;
  577. }
  578. next if($user->{firstname} eq "Repository-User");
  579. my $id = $user->{id};
  580. my $devname = "withings_U". $id;
  581. my $define= "$devname withings $id $user->{publickey}";
  582. Log3 $name, 2, "$name: create new device '$devname' for user '$id'";
  583. my $cmdret= CommandDefine(undef,$define);
  584. if($cmdret) {
  585. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  586. } else {
  587. $cmdret= CommandAttr(undef,"$devname alias ".$user->{shortname});
  588. #$cmdret= CommandAttr(undef,"$devname room WithingsTest");
  589. $cmdret= CommandAttr(undef,"$devname IODev $name");
  590. #$cmdret= CommandAttr(undef,"$devname disable 1");
  591. #$cmdret= CommandAttr(undef,"$devname verbose 5");
  592. $autocreated++;
  593. }
  594. }
  595. my $devices = withings_getDevices($hash);
  596. foreach my $device (@{$devices}) {
  597. if( defined($modules{$hash->{TYPE}}{defptr}{"D$device->{deviceid}"}) ) {
  598. my $d = $modules{$hash->{TYPE}}{defptr}{"D$device->{deviceid}"};
  599. $d->{association} = $device->{association} if($device->{association});
  600. Log3 $name, 2, "$name: device '$device->{deviceid}' already defined";
  601. next;
  602. }
  603. my $detail = $device->{deviceproperties};
  604. next if( !defined($detail->{id}) );
  605. my $id = $detail->{id};
  606. my $devname = "withings_D". $id;
  607. my $define= "$devname withings $id";
  608. Log3 $name, 2, "$name: create new device '$devname' for device '$id'";
  609. my $cmdret= CommandDefine(undef,$define);
  610. if($cmdret) {
  611. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  612. } else {
  613. $cmdret= CommandAttr(undef,"$devname alias ".$device_types{$detail->{type}}) if( defined($device_types{$detail->{type}}) );
  614. $cmdret= CommandAttr(undef,"$devname alias ".$device_models{$detail->{type}}->{$detail->{model}}) if( defined($device_models{$detail->{type}}) && defined($device_models{$detail->{type}}->{$detail->{model}}) );
  615. #$cmdret= CommandAttr(undef,"$devname room WithingsTest");
  616. $cmdret= CommandAttr(undef,"$devname IODev $name");
  617. #$cmdret= CommandAttr(undef,"$devname disable 1");
  618. #$cmdret= CommandAttr(undef,"$devname verbose 5");
  619. $autocreated++;
  620. }
  621. }
  622. CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
  623. }
  624. sub withings_autocreate($) {
  625. my ($hash) = @_;
  626. my $name = $hash->{NAME};
  627. Log3 "withings", 5, "$name: autocreate";
  628. $hash->{'.https'} = "https";
  629. $hash->{'.https'} = "http" if( AttrVal($name, "nossl", 0) );
  630. withings_getSessionKey( $hash );
  631. my $autocreated = 0;
  632. my $users = withings_getUsers($hash);
  633. foreach my $user (@{$users}) {
  634. if( defined($modules{$hash->{TYPE}}{defptr}{"U$user->{id}"}) ) {
  635. Log3 $name, 2, "$name: user '$user->{id}' already defined";
  636. next;
  637. }
  638. next if($user->{firstname} eq "Repository-User");
  639. my $id = $user->{id};
  640. my $devname = "withings_U". $id;
  641. my $define= "$devname withings $id $user->{publickey}";
  642. Log3 $name, 2, "$name: create new device '$devname' for user '$id'";
  643. my $cmdret= CommandDefine(undef,$define);
  644. if($cmdret) {
  645. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  646. } else {
  647. $cmdret= CommandAttr(undef,"$devname alias ".$user->{shortname});
  648. $cmdret= CommandAttr(undef,"$devname IODev $name");
  649. $cmdret= CommandAttr(undef,"$devname room Withings");
  650. $autocreated++;
  651. }
  652. }
  653. my $devices = withings_getDevices($hash);
  654. foreach my $device (@{$devices}) {
  655. if( defined($modules{$hash->{TYPE}}{defptr}{"D$device->{deviceid}"}) ) {
  656. my $d = $modules{$hash->{TYPE}}{defptr}{"D$device->{deviceid}"};
  657. $d->{association} = $device->{association} if($device->{association});
  658. Log3 $name, 2, "$name: device '$device->{deviceid}' already defined";
  659. next;
  660. }
  661. my $detail = $device->{deviceproperties};
  662. next if( !defined($detail->{id}) );
  663. my $id = $detail->{id};
  664. my $devname = "withings_D". $id;
  665. my $define= "$devname withings $id";
  666. Log3 $name, 2, "$name: create new device '$devname' for device '$id'";
  667. my $cmdret= CommandDefine(undef,$define);
  668. if($cmdret) {
  669. Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
  670. } else {
  671. $cmdret= CommandAttr(undef,"$devname alias ".$device_types{$detail->{type}}) if( defined($device_types{$detail->{type}}) );
  672. $cmdret= CommandAttr(undef,"$devname alias ".$device_models{$detail->{type}}->{$detail->{model}}) if( defined($device_models{$detail->{type}}) && defined($device_models{$detail->{type}}->{$detail->{model}}) );
  673. $cmdret= CommandAttr(undef,"$devname IODev $name");
  674. $cmdret= CommandAttr(undef,"$devname room Withings");
  675. $autocreated++;
  676. }
  677. }
  678. CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
  679. }
  680. sub withings_initDevice($) {
  681. my ($hash) = @_;
  682. my $name = $hash->{NAME};
  683. Log3 "withings", 5, "$name: initdevice ".$hash->{Device};
  684. AssignIoPort($hash);
  685. if(defined($hash->{IODev}->{NAME})) {
  686. Log3 $name, 2, "$name: I/O device is " . $hash->{IODev}->{NAME};
  687. } else {
  688. Log3 $name, 1, "$name: no I/O device";
  689. }
  690. $hash->{'.https'} = "https";
  691. $hash->{'.https'} = "http" if( AttrVal($hash->{NAME}, "nossl", 0) );
  692. my $device = withings_getDeviceDetail( $hash );
  693. $hash->{DeviceType} = "UNKNOWN";
  694. $hash->{sn} = $device->{sn};
  695. $hash->{fw} = $device->{fw};
  696. $hash->{created} = $device->{created};
  697. $hash->{location} = $device->{latitude}.",".$device->{longitude} if(defined($device->{latitude}));
  698. $hash->{DeviceType} = $device->{type};
  699. $hash->{DeviceType} = $device_types{$device->{type}} if( defined($device->{type}) && defined($device_types{$device->{type}}) );
  700. $hash->{model} = $device->{model};
  701. $hash->{model} = $device_models{$device->{type}}->{$device->{model}}
  702. if( defined($device->{type}) && defined($device->{model}) && defined($device_models{$device->{type}}) && defined($device_models{$device->{type}}->{$device->{model}}) );
  703. $hash->{modelID} = $device->{model};
  704. $hash->{typeID} = $device->{type};
  705. $hash->{lastsessiondate} = $device->{lastsessiondate} if( defined($device->{lastsessiondate}) );
  706. $hash->{lastweighindate} = $device->{lastweighindate} if( defined($device->{lastweighindate}) );
  707. if((defined($hash->{typeID}) && $hash->{typeID} == 16) or (defined($hash->{modelID}) && $hash->{modelID} == 61))
  708. {
  709. my $devicelink = withings_getDeviceLink( $hash );
  710. if(defined($devicelink->{userid}))
  711. {
  712. $hash->{User} = $devicelink->{userid};
  713. $hash->{UserDevice} = $modules{$hash->{TYPE}}{defptr}{"U".$devicelink->{userid}} if defined($modules{$hash->{TYPE}}{defptr}{"U".$devicelink->{userid}});
  714. }
  715. }
  716. if( !defined( $attr{$name}{stateFormat} ) ) {
  717. $attr{$name}{stateFormat} = "batteryLevel %";
  718. $attr{$name}{stateFormat} = "co2 ppm" if( $device->{model} == 4 );
  719. $attr{$name}{stateFormat} = "voc ppm" if( $device->{model} == 22 );
  720. $attr{$name}{stateFormat} = "light lux" if( $device->{model} == 60 );
  721. $attr{$name}{stateFormat} = "lastWeighinDate" if( $device->{model} == 61 );
  722. }
  723. withings_readAuraAlarm($hash) if( defined(AttrVal($name,"IP",undef)) && defined($device->{model}) && $device->{model} == 60 && defined($device->{type}) && $device->{type} == 32 );
  724. InternalTimer(gettimeofday()+60, "withings_poll", $hash, 0);
  725. }
  726. sub withings_initUser($) {
  727. my ($hash) = @_;
  728. my $name = $hash->{NAME};
  729. Log3 "withings", 5, "$name: inituser ".$hash->{User};
  730. AssignIoPort($hash);
  731. if(defined($hash->{IODev}->{NAME})) {
  732. Log3 $name, 2, "$name: I/O device is " . $hash->{IODev}->{NAME};
  733. } else {
  734. Log3 $name, 1, "$name: no I/O device";
  735. }
  736. $hash->{'.https'} = "https";
  737. $hash->{'.https'} = "http" if( AttrVal($hash->{NAME}, "nossl", 0) );
  738. my $user = withings_getUserDetail( $hash );
  739. $hash->{shortName} = $user->{shortname};
  740. $hash->{gender} = ($user->{gender}==0)?"male":"female" if( defined($hash->{gender}) );
  741. $hash->{userName} = ($user->{firstname}?$user->{firstname}:"") ." ". ($user->{lastname}?$user->{lastname}:"");
  742. $hash->{birthdate} = strftime("%Y-%m-%d", localtime($user->{birthdate})) if( defined($user->{birthdate}) );
  743. $hash->{created} = $user->{created};
  744. $hash->{modified} = $user->{modified};
  745. $attr{$name}{stateFormat} = "weight kg" if( !defined( $attr{$name}{stateFormat} ) );
  746. InternalTimer(gettimeofday()+60, "withings_poll", $hash, 0);
  747. }
  748. sub withings_getUsers($) {
  749. my ($hash) = @_;
  750. my $name = $hash->{NAME};
  751. Log3 "withings", 5, "$name: getusers";
  752. withings_getSessionKey($hash);
  753. my ($err,$data) = HttpUtils_BlockingGet({
  754. url => $hash->{'.https'}."://healthmate.withings.com/index/service/account",
  755. timeout => 10,
  756. noshutdown => 1,
  757. data => {sessionid => $hash->{SessionKey}, accountid => $hash->{AccountID} , recurse_use => '1', recurse_devtype => '1', listmask => '5', allusers => 't' , appname => 'my2', appliver=> $hash->{helper}{appliver}, apppfm => 'web', action => 'getuserslist'},
  758. });
  759. #my $ua = LWP::UserAgent->new;
  760. #my $request = HTTP::Request->new(POST => $hash->{'.https'}.'://healthmate.withings.com/index/service/account');
  761. #my $get_data = 'sessionid='.$hash->{SessionKey}.'&accountid='.$hash->{AccountID}.'&recurse_use=1&recurse_devtype=1&listmask=5&allusers=t&appname=my2&appliver='.$hash->{helper}{appliver}.'&apppfm=web&action=getuserslist';
  762. #$request->content($get_data);
  763. #my $response = $ua->request($request);
  764. return undef if(!defined($data));
  765. my $json = eval { JSON->new->utf8(0)->decode($data) };
  766. if($@)
  767. {
  768. Log3 $name, 2, "$name: json evaluation error on getUsers ".$@;
  769. return undef;
  770. }
  771. my @users = ();
  772. foreach my $user (@{$json->{body}{users}}) {
  773. next if( !defined($user->{id}) );
  774. push( @users, $user );
  775. }
  776. return \@users;
  777. }
  778. sub withings_getDevices($) {
  779. my ($hash) = @_;
  780. my $name = $hash->{NAME};
  781. Log3 "withings", 5, "$name: getdevices";
  782. withings_getSessionKey($hash);
  783. my ($err,$data) = HttpUtils_BlockingGet({
  784. url => $hash->{'.https'}."://healthmate.withings.com/index/service/association",
  785. timeout => 10,
  786. noshutdown => 1,
  787. data => {sessionid => $hash->{SessionKey}, accountid => $hash->{AccountID} , type => '-1', enrich => 't' , appname => 'my2', appliver=> $hash->{helper}{appliver}, apppfm => 'web', action => 'getbyaccountid'},
  788. });
  789. #my $ua = LWP::UserAgent->new;
  790. #my $request = HTTP::Request->new(POST => $hash->{'.https'}.'://healthmate.withings.com/index/service/association');
  791. #my $get_data = 'sessionid='.$hash->{SessionKey}.'&accountid='.$hash->{AccountID}.'&type=-1&enrich=t&appname=my2&appliver='.$hash->{helper}{appliver}.'&apppfm=web&action=getbyaccountid';
  792. #$request->content($get_data);
  793. #my $response = $ua->request($request);
  794. return undef if(!defined($data));
  795. my $json = eval { JSON->new->utf8(0)->decode($data) };
  796. if($@)
  797. {
  798. Log3 $name, 2, "$name: json evaluation error on getDevices ".$@;
  799. return undef;
  800. }
  801. Log3 "withings", 5, "$name: getdevices ".Dumper($json);
  802. my @devices = ();
  803. foreach my $association (@{$json->{body}{associations}}) {
  804. next if( !defined($association->{deviceid}) );
  805. push( @devices, $association );
  806. }
  807. return \@devices;
  808. }
  809. sub withings_getDeviceDetail($) {
  810. my ($hash) = @_;
  811. my $name = $hash->{NAME};
  812. Log3 "withings", 5, "$name: getdevicedetail ".$hash->{Device};
  813. return undef if( !defined($hash->{IODev}) );
  814. withings_getSessionKey( $hash->{IODev} );
  815. my ($err,$data) = HttpUtils_BlockingGet({
  816. url => $hash->{'.https'}."://healthmate.withings.com/index/service/device",
  817. timeout => 10,
  818. noshutdown => 1,
  819. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid => $hash->{Device} , appname => 'my2', appliver=> $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getproperties'},
  820. });
  821. #Log3 "withings", 5, "$name: getdevicedetaildata ".Dumper($data);
  822. return undef if(!defined($data));
  823. my $json = eval { JSON->new->utf8(0)->decode($data) };
  824. if($@)
  825. {
  826. Log3 $name, 2, "$name: json evaluation error on getDeviceDetail ".$@;
  827. return undef;
  828. }
  829. if($json)
  830. {
  831. my $device = $json->{body};
  832. $hash->{sn} = $device->{sn};
  833. $hash->{fw} = $device->{fw};
  834. $hash->{created} = $device->{created};
  835. $hash->{location} = $device->{latitude}.",".$device->{longitude} if(defined($device->{latitude}));
  836. $hash->{DeviceType} = $device->{type};
  837. $hash->{DeviceType} = $device_types{$device->{type}} if( defined($device->{type}) && defined($device_types{$device->{type}}) );
  838. $hash->{model} = $device->{model};
  839. $hash->{model} = $device_models{$device->{type}}->{$device->{model}}
  840. if( defined($device->{type}) && defined($device->{model}) && defined($device_models{$device->{type}}) && defined($device_models{$device->{type}}->{$device->{model}}) );
  841. $hash->{modelID} = $device->{model};
  842. $hash->{typeID} = $device->{type};
  843. $hash->{lastsessiondate} = $device->{lastsessiondate} if( defined($device->{lastsessiondate}) );
  844. $hash->{lastweighindate} = $device->{lastweighindate} if( defined($device->{lastweighindate}) );
  845. }
  846. return $json->{body};
  847. }
  848. sub withings_getDeviceLink($) {
  849. my ($hash) = @_;
  850. my $name = $hash->{NAME};
  851. Log3 "withings", 5, "$name: getdevicelink ".$hash->{Device};
  852. return undef if( !defined($hash->{IODev}) );
  853. withings_getSessionKey( $hash->{IODev} );
  854. my ($err,$data) = HttpUtils_BlockingGet({
  855. url => $hash->{'.https'}."://healthmate.withings.com/index/service/v2/link",
  856. timeout => 10,
  857. noshutdown => 1,
  858. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid => $hash->{Device} , appname => 'my2', appliver=> $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'get'},
  859. });
  860. #my $ua = LWP::UserAgent->new;
  861. #my $request = HTTP::Request->new(POST => $hash->{'.https'}.'://healthmate.withings.com/index/service/v2/link');
  862. #my $get_data = 'sessionid='.$hash->{IODev}->{SessionKey}.'&deviceid='.$hash->{Device}.'&appname=my2&appliver='.$hash->{IODev}->{helper}{appliver}.'&apppfm=web&action=get';
  863. #$request->content($get_data);
  864. #my $response = $ua->request($request);
  865. return undef if(!defined($data));
  866. my $json = eval { JSON->new->utf8(0)->decode($data) };
  867. if($@)
  868. {
  869. Log3 $name, 2, "$name: json evaluation error on getDeviceLink ".$@;
  870. return undef;
  871. }
  872. return $json->{body};
  873. }
  874. sub withings_getDeviceProperties($) {
  875. my ($hash) = @_;
  876. my $name = $hash->{NAME};
  877. Log3 "withings", 5, "$name: getdeviceproperties ".$hash->{Device};
  878. return undef if( !defined($hash->{Device}) );
  879. return undef if( !defined($hash->{IODev}) );
  880. withings_getSessionKey( $hash->{IODev} );
  881. HttpUtils_NonblockingGet({
  882. url => "https://healthmate.withings.com/index/service/device",
  883. timeout => 30,
  884. noshutdown => 1,
  885. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getproperties'},
  886. hash => $hash,
  887. type => 'deviceProperties',
  888. callback => \&withings_Dispatch,
  889. });
  890. my ($seconds) = gettimeofday();
  891. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  892. readingsSingleUpdate( $hash, ".pollProperties", $seconds, 0 );
  893. return undef;
  894. }
  895. sub withings_getDeviceReadingsScale($) {
  896. my ($hash) = @_;
  897. my $name = $hash->{NAME};
  898. Log3 "withings", 5, "$name: getscalereadings ".$hash->{Device};
  899. return undef if( !defined($hash->{Device}) );
  900. return undef if( !defined($hash->{IODev}) );
  901. withings_getSessionKey( $hash->{IODev} );
  902. my ($now) = time;
  903. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-7*24*60*60) );#$hash->{created} );#
  904. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  905. my $enddate = ($lastupdate+(24*60*60));
  906. $enddate = $now if ($enddate > $now);
  907. HttpUtils_NonblockingGet({
  908. url => "https://healthmate.withings.com/index/service/v2/measure",
  909. timeout => 30,
  910. noshutdown => 1,
  911. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, meastype => '12,35', startdate => int($lastupdate), enddate => int($enddate), devicetype => '16', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getmeashf'},
  912. hash => $hash,
  913. type => 'deviceReadingsScale',
  914. enddate => int($enddate),
  915. callback => \&withings_Dispatch,
  916. });
  917. my ($seconds) = gettimeofday();
  918. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  919. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  920. return undef;
  921. }
  922. sub withings_getDeviceReadingsBedside($) {
  923. my ($hash) = @_;
  924. my $name = $hash->{NAME};
  925. Log3 "withings", 5, "$name: getaurareadings ".$hash->{Device};
  926. return undef if( !defined($hash->{Device}) );
  927. return undef if( !defined($hash->{IODev}) );
  928. withings_getSessionKey( $hash->{IODev} );
  929. my ($now) = time;
  930. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-7*24*60*60) );#$hash->{created} );#
  931. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  932. my $enddate = ($lastupdate+(8*60*60));
  933. $enddate = $now if ($enddate > $now);
  934. HttpUtils_NonblockingGet({
  935. url => "https://healthmate.withings.com/index/service/v2/measure",
  936. timeout => 30,
  937. noshutdown => 1,
  938. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, meastype => '12,13,14,15,56', startdate => int($lastupdate), enddate => int($enddate), devicetype => '16', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getmeashf'},
  939. hash => $hash,
  940. type => 'deviceReadingsBedside',
  941. enddate => int($enddate),
  942. callback => \&withings_Dispatch,
  943. });
  944. my ($seconds) = gettimeofday();
  945. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  946. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  947. return undef;
  948. }
  949. sub withings_getDeviceReadingsHome($) {
  950. my ($hash) = @_;
  951. my $name = $hash->{NAME};
  952. Log3 "withings", 5, "$name: gethomereadings ".$hash->{Device};
  953. return undef if( !defined($hash->{Device}) );
  954. return undef if( !defined($hash->{IODev}) );
  955. withings_getSessionKey( $hash->{IODev} );
  956. my ($now) = time;
  957. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-7*24*60*60) );#$hash->{created} );#
  958. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  959. my $enddate = ($lastupdate+(8*60*60));
  960. $enddate = $now if ($enddate > $now);
  961. HttpUtils_NonblockingGet({
  962. url => "https://healthmate.withings.com/index/service/v2/measure",
  963. timeout => 30,
  964. noshutdown => 1,
  965. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, meastype => '12,13,14,15,58', startdate => int($lastupdate), enddate => int($enddate), devicetype => '16', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getmeashf'},
  966. hash => $hash,
  967. type => 'deviceReadingsHome',
  968. enddate => int($enddate),
  969. callback => \&withings_Dispatch,
  970. });
  971. my ($seconds) = gettimeofday();
  972. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  973. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  974. return undef;
  975. }
  976. sub withings_getDeviceEventsBaby($) {
  977. my ($hash) = @_;
  978. my $name = $hash->{NAME};
  979. Log3 "withings", 5, "$name: getbabyevents ".$hash->{Device};
  980. return undef if( !defined($hash->{Device}) );
  981. return undef if( !defined($hash->{IODev}) );
  982. withings_getSessionKey( $hash->{IODev} );
  983. my ($now) = time;
  984. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-7*24*60*60) );#$hash->{created} );#
  985. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  986. HttpUtils_NonblockingGet({
  987. url => "https://healthmate.withings.com/index/service/event",
  988. timeout => 30,
  989. noshutdown => 1,
  990. data => {activated => '0', action => 'get', sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, type => '10,11,12,13,14,15,20', begindate => int($lastupdate)},
  991. hash => $hash,
  992. type => 'deviceReadingsBaby',
  993. callback => \&withings_Dispatch,
  994. });
  995. my ($seconds) = gettimeofday();
  996. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  997. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  998. return undef;
  999. }
  1000. sub withings_getDeviceAlertsHome($) {
  1001. my ($hash) = @_;
  1002. my $name = $hash->{NAME};
  1003. Log3 "withings", 5, "$name: gethomealerts ".$hash->{Device};
  1004. return undef if( !defined($hash->{Device}) );
  1005. return undef if( !defined($hash->{IODev}) );
  1006. withings_getSessionKey( $hash->{IODev} );
  1007. my ($now) = time;
  1008. my $lastupdate = ReadingsVal( $name, ".lastAlert", ($now-7*24*60*60) );#$hash->{created} );#
  1009. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  1010. HttpUtils_NonblockingGet({
  1011. url => "https://scalews.withings.net/cgi-bin/v2/timeline",
  1012. timeout => 30,
  1013. noshutdown => 1,
  1014. data => {type => '1', callctx => 'foreground', action => 'getbydeviceid', appname => 'HomeMonitor', apppfm => 'ios', appliver => '20000', sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, lastupdate => int($lastupdate) },
  1015. hash => $hash,
  1016. type => 'deviceAlertsHome',
  1017. callback => \&withings_Dispatch,
  1018. });
  1019. my ($seconds) = gettimeofday();
  1020. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1021. readingsSingleUpdate( $hash, ".pollAlert", $seconds, 0 );
  1022. return undef;
  1023. }
  1024. sub withings_getDeviceAlertsBaby($) {
  1025. my ($hash) = @_;
  1026. my $name = $hash->{NAME};
  1027. Log3 "withings", 5, "$name: getbabyevents ".$hash->{Device};
  1028. return undef if( !defined($hash->{Device}) );
  1029. return undef if( !defined($hash->{IODev}) );
  1030. withings_getSessionKey( $hash->{IODev} );
  1031. my ($now) = time;
  1032. my $lastupdate = ReadingsVal( $name, ".lastAlert", ($now-120*60) );
  1033. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  1034. HttpUtils_NonblockingGet({
  1035. url => "https://healthmate.withings.com/index/service/event",
  1036. timeout => 30,
  1037. noshutdown => 1,
  1038. data => {activated => '1', action => 'get', sessionid => $hash->{IODev}->{SessionKey}, deviceid=> $hash->{Device}, type => '10,11,12,13,14,15,20', begindate => int($lastupdate)},
  1039. hash => $hash,
  1040. type => 'deviceAlertsBaby',
  1041. callback => \&withings_Dispatch,
  1042. });
  1043. my ($seconds) = gettimeofday();
  1044. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1045. readingsSingleUpdate( $hash, ".pollAlert", $seconds, 0 );
  1046. return undef;
  1047. }
  1048. sub withings_getVideoLink($) {
  1049. my ($hash) = @_;
  1050. my $name = $hash->{NAME};
  1051. Log3 "withings", 5, "$name: getbabyvideo ".$hash->{Device};
  1052. return undef if( !defined($hash->{Device}) );
  1053. return undef if( !defined($hash->{IODev}) );
  1054. withings_getSessionKey( $hash->{IODev} );
  1055. my ($err,$data) = HttpUtils_BlockingGet({
  1056. url => $hash->{'.https'}."://babyws.withings.net/cgi-bin/presence",
  1057. timeout => 10,
  1058. noshutdown => 1,
  1059. data => {sessionid => $hash->{IODev}->{SessionKey}, deviceid => $hash->{Device} , action => 'get'},
  1060. });
  1061. return undef if(!defined($data));
  1062. my $json = eval { JSON->new->utf8(0)->decode($data) };
  1063. if($@)
  1064. {
  1065. Log3 $name, 2, "$name: json evaluation error on getVideoLink ".$@;
  1066. return undef;
  1067. }
  1068. if(defined($json->{body}{device}))
  1069. {
  1070. $hash->{videolink_ext} = "http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf?streamType=live&autoPlay=true&playButtonOverlay=false&src=rtmp://".$json->{body}{device}{proxy_ip}.":".$json->{body}{device}{proxy_port}."/".$json->{body}{device}{kp_hash}."/";
  1071. $hash->{videolink_int} = "http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf?streamType=live&autoPlay=true&playButtonOverlay=false&src=rtmp://".$json->{body}{device}{private_ip}.":".$json->{body}{device}{proxy_port}."/".$json->{body}{device}{kd_hash}."/";
  1072. }
  1073. return $json;
  1074. }
  1075. sub withings_getS3Credentials($) {
  1076. my ($hash) = @_;
  1077. my $name = $hash->{NAME};
  1078. return undef if( !defined($hash->{Device}) );
  1079. return undef if( $hash->{sts_expiretime} && $hash->{sts_expiretime} > time - 3600 ); # min 1h
  1080. return undef if( !defined($hash->{IODev}) );
  1081. Log3 "withings", 5, "$name: gets3credentials ".$hash->{Device};
  1082. withings_getSessionKey( $hash->{IODev} );
  1083. my ($err,$data) = HttpUtils_BlockingGet({
  1084. url => $hash->{'.https'}."://scalews.withings.net/cgi-bin/v2/device",
  1085. timeout => 10,
  1086. noshutdown => 1,
  1087. data => {callctx => 'foreground', action => 'getsts', deviceid => $hash->{Device}, appname => 'HomeMonitor', apppfm => 'ios' , appliver => '20000', sessionid => $hash->{IODev}->{SessionKey}},
  1088. });
  1089. return undef if(!defined($data));
  1090. my $json = eval { JSON->new->utf8(0)->decode($data) };
  1091. if($@)
  1092. {
  1093. Log3 $name, 2, "$name: json evaluation error on getS3Credentials ".$@;
  1094. return undef;
  1095. }
  1096. if(defined($json->{body}{sts}))
  1097. {
  1098. $hash->{sts_region} = $json->{body}{sts}{region};
  1099. $hash->{sts_sessiontoken} = $json->{body}{sts}{sessiontoken};
  1100. $hash->{sts_accesskeyid} = $json->{body}{sts}{accesskeyid};
  1101. $hash->{sts_expiretime} = $json->{body}{sts}{expiretime};
  1102. $hash->{sts_secretaccesskey} = $json->{body}{sts}{secretaccesskey};
  1103. $hash->{sts_buckets} = (@{$json->{body}{sts}{buckets}}).join(",");
  1104. }
  1105. return $json;
  1106. }
  1107. sub withings_signS3Link($$$;$) {
  1108. my ($hash,$url,$sign,$bucket) = @_;
  1109. my $name = $hash->{NAME};
  1110. withings_getS3Credentials($hash);
  1111. my $signing = "GET\n\n\n";
  1112. $signing .= $hash->{sts_expiretime}."\n";
  1113. $signing .= "x-amz-security-token:".$hash->{sts_sessiontoken}."\n";
  1114. $signing .= $sign;
  1115. my $signature = hmac_sha1_base64($signing, $hash->{sts_secretaccesskey})."=";
  1116. $url .= "?AWSAccessKeyId=".uri_escape($hash->{sts_accesskeyid});
  1117. $url .= "&Expires=".$hash->{sts_expiretime};
  1118. $url .= "&x-amz-security-token=".uri_escape($hash->{sts_sessiontoken});
  1119. $url .= "&Signature=".uri_escape($signature);
  1120. return $url;
  1121. }
  1122. sub withings_getUserDetail($) {
  1123. my ($hash) = @_;
  1124. my $name = $hash->{NAME};
  1125. Log3 "withings", 5, "$name: getuserdetails ".$hash->{User};
  1126. return undef if( !defined($hash->{User}) );
  1127. return undef if( $hash->{SUBTYPE} ne "USER" );
  1128. return undef if( !defined($hash->{IODev}));
  1129. withings_getSessionKey( $hash->{IODev} );
  1130. my ($err,$data) = HttpUtils_BlockingGet({
  1131. url => $hash->{'.https'}."://healthmate.withings.com/index/service/user",
  1132. timeout => 10,
  1133. noshutdown => 1,
  1134. data => {sessionid => $hash->{IODev}->{SessionKey}, userid => $hash->{User} , appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getbyuserid'},
  1135. });
  1136. return undef if(!defined($data));
  1137. my $json = eval { JSON->new->utf8(0)->decode($data) };
  1138. if($@)
  1139. {
  1140. Log3 $name, 2, "$name: json evaluation error on getUserDetail ".$@;
  1141. return undef;
  1142. }
  1143. return $json->{body}{users}[0];
  1144. }
  1145. sub withings_poll($;$) {
  1146. my ($hash,$force) = @_;
  1147. $force = 0 if(!defined($force));
  1148. my $name = $hash->{NAME};
  1149. RemoveInternalTimer($hash);
  1150. return undef if(AttrVal($name,"disable",0) eq "1");
  1151. my $resolve = inet_aton("healthmate.withings.com");
  1152. if(!defined($resolve))
  1153. {
  1154. $hash->{STATE} = "DNS error";
  1155. InternalTimer( gettimeofday() + 3600, "withings_poll", $hash, 0);
  1156. return undef;
  1157. }
  1158. my ($now) = int(time());
  1159. if( $hash->{SUBTYPE} eq "DEVICE" ) {
  1160. my $intervalData = AttrVal($name,"intervalData",900);
  1161. my $intervalDebug = AttrVal($name,"intervalDebug",900);
  1162. my $lastData = ReadingsVal( $name, ".pollData", 0 );
  1163. my $lastDebug = ReadingsVal( $name, ".pollDebug", 0 );
  1164. my $intervalProperties = AttrVal($name,"intervalProperties",43200);
  1165. my $lastProperties = ReadingsVal( $name, ".pollProperties", 0 );
  1166. if(defined($hash->{modelID}) && $hash->{modelID} eq '4') {
  1167. withings_getDeviceProperties($hash) if($force > 1 || $lastData <= ($now - $intervalData));
  1168. withings_getDeviceReadingsScale($hash) if($force || $lastData <= ($now - $intervalData));
  1169. }
  1170. elsif(defined($hash->{modelID}) && $hash->{modelID} eq '21') {
  1171. my $intervalAlert = AttrVal($name,"intervalAlert",120);
  1172. my $lastAlert = ReadingsVal( $name, ".pollAlert", 0 );
  1173. withings_getDeviceProperties($hash) if($force > 1 || $lastProperties <= ($now - $intervalProperties));
  1174. withings_getDeviceEventsBaby($hash) if($force || $lastData <= ($now - $intervalData));
  1175. #withings_getDeviceAlertsBaby($hash) if($force || $lastAlert <= ($now - $intervalAlert));
  1176. }
  1177. elsif(defined($hash->{modelID}) && $hash->{modelID} eq '22') {
  1178. my $intervalAlert = AttrVal($name,"intervalAlert",120);
  1179. my $lastAlert = ReadingsVal( $name, ".pollAlert", 0 );
  1180. withings_getDeviceProperties($hash) if($force > 1 || $lastProperties <= ($now - $intervalProperties));
  1181. withings_getDeviceReadingsHome($hash) if($force || $lastData <= ($now - $intervalData));
  1182. withings_getDeviceAlertsHome($hash) if($force || $lastAlert <= ($now - $intervalAlert));
  1183. }
  1184. elsif(defined($hash->{typeID}) && $hash->{typeID} eq '16') {
  1185. withings_getDeviceProperties($hash) if($force > 1 || $lastProperties <= ($now - $intervalProperties));
  1186. withings_getUserReadingsActivity($hash) if($force || $lastData <= ($now - $intervalData));
  1187. }
  1188. elsif(defined($hash->{modelID}) && $hash->{modelID} eq '60') {
  1189. withings_getDeviceProperties($hash) if($force > 1 || $lastProperties <= ($now - $intervalProperties));
  1190. withings_getDeviceReadingsBedside($hash) if($force || $lastData <= ($now - $intervalData));
  1191. }
  1192. elsif(defined($hash->{modelID}) && $hash->{modelID} eq '61') {
  1193. withings_getDeviceProperties($hash) if($force > 1 || $lastProperties <= ($now - $intervalProperties));
  1194. withings_getUserReadingsSleep($hash) if($force || $lastData <= ($now - $intervalData));
  1195. withings_getUserReadingsSleepDebug($hash) if($force || $lastDebug <= ($now - $intervalDebug));
  1196. }
  1197. else
  1198. {
  1199. withings_getDeviceProperties($hash) if($force || $lastProperties <= ($now - $intervalProperties));
  1200. }
  1201. } elsif( $hash->{SUBTYPE} eq "DUMMY" ) {
  1202. my $intervalData = AttrVal($name,"intervalData",900);
  1203. my $lastData = ReadingsVal( $name, ".pollData", 0 );
  1204. if($hash->{typeID} eq '16') {
  1205. withings_getUserReadingsActivity($hash) if($force || $lastData <= ($now - $intervalData));
  1206. }
  1207. } elsif( $hash->{SUBTYPE} eq "USER" ) {
  1208. my $intervalData = AttrVal($name,"intervalData",900);
  1209. my $intervalDaily = AttrVal($name,"intervalDaily",(6*60*60));
  1210. my $lastData = ReadingsVal( $name, ".pollData", 0 );
  1211. my $lastDaily = ReadingsVal( $name, ".pollDaily", 0 );
  1212. withings_getUserReadingsCommon($hash) if($force || $lastData <= ($now - $intervalData));
  1213. withings_getUserReadingsDaily($hash) if($force || $lastDaily <= ($now - $intervalDaily));
  1214. }
  1215. InternalTimer(gettimeofday()+60, "withings_poll", $hash, 0);
  1216. }
  1217. sub withings_getUserReadingsDaily($) {
  1218. my ($hash) = @_;
  1219. my $name = $hash->{NAME};
  1220. Log3 "withings", 5, "$name: getuserdailystats ".$hash->{User};
  1221. return undef if( !defined($hash->{IODev}) );
  1222. withings_getSessionKey( $hash->{IODev} );
  1223. my ($now) = time;
  1224. my $lastupdate = ReadingsVal( $name, ".lastAggregate", ($now-21*24*60*60) );#$hash->{created} );#
  1225. my $enddate = ($lastupdate+(14*24*60*60));
  1226. $enddate = $now if ($enddate > $now);
  1227. my $startdateymd = strftime("%Y-%m-%d", localtime($lastupdate));
  1228. my $enddateymd = strftime("%Y-%m-%d", localtime($enddate));
  1229. HttpUtils_NonblockingGet({
  1230. url => "https://healthmate.withings.com/index/service/v2/aggregate",
  1231. timeout => 60,
  1232. noshutdown => 1,
  1233. data => {sessionid => $hash->{IODev}->{SessionKey}, userid=> $hash->{User}, range => '1', meastype => '36,37,38,40,41,49,50,51,52,53,87', startdateymd => $startdateymd, enddateymd => $enddateymd, appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getbyuserid'},
  1234. hash => $hash,
  1235. type => 'userDailyAggregate',
  1236. enddate => int($enddate),
  1237. callback => \&withings_Dispatch,
  1238. });
  1239. $lastupdate = ReadingsVal( $name, ".lastActivity", ($now-21*24*60*60) );#$hash->{created} );
  1240. $enddate = ($lastupdate+(14*24*60*60));
  1241. $enddate = $now if ($enddate > $now);
  1242. $startdateymd = strftime("%Y-%m-%d", localtime($lastupdate));
  1243. $enddateymd = strftime("%Y-%m-%d", localtime($enddate));
  1244. HttpUtils_NonblockingGet({
  1245. url => "https://healthmate.withings.com/index/service/v2/activity",
  1246. timeout => 60,
  1247. noshutdown => 1,
  1248. data => {sessionid => $hash->{IODev}->{SessionKey}, userid=> $hash->{User}, subcategory => '37', startdateymd => $startdateymd, enddateymd => $enddateymd, appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getbyuserid'},
  1249. hash => $hash,
  1250. type => 'userDailyActivity',
  1251. enddate => int($enddate),
  1252. callback => \&withings_Dispatch,
  1253. });
  1254. my ($seconds) = gettimeofday();
  1255. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1256. readingsSingleUpdate( $hash, ".pollDaily", $seconds, 0 );
  1257. return undef;
  1258. }
  1259. sub withings_getUserReadingsCommon($) {
  1260. my ($hash) = @_;
  1261. my $name = $hash->{NAME};
  1262. Log3 "withings", 5, "$name: getuserreadings ".$hash->{User};
  1263. return undef if( !defined($hash->{IODev}) );
  1264. withings_getSessionKey( $hash->{IODev} );
  1265. my ($now) = time;
  1266. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-100*24*60*60) );#$hash->{created} );#
  1267. my $enddate = ($lastupdate+(100*24*60*60));
  1268. $enddate = $now if ($enddate > $now);
  1269. HttpUtils_NonblockingGet({
  1270. url => "https://healthmate.withings.com/index/service/measure",
  1271. timeout => 60,
  1272. noshutdown => 1,
  1273. data => {sessionid => $hash->{IODev}->{SessionKey}, category => '1', userid=> $hash->{User}, offset => '0', limit => '400', startdate => int($lastupdate), enddate => int($enddate), appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getmeas'},
  1274. hash => $hash,
  1275. type => 'userReadingsCommon',
  1276. enddate => int($enddate),
  1277. callback => \&withings_Dispatch,
  1278. });
  1279. my ($seconds) = gettimeofday();
  1280. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1281. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  1282. return undef;
  1283. }
  1284. sub withings_getUserReadingsSleep($) {
  1285. my ($hash) = @_;
  1286. my $name = $hash->{NAME};
  1287. Log3 "withings", 5, "$name: getsleepreadings ".$hash->{User};
  1288. return undef if( !defined($hash->{IODev}) );
  1289. withings_getSessionKey( $hash->{IODev} );
  1290. my ($now) = time;
  1291. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-7*24*60*60) );#$hash->{created} );#
  1292. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  1293. my $enddate = ($lastupdate+(8*60*60));
  1294. $enddate = $now if ($enddate > $now);
  1295. # data => {sessionid => $hash->{IODev}->{SessionKey}, userid=> $hash->{User}, meastype => '43,44,11,57,59,60,61,62,63,64,65,66,67,68,69,70', startdate => int($lastupdate), enddate => int($enddate), devicetype => '32', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getvasistas'},
  1296. HttpUtils_NonblockingGet({
  1297. url => "https://healthmate.withings.com/index/service/v2/measure",
  1298. timeout => 60,
  1299. noshutdown => 1,
  1300. data => {sessionid => $hash->{IODev}->{SessionKey}, userid=> $hash->{User}, meastype => '11,39,41,43,44,57,59,87', startdate => int($lastupdate), enddate => int($enddate), devicetype => '32', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getvasistas'},
  1301. hash => $hash,
  1302. type => 'userReadingsSleep',
  1303. enddate => int($enddate),
  1304. callback => \&withings_Dispatch,
  1305. });
  1306. my ($seconds) = gettimeofday();
  1307. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1308. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  1309. return undef;
  1310. }
  1311. sub withings_getUserReadingsSleepDebug($) {
  1312. my ($hash) = @_;
  1313. my $name = $hash->{NAME};
  1314. Log3 "withings", 5, "$name: getsleepreadingsdebug ".$hash->{User};
  1315. return undef if( !defined($hash->{IODev}) );
  1316. withings_getSessionKey( $hash->{IODev} );
  1317. my ($now) = time;
  1318. my $lastupdate = ReadingsVal( $name, ".lastDebug", ($now-7*24*60*60) );#$hash->{created} );
  1319. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  1320. my $enddate = ($lastupdate+(8*60*60));
  1321. $enddate = $now if ($enddate > $now);
  1322. HttpUtils_NonblockingGet({
  1323. url => "https://healthmate.withings.com/index/service/v2/measure",
  1324. timeout => 60,
  1325. noshutdown => 1,
  1326. data => {sessionid => $hash->{IODev}->{SessionKey}, userid=> $hash->{User}, meastype => '60,61,62,63,64,65,66,67,68,69,70', startdate => int($lastupdate), enddate => int($enddate), devicetype => '32', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getvasistas'},
  1327. hash => $hash,
  1328. type => 'userReadingsSleepDebug',
  1329. enddate => int($enddate),
  1330. callback => \&withings_Dispatch,
  1331. });
  1332. my ($seconds) = gettimeofday();
  1333. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1334. readingsSingleUpdate( $hash, ".pollDebug", $seconds, 0 );
  1335. return undef;
  1336. }
  1337. sub withings_getUserReadingsActivity($) {
  1338. my ($hash) = @_;
  1339. my $name = $hash->{NAME};
  1340. Log3 "withings", 5, "$name: getactivityreadings ".$hash->{User};
  1341. return undef if( !defined($hash->{IODev}) );
  1342. withings_getSessionKey( $hash->{IODev} );
  1343. my ($now) = time;
  1344. my $lastupdate = ReadingsVal( $name, ".lastData", ($now-7*24*60*60) );#$hash->{created} );#
  1345. $lastupdate = $hash->{lastsessiondate} if(defined($hash->{lastsessiondate}) and $hash->{lastsessiondate} < $lastupdate);
  1346. my $enddate = ($lastupdate+(8*60*60));
  1347. $enddate = $now if ($enddate > $now);
  1348. Log3 "withings", 5, "$name: getactivityreadings ".$lastupdate." to ".$enddate;
  1349. HttpUtils_NonblockingGet({
  1350. url => "https://healthmate.withings.com/index/service/v2/measure",
  1351. timeout => 60,
  1352. noshutdown => 1,
  1353. data => {sessionid => $hash->{IODev}->{SessionKey}, userid=> $hash->{User}, meastype => '36,37,38,39,40,41,42,43,44,59,70,87,90', startdate => int($lastupdate), enddate => int($enddate), devicetype => '16', appname => 'my2', appliver => $hash->{IODev}->{helper}{appliver}, apppfm => 'web', action => 'getvasistas'},
  1354. hash => $hash,
  1355. type => 'userReadingsActivity',
  1356. enddate => int($enddate),
  1357. callback => \&withings_Dispatch,
  1358. });
  1359. my ($seconds) = gettimeofday();
  1360. $hash->{LAST_POLL} = FmtDateTime( $seconds );
  1361. readingsSingleUpdate( $hash, ".pollData", $seconds, 0 );
  1362. return undef;
  1363. }
  1364. sub withings_parseProperties($$) {
  1365. my ($hash,$json) = @_;
  1366. my $name = $hash->{NAME};
  1367. Log3 "withings", 5, "$name: parsedevice";
  1368. #parse
  1369. my $detail = $json->{body};
  1370. readingsBeginUpdate($hash);
  1371. if( defined($detail->{batterylvl}) and $detail->{batterylvl} > 0 and $detail->{type} ne '32' and $detail->{model} ne '22') {
  1372. readingsBulkUpdate( $hash, "batteryLevel", $detail->{batterylvl}, 1 );
  1373. readingsBulkUpdate( $hash, "battery", ($detail->{batterylvl}>20?"ok":"low"), 1 );
  1374. }
  1375. readingsBulkUpdate( $hash, "lastWeighinDate", FmtDateTime($detail->{lastweighindate}), 1 ) if( defined($detail->{lastweighindate}) and $detail->{lastweighindate} > 0 and $detail->{model} ne '60' );
  1376. readingsBulkUpdate( $hash, "lastSessionDate", FmtDateTime($detail->{lastsessiondate}), 1 ) if( defined($detail->{lastsessiondate}) );
  1377. $hash->{lastsessiondate} = $detail->{lastsessiondate} if( defined($detail->{lastsessiondate}) );
  1378. readingsEndUpdate($hash,1);
  1379. }
  1380. sub withings_parseMeasureGroups($$) {
  1381. my ($hash, $json) = @_;
  1382. my $name = $hash->{NAME};
  1383. #parse
  1384. Log3 "withings", 5, "$name: parsemeasuregroups";
  1385. my ($now) = time;
  1386. my $lastupdate = ReadingsVal( $name, ".lastData", 0 );
  1387. my $newlastupdate = $lastupdate;
  1388. $hash->{status} = $json->{status};
  1389. if( $hash->{status} == 0 ) {
  1390. my $i = 0;
  1391. foreach my $measuregrp ( sort { $a->{date} <=> $b->{date} } @{$json->{body}{measuregrps}}) {
  1392. if( $measuregrp->{date} < $newlastupdate )
  1393. {
  1394. Log3 $name, 4, "$name: old measuregroup skipped: ".FmtDateTime($measuregrp->{date});
  1395. next;
  1396. }
  1397. $newlastupdate = $measuregrp->{date};
  1398. foreach my $measure (@{$measuregrp->{measures}}) {
  1399. my $reading = $measure_types{$measure->{type}}->{reading};
  1400. if( !defined($reading) ) {
  1401. Log3 $name, 1, "$name: unknown measure type: $measure->{type}";
  1402. next;
  1403. }
  1404. my $value = $measure->{value} * 10 ** $measure->{unit};
  1405. readingsBeginUpdate($hash);
  1406. $hash->{".updateTimestamp"} = FmtDateTime($measuregrp->{date});
  1407. readingsBulkUpdate( $hash, $reading, $value, 1 );
  1408. $hash->{CHANGETIME}[0] = FmtDateTime($measuregrp->{date});
  1409. readingsEndUpdate($hash,1);
  1410. }
  1411. }
  1412. if($newlastupdate == $lastupdate and $i == 0)
  1413. {
  1414. my $user = withings_getUserDetail( $hash );
  1415. $hash->{modified} = $user->{modified};
  1416. $newlastupdate = $json->{requestedenddate} if($json->{requestedenddate});
  1417. $newlastupdate = $user->{modified} if($user->{modified} and $user->{modified} < $newlastupdate);
  1418. }
  1419. $newlastupdate = $now if($newlastupdate > $now);
  1420. if($newlastupdate < $lastupdate-1)
  1421. {
  1422. Log3 $name, 2, "$name: Measuregroups gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") ".$i if($i>0);
  1423. withings_getDeviceProperties($hash) if($i>0);
  1424. $newlastupdate = $lastupdate-1;
  1425. }
  1426. readingsSingleUpdate( $hash, ".lastData", $newlastupdate+1, 0 );
  1427. $hash->{LAST_DATA} = FmtDateTime( $newlastupdate );
  1428. delete $hash->{CHANGETIME};
  1429. Log3 $name, 4, "$name: got ".$i.' entries from MeasureGroups (latest: '.FmtDateTime($newlastupdate).')';
  1430. }
  1431. }
  1432. sub withings_parseMeasurements($$) {
  1433. my ($hash, $json) = @_;
  1434. my $name = $hash->{NAME};
  1435. #parse
  1436. Log3 "withings", 5, "$name: parsemeasurements";
  1437. my ($now) = time;
  1438. my $lastupdate = ReadingsVal( $name, ".lastData", 0 );
  1439. my $newlastupdate = $lastupdate;
  1440. my $i = 0;
  1441. if( $json )
  1442. {
  1443. $hash->{status} = $json->{status};
  1444. my @readings = ();
  1445. if( $hash->{status} == 0 )
  1446. {
  1447. foreach my $series ( @{$json->{body}{series}}) {
  1448. my $reading = $measure_types{$series->{type}}->{reading};
  1449. if( !defined($reading) ) {
  1450. Log3 $name, 1, "$name: unknown measure type: $series->{type}";
  1451. next;
  1452. }
  1453. foreach my $measure (@{$series->{data}}) {
  1454. my $value = $measure->{value};
  1455. push(@readings, [$measure->{date}, $reading, $value]);
  1456. }
  1457. }
  1458. if( @readings ) {
  1459. $i = 0;
  1460. foreach my $reading (sort { $a->[0] <=> $b->[0] } @readings) {
  1461. if( $reading->[0] < $newlastupdate )
  1462. {
  1463. Log3 $name, 5, "$name: old measurement skipped: ".FmtDateTime($reading->[0])." ".$reading->[1];
  1464. next;
  1465. }
  1466. $newlastupdate = $reading->[0];
  1467. readingsBeginUpdate($hash);
  1468. $hash->{".updateTimestamp"} = FmtDateTime($reading->[0]);
  1469. readingsBulkUpdate( $hash, $reading->[1], $reading->[2], 1 );
  1470. $hash->{CHANGETIME}[0] = FmtDateTime($reading->[0]);;
  1471. readingsEndUpdate($hash,1);
  1472. }
  1473. }
  1474. if($newlastupdate == $lastupdate and $i == 0)
  1475. {
  1476. my $device = withings_getDeviceDetail( $hash );
  1477. $newlastupdate = $json->{requestedenddate} if($json->{requestedenddate});
  1478. $newlastupdate = $device->{lastsessiondate} if($device->{lastsessiondate} and $device->{lastsessiondate} < $newlastupdate);
  1479. $newlastupdate = $device->{lastweighindate} if($device->{lastweighindate} and $device->{lastweighindate} < $newlastupdate);
  1480. }
  1481. $newlastupdate = $now if($newlastupdate > $now);
  1482. if($newlastupdate < $lastupdate-1)
  1483. {
  1484. Log3 $name, 2, "$name: Measurements gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") ".$i if($i>0);
  1485. withings_getDeviceProperties($hash) if($i>0);
  1486. $newlastupdate = $lastupdate-1;
  1487. }
  1488. readingsSingleUpdate( $hash, ".lastData", $newlastupdate+1, 0 );
  1489. $hash->{LAST_DATA} = FmtDateTime( $newlastupdate );
  1490. delete $hash->{CHANGETIME};
  1491. Log3 $name, 4, "$name: got ".$i.' entries from Measurements (latest: '.FmtDateTime($newlastupdate).')';
  1492. }
  1493. }
  1494. }
  1495. sub withings_parseAggregate($$) {
  1496. my ($hash, $json) = @_;
  1497. my $name = $hash->{NAME};
  1498. #parse
  1499. Log3 "withings", 5, "$name: parseaggregate";
  1500. #return undef;
  1501. my ($now) = time;
  1502. my $lastupdate = ReadingsVal( $name, ".lastAggregate", 0 );
  1503. my $newlastupdate = $lastupdate;
  1504. my $i = 0;
  1505. my $unfinished;
  1506. if( $json )
  1507. {
  1508. $hash->{status} = $json->{status};
  1509. my @readings = ();
  1510. if( $hash->{status} == 0 )
  1511. {
  1512. if(defined($json->{body}{series}))
  1513. {
  1514. my $series = $json->{body}->{series};
  1515. foreach my $serieskey ( keys %$series)
  1516. {
  1517. if(defined($series->{$serieskey}))
  1518. {
  1519. my $typestring = substr($serieskey, -2);
  1520. my $serieshash = $json->{body}->{series}{$serieskey};
  1521. next if(ref($serieshash) ne "HASH");
  1522. foreach my $daykey ( keys %$serieshash)
  1523. {
  1524. my $dayhash = $json->{body}->{series}{$serieskey}{$daykey};
  1525. next if(ref($dayhash) ne "HASH");
  1526. if(!$dayhash->{complete})
  1527. {
  1528. $unfinished = 1;
  1529. next;
  1530. }
  1531. my ($year,$mon,$day) = split(/[\s-]+/, $daykey);
  1532. my $timestamp = timelocal(0,0,18,$day,$mon-1,$year-1900);
  1533. #my $timestamp = $dayhash->{midnight};
  1534. my $reading = $measure_types{$typestring}->{dailyreading};
  1535. if( !defined($reading) ) {
  1536. Log3 $name, 1, "$name: unknown measure type: $typestring";
  1537. next;
  1538. }
  1539. my $value = $dayhash->{sum};
  1540. push(@readings, [$timestamp, $reading, $value]);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. if( @readings )
  1546. {
  1547. $i = 0;
  1548. foreach my $reading (sort { $a->[0] <=> $b->[0] } @readings)
  1549. {
  1550. if( $reading->[0] < $newlastupdate )
  1551. {
  1552. Log3 $name, 5, "$name: old aggregate skipped: ".FmtDateTime($reading->[0])." ".$reading->[1];
  1553. next;
  1554. }
  1555. $newlastupdate = $reading->[0];
  1556. readingsBeginUpdate($hash);
  1557. $hash->{".updateTimestamp"} = FmtDateTime($reading->[0]);
  1558. readingsBulkUpdate( $hash, $reading->[1], $reading->[2], 1 );
  1559. $hash->{CHANGETIME}[0] = FmtDateTime($reading->[0]);
  1560. readingsEndUpdate($hash,1);
  1561. }
  1562. }
  1563. if($newlastupdate == $lastupdate and $i == 0)
  1564. {
  1565. $newlastupdate = $lastupdate - 1; #$json->{requestedenddate} if($json->{requestedenddate});
  1566. }
  1567. $newlastupdate = $now if($newlastupdate > $now);
  1568. if($newlastupdate < $lastupdate-1)
  1569. {
  1570. Log3 $name, 2, "$name: Aggregate gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") ".$i if($i>0);
  1571. withings_getDeviceProperties($hash) if($i>0);
  1572. $newlastupdate = $lastupdate-1;
  1573. }
  1574. readingsSingleUpdate( $hash, ".lastAggregate", $newlastupdate+1, 0 );
  1575. #$hash->{LAST_DATA} = FmtDateTime( $newlastupdate );
  1576. delete $hash->{CHANGETIME};
  1577. Log3 $name, 4, "$name: got ".$i.' entries from Aggregate (latest: '.FmtDateTime($newlastupdate).')';
  1578. }
  1579. }
  1580. }
  1581. sub withings_parseActivity($$) {
  1582. my ($hash, $json) = @_;
  1583. my $name = $hash->{NAME};
  1584. #parse
  1585. Log3 "withings", 5, "$name: parseactivity";
  1586. my ($now) = time;
  1587. my $lastupdate = ReadingsVal( $name, ".lastActivity", 0 );
  1588. my $newlastupdate = $lastupdate;
  1589. my $i = 0;
  1590. my $unfinished;
  1591. if( $json )
  1592. {
  1593. $hash->{status} = $json->{status};
  1594. my @readings = ();
  1595. if( $hash->{status} == 0 )
  1596. {
  1597. foreach my $series ( @{$json->{body}{series}})
  1598. {
  1599. if($series->{completed} ne '1')
  1600. {
  1601. $unfinished = 1;
  1602. next;
  1603. }
  1604. foreach my $dataset ( keys (%{$series->{data}}))
  1605. {
  1606. if(!defined($sleep_readings{$dataset}->{reading}))
  1607. {
  1608. Log3 $name, 2, "$name: unknown sleep reading $dataset";
  1609. next;
  1610. }
  1611. my ($year,$mon,$day) = split(/[\s-]+/, $series->{date});
  1612. my $timestamp = timelocal(0,0,6,$day,$mon-1,$year-1900);
  1613. my $reading = $sleep_readings{$dataset}->{reading};
  1614. my $value = $series->{data}{$dataset};
  1615. push(@readings, [$timestamp, $reading, $value]);
  1616. }
  1617. }
  1618. if( @readings ) {
  1619. $i = 0;
  1620. foreach my $reading (sort { $a->[0] <=> $b->[0] } @readings) {
  1621. if( $reading->[0] < $newlastupdate )
  1622. {
  1623. Log3 $name, 5, "$name: old activity skipped: ".FmtDateTime($reading->[0])." ".$reading->[1];
  1624. next;
  1625. }
  1626. $newlastupdate = $reading->[0];
  1627. readingsBeginUpdate($hash);
  1628. $hash->{".updateTimestamp"} = FmtDateTime($reading->[0]);
  1629. readingsBulkUpdate( $hash, $reading->[1], $reading->[2], 1 );
  1630. $hash->{CHANGETIME}[0] = FmtDateTime($reading->[0]);
  1631. readingsEndUpdate($hash,1);
  1632. }
  1633. }
  1634. if($newlastupdate == $lastupdate and $i == 0)
  1635. {
  1636. $newlastupdate = $lastupdate - 1; #$json->{requestedenddate} if($json->{requestedenddate});
  1637. }
  1638. $newlastupdate = $now if($newlastupdate > $now);
  1639. if($newlastupdate < $lastupdate-1)
  1640. {
  1641. Log3 $name, 2, "$name: Activity gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") .$i if($i>0)";
  1642. withings_getDeviceProperties($hash) if($i>0);
  1643. $newlastupdate = $lastupdate-1;
  1644. }
  1645. readingsSingleUpdate( $hash, ".lastActivity", $newlastupdate+1, 0 );
  1646. #$hash->{LAST_DATA} = FmtDateTime( $newlastupdate );
  1647. delete $hash->{CHANGETIME};
  1648. Log3 $name, 4, "$name: got ".$i.' entries from Activity (latest: '.FmtDateTime($newlastupdate).')';
  1649. }
  1650. }
  1651. }
  1652. sub withings_parseWorkouts($$) {
  1653. my ($hash, $json) = @_;
  1654. my $name = $hash->{NAME};
  1655. #parse
  1656. Log3 "withings", 1, "$name: parseworkouts\n".Dumper($json);
  1657. return undef;
  1658. }
  1659. sub withings_parseVasistas($$;$) {
  1660. my ($hash, $json, $datatype) = @_;
  1661. my $name = $hash->{NAME};
  1662. #parse
  1663. Log3 "withings", 5, "$name: parsevasistas";
  1664. my ($now) = time;
  1665. my $lastupdate = ReadingsVal( $name, ".lastData", 0 );
  1666. $lastupdate = ReadingsVal( $name, ".lastDebug", 0 ) if($datatype =~ /Debug/);
  1667. if( $json ) {
  1668. $hash->{status} = $json->{status};
  1669. if( $hash->{status} == 0 ) {
  1670. my @readings = ();
  1671. my $i = 0;
  1672. my $j;
  1673. my $k;
  1674. my $readingsdate;
  1675. my $newlastupdate = $lastupdate;
  1676. foreach my $series ( @{$json->{body}{series}}) {
  1677. $j=0;
  1678. my @types= (@{$series->{types}});
  1679. my @dates= (@{$series->{dates}});
  1680. my @values= (@{$series->{vasistas}});
  1681. foreach $readingsdate (@dates) {
  1682. my @readingsvalue = (@{$values[$j++]});
  1683. if($readingsdate <= $lastupdate)
  1684. {
  1685. Log3 $name, 4, "$name: old vasistas skipped: ".FmtDateTime($readingsdate);
  1686. next;
  1687. }
  1688. $k=0;
  1689. foreach my $readingstype (@types) {
  1690. my $updatetime = FmtDateTime($readingsdate);
  1691. my $updatevalue = $readingsvalue[$k++];
  1692. my $updatetype = $measure_types{$readingstype}->{reading};
  1693. if( !defined($updatetype) ) {
  1694. Log3 $name, 1, "$name: unknown measure type: $readingstype";
  1695. next;
  1696. }
  1697. if(($updatetype eq "breathing") and ($updatevalue > 90)) {
  1698. Log3 $name, 2, "$name: Implausible Aura reading ".$updatetime.' '.$updatetype.': '.$updatevalue;
  1699. $newlastupdate = $readingsdate if($readingsdate > $newlastupdate);
  1700. next;
  1701. }
  1702. if($updatetype eq "duration")
  1703. {
  1704. Log3 $name, 4, "$name: Duration skipped ".$updatetime.' '.$updatetype.': '.$updatevalue if($updatevalue > 90);
  1705. $newlastupdate = $readingsdate if($readingsdate > $newlastupdate);
  1706. next;
  1707. }
  1708. if($updatetype eq "activityType")
  1709. {
  1710. my $activity = $updatevalue;
  1711. $updatevalue = $activity_types{$updatevalue};
  1712. if( !defined($updatevalue) ) {
  1713. Log3 $name, 1, "$name: unknown activity type: $activity";
  1714. $updatevalue = $activity;
  1715. }
  1716. }
  1717. readingsBeginUpdate($hash);
  1718. $hash->{".updateTimestamp"} = FmtDateTime($readingsdate);
  1719. readingsBulkUpdate( $hash, $updatetype, $updatevalue, 1 );
  1720. $hash->{CHANGETIME}[0] = FmtDateTime($readingsdate);
  1721. readingsEndUpdate($hash,1);
  1722. if($updatetype ne "unknown") {
  1723. $newlastupdate = $readingsdate if($readingsdate > $newlastupdate);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. if($newlastupdate == $lastupdate and $i == 0)
  1729. {
  1730. my $device = withings_getDeviceDetail( $hash );
  1731. $newlastupdate = $json->{requestedenddate} if($json->{requestedenddate});
  1732. $newlastupdate = $device->{lastsessiondate} if($device->{lastsessiondate} and $device->{lastsessiondate} < $newlastupdate);
  1733. $newlastupdate = $device->{lastweighindate} if($device->{lastweighindate} and $device->{lastweighindate} < $newlastupdate);
  1734. }
  1735. $newlastupdate = $now if($newlastupdate > $now);
  1736. if($newlastupdate < ($lastupdate-1))
  1737. {
  1738. Log3 $name, 2, "$name: Vasistas gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") ".$i if($i>0);
  1739. withings_getDeviceProperties($hash) if($i>0);
  1740. $newlastupdate = $lastupdate;
  1741. }
  1742. my ($seconds) = gettimeofday();
  1743. if($datatype =~ /Debug/)
  1744. {
  1745. readingsSingleUpdate( $hash, ".lastDebug", $newlastupdate, 0 );
  1746. } else {
  1747. readingsSingleUpdate( $hash, ".lastData", $newlastupdate, 0 );
  1748. }
  1749. $hash->{LAST_DATA} = FmtDateTime( $newlastupdate );
  1750. Log3 $name, 4, "$name: got ".$i.' entries from Vasistas (latest: '.FmtDateTime($newlastupdate).')';
  1751. }
  1752. }
  1753. }
  1754. sub withings_parseTimeline($$) {
  1755. my ($hash, $json) = @_;
  1756. my $name = $hash->{NAME};
  1757. #parse
  1758. Log3 "withings", 5, "$name: parsemetimeline ";
  1759. my ($now) = time;
  1760. my $lastupdate = ReadingsVal( $name, ".lastAlert", 0 );
  1761. my $newlastupdate = $lastupdate;
  1762. $hash->{status} = $json->{status};
  1763. if( $hash->{status} == 0 )
  1764. {
  1765. my $i = 0;
  1766. foreach my $event ( sort { $a->{epoch} <=> $b->{epoch} } @{$json->{body}{timeline}}) {
  1767. if( $event->{epoch} < $newlastupdate )
  1768. {
  1769. Log3 $name, 5, "$name: old timeline event skipped: ".FmtDateTime($event->{epoch})." $event->{class}";
  1770. next;
  1771. }
  1772. $newlastupdate = $event->{epoch};
  1773. if($event->{class} eq 'period_activity' or $event->{class} eq 'period_activity_start' or $event->{class} eq 'period_activity_cancel' or $event->{class} eq 'period_offline')
  1774. {
  1775. next;
  1776. }
  1777. elsif($event->{class} eq 'deleted')
  1778. {
  1779. Log3 "withings", 5, "withings: event " . FmtDateTime($event->{epoch})." Event was deleted";
  1780. next;
  1781. }
  1782. elsif($event->{class} ne 'noise_detected' && $event->{class} ne 'movement_detected' && $event->{class} ne 'alert_environment' && $event->{class} ne 'offline' && $event->{class} ne 'online' && $event->{class} ne 'snapshot')
  1783. {
  1784. Log3 "withings", 2, "withings: alert class unknown " . $event->{class};
  1785. next;
  1786. }
  1787. my $reading = $timeline_classes{$event->{class}}->{reading};
  1788. my $value = "alert";
  1789. $value = $event->{data}->{value} * 10 ** $timeline_classes{$event->{class}}->{unit} if(defined($event->{class}) && defined($event->{data}) && defined($event->{data}->{value}) && defined($timeline_classes{$event->{class}}) && defined($timeline_classes{$event->{class}}->{unit}));
  1790. if( !defined($reading) ) {
  1791. Log3 $name, 2, "$name: unknown event type: $event->{class}";
  1792. next;
  1793. }
  1794. else
  1795. {
  1796. readingsBeginUpdate($hash);
  1797. $hash->{".updateTimestamp"} = FmtDateTime($event->{epoch});
  1798. readingsBulkUpdate( $hash, $reading, $value, 1 );
  1799. $hash->{CHANGETIME}[0] = FmtDateTime($event->{epoch});
  1800. readingsEndUpdate($hash,1);
  1801. }
  1802. if(AttrVal($name,"videoLinkEvents",0) eq "1")
  1803. {
  1804. my $pathlist = $event->{data}->{path_list}[0];
  1805. my $eventurl = withings_signS3Link($hash,$pathlist->{url},$pathlist->{sign});
  1806. DoTrigger($name, "alerturl: ".$eventurl);
  1807. }
  1808. }
  1809. if($newlastupdate == $lastupdate and $i == 0)
  1810. {
  1811. my $device = withings_getDeviceDetail( $hash );
  1812. $newlastupdate = $json->{requestedenddate} if(defined($json->{requestedenddate}));
  1813. $newlastupdate = $device->{lastsessiondate} if($device->{lastsessiondate} and $device->{lastsessiondate} < $newlastupdate);
  1814. $newlastupdate = $device->{lastweighindate} if($device->{lastweighindate} and $device->{lastweighindate} < $newlastupdate);
  1815. }
  1816. $newlastupdate = $now if($newlastupdate > $now);
  1817. if($newlastupdate < $lastupdate-1)
  1818. {
  1819. Log3 $name, 2, "$name: Timeline gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") ".$i if($i>0);
  1820. withings_getDeviceProperties($hash) if($i>0);
  1821. $newlastupdate = $lastupdate-1;
  1822. }
  1823. readingsSingleUpdate( $hash, ".lastAlert", $newlastupdate+1, 0 );
  1824. #$hash->{LAST_DATA} = FmtDateTime( $lastupdate );
  1825. delete $hash->{CHANGETIME};
  1826. Log3 $name, 4, "$name: got ".$i.' entries from Timeline (latest: '.FmtDateTime($newlastupdate).')';
  1827. }
  1828. }
  1829. sub withings_parseEvents($$) {
  1830. my ($hash, $json) = @_;
  1831. my $name = $hash->{NAME};
  1832. #parse
  1833. Log3 "withings", 5, "$name: parseevents";
  1834. my ($now) = time;
  1835. my $lastupdate = ReadingsVal( $name, ".lastData", 0 );
  1836. my $lastalertupdate = ReadingsVal( $name, ".lastAlert", 0 );
  1837. my $newlastupdate = $lastupdate;
  1838. $hash->{status} = $json->{status};
  1839. if( $hash->{status} == 0 ) {
  1840. my $i = 0;
  1841. foreach my $event ( sort { $a->{date} <=> $b->{date} } @{$json->{body}{events}}) {
  1842. if( $event->{date} < $newlastupdate )
  1843. {
  1844. Log3 $name, 5, "$name: old event skipped: ".FmtDateTime($event->{date})." $event->{type}";
  1845. next;
  1846. }
  1847. next if( $event->{deviceid} ne $hash->{Device} );
  1848. $newlastupdate = $event->{date};
  1849. readingsBeginUpdate($hash);
  1850. $hash->{".updateTimestamp"} = FmtDateTime($event->{date});
  1851. my $changeindex = 0;
  1852. #Log3 "withings", 5, "withings: event " . FmtDateTime($event->{date})." ".$event->{type}." ".$event->{activated}."/".$event->{measure}{value};
  1853. my $reading = $event_types{$event->{type}}->{reading};
  1854. my $value = "notice";
  1855. if($event->{activated})
  1856. {
  1857. $lastalertupdate = $event->{date};
  1858. $value = "alert";
  1859. }
  1860. if( !defined($reading) ) {
  1861. Log3 $name, 2, "$name: unknown event type: $event->{type}";
  1862. next;
  1863. }
  1864. else
  1865. {
  1866. readingsBulkUpdate( $hash, $reading, $value, 1 );
  1867. $hash->{CHANGETIME}[$changeindex++] = FmtDateTime($event->{date});
  1868. }
  1869. if(defined($event->{duration}) and $event->{duration} ne "0")
  1870. {
  1871. my $durationreading = $event_types{$event->{type}}->{duration};
  1872. my $durationvalue = $event->{duration};
  1873. readingsBulkUpdate( $hash, $durationreading, $durationvalue, 0 );
  1874. $hash->{CHANGETIME}[$changeindex++] = FmtDateTime($event->{date});
  1875. }
  1876. if($event->{type} ne "20" and $event->{activated})
  1877. {
  1878. my $thresholdreading = $event_types{$event->{type}}->{threshold};
  1879. my $thresholdvalue = $event->{threshold}->{value} * 10 ** $event_types{$event->{type}}->{unit};
  1880. readingsBulkUpdate( $hash, $thresholdreading, $thresholdvalue, 0 );
  1881. $hash->{CHANGETIME}[$changeindex++] = FmtDateTime($event->{date});
  1882. }
  1883. readingsEndUpdate($hash,1);
  1884. }
  1885. if($newlastupdate == $lastupdate and $i == 0)
  1886. {
  1887. my $device = withings_getDeviceDetail( $hash );
  1888. $newlastupdate = $json->{requestedenddate} if($json->{requestedenddate});
  1889. $newlastupdate = $device->{lastsessiondate} if($device->{lastsessiondate} and $device->{lastsessiondate} < $newlastupdate);
  1890. $newlastupdate = $device->{lastweighindate} if($device->{lastweighindate} and $device->{lastweighindate} < $newlastupdate);
  1891. }
  1892. $newlastupdate = $now if($newlastupdate > $now);
  1893. if($newlastupdate < $lastupdate-1)
  1894. {
  1895. Log3 $name, 2, "$name: Events gap error! (latest: ".FmtDateTime($newlastupdate)." < ".FmtDateTime($lastupdate-1).") ".$i if($i>0);
  1896. withings_getDeviceProperties($hash) if($i>0);
  1897. $newlastupdate = $lastupdate-1;
  1898. }
  1899. readingsBeginUpdate($hash);
  1900. readingsBulkUpdate( $hash, ".lastAlert", $lastalertupdate, 0 );
  1901. readingsBulkUpdate( $hash, ".lastData", $newlastupdate+1, 0 );
  1902. readingsEndUpdate($hash,0);
  1903. $hash->{LAST_DATA} = FmtDateTime( $newlastupdate );
  1904. delete $hash->{CHANGETIME};
  1905. Log3 $name, 4, "$name: got ".$i.' entries from Events (latest: '.FmtDateTime($newlastupdate).')';
  1906. }
  1907. }
  1908. sub withings_Get($$@) {
  1909. my ($hash, $name, $cmd) = @_;
  1910. my $list;
  1911. if( $hash->{SUBTYPE} eq "USER" ) {
  1912. $list = "update:noArg updateAll:noArg";
  1913. if( $cmd eq "updateAll" ) {
  1914. withings_poll($hash,2);
  1915. return undef;
  1916. }
  1917. elsif( $cmd eq "update" ) {
  1918. withings_poll($hash,1);
  1919. return undef;
  1920. }
  1921. } elsif( $hash->{SUBTYPE} eq "DEVICE" || $hash->{SUBTYPE} eq "DUMMY" ) {
  1922. $list = "update:noArg updateAll:noArg";
  1923. $list .= " videoLink:noArg" if(defined($hash->{modelID}) && $hash->{modelID} eq '21');
  1924. $list .= " videoCredentials:noArg" if(defined($hash->{modelID}) && $hash->{modelID} eq '22');
  1925. $list .= " settings:noArg" if(defined($hash->{modelID}) && $hash->{modelID} eq '60' && AttrVal($name,"IP",undef));
  1926. if( $cmd eq "videoCredentials" ) {
  1927. my $credentials = withings_getS3Credentials($hash);
  1928. return undef;
  1929. }
  1930. elsif( $cmd eq "videoLink" ) {
  1931. my $ret = "Flash Player Links:\n";
  1932. my $videolinkdata = withings_getVideoLink($hash);
  1933. if(defined($videolinkdata->{body}{device}))
  1934. {
  1935. #$hash->{videolink_ext} = "http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf?streamType=live&autoPlay=true&playButtonOverlay=false&src=rtmp://".$videolinkdata->{body}{device}{proxy_ip}.":".$videolinkdata->{body}{device}{proxy_port}."/".$videolinkdata->{body}{device}{kp_hash}."/";
  1936. #$hash->{videolink_int} = "http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf?streamType=live&autoPlay=true&playButtonOverlay=false&src=rtmp://".$videolinkdata->{body}{device}{private_ip}.":".$videolinkdata->{body}{device}{proxy_port}."/".$videolinkdata->{body}{device}{kd_hash}."/";
  1937. $ret .= " <a href='".$hash->{videolink_ext}."'>Play video from internet (Flash)</a>\n";
  1938. $ret .= " <a href='".$hash->{videolink_int}."'>Play video from local network (Flash)</a>\n";
  1939. }
  1940. else
  1941. {
  1942. $ret .= " no links available";
  1943. }
  1944. return $ret;
  1945. }
  1946. elsif( $cmd eq "updateAll" ) {
  1947. withings_poll($hash,2);
  1948. return undef;
  1949. }
  1950. elsif( $cmd eq "update" ) {
  1951. withings_poll($hash,1);
  1952. return undef;
  1953. }
  1954. elsif( $cmd eq "settings" ) {
  1955. withings_readAuraAlarm($hash);
  1956. return undef;
  1957. }
  1958. } elsif( $hash->{SUBTYPE} eq "ACCOUNT" ) {
  1959. $list = "users:noArg devices:noArg showAccount:noArg";
  1960. if( $cmd eq "users" ) {
  1961. my $users = withings_getUsers($hash);
  1962. my $ret;
  1963. foreach my $user (@{$users}) {
  1964. $ret .= "$user->{id}\t\[$user->{shortname}\]\t$user->{publickey}\t$user->{firstname} $user->{lastname}\n";
  1965. }
  1966. $ret = "id\tshort\tpublickey\t\tname\n" . $ret if( $ret );;
  1967. $ret = "no users found" if( !$ret );
  1968. return $ret;
  1969. }
  1970. if( $cmd eq "devices" ) {
  1971. my $devices = withings_getDevices($hash);
  1972. my $ret;
  1973. foreach my $device (@{$devices}) {
  1974. my $detail = $device->{deviceproperties};
  1975. $ret .= "$detail->{id}\t$device_types{$detail->{type}}\t$detail->{batterylvl}\t$detail->{sn}\n";
  1976. }
  1977. $ret = "id\ttype\t\tbattery\tSN\n" . $ret if( $ret );;
  1978. $ret = "no devices found" if( !$ret );
  1979. return $ret;
  1980. }
  1981. if( $cmd eq 'showAccount' )
  1982. {
  1983. my $username = $hash->{helper}{username};
  1984. my $password = $hash->{helper}{password};
  1985. return 'no username set' if( !$username );
  1986. return 'no password set' if( !$password );
  1987. $username = withings_decrypt( $username );
  1988. $password = withings_decrypt( $password );
  1989. return "username: $username\npassword: $password";
  1990. }
  1991. }
  1992. return "Unknown argument $cmd, choose one of $list";
  1993. }
  1994. sub withings_Set($$@) {
  1995. my ( $hash, $name, $cmd, @arg ) = @_;
  1996. my $list="";
  1997. if( $hash->{SUBTYPE} eq "DEVICE" and defined($hash->{modelID}) && $hash->{modelID} eq "60" && AttrVal($name,"IP",undef))
  1998. {
  1999. $list = " nap:noArg sleep:noArg alarm:noArg";
  2000. $list .= " stop:noArg snooze:noArg";
  2001. $list .= " nap_volume:slider,0,1,100 nap_brightness:slider,0,1,100";
  2002. $list .= " sleep_volume:slider,0,1,100 sleep_brightness:slider,0,1,100";
  2003. $list .= " clock_state:on,off clock_brightness:slider,0,1,100";
  2004. $list .= " flashMat";
  2005. $list .= " sensors:on,off";
  2006. $list .= " rawCmd";
  2007. if (defined($hash->{helper}{ALARMSCOUNT})&&($hash->{helper}{ALARMSCOUNT}>0))
  2008. {
  2009. for(my $i=1;$i<=$hash->{helper}{ALARMSCOUNT};$i++)
  2010. {
  2011. $list .= " alarm".$i."_time alarm".$i."_volume:slider,0,1,100 alarm".$i."_brightness:slider,0,1,100";
  2012. $list .= " alarm".$i."_state:on,off alarm".$i."_wdays";
  2013. $list .= " alarm".$i."_smartwake:slider,0,1,60";
  2014. }
  2015. }
  2016. if ( lc $cmd eq 'nap' or lc $cmd eq 'sleep' or lc $cmd eq 'alarm' or lc $cmd eq 'stop' or lc $cmd eq 'snooze' )
  2017. {
  2018. return withings_setAuraAlarm($hash,$cmd);
  2019. }
  2020. elsif ( lc $cmd eq 'rawcmd')
  2021. {
  2022. return withings_setAuraDebug($hash,join( "", @arg ));
  2023. }
  2024. #elsif( index( $cmd, "alarm" ) != -1 )
  2025. #{
  2026. # my $alarmno = int( substr( $cmd, 5 ) ) + 0;
  2027. # return( withings_parseAlarm( $hash, $alarmno, @arg ) );
  2028. #}
  2029. elsif ( lc $cmd =~ /^alarm/ or lc $cmd =~ /^nap/ or lc $cmd =~ /^sleep/ or lc $cmd =~ /^clock/ or lc $cmd eq 'smartwake' )
  2030. {
  2031. readingsSingleUpdate( $hash, $cmd, join( ",", @arg ), 1 );
  2032. return withings_setAuraAlarm($hash,$cmd,join( ":", @arg ));
  2033. }
  2034. elsif ( lc $cmd eq "flashmat" )
  2035. {
  2036. return withings_setAuraAlarm($hash,$cmd,join( ":", @arg ));
  2037. }
  2038. elsif ( lc $cmd eq "sensors" )
  2039. {
  2040. return withings_setAuraAlarm($hash,$cmd,join( ":", @arg ));
  2041. }
  2042. return "Unknown argument $cmd, choose one of $list";
  2043. } elsif($hash->{SUBTYPE} eq "ACCOUNT") {
  2044. $list = "autocreate:noArg";
  2045. return withings_autocreate($hash) if($cmd eq "autocreate");
  2046. return "Unknown argument $cmd, choose one of $list";
  2047. } else {
  2048. return "Unknown argument $cmd, choose one of $list";
  2049. }
  2050. }
  2051. sub withings_readAuraAlarm($) {
  2052. my ($hash) = @_;
  2053. my $name = $hash->{NAME};
  2054. Log3 $name, 5, "$name: readauraalarm";
  2055. my $auraip = AttrVal($name,"IP",undef);
  2056. return if(!$auraip);
  2057. my $socket = new IO::Socket::INET (
  2058. PeerHost => $auraip,
  2059. PeerPort => '7685',
  2060. Proto => 'tcp',
  2061. Timeout => 5,
  2062. ) or die "ERROR in Socket Creation : $!\n";
  2063. return if(!$socket);
  2064. $socket->autoflush(1);
  2065. my $data = "000100010100050101010000"; #hello
  2066. $socket->send(pack('H*', $data));
  2067. $socket->flush();
  2068. $socket->recv($data,1024);
  2069. $socket->flush();
  2070. $data="010100050101110000"; #hello2
  2071. $socket->send(pack('H*', $data));
  2072. $socket->flush();
  2073. $socket->recv($data, 1024);
  2074. $socket->flush();
  2075. $data="0101000a01090a0005090a000100"; #ping
  2076. $socket->send(pack('H*', $data));
  2077. $socket->flush();
  2078. $socket->recv($data, 1024);
  2079. $socket->flush();
  2080. $data="010100050101250000"; #new alarmdata
  2081. $socket->send(pack('H*', $data));
  2082. $socket->flush();
  2083. $socket->recv($data, 1024);
  2084. $socket->flush();
  2085. my $datalength = ord(substr($data,2,1))*256 + ord(substr($data,3,1));
  2086. Log3 $name, 5, "$name: alarmdata ($datalength)".unpack('H*', $data);
  2087. my $base = 9;
  2088. readingsBeginUpdate($hash);
  2089. my $alarmcounter = 1;
  2090. my @dataarray = split("05120007",unpack('H*', $data));
  2091. while(defined($dataarray[$alarmcounter]))
  2092. {
  2093. my @alarmparts = split("091600",$dataarray[$alarmcounter]);#seriously, withings?
  2094. my $timedatehex = pack('H*', $alarmparts[0]);
  2095. my $alarmhour = ord(substr($timedatehex,0,1));
  2096. my $alarmminute = ord(substr($timedatehex,1,1));
  2097. my $alarmdays = ord(substr($timedatehex,2,1));
  2098. my $alarmstate = (ord(substr($timedatehex,2,1)) > 128) ? "on" : "off";
  2099. my $alarmperiod = ord(substr($timedatehex,6,1));
  2100. my $alarmvolume = 0;
  2101. my $alarmbrightness = 0;
  2102. my $alarmsong = 0;
  2103. for(my $i=1;$i<=3;$i++) #whoever did this must have been high as fuck!
  2104. {
  2105. my $hexdata = pack('H*', $alarmparts[$i]);
  2106. my $datatype = ord(substr($hexdata,1,1)); #order is not consistent
  2107. my $datalength = ord(substr($hexdata,2,1));
  2108. if($datatype == 1)
  2109. {
  2110. $alarmvolume = ord(substr($hexdata,3,1))-48; #value as ascii characters
  2111. $alarmvolume = $alarmvolume*10 + ord(substr($hexdata,4,1))-48 if($datalength>1);
  2112. $alarmvolume = $alarmvolume*10 + ord(substr($hexdata,5,1))-48 if($datalength>2);
  2113. }
  2114. elsif($datatype == 2)
  2115. {
  2116. $alarmbrightness = ord(substr($hexdata,3,1))-48; #same for other values - wtf?
  2117. $alarmbrightness = $alarmbrightness*10 + ord(substr($hexdata,4,1))-48 if($datalength>1);
  2118. $alarmbrightness = $alarmbrightness*10 + ord(substr($hexdata,5,1))-48 if($datalength>2);
  2119. }
  2120. elsif($datatype == 3)
  2121. {
  2122. $alarmsong = ord(substr($hexdata,3,1))-48;
  2123. }
  2124. else{
  2125. Log3 $name, 2, "$name: unknown alarm data type: $datatype";
  2126. }
  2127. }
  2128. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_time", sprintf( "%02d:%02d:%02d",$alarmhour,$alarmminute,0), 1 );
  2129. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_wdays", withings_int2Weekdays($alarmdays), 1 );
  2130. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_volume", $alarmvolume, 1 );
  2131. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_brightness", $alarmbrightness, 1 );
  2132. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_smartwake", $alarmperiod, 1 );
  2133. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_state", $alarmstate, 1 );
  2134. readingsBulkUpdate( $hash, "alarm".$alarmcounter."_sound", $alarm_sound{$alarmsong}, 1 );
  2135. Log3 $name, 4, "$name: alarm $alarmstate $alarmhour:$alarmminute ($alarmperiod) on ".withings_int2Weekdays($alarmdays)." light:$alarmbrightness vol:$alarmvolume [$base]";
  2136. $hash->{helper}{ALARMSCOUNT} = $alarmcounter;
  2137. $alarmcounter++;
  2138. }
  2139. for(my $i=$alarmcounter;$i<10;$i++)
  2140. {
  2141. fhem( "deletereading $name alarm".$i."_.*" );
  2142. }
  2143. $data="010100050109100000"; #sensordata
  2144. $socket->send(pack('H*', $data));
  2145. $socket->flush();
  2146. $socket->recv($data, 1024);
  2147. $socket->flush();
  2148. my $sensors = (ord(substr($data,19,1))==0)?"on":"off";
  2149. readingsBulkUpdate( $hash, "sensors", $sensors, 1 );
  2150. $data="0101000b0109060006090800020300"; #sleepdata
  2151. $socket->send(pack('H*', $data));
  2152. $socket->flush();
  2153. $socket->recv($data, 1024);
  2154. $socket->flush();
  2155. #Log3 $name, 4, "$name: sleepdata ".unpack('H*', $data);
  2156. my $sleepvolume = ord(substr($data,13,1));
  2157. my $sleepbrightness = ord(substr($data,14,1));
  2158. my $sleepsong = ord(substr($data,16,1));
  2159. readingsBulkUpdate( $hash, "sleep_volume", $sleepvolume, 1 );
  2160. readingsBulkUpdate( $hash, "sleep_brightness", $sleepbrightness, 1 );
  2161. readingsBulkUpdate( $hash, "sleep_sound", $sleep_sound{$sleepsong}, 1 );
  2162. $data="0101000b0109060006090800020200"; #napdata
  2163. $socket->send(pack('H*', $data));
  2164. $socket->flush();
  2165. $socket->recv($data, 1024);
  2166. $socket->flush();
  2167. #Log3 $name, 4, "$name: napdata ".unpack('H*', $data);
  2168. my $napvolume = ord(substr($data,13,1));
  2169. my $napbrightness = ord(substr($data,14,1));
  2170. my $napsong = ord(substr($data,16,1));
  2171. readingsBulkUpdate( $hash, "nap_volume", $napvolume, 1 );
  2172. readingsBulkUpdate( $hash, "nap_brightness", $napbrightness, 1 );
  2173. readingsBulkUpdate( $hash, "nap_sound", $nap_sound{$napsong}, 1 );
  2174. $data="010100050109100000"; #clock
  2175. $socket->send(pack('H*', $data));
  2176. $socket->flush();
  2177. $socket->recv($data, 1024);
  2178. $socket->flush();
  2179. my $clockdisplay = ord(substr($data,13,1));
  2180. my $clockbrightness = ord(substr($data,14,1));
  2181. readingsBulkUpdate( $hash, "clock_state", ($clockdisplay ? "on":"off"), 1 );
  2182. readingsBulkUpdate( $hash, "clock_brightness", $clockbrightness, 1 );
  2183. #Log3 $name, 4, "$name: clock ".unpack('H*', $data);
  2184. $data="010100050109070000"; #state
  2185. $socket->send(pack('H*', $data));
  2186. $socket->flush();
  2187. $socket->recv($data, 1024);
  2188. $socket->flush();
  2189. #Log3 $name, 4, "$name: state ".unpack('H*', $data);
  2190. my $devicestate = ord(substr($data,18,1));
  2191. my $alarmtype = ord(substr($data,13,1));
  2192. if($devicestate eq 0)
  2193. {
  2194. readingsBulkUpdate( $hash, "state", "off", 1 );
  2195. }
  2196. elsif($devicestate eq 2)
  2197. {
  2198. readingsBulkUpdate( $hash, "state", "snoozed", 1 );
  2199. }
  2200. elsif($devicestate eq 1)
  2201. {
  2202. readingsBulkUpdate( $hash, "state", "sleep", 1 ) if($alarmtype eq 1);
  2203. readingsBulkUpdate( $hash, "state", "alarm", 1 ) if($alarmtype eq 2);
  2204. readingsBulkUpdate( $hash, "state", "nap", 1 ) if($alarmtype eq 3);
  2205. }
  2206. readingsEndUpdate($hash,1);
  2207. $socket->close();
  2208. return;
  2209. }
  2210. sub withings_setAuraAlarm($$;$) {
  2211. my ($hash, $setting, $value) = @_;
  2212. my $name = $hash->{NAME};
  2213. Log3 $name, 5, "$name: setaura ".$setting;
  2214. my $auraip = AttrVal($name,"IP",undef);
  2215. return if(!$auraip);
  2216. my $socket = new IO::Socket::INET (
  2217. PeerHost => $auraip,
  2218. PeerPort => '7685',
  2219. Proto => 'tcp',
  2220. Timeout => 5,
  2221. ) or die "ERROR in Socket Creation : $!\n";
  2222. return if(!$socket);
  2223. $socket->autoflush(1);
  2224. my $data = "000100010100050101010000"; #hello
  2225. $socket->send(pack('H*', $data));
  2226. $socket->flush();
  2227. $socket->recv($data,1024);
  2228. $socket->flush();
  2229. $data="010100050101110000"; #hello2
  2230. $socket->send(pack('H*', $data));
  2231. $socket->flush();
  2232. $socket->recv($data,1024);
  2233. $socket->flush();
  2234. $data="0101000a01090a0005090a000100"; #ping
  2235. $socket->send(pack('H*', $data));
  2236. $socket->flush();
  2237. $socket->recv($data,1024);
  2238. $socket->flush();
  2239. $data="010100050109070000"; #getstate
  2240. if($setting eq "nap")
  2241. {
  2242. $data="0101000b0109030006090800020200"; #nap
  2243. }
  2244. elsif($setting eq "sleep")
  2245. {
  2246. $data="0101000b0109030006090800020300"; #sleep
  2247. }
  2248. elsif($setting eq "alarm")
  2249. {
  2250. $data="0101000b0109030006090800020400"; #alarm
  2251. }
  2252. elsif($setting eq "stop")
  2253. {
  2254. $data="010100050109040000"; #stop
  2255. }
  2256. elsif($setting eq "snooze")
  2257. {
  2258. $data="010100050109110000"; #snooze
  2259. }
  2260. elsif($setting =~ /^alarm/)
  2261. {
  2262. my $alarmno = int( substr( $setting,5,1 ) ) + 0;
  2263. my $volume = ReadingsVal( $name, "alarm".$alarmno."_volume", 60);
  2264. my $volumestring = "";
  2265. if($volume > 99)
  2266. {
  2267. $volumestring = "050103" . sprintf("%.2x",substr($volume,0,1)+48) . sprintf("%.2x",substr($volume,1,1)+48) . sprintf("%.2x",substr($volume,2,1)+48);
  2268. }
  2269. elsif($volume > 9)
  2270. {
  2271. $volumestring = "040102" . sprintf("%.2x",substr($volume,0,1)+48) . sprintf("%.2x",substr($volume,1,1)+48);
  2272. }
  2273. else
  2274. {
  2275. $volumestring = "030101" . sprintf("%.2x",$volume+48);
  2276. }
  2277. my $brightness = ReadingsVal( $name, "alarm".$alarmno."_brightness", 60);
  2278. my $brightnessstring = "";
  2279. if($brightness > 99)
  2280. {
  2281. $brightnessstring = "050203" . sprintf("%.2x",substr($brightness,0,1)+48) . sprintf("%.2x",substr($brightness,1,1)+48) . sprintf("%.2x",substr($brightness,2,1)+48);;
  2282. }
  2283. elsif($brightness > 9)
  2284. {
  2285. $brightnessstring = "040202" . sprintf("%.2x",substr($brightness,0,1)+48) . sprintf("%.2x",substr($brightness,1,1)+48);
  2286. }
  2287. else
  2288. {
  2289. $brightnessstring = "030201" . sprintf("%.2x",$brightness+48);
  2290. }
  2291. $data = "05120007";
  2292. my @timestr = split(":",ReadingsVal( $name, "alarm".$alarmno."_time", "07:00" ));
  2293. $data .= sprintf("%.2x%.2x",$timestr[0],$timestr[1]);
  2294. my $alarmint = withings_weekdays2Int(ReadingsVal( $name, "alarm".$alarmno."_wdays", "all"));
  2295. $alarmint += 128 if(ReadingsVal( $name, "alarm".$alarmno."_state", "on") eq "on");
  2296. $data .= sprintf("%.2x",$alarmint);
  2297. $data .= "000000";
  2298. $data .= sprintf("%.2x",ReadingsVal( $name, "alarm".$alarmno."_smartwake", 10));
  2299. $data .= "091600";
  2300. $data .= $volumestring;
  2301. $data .= "091600";
  2302. $data .= $brightnessstring;
  2303. $data .= "091600030301";
  2304. my $alarmsong = $alarm_song{ReadingsVal( $name, "alarm".$alarmno."_sound", 1)};
  2305. $alarmsong = 1 if(!defined($alarmsong) || $alarmsong==0);
  2306. $data .= sprintf("%.2x",$alarmsong+48);
  2307. my $datalen = length($data)/2;
  2308. $data = "010100".sprintf("%.2x",$datalen+10)."01012900".sprintf("%.2x",$datalen+5)."01260001".sprintf("%.2x",$alarmno).$data;
  2309. #if($setting =~ /volume/i or $setting =~ /brightness/i or $setting =~ /song/i )
  2310. #{
  2311. # $data = "0101000d010905000809060004";
  2312. # $data .= sprintf("%.2x",ReadingsVal( $name, "alarm".$alarmno."_volume", 60));
  2313. # $data .= sprintf("%.2x",ReadingsVal( $name, "alarm".$alarmno."_brightness", 60));
  2314. # $data .= "04";
  2315. # $data .= sprintf("%.2x",$alarm_song{ReadingsVal( $name, "alarm".$alarmno."_sound", 1)});
  2316. #}
  2317. #else
  2318. #{
  2319. # $data = "0101001101011b000c09040008";
  2320. # my @timestr = split(":",ReadingsVal( $name, "alarm".$alarmno."_time", "07:00" ));
  2321. # $data .= sprintf("%.2x%.2x",$timestr[0],$timestr[1]);
  2322. # my $alarmint = withings_weekdays2Int(ReadingsVal( $name, "alarm".$alarmno."_wdays", "all"));
  2323. # $alarmint += 128 if(ReadingsVal( $name, "alarm".$alarmno."_state", "on") eq "on");
  2324. # $data .= sprintf("%.2x",$alarmint);
  2325. # $data .= "6565d2";
  2326. # $data .= sprintf("%.2x",(ReadingsVal( $name, "alarm".$alarmno."_state", "on") eq "on" ? 1 : 0));
  2327. # $data .= sprintf("%.2x",ReadingsVal( $name, "alarm".$alarmno."_smartwake", 10));
  2328. #}
  2329. Log3 $name, 5, "$name: set alarm ".$data;
  2330. }
  2331. elsif($setting =~ /^nap/)
  2332. {
  2333. $data = "0101000d010905000809060004";
  2334. $data .= sprintf("%.2x",ReadingsVal( $name, "nap_volume", 25));
  2335. $data .= sprintf("%.2x",ReadingsVal( $name, "nap_brightness", 25));
  2336. $data .= "02";
  2337. $data .= sprintf("%.2x",ReadingsVal( $name, "nap_sound", 1)==0?1:ReadingsVal( $name, "nap_sound", 1));
  2338. }
  2339. elsif($setting =~ /^sleep/)
  2340. {
  2341. $data = "0101000d010905000809060004";
  2342. $data .= sprintf("%.2x",ReadingsVal( $name, "sleep_volume", 25));
  2343. $data .= sprintf("%.2x",ReadingsVal( $name, "sleep_brightness", 10));
  2344. $data .= "03";
  2345. $data .= sprintf("%.2x",ReadingsVal( $name, "sleep_sound", 1)==0?1:ReadingsVal( $name, "sleep_sound", 1));
  2346. }
  2347. elsif($setting =~ /^clock/)
  2348. {
  2349. $data = "0101000b01090f0006090d0002";
  2350. $data .= (ReadingsVal( $name, "clock_state", 1) ? "01":"00");
  2351. $data .= sprintf("%.2x",ReadingsVal( $name, "clock_brightness", 40));
  2352. }
  2353. elsif($setting =~ /^flashMat/)
  2354. {
  2355. $data = "0101003201090c002d0413001211";
  2356. $data .= unpack('H*', $value);
  2357. $data .= "080a0013000000000000000000004e200000000000ffff";
  2358. }
  2359. elsif($setting =~ /^sensors/)
  2360. {
  2361. $data = "0101000a01090f0005080b000100";
  2362. $data = "0101000a01090f0005080b000101" if($value eq "off");
  2363. }
  2364. Log3 $name, 3, "$name: writesocket ".$data;
  2365. $socket->send(pack('H*', $data));
  2366. $socket->flush();
  2367. $socket->recv($data, 1024);
  2368. $socket->flush();
  2369. Log3 $name, 4, "$name: readsocket ".unpack('H*', $data);
  2370. $socket->close();
  2371. return;
  2372. }
  2373. sub withings_setAuraDebug($$;$) {
  2374. my ($hash, $value) = @_;
  2375. my $name = $hash->{NAME};
  2376. my $auraip = AttrVal($name,"IP",undef);
  2377. return if(!$auraip);
  2378. my $socket = new IO::Socket::INET (
  2379. PeerHost => $auraip,
  2380. PeerPort => '7685',
  2381. Proto => 'tcp',
  2382. Timeout => 5,
  2383. ) or die "ERROR in Socket Creation : $!\n";
  2384. return if(!$socket);
  2385. $socket->autoflush(1);
  2386. my $data = "000100010100050101010000"; #hello
  2387. $socket->send(pack('H*', $data));
  2388. $socket->flush();
  2389. $socket->recv($data,1024);
  2390. $socket->flush();
  2391. $data="010100050101110000"; #hello2
  2392. $socket->send(pack('H*', $data));
  2393. $socket->flush();
  2394. $socket->recv($data,1024);
  2395. $socket->flush();
  2396. $data="0101000a01090a0005090a000100"; #ping
  2397. $socket->send(pack('H*', $data));
  2398. $socket->flush();
  2399. $socket->recv($data,1024);
  2400. $socket->flush();
  2401. $data=$value; #debug
  2402. Log3 $name, 5, "$name: writesocket ".$data;
  2403. Log3 $name, 5, "$name: writesocket ".pack('H*', $data);
  2404. $socket->send(pack('H*', $data));
  2405. $socket->flush();
  2406. $data="";
  2407. $socket->recv($data, 1024);
  2408. $socket->flush();
  2409. Log3 $name, 5, "$name: readsocket ".$data;
  2410. Log3 $name, 5, "$name: readsocket ".unpack('H*', $data);
  2411. $socket->close();
  2412. return;
  2413. }
  2414. sub withings_Attr($$$) {
  2415. my ($cmd, $name, $attrName, $attrVal) = @_;
  2416. return undef if(!defined($defs{$name}));
  2417. my $orig = $attrVal;
  2418. $attrVal = int($attrVal) if($attrName eq "intervalData" or $attrName eq "intervalAlert" or $attrName eq "intervalProperties" or $attrName eq "intervalDebug");
  2419. $attrVal = 300 if($attrName eq "intervalData" && $attrVal < 300 );
  2420. $attrVal = 300 if($attrName eq "intervalDebug" && $attrVal < 300 );
  2421. $attrVal = 120 if($attrName eq "intervalAlert" && $attrVal < 120 );
  2422. $attrVal = 1800 if($attrName eq "intervalProperties" && $attrVal < 1800 );
  2423. if( $attrName eq "disable" ) {
  2424. my $hash = $defs{$name};
  2425. RemoveInternalTimer($hash);
  2426. if( $cmd eq "set" && $attrVal ne "0" ) {
  2427. } else {
  2428. $attr{$name}{$attrName} = 0;
  2429. withings_poll($hash,0);
  2430. }
  2431. }
  2432. elsif( $attrName eq "nossl" ) {
  2433. my $hash = $defs{$name};
  2434. if( $cmd eq "set" && $attrVal ne "0" ) {
  2435. $hash->{'.https'} = "http";
  2436. } else {
  2437. $hash->{'.https'} = "https";
  2438. }
  2439. }
  2440. if( $cmd eq "set" ) {
  2441. if( $orig ne $attrVal ) {
  2442. $attr{$name}{$attrName} = $attrVal;
  2443. return $attrName ." set to ". $attrVal;
  2444. }
  2445. }
  2446. return;
  2447. }
  2448. ##########################
  2449. sub withings_Dispatch($$$) {
  2450. my ($param, $err, $data) = @_;
  2451. my $hash = $param->{hash};
  2452. my $name = $hash->{NAME};
  2453. Log3 $name, 5, "$name: dispatch ".$param->{type};
  2454. if( $err )
  2455. {
  2456. Log3 $name, 1, "$name: http request failed: type $param->{type} - $err";
  2457. }
  2458. elsif( $data )
  2459. {
  2460. $data =~ s/\n//g;
  2461. if( $data !~ /{.*}/ or $data =~ /</)
  2462. {
  2463. Log3 $name, 1, "$name: invalid json detected: >>$data<< " . $param->{type} if($data ne "[]");
  2464. return undef;
  2465. }
  2466. my $json = eval { JSON->new->utf8(0)->decode($data) };
  2467. if($@)
  2468. {
  2469. Log3 $name, 2, "$name: json evaluation error on dispatch type ".$param->{type}." ".$@;
  2470. return undef;
  2471. }
  2472. Log3 $name, 4, "$name: json returned: ".Dumper($json);
  2473. if(defined($param->{enddate}))
  2474. {
  2475. $json->{requestedenddate} = $param->{enddate};
  2476. }
  2477. if( $param->{type} eq 'deviceReadingsScale' || $param->{type} eq 'deviceReadingsBedside' || $param->{type} eq 'deviceReadingsHome' ) {
  2478. withings_parseMeasurements($hash, $json);
  2479. } elsif( $param->{type} eq 'userReadingsSleep' || $param->{type} eq 'userReadingsSleepDebug' || $param->{type} eq 'userReadingsActivity' ) {
  2480. withings_parseVasistas($hash, $json, $param->{type});
  2481. } elsif( $param->{type} eq 'deviceReadingsBaby' || $param->{type} eq 'deviceAlertsBaby' ) {
  2482. withings_parseEvents($hash, $json);
  2483. } elsif( $param->{type} eq 'deviceAlertsHome' ) {
  2484. withings_parseTimeline($hash, $json);
  2485. } elsif( $param->{type} eq 'userReadingsCommon' ) {
  2486. withings_parseMeasureGroups($hash, $json);
  2487. } elsif( $param->{type} eq 'userDailyAggregate' ) {
  2488. withings_parseAggregate($hash, $json);
  2489. } elsif( $param->{type} eq 'userDailyActivity' ) {
  2490. withings_parseActivity($hash, $json);
  2491. } elsif( $param->{type} eq 'userDailyWorkouts' ) {
  2492. withings_parseWorkouts($hash, $json);
  2493. } elsif( $param->{type} eq 'deviceProperties' ) {
  2494. withings_parseProperties($hash, $json);
  2495. }
  2496. }
  2497. }
  2498. sub withings_encrypt($)
  2499. {
  2500. my ($decoded) = @_;
  2501. my $key = getUniqueId();
  2502. my $encoded;
  2503. return $decoded if( $decoded =~ /crypt:/ );
  2504. for my $char (split //, $decoded) {
  2505. my $encode = chop($key);
  2506. $encoded .= sprintf("%.2x",ord($char)^ord($encode));
  2507. $key = $encode.$key;
  2508. }
  2509. return 'crypt:'.$encoded;
  2510. }
  2511. sub withings_decrypt($)
  2512. {
  2513. my ($encoded) = @_;
  2514. my $key = getUniqueId();
  2515. my $decoded;
  2516. return $encoded if( $encoded !~ /crypt:/ );
  2517. $encoded = $1 if( $encoded =~ /crypt:(.*)/ );
  2518. for my $char (map { pack('C', hex($_)) } ($encoded =~ /(..)/g)) {
  2519. my $decode = chop($key);
  2520. $decoded .= chr(ord($char)^ord($decode));
  2521. $key = $decode.$key;
  2522. }
  2523. return $decoded;
  2524. }
  2525. ##########################
  2526. sub withings_DbLog_splitFn($) {
  2527. my ($event) = @_;
  2528. my ($reading, $value, $unit) = "";
  2529. Log3 ("dbsplit", 5, "withings dbsplit event ".$event);
  2530. my @parts = split(/ /,$event,3);
  2531. $reading = $parts[0];
  2532. $reading =~ tr/://d;
  2533. $value = $parts[1];
  2534. if($event =~ m/heartPulse/)
  2535. {
  2536. $reading = 'heartPulse';
  2537. $unit = 'bpm';
  2538. }
  2539. elsif($event =~ m/pulseWave/)
  2540. {
  2541. $reading = 'pulseWave';
  2542. $unit = 'm/s';
  2543. }
  2544. elsif($event =~ m/dailyDescent/)
  2545. {
  2546. $reading = 'dailyDescent';
  2547. $unit = 'm';
  2548. }
  2549. elsif($event =~ m/dailyDistance/)
  2550. {
  2551. $reading = 'dailyDistance';
  2552. $unit = 'm';
  2553. }
  2554. elsif($event =~ m/dailyElevation/)
  2555. {
  2556. $reading = 'dailyElevation';
  2557. $unit = 'm';
  2558. }
  2559. elsif($event =~ m/dailySteps/)
  2560. {
  2561. $reading = 'dailySteps';
  2562. $unit = 'steps';
  2563. }
  2564. elsif($event =~ m/steps/)
  2565. {
  2566. $reading = 'steps';
  2567. $unit = 'steps';
  2568. }
  2569. elsif($event =~ m/temperature/)
  2570. {
  2571. $reading = 'temperature';
  2572. $unit = '˚C';
  2573. }
  2574. elsif($event =~ m/bodyTemperature/)
  2575. {
  2576. $reading = 'bodyTemperature';
  2577. $unit = '˚C';
  2578. }
  2579. elsif($event =~ m/skinTemperature/)
  2580. {
  2581. $reading = 'skinTemperature';
  2582. $unit = '˚C';
  2583. }
  2584. elsif($event =~ m/humidity/)
  2585. {
  2586. $reading = 'humidity';
  2587. $unit = '%';
  2588. }
  2589. elsif($event =~ m/systolicBloodPressure/)
  2590. {
  2591. $reading = 'systolicBloodPressure';
  2592. $unit = 'mmHg';
  2593. }
  2594. elsif($event =~ m/diastolicBloodPressure/)
  2595. {
  2596. $reading = 'diastolicBloodPressure';
  2597. $unit = 'mmHg';
  2598. }
  2599. elsif($event =~ m/spo2/)
  2600. {
  2601. $reading = 'spo2';
  2602. $unit = '%';
  2603. }
  2604. elsif($event =~ m/boneMassWeight/)
  2605. {
  2606. $reading = 'boneMassWeight';
  2607. $unit = 'kg';
  2608. }
  2609. elsif($event =~ m/fatFreeMass/)
  2610. {
  2611. $reading = 'fatFreeMass';
  2612. $unit = 'kg';
  2613. }
  2614. elsif($event =~ m/fatMassWeight/)
  2615. {
  2616. $reading = 'fatMassWeight';
  2617. $unit = 'kg';
  2618. }
  2619. elsif($event =~ m/weight/)
  2620. {
  2621. $reading = 'weight';
  2622. $unit = 'kg';
  2623. }
  2624. elsif($event =~ m/muscleRatio/)
  2625. {
  2626. $reading = 'muscleRatio';
  2627. $unit = '%';
  2628. }
  2629. elsif($event =~ m/boneRatio/)
  2630. {
  2631. $reading = 'boneRatio';
  2632. $unit = '%';
  2633. }
  2634. elsif($event =~ m/fatRatio/)
  2635. {
  2636. $reading = 'fatRatio';
  2637. $unit = '%';
  2638. }
  2639. elsif($event =~ m/hydration/)
  2640. {
  2641. $reading = 'hydration';
  2642. $unit = '%';
  2643. }
  2644. elsif($event =~ m/waterMass/)
  2645. {
  2646. $reading = 'waterMass';
  2647. $unit = 'kg';
  2648. }
  2649. elsif($event =~ m/dailyCaloriesPassive/)
  2650. {
  2651. $reading = 'dailyCaloriesPassive';
  2652. $unit = 'kcal';
  2653. }
  2654. elsif($event =~ m/dailyCaloriesActive/)
  2655. {
  2656. $reading = 'dailyCaloriesActive';
  2657. $unit = 'kcal';
  2658. }
  2659. elsif($event =~ m/calories/)
  2660. {
  2661. $reading = 'calories';
  2662. $unit = 'kcal';
  2663. }
  2664. elsif($event =~ m/co2/)
  2665. {
  2666. $reading = 'co2';
  2667. $unit = 'ppm';
  2668. }
  2669. elsif($event =~ m/voc/)
  2670. {
  2671. $reading = 'voc';
  2672. $unit = 'ppm';
  2673. }
  2674. elsif($event =~ m/light/)
  2675. {
  2676. $reading = 'light';
  2677. $unit = 'lux';
  2678. }
  2679. elsif($event =~ m/batteryLevel/)
  2680. {
  2681. $reading = 'batteryLevel';
  2682. $unit = '%';
  2683. }
  2684. else
  2685. {
  2686. $value = $parts[1];
  2687. $value = $value." ".$parts[2] if(defined($parts[2]));
  2688. }
  2689. #Log3 ("dbsplit", 5, "withings dbsplit output ".$reading." / ".$value." / ".$unit);
  2690. return ($reading, $value, $unit);
  2691. }
  2692. sub withings_int2Weekdays( $ ) {
  2693. my ($wdayint) = @_;
  2694. my $wdayargs = '';
  2695. my $weekdays = '';
  2696. $wdayint -= 128 if($wdayint >= 128);
  2697. if($wdayint >= 64)
  2698. {
  2699. $wdayargs.="Sa";
  2700. $wdayint-=64;
  2701. }
  2702. if($wdayint >= 32)
  2703. {
  2704. $wdayargs.="Fr";
  2705. $wdayint-=32;
  2706. }
  2707. if($wdayint >= 16)
  2708. {
  2709. $wdayargs.="Th";
  2710. $wdayint-=16;
  2711. }
  2712. if($wdayint >= 8)
  2713. {
  2714. $wdayargs.="We";
  2715. $wdayint-=8;
  2716. }
  2717. if($wdayint >= 4)
  2718. {
  2719. $wdayargs.="Tu";
  2720. $wdayint-=4;
  2721. }
  2722. if($wdayint >= 2)
  2723. {
  2724. $wdayargs.="Mo";
  2725. $wdayint-=2;
  2726. }
  2727. if($wdayint >= 1)
  2728. {
  2729. $wdayargs.="Su";
  2730. $wdayint-=1;
  2731. }
  2732. if(index($wdayargs,"Mo") != -1)
  2733. {
  2734. $weekdays.='Mo,';
  2735. }
  2736. if(index($wdayargs,"Tu") != -1)
  2737. {
  2738. $weekdays.='Tu,';
  2739. }
  2740. if(index($wdayargs,"We") != -1)
  2741. {
  2742. $weekdays.='We,';
  2743. }
  2744. if(index($wdayargs,"Th") != -1)
  2745. {
  2746. $weekdays.='Th,';
  2747. }
  2748. if(index($wdayargs,"Fr") != -1)
  2749. {
  2750. $weekdays.='Fr,';
  2751. }
  2752. if(index($wdayargs,"Sa") != -1)
  2753. {
  2754. $weekdays.='Sa,';
  2755. }
  2756. if(index($wdayargs,"Su") != -1)
  2757. {
  2758. $weekdays.='Su,';
  2759. }
  2760. if($weekdays eq "Mo,Tu,We,Th,Fr,Sa,Su,")
  2761. {
  2762. $weekdays="all";
  2763. }
  2764. if($weekdays eq "")
  2765. {
  2766. $weekdays="none";
  2767. }
  2768. $weekdays=~ s/,$//;
  2769. return $weekdays;
  2770. }
  2771. sub withings_weekdays2Int( $ ) {
  2772. my ($wdayargs) = @_;
  2773. my $weekdays = 0;
  2774. if(index($wdayargs,"Mo") != -1 || index($wdayargs,"1") != -1)
  2775. {
  2776. $weekdays+=2;
  2777. }
  2778. if(index($wdayargs,"Tu") != -1 || index($wdayargs,"Di") != -1 || index($wdayargs,"2") != -1)
  2779. {
  2780. $weekdays+=4;
  2781. }
  2782. if(index($wdayargs,"We") != -1 || index($wdayargs,"Mi") != -1 || index($wdayargs,"3") != -1)
  2783. {
  2784. $weekdays+=8;
  2785. }
  2786. if(index($wdayargs,"Th") != -1 || index($wdayargs,"Do") != -1 || index($wdayargs,"4") != -1)
  2787. {
  2788. $weekdays+=16;
  2789. }
  2790. if(index($wdayargs,"Fr") != -1 || index($wdayargs,"5") != -1)
  2791. {
  2792. $weekdays+=32;
  2793. }
  2794. if(index($wdayargs,"Sa") != -1 || index($wdayargs,"6") != -1)
  2795. {
  2796. $weekdays+=64;
  2797. }
  2798. if(index($wdayargs,"Su") != -1 || index($wdayargs,"So") != -1 || index($wdayargs,"0") != -1)
  2799. {
  2800. $weekdays+=1;
  2801. }
  2802. if(index($wdayargs,"all") != -1 || index($wdayargs,"daily") != -1 || index($wdayargs,"7") != -1)
  2803. {
  2804. $weekdays=127;
  2805. }
  2806. if(index($wdayargs,"none") != -1 || index($wdayargs,"once") != -1)
  2807. {
  2808. $weekdays=0;
  2809. }
  2810. return $weekdays;
  2811. }
  2812. 1;
  2813. =pod
  2814. =item device
  2815. =item summary Withings health data for users and devices
  2816. =begin html
  2817. <a name="withings"></a>
  2818. <h3>withings</h3>
  2819. <ul>
  2820. FHEM module for Withings devices.<br><br>
  2821. Notes:
  2822. <ul>
  2823. <li>JSON and Digest::SHA have to be installed on the FHEM host.</li>
  2824. </ul><br>
  2825. <a name="withings_Define"></a>
  2826. <b>Define</b>
  2827. <ul>
  2828. <code>define &lt;name&gt; withings ACCOUNT &lt;login@email&gt; &lt;password&gt;</code><br>
  2829. <code>define &lt;name&gt; withings &lt;device&gt;</code><br>
  2830. <br>
  2831. Defines a withings device.<br><br>
  2832. If a withings device of the account type is created all fhem devices for users and devices are automaticaly created.
  2833. <br>
  2834. Examples:
  2835. <ul>
  2836. <code>define withings withings ACCOUNT abc@test.com myPassword</code><br>
  2837. </ul>
  2838. </ul><br>
  2839. <a name="withings_Readings"></a>
  2840. <b>Readings</b>
  2841. <ul>
  2842. <li>height</li>
  2843. <li>weight</li>
  2844. <li>fatFreeMass</li>
  2845. <li>muscleRatio</li>
  2846. <li>fatMassWeight</li>
  2847. <li>fatRatio</li>
  2848. <li>boneMassWeight</li>
  2849. <li>boneRatio</li>
  2850. <li>hydration</li>
  2851. <li>diastolicBloodPressure</li>
  2852. <li>systolicBloodPressure</li>
  2853. <li>heartPulse</li>
  2854. <li>pulseWave</li>
  2855. <li>spo2</li>
  2856. <li>bodyTemperature</li>
  2857. <li>skinTemperature</li>
  2858. <li>temperature</li>
  2859. <li>dailySteps</li>
  2860. <li>dailyDistance</li>
  2861. <li>dailyElevation</li>
  2862. <li>dailyDescent</li>
  2863. <li>dailyDurationLight</li>
  2864. <li>dailyDurationModerate</li>
  2865. <li>dailyDurationIntense</li>
  2866. <li>dailyCaloriesActive</li>
  2867. <li>dailyCaloriesPassive</li>
  2868. <li>sleepDurationAwake</li>
  2869. <li>sleepDurationLight</li>
  2870. <li>sleepDurationDeep</li>
  2871. <li>sleepDurationREM</li>
  2872. <li>wakeupCount</li>
  2873. <li>co2</li>
  2874. <li>temperature</li>
  2875. <li>light</li>
  2876. <li>noise</li>
  2877. <li>voc</li>
  2878. <li>battery</li>
  2879. <li>batteryLevel</li>
  2880. </ul><br>
  2881. <a name="withings_Get"></a>
  2882. <b>Get</b>
  2883. <ul>
  2884. <li>update<br>
  2885. trigger an update</li>
  2886. </ul><br>
  2887. <a name="withings_Attr"></a>
  2888. <b>Attributes</b>
  2889. <ul>
  2890. <li>interval<br>
  2891. the interval in seconds used to check for new values.</li>
  2892. <li>disable<br>
  2893. 1 -> stop polling</li>
  2894. </ul>
  2895. </ul>
  2896. =end html
  2897. =cut