-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlifxlancontrol.py
219 lines (197 loc) · 8.37 KB
/
lifxlancontrol.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
import logging
import cgi
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from apscheduler.schedulers.background import BackgroundScheduler
from lifxlan import LifxLAN, Light, Group
PORT = 7990
NUM_LIGHTS = 10
LIGHTS = {}
sched = BackgroundScheduler()
sched.start()
class S(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
self.devices = LifxLAN(NUM_LIGHTS)
sched.add_job(self.get_lights,
'interval',
minutes=2,
id='get_lights',
replace_existing=True)
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def get_lights(self):
lights = self.devices.get_lights()
resp = "<table><tbody>"
for l in lights:
LIGHTS[l.get_label()] = {'mac': l.get_mac_addr(),
'ip': l.get_ip_addr(),
'colour': l.get_color()}
resp += "<tr><td>" + l.get_label() + "</td>"
resp += "<td>{}</td>".format(l.get_color())
resp += "<td>" + l.get_mac_addr() + "</td>"
resp += "<td>" + l.get_ip_addr() + "</td></tr>"
resp += '</tbody></table>'
resp += "<p>POST to /lights with either mac&ip or light (with label)<br/>"
resp += "no args: toggle on/off<br/>"
resp += "<pre>level</pre> 'on'/'off', or 0/65535<br/>"
resp += "<pre>dim</pre> 'up'/'down' or no arg to continue last dim (1/10th each time)<br/>"
resp += "<pre>white</pre> 'warm'/'cool' to change kelvin level</p>"
logging.debug(len(LIGHTS))
return resp
def set_lights(self, postvars={}):
sched.pause()
resp = 'no post data found'
l = None
if any(postvars):
resp = 'vars!'
mac = postvars.get('mac', None)
if mac:
ip = postvars.get('ip', None)
if ip:
l = Light(mac[0], ip[0])
light = postvars.get('light', None)
if light:
logging.debug(light)
if light[0] in LIGHTS:
logging.debug('found {}'.format(light[0]))
light = LIGHTS.get(light[0])
mac = light.get('mac')
ip = light.get('ip')
colour = light.get('colour')
l = Light(mac, ip)
else:
logging.debug(LIGHTS)
l = self.devices.get_device_by_name(light[0])
if l:
colour = l.get_color()
if l:
level = postvars.get('level', None)
dim = postvars.get('dim', None)
white = postvars.get('white', None)
if level is not None:
try:
if (level[0] == 'full'):
h, s, b, k = colour
b = 65535
l.set_power('on')
l.set_color([h, s, b, k], 300)
else:
l.set_power(level[0])
resp = 'set power {}'.format(level)
except Exception as e:
resp = 'err... {}'.format(repr(e))
elif dim is not None:
switch_after_dim = False
try:
h, s, b, k = colour
if l.get_power() == 0:
switch_after_dim = True
b = 0
dim = dim[0]
if dim not in ('up', 'down'):
dim = LIGHTS[l.get_label()].get('last_dim', None)
if dim is None or b in (0, 65535):
if b > 32000:
dim = 'down'
else:
dim = 'up'
if dim == 'down':
b -= 6554
if dim == 'up':
b += 6554
if b < 0:
b = 0
if b > 65535:
b = 65535
l.set_color([h, s, b, k], 600)
if LIGHTS.get(l.get_label(), None) is None:
LIGHTS[l.get_label()] = {'mac': l.get_mac_addr(),
'ip': l.get_ip_addr(),
'colour': l.get_color(),
'last_dim': dim}
else:
LIGHTS[l.get_label()]['colour'] = [h, s, b, k]
LIGHTS[l.get_label()]['last_dim'] = dim
if switch_after_dim is True:
l.set_power('on')
resp = 'set brightness {}'.format(b)
except Exception as e:
resp = 'dim... {}'.format(repr(e))
elif white is not None:
try:
h, s, b, k = colour
white = white[0]
if white not in ('warm', 'cool'):
k = int(white)
if white == 'warm':
k -= 500
if white == 'cool':
k += 500
if k < 2500:
k = 2500
if k > 9000:
k = 9000
l.set_color([h, s, b, k], 500)
if LIGHTS.get(l.get_label(), None) is None:
LIGHTS[l.get_label()] = {'mac': l.get_mac_addr(),
'ip': l.get_ip_addr(),
'colour': l.get_color()}
else:
LIGHTS[l.get_label()]['colour'] = [h, s, b, k]
resp = 'set white level {}'.format(k)
except Exception as e:
resp = 'white... {}'.format(repr(e))
else:
try:
if l.get_power() > 0:
l.set_power(0)
else:
l.set_power('on')
except:
resp = 'nope...'
else:
resp = "<p>Light not found ):</p>"
sched.resume()
return resp
def do_GET(self):
self._set_headers()
self.wfile.write("<html><body><h1>Hi!</h1><p>Path: {path}</p>".format(path=self.path))
if self.path == '/lights':
self.wfile.write(self.get_lights())
self.wfile.write("</body></html>")
def do_HEAD(self):
self._set_headers()
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
else:
postvars = {}
if len(postvars):
i = 0
for key in sorted(postvars):
logging.debug('ARG[%d] %s=%s' % (i, key, postvars[key]))
i += 1
self._set_headers()
self.wfile.write("<html><body><p>POST</p>")
logging.debug(self.headers)
if self.path.startswith('/lights'):
self.wfile.write(self.set_lights(postvars))
self.wfile.write("</body></html>")
def run(server_class=HTTPServer, handler_class=S, port=PORT):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print "Starting httpd..."
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=logging.DEBUG)
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()