forked from angadsingh/wiz_light
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wizlight.py
executable file
·330 lines (280 loc) · 10.5 KB
/
wizlight.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
'''
MIT License
Copyright (c) 2020 Stephan Traub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import socket
import json
import asyncio
import asyncio_dgram
import logging
from time import time
from .scenes import SCENES
_LOGGER = logging.getLogger(__name__)
class PilotBuilder:
def __init__ (self, warm_white = None,
cold_white = None,
speed = None,
scene = None,
rgb = None,
brightness = None,
colortemp = None):
self.pilot_params = {"state": True}
if warm_white != None:
self._set_warm_white(warm_white)
if cold_white != None:
self._set_cold_white(cold_white)
if speed != None:
self._set_speed(speed)
if scene != None:
self._set_scene(scene)
if rgb != None:
self._set_rgb(rgb)
if brightness != None:
self._set_brightness(brightness)
if colortemp != None:
self._set_colortemp(colortemp)
def get_pilot_message(self):
return json.dumps({"method": "setPilot",
"params": self.pilot_params })
def _set_warm_white(self, value: int):
'''
set the value of the cold white led
'''
if value > 0 and value < 256:
self.pilot_params['w'] = value
def _set_cold_white(self, value: int):
'''
set the value of the cold white led
'''
if value > 0 and value < 256:
self.pilot_params['c'] = value
else:
raise IndexError("Value must be between 1 and 255")
def _set_speed(self, value: int):
'''
set the color changing speed in precent (0-100)
This applies only to changing effects!
'''
if value > 0 and value < 101:
self.pilot_params['speed'] = value
else:
raise IndexError("Value must be between 0 and 100")
def _set_scene(self, scene_id: int):
'''
set the scene by id
'''
if scene_id in SCENES:
self.pilot_params['sceneId'] = scene_id
else:
# id not in SCENES !
raise IndexError("Scene is not available - only 0 to 32 are supported")
def _set_rgb(self, values):
'''
set the rgb color state of the bulb
'''
r, g, b = values
self.pilot_params['r'] = r
self.pilot_params['g'] = g
self.pilot_params['b'] = b
def _set_brightness(self, value: int):
'''
set the value of the brightness 0-255
'''
percent = self.hex_to_percent(value)
# lamp doesn't supports lower than 10%
if percent < 10: percent = 10
self.pilot_params['dimming'] = percent
def _set_colortemp(self, kelvin: int):
'''
sets the color temperature for the white led in the bulb
'''
# normalize the kelvin values - should be removed
if kelvin < 2500: kelvin = 2500
if kelvin > 6500: kelvin = 6500
self.pilot_params['temp'] = kelvin
def hex_to_percent(self, hex):
''' converts hex 0-255 values to percent '''
return round((hex/255)*100)
class PilotParser:
def __init__ (self, pilotResult):
self.pilotResult = pilotResult
def get_state(self) -> str:
return self.pilotResult['state']
def get_warm_white(self) -> int:
'''
get the value of the warm white led
'''
if "w" in self.pilotResult:
return self.pilotResult['w']
else:
return None
def get_speed(self) -> int:
'''
get the color changing speed
'''
if "speed" in self.pilotResult:
return self.pilotResult['speed']
else:
return None
def get_scene(self) -> str:
'''
get the current scene name
'''
if 'schdPsetId' in self.pilotResult: #rhythm
return SCENES[1000]
id = self.pilotResult['sceneId']
if id in SCENES:
return SCENES[id]
else:
return None
def get_cold_white(self) -> int:
'''
get the value of the cold white led
'''
if "c" in self.pilotResult:
return self.pilotResult['c']
else:
return None
def get_rgb(self):
'''
get the rgb color state of the bulb and turns it on
'''
if "r" in self.pilotResult and "g" in self.pilotResult and "b" in self.pilotResult:
r = self.pilotResult['r']
g = self.pilotResult['g']
b = self.pilotResult['b']
return r, g, b
else:
# no RGB color value was set
return None, None, None
def get_brightness(self) -> int:
'''
gets the value of the brightness 0-255
'''
return self.percent_to_hex(self.pilotResult['dimming'])
def get_colortemp(self) -> int:
if "temp" in self.pilotResult:
return self.pilotResult['temp']
else:
return None
def percent_to_hex(self, percent):
''' converts percent values 0-100 into hex 0-255'''
return round((percent / 100)*255)
class wizlight:
'''
Creates a instance of a WiZ Light Bulb
'''
# default port for WiZ lights
def __init__ (self, ip, port=38899):
''' Constructor with ip of the bulb '''
self.ip = ip
self.port = port
self.state = None
@property
def status(self) -> bool:
'''
returns true or false / true = on , false = off
'''
if self.state == None:
return None
return self.state.get_state()
## ------------------ Non properties --------------
async def turn_off(self):
'''
turns the light off
'''
message = r'{"method":"setPilot","params":{"state":false}}'
await self.sendUDPMessage(message)
async def turn_on(self, pilot_builder = PilotBuilder()):
'''
turns the light on
'''
await self.sendUDPMessage(pilot_builder.get_pilot_message(), max_send_datagrams = 10)
def get_id_from_scene_name(self, scene: str) -> int:
''' gets the id from a scene name '''
for id in SCENES:
if SCENES[id] == scene:
return id
raise ValueError("Scene '%s' not in scene list." % scene)
### ---------- Helper Functions ------------
async def updateState(self):
'''
Note: Call this method before getting any other property
Also, call this method to update the current value for any property
getPilot - gets the current bulb state - no paramters need to be included
{"method": "getPilot", "id": 24}
'''
message = r'{"method":"getPilot","params":{}}'
resp = await self.sendUDPMessage(message)
if resp != None and 'result' in resp:
self.state = PilotParser(resp['result'])
else:
self.state = None
return self.state
async def getBulbConfig(self):
'''
returns the configuration from the bulb
'''
message = r'{"method":"getSystemConfig","params":{}}'
return await self.sendUDPMessage(message)
async def lightSwitch(self):
'''
turns the light bulb on or off like a switch
'''
# first get the status
state = await self.updateState()
if state.get_state():
# if the light is on - switch off
await self.turn_off()
else:
# if the light is off - turn on
await self.turn_on()
async def receiveUDPwithTimeout(self, stream, timeout):
data, remote_addr = await asyncio.wait_for(stream.recv(), timeout)
return data
async def sendUDPMessage(self, message, timeout = 60, send_interval = 0.5, max_send_datagrams = 100):
'''
send the udp message to the bulb
'''
connid = hex(int(time()*10000000))[2:]
data = None
try:
_LOGGER.debug("[wizlight {}, connid {}] connecting to UDP port".format(self.ip, connid))
stream = await asyncio.wait_for(asyncio_dgram.connect((self.ip, self.port)), timeout)
_LOGGER.debug("[wizlight {}, connid {}] listening for response datagram".format(self.ip, connid))
receive_task = asyncio.create_task(self.receiveUDPwithTimeout(stream, timeout))
i = 0
while not receive_task.done() and i < max_send_datagrams:
_LOGGER.debug("[wizlight {}, connid {}] sending command datagram {}: {}".format(self.ip, connid, i, message))
asyncio.create_task(stream.send(bytes(message, "utf-8")))
await asyncio.sleep(send_interval)
i += 1
await receive_task
data = receive_task.result()
except asyncio.TimeoutError:
_LOGGER.exception("[wizlight {}, connid {}] Failed to do UDP call(s) to wiz light".format(self.ip, connid))
finally:
stream.close()
if data != None and len(data) is not None:
resp = json.loads(data.decode())
if "error" not in resp:
_LOGGER.debug("[wizlight {}, connid {}] response received: {}".format(self.ip, connid, resp))
return resp
else:
# exception should be created
raise ValueError("Cant read response from the bulb. Debug:",resp)