1 """Offer zone automation rules."""
3 from __future__
import annotations
7 import voluptuous
as vol
19 EventStateChangedData,
26 config_validation
as cv,
27 entity_registry
as er,
36 DEFAULT_EVENT = EVENT_ENTER
38 _LOGGER = logging.getLogger(__name__)
40 _EVENT_DESCRIPTION = {EVENT_ENTER:
"entering", EVENT_LEAVE:
"leaving"}
42 _TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
44 vol.Required(CONF_PLATFORM):
"zone",
45 vol.Required(CONF_ENTITY_ID): cv.entity_ids_or_uuids,
46 vol.Required(CONF_ZONE): cv.entity_id,
47 vol.Required(CONF_EVENT, default=DEFAULT_EVENT): vol.Any(
48 EVENT_ENTER, EVENT_LEAVE
55 hass: HomeAssistant, config: ConfigType
57 """Validate trigger config."""
59 registry = er.async_get(hass)
60 config[CONF_ENTITY_ID] = er.async_validate_entity_ids(
61 registry, config[CONF_ENTITY_ID]
69 action: TriggerActionType,
70 trigger_info: TriggerInfo,
72 platform_type: str =
"zone",
74 """Listen for state changes based on configuration."""
75 trigger_data = trigger_info[
"trigger_data"]
76 entity_id: list[str] = config[CONF_ENTITY_ID]
77 zone_entity_id: str = config[CONF_ZONE]
78 event: str = config[CONF_EVENT]
82 def zone_automation_listener(zone_event: Event[EventStateChangedData]) ->
None:
83 """Listen for state changes and calls action."""
84 entity = zone_event.data[
"entity_id"]
85 from_s = zone_event.data[
"old_state"]
86 to_s = zone_event.data[
"new_state"]
90 and not location.has_location(from_s)
92 and not location.has_location(to_s)
96 if not (zone_state := hass.states.get(zone_entity_id)):
99 "Automation '%s' is referencing non-existing zone '%s' in a zone"
102 trigger_info[
"name"],
107 from_match = condition.zone(hass, zone_state, from_s)
if from_s
else False
108 to_match = condition.zone(hass, zone_state, to_s)
if to_s
else False
114 or event == EVENT_LEAVE
118 description = f
"{entity} {_EVENT_DESCRIPTION[event]} {zone_state.attributes[ATTR_FRIENDLY_NAME]}"
119 hass.async_run_hass_job(
124 "platform": platform_type,
126 "from_state": from_s,
130 "description": description,
133 to_s.context
if to_s
else None,
ConfigType async_validate_trigger_config(HomeAssistant hass, ConfigType config)
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info, *str platform_type="zone")
CALLBACK_TYPE async_track_state_change_event(HomeAssistant hass, str|Iterable[str] entity_ids, Callable[[Event[EventStateChangedData]], Any] action, HassJobType|None job_type=None)