-
Notifications
You must be signed in to change notification settings - Fork 0
/
hue.py
74 lines (65 loc) · 2.58 KB
/
hue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import requests
import json
class HueException(Exception):
pass
class Hue(object):
def __init__(self, **kwargs):
self.url = kwargs.pop('url', None)
self.api_key = kwargs.pop('api_key', None)
def process_errors(self, resp):
errors = [m['error']['description'] for m in resp if 'error' in m]
if errors:
raise HueException("\n".join(errors))
def get_light_id(self, **kwargs):
light_found = False
light_name = kwargs.pop('light_name', None)
url = "%s/api/%s/lights" % (self.url, self.api_key)
r = requests.get(url)
if r.status_code != 200:
raise HueException(
"Recieved %s status code from url %s ") % (r.status_code, url)
self.process_errors(json.loads(r.text))
lights = json.loads(r.text)
for light in lights:
name = lights[light].get('name')
if name == light_name:
light_found = True
return light
if not light_found:
raise HueException('light not found')
def change_state(self, **kwargs):
light_id = kwargs.pop('light_id', None)
alert = kwargs.pop('alert', None)
payload = {}
on = kwargs.pop('on', None)
bri = kwargs.pop('brightness', None)
if alert:
payload['alert'] = 'lselect'
if on:
payload['on'] = on
if bri:
payload['bri'] = bri
payload['on'] = True
url = "%s/api/%s/lights/%s/state" % (self.url, self.api_key, light_id)
r = requests.put(url, data=json.dumps(payload))
if r.status_code != 200:
raise HueException(
"Recieved %s status code from url %s ") % (r.status_code, url)
self.process_errors(json.loads(r.text))
success = [s['success'] for s in json.loads(r.text) if 'success' in s]
return success
def off(self, **kwargs):
light_id = kwargs.pop('light_id', None)
if not light_id:
light_name = kwargs.pop('light_name', None)
light_id = self.get_light_id(light_name=light_name)
self.change_state(on=False, light_id=light_id)
def on(self, **kwargs):
brightness = kwargs.pop('brightness', None)
alert = kwargs.pop('alert', None)
light_id = kwargs.pop('light_id', None)
if not light_id:
light_name = kwargs.pop('light_name', None)
light_id = self.get_light_id(light_name=light_name)
self.change_state(on=True, light_id=light_id, brightness=brightness,
alert=alert)