-
-
Notifications
You must be signed in to change notification settings - Fork 38.6k
Expand file tree
/
Copy pathselector.py
More file actions
1756 lines (1292 loc) · 53.6 KB
/
Copy pathselector.py
File metadata and controls
1756 lines (1292 loc) · 53.6 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
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
"""Selectors for Home Assistant."""
from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from copy import deepcopy
from enum import StrEnum
from functools import cache
import importlib
from typing import Any, Literal, Required, TypedDict, cast
from uuid import UUID
import voluptuous as vol
from homeassistant.const import CONF_MODE, CONF_UNIT_OF_MEASUREMENT
from homeassistant.core import split_entity_id, valid_entity_id
from homeassistant.generated.countries import COUNTRIES
from homeassistant.util import decorator
from homeassistant.util.yaml import dumper
from . import config_validation as cv
SELECTORS: decorator.Registry[str, type[Selector]] = decorator.Registry()
def _get_selector_type_and_class(config: Any) -> tuple[str, type[Selector]]:
"""Get selector type and class."""
if not isinstance(config, dict):
raise vol.Invalid("Expected a dictionary")
if len(config) != 1:
raise vol.Invalid(f"Only one type can be specified. Found {', '.join(config)}")
selector_type: str = list(config)[0]
if (selector_class := SELECTORS.get(selector_type)) is None:
raise vol.Invalid(f"Unknown selector type {selector_type} found")
return selector_type, selector_class
def selector(config: Any) -> Selector:
"""Instantiate a selector."""
selector_type, selector_class = _get_selector_type_and_class(config)
return selector_class(config[selector_type])
def validate_selector(config: Any) -> dict:
"""Validate a selector."""
selector_type, selector_class = _get_selector_type_and_class(config)
return {selector_type: selector_class.CONFIG_SCHEMA(config[selector_type])}
class Selector[_T: Mapping[str, Any]]:
"""Base class for selectors."""
CONFIG_SCHEMA: Callable
config: _T
selector_type: str
# Context keys that are allowed to be used in the selector, with list of allowed selector types.
# Selectors can use the value of other fields in the same schema as context for filtering for example.
# The selector defines which context keys it supports and what selector types are allowed for each key.
allowed_context_keys: dict[str, set[str]] = {}
def __init__(self, config: Mapping[str, Any] | None = None) -> None:
"""Instantiate a selector."""
self.config = self.CONFIG_SCHEMA(config)
def __eq__(self, other: object) -> bool:
"""Check equality."""
if not isinstance(other, Selector):
return NotImplemented
return self.selector_type == other.selector_type and self.config == other.config
def serialize(self) -> dict[str, dict[str, _T]]:
"""Serialize Selector for voluptuous_serialize."""
return {"selector": {self.selector_type: self.config}}
@cache
def _entity_feature_flag(domain: str, enum_name: str, feature_name: str) -> int:
"""Return a cached lookup of an entity feature enum.
This will import a module from disk and is run from an executor when
loading the services schema files.
"""
module = importlib.import_module(f"homeassistant.components.{domain}")
enum = getattr(module, enum_name)
feature = getattr(enum, feature_name)
return cast(int, feature.value)
def _validate_supported_feature(supported_feature: str) -> int:
"""Validate a supported feature and resolve an enum string to its value."""
try:
domain, enum, feature = supported_feature.split(".", 2)
except ValueError as exc:
raise vol.Invalid(
f"Invalid supported feature '{supported_feature}', expected "
"<domain>.<enum>.<member>"
) from exc
try:
return _entity_feature_flag(domain, enum, feature)
except (ModuleNotFoundError, AttributeError) as exc:
raise vol.Invalid(f"Unknown supported feature '{supported_feature}'") from exc
def _validate_supported_features(supported_features: list[str]) -> int:
"""Validate supported features and resolve enum strings to their value."""
feature_mask = 0
for supported_feature in supported_features:
feature_mask |= _validate_supported_feature(supported_feature)
return feature_mask
def make_selector_config_schema(schema_dict: dict | None = None) -> vol.Schema:
"""Make selector config schema."""
if schema_dict is None:
schema_dict = {}
def none_to_empty_dict(value: Any) -> Any:
if value is None:
return {}
return value
return vol.Schema(
vol.All(
none_to_empty_dict,
{
vol.Optional("read_only"): bool,
**schema_dict,
},
)
)
class BaseSelectorConfig(TypedDict, total=False):
"""Class to common options of all selectors."""
read_only: bool
ENTITY_FILTER_SELECTOR_CONFIG_SCHEMA = vol.Schema(
{
# Integration that provided the entity
vol.Optional("integration"): str,
# Domain the entity belongs to
vol.Optional("domain"): vol.All(cv.ensure_list, [str]),
# Device class of the entity
vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
# Features supported by the entity
vol.Optional("supported_features"): [
vol.All(cv.ensure_list, [str], _validate_supported_features)
],
}
)
# Legacy entity selector config schema used directly under entity selectors
# is provided for backwards compatibility and remains feature frozen.
# New filtering features should be added under the `filter` key instead.
# https://github.com/home-assistant/frontend/pull/15302
_LEGACY_ENTITY_SELECTOR_CONFIG_SCHEMA_DICT = {
# Integration that provided the entity
vol.Optional("integration"): str,
# Domain the entity belongs to
vol.Optional("domain"): vol.All(cv.ensure_list, [str]),
# Device class of the entity
vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
}
class EntityFilterSelectorConfig(TypedDict, total=False):
"""Class to represent a single entity selector config."""
integration: str
domain: str | list[str]
device_class: str | list[str]
supported_features: list[str]
DEVICE_FILTER_SELECTOR_CONFIG_SCHEMA = vol.Schema(
{
# Integration linked to it with a config entry
vol.Optional("integration"): str,
# Manufacturer of device
vol.Optional("manufacturer"): str,
# Model of device
vol.Optional("model"): str,
# Model ID of device
vol.Optional("model_id"): str,
}
)
# Legacy device selector config schema used directly under device selectors
# is provided for backwards compatibility and remains feature frozen.
# New filtering features should be added under the `filter` key instead.
# https://github.com/home-assistant/frontend/pull/15302
_LEGACY_DEVICE_SELECTOR_CONFIG_SCHEMA_DICT = {
# Integration linked to it with a config entry
vol.Optional("integration"): str,
# Manufacturer of device
vol.Optional("manufacturer"): str,
# Model of device
vol.Optional("model"): str,
}
class DeviceFilterSelectorConfig(TypedDict, total=False):
"""Class to represent a single device selector config."""
integration: str
manufacturer: str
model: str
model_id: str
class ActionSelectorConfig(BaseSelectorConfig):
"""Class to represent an action selector config."""
@SELECTORS.register("action")
class ActionSelector(Selector[ActionSelectorConfig]):
"""Selector of an action sequence (script syntax)."""
selector_type = "action"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: ActionSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
return data
class AddonSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent an addon selector config."""
name: str
slug: str
@SELECTORS.register("addon")
class AddonSelector(Selector[AddonSelectorConfig]):
"""Selector of a add-on."""
selector_type = "addon"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("name"): str,
vol.Optional("slug"): str,
}
)
def __init__(self, config: AddonSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
addon: str = vol.Schema(str)(data)
return addon
class AreaSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent an area selector config."""
entity: EntityFilterSelectorConfig | list[EntityFilterSelectorConfig]
device: DeviceFilterSelectorConfig | list[DeviceFilterSelectorConfig]
multiple: bool
@SELECTORS.register("area")
class AreaSelector(Selector[AreaSelectorConfig]):
"""Selector of a single or list of areas."""
selector_type = "area"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("entity"): vol.All(
cv.ensure_list,
[ENTITY_FILTER_SELECTOR_CONFIG_SCHEMA],
),
vol.Optional("device"): vol.All(
cv.ensure_list,
[DEVICE_FILTER_SELECTOR_CONFIG_SCHEMA],
),
vol.Optional("multiple", default=False): cv.boolean,
}
)
def __init__(self, config: AreaSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str | list[str]:
"""Validate the passed selection."""
if not self.config["multiple"]:
area_id: str = vol.Schema(str)(data)
return area_id
if not isinstance(data, list):
raise vol.Invalid("Value should be a list")
return [vol.Schema(str)(val) for val in data]
class AssistPipelineSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent an assist pipeline selector config."""
@SELECTORS.register("assist_pipeline")
class AssistPipelineSelector(Selector[AssistPipelineSelectorConfig]):
"""Selector for an assist pipeline."""
selector_type = "assist_pipeline"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: AssistPipelineSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
pipeline: str = vol.Schema(str)(data)
return pipeline
class AttributeSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent an attribute selector config."""
entity_id: Required[str]
hide_attributes: list[str]
@SELECTORS.register("attribute")
class AttributeSelector(Selector[AttributeSelectorConfig]):
"""Selector for an entity attribute."""
selector_type = "attribute"
allowed_context_keys = {
# Filters the available attributes based on the selected entity
"filter_entity": {"entity"}
}
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Required("entity_id"): cv.entity_id,
# hide_attributes is used to hide attributes in the frontend.
# A hidden attribute can still be provided manually.
vol.Optional("hide_attributes"): [str],
}
)
def __init__(self, config: AttributeSelectorConfig) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
attribute: str = vol.Schema(str)(data)
return attribute
class BackupLocationSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a backup location selector config."""
@SELECTORS.register("backup_location")
class BackupLocationSelector(Selector[BackupLocationSelectorConfig]):
"""Selector of a backup location."""
selector_type = "backup_location"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: BackupLocationSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
name: str = vol.Match(r"^(?:\/backup|\w+)$")(data)
return name
class BooleanSelectorConfig(BaseSelectorConfig):
"""Class to represent a boolean selector config."""
@SELECTORS.register("boolean")
class BooleanSelector(Selector[BooleanSelectorConfig]):
"""Selector of a boolean value."""
selector_type = "boolean"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: BooleanSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> bool:
"""Validate the passed selection."""
value: bool = vol.Coerce(bool)(data)
return value
def reject_nested_choose_selector(config: dict[str, Any]) -> dict[str, Any]:
"""Reject nested choose selectors."""
for choice in config.get("choices", {}).values():
if isinstance(choice["selector"], dict):
selector_type, _ = _get_selector_type_and_class(choice["selector"])
if selector_type == "choose":
raise vol.Invalid("Nested choose selectors are not allowed")
return config
class ChooseSelectorChoiceConfig(TypedDict, total=False):
"""Class to represent a choose selector choice config."""
selector: Required[Selector | dict[str, Any]]
class ChooseSelectorConfig(BaseSelectorConfig):
"""Class to represent a choose selector config."""
choices: Required[dict[str, ChooseSelectorChoiceConfig]]
translation_key: str
@SELECTORS.register("choose")
class ChooseSelector(Selector[ChooseSelectorConfig]):
"""Selector allowing to choose one of several selectors."""
selector_type = "choose"
CONFIG_SCHEMA = vol.All(
make_selector_config_schema(
{
vol.Required("choices"): {
str: {
vol.Required("selector"): vol.Any(Selector, validate_selector),
}
},
vol.Optional("translation_key"): cv.string,
},
),
reject_nested_choose_selector,
)
def __init__(self, config: ChooseSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def serialize(self) -> dict[str, dict[str, ChooseSelectorConfig]]:
"""Serialize ChooseSelectorConfig for voluptuous_serialize."""
_config = deepcopy(self.config)
if "choices" in _config:
for choice in _config["choices"].values():
if isinstance(choice["selector"], Selector):
choice["selector"] = choice["selector"].serialize()["selector"]
return {"selector": {self.selector_type: _config}}
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
if not isinstance(data, dict):
for choice in self.config["choices"].values():
try:
validated = selector(choice["selector"])(data) # type: ignore[operator]
except (vol.Invalid, vol.MultipleInvalid):
continue
else:
return validated
raise vol.Invalid("Value does not match any choice selector")
if "active_choice" not in data:
raise vol.Invalid("Missing active_choice key")
if data["active_choice"] not in data:
raise vol.Invalid("Missing value for active choice")
choices = self.config.get("choices", {})
if data["active_choice"] not in choices:
raise vol.Invalid("Invalid active_choice key")
return selector(choices[data["active_choice"]]["selector"])( # type: ignore[operator]
data[data["active_choice"]]
)
class ColorRGBSelectorConfig(BaseSelectorConfig):
"""Class to represent a color RGB selector config."""
@SELECTORS.register("color_rgb")
class ColorRGBSelector(Selector[ColorRGBSelectorConfig]):
"""Selector of an RGB color value."""
selector_type = "color_rgb"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: ColorRGBSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> list[int]:
"""Validate the passed selection."""
value: list[int] = vol.All(list, vol.ExactSequence((cv.byte,) * 3))(data)
return value
class ColorTempSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a color temp selector config."""
unit: ColorTempSelectorUnit
min: int
max: int
max_mireds: int
min_mireds: int
class ColorTempSelectorUnit(StrEnum):
"""Possible units for a color temperature selector."""
KELVIN = "kelvin"
MIRED = "mired"
@SELECTORS.register("color_temp")
class ColorTempSelector(Selector[ColorTempSelectorConfig]):
"""Selector of an color temperature."""
selector_type = "color_temp"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("unit", default=ColorTempSelectorUnit.MIRED): vol.All(
vol.Coerce(ColorTempSelectorUnit), lambda val: val.value
),
vol.Optional("min"): vol.Coerce(int),
vol.Optional("max"): vol.Coerce(int),
vol.Optional("max_mireds"): vol.Coerce(int),
vol.Optional("min_mireds"): vol.Coerce(int),
}
)
def __init__(self, config: ColorTempSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> int:
"""Validate the passed selection."""
range_min = self.config.get("min")
range_max = self.config.get("max")
if range_min is None:
range_min = self.config.get("min_mireds")
if range_max is None:
range_max = self.config.get("max_mireds")
value: int = vol.All(
vol.Coerce(float),
vol.Range(
min=range_min,
max=range_max,
),
)(data)
return value
class ConditionSelectorConfig(BaseSelectorConfig):
"""Class to represent an condition selector config."""
@SELECTORS.register("condition")
class ConditionSelector(Selector[ConditionSelectorConfig]):
"""Selector of an condition sequence (script syntax)."""
selector_type = "condition"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: ConditionSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
return vol.Schema(cv.CONDITIONS_SCHEMA)(data)
class ConfigEntrySelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a config entry selector config."""
integration: str
@SELECTORS.register("config_entry")
class ConfigEntrySelector(Selector[ConfigEntrySelectorConfig]):
"""Selector of a config entry."""
selector_type = "config_entry"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("integration"): str,
}
)
def __init__(self, config: ConfigEntrySelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
config: str = vol.Schema(str)(data)
return config
class ConstantSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a constant selector config."""
label: str
translation_key: str
value: str | int | bool
@SELECTORS.register("constant")
class ConstantSelector(Selector[ConstantSelectorConfig]):
"""Constant selector."""
selector_type = "constant"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("label"): str,
vol.Optional("translation_key"): cv.string,
vol.Required("value"): vol.Any(str, int, bool),
}
)
def __init__(self, config: ConstantSelectorConfig) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
vol.Schema(self.config["value"])(data)
return self.config["value"]
class ConversationAgentSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a conversation agent selector config."""
language: str
@SELECTORS.register("conversation_agent")
class ConversationAgentSelector(Selector[ConversationAgentSelectorConfig]):
"""Selector for a conversation agent."""
selector_type = "conversation_agent"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("language"): str,
}
)
def __init__(self, config: ConversationAgentSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
agent: str = vol.Schema(str)(data)
return agent
class CountrySelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a country selector config."""
countries: list[str]
no_sort: bool
@SELECTORS.register("country")
class CountrySelector(Selector[CountrySelectorConfig]):
"""Selector for a single-choice country select."""
selector_type = "country"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("countries"): [str],
vol.Optional("no_sort", default=False): cv.boolean,
}
)
def __init__(self, config: CountrySelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
country: str = vol.Schema(str)(data)
if "countries" in self.config and (
country not in self.config["countries"] or country not in COUNTRIES
):
raise vol.Invalid(f"Value {country} is not a valid option")
return country
class DateSelectorConfig(BaseSelectorConfig):
"""Class to represent a date selector config."""
@SELECTORS.register("date")
class DateSelector(Selector[DateSelectorConfig]):
"""Selector of a date."""
selector_type = "date"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: DateSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
cv.date(data)
return data
class DateTimeSelectorConfig(BaseSelectorConfig):
"""Class to represent a date time selector config."""
@SELECTORS.register("datetime")
class DateTimeSelector(Selector[DateTimeSelectorConfig]):
"""Selector of a datetime."""
selector_type = "datetime"
CONFIG_SCHEMA = make_selector_config_schema()
def __init__(self, config: DateTimeSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> Any:
"""Validate the passed selection."""
cv.datetime(data)
return data
class DeviceSelectorConfig(BaseSelectorConfig, DeviceFilterSelectorConfig, total=False):
"""Class to represent a device selector config."""
entity: EntityFilterSelectorConfig | list[EntityFilterSelectorConfig]
multiple: bool
filter: DeviceFilterSelectorConfig | list[DeviceFilterSelectorConfig]
@SELECTORS.register("device")
class DeviceSelector(Selector[DeviceSelectorConfig]):
"""Selector of a single or list of devices."""
selector_type = "device"
CONFIG_SCHEMA = make_selector_config_schema(
{
**_LEGACY_DEVICE_SELECTOR_CONFIG_SCHEMA_DICT,
# Device has to contain entities matching this selector
vol.Optional("entity"): vol.All(
cv.ensure_list, [ENTITY_FILTER_SELECTOR_CONFIG_SCHEMA]
),
vol.Optional("multiple", default=False): cv.boolean,
vol.Optional("filter"): vol.All(
cv.ensure_list,
[DEVICE_FILTER_SELECTOR_CONFIG_SCHEMA],
),
},
)
def __init__(self, config: DeviceSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str | list[str]:
"""Validate the passed selection."""
if not self.config["multiple"]:
device_id: str = vol.Schema(str)(data)
return device_id
if not isinstance(data, list):
raise vol.Invalid("Value should be a list")
return [vol.Schema(str)(val) for val in data]
class DurationSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a duration selector config."""
enable_day: bool
enable_millisecond: bool
allow_negative: bool
@SELECTORS.register("duration")
class DurationSelector(Selector[DurationSelectorConfig]):
"""Selector for a duration."""
selector_type = "duration"
CONFIG_SCHEMA = make_selector_config_schema(
{
# Enable day field in frontend. A selection with `days` set is allowed
# even if `enable_day` is not set
vol.Optional("enable_day"): cv.boolean,
# Enable millisecond field in frontend.
vol.Optional("enable_millisecond"): cv.boolean,
# Allow negative durations. Will default to False in HA Core 2025.6.0.
vol.Optional("allow_negative"): cv.boolean,
}
)
def __init__(self, config: DurationSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> dict[str, float]:
"""Validate the passed selection."""
if self.config.get("allow_negative", True):
cv.time_period_dict(data)
else:
cv.positive_time_period_dict(data)
return cast(dict[str, float], data)
class EntitySelectorConfig(BaseSelectorConfig, EntityFilterSelectorConfig, total=False):
"""Class to represent an entity selector config."""
exclude_entities: list[str]
include_entities: list[str]
multiple: bool
reorder: bool
filter: EntityFilterSelectorConfig | list[EntityFilterSelectorConfig]
@SELECTORS.register("entity")
class EntitySelector(Selector[EntitySelectorConfig]):
"""Selector of a single or list of entities."""
selector_type = "entity"
CONFIG_SCHEMA = make_selector_config_schema(
{
**_LEGACY_ENTITY_SELECTOR_CONFIG_SCHEMA_DICT,
vol.Optional("exclude_entities"): [str],
vol.Optional("include_entities"): [str],
vol.Optional("multiple", default=False): cv.boolean,
vol.Optional("reorder", default=False): cv.boolean,
vol.Optional("filter"): vol.All(
cv.ensure_list,
[ENTITY_FILTER_SELECTOR_CONFIG_SCHEMA],
),
}
)
def __init__(self, config: EntitySelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str | list[str]:
"""Validate the passed selection."""
include_entities = self.config.get("include_entities")
exclude_entities = self.config.get("exclude_entities")
def validate(e_or_u: str) -> str:
e_or_u = cv.entity_id_or_uuid(e_or_u)
if not valid_entity_id(e_or_u):
return e_or_u
if allowed_domains := cv.ensure_list(self.config.get("domain")):
domain = split_entity_id(e_or_u)[0]
if domain not in allowed_domains:
raise vol.Invalid(
f"Entity {e_or_u} belongs to domain {domain}, "
f"expected {allowed_domains}"
)
if include_entities:
vol.In(include_entities)(e_or_u)
if exclude_entities:
vol.NotIn(exclude_entities)(e_or_u)
return e_or_u
if not self.config["multiple"]:
return validate(data)
if not isinstance(data, list):
raise vol.Invalid("Value should be a list")
return cast(list, vol.Schema([validate])(data)) # Output is a list
class FileSelectorConfig(BaseSelectorConfig):
"""Class to represent a file selector config."""
accept: str # required
@SELECTORS.register("file")
class FileSelector(Selector[FileSelectorConfig]):
"""Selector of a file."""
selector_type = "file"
CONFIG_SCHEMA = make_selector_config_schema(
{
# https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept
vol.Required("accept"): str,
}
)
def __init__(self, config: FileSelectorConfig) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str:
"""Validate the passed selection."""
if not isinstance(data, str):
raise vol.Invalid("Value should be a string")
UUID(data)
return data
class FloorSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent an floor selector config."""
entity: EntityFilterSelectorConfig | list[EntityFilterSelectorConfig]
device: DeviceFilterSelectorConfig | list[DeviceFilterSelectorConfig]
multiple: bool
@SELECTORS.register("floor")
class FloorSelector(Selector[FloorSelectorConfig]):
"""Selector of a single or list of floors."""
selector_type = "floor"
CONFIG_SCHEMA = make_selector_config_schema(
{
vol.Optional("entity"): vol.All(
cv.ensure_list,
[ENTITY_FILTER_SELECTOR_CONFIG_SCHEMA],
),
vol.Optional("device"): vol.All(
cv.ensure_list,
[DEVICE_FILTER_SELECTOR_CONFIG_SCHEMA],
),
vol.Optional("multiple", default=False): cv.boolean,
}
)
def __init__(self, config: FloorSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str | list[str]:
"""Validate the passed selection."""
if not self.config["multiple"]:
floor_id: str = vol.Schema(str)(data)
return floor_id
if not isinstance(data, list):
raise vol.Invalid("Value should be a list")
return [vol.Schema(str)(val) for val in data]
class IconSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent an icon selector config."""
placeholder: str
@SELECTORS.register("icon")
class IconSelector(Selector[IconSelectorConfig]):