-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathhome_assistant_streamdeck_yaml.py
executable file
·2600 lines (2258 loc) · 85.1 KB
/
home_assistant_streamdeck_yaml.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
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Home Assistant Stream Deck integration."""
from __future__ import annotations
import asyncio
import colorsys
import functools as ft
import hashlib
import io
import json
import math
import re
import time
import warnings
from contextlib import asynccontextmanager
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Literal,
TextIO,
TypeAlias,
)
import jinja2
import requests
import websockets
import yaml
from lxml import etree
from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOps
from pydantic import BaseModel, Field, PrivateAttr, validator
from pydantic.fields import Undefined
from rich.console import Console
from rich.table import Table
from StreamDeck.DeviceManager import DeviceManager
from StreamDeck.Devices.StreamDeck import DialEventType, TouchscreenEventType
from StreamDeck.ImageHelpers import PILHelper
if TYPE_CHECKING:
from collections.abc import Coroutine
import pandas as pd
from StreamDeck.Devices import StreamDeck
try:
__version__ = version("home_assistant_streamdeck_yaml")
except PackageNotFoundError:
__version__ = "unknown"
SCRIPT_DIR = Path(__file__).parent
ASSETS_PATH = SCRIPT_DIR / "assets"
DEFAULT_CONFIG = SCRIPT_DIR / "configuration.yaml"
DEFAULT_FONT: str = "Roboto-Regular.ttf"
DEFAULT_MDI_ICONS = {
"light": "lightbulb",
"switch": "power-socket-eu",
"script": "script",
}
ICON_PIXELS = 72
_ID_COUNTER = 0
# Resolution for Stream deck plus
LCD_PIXELS_X = 800
LCD_PIXELS_Y = 100
# Default resolution for each icon on Stream deck plus
LCD_ICON_SIZE_X = 200
LCD_ICON_SIZE_Y = 100
console = Console()
StateDict: TypeAlias = dict[str, dict[str, Any]]
class _ButtonDialBase(BaseModel, extra="forbid"): # type: ignore[call-arg]
"""Parent of Button and Dial."""
entity_id: str | None = Field(
default=None,
allow_template=True,
description="The `entity_id` that this button controls."
" This entity will be passed to the `service` when the button is pressed."
" The button is re-rendered whenever the state of this entity changes.",
)
linked_entity: str | None = Field(
default=None,
allow_template=True,
description="A secondary entity_id that is used for updating images and states",
)
service: str | None = Field(
default=None,
allow_template=True,
description="The `service` that will be called when the button is pressed.",
)
service_data: dict[str, Any] | None = Field(
default=None,
allow_template=True,
description="The `service_data` that will be passed to the `service` when the button is pressed."
" If empty, the `entity_id` will be passed.",
)
target: dict[str, Any] | None = Field(
default=None,
allow_template=True,
description="The `target` that will be passed to the `service` when the button is pressed.",
)
text: str = Field(
default="",
allow_template=True,
description="The text to display on the button."
" If empty, no text is displayed."
r" You might want to add `\n` characters to spread the text over several"
r" lines, or use the `\|` character in YAML to create a multi-line string.",
)
text_color: str | None = Field(
default=None,
allow_template=True,
description="Color of the text."
" If empty, the color is `white`, unless an `entity_id` is specified, in"
" which case the color is `amber` when the state is `on`, and `white` when it is `off`.",
)
text_size: int = Field(
default=12,
allow_template=False,
description="Integer size of the text.",
)
text_offset: int = Field(
default=0,
allow_template=False,
description="The text's position can be moved up or down from the center of"
" the button, and this movement is measured in pixels. The value can be"
" positive (for upward movement) or negative (for downward movement).",
)
icon: str | None = Field(
default=None,
allow_template=True,
description="The icon filename to display on the button."
" Make the path absolute (e.g., `/config/streamdeck/my_icon.png`) or relative to the"
" `assets` directory (e.g., `my_icon.png`)."
" If empty, a icon with `icon_background_color` and `text` is displayed."
" The icon can be a URL to an image,"
" like `'url:https://www.nijho.lt/authors/admin/avatar.jpg'`, or a `spotify:`"
" icon, like `'spotify:album/6gnYcXVaffdG0vwVM34cr8'`."
" If the icon is a `spotify:` icon, the icon will be downloaded and cached."
" The icon can also display a partially complete ring, like a progress bar,"
" or sensor value, like `ring:25` for a 25% complete ring.",
)
icon_mdi: str | None = Field(
default=None,
allow_template=True,
description="The Material Design Icon to display on the button."
" If empty, no icon is displayed."
" See https://mdi.bessarabov.com/ for a list of icons."
" The SVG icon will be downloaded and cached.",
)
icon_background_color: str = Field(
default="#000000",
allow_template=True,
description="A color (in hex format, e.g., '#FF0000') for the background of the icon (if no `icon` is specified).",
)
icon_mdi_color: str | None = Field(
default=None,
allow_template=True,
description="The color of the Material Design Icon (in hex format, e.g., '#FF0000')."
" If empty, the color is derived from `text_color` but is less saturated (gray is mixed in).",
)
icon_gray_when_off: bool = Field(
default=False,
allow_template=False,
description="When specifying `icon` and `entity_id`, if the state is `off`, the icon will be converted to grayscale.",
)
delay: float | str = Field(
default=0.0,
allow_template=True,
description="The delay (in seconds) before the `service` is called."
" This is useful if you want to wait before calling the `service`."
" Counts down from the time the button is pressed."
" If while counting the button is pressed again, the timer is cancelled."
" Should be a float or template string that evaluates to a float.",
)
_timer: AsyncDelayedCallback | None = PrivateAttr(None)
@classmethod
def templatable(cls: type[Button]) -> set[str]:
"""Return if an attribute is templatable, which is if the type-annotation is str."""
schema = cls.schema()
properties = schema["properties"]
return {k for k, v in properties.items() if v["allow_template"]}
@classmethod
def to_pandas_table(cls: type[Button]) -> pd.DataFrame:
"""Return a pandas table with the schema."""
import pandas as pd
rows = []
for k, field in cls.__fields__.items():
info = field.field_info
if info.description is None:
continue
def code(text: str) -> str:
return f"`{text}`"
row = {
"Variable name": code(k),
"Allow template": "✅" if info.extra["allow_template"] else "❌",
"Description": info.description,
"Default": code(info.default) if info.default else "",
"Type": code(field._type_display()),
}
rows.append(row)
return pd.DataFrame(rows)
@classmethod
def to_markdown_table(cls: type[Button]) -> str:
"""Return a markdown table with the schema."""
return cls.to_pandas_table().to_markdown(index=False)
class Button(_ButtonDialBase, extra="forbid"): # type: ignore[call-arg]
"""Button configuration."""
special_type: (
Literal[
"next-page",
"previous-page",
"empty",
"go-to-page",
"turn-off",
"light-control",
"reload",
]
| None
) = Field(
default=None,
allow_template=False,
description="Special type of button."
" If no specified, the button is a normal button."
" If `next-page`, the button will go to the next page."
" If `previous-page`, the button will go to the previous page."
" If `turn-off`, the button will turn off the SteamDeck until any button is pressed."
" If `empty`, the button will be empty."
" If `go-to-page`, the button will go to the page specified by `special_type_data`"
" (either an `int` or `str` (name of the page))."
" If `light-control`, the button will control a light, and the `special_type_data`"
" can be a dictionary, see its description."
" If `reload`, the button will reload the configuration file when pressed.",
)
special_type_data: Any | None = Field(
default=None,
allow_template=True,
description="Data for the special type of button."
" If `go-to-page`, the data should be an `int` or `str` (name of the page)."
" If `light-control`, the data should optionally be a dictionary."
" The dictionary can contain the following keys:"
" The `colors` key and a value a list of max (`n_keys_on_streamdeck - 5`) hex colors."
" The `color_temp_kelvin` key and a value a list of max (`n_keys_on_streamdeck - 5`) color temperatures in Kelvin."
" The `colormap` key and a value a colormap (https://matplotlib.org/stable/tutorials/colors/colormaps.html)"
" can be used. This requires the `matplotlib` package to be installed. If no"
" list of `colors` or `colormap` is specified, 10 equally spaced colors are used.",
)
@classmethod
def from_yaml(cls: type[Button], yaml_str: str) -> Button:
"""Set the attributes from a YAML string."""
data = safe_load_yaml(yaml_str)
return cls(**data[0])
@property
def domain(self) -> str | None:
"""Return the domain of the entity."""
if self.service is None:
return None
return self.service.split(".", 1)[0]
def rendered_template_button(
self,
complete_state: StateDict,
) -> Button:
"""Return a button with the rendered text."""
dct = self.dict(exclude_unset=True)
for key in self.templatable():
if key not in dct:
continue
val = dct[key]
if isinstance(val, dict): # e.g., service_data, target
for k, v in val.items():
val[k] = _render_jinja(v, complete_state)
else:
dct[key] = _render_jinja(val, complete_state) # type: ignore[assignment]
return Button(**dct)
def try_render_icon(
self,
complete_state: StateDict,
*,
key_pressed: bool = False,
size: tuple[int, int] = (ICON_PIXELS, ICON_PIXELS),
icon_mdi_margin: int = 0,
font_filename: str = DEFAULT_FONT,
) -> Image.Image:
"""Try to render the icon."""
try:
return self.render_icon(
complete_state,
key_pressed=key_pressed,
size=size,
icon_mdi_margin=icon_mdi_margin,
font_filename=font_filename,
)
except Exception as exc: # noqa: BLE001
console.print_exception()
warnings.warn(
f"Failed to render icon for {self}: {exc}",
IconWarning,
stacklevel=2,
)
return _generate_failed_icon(size)
def render_icon( # noqa: PLR0912 PLR0915
self,
complete_state: StateDict,
*,
key_pressed: bool = False,
size: tuple[int, int] = (ICON_PIXELS, ICON_PIXELS),
icon_mdi_margin: int = 0,
font_filename: str = DEFAULT_FONT,
) -> Image.Image:
"""Render the icon."""
if self.is_sleeping():
button, image = self.sleep_button_and_image(size)
else:
button = self.rendered_template_button(complete_state)
image = None
if isinstance(button.icon, str) and ":" in button.icon:
which, id_ = button.icon.split(":", 1)
if which == "spotify":
filename = _to_filename(button.icon, ".jpeg")
# copy to avoid modifying the cached image
image = _download_spotify_image(id_, filename).copy()
if which == "url":
filename = _url_to_filename(id_)
# copy to avoid modifying the cached image
image = _download_image(id_, filename, size).copy()
if which == "ring":
pct = _maybe_number(id_)
assert isinstance(pct, (int, float)), f"Invalid ring percentage: {id_}"
image = _draw_percentage_ring(pct, size)
icon_convert_to_grayscale = False
text = button.text
text_color = button.text_color or "white"
icon_mdi = button.icon_mdi
if button.special_type == "next-page":
text = button.text or "Next\nPage"
icon_mdi = button.icon_mdi or "chevron-right"
elif button.special_type == "previous-page":
text = button.text or "Previous\nPage"
icon_mdi = button.icon_mdi or "chevron-left"
elif button.special_type == "go-to-page":
page = button.special_type_data
text = button.text or f"Go to\nPage\n{page}"
icon_mdi = button.icon_mdi or "book-open-page-variant"
elif button.special_type == "turn-off":
text = button.text or "Turn off"
icon_mdi = button.icon_mdi or "power"
elif button.special_type == "reload":
text = button.text or "Reload\nconfig"
icon_mdi = button.icon_mdi or "reload"
elif button.entity_id in complete_state:
# Has entity_id
state = complete_state[button.entity_id]
if button.text_color is not None:
text_color = button.text_color
elif state["state"] == "on":
text_color = "orangered"
if (
button.icon_mdi is None
and button.icon is None
and button.domain in DEFAULT_MDI_ICONS
):
icon_mdi = DEFAULT_MDI_ICONS[button.domain]
if state["state"] == "off":
icon_convert_to_grayscale = button.icon_gray_when_off
if image is None:
image = _init_icon(
icon_background_color=button.icon_background_color,
icon_filename=button.icon,
icon_mdi=icon_mdi,
icon_mdi_margin=icon_mdi_margin,
icon_mdi_color=_named_to_hex(button.icon_mdi_color or text_color),
size=size,
).copy() # copy to avoid modifying the cached image
if icon_convert_to_grayscale:
image = _convert_to_grayscale(image)
_add_text(
image=image,
font_filename=font_filename,
text_size=self.text_size,
text=text,
text_color=text_color if not key_pressed else "green",
text_offset=self.text_offset,
)
return image
@validator("special_type_data")
def _validate_special_type( # noqa: PLR0912
cls: type[Button],
v: Any,
values: dict[str, Any],
) -> Any:
"""Validate the special_type_data."""
special_type = values["special_type"]
if special_type == "go-to-page" and not isinstance(v, (int, str)):
msg = (
"If special_type is go-to-page, special_type_data must be an int or str"
)
raise AssertionError(msg)
if (
special_type in {"next-page", "previous-page", "empty", "turn-off"}
and v is not None
):
msg = f"special_type_data needs to be empty with {special_type=}"
raise AssertionError(msg)
if special_type == "light-control":
if v is None:
v = {}
if not isinstance(v, dict):
msg = (
"With 'light-control', 'special_type_data' must"
f" be a dict, not '{v}'"
)
raise AssertionError(msg)
# Can only have the following keys: colors and colormap
allowed_keys = {"colors", "colormap", "color_temp_kelvin"}
invalid_keys = v.keys() - allowed_keys
if invalid_keys:
msg = (
f"Invalid keys in 'special_type_data', only {allowed_keys} allowed"
)
raise AssertionError(msg)
# If colors is present, it must be a list of strings
if "colors" in v:
if not isinstance(v["colors"], (tuple, list)):
msg = "If 'colors' is present, it must be a list"
raise AssertionError(msg)
for color in v["colors"]:
if not isinstance(color, str):
msg = "All colors must be strings"
raise AssertionError(msg) # noqa: TRY004
# Cast colors to tuple (to make it hashable)
v["colors"] = tuple(v["colors"])
if "color_temp_kelvin" in v:
for kelvin in v["color_temp_kelvin"]:
if not isinstance(kelvin, int):
msg = "All color_temp_kelvin must be integers"
raise AssertionError(msg) # noqa: TRY004
# Cast color_temp_kelvin to tuple (to make it hashable)
v["color_temp_kelvin"] = tuple(v["color_temp_kelvin"])
return v
def maybe_start_or_cancel_timer(
self,
callback: Callable[[], None | Coroutine] | None = None,
) -> bool:
"""Start or cancel the timer."""
if self.delay:
if self._timer is None:
assert isinstance(
self.delay,
(int, float),
), f"Invalid delay: {self.delay}"
self._timer = AsyncDelayedCallback(delay=self.delay, callback=callback)
if self._timer.is_running():
self._timer.cancel()
else:
self._timer.start()
return True
return False
def is_sleeping(self) -> bool:
"""Return True if the timer is sleeping."""
return self._timer is not None and self._timer.is_sleeping
def sleep_button_and_image(
self,
size: tuple[int, int],
) -> tuple[Button, Image.Image]:
"""Return the button and image for the sleep button."""
assert self._timer is not None
assert isinstance(self.delay, (int, float)), f"Invalid delay: {self.delay}"
remaining = self._timer.remaining_time()
pct = round(remaining / self.delay * 100)
image = _draw_percentage_ring(pct, size)
button = Button(
text=f"{remaining:.0f}s\n{pct}%",
text_color="white",
)
return button, image
class Dial(_ButtonDialBase, extra="forbid"): # type: ignore[call-arg]
"""Dial configuration."""
dial_event_type: str | None = Field(
default=None,
allow_template=True,
description="The event type of the dial that will trigger the service."
" Either `DialEventType.TURN` or `DialEventType.PUSH`.",
)
state_attribute: str | None = Field(
default=None,
allow_template=True,
description="The attribute of the entity which gets used for the dial state.",
# TODO: use this?
# An attribute of an HA entity that the dial should control e.g., brightness for a light.
)
attributes: dict[str, float] | None = Field(
default=None,
allow_template=True,
description="Sets the attributes of the dial."
" `min`: The minimal value of the dial."
" `max`: The maximal value of the dial."
" `step`: the step size by which the value of the dial is increased by on an event.",
)
allow_touchscreen_events: bool = Field(
default=False,
allow_template=True,
description="Whether events from the touchscreen are allowed, for example set the minimal value on `SHORT` and set maximal value on `LONG`.",
)
# vars for timer
_timer: AsyncDelayedCallback | None = PrivateAttr(None)
# Internal attributes for Dial
_attributes: dict[str, float] = PrivateAttr(
{"state": 0, "min": 0, "max": 100, "step": 1},
)
def update_attributes(self, data: dict[str, Any]) -> None:
"""Updates all home assistant entity attributes."""
if self.attributes is None:
self._attributes = data["attributes"]
else:
self._attributes = self.attributes
if self.state_attribute is None:
self._attributes.update({"state": float(data["state"])})
else:
try:
if data["attributes"][self.state_attribute] is None:
self._attributes["state"] = 0
else:
self._attributes["state"] = float(
data["attributes"][self.state_attribute],
)
except KeyError:
console.log(f"Could not find attribute {self.state_attribute}")
self._attributes["state"] = 0
def get_attributes(self) -> dict[str, float]:
"""Returns all home assistant entity attributes."""
return self._attributes
def increment_state(self, value: float) -> None:
"""Increments the value of the dial with checks for the minimal and maximal value."""
num: float = self._attributes["state"] + value * self._attributes["step"]
num = min(self._attributes["max"], num)
num = max(self._attributes["min"], num)
self._attributes["state"] = num
def set_state(self, value: float) -> None:
"""Sets the value of the dial without checks for the minimal and maximal value."""
self._attributes["state"] = value
def rendered_template_dial(
self,
complete_state: StateDict,
) -> Dial:
"""Return a dial with the rendered text."""
dct = self.dict(exclude_unset=True)
for key in self.templatable():
if key not in dct:
continue
val = dct[key]
if isinstance(val, dict):
for k, v in val.items():
val[k] = _render_jinja(v, complete_state, self)
else:
dct[key] = _render_jinja(val, complete_state, self)
return Dial(**dct)
# LCD/Touchscreen management
def render_lcd_image(
self,
complete_state: StateDict,
key: int, # Key needs to be from sorted dials
size: tuple[int, int],
icon_mdi_margin: int = 0,
font_filename: str = DEFAULT_FONT,
) -> Image.Image:
"""Render the image for the LCD."""
try:
image = None
dial = self.rendered_template_dial(complete_state)
if isinstance(dial.icon, str) and ":" in dial.icon:
which, id_ = dial.icon.split(":", 1)
if which == "spotify":
filename = _to_filename(dial.icon, ".jpeg")
image = _download_spotify_image(id_, filename).copy()
elif which == "url":
filename = _url_to_filename(id_)
image = _download_image(id_, filename, size).copy()
elif which == "ring":
pct = _maybe_number(id_)
assert isinstance(
pct,
(int, float),
), f"Invalid ring percentage: {id_}"
image = _draw_percentage_ring(
percentage=pct,
size=size,
radius=40,
)
icon_convert_to_grayscale = False
text = dial.text
text_color = dial.text_color or "white"
assert dial.entity_id is not None
if (
complete_state[dial.entity_id]["state"] == "off"
and dial.icon_gray_when_off
):
icon_convert_to_grayscale = True
if image is None:
image = _init_icon(
icon_background_color=dial.icon_background_color,
icon_filename=dial.icon,
icon_mdi=dial.icon_mdi,
icon_mdi_margin=icon_mdi_margin,
icon_mdi_color=_named_to_hex(dial.icon_mdi_color or text_color),
size=size,
).copy()
if icon_convert_to_grayscale:
image = _convert_to_grayscale(image)
_add_text(
image=image,
font_filename=font_filename,
text_size=self.text_size,
text=text,
text_color=text_color,
text_offset=self.text_offset,
)
return image # noqa: TRY300
except ValueError as e:
console.log(e)
warnings.warn(
f"Failed to render icon for dial {key}",
IconWarning,
stacklevel=2,
)
return _generate_failed_icon(size=size)
def start_or_restart_timer(
self,
callback: Callable[[], None | Coroutine] | None = None,
) -> bool:
"""Starts or restarts AsyncDelayedCallback timer."""
if not self.delay:
return False
if self._timer is None:
assert isinstance(
self.delay,
(int, float),
), f"Invalid delay: {self.delay}"
self._timer = AsyncDelayedCallback(delay=self.delay, callback=callback)
self._timer.start()
return True
def _update_dial_descriptions() -> None:
for _k, _v in Dial.__fields__.items():
_v.field_info.description = (
_v.field_info.description.replace("on the button", "above the dial")
.replace("button", "dial")
.replace("pressed", "rotated")
)
if _k == "delay":
_v.field_info.description = (
"The delay (in seconds) before the `service` is called."
" This counts down from the specified time and collects the called turn events and"
" sends the bundled value to Home Assistant after the dial hasn't been turned for the specified time in delay."
)
_update_dial_descriptions()
def _to_filename(id_: str, suffix: str = "") -> Path:
"""Converts an id with ":" and "_" to a filename with optional suffix."""
filename = ASSETS_PATH / id_.replace("/", "_").replace(":", "_")
return filename.with_suffix(suffix)
def to_pandas_table(cls: type[BaseModel]) -> pd.DataFrame:
"""Return a markdown table with the schema."""
import pandas as pd
rows = []
for k, field in cls.__fields__.items():
info = field.field_info
if info.description is None:
continue
def code(text: str) -> str:
return f"`{text}`"
row = {
"Variable name": code(k),
"Description": info.description,
"Default": code(info.default) if info.default is not Undefined else "",
"Type": code(field._type_display()),
}
rows.append(row)
return pd.DataFrame(rows)
def _pandas_to_rich_table(df: pd.DataFrame) -> Table:
"""Return a rich table from a pandas DataFrame."""
table = Table()
# Add the columns
for column in df.columns:
table.add_column(column)
# Add the rows
for _, row in df.iterrows():
table.add_row(*row.astype(str).tolist())
return table
class Page(BaseModel):
"""A page of buttons."""
name: str = Field(description="The name of the page.")
buttons: list[Button] = Field(
default_factory=list,
description="A list of buttons on the page.",
)
dials: list[Dial] = Field(
default_factory=list,
description="A list of dials on the page.",
)
_dials_sorted: list[Dial] = PrivateAttr([])
def sort_dials(self) -> list[tuple[Dial, Dial | None]]:
"""Sorts dials by dialEventType."""
self._dials_sorted = []
skip = False
for index, dial in enumerate(self.dials):
if index + 1 < len(self.dials):
if skip:
skip = False
continue
next_dial = self.dials[index + 1]
if dial.dial_event_type != next_dial.dial_event_type:
self._dials_sorted.append((dial, next_dial)) # type: ignore[arg-type]
skip = True
else:
self._dials_sorted.append((dial, None)) # type: ignore[arg-type]
else:
self._dials_sorted.append((dial, None)) # type: ignore[arg-type]
return self._dials_sorted # type: ignore[return-value]
def get_sorted_key(self, dial: Dial) -> int | None:
"""Returns the integer key for a dial."""
dial_list = self._dials_sorted
for i in range(len(dial_list)):
if dial in dial_list[i]:
return i
return None
@classmethod
def to_pandas_table(cls: type[Page]) -> pd.DataFrame:
"""Return a pandas DataFrame with the schema."""
return to_pandas_table(cls)
@classmethod
def to_markdown_table(cls: type[Page]) -> str:
"""Return a markdown table with the schema."""
return cls.to_pandas_table().to_markdown(index=False)
class Config(BaseModel):
"""Configuration file."""
pages: list[Page] = Field(
default_factory=list,
description="A list of `Page`s in the configuration.",
)
anonymous_pages: list[Page] = Field(
default_factory=list,
description="A list of anonymous Pages in the configuration."
" These pages are hidden and not displayed when cycling through the pages."
" They can only be reached using the `special_type: 'go-to-page'` button."
" Designed for single use, these pages return to the previous page"
" upon clicking a button.",
)
state_entity_id: str | None = Field(
default=None,
description="The entity ID to sync display state with. For"
" example `input_boolean.streamdeck` or `binary_sensor.anyone_home`.",
)
brightness: int = Field(
default=100,
description="The default brightness of the Stream Deck (0-100).",
)
auto_reload: bool = Field(
default=False,
description="If True, the configuration YAML file will automatically"
" be reloaded when it is modified.",
)
_current_page_index: int = PrivateAttr(default=0)
_is_on: bool = PrivateAttr(default=True)
_detached_page: Page | None = PrivateAttr(default=None)
_configuration_file: Path | None = PrivateAttr(default=None)
_include_files: list[Path] = PrivateAttr(default_factory=list)
@classmethod
def load(cls: type[Config], fname: Path) -> Config:
"""Read the configuration file."""
with fname.open() as f:
data, include_files = safe_load_yaml(f, return_included_paths=True)
config = cls(**data) # type: ignore[arg-type]
config._configuration_file = fname
config._include_files = include_files
config.current_page().sort_dials()
return config
def reload(self) -> None:
"""Reload the configuration file."""
assert self._configuration_file is not None
# Updates all public attributes
new_config = self.load(self._configuration_file)
self.__dict__.update(new_config.__dict__)
self._include_files = new_config._include_files
# Set the private attributes we want to preserve
if self._detached_page is not None:
self._detached_page = self.to_page(self._detached_page.name)
self.current_page().sort_dials()
if self._current_page_index >= len(self.pages):
# In case pages were removed, reset to the first page
self._current_page_index = 0
@classmethod
def to_pandas_table(cls: type[Config]) -> pd.DataFrame:
"""Return a pandas DataFrame with the schema."""
return to_pandas_table(cls)
@classmethod
def to_markdown_table(cls: type[Config]) -> str:
"""Return a markdown table with the schema."""
return cls.to_pandas_table().to_markdown(index=False)
def update_timers(
self,
deck: StreamDeck,
complete_state: dict[str, dict[str, Any]],
) -> None:
"""Update all timers."""
for key in range(deck.key_count()):
button = self.button(key)
if button is not None and button.is_sleeping():
console.log(f"Updating timer for key {key}")
update_key_image(
deck,
key=key,
config=self,
complete_state=complete_state,
key_pressed=False,
)
def next_page(self) -> Page:
"""Go to the next page."""
self._current_page_index = self.next_page_index
return self.pages[self._current_page_index]
@property
def next_page_index(self) -> int:
"""Return the next page index."""
return (self._current_page_index + 1) % len(self.pages)
@property
def previous_page_index(self) -> int:
"""Return the previous page index."""
return (self._current_page_index - 1) % len(self.pages)
def previous_page(self) -> Page:
"""Go to the previous page."""
self._current_page_index = self.previous_page_index
return self.pages[self._current_page_index]
def current_page(self) -> Page:
"""Return the current page."""
if self._detached_page is not None:
return self._detached_page
return self.pages[self._current_page_index]
def dial(self, key: int) -> Dial | None:
"""Gets Dial from key."""
dials = self.current_page().dials
if key < len(dials):
return dials[key]
return None
def dial_sorted(self, key: int) -> tuple[Dial, Dial | None] | None:
"""Gets sorted dials by key."""
dials = self.current_page()._dials_sorted
if key < len(dials):
return dials[key]
return None
def button(self, key: int) -> Button | None:
"""Return the button for a key."""
buttons = self.current_page().buttons
if key < len(buttons):
return buttons[key]
return None
def to_page(self, page: int | str) -> Page:
"""Go to a page based on the page name or index."""
if isinstance(page, int):
self._current_page_index = page
return self.current_page()
for i, p in enumerate(self.pages):
if p.name == page:
self._current_page_index = i
return self.current_page()
for p in self.anonymous_pages:
if p.name == page:
self._detached_page = p
return p
console.log(f"Could find page {page}, staying on current page")
return self.current_page()
def _next_id() -> int:
global _ID_COUNTER
_ID_COUNTER += 1
return _ID_COUNTER
class AsyncDelayedCallback:
"""A callback that is called after a delay.
Parameters
----------
delay
The delay in seconds after which the callback will be called.
callback
The function or coroutine to be called after the delay.
"""
def __init__(
self,
delay: float,
callback: Callable[[], None | Coroutine] | None = None,
) -> None:
"""Initialize."""
self.delay = delay
self.callback = callback
self.task: asyncio.Task | None = None
self.start_time: float | None = None
self.is_sleeping: bool = False