-
-
Notifications
You must be signed in to change notification settings - Fork 37.8k
Expand file tree
/
Copy pathcondition.py
More file actions
2076 lines (1724 loc) · 68.7 KB
/
Copy pathcondition.py
File metadata and controls
2076 lines (1724 loc) · 68.7 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
"""Offer reusable conditions."""
from __future__ import annotations
import abc
from collections import deque
from collections.abc import Callable, Container, Coroutine, Generator, Iterable, Mapping
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, time as dt_time, timedelta
import functools as ft
import inspect
import logging
import re
import sys
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Final,
Literal,
Never,
Protocol,
TypedDict,
Unpack,
cast,
overload,
override,
)
import voluptuous as vol
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_UNIT_OF_MEASUREMENT,
CONF_ABOVE,
CONF_AFTER,
CONF_ATTRIBUTE,
CONF_BEFORE,
CONF_BELOW,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_ENABLED,
CONF_ENTITY_ID,
CONF_FOR,
CONF_ID,
CONF_MATCH,
CONF_OPTIONS,
CONF_SELECTOR,
CONF_STATE,
CONF_TARGET,
CONF_VALUE_TEMPLATE,
CONF_WEEKDAY,
ENTITY_MATCH_ALL,
ENTITY_MATCH_ANY,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
WEEKDAYS,
)
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.exceptions import (
ConditionError,
ConditionErrorContainer,
ConditionErrorIndex,
ConditionErrorMessage,
HomeAssistantError,
TemplateError,
)
from homeassistant.loader import (
Integration,
IntegrationNotFound,
async_get_integration,
async_get_integrations,
)
from homeassistant.util import dt as dt_util
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util.hass_dict import HassKey
from homeassistant.util.unit_conversion import BaseUnitConverter
from homeassistant.util.yaml import load_yaml_dict
from . import config_validation as cv, entity_registry as er, selector
from .automation import (
DomainSpec,
ThresholdConfig,
filter_by_domain_specs,
get_absolute_description_key,
get_relative_description_key,
move_options_fields_to_top_level,
)
from .integration_platform import async_process_integration_platforms
from .selector import (
NumericThresholdMode,
NumericThresholdSelector,
NumericThresholdSelectorConfig,
NumericThresholdType,
TargetSelector,
)
from .target import (
TargetSelection,
TargetStateChangedData,
async_extract_referenced_entity_ids,
async_track_target_selector_state_change_event,
)
from .template import Template, render_complex
from .trace import (
TraceElement,
trace_append_element,
trace_path,
trace_path_get,
trace_stack_cv,
trace_stack_pop,
trace_stack_push,
trace_stack_top,
)
from .typing import UNDEFINED, ConfigType, TemplateVarsType, UndefinedType
ASYNC_FROM_CONFIG_FORMAT = "async_{}_from_config"
FROM_CONFIG_FORMAT = "{}_from_config"
VALIDATE_CONFIG_FORMAT = "{}_validate_config"
_LOGGER = logging.getLogger(__name__)
_PLATFORM_ALIASES: dict[str | None, str | None] = {
"and": None,
"device": "device_automation",
"not": None,
"numeric_state": None,
"or": None,
"state": None,
"template": None,
"time": None,
"trigger": None,
}
INPUT_ENTITY_ID = re.compile(
r"^input_(?:select|text|number|boolean|datetime)\.(?!.+__)(?!_)[\da-z_]+(?<!_)$"
)
CONDITION_DESCRIPTION_CACHE: HassKey[dict[str, dict[str, Any] | None]] = HassKey(
"condition_description_cache"
)
CONDITION_DISABLED_CONDITIONS: HassKey[set[str]] = HassKey(
"condition_disabled_conditions"
)
CONDITION_PLATFORM_SUBSCRIPTIONS: HassKey[
list[Callable[[set[str]], Coroutine[Any, Any, None]]]
] = HassKey("condition_platform_subscriptions")
CONDITIONS: HassKey[dict[str, str]] = HassKey("conditions")
# Basic schemas to sanity check the condition descriptions,
# full validation is done by hassfest.conditions
_FIELD_DESCRIPTION_SCHEMA = vol.Schema(
{
vol.Optional(CONF_SELECTOR): selector.validate_selector,
},
extra=vol.ALLOW_EXTRA,
)
_CONDITION_DESCRIPTION_SCHEMA = vol.Schema(
{
vol.Optional("target"): TargetSelector.CONFIG_SCHEMA,
vol.Optional("fields"): vol.Schema({str: _FIELD_DESCRIPTION_SCHEMA}),
},
extra=vol.ALLOW_EXTRA,
)
def starts_with_dot(key: str) -> str:
"""Check if key starts with dot."""
if not key.startswith("."):
raise vol.Invalid("Key does not start with .")
return key
_CONDITIONS_DESCRIPTION_SCHEMA = vol.Schema(
{
vol.Remove(vol.All(str, starts_with_dot)): object,
cv.underscore_slug: vol.Any(None, _CONDITION_DESCRIPTION_SCHEMA),
}
)
async def async_setup(hass: HomeAssistant) -> None:
"""Set up the condition helper."""
from homeassistant.components import automation, labs # noqa: PLC0415
hass.data[CONDITION_DESCRIPTION_CACHE] = {}
hass.data[CONDITION_DISABLED_CONDITIONS] = set()
hass.data[CONDITION_PLATFORM_SUBSCRIPTIONS] = []
hass.data[CONDITIONS] = {}
async def new_triggers_conditions_listener(
_event_data: labs.EventLabsUpdatedData,
) -> None:
"""Handle new_triggers_conditions flag change."""
# Invalidate the cache
hass.data[CONDITION_DESCRIPTION_CACHE] = {}
hass.data[CONDITION_DISABLED_CONDITIONS] = set()
labs.async_subscribe_preview_feature(
hass,
automation.DOMAIN,
automation.NEW_TRIGGERS_CONDITIONS_FEATURE_FLAG,
new_triggers_conditions_listener,
)
await async_process_integration_platforms(
hass, "condition", _register_condition_platform, wait_for_platforms=True
)
@callback
def async_subscribe_platform_events(
hass: HomeAssistant,
on_event: Callable[[set[str]], Coroutine[Any, Any, None]],
) -> Callable[[], None]:
"""Subscribe to condition platform events."""
condition_platform_event_subscriptions = hass.data[CONDITION_PLATFORM_SUBSCRIPTIONS]
def remove_subscription() -> None:
condition_platform_event_subscriptions.remove(on_event)
condition_platform_event_subscriptions.append(on_event)
return remove_subscription
async def _register_condition_platform(
hass: HomeAssistant, integration_domain: str, platform: ConditionProtocol
) -> None:
"""Register a condition platform and notify listeners.
If the condition platform does not provide any conditions, or it is disabled,
listeners will not be notified.
"""
from homeassistant.components import automation # noqa: PLC0415
new_conditions: set[str] = set()
conditions = hass.data[CONDITIONS]
if hasattr(platform, "async_get_conditions"):
all_conditions = await platform.async_get_conditions(hass)
for condition_key in all_conditions:
condition_key = get_absolute_description_key(
integration_domain, condition_key
)
if condition_key not in conditions:
conditions[condition_key] = integration_domain
new_conditions.add(condition_key)
if not new_conditions:
if not all_conditions:
_LOGGER.debug(
"Integration %s returned no conditions in async_get_conditions",
integration_domain,
)
return
else:
_LOGGER.debug(
"Integration %s does not provide condition support, skipping",
integration_domain,
)
return
if automation.is_disabled_experimental_condition(hass, integration_domain):
_LOGGER.debug("Conditions for integration %s are disabled", integration_domain)
return
# We don't use gather here because gather adds additional overhead
# when wrapping each coroutine in a task, and we expect our listeners
# to call condition.async_get_all_descriptions which will only yield
# the first time it's called, after that it returns cached data.
for listener in hass.data[CONDITION_PLATFORM_SUBSCRIPTIONS]:
try:
await listener(new_conditions)
except Exception:
_LOGGER.exception("Error while notifying condition platform listener")
_CONDITION_BASE_SCHEMA = vol.Schema(
{
**cv.CONDITION_BASE_SCHEMA,
vol.Required(CONF_CONDITION): str,
}
)
_CONDITION_SCHEMA = _CONDITION_BASE_SCHEMA.extend(
{
vol.Optional(CONF_OPTIONS): object,
vol.Optional(CONF_TARGET): cv.TARGET_FIELDS,
}
)
class ConditionChecker(abc.ABC):
"""Base class for condition checkers."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize condition checker."""
self._hass = hass
self._unloaded = False
def __call__(
self, hass: HomeAssistant, variables: TemplateVarsType = None
) -> bool | None:
"""Check the condition.
`hass` parameter is for backwards compatibility only and is always ignored.
"""
return self.async_check(variables=variables)
def __del__(self) -> None:
"""Clean up when the checker is deleted."""
if self._unloaded:
return
try:
self.async_unload()
except Exception:
_LOGGER.exception("Error while unloading condition checker")
async def async_setup(self) -> None:
"""Set up the condition checker.
Intended to be overridden in derived classes that need to do setup.
"""
def async_unload(self) -> None:
"""Clean up any resources held by the checker.
Intended to be overridden in derived classes that need to do unloading.
"""
self._unloaded = True
def async_check(
self, *, variables: TemplateVarsType = None, **kwargs: Never
) -> bool | None:
"""Check the condition."""
with trace_condition(variables):
result = self._async_check(variables=variables)
condition_trace_update_result(result=result)
return result
@abc.abstractmethod
def _async_check(self, **kwargs: Unpack[ConditionCheckParams]) -> bool | None:
"""Check the condition."""
class LegacyConditionChecker(ConditionChecker):
"""Condition checker wrapping a legacy condition factory function."""
def __init__(self, hass: HomeAssistant, checker: ConditionCheckerType) -> None:
"""Initialize condition checker."""
super().__init__(hass)
self._checker = checker
def _async_check(self, variables: TemplateVarsType = None, **kwargs: Any) -> bool:
return self._checker(self._hass, variables)
class DisabledConditionChecker(ConditionChecker):
"""Condition checker for disabled conditions."""
def _async_check(self, **kwargs: Unpack[ConditionCheckParams]) -> None:
return None
class CompoundConditionChecker(ConditionChecker):
"""Base class for compound condition checkers (and/or/not)."""
def __init__(self, hass: HomeAssistant, conditions: list[ConditionChecker]) -> None:
"""Initialize condition checker."""
super().__init__(hass)
self._conditions = conditions
def async_unload(self) -> None:
"""Clean up child conditions."""
for condition in self._conditions:
condition.async_unload()
super().async_unload()
class Condition(ConditionChecker):
"""Condition class."""
@classmethod
async def async_validate_complete_config(
cls, hass: HomeAssistant, complete_config: ConfigType
) -> ConfigType:
"""Validate complete config.
The complete config includes fields that are generic to all conditions,
such as the alias.
This method should be overridden by conditions that need to migrate
from the old-style config.
"""
complete_config = _CONDITION_SCHEMA(complete_config)
specific_config: ConfigType = {}
for key in (CONF_OPTIONS, CONF_TARGET):
if key in complete_config:
specific_config[key] = complete_config.pop(key)
specific_config = await cls.async_validate_config(hass, specific_config)
for key in (CONF_OPTIONS, CONF_TARGET):
if key in specific_config:
complete_config[key] = specific_config[key]
return complete_config
@classmethod
@abc.abstractmethod
async def async_validate_config(
cls, hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
def __init__(self, hass: HomeAssistant, config: ConditionConfig) -> None:
"""Initialize condition."""
super().__init__(hass)
ATTR_BEHAVIOR: Final = "behavior"
BEHAVIOR_ANY: Final = "any"
BEHAVIOR_ALL: Final = "all"
ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL = vol.Schema(
{
vol.Required(CONF_TARGET): cv.TARGET_FIELDS,
vol.Required(CONF_OPTIONS): {
vol.Required(ATTR_BEHAVIOR, default=BEHAVIOR_ANY): vol.In(
[BEHAVIOR_ANY, BEHAVIOR_ALL]
),
},
}
)
ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL_FOR = (
ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL.extend(
{
vol.Required(CONF_OPTIONS): {
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
},
}
)
)
class EntityConditionBase(Condition):
"""Base class for entity conditions."""
_domain_specs: Mapping[str, DomainSpec]
_schema: vol.Schema = ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL
# When True, indirect target expansion (via device/area/floor) skips
# entities with an entity_category.
_primary_entities_only: ClassVar[bool] = True
@override
@classmethod
async def async_validate_config(
cls, hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
return cast(ConfigType, cls._schema(config))
def __init__(self, hass: HomeAssistant, config: ConditionConfig) -> None:
"""Initialize condition."""
super().__init__(hass, config)
if TYPE_CHECKING:
assert config.target
assert config.options
self._target = config.target
self._target_selection = TargetSelection(config.target)
self._behavior = config.options[ATTR_BEHAVIOR]
self._duration: timedelta | None = config.options.get(CONF_FOR)
if self._behavior == BEHAVIOR_ANY:
self._matcher = self._check_any_match_state
elif self._behavior == BEHAVIOR_ALL:
self._matcher = self._check_all_match_state
self._on_unload: list[Callable[[], None]] = []
self._valid_since: dict[str, datetime] = {}
def entity_filter(self, entities: set[str]) -> set[str]:
"""Filter entities matching any of the domain specs."""
return filter_by_domain_specs(self._hass, self._domain_specs, entities)
@property
def _needs_duration_tracking(self) -> bool:
"""Whether this condition needs active state change tracking for duration.
The base implementation intentionally defaults to always tracking
duration and should be overridden by subclasses that can safely use
state.last_changed directly. For example, conditions that are true
for a single main state value may not need active tracking, while
conditions that track attributes or match multiple states do because
last_changed does not capture those transitions.
"""
return True
def _update_valid_since(self, entity_id: str, _state: State | None) -> None:
"""Update _valid_since tracking for an entity based on its current state.
If the entity is in a valid state and not already tracked, records when
the condition became true. If the entity is not in a valid state, removes
it from tracking.
For state-based conditions (value_source is None), last_changed
accurately reflects when the state changed to the current value.
For attribute-based conditions, last_changed only tracks main state
changes, so we use last_updated which is bumped on any update
(state or attributes). This is conservative — the tracked attribute
may have held its value longer — but it's the best we can do
to avoid false positives.
"""
if (
_state is not None
and _state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
and self.is_valid_state(_state)
):
# Only record the time if not already tracked, to avoid
# resetting the duration on unrelated state/attribute updates.
if entity_id not in self._valid_since:
domain_spec = self._domain_specs[_state.domain]
if domain_spec.value_source is None:
self._valid_since[entity_id] = _state.last_changed
else:
self._valid_since[entity_id] = _state.last_updated
else:
self._valid_since.pop(entity_id, None)
@override
async def async_setup(self) -> None:
"""Set up state tracking for duration-based conditions."""
await super().async_setup()
if not self._duration or not self._needs_duration_tracking:
return
@callback
def _state_change_listener(
data: TargetStateChangedData,
) -> None:
"""Track when entities enter or leave a valid state."""
event = data.state_change_event
entity_id = event.data["entity_id"]
to_state = event.data["new_state"]
self._update_valid_since(entity_id, to_state)
@callback
def _on_entities_update(added: set[str], removed: set[str]) -> None:
"""Handle changes to the tracked entity set."""
for entity_id in added:
self._update_valid_since(entity_id, self._hass.states.get(entity_id))
for entity_id in removed:
self._valid_since.pop(entity_id, None)
unsub = async_track_target_selector_state_change_event(
self._hass,
self._target,
_state_change_listener,
self.entity_filter,
_on_entities_update,
primary_entities_only=self._primary_entities_only,
)
self._on_unload.append(unsub)
@override
def async_unload(self) -> None:
"""Unsubscribe from listeners."""
super().async_unload()
for cb in self._on_unload:
cb()
self._on_unload.clear()
def _get_tracked_value(self, entity_state: State) -> Any:
"""Get the tracked value from a state based on the DomainSpec."""
domain_spec = self._domain_specs[entity_state.domain]
if domain_spec.value_source is None:
return entity_state.state
return entity_state.attributes.get(domain_spec.value_source)
@abc.abstractmethod
def is_valid_state(self, entity_state: State) -> bool:
"""Check if the state matches the expected state(s)."""
def _check_any_match_state(self, states: list[State]) -> bool:
"""Test if any entity matches the state."""
if not self._duration:
# Skip duration check if duration is not specified or 0
return any(self.is_valid_state(state) for state in states)
cutoff = dt_util.utcnow() - self._duration
if not self._needs_duration_tracking:
return any(
self.is_valid_state(state) and state.last_changed <= cutoff
for state in states
)
return any(
self.is_valid_state(state)
and (valid_since := self._valid_since.get(state.entity_id)) is not None
and valid_since <= cutoff
for state in states
)
def _check_all_match_state(self, states: list[State]) -> bool:
"""Test if all entities match the state."""
if not self._duration:
# Skip duration check if duration is not specified or 0
return all(self.is_valid_state(state) for state in states)
cutoff = dt_util.utcnow() - self._duration
if not self._needs_duration_tracking:
return all(
self.is_valid_state(state) and state.last_changed <= cutoff
for state in states
)
return all(
self.is_valid_state(state)
and (valid_since := self._valid_since.get(state.entity_id)) is not None
and valid_since <= cutoff
for state in states
)
def _async_check(self, **kwargs: Unpack[ConditionCheckParams]) -> bool:
"""Test state condition."""
targeted_entities = async_extract_referenced_entity_ids(
self._hass,
self._target_selection,
expand_group=False,
primary_entities_only=self._primary_entities_only,
)
referenced_entity_ids = targeted_entities.referenced.union(
targeted_entities.indirectly_referenced
)
filtered_entity_ids = self.entity_filter(referenced_entity_ids)
entity_states = [
_state
for entity_id in filtered_entity_ids
if (_state := self._hass.states.get(entity_id))
and _state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
]
return self._matcher(entity_states)
class EntityStateConditionBase(EntityConditionBase):
"""State condition."""
_states: set[str | bool]
@property
def _needs_duration_tracking(self) -> bool:
"""Single-state conditions with no attribute tracking can use last_changed."""
if len(self._states) != 1:
return True
return any(
spec.value_source is not None for spec in self._domain_specs.values()
)
def is_valid_state(self, entity_state: State) -> bool:
"""Check if the state matches the expected state(s)."""
return self._get_tracked_value(entity_state) in self._states
def _normalize_domain_specs(
domain_specs: Mapping[str, DomainSpec] | str,
) -> Mapping[str, DomainSpec]:
"""Normalize domain_specs argument to a Mapping."""
if isinstance(domain_specs, str):
return {domain_specs: DomainSpec()}
return domain_specs
def make_entity_state_condition(
domain_specs: Mapping[str, DomainSpec] | str,
states: str | bool | set[str | bool],
*,
support_duration: bool = False,
primary_entities_only: bool = True,
) -> type[EntityStateConditionBase]:
"""Create a condition for entity state changes to specific state(s).
domain_specs can be a string (domain name) for simple state-based conditions,
or a Mapping[str, DomainSpec] for attribute-based or multi-domain conditions.
"""
specs = _normalize_domain_specs(domain_specs)
if isinstance(states, (str, bool)):
states_set: set[str | bool] = {states}
else:
states_set = states
class CustomCondition(EntityStateConditionBase):
"""Condition for entity state."""
_domain_specs = specs
_schema = (
ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL_FOR
if support_duration
else ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL
)
_states = states_set
_primary_entities_only = primary_entities_only
return CustomCondition
NUMERICAL_CONDITION_SCHEMA = ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL.extend(
{
vol.Required(CONF_OPTIONS): {
vol.Required("threshold"): NumericThresholdSelector(
NumericThresholdSelectorConfig(mode=NumericThresholdMode.IS)
),
},
}
)
class EntityNumericalConditionBase(EntityConditionBase):
"""Condition for numerical state comparisons with above/below thresholds."""
_schema = NUMERICAL_CONDITION_SCHEMA
_valid_unit: str | None | UndefinedType = UNDEFINED
def __init__(self, hass: HomeAssistant, config: ConditionConfig) -> None:
"""Initialize the numerical condition."""
super().__init__(hass, config)
if TYPE_CHECKING:
assert config.options is not None
threshold_options: dict[str, Any] = config.options["threshold"]
self.threshold = ThresholdConfig.from_config(threshold_options.get("value"))
self.lower_threshold = ThresholdConfig.from_config(
threshold_options.get("value_min")
)
self.upper_threshold = ThresholdConfig.from_config(
threshold_options.get("value_max")
)
self._threshold_type = threshold_options["type"]
def _is_valid_unit(self, unit: str | None) -> bool:
"""Check if the given unit is valid for this condition."""
if isinstance(self._valid_unit, UndefinedType):
return True
return unit == self._valid_unit
def _get_threshold_value(self, threshold: ThresholdConfig | None) -> float | None:
"""Get threshold value from float or entity state."""
if threshold is None:
return None
if threshold.numerical:
return threshold.number
if not (entity_state := self._hass.states.get(threshold.entity)): # type: ignore[arg-type]
# Entity not found
return None
if not self._is_valid_unit(
entity_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
):
# Entity unit does not match the expected unit
return None
try:
return float(entity_state.state)
except TypeError, ValueError:
# Entity state is not a valid number
return None
def _get_tracked_value(self, entity_state: State) -> Any:
"""Get the tracked value from a state, with unit validation for state-based values."""
domain_spec = self._domain_specs[entity_state.domain]
if domain_spec.value_source is None:
if not self._is_valid_unit(
entity_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
):
return None
return entity_state.state
return entity_state.attributes.get(domain_spec.value_source)
def is_valid_state(self, entity_state: State) -> bool:
"""Check if the state is within the specified range."""
try:
value = float(self._get_tracked_value(entity_state))
except TypeError, ValueError:
return False
if self._threshold_type == NumericThresholdType.ABOVE:
if (limit := self._get_threshold_value(self.threshold)) is None:
# Entity not found or invalid number, don't trigger
return False
return value > limit
if self._threshold_type == NumericThresholdType.BELOW:
if (limit := self._get_threshold_value(self.threshold)) is None:
# Entity not found or invalid number, don't trigger
return False
return value < limit
# Mode is BETWEEN or OUTSIDE
lower_limit = self._get_threshold_value(self.lower_threshold)
upper_limit = self._get_threshold_value(self.upper_threshold)
if lower_limit is None or upper_limit is None:
# Entity not found or invalid number, don't trigger
return False
between = lower_limit < value < upper_limit
if self._threshold_type == NumericThresholdType.BETWEEN:
return between
return not between
def make_entity_numerical_condition(
domain_specs: Mapping[str, DomainSpec] | str,
valid_unit: str | None | UndefinedType = UNDEFINED,
*,
primary_entities_only: bool = True,
) -> type[EntityNumericalConditionBase]:
"""Create a condition for numerical state comparisons."""
specs = _normalize_domain_specs(domain_specs)
class CustomCondition(EntityNumericalConditionBase):
"""Condition for numerical state."""
_domain_specs = specs
_valid_unit = valid_unit
_primary_entities_only = primary_entities_only
return CustomCondition
def _make_numerical_condition_with_unit_schema(
unit_converter: type[BaseUnitConverter],
) -> vol.Schema:
"""Factory for numerical condition schema with unit option."""
return ENTITY_STATE_CONDITION_SCHEMA_ANY_ALL.extend(
{
vol.Required(CONF_OPTIONS): {
vol.Required("threshold"): NumericThresholdSelector(
NumericThresholdSelectorConfig(
mode=NumericThresholdMode.IS,
unit_of_measurement=list(unit_converter.VALID_UNITS),
)
),
},
}
)
class EntityNumericalConditionWithUnitBase(EntityNumericalConditionBase):
"""Condition for numerical state comparisons with unit conversion."""
_base_unit: str | None # Base unit for the tracked value
_unit_converter: type[BaseUnitConverter]
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Create a schema."""
super().__init_subclass__(**kwargs)
cls._schema = _make_numerical_condition_with_unit_schema(cls._unit_converter)
def _get_entity_unit(self, entity_state: State) -> str | None:
"""Get the unit of an entity from its state."""
return entity_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
def _get_threshold_value(self, threshold: ThresholdConfig | None) -> float | None:
"""Get threshold value from float or entity state."""
if threshold is None:
return None
if threshold.numerical:
return self._unit_converter.convert(
threshold.number, # type: ignore[arg-type]
threshold.unit, # type: ignore[arg-type]
self._base_unit,
)
if not (entity_state := self._hass.states.get(threshold.entity)): # type: ignore[arg-type]
# Entity not found
return None
try:
value = float(entity_state.state)
except TypeError, ValueError:
# Entity state is not a valid number
return None
try:
return self._unit_converter.convert(
value,
entity_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT),
self._base_unit,
)
except HomeAssistantError:
# Unit conversion failed (i.e. incompatible units), treat as invalid number
return None
def _get_tracked_value(self, entity_state: State) -> Any:
"""Get the tracked numerical value from a state."""
domain_spec = self._domain_specs[entity_state.domain]
raw_value: Any
if domain_spec.value_source is None:
raw_value = entity_state.state
else:
raw_value = entity_state.attributes.get(domain_spec.value_source)
try:
value = float(raw_value)
except TypeError, ValueError:
return None
try:
return self._unit_converter.convert(
value, self._get_entity_unit(entity_state), self._base_unit
)
except HomeAssistantError:
return None
def make_entity_numerical_condition_with_unit(
domain_specs: Mapping[str, DomainSpec],
base_unit: str,
unit_converter: type[BaseUnitConverter],
) -> type[EntityNumericalConditionWithUnitBase]:
"""Create a condition for numerical state comparisons with unit conversion."""
class CustomCondition(EntityNumericalConditionWithUnitBase):
"""Condition for numerical state with unit conversion."""
_domain_specs = domain_specs
_base_unit = base_unit
_unit_converter = unit_converter
return CustomCondition
class ConditionProtocol(Protocol):
"""Define the format of condition modules."""
async def async_get_conditions(
self, hass: HomeAssistant
) -> dict[str, type[Condition]]:
"""Return the conditions provided by this integration."""
@dataclass(slots=True)
class ConditionConfig:
"""Condition config."""
options: dict[str, Any] | None = None
target: dict[str, Any] | None = None
class ConditionCheckParams(TypedDict, total=False):
"""Condition check params."""
variables: TemplateVarsType
type ConditionCheckerType = Callable[[HomeAssistant, TemplateVarsType], bool]
type ConditionCheckerTypeOptional = Callable[
[HomeAssistant, TemplateVarsType], bool | None
]
def condition_trace_append(variables: TemplateVarsType, path: str) -> TraceElement:
"""Append a TraceElement to trace[path]."""
trace_element = TraceElement(variables, path)
trace_append_element(trace_element)
return trace_element
def condition_trace_set_result(result: bool, **kwargs: Any) -> None:
"""Set the result of TraceElement at the top of the stack."""
node = trace_stack_top(trace_stack_cv)
# The condition function may be called directly, in which case tracing
# is not setup
if not node:
return
node.set_result(result=result, **kwargs)
def condition_trace_update_result(**kwargs: Any) -> None:
"""Update the result of TraceElement at the top of the stack."""
node = trace_stack_top(trace_stack_cv)
# The condition function may be called directly, in which case tracing
# is not setup
if not node:
return
node.update_result(**kwargs)
@contextmanager
def trace_condition(variables: TemplateVarsType) -> Generator[TraceElement]:
"""Trace condition evaluation."""
should_pop = True
trace_element = trace_stack_top(trace_stack_cv)
if trace_element and trace_element.reuse_by_child:
should_pop = False
trace_element.reuse_by_child = False
else:
trace_element = condition_trace_append(variables, trace_path_get())
trace_stack_push(trace_stack_cv, trace_element)
try:
yield trace_element
except Exception as ex:
trace_element.set_error(ex)
raise
finally: