-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
models.py
822 lines (668 loc) · 21.2 KB
/
models.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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
"""Models for WLED."""
from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum, IntFlag
from typing import Any
from awesomeversion import AwesomeVersion
from .exceptions import WLEDError
@dataclass
class Nightlight:
"""Object holding nightlight state in WLED."""
duration: int
fade: bool
on: bool
mode: NightlightMode
target_brightness: int
@staticmethod
def from_dict(data: dict[str, Any]) -> Nightlight:
"""Return Nightlight object from WLED API response.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A Nightlight object.
"""
nightlight = data.get("nl", {})
# Handle deprecated fade property for Nightlight
mode = nightlight.get("mode")
fade = nightlight.get("fade", False)
if mode is not None:
fade = mode != NightlightMode.INSTANT
if mode is None:
mode = NightlightMode.FADE if fade else NightlightMode.INSTANT
return Nightlight(
duration=nightlight.get("dur", 1),
fade=fade,
mode=NightlightMode(mode),
on=nightlight.get("on", False),
target_brightness=nightlight.get("tbri", 0),
)
@dataclass
class Sync:
"""Object holding sync state in WLED."""
receive: bool
send: bool
@staticmethod
def from_dict(data: dict[str, Any]) -> Sync:
"""Return Sync object from WLED API response.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A sync object.
"""
sync = data.get("udpn", {})
return Sync(send=sync.get("send", False), receive=sync.get("recv", False))
@dataclass
class Effect:
"""Object holding an effect in WLED."""
effect_id: int
name: str
@dataclass
class Palette:
"""Object holding an palette in WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A palette object.
"""
name: str
palette_id: int
@dataclass
class Segment:
"""Object holding segment state in WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A segment object.
"""
brightness: int
clones: int
color_primary: tuple[int, int, int, int] | tuple[int, int, int]
color_secondary: tuple[int, int, int, int] | tuple[int, int, int]
color_tertiary: tuple[int, int, int, int] | tuple[int, int, int]
effect: Effect
intensity: int
length: int
on: bool
palette: Palette
reverse: bool
segment_id: int
selected: bool
speed: int
start: int
stop: int
@staticmethod
# pylint: disable-next=too-many-arguments
def from_dict( # noqa: PLR0913
segment_id: int,
data: dict[str, Any],
*,
effects: list[Effect],
palettes: list[Palette],
state_on: bool,
state_brightness: int,
) -> Segment:
"""Return Segment object from WLED API response.
Args:
----
segment_id: The ID of the LED strip segment.
data: The segment data received from the WLED device.
effects: A list of Effect objects.
palettes: A list of Palette objects.
state_on: Boolean the represents the on/off state of this segment.
state_brightness: The brightness level of this segment.
Returns:
-------
An Segment object.
"""
start = data.get("start", 0)
stop = data.get("stop", 0)
length = data.get("len", (stop - start))
colors = data.get("col", [])
primary_color, secondary_color, tertiary_color = (0, 0, 0)
try:
primary_color = tuple(colors.pop(0)) # type: ignore[assignment]
secondary_color = tuple(colors.pop(0)) # type: ignore[assignment]
tertiary_color = tuple(colors.pop(0)) # type: ignore[assignment]
except IndexError:
pass
effect = next(
(item for item in effects if item.effect_id == data.get("fx", 0)),
Effect(effect_id=0, name="Unknown"),
)
palette = next(
(item for item in palettes if item.palette_id == data.get("pal", 0)),
Palette(palette_id=0, name="Unknown"),
)
return Segment(
brightness=data.get("bri", state_brightness),
clones=data.get("cln", -1),
color_primary=primary_color, # type: ignore[arg-type]
color_secondary=secondary_color, # type: ignore[arg-type]
color_tertiary=tertiary_color, # type: ignore[arg-type]
effect=effect,
intensity=data.get("ix", 0),
length=length,
on=data.get("on", state_on),
palette=palette,
reverse=data.get("rev", False),
segment_id=segment_id,
selected=data.get("sel", False),
speed=data.get("sx", 0),
start=start,
stop=stop,
)
@dataclass
class Leds:
"""Object holding leds info from WLED."""
cct: bool
count: int
fps: int | None
light_capabilities: LightCapability | None
max_power: int
max_segments: int
power: int
rgbw: bool
wv: bool
segment_light_capabilities: list[LightCapability] | None
@staticmethod
def from_dict(data: dict[str, Any]) -> Leds:
"""Return Leds object from WLED API response.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A Leds object.
"""
leds = data.get("leds", {})
light_capabilities = None
segment_light_capabilities = None
if "lc" in leds and "seglc" in leds:
light_capabilities = LightCapability(leds["lc"])
segment_light_capabilities = [
LightCapability(item) for item in leds["seglc"]
]
return Leds(
cct=bool(leds.get("cct")),
count=leds.get("count", 0),
fps=leds.get("fps", None),
light_capabilities=light_capabilities,
max_power=leds.get("maxpwr", 0),
max_segments=leds.get("maxseg", 0),
power=leds.get("pwr", 0),
rgbw=leds.get("rgbw", False),
segment_light_capabilities=segment_light_capabilities,
wv=bool(leds.get("wv", True)),
)
@dataclass
class Wifi:
"""Object holding Wi-Fi information from WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A Wi-Fi object.
"""
bssid: str
channel: int
rssi: int
signal: int
@staticmethod
def from_dict(data: dict[str, Any]) -> Wifi | None:
"""Return Wifi object form WLED API response.
Args:
----
data: The response from the WLED API.
Returns:
-------
An Wifi object.
"""
if "wifi" not in data:
return None
wifi = data.get("wifi", {})
return Wifi(
bssid=wifi.get("bssid", "00:00:00:00:00:00"),
channel=wifi.get("channel", 0),
rssi=wifi.get("rssi", 0),
signal=wifi.get("signal", 0),
)
@dataclass
class Filesystem:
"""Object holding Filesystem information from WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A Filesystem object.
"""
total: int
used: int
free: int
percentage: int
@staticmethod
def from_dict(data: dict[str, Any]) -> Filesystem | None:
"""Return Filesystem object form WLED API response.
Args:
----
data: The response from the WLED API.
Returns:
-------
An Filesystem object.
"""
if "fs" not in data:
return None
filesystem = data.get("fs", {})
total = filesystem.get("t", 1)
used = filesystem.get("u", 1)
return Filesystem(
total=total,
used=used,
free=(total - used),
percentage=round((used / total) * 100),
)
@dataclass
class Info: # pylint: disable=too-many-instance-attributes
"""Object holding information from WLED."""
architecture: str
arduino_core_version: str
brand: str
build_type: str
effect_count: int
filesystem: Filesystem | None
free_heap: int
ip: str # pylint: disable=invalid-name
leds: Leds
live_ip: str
live_mode: str
live: bool
mac_address: str
name: str
pallet_count: int
product: str
udp_port: int
uptime: int
version_id: str
version: AwesomeVersion | None
version_latest_beta: AwesomeVersion | None
version_latest_stable: AwesomeVersion | None
websocket: int | None
wifi: Wifi | None
@staticmethod
def from_dict(data: dict[str, Any]) -> Info:
"""Return Info object from WLED API response.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A info object.
"""
if (websocket := data.get("ws")) == -1:
websocket = None
if version := data.get("ver"):
version = AwesomeVersion(version)
if not version.valid:
version = None
if version_latest_stable := data.get("version_latest_stable"):
version_latest_stable = AwesomeVersion(version_latest_stable)
if version_latest_beta := data.get("version_latest_beta"):
version_latest_beta = AwesomeVersion(version_latest_beta)
arch = data.get("arch", "Unknown")
if (
(filesystem := Filesystem.from_dict(data)) is not None
and arch == "esp8266"
and filesystem.total
):
if filesystem.total <= 256:
arch = "esp01"
elif filesystem.total <= 512:
arch = "esp02"
return Info(
architecture=arch,
arduino_core_version=data.get("core", "Unknown").replace("_", "."),
brand=data.get("brand", "WLED"),
build_type=data.get("btype", "Unknown"),
effect_count=data.get("fxcount", 0),
filesystem=filesystem,
free_heap=data.get("freeheap", 0),
ip=data.get("ip", "Unknown"),
leds=Leds.from_dict(data),
live_ip=data.get("lip", "Unknown"),
live_mode=data.get("lm", "Unknown"),
live=data.get("live", False),
mac_address=data.get("mac", ""),
name=data.get("name", "WLED Light"),
pallet_count=data.get("palcount", 0),
product=data.get("product", "DIY Light"),
udp_port=data.get("udpport", 0),
uptime=data.get("uptime", 0),
version_id=data.get("vid", "Unknown"),
version=version,
version_latest_beta=version_latest_beta,
version_latest_stable=version_latest_stable,
websocket=websocket,
wifi=Wifi.from_dict(data),
)
@dataclass
class State:
"""Object holding the state of WLED."""
brightness: int
nightlight: Nightlight
on: bool
playlist: Playlist | int | None
preset: Preset | int | None
segments: list[Segment]
sync: Sync
transition: int
lor: Live
@property
def playlist_active(self) -> bool:
"""Return if a playlist is currently active.
Returns
-------
True if there is currently a playlist active, False otherwise.
"""
return self.playlist == -1
@property
def preset_active(self) -> bool:
"""Return if a preset is currently active.
Returns
-------
True is a preset is currently active, False otherwise.
"""
return self.preset == -1
@staticmethod
def from_dict(
data: dict[str, Any],
effects: list[Effect],
palettes: list[Palette],
presets: list[Preset],
playlists: list[Playlist],
) -> State:
"""Return State object from WLED API response.
Args:
----
data: The state response received from the WLED device API.
effects: A list of effect objects.
palettes: A list of palette objects.
presets: A list of preset objects.
playlists: A list of playlist objects.
Returns:
-------
A State object.
"""
brightness = data.get("bri", 1)
on = data.get("on", False)
lor = data.get("lor", 0)
segments = [
Segment.from_dict(
segment_id=segment_id,
data=segment,
effects=effects,
palettes=palettes,
state_on=on,
state_brightness=brightness,
)
for segment_id, segment in enumerate(data.get("seg", []))
]
playlist = data.get("pl", -1)
preset = data.get("ps", -1)
if presets:
preset = next(
(item for item in presets if item.preset_id == data.get("ps")),
None,
)
playlist = next(
(item for item in playlists if item.playlist_id == data.get("pl")),
None,
)
return State(
brightness=brightness,
nightlight=Nightlight.from_dict(data),
on=on,
playlist=playlist,
preset=preset,
segments=segments,
sync=Sync.from_dict(data),
transition=data.get("transition", 0),
lor=Live(lor),
)
@dataclass
class Preset:
"""Object representing a WLED preset."""
preset_id: int
name: str
quick_label: str | None
on: bool
transition: int
main_segment: Segment | None
segments: list[Segment]
@staticmethod
def from_dict(
preset_id: int,
data: dict[str, Any],
effects: list[Effect],
palettes: list[Palette],
) -> Preset:
"""Return Preset object from WLED API response.
Args:
----
preset_id: The ID of the preset.
data: The data from the WLED device API.
effects: A list of effect objects.
palettes: A list of palette object.
Returns:
-------
A Preset object.
"""
segment_data = data.get("seg", [])
if not isinstance(segment_data, list):
# Some older versions of WLED have an single segment
# instead of a list.
segment_data = [segment_data]
segments = [
Segment.from_dict(
segment_id=segment_id,
data=segment,
effects=effects,
palettes=palettes,
state_on=False,
state_brightness=0,
)
for segment_id, segment in enumerate(segment_data)
]
main_segment = next(
(item for item in segments if item.segment_id == data.get("mainseg", 0)),
None,
)
return Preset(
main_segment=main_segment,
name=data.get("n", str(preset_id)),
on=data.get("on", False),
preset_id=preset_id,
quick_label=data.get("ql"),
segments=segments,
transition=data.get("transition", 0),
)
@dataclass
class PlaylistEntry:
"""Object representing a entry in a WLED playlist."""
duration: int
entry_id: int
preset: Preset | None
transition: int
@dataclass
class Playlist:
"""Object representing a WLED playlist."""
end: Preset | None
entries: list[PlaylistEntry]
name: str
playlist_id: int
repeat: int
shuffle: bool
@staticmethod
def from_dict(
playlist_id: int,
data: dict[str, Any],
presets: list[Preset],
) -> Playlist:
"""Return Playlist object from WLED API response.
Args:
----
playlist_id: The ID of the playlist.
data: The data from the WLED device API.
presets: A list of preset objects.
Returns:
-------
A Playlist object.
"""
playlist = data.get("playlist", {})
entries_durations = playlist.get("dur", [])
entries_presets = playlist.get("ps", [])
entries_transitions = playlist.get("transition", [])
entries = [
PlaylistEntry(
entry_id=entry_id,
duration=entries_durations[entry_id],
transition=entries_transitions[entry_id],
preset=next(
(item for item in presets if item.preset_id == preset_id),
None,
),
)
for entry_id, preset_id in enumerate(entries_presets)
]
end = next(
(item for item in presets if item.preset_id == playlist.get("end")),
None,
)
return Playlist(
playlist_id=playlist_id,
shuffle=playlist.get("r", False),
name=data.get("n", str(playlist_id)),
repeat=playlist.get("repeat", 0),
end=end,
entries=entries,
)
class Device:
"""Object holding all information of WLED."""
effects: list[Effect]
info: Info
palettes: list[Palette]
playlists: list[Playlist]
presets: list[Preset]
state: State
def __init__(self, data: dict[str, Any]) -> None:
"""Initialize an empty WLED device class.
Args:
----
data: The full API response from a WLED device.
Raises:
------
WLEDError: In case the given API response is incomplete in a way
that a Device object cannot be constructed from it.
"""
self.effects = []
self.palettes = []
self.playlists = []
self.presets = []
# Check if all elements are in the passed dict, else raise an Error
if any(
k not in data and data[k] is not None
for k in ("effects", "palettes", "info", "state")
):
msg = "WLED data is incomplete, cannot construct device object"
raise WLEDError(msg)
self.update_from_dict(data)
def update_from_dict(self, data: dict[str, Any]) -> Device:
"""Return Device object from WLED API response.
Args:
----
data: Update the device object with the data received from a
WLED device API.
Returns:
-------
The updated Device object.
"""
if _effects := data.get("effects"):
effects = [
Effect(effect_id=effect_id, name=effect)
for effect_id, effect in enumerate(_effects)
]
effects.sort(key=lambda x: x.name)
self.effects = effects
if _palettes := data.get("palettes"):
palettes = [
Palette(palette_id=palette_id, name=palette)
for palette_id, palette in enumerate(_palettes)
]
palettes.sort(key=lambda x: x.name)
self.palettes = palettes
if _presets := data.get("presets"):
# The preset data contains both presets and playlists,
# we split those out, so we can handle those correctly.
# Nobody cares about 0.
_presets.pop("0", None)
presets = [
Preset.from_dict(int(preset_id), preset, self.effects, self.palettes)
for preset_id, preset in _presets.items()
if "playlist" not in preset
or not ("ps" in preset["playlist"] and preset["playlist"]["ps"])
]
presets.sort(key=lambda x: x.name)
self.presets = presets
playlists = [
Playlist.from_dict(int(playlist_id), playlist, self.presets)
for playlist_id, playlist in _presets.items()
if "playlist" in playlist
and "ps" in playlist["playlist"]
and playlist["playlist"]["ps"]
]
playlists.sort(key=lambda x: x.name)
self.playlists = playlists
if _info := data.get("info"):
self.info = Info.from_dict(_info)
if _state := data.get("state"):
self.state = State.from_dict(
_state,
self.effects,
self.palettes,
self.presets,
self.playlists,
)
return self
class LightCapability(IntFlag):
"""Enumeration representing the capabilities of a light in WLED."""
NONE = 0
RGB_COLOR = 1
WHITE_CHANNEL = 2
COLOR_TEMPERATURE = 4
MANUAL_WHITE = 8
# These are not used, but are reserved for future use.
# WLED specifications documents we should expect them,
# therefore, we include them here.
RESERVED_2 = 16
RESERVED_3 = 32
RESERVED_4 = 64
RESERVED_5 = 128
class Live(IntEnum):
"""Enumeration representing live override mode from WLED."""
OFF = 0
ON = 1
OFF_UNTIL_REBOOT = 2
class NightlightMode(IntEnum):
"""Enumeration representing nightlight mode from WLED."""
INSTANT = 0
FADE = 1
COLOR_FADE = 2
SUNRISE = 3