commit cb73c0756dff6e7e792ef4026800ccd900ea5d35 Author: mischa Date: Thu Oct 31 21:29:14 2019 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7d86ce4 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +hue-token diff --git a/daylight-trigger.py b/daylight-trigger.py new file mode 100755 index 0000000..33fc882 --- /dev/null +++ b/daylight-trigger.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# +# Copyright 2019, Mischa Peters , High5!. +# Version 1.0 - 20191030 +# +# depending where your sensor is located you can use ['daylight'] +# +# Requires: +# - Python 3.x +# +import argparse +import ssl +import urllib.request +import json + +parser = argparse.ArgumentParser(description="Turn light on") +parser.add_argument("bridge", type=str, help="Hue Bridge IP") +parser.add_argument("token", type=str, help="Hue API Token") +parser.add_argument("-s", "--sensor", type=int, required=True, help="sensor id#") +parser.add_argument("-l", "--light", type=int, required=True, help="light id#") +parser.add_argument("-v", "--verbose", action='store_true', help="verbose") +parser.add_argument("-d", "--debug", action='store_true', help="debug") + +try: + args = parser.parse_args() + bridge = args.bridge + token = args.token + sensor = args.sensor + light = args.light + verbose = args.verbose + debug = args.debug + +except argparse.ArgumentError as e: + print(str(e)) + +no_cert_check = ssl.create_default_context() +no_cert_check.check_hostname=False +no_cert_check.verify_mode=ssl.CERT_NONE + +def get_state(type, id): + url = f"https://{bridge}/api/{token}/{type}/{id}" + req = urllib.request.Request(url) + with urllib.request.urlopen(req, context=no_cert_check) as response: + content = response.read() + json_data = json.loads(content) + if debug: print (f"State for {type[:-1]} id {id}:\n{json_data['state']}") + return (json_data['state']) + +def put_state(type, id, action): + if action == "on": + data = b'{"on": true, "bri": 77, "hue": 8402, "sat": 254, "effect": "none", "xy": [0.4578, 0.41], "ct": 367, "alert": "none", "colormode": "xy"}' + if action == "off": + data = b'{"on":false}' + + url = f"https://{bridge}/api/{token}/{type}/{id}/state" + req = urllib.request.Request(url=url, data=data, method='PUT') + res = urllib.request.urlopen(req, context=no_cert_check) + if debug: print (f"PUT response: {res.status} {res.reason}") + if verbose or debug: print (f"{res.status} {res.reason}") + return(res) + +sensor_state = get_state("sensors", sensor) +light_state = get_state("lights", light) +if debug: print (f"Dark: {sensor_state['dark']}, Daylight: {sensor_state['daylight']}, Light On: {sensor_state['daylight']}") + +if sensor_state['dark'] and not light_state['on']: + if verbose or debug: print ("Lights ON!") + put_state("lights", light, "on") +if not sensor_state['dark'] and light_state['on']: + if verbose or debug: print ("Light OFF!") + put_state("lights", light, "off") +