-
Notifications
You must be signed in to change notification settings - Fork 1
/
light.py
503 lines (422 loc) · 15.7 KB
/
light.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
"""Support for HASP LVGL moodlights."""
import json
import logging
from typing import Callable
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.color as color_util
import voluptuous as vol
from .common import HASP_IDLE_SCHEMA, HASPToggleEntity
from .const import (
ATTR_AWAKE_BRIGHTNESS,
ATTR_IDLE_BRIGHTNESS,
CONF_DIMLIGHTS,
CONF_HWID,
CONF_IDLE_BRIGHTNESS,
CONF_LIGHTS,
CONF_TOPIC,
HASP_IDLE_LONG,
HASP_IDLE_OFF,
HASP_IDLE_SHORT,
)
_LOGGER = logging.getLogger(__name__)
HASP_MOODLIGHT_SCHEMA = vol.Schema(
{
vol.Required("state"): cv.boolean,
vol.Required("r"): vol.All(int, vol.Range(min=0, max=255)),
vol.Required("g"): vol.All(int, vol.Range(min=0, max=255)),
vol.Required("b"): vol.All(int, vol.Range(min=0, max=255)),
vol.Required("brightness"): vol.All(int, vol.Range(min=0, max=255)),
vol.Optional("color"): str,
},
)
HASP_BACKLIGHT_SCHEMA = vol.Schema(
{
vol.Required("state"): cv.boolean,
vol.Required("brightness"): vol.All(int, vol.Range(min=0, max=255)),
}
)
HASP_LIGHT_SCHEMA = vol.Schema(
{
vol.Required("state"): cv.boolean,
vol.Optional("brightness"): vol.All(int, vol.Range(min=0, max=255)),
}
)
# pylint: disable=R0801, W0613
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable
):
"""Set up Plate Light sensors based on a config entry."""
async_add_entities(
[
HASPBackLight(
entry.data[CONF_NAME],
entry.data[CONF_HWID],
entry.data[CONF_TOPIC],
entry.options.get(
CONF_IDLE_BRIGHTNESS, entry.data[CONF_IDLE_BRIGHTNESS]
),
),
HASPMoodLight(
entry.data[CONF_NAME], entry.data[CONF_HWID], entry.data[CONF_TOPIC]
),
]
+ [
HASPLight(
entry.data[CONF_NAME],
entry.data[CONF_HWID],
entry.data[CONF_TOPIC],
gpio,
)
for gpio in entry.data[CONF_LIGHTS]
]
+ [
HASPDimmableLight(
entry.data[CONF_NAME],
entry.data[CONF_HWID],
entry.data[CONF_TOPIC],
gpio,
)
for gpio in entry.data[CONF_DIMLIGHTS]
]
)
return True
class HASPLight(HASPToggleEntity, LightEntity):
"""Representation of openHASP Light."""
def __init__(self, name, hwid, topic, gpio):
"""Initialize the light."""
super().__init__(name, hwid, topic, gpio)
self._attr_name = f"{name} light {gpio}"
async def refresh(self):
"""Sync local state back to plate."""
await self.hass.components.mqtt.async_publish(
self.hass,
f"{self._topic}/command/output{self._gpio}",
json.dumps(HASP_LIGHT_SCHEMA({"state": int(self._state)})),
qos=0,
retain=False,
)
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()
@callback
async def light_state_message_received(msg):
"""Process State."""
try:
self._available = True
message = HASP_LIGHT_SCHEMA(json.loads(msg.payload))
_LOGGER.debug("received light %s: %s", self.name, message)
self._state = message["state"]
self.async_write_ha_state()
except vol.error.Invalid as err:
_LOGGER.error(err)
self._subscriptions.append(
await self.hass.components.mqtt.async_subscribe(
f"{self._topic}/state/output{self._gpio}", light_state_message_received
)
)
# Force immediatable state update from plate
await self.hass.components.mqtt.async_publish(
self.hass,
f"{self._topic}/command/output{self._gpio}",
"",
qos=0,
retain=False,
)
class HASPDimmableLight(HASPToggleEntity, LightEntity):
"""Representation of openHASP Light."""
def __init__(self, name, hwid, topic, gpio):
"""Initialize the dimmable light."""
super().__init__(name, hwid, topic, gpio)
self._brightness = None
self._attr_supported_features = SUPPORT_BRIGHTNESS
self._gpio = gpio
self._attr_name = f"{name} dimmable light {self._gpio}"
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self._brightness
async def refresh(self):
"""Sync local state back to plate."""
_LOGGER.debug(
"refresh dim %s state = %s, brightness = %s",
self.name,
self._state,
self._brightness,
)
await self.hass.components.mqtt.async_publish(
self.hass,
f"{self._topic}/command/output{self._gpio}",
json.dumps(
HASP_LIGHT_SCHEMA(
{"state": self._state, "brightness": self._brightness}
)
),
qos=0,
retain=False,
)
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()
@callback
async def dimmable_light_message_received(msg):
"""Process State."""
try:
self._available = True
message = HASP_LIGHT_SCHEMA(json.loads(msg.payload))
_LOGGER.debug("received dimmable light %s: %s", self.name, message)
self._state = message["state"]
self._brightness = message["brightness"]
self.async_write_ha_state()
except vol.error.Invalid as err:
_LOGGER.error(err)
self._subscriptions.append(
await self.hass.components.mqtt.async_subscribe(
f"{self._topic}/state/output{self._gpio}",
dimmable_light_message_received,
)
)
# Force immediatable state update from plate
await self.hass.components.mqtt.async_publish(
self.hass,
f"{self._topic}/command/output{self._gpio}",
"",
qos=0,
retain=False,
)
async def async_turn_on(self, **kwargs):
"""Turn on the dimmable light."""
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
self._state = True
await self.refresh()
class HASPBackLight(HASPToggleEntity, LightEntity, RestoreEntity):
"""Representation of HASP LVGL Backlight."""
def __init__(self, name, hwid, topic, brightness):
"""Initialize the light."""
super().__init__(name, hwid, topic, "backlight")
self._awake_brightness = 255
self._brightness = None
self._idle_brightness = brightness
self._attr_supported_features = SUPPORT_BRIGHTNESS
self._attr_name = f"{name} backlight"
@property
def extra_state_attributes(self):
"""Return the state attributes."""
attributes = {
ATTR_AWAKE_BRIGHTNESS: self._awake_brightness,
ATTR_IDLE_BRIGHTNESS: self._idle_brightness,
}
return attributes
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self._brightness
async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state
self._brightness = state.attributes.get(ATTR_BRIGHTNESS)
self._awake_brightness = state.attributes.get(ATTR_AWAKE_BRIGHTNESS, 255)
_LOGGER.debug(
"Restoring %s self.brigthness = %s; awake_brightness = %s",
self.name,
self._brightness,
self._awake_brightness,
)
if not self._brightness:
self._brightness = self._awake_brightness
await self.async_listen_idleness()
cmd_topic = f"{self._topic}/command"
state_topic = f"{self._topic}/state/backlight"
@callback
async def backlight_message_received(msg):
"""Process Backlight State."""
try:
self._available = True
message = HASP_BACKLIGHT_SCHEMA(json.loads(msg.payload))
_LOGGER.debug("received backlight %s: %s", self.name, message)
self._state = message["state"]
self._brightness = message["brightness"]
self.async_write_ha_state()
except vol.error.Invalid as err:
_LOGGER.error(
"While proccessing backlight: %s, original message was: %s",
err,
msg,
)
self._subscriptions.append(
await self.hass.components.mqtt.async_subscribe(
state_topic, backlight_message_received
)
)
await self.hass.components.mqtt.async_publish(
self.hass, cmd_topic, "backlight", qos=0, retain=False
)
async def async_listen_idleness(self):
"""Listen to messages on MQTT for HASP idleness."""
@callback
async def idle_message_received(msg):
"""Process MQTT message from plate."""
message = HASP_IDLE_SCHEMA(msg.payload)
if message == HASP_IDLE_OFF:
brightness = self._awake_brightness
backlight = 1
elif message == HASP_IDLE_SHORT:
brightness = self._idle_brightness
backlight = 1
elif message == HASP_IDLE_LONG:
brightness = self._awake_brightness
backlight = 0
else:
return
#
# Skip IDLE_OFF commands for specific openHASP devices
# skip device = device MQTT nodename
#
skip_device ="sunton_02"
if self.name == skip_device + " backlight" and message == HASP_IDLE_OFF:
return
else:
new_state = {"state": backlight, "brightness": brightness}
_LOGGER.debug(
"Idle state for %s is %s - Dimming to %s; Backlight to %s",
self.name,
message,
brightness,
backlight,
)
await self.hass.components.mqtt.async_publish(
self.hass,
f"{self._topic}/command",
f"backlight {json.dumps(new_state)}",
qos=0,
retain=False,
)
self.async_write_ha_state()
self._subscriptions.append(
await self.hass.components.mqtt.async_subscribe(
f"{self._topic}/state/idle", idle_message_received
)
)
async def refresh(self):
"""Sync local state back to plate."""
cmd_topic = f"{self._topic}/command"
new_state = {"state": self._state, "brightness": self._brightness}
_LOGGER.debug("refresh(%s) backlight - %s", self.name, new_state)
await self.hass.components.mqtt.async_publish(
self.hass,
cmd_topic,
f"backlight {json.dumps(new_state)}",
qos=0,
retain=False,
)
self.async_write_ha_state()
async def async_turn_on(self, **kwargs):
"""Turn on the backlight."""
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
self._awake_brightness = (
self._brightness
) # save this value for later recall
self._state = True
await self.refresh()
class HASPMoodLight(HASPToggleEntity, LightEntity, RestoreEntity):
"""Representation of HASP LVGL Moodlight."""
def __init__(self, name, hwid, topic):
"""Initialize the light."""
super().__init__(name, hwid, topic, "moodlight")
self._hs = None
self._brightness = None
self._attr_supported_features = SUPPORT_COLOR | SUPPORT_BRIGHTNESS
self._attr_name = f"{name} moodlight"
@property
def hs_color(self):
"""Return the color property."""
return self._hs
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self._brightness
async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state
self._brightness = state.attributes.get(ATTR_BRIGHTNESS)
self._hs = state.attributes.get(ATTR_HS_COLOR)
_LOGGER.debug(
"Restoring %s self.brigthness = %s; hs_color = %s",
self.name,
self._brightness,
self._hs,
)
@callback
async def moodlight_message_received(msg):
"""Process Moodlight State."""
try:
self._available = True
message = HASP_MOODLIGHT_SCHEMA(json.loads(msg.payload))
_LOGGER.debug("received moodlight %s: %s", self.name, message)
self._state = message["state"]
self._hs = color_util.color_RGB_to_hs(
message["r"], message["g"], message["b"]
)
self._brightness = message["brightness"]
self.async_write_ha_state()
except vol.error.Invalid as err:
_LOGGER.error("While proccessing moodlight: %s", err)
self._subscriptions.append(
await self.hass.components.mqtt.async_subscribe(
f"{self._topic}/state/moodlight", moodlight_message_received
)
)
await self.hass.components.mqtt.async_publish(
self.hass, f"{self._topic}/command", "moodlight", qos=0, retain=False
)
async def refresh(self):
"""Sync local state back to plate."""
cmd_topic = f"{self._topic}/command"
new_state = {"state": self._state}
if self._hs:
rgb = color_util.color_hs_to_RGB(*self._hs)
new_state = {**new_state, **dict(zip("rgb", rgb))}
if self._brightness:
new_state["brightness"] = self._brightness
_LOGGER.debug("refresh(%s) moodlight - %s", self.name, new_state)
await self.hass.components.mqtt.async_publish(
self.hass,
cmd_topic,
f"moodlight {json.dumps(new_state)}",
qos=0,
retain=False,
)
async def async_turn_on(self, **kwargs):
"""Turn on the moodlight."""
if ATTR_HS_COLOR in kwargs:
self._hs = kwargs[ATTR_HS_COLOR]
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
self._state = True
_LOGGER.debug(
"Turn on %s - %s - %s",
self._topic,
color_util.color_hs_to_RGB(*self._hs) if self._hs else None,
self._brightness,
)
await self.refresh()