{"id":1451,"date":"2018-05-28T15:53:47","date_gmt":"2018-05-28T15:53:47","guid":{"rendered":"https:\/\/zogspat.tk\/blog\/?p=1451"},"modified":"2018-05-28T15:53:47","modified_gmt":"2018-05-28T15:53:47","slug":"using-sunset-to-adjust-philips-hue-sensor-on-off-times","status":"publish","type":"post","link":"https:\/\/the-plot.com\/blog\/?p=1451","title":{"rendered":"Using Sunset to adjust Philips Hue Sensor On\/Off Times"},"content":{"rendered":"<p>I&#8217;ve been meaning to do this for ages, and it turned out to be a bit easier than I thought. The Python I&#8217;m using is a bit rough and ready &#8211; rather than the 8 separate API calls to PUT the date changes back [4 rules for each sensor], I could do this with one API call, based on the single data structure for all of the rules. It doesn&#8217;t really matter that much.<\/p>\n<p>I haven&#8217;t done anything for sunrise processing, which fits our usage patterns with the sensors.<\/p>\n<p>Here&#8217;s the script, which I&#8217;m calling from cron, once a day, which is a bit of overkill. I could probably do it weekly:<\/p>\n<pre>#!\/usr\/bin\/env python3\r\n\r\nimport requests\r\nimport json\r\nimport time\r\nfrom datetime import datetime, timedelta\r\n\r\nfudgeFactorMins = -30\r\nmorningOffTime = \"T08:00:00\"\r\n<\/pre>\n<p>The\u00a0fudgeFactorMins variable is an offset for the actual sunset: I eventually subtract this from the sunset date. The rule numbers are not going to be nailed on, but they do appear to be contiguous for each sensor, in groups of 4:<\/p>\n<pre>\r\n# Format: \"T20:00:00\/T08:00:00\"\r\n\r\n# 8am \/ 8pm: day-on\r\nbathroomDayOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/1\"\r\n# 8am \/ 8pm: day-dark-on\r\nbathroomDayDarkOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/2\"\r\n# 8pm \/ 8am: night-on\r\nbathroomNightOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/3\"\r\n# 8pm \/ 8am: night-dark-on\r\nbathroomNightDarkOnRuleURL = \"http:\/\/10.40.0.3\/yourIP\/api\/yourKey\/rules\/4\"\r\n\r\n# 8am \/ 8pdm: day-on\r\nlivingroomDayOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/9\"\r\n# 8am \/ 8pm: day-dark-on\r\nlivingroomDayDarkOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/10\"\r\n# 8pm \/ 8am: night-on\r\nlivingroomNightOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/11\"\r\n# 8pm \/ 8am: night-dark-on\r\nlivingroomNightDarkOnRuleURL = \"http:\/\/yourIP\/api\/yourKey\/rules\/12\"\r\n\r\n<\/pre>\n<p>This is a bit messy but&#8230;<\/p>\n<pre>allUrls = [bathroomDayOnRuleURL,bathroomDayDarkOnRuleURL,bathroomNightOnRuleURL,bathroomNightDarkOnRuleURL,li\r\nvingroomDayOnRuleURL, livingroomDayDarkOnRuleURL, livingroomNightOnRuleURL, livingroomNightDarkOnRuleURL]\r\n<\/pre>\n<p>The sunsetAPIurl refers to a free API. I had a look at one implementation on StackOverflow which calculates locally. This endpoint is returning results within a few mins of the app on my phone, which is certainly good enough.<\/p>\n<p>One slight nuisance is that I need to adjust for British SummerTime. What I&#8217;m doing for now is using Daylight Saving as the Python datetime library gives you it for free. It&#8217;s going to &#8216;wrong&#8217; for the week or so when DST and BST are out of synch at the start and end of the summer, but I can live with that for now:<\/p>\n<pre>sunsetAPIurl = \"https:\/\/api.sunrise-sunset.org\/json?lat=yourLat8&amp;lng=-yourLong\"\r\n\r\ndef getSunset(sunsetAPIurl):\r\n   r = requests.get(sunsetAPIurl)\r\n   jsonData = r.json()\r\n   # date format is 8:08:18 PM\r\n   dateFromJson = datetime.strptime(jsonData[\"results\"][\"sunset\"], '%I:%M:%S %p')\r\n   if is_dst():\r\n     adjustedSunset = dateFromJson + timedelta(hours=1)\r\n     return adjustedSunset\r\n   else:\r\n     return dateFromJson\r\n\r\ndef is_dst( ):\r\n    return bool(time.localtime( ).tm_isdst)\r\n\r\n<\/pre>\n<p>So another quick adjustment to reformat to the requirements of the Hue endpoint date handling, after processing the fudge factor:<\/p>\n<pre>def adjustSunsetToString(sunset, fudgeFactorMins):\r\n  fudgeAdjusted = sunset + timedelta(minutes=fudgeFactorMins)\r\n  return fudgeAdjusted.strftime('T%H:%M:%S')\r\n\r\ndef hitEndpoint(allUrls, dayOnString, nightOnString):\r\n  for oneUrl in allUrls:\r\n    r = requests.get(oneUrl)\r\n    jsonData = r.json()\r\n    currentDate = jsonData[\"conditions\"][0][\"value\"]\r\n    #print(\"currentDate: \" + currentDate)\r\n    ruleName = jsonData[\"name\"]\r\n    #print(\"rulename: \" + ruleName)\r\n<\/pre>\n<p>The dates that I push back into the JSON need to conditionally flick around [earliest \/ latest or vice versa], which I do based on the substring search for &#8216;day&#8217; on the rule name:<\/p>\n<pre> \r\n    if \"day\" in ruleName:\r\n      jsonData[\"conditions\"][0][\"value\"] = dayOnString\r\n    else:\r\n      jsonData[\"conditions\"][0][\"value\"] = nightOnString\r\n    newJsonPayload = {\"conditions\": jsonData[\"conditions\"], \"actions\": jsonData[\"actions\"]}\r\n    r = requests.put(oneUrl, json = newJsonPayload)\r\n    #print(\"response: \" + r.text)\r\n\r\n\r\nsunset = getSunset(sunsetAPIurl)\r\nadjStrDate = adjustSunsetToString(sunset, fudgeFactorMins)\r\n\r\ndayOnString = morningOffTime + \"\/\" + adjStrDate\r\nnightOnString = adjStrDate + \"\/\" +  morningOffTime\r\n\r\nhitEndpoint(allUrls, dayOnString, nightOnString)\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve been meaning to do this for ages, and it turned out to be a bit easier than I thought. The Python I&#8217;m using is a bit rough and ready &#8211; rather than the 8 separate API calls to PUT &hellip; <a href=\"https:\/\/the-plot.com\/blog\/?p=1451\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-1451","post","type-post","status-publish","format-standard","hentry","category-tech"],"_links":{"self":[{"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1451","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1451"}],"version-history":[{"count":1,"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1451\/revisions"}],"predecessor-version":[{"id":1452,"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1451\/revisions\/1452"}],"wp:attachment":[{"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1451"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1451"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/the-plot.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1451"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}