#!/usr/bin/env python3 # # Copyright 2019, Mischa Peters , High5!. # Version 1.0 - 20191030 # # Get ['dark'] from sensor ID and switch on/off light ID # depending where your sensor is located you can use ['daylight'] # # For example: # $ daylight-trigger -s 50 -l 24 # # Follow the steps at the Hue Developer site to get the username/token # https://developers.meethue.com/develop/get-started-2/ # # Requires: # - Python >3.6 # 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 ("Light 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")