forked from issackelly/python-hue
/
hue.py
266 lines (207 loc) · 7.77 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import requests
import socket
import binascii
import json
import datetime
import logging
import functools
from time import sleep
import hashlib
from colorpy import colormodels
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('hue')
AUTH_FAILURE_RETRIES = 6
AUTH_FAILURE_SLEEP = 10
class Hue:
# Hue appears to expect your username to be a 32 character hash
client_identifier = hashlib.md5("ph-%s" % socket.getfqdn()).hexdigest()
devicetype = "python-hue"
last_update_state = None
is_allowed = True
state = {}
_lights = {}
groups = {}
schedules = {}
config = {}
@property
def lights(self):
return LightGroup(self._lights)
def __init__(self, station_ip=None):
if station_ip is None:
station_ip = self.find_station()
self.station_ip = station_ip
self.get_state()
def find_station(self):
MCAST_GRP = '239.255.255.250'
MCAST_PORT = 1900
payload = []
payload.append("M-SEARCH * HTTP/1.1")
payload.append("HOST: 239.255.255.250:1900")
payload.append("MAN: ssdp:discover")
payload.append("MX: 10")
payload.append("ST: ssdp:all")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.sendto("\n".join(payload), (MCAST_GRP, MCAST_PORT))
while 1:
try:
data, (ip_addr, port) = sock.recvfrom(1024)
except socket.error, e:
logger.exception("Failed to receive from multicast port")
raise
if "description.xml" in data:
return ip_addr
def request(self, *args, **kwargs):
path = "http://%s/api/%s%s" % (
self.station_ip,
self.client_identifier,
kwargs.get("path", ""),
)
method = kwargs.get("method", "GET")
data = kwargs.get("data", None)
## Needs more error checking, currently assumes connection will work
## and that returns proper json.
resp = requests.request(method, path, data=data)
logger.debug(resp)
logger.debug(resp.content)
resp = json.loads(resp.content)
logger.debug(resp)
if isinstance(resp, list) and resp[0].get("error", None):
error = resp[0]["error"]
if error["type"] == 1:
## Try to authenticate
if self.authenticate():
return self.request(*args, **kwargs)
else:
raise CouldNotAuthenticate()
else:
self.is_authenticated = True
return resp
def authenticate(self, tries=AUTH_FAILURE_RETRIES):
path = "http://%s/api" % (
self.station_ip
)
## Needs more error checking, currently assumes connection will work
## and that returns proper json.
auth = {
"devicetype": self.devicetype,
"username": self.client_identifier
}
resp = requests.post(path, data=json.dumps(auth))
logger.debug(resp)
logger.debug(resp.content)
resp = json.loads(resp.content)
logger.debug(resp)
logger.warn("Time to go press your button!")
if isinstance(resp, list) and resp[0].get("error", None):
logger.debug(resp[0]["error"])
if tries:
sleep(AUTH_FAILURE_SLEEP)
self.authenticate()
else:
raise TooManyFailures()
return True
def get_state(self):
self.last_resp = self.request()
state = self.last_resp
logger.debug(state)
self.state = state
self.config = state['config']
self.schedules = state['schedules']
self.groups = state['groups']
for l in state['lights']:
light = self._lights.get("l%s" % l, None)
if not light:
light = ExtendedColorLight(self, l)
self._lights["l%s" % l] = light
light.update_state_cache(state['lights'][l])
self.last_update_state = datetime.datetime.now()
colormodels.init(
phosphor_red=colormodels.xyz_color(0.64843, 0.33086),
phosphor_green=colormodels.xyz_color(0.4091, 0.518),
phosphor_blue=colormodels.xyz_color(0.167, 0.04))
class LightGroup(object):
__slots__ = ['_lights']
def __init__(self, lights):
super(LightGroup, self).__setattr__('_lights', lights)
def __getattr__(self, name):
def apply_to_all(*args, **kwargs):
for l in self._lights.values():
getattr(l, name)(*args, **kwargs)
return self
origfunc = getattr(self._lights.itervalues().next(), name)
functools.update_wrapper(apply_to_all, origfunc)
return apply_to_all
def __getitem__(self, key):
return self._lights[key]
class ExtendedColorLight:
last_status_time = None
light_id = None
state = {}
hue = None
def __init__(self, hue, light_id):
self.hue = hue
self.light_id = light_id
def update_state_cache(self, values=None):
if not values:
values = self.hue.request(path="/lights/%s" % self.light_id)
self.state.update(values)
self.last_status_time = datetime.datetime.now()
def set_state(self, state):
self.hue.request(
path="/lights/%s/state" % self.light_id,
method="PUT",
data=json.dumps(state))
self.update_state_cache()
return self
def on(self, transitiontime=5):
return self.set_state({"on": True, "transitiontime": transitiontime})
def off(self, transitiontime=5):
return self.set_state({"on": False, "transitiontime": transitiontime})
def ct(self, ct, transitiontime=5):
# set color temp in mired scale
return self.set_state({"ct": ct, "transitiontime": transitiontime})
def cct(self, cct, transitiontime=5):
# set color temp in degrees kelvin
return self.ct(1000000 / cct, transitiontime)
def bri(self, level, transitiontime=5):
# level between 0 and 255
return self.set_state({"bri": level, "transitiontime": transitiontime})
def toggle(self, transitiontime=5):
self.update_state_cache()
if self.state and self.state.get(
'state', None) and self.state["state"].get("on", None):
self.off(transitiontime)
else:
self.on(transitiontime)
def alert(self, type="select"):
return self.set_state({"alert": type})
def xy(self, x, y, transitiontime=5):
return self.set_state({"xy": [x, y], "transitiontime": transitiontime})
def rgb(self, red, green=None, blue=None, transitiontime=5):
if isinstance(red, basestring):
if not red.startswith('#'):
raise ArgumentError('rgb strings must start with "#"')
# assume a hex string is passed
rstring = red
red = int(rstring[1:3], 16)
green = int(rstring[3:5], 16)
blue = int(rstring[5:], 16)
logger.debug("%d %d %d"%(red, green, blue))
# We need to convert the RGB value to Yxy.
redScale = float(red) / 255.0
greenScale = float(green) / 255.0
blueScale = float(blue) / 255.0
logger.debug("%d %d %d"%(redScale, greenScale, blueScale))
xyz = colormodels.irgb_color(red, green, blue)
logger.debug(xyz)
xyz = colormodels.xyz_from_rgb(xyz)
logger.debug(xyz)
xyz = colormodels.xyz_normalize(xyz)
logger.debug(xyz)
return self.set_state(
{"xy": [xyz[0], xyz[1]], "transitiontime": transitiontime})
class TooManyFailures(Exception):
pass
class CouldNotAuthenticate(Exception):
pass