3 # Copyright 2019-2020, Mischa Peters <mischa AT high5 DOT nl>, High5!.
4 # Version 1.0 - 20191030
5 # Version 1.1 - 20200507 - added config file support
7 # Control a light based on sensor information
8 # Get ['dark'] from sensor ID and switch on/off light ID
9 # depending where your sensor is located you can use ['daylight']
12 # $ daylight-trigger.py <bridge name> -s 50 -l 24
14 # Add the following to crontab:
15 # */5 * * * * /<path-to-your-script>/daylight-trigger.py <bridge name> -s 50 -l 24 -a dimmed
17 # Follow the steps at the Hue Developer site to get the username/token
18 # https://developers.meethue.com/develop/get-started-2/
30 parser = argparse.ArgumentParser(description="Control light based on light sensor")
31 parser.add_argument("bridgename", type=str, help="Hue Bridge name in specified in hue.conf")
32 parser.add_argument("-s", "--sensor", type=int, required=True, help="sensor id#")
33 parser.add_argument("-l", "--light", type=int, required=True, help="light id#")
34 parser.add_argument("-a", "--action", type=str, default='on', help="on|off|relax|bright|dimmed|nightlight")
35 parser.add_argument("-v", "--verbose", action='store_true', help="verbose")
36 parser.add_argument("-d", "--debug", action='store_true', help="debug")
39 args = parser.parse_args()
40 bridgename = args.bridgename
44 verbose = args.verbose
47 except argparse.ArgumentError as e:
50 config_files = ['./hue.conf', './.hue.conf', '/etc/hue.conf', '/etc/hue/hue.conf', os.path.expanduser('~/.hue.conf'), os.path.expanduser('~/hue.conf')]
51 config = configparser.RawConfigParser()
52 config.read(config_files)
53 bridge = config.get(bridgename, 'ip')
54 token = config.get(bridgename, 'token')
56 no_cert_check = ssl.create_default_context()
57 no_cert_check.check_hostname=False
58 no_cert_check.verify_mode=ssl.CERT_NONE
60 scenes = {'br': {}, 'ct': {}, 'xy': {}}
61 scenes['br']['bright'] = b'{"on": true, "bri": 254, "alert": "none"}'
62 scenes['br']['relax'] = b'{"on": true, "bri": 144, "alert": "none"}'
63 scenes['br']['dimmed'] = b'{"on": true, "bri": 77, "alert": "none"}'
64 scenes['br']['nightlight'] = b'{"on": true, "bri": 1, "alert": "none"}'
65 scenes['ct']['bright'] = b'{"on": true, "bri": 254, "ct": 367, "alert": "none", "colormode": "ct"}'
66 scenes['ct']['relax'] = b'{"on": true, "bri": 144, "ct": 447, "alert": "none", "colormode": "ct"}'
67 scenes['ct']['dimmed'] = b'{"on": true, "bri": 77, "ct": 367, "alert": "none", "colormode": "ct"}'
68 scenes['ct']['nightlight'] = b'{"on": true, "bri": 1, "ct": 447, "alert": "none", "colormode": "ct"}'
69 scenes['xy']['bright'] = b'{"on": true, "bri": 254, "hue": 8402, "sat": 140, "effect": "none", "xy": [0.4578, 0.41], "ct": 367, "alert": "none", "colormode": "xy"}'
70 scenes['xy']['relax'] = b'{"on": true, "bri": 144, "hue": 8402, "sat": 140, "effect": "none", "xy": [0.5019, 0.4152], "ct": 447, "alert": "none", "colormode": "xy"}'
71 scenes['xy']['dimmed'] = b'{"on": true, "bri": 77, "hue": 8402, "sat": 140, "effect": "none", "xy": [0.4578, 0.41], "ct": 367, "alert": "none", "colormode": "xy"}'
72 scenes['xy']['nightlight'] = b'{"on": true, "bri": 1, "hue": 8402, "sat": 140, "effect": "none", "xy": [0.561, 0.4042], "ct": 367, "alert": "none", "colormode": "xy"}'
74 def get_state(type, id):
75 url = f"https://{bridge}/api/{token}/{type}/{id}"
76 req = urllib.request.Request(url)
77 with urllib.request.urlopen(req, context=no_cert_check) as response:
78 content = response.read()
79 json_data = json.loads(content)
80 if debug: print (f"State for {type[:-1]} id {id}:\n{json_data['state']}")
81 return (json_data['state'])
83 def put_state(id, state, action):
84 if not 'colormode' in state:
85 if debug: print("state[colormode] not found, colormode set to: br")
88 if debug: print(f"state[colormode] found, colormode set to: {state['colormode']}")
89 colormode = state['colormode']
92 if verbose or debug: print(f"Light {action}!")
93 data = b'{"on": false}'
95 if verbose or debug: print(f"Light {action}!")
96 data = b'{"on": true}'
97 elif action in scenes[colormode]:
98 if verbose or debug: print(f"Light {action}!")
99 if debug: print(f"Light set to: {scenes[colormode][action]}")
100 data = scenes[colormode][action]
102 url = f"https://{bridge}/api/{token}/lights/{id}/state"
103 req = urllib.request.Request(url=url, data=data, method='PUT')
104 res = urllib.request.urlopen(req, context=no_cert_check)
105 if debug: print (f"PUT response: {res.status} {res.reason}")
106 if verbose or debug: print (f"{res.status} {res.reason}")
109 sensor_state = get_state("sensors", sensor)
110 light_state = get_state("lights", light)
111 if debug: print (f"Dark: {sensor_state['dark']}, Daylight: {sensor_state['daylight']}, Light On: {sensor_state['daylight']}")
113 if sensor_state['dark'] and not light_state['on']:
114 put_state(light, light_state, action)
115 if not sensor_state['dark'] and light_state['on']:
116 put_state(light, light_state, "off")