This repository was archived by the owner on May 23, 2026. It is now read-only.
forked from frenck/python-wled
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
849 lines (636 loc) · 26.8 KB
/
Copy pathmodels.py
File metadata and controls
849 lines (636 loc) · 26.8 KB
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
"""Models for WLED."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from functools import cached_property
from typing import Any
from awesomeversion import AwesomeVersion
from mashumaro import field_options
from mashumaro.config import BaseConfig
from mashumaro.mixins.orjson import DataClassORJSONMixin
from mashumaro.types import SerializableType, SerializationStrategy
from .const import (
MIN_REQUIRED_VERSION,
LightCapability,
LiveDataOverride,
NightlightMode,
SyncGroup,
)
from .exceptions import WLEDUnsupportedVersionError
from .utils import get_awesome_version
class AwesomeVersionSerializationStrategy(SerializationStrategy, use_annotations=True):
"""Serialization strategy for AwesomeVersion objects."""
def serialize(self, value: AwesomeVersion | None) -> str:
"""Serialize AwesomeVersion object to string."""
if value is None:
return ""
return str(value)
def deserialize(self, value: str) -> AwesomeVersion | None:
"""Deserialize string to AwesomeVersion object."""
version = get_awesome_version(value)
if not version.valid:
return None
return version
class TimedeltaSerializationStrategy(SerializationStrategy, use_annotations=True):
"""Serialization strategy for timedelta objects."""
def serialize(self, value: timedelta) -> int:
"""Serialize timedelta object to seconds."""
return int(value.total_seconds())
def deserialize(self, value: int) -> timedelta:
"""Deserialize integer to timedelta object."""
return timedelta(seconds=value)
class TimestampSerializationStrategy(SerializationStrategy, use_annotations=True):
"""Serialization strategy for datetime objects."""
def serialize(self, value: datetime) -> float:
"""Serialize datetime object to timestamp."""
return value.timestamp()
def deserialize(self, value: float) -> datetime:
"""Deserialize timestamp to datetime object."""
return datetime.fromtimestamp(value, tz=UTC)
@dataclass
class Color(SerializableType):
"""Object holding color information in WLED."""
primary: tuple[int, int, int, int] | tuple[int, int, int]
secondary: tuple[int, int, int, int] | tuple[int, int, int] | None = None
tertiary: tuple[int, int, int, int] | tuple[int, int, int] | None = None
def _serialize(self) -> list[tuple[int, int, int, int] | tuple[int, int, int]]:
colors = [self.primary]
if self.secondary is not None:
colors.append(self.secondary)
if self.tertiary is not None:
colors.append(self.tertiary)
return colors
@classmethod
def _deserialize(
cls, value: list[tuple[int, int, int, int] | tuple[int, int, int] | str]
) -> Color:
# Some values in the list can be strings, which indicates that the
# color is a hex color value.
return cls(
*[
tuple(int(color[i : i + 2], 16) for i in (1, 3, 5))
if isinstance(color, str)
else color
for color in value
] # ty: ignore[invalid-argument-type]
)
class BaseModel(DataClassORJSONMixin):
"""Base model for all WLED models."""
# pylint: disable-next=too-few-public-methods
class Config(BaseConfig):
"""Mashumaro configuration."""
omit_none = True
serialization_strategy = { # noqa: RUF012
AwesomeVersion: AwesomeVersionSerializationStrategy(),
datetime: TimestampSerializationStrategy(),
timedelta: TimedeltaSerializationStrategy(),
}
serialize_by_alias = True
@dataclass(kw_only=True)
class Nightlight(BaseModel):
"""Object holding nightlight state in WLED."""
duration: int = field(default=1, metadata=field_options(alias="dur"))
"""Duration of nightlight in minutes."""
mode: NightlightMode = field(default=NightlightMode.INSTANT)
"""Nightlight mode (available since 0.10.2)."""
on: bool = field(default=False)
"""Nightlight currently active."""
target_brightness: int = field(default=0, metadata=field_options(alias="tbri"))
"""Target brightness of nightlight feature."""
@dataclass(kw_only=True)
class UDPSync(BaseModel):
"""Object holding UDP sync state in WLED.
Missing at this point, is the `nn` field. This field allows to skip
sending a broadcast packet for the current API request; However, this field
is only used for requests and not part of the state responses.
"""
receive: bool = field(default=False, metadata=field_options(alias="recv"))
"""Receive broadcast packets."""
receive_groups: SyncGroup = field(
default=SyncGroup.NONE, metadata=field_options(alias="rgrp")
)
"""Groups to receive WLED broadcast packets from."""
send: bool = field(default=False, metadata=field_options(alias="send"))
"""Send WLED broadcast (UDP sync) packet on state change."""
send_groups: SyncGroup = field(
default=SyncGroup.NONE, metadata=field_options(alias="sgrp")
)
"""Groups to send WLED broadcast packets to."""
@dataclass(frozen=True, kw_only=True)
class Effect(BaseModel):
"""Object holding an effect in WLED."""
effect_id: int
name: str
@dataclass(frozen=True, kw_only=True)
class Palette(BaseModel):
"""Object holding a palette in WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A palette object.
"""
name: str
palette_id: int
@dataclass(kw_only=True)
class Segment(BaseModel):
"""Object holding segment state in WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A segment object.
"""
brightness: int = field(default=0, metadata=field_options(alias="bri"))
"""Brightness of the segment."""
clones: int = field(default=-1, metadata=field_options(alias="cln"))
"""The segment this segment clones."""
color: Color | None = field(default=None, metadata=field_options(alias="col"))
"""The primary, secondary (background) and tertiary colors of the segment.
Each color is a tuple of 3 or 4 bytes, which represents a RGB(W) color,
i.e. (255,170,0) or (64,64,64,64).
WLED can also return hex color values as strings, this library will
automatically convert those to RGB values to keep the data consistent.
"""
effect_id: int | str = field(default=0, metadata=field_options(alias="fx"))
"""ID of the effect.
~ to increment, ~- to decrement, or "r" for random.
"""
intensity: int | str = field(default=0, metadata=field_options(alias="ix"))
"""Intensity of the segment.
Effect intensity. ~ to increment, ~- to decrement. ~10 to increment by 10,
~-10 to decrement by 10.
"""
length: int = field(default=0, metadata=field_options(alias="len"))
"""Length of the segment (stop - start).
Stop has preference, so if it is included, length is ignored.
"""
on: bool | None = field(default=None)
"""The on/off state of the segment."""
palette_id: int | str = field(default=0, metadata=field_options(alias="pal"))
"""ID of the palette.
~ to increment, ~- to decrement, or r for random.
"""
reverse: bool = field(default=False, metadata=field_options(alias="rev"))
"""
Flips the segment (in horizontal dimension for 2D set-up),
causing animations to change direction.
"""
segment_id: int | None = field(default=None, metadata=field_options(alias="id"))
"""The ID of the segment."""
selected: bool = field(default=False, metadata=field_options(alias="sel"))
"""
Indicates if the segment is selected.
Selected segments will have their state (color/FX) updated by APIs that
don't support segments (e.g. UDP sync, HTTP API). If no segment is selected,
the first segment (id:0) will behave as if selected.
WLED will report the state of the first (lowest id) segment that is selected
to APIs (HTTP, MQTT, Blynk...), or mainseg in case no segment is selected
and for the UDP API.
Live data is always applied to all LEDs regardless of segment configuration.
"""
speed: int = field(default=0, metadata=field_options(alias="sx"))
"""Relative effect speed.
~ to increment, ~- to decrement. ~10 to increment by 10, ~-10 to decrement by 10.
"""
start: int = 0
"""LED the segment starts at.
For 2D set-up it determines column where segment starts,
from top-left corner of the matrix.
"""
stop: int = 0
"""LED the segment stops at, not included in range.
If stop is set to a lower or equal value than start (setting to 0 is
recommended), the segment is invalidated and deleted.
For 2D set-up it determines column where segment stops,
from top-left corner of the matrix.
"""
cct: int = field(default=0)
"""White spectrum color temperature.
0 indicates the warmest possible color temperature,
255 indicates the coldest temperature
"""
@dataclass(kw_only=True)
class Leds:
"""Object holding leds info from WLED."""
count: int = 0
"""Total LED count."""
fps: int = 0
"""Current frames per second."""
light_capabilities: LightCapability = field(
default=LightCapability.NONE, metadata=field_options(alias="lc")
)
"""Capabilities of the light."""
max_power: int = field(default=0, metadata=field_options(alias="maxpwr"))
"""Maximum power budget in milliamperes for the ABL. 0 if ABL is disabled."""
max_segments: int = field(default=0, metadata=field_options(alias="maxseg"))
"""Maximum number of segments supported by this version."""
power: int = field(default=0, metadata=field_options(alias="pwr"))
"""
Current LED power usage in milliamperes as determined by the ABL.
0 if ABL is disabled.
"""
segment_light_capabilities: list[LightCapability] = field(
default_factory=list, metadata=field_options(alias="seglc")
)
"""Capabilities of each segment."""
@dataclass(kw_only=True)
class Wifi(BaseModel):
"""Object holding Wi-Fi information from WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A Wi-Fi object.
"""
bssid: str = "00:00:00:00:00:00"
channel: int = 0
rssi: int = 0
signal: int = 0
@dataclass(kw_only=True)
class Filesystem(BaseModel):
"""Object holding Filesystem information from WLED.
Args:
----
data: The data from the WLED device API.
Returns:
-------
A Filesystem object.
"""
last_modified: datetime | None = field(
default=None, metadata=field_options(alias="pmt")
)
"""
Last modification of the presets.json file. Not accurate after boot or
after using /edit.
"""
total: int = field(default=1, metadata=field_options(alias="t"))
"""Total space of the filesystem in kilobytes."""
used: int = field(default=1, metadata=field_options(alias="u"))
"""Used space of the filesystem in kilobytes."""
@cached_property
def free(self) -> int:
"""Return the free space of the filesystem in kilobytes.
Returns
-------
The free space of the filesystem.
"""
return self.total - self.used
@cached_property
def free_percentage(self) -> int:
"""Return the free percentage of the filesystem.
Returns
-------
The free percentage of the filesystem.
"""
return round((self.free / self.total) * 100)
@cached_property
def used_percentage(self) -> int:
"""Return the used percentage of the filesystem.
Returns
-------
The used percentage of the filesystem.
"""
return round((self.used / self.total) * 100)
@dataclass(kw_only=True)
class Info(BaseModel): # pylint: disable=too-many-instance-attributes
"""Object holding information from WLED."""
architecture: str = field(default="unknown", metadata=field_options(alias="arch"))
"""Name of the platform."""
arduino_core_version: str = field(
default="Unknown", metadata=field_options(alias="core")
)
"""Version of the underlying (Arduino core) SDK."""
brand: str = "WLED"
"""The producer/vendor of the light. Always WLED for standard installations."""
build: str = field(default="Unknown", metadata=field_options(alias="vid"))
"""Build ID (YYMMDDB, B = daily build index)."""
effect_count: int = field(default=0, metadata=field_options(alias="fxcount"))
"""Number of effects included."""
filesystem: Filesystem = field(metadata=field_options(alias="fs"))
"""Info about the embedded LittleFS filesystem."""
free_heap: int = field(default=0, metadata=field_options(alias="freeheap"))
"""Bytes of heap memory (RAM) currently available. Problematic if <10k."""
ip: str = "" # pylint: disable=invalid-name
"""The IP address of this instance. Empty string if not connected."""
leds: Leds = field(default_factory=Leds)
"""Contains info about the LED setup."""
live_ip: str = field(default="Unknown", metadata=field_options(alias="lip"))
"""Realtime data source IP address."""
live_mode: str = field(default="Unknown", metadata=field_options(alias="lm"))
"""Info about the realtime data source."""
live: bool = False
"""Realtime data source active via UDP or E1.31."""
mac_address: str = field(default="", metadata=field_options(alias="mac"))
"""
The hexadecimal hardware MAC address of the light,
lowercase and without colons.
"""
name: str = "WLED Light"
"""Friendly name of the light. Intended for display in lists and titles."""
palette_count: int = field(default=0, metadata=field_options(alias="palcount"))
"""Number of palettes configured."""
product: str = "DIY Light"
"""The product name. Always FOSS for standard installations."""
udp_port: int = field(default=0, metadata=field_options(alias="udpport"))
"""The UDP port for realtime packets and WLED broadcast."""
uptime: timedelta = timedelta(0)
"""Uptime of the device."""
version: AwesomeVersion | None = field(
default=None, metadata=field_options(alias="ver")
)
"""Version of the WLED software."""
websocket: int | None = field(default=None, metadata=field_options(alias="ws"))
"""
Number of currently connected WebSockets clients.
`None` indicates that WebSockets are unsupported in this build.
"""
wifi: Wifi | None = None
"""Info about the Wi-Fi connection."""
@classmethod
def __post_deserialize__(cls, obj: Info) -> Info:
"""Post deserialize hook for Info object."""
# If the websocket is disabled in this build, the value will be -1.
# We want to represent this as None.
if obj.websocket == -1:
obj.websocket = None
# We want the architecture in lower case
obj.architecture = obj.architecture.lower()
# We can tweak the architecture name based on the filesystem size.
if obj.filesystem is not None and obj.architecture == "esp8266":
if obj.filesystem.total <= 256:
obj.architecture = "esp01"
elif obj.filesystem.total <= 512:
obj.architecture = "esp02"
return obj
@dataclass(kw_only=True)
class State(BaseModel):
"""Object holding the state of WLED."""
brightness: int = field(default=1, metadata=field_options(alias="bri"))
"""Brightness of the light.
If on is false, contains last brightness when light was on (aka brightness
when on is set to true). Setting bri to 0 is supported but it is
recommended to use the range 1-255 and use on: false to turn off.
The state response will never have the value 0 for bri.
"""
nightlight: Nightlight = field(metadata=field_options(alias="nl"))
"""Nightlight state."""
on: bool = False
"""The on/off state of the light."""
playlist_id: int | None = field(default=-1, metadata=field_options(alias="pl"))
"""ID of currently set playlist."""
preset_id: int | None = field(default=-1, metadata=field_options(alias="ps"))
"""ID of currently set preset."""
segments: dict[int, Segment] = field(
default_factory=dict, metadata=field_options(alias="seg")
)
"""Segments are individual parts of the LED strip."""
sync: UDPSync = field(metadata=field_options(alias="udpn"))
"""UDP sync state."""
transition: int = 0
"""Duration of the crossfade between different colors/brightness levels.
One unit is 100ms, so a value of 4 results in a transition of 400ms.
"""
live_data_override: LiveDataOverride = field(metadata=field_options(alias="lor"))
"""Live data override.
0 is off, 1 is override until live data ends, 2 is override until ESP reboot.
"""
@classmethod
def __pre_deserialize__(cls, d: dict[Any, Any]) -> dict[Any, Any]:
"""Pre deserialize hook for State object."""
# Segments are not indexed, which is suboptimal for the user.
# We will add the segment ID to the segment data and convert
# the segments list to an indexed dict.
d["seg"] = {
segment_id: segment | {"id": segment_id}
for segment_id, segment in enumerate(d.get("seg", []))
}
return d
@classmethod
def __post_deserialize__(cls, obj: State) -> State:
"""Post deserialize hook for State object."""
# If no playlist is active, the value will be -1. We want to represent
# this as None.
if obj.playlist_id == -1:
obj.playlist_id = None
# If no preset is active, the value will be -1. We want to represent
# this as None.
if obj.preset_id == -1:
obj.preset_id = None
return obj
@dataclass(kw_only=True)
class Preset(BaseModel):
"""Object representing a WLED preset."""
preset_id: int
"""The ID of the preset."""
name: str = field(default="", metadata=field_options(alias="n"))
"""The name of the preset."""
quick_label: str | None = field(default=None, metadata=field_options(alias="ql"))
"""The quick label of the preset."""
on: bool = False
"""The on/off state of the preset."""
transition: int = 0
"""Duration of the crossfade between different colors/brightness levels.
One unit is 100ms, so a value of 4 results in a transition of 400ms.
"""
main_segment_id: int = field(default=0, metadata=field_options(alias="mainseg"))
"""The main segment of the preset."""
segments: list[Segment] = field(
default_factory=list, metadata=field_options(alias="seg")
)
"""Segments are individual parts of the LED strip."""
@classmethod
def __pre_deserialize__(cls, d: dict[Any, Any]) -> dict[Any, Any]:
"""Pre deserialize hook for Preset object."""
# If the segment is a single value, we will convert it to a list.
if "seg" in d and not isinstance(d["seg"], list):
d["seg"] = [d["seg"]]
return d
@classmethod
def __post_deserialize__(cls, obj: Preset) -> Preset:
"""Post deserialize hook for Preset object."""
# If name is empty, we will replace it with the preset ID.
if not obj.name:
obj.name = str(obj.preset_id)
return obj
@dataclass(frozen=True, kw_only=True)
class PlaylistEntry(BaseModel):
"""Object representing an entry in a WLED playlist."""
duration: int = field(metadata=field_options(alias="dur"))
entry_id: int
preset: int = field(metadata=field_options(alias="ps"))
transition: int
@dataclass(kw_only=True)
class Playlist(BaseModel):
"""Object representing a WLED playlist."""
end_preset_id: int | None = field(default=None, metadata=field_options(alias="end"))
"""Single preset ID to apply after the playlist finished.
Has no effect when an indefinite cycle is set. If not provided,
the light will stay on the last preset of the playlist.
"""
entries: list[PlaylistEntry]
"""List of entries in the playlist."""
name: str = field(default="", metadata=field_options(alias="n"))
"""The name of the playlist."""
playlist_id: int
"""The ID of the playlist."""
repeat: int = 0
"""Number of times the playlist should repeat."""
shuffle: bool = field(default=False, metadata=field_options(alias="r"))
"""Shuffle the playlist entries."""
@classmethod
def __pre_deserialize__(cls, d: dict[Any, Any]) -> dict[Any, Any]:
"""Pre deserialize hook for Playlist object."""
d |= d["playlist"]
# Duration, presets and transitions values are separate lists stored
# in the playlist data. We will combine those into a list of
# dictionaries, which will make it easier to work with the data.
item_count = len(d.get("ps", []))
# If the duration is a single value, we will convert it to a list.
# with the same length as the presets list.
if not isinstance(d["dur"], list):
d["dur"] = [d["dur"]] * item_count
# If the transition value doesn't exist, we will set it to 0.
if "transitions" not in d:
d["transitions"] = [0] * item_count
# If the transition is a single value, we will convert it to a list.
# with the same length as the presets list.
elif not isinstance(d["transitions"], list):
d["transitions"] = [d["transitions"]] * item_count
# Now we can easily combine the data into a list of dictionaries.
d["entries"] = [
{
"entry_id": entry_id,
"ps": ps,
"dur": dur,
"transition": transition,
}
for entry_id, (ps, dur, transition) in enumerate(
zip(d["ps"], d["dur"], d["transitions"], strict=True)
)
]
return d
@classmethod
def __post_deserialize__(cls, obj: Playlist) -> Playlist:
"""Post deserialize hook for Playlist object."""
# If name is empty, we will replace it with the playlist ID.
if not obj.name:
obj.name = str(obj.playlist_id)
return obj
@dataclass(kw_only=True)
class Device(BaseModel):
"""Object holding all information of WLED."""
info: Info
state: State
effects: dict[int, Effect] = field(default_factory=dict)
palettes: dict[int, Palette] = field(default_factory=dict)
playlists: dict[int, Playlist] = field(default_factory=dict)
presets: dict[int, Preset] = field(default_factory=dict)
@classmethod
def __pre_deserialize__(cls, d: dict[Any, Any]) -> dict[Any, Any]:
"""Pre deserialize hook for Device object."""
if (version := d.get("info", {}).get("ver")) and version < MIN_REQUIRED_VERSION:
msg = (
f"Unsupported firmware version {version}. "
f"Minimum required version is {MIN_REQUIRED_VERSION}. "
f"Please update your WLED device."
)
raise WLEDUnsupportedVersionError(msg)
if _effects := d.get("effects"):
d["effects"] = {
effect_id: {"effect_id": effect_id, "name": name}
for effect_id, name in enumerate(_effects)
}
if _palettes := d.get("palettes"):
d["palettes"] = {
palette_id: {"palette_id": palette_id, "name": name}
for palette_id, name in enumerate(_palettes)
}
elif _palettes is None:
# Some less capable devices don't have palettes and
# will return `null`.
# Refs:
# - https://github.com/home-assistant/core/issues/123506
# - https://github.com/wled/WLED/issues/1974
d["palettes"] = {}
if _presets := d.get("presets"):
_presets = _presets.copy()
# The preset data contains both presets and playlists,
# we split those out, so we can handle those correctly.
d["presets"] = {
int(preset_id): preset | {"preset_id": int(preset_id)}
for preset_id, preset in _presets.items()
if "playlist" not in preset
or "ps" not in preset["playlist"]
or not preset["playlist"]["ps"]
}
# Nobody cares about 0.
d["presets"].pop(0, None)
d["playlists"] = {
int(playlist_id): playlist | {"playlist_id": int(playlist_id)}
for playlist_id, playlist in _presets.items()
if "playlist" in playlist
and "ps" in playlist["playlist"]
and playlist["playlist"]["ps"]
}
# Nobody cares about 0.
d["playlists"].pop(0, None)
return d
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"):
self.effects = {
effect_id: Effect(effect_id=effect_id, name=name)
for effect_id, name in enumerate(_effects)
}
if _palettes := data.get("palettes"):
self.palettes = {
palette_id: Palette(palette_id=palette_id, name=name)
for palette_id, name in enumerate(_palettes)
}
if _presets := data.get("presets"):
# The preset data contains both presets and playlists,
# we split those out, so we can handle those correctly.
self.presets = {
int(preset_id): Preset.from_dict(
preset | {"preset_id": int(preset_id)},
)
for preset_id, preset in _presets.items()
if "playlist" not in preset
or "ps" not in preset["playlist"]
or not preset["playlist"]["ps"]
}
# Nobody cares about 0.
self.presets.pop(0, None)
self.playlists = {
int(playlist_id): Playlist.from_dict(
playlist | {"playlist_id": int(playlist_id)}
)
for playlist_id, playlist in _presets.items()
if "playlist" in playlist
and "ps" in playlist["playlist"]
and playlist["playlist"]["ps"]
}
# Nobody cares about 0.
self.playlists.pop(0, None)
if _info := data.get("info"):
self.info = Info.from_dict(_info)
if _state := data.get("state"):
self.state = State.from_dict(_state)
return self
@dataclass(frozen=True, kw_only=True)
class Releases(BaseModel):
"""Object holding WLED releases information."""
beta: AwesomeVersion | None
stable: AwesomeVersion | None