Initial commit

This commit is contained in:
mischa 2019-10-31 21:29:14 +01:00
commit cb73c0756d
2 changed files with 73 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
hue-token

72
daylight-trigger.py Executable file
View File

@ -0,0 +1,72 @@
#!/usr/bin/env python3
#
# Copyright 2019, Mischa Peters <mischa AT high5 DOT nl>, 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")