1 """Offer template automation rules."""
3 from datetime
import timedelta
7 import voluptuous
as vol
9 from homeassistant
import exceptions
14 EventStateChangedData,
24 async_track_template_result,
30 _LOGGER = logging.getLogger(__name__)
32 TRIGGER_SCHEMA = IF_ACTION_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
34 vol.Required(CONF_PLATFORM):
"template",
35 vol.Required(CONF_VALUE_TEMPLATE): cv.template,
36 vol.Optional(CONF_FOR): cv.positive_time_period_template,
44 action: TriggerActionType,
45 trigger_info: TriggerInfo,
47 platform_type: str =
"template",
49 """Listen for state changes based on configuration."""
50 trigger_data = trigger_info[
"trigger_data"]
51 value_template: Template = config[CONF_VALUE_TEMPLATE]
52 time_delta = config.get(CONF_FOR)
60 value_template.async_render(trigger_info[
"variables"])
65 "Error initializing 'template' trigger for '%s': %s",
71 def template_listener(
72 event: Event[EventStateChangedData] |
None,
73 updates: list[TrackTemplateResult],
75 """Listen for state changes and calls action."""
76 nonlocal delay_cancel, armed
77 result = updates.pop().result
81 "Error evaluating 'template' trigger for '%s': %s",
102 entity_id = event
and event.data[
"entity_id"]
103 from_s = event
and event.data[
"old_state"]
104 to_s = event
and event.data[
"new_state"]
106 if entity_id
is not None:
107 description = f
"{entity_id} via template"
109 description =
"time change or manual update via template"
111 template_variables = {
112 "platform": platform_type,
113 "entity_id": entity_id,
114 "from_state": from_s,
117 trigger_variables = {
120 "description": description,
124 def call_action(*_: Any) ->
None:
125 """Call action with right context."""
126 nonlocal trigger_variables
127 hass.async_run_hass_job(
129 {
"trigger": {**template_variables, **trigger_variables}},
130 (to_s.context
if to_s
else None),
138 period: timedelta = cv.positive_time_period(
139 template.render_complex(time_delta, {
"trigger": template_variables})
143 "Error rendering '%s' for template: %s", trigger_info[
"name"], ex
147 trigger_variables[
"for"] = period
156 unsub = info.async_remove
160 """Remove state listeners async."""
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info, *str platform_type="template")
CALLBACK_TYPE async_call_later(HomeAssistant hass, float|timedelta delay, HassJob[[datetime], Coroutine[Any, Any, None]|None]|Callable[[datetime], Coroutine[Any, Any, None]|None] action)
TrackTemplateResultInfo async_track_template_result(HomeAssistant hass, Sequence[TrackTemplate] track_templates, TrackTemplateResultListener action, bool strict=False, Callable[[int, str], None]|None log_fn=None, bool has_super_template=False)
None async_remove(HomeAssistant hass, str intent_type)
bool result_as_boolean(Any|None template_result)