forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.py
1633 lines (1290 loc) · 51.3 KB
/
event.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
"""Helpers for listening to events."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Iterable, Sequence
import copy
from dataclasses import dataclass
from datetime import datetime, timedelta
import functools as ft
import logging
import time
from typing import Any, Union, cast
import attr
from typing_extensions import Concatenate, ParamSpec
from homeassistant.const import (
ATTR_ENTITY_ID,
EVENT_CORE_CONFIG_UPDATE,
EVENT_STATE_CHANGED,
MATCH_ALL,
SUN_EVENT_SUNRISE,
SUN_EVENT_SUNSET,
)
from homeassistant.core import (
CALLBACK_TYPE,
Event,
HassJob,
HomeAssistant,
State,
callback,
split_entity_id,
)
from homeassistant.exceptions import TemplateError
from homeassistant.loader import bind_hass
from homeassistant.util import dt as dt_util
from homeassistant.util.async_ import run_callback_threadsafe
from .entity_registry import EVENT_ENTITY_REGISTRY_UPDATED
from .ratelimit import KeyedRateLimit
from .sun import get_astral_event_next
from .template import RenderInfo, Template, result_as_boolean
from .typing import TemplateVarsType
TRACK_STATE_CHANGE_CALLBACKS = "track_state_change_callbacks"
TRACK_STATE_CHANGE_LISTENER = "track_state_change_listener"
TRACK_STATE_ADDED_DOMAIN_CALLBACKS = "track_state_added_domain_callbacks"
TRACK_STATE_ADDED_DOMAIN_LISTENER = "track_state_added_domain_listener"
TRACK_STATE_REMOVED_DOMAIN_CALLBACKS = "track_state_removed_domain_callbacks"
TRACK_STATE_REMOVED_DOMAIN_LISTENER = "track_state_removed_domain_listener"
TRACK_ENTITY_REGISTRY_UPDATED_CALLBACKS = "track_entity_registry_updated_callbacks"
TRACK_ENTITY_REGISTRY_UPDATED_LISTENER = "track_entity_registry_updated_listener"
_ALL_LISTENER = "all"
_DOMAINS_LISTENER = "domains"
_ENTITIES_LISTENER = "entities"
_LOGGER = logging.getLogger(__name__)
_P = ParamSpec("_P")
@dataclass
class TrackStates:
"""Class for keeping track of states being tracked.
all_states: All states on the system are being tracked
entities: Entities to track
domains: Domains to track
"""
all_states: bool
entities: set[str]
domains: set[str]
@dataclass
class TrackTemplate:
"""Class for keeping track of a template with variables.
The template is template to calculate.
The variables are variables to pass to the template.
The rate_limit is a rate limit on how often the template is re-rendered.
"""
template: Template
variables: TemplateVarsType
rate_limit: timedelta | None = None
@dataclass
class TrackTemplateResult:
"""Class for result of template tracking.
template
The template that has changed.
last_result
The output from the template on the last successful run, or None
if no previous successful run.
result
Result from the template run. This will be a string or an
TemplateError if the template resulted in an error.
"""
template: Template
last_result: Any
result: Any
def threaded_listener_factory(
async_factory: Callable[Concatenate[HomeAssistant, _P], Any] # type: ignore[misc]
) -> Callable[Concatenate[HomeAssistant, _P], CALLBACK_TYPE]: # type: ignore[misc]
"""Convert an async event helper to a threaded one."""
@ft.wraps(async_factory)
def factory(
hass: HomeAssistant, *args: _P.args, **kwargs: _P.kwargs
) -> CALLBACK_TYPE:
"""Call async event helper safely."""
if not isinstance(hass, HomeAssistant):
raise TypeError("First parameter needs to be a hass instance")
async_remove = run_callback_threadsafe(
hass.loop, ft.partial(async_factory, hass, *args, **kwargs)
).result()
def remove() -> None:
"""Threadsafe removal."""
run_callback_threadsafe(hass.loop, async_remove).result()
return remove
return factory
@callback
@bind_hass
def async_track_state_change(
hass: HomeAssistant,
entity_ids: str | Iterable[str],
action: Callable[[str, State, State], Awaitable[None] | None],
from_state: None | str | Iterable[str] = None,
to_state: None | str | Iterable[str] = None,
) -> CALLBACK_TYPE:
"""Track specific state changes.
entity_ids, from_state and to_state can be string or list.
Use list to match multiple.
Returns a function that can be called to remove the listener.
If entity_ids are not MATCH_ALL along with from_state and to_state
being None, async_track_state_change_event should be used instead
as it is slightly faster.
Must be run within the event loop.
"""
if from_state is not None:
match_from_state = process_state_match(from_state)
if to_state is not None:
match_to_state = process_state_match(to_state)
# Ensure it is a lowercase list with entity ids we want to match on
if entity_ids == MATCH_ALL:
pass
elif isinstance(entity_ids, str):
entity_ids = (entity_ids.lower(),)
else:
entity_ids = tuple(entity_id.lower() for entity_id in entity_ids)
job = HassJob(action)
@callback
def state_change_filter(event: Event) -> bool:
"""Handle specific state changes."""
if from_state is not None:
if (old_state := event.data.get("old_state")) is not None:
old_state = old_state.state
if not match_from_state(old_state):
return False
if to_state is not None:
if (new_state := event.data.get("new_state")) is not None:
new_state = new_state.state
if not match_to_state(new_state):
return False
return True
@callback
def state_change_dispatcher(event: Event) -> None:
"""Handle specific state changes."""
hass.async_run_hass_job(
job,
event.data.get("entity_id"),
event.data.get("old_state"),
event.data.get("new_state"),
)
@callback
def state_change_listener(event: Event) -> None:
"""Handle specific state changes."""
if not state_change_filter(event):
return
state_change_dispatcher(event)
if entity_ids != MATCH_ALL:
# If we have a list of entity ids we use
# async_track_state_change_event to route
# by entity_id to avoid iterating though state change
# events and creating a jobs where the most
# common outcome is to return right away because
# the entity_id does not match since usually
# only one or two listeners want that specific
# entity_id.
return async_track_state_change_event(hass, entity_ids, state_change_listener)
return hass.bus.async_listen(
EVENT_STATE_CHANGED, state_change_dispatcher, event_filter=state_change_filter
)
track_state_change = threaded_listener_factory(async_track_state_change)
@bind_hass
def async_track_state_change_event(
hass: HomeAssistant,
entity_ids: str | Iterable[str],
action: Callable[[Event], Any],
) -> CALLBACK_TYPE:
"""Track specific state change events indexed by entity_id.
Unlike async_track_state_change, async_track_state_change_event
passes the full event to the callback.
In order to avoid having to iterate a long list
of EVENT_STATE_CHANGED and fire and create a job
for each one, we keep a dict of entity ids that
care about the state change events so we can
do a fast dict lookup to route events.
"""
if not (entity_ids := _async_string_to_lower_list(entity_ids)):
return _remove_empty_listener
entity_callbacks = hass.data.setdefault(TRACK_STATE_CHANGE_CALLBACKS, {})
if TRACK_STATE_CHANGE_LISTENER not in hass.data:
@callback
def _async_state_change_filter(event: Event) -> bool:
"""Filter state changes by entity_id."""
return event.data.get("entity_id") in entity_callbacks
@callback
def _async_state_change_dispatcher(event: Event) -> None:
"""Dispatch state changes by entity_id."""
entity_id = event.data.get("entity_id")
if entity_id not in entity_callbacks:
return
for job in entity_callbacks[entity_id][:]:
try:
hass.async_run_hass_job(job, event)
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error while processing state change for %s", entity_id
)
hass.data[TRACK_STATE_CHANGE_LISTENER] = hass.bus.async_listen(
EVENT_STATE_CHANGED,
_async_state_change_dispatcher,
event_filter=_async_state_change_filter,
)
job = HassJob(action)
for entity_id in entity_ids:
entity_callbacks.setdefault(entity_id, []).append(job)
@callback
def remove_listener() -> None:
"""Remove state change listener."""
_async_remove_indexed_listeners(
hass,
TRACK_STATE_CHANGE_CALLBACKS,
TRACK_STATE_CHANGE_LISTENER,
entity_ids,
job,
)
return remove_listener
@callback
def _remove_empty_listener() -> None:
"""Remove a listener that does nothing."""
@callback
def _async_remove_indexed_listeners(
hass: HomeAssistant,
data_key: str,
listener_key: str,
storage_keys: Iterable[str],
job: HassJob[Any],
) -> None:
"""Remove a listener."""
callbacks = hass.data[data_key]
for storage_key in storage_keys:
callbacks[storage_key].remove(job)
if len(callbacks[storage_key]) == 0:
del callbacks[storage_key]
if not callbacks:
hass.data[listener_key]()
del hass.data[listener_key]
@bind_hass
def async_track_entity_registry_updated_event(
hass: HomeAssistant,
entity_ids: str | Iterable[str],
action: Callable[[Event], Any],
) -> CALLBACK_TYPE:
"""Track specific entity registry updated events indexed by entity_id.
Similar to async_track_state_change_event.
"""
if not (entity_ids := _async_string_to_lower_list(entity_ids)):
return _remove_empty_listener
entity_callbacks = hass.data.setdefault(TRACK_ENTITY_REGISTRY_UPDATED_CALLBACKS, {})
if TRACK_ENTITY_REGISTRY_UPDATED_LISTENER not in hass.data:
@callback
def _async_entity_registry_updated_filter(event: Event) -> bool:
"""Filter entity registry updates by entity_id."""
entity_id = event.data.get("old_entity_id", event.data["entity_id"])
return entity_id in entity_callbacks
@callback
def _async_entity_registry_updated_dispatcher(event: Event) -> None:
"""Dispatch entity registry updates by entity_id."""
entity_id = event.data.get("old_entity_id", event.data["entity_id"])
if entity_id not in entity_callbacks:
return
for job in entity_callbacks[entity_id][:]:
try:
hass.async_run_hass_job(job, event)
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error while processing entity registry update for %s",
entity_id,
)
hass.data[TRACK_ENTITY_REGISTRY_UPDATED_LISTENER] = hass.bus.async_listen(
EVENT_ENTITY_REGISTRY_UPDATED,
_async_entity_registry_updated_dispatcher,
event_filter=_async_entity_registry_updated_filter,
)
job = HassJob(action)
for entity_id in entity_ids:
entity_callbacks.setdefault(entity_id, []).append(job)
@callback
def remove_listener() -> None:
"""Remove state change listener."""
_async_remove_indexed_listeners(
hass,
TRACK_ENTITY_REGISTRY_UPDATED_CALLBACKS,
TRACK_ENTITY_REGISTRY_UPDATED_LISTENER,
entity_ids,
job,
)
return remove_listener
@callback
def _async_dispatch_domain_event(
hass: HomeAssistant, event: Event, callbacks: dict[str, list[HassJob[Any]]]
) -> None:
domain = split_entity_id(event.data["entity_id"])[0]
if domain not in callbacks and MATCH_ALL not in callbacks:
return
listeners = callbacks.get(domain, []) + callbacks.get(MATCH_ALL, [])
for job in listeners:
try:
hass.async_run_hass_job(job, event)
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error while processing event %s for domain %s", event, domain
)
@bind_hass
def async_track_state_added_domain(
hass: HomeAssistant,
domains: str | Iterable[str],
action: Callable[[Event], Any],
) -> CALLBACK_TYPE:
"""Track state change events when an entity is added to domains."""
if not (domains := _async_string_to_lower_list(domains)):
return _remove_empty_listener
domain_callbacks = hass.data.setdefault(TRACK_STATE_ADDED_DOMAIN_CALLBACKS, {})
if TRACK_STATE_ADDED_DOMAIN_LISTENER not in hass.data:
@callback
def _async_state_change_filter(event: Event) -> bool:
"""Filter state changes by entity_id."""
return event.data.get("old_state") is None
@callback
def _async_state_change_dispatcher(event: Event) -> None:
"""Dispatch state changes by entity_id."""
if event.data.get("old_state") is not None:
return
_async_dispatch_domain_event(hass, event, domain_callbacks)
hass.data[TRACK_STATE_ADDED_DOMAIN_LISTENER] = hass.bus.async_listen(
EVENT_STATE_CHANGED,
_async_state_change_dispatcher,
event_filter=_async_state_change_filter,
)
job = HassJob(action)
for domain in domains:
domain_callbacks.setdefault(domain, []).append(job)
@callback
def remove_listener() -> None:
"""Remove state change listener."""
_async_remove_indexed_listeners(
hass,
TRACK_STATE_ADDED_DOMAIN_CALLBACKS,
TRACK_STATE_ADDED_DOMAIN_LISTENER,
domains,
job,
)
return remove_listener
@bind_hass
def async_track_state_removed_domain(
hass: HomeAssistant,
domains: str | Iterable[str],
action: Callable[[Event], Any],
) -> CALLBACK_TYPE:
"""Track state change events when an entity is removed from domains."""
if not (domains := _async_string_to_lower_list(domains)):
return _remove_empty_listener
domain_callbacks = hass.data.setdefault(TRACK_STATE_REMOVED_DOMAIN_CALLBACKS, {})
if TRACK_STATE_REMOVED_DOMAIN_LISTENER not in hass.data:
@callback
def _async_state_change_filter(event: Event) -> bool:
"""Filter state changes by entity_id."""
return event.data.get("new_state") is None
@callback
def _async_state_change_dispatcher(event: Event) -> None:
"""Dispatch state changes by entity_id."""
if event.data.get("new_state") is not None:
return
_async_dispatch_domain_event(hass, event, domain_callbacks)
hass.data[TRACK_STATE_REMOVED_DOMAIN_LISTENER] = hass.bus.async_listen(
EVENT_STATE_CHANGED,
_async_state_change_dispatcher,
event_filter=_async_state_change_filter,
)
job = HassJob(action)
for domain in domains:
domain_callbacks.setdefault(domain, []).append(job)
@callback
def remove_listener() -> None:
"""Remove state change listener."""
_async_remove_indexed_listeners(
hass,
TRACK_STATE_REMOVED_DOMAIN_CALLBACKS,
TRACK_STATE_REMOVED_DOMAIN_LISTENER,
domains,
job,
)
return remove_listener
@callback
def _async_string_to_lower_list(instr: str | Iterable[str]) -> list[str]:
if isinstance(instr, str):
return [instr.lower()]
return [mstr.lower() for mstr in instr]
class _TrackStateChangeFiltered:
"""Handle removal / refresh of tracker."""
def __init__(
self,
hass: HomeAssistant,
track_states: TrackStates,
action: Callable[[Event], Any],
) -> None:
"""Handle removal / refresh of tracker init."""
self.hass = hass
self._action = action
self._action_as_hassjob = HassJob(action)
self._listeners: dict[str, Callable[[], None]] = {}
self._last_track_states: TrackStates = track_states
@callback
def async_setup(self) -> None:
"""Create listeners to track states."""
track_states = self._last_track_states
if (
not track_states.all_states
and not track_states.domains
and not track_states.entities
):
return
if track_states.all_states:
self._setup_all_listener()
return
self._setup_domains_listener(track_states.domains)
self._setup_entities_listener(track_states.domains, track_states.entities)
@property
def listeners(self) -> dict:
"""State changes that will cause a re-render."""
track_states = self._last_track_states
return {
_ALL_LISTENER: track_states.all_states,
_ENTITIES_LISTENER: track_states.entities,
_DOMAINS_LISTENER: track_states.domains,
}
@callback
def async_update_listeners(self, new_track_states: TrackStates) -> None:
"""Update the listeners based on the new TrackStates."""
last_track_states = self._last_track_states
self._last_track_states = new_track_states
had_all_listener = last_track_states.all_states
if new_track_states.all_states:
if had_all_listener:
return
self._cancel_listener(_DOMAINS_LISTENER)
self._cancel_listener(_ENTITIES_LISTENER)
self._setup_all_listener()
return
if had_all_listener:
self._cancel_listener(_ALL_LISTENER)
domains_changed = new_track_states.domains != last_track_states.domains
if had_all_listener or domains_changed:
domains_changed = True
self._cancel_listener(_DOMAINS_LISTENER)
self._setup_domains_listener(new_track_states.domains)
if (
had_all_listener
or domains_changed
or new_track_states.entities != last_track_states.entities
):
self._cancel_listener(_ENTITIES_LISTENER)
self._setup_entities_listener(
new_track_states.domains, new_track_states.entities
)
@callback
def async_remove(self) -> None:
"""Cancel the listeners."""
for key in list(self._listeners):
self._listeners.pop(key)()
@callback
def _cancel_listener(self, listener_name: str) -> None:
if listener_name not in self._listeners:
return
self._listeners.pop(listener_name)()
@callback
def _setup_entities_listener(self, domains: set[str], entities: set[str]) -> None:
if domains:
entities = entities.copy()
entities.update(self.hass.states.async_entity_ids(domains))
# Entities has changed to none
if not entities:
return
self._listeners[_ENTITIES_LISTENER] = async_track_state_change_event(
self.hass, entities, self._action
)
@callback
def _state_added(self, event: Event) -> None:
self._cancel_listener(_ENTITIES_LISTENER)
self._setup_entities_listener(
self._last_track_states.domains, self._last_track_states.entities
)
self.hass.async_run_hass_job(self._action_as_hassjob, event)
@callback
def _setup_domains_listener(self, domains: set[str]) -> None:
if not domains:
return
self._listeners[_DOMAINS_LISTENER] = async_track_state_added_domain(
self.hass, domains, self._state_added
)
@callback
def _setup_all_listener(self) -> None:
self._listeners[_ALL_LISTENER] = self.hass.bus.async_listen(
EVENT_STATE_CHANGED, self._action
)
@callback
@bind_hass
def async_track_state_change_filtered(
hass: HomeAssistant,
track_states: TrackStates,
action: Callable[[Event], Any],
) -> _TrackStateChangeFiltered:
"""Track state changes with a TrackStates filter that can be updated.
Parameters
----------
hass
Home assistant object.
track_states
A TrackStates data class.
action
Callable to call with results.
Returns
-------
Object used to update the listeners (async_update_listeners) with a new TrackStates or
cancel the tracking (async_remove).
"""
tracker = _TrackStateChangeFiltered(hass, track_states, action)
tracker.async_setup()
return tracker
@callback
@bind_hass
def async_track_template(
hass: HomeAssistant,
template: Template,
action: Callable[[str, State | None, State | None], Awaitable[None] | None],
variables: TemplateVarsType | None = None,
) -> CALLBACK_TYPE:
"""Add a listener that fires when a a template evaluates to 'true'.
Listen for the result of the template becoming true, or a true-like
string result, such as 'On', 'Open', or 'Yes'. If the template results
in an error state when the value changes, this will be logged and not
passed through.
If the initial check of the template is invalid and results in an
exception, the listener will still be registered but will only
fire if the template result becomes true without an exception.
Action arguments
----------------
entity_id
ID of the entity that triggered the state change.
old_state
The old state of the entity that changed.
new_state
New state of the entity that changed.
Parameters
----------
hass
Home assistant object.
template
The template to calculate.
action
Callable to call with results. See above for arguments.
variables
Variables to pass to the template.
Returns
-------
Callable to unregister the listener.
"""
job = HassJob(action)
@callback
def _template_changed_listener(
event: Event | None, updates: list[TrackTemplateResult]
) -> None:
"""Check if condition is correct and run action."""
track_result = updates.pop()
template = track_result.template
last_result = track_result.last_result
result = track_result.result
if isinstance(result, TemplateError):
_LOGGER.error(
"Error while processing template: %s",
template.template,
exc_info=result,
)
return
if (
not isinstance(last_result, TemplateError)
and result_as_boolean(last_result)
or not result_as_boolean(result)
):
return
hass.async_run_hass_job(
job,
event and event.data.get("entity_id"),
event and event.data.get("old_state"),
event and event.data.get("new_state"),
)
info = async_track_template_result(
hass, [TrackTemplate(template, variables)], _template_changed_listener
)
return info.async_remove
track_template = threaded_listener_factory(async_track_template)
class _TrackTemplateResultInfo:
"""Handle removal / refresh of tracker."""
def __init__(
self,
hass: HomeAssistant,
track_templates: Sequence[TrackTemplate],
action: Callable[[Event | None, list[TrackTemplateResult]], None],
has_super_template: bool = False,
) -> None:
"""Handle removal / refresh of tracker init."""
self.hass = hass
self._job = HassJob(action)
for track_template_ in track_templates:
track_template_.template.hass = hass
self._track_templates = track_templates
self._has_super_template = has_super_template
self._last_result: dict[Template, bool | str | TemplateError] = {}
self._rate_limit = KeyedRateLimit(hass)
self._info: dict[Template, RenderInfo] = {}
self._track_state_changes: _TrackStateChangeFiltered | None = None
self._time_listeners: dict[Template, Callable[[], None]] = {}
def async_setup(self, raise_on_template_error: bool, strict: bool = False) -> None:
"""Activation of template tracking."""
block_render = False
super_template = self._track_templates[0] if self._has_super_template else None
# Render the super template first
if super_template is not None:
template = super_template.template
variables = super_template.variables
self._info[template] = info = template.async_render_to_info(
variables, strict=strict
)
# If the super template did not render to True, don't update other templates
try:
super_result: str | TemplateError = info.result()
except TemplateError as ex:
super_result = ex
if (
super_result is not None
and self._super_template_as_boolean(super_result) is not True
):
block_render = True
# Then update the remaining templates unless blocked by the super template
for track_template_ in self._track_templates:
if block_render or track_template_ == super_template:
continue
template = track_template_.template
variables = track_template_.variables
self._info[template] = info = template.async_render_to_info(
variables, strict=strict
)
if info.exception:
if raise_on_template_error:
raise info.exception
_LOGGER.error(
"Error while processing template: %s",
track_template_.template,
exc_info=info.exception,
)
self._track_state_changes = async_track_state_change_filtered(
self.hass, _render_infos_to_track_states(self._info.values()), self._refresh
)
self._update_time_listeners()
_LOGGER.debug(
"Template group %s listens for %s, first render blocker by super template: %s",
self._track_templates,
self.listeners,
block_render,
)
@property
def listeners(self) -> dict:
"""State changes that will cause a re-render."""
assert self._track_state_changes
return {
**self._track_state_changes.listeners,
"time": bool(self._time_listeners),
}
@callback
def _setup_time_listener(self, template: Template, has_time: bool) -> None:
if not has_time:
if template in self._time_listeners:
# now() or utcnow() has left the scope of the template
self._time_listeners.pop(template)()
return
if template in self._time_listeners:
return
track_templates = [
track_template_
for track_template_ in self._track_templates
if track_template_.template == template
]
@callback
def _refresh_from_time(now: datetime) -> None:
self._refresh(None, track_templates=track_templates)
self._time_listeners[template] = async_track_utc_time_change(
self.hass, _refresh_from_time, second=0
)
@callback
def _update_time_listeners(self) -> None:
for template, info in self._info.items():
self._setup_time_listener(template, info.has_time)
@callback
def async_remove(self) -> None:
"""Cancel the listener."""
assert self._track_state_changes
self._track_state_changes.async_remove()
self._rate_limit.async_remove()
for template in list(self._time_listeners):
self._time_listeners.pop(template)()
@callback
def async_refresh(self) -> None:
"""Force recalculate the template."""
self._refresh(None)
def _render_template_if_ready(
self,
track_template_: TrackTemplate,
now: datetime,
event: Event | None,
) -> bool | TrackTemplateResult:
"""Re-render the template if conditions match.
Returns False if the template was not re-rendered.
Returns True if the template re-rendered and did not
change.
Returns TrackTemplateResult if the template re-render
generates a new result.
"""
template = track_template_.template
if event:
info = self._info[template]
if not _event_triggers_rerender(event, info):
return False
had_timer = self._rate_limit.async_has_timer(template)
if self._rate_limit.async_schedule_action(
template,
_rate_limit_for_event(event, info, track_template_),
now,
self._refresh,
event,
(track_template_,),
True,
):
return not had_timer
_LOGGER.debug(
"Template update %s triggered by event: %s",
template.template,
event,
)
self._rate_limit.async_triggered(template, now)
self._info[template] = info = template.async_render_to_info(
track_template_.variables
)
try:
result: str | TemplateError = info.result()
except TemplateError as ex:
result = ex
last_result = self._last_result.get(template)
# Check to see if the result has changed or is new
if result == last_result and template in self._last_result:
return True
if isinstance(result, TemplateError) and isinstance(last_result, TemplateError):
return True
return TrackTemplateResult(template, last_result, result)
@staticmethod
def _super_template_as_boolean(result: bool | str | TemplateError) -> bool:
"""Return True if the result is truthy or a TemplateError."""
if isinstance(result, TemplateError):
return True
return result_as_boolean(result)
@callback
def _refresh(
self,
event: Event | None,
track_templates: Iterable[TrackTemplate] | None = None,
replayed: bool | None = False,
) -> None:
"""Refresh the template.
The event is the state_changed event that caused the refresh
to be considered.
track_templates is an optional list of TrackTemplate objects
to refresh. If not provided, all tracked templates will be
considered.
replayed is True if the event is being replayed because the
rate limit was hit.
"""
updates: list[TrackTemplateResult] = []
info_changed = False