Home Assistant Unofficial Reference 2024.12.1
event.py
Go to the documentation of this file.
1 """Platform allowing several event entities to be grouped into one event."""
2 
3 from __future__ import annotations
4 
5 import itertools
6 from typing import Any
7 
8 import voluptuous as vol
9 
11  ATTR_EVENT_TYPE,
12  ATTR_EVENT_TYPES,
13  DOMAIN as EVENT_DOMAIN,
14  PLATFORM_SCHEMA as EVENT_PLATFORM_SCHEMA,
15  EventEntity,
16 )
17 from homeassistant.config_entries import ConfigEntry
18 from homeassistant.const import (
19  ATTR_DEVICE_CLASS,
20  ATTR_ENTITY_ID,
21  ATTR_FRIENDLY_NAME,
22  CONF_ENTITIES,
23  CONF_NAME,
24  CONF_UNIQUE_ID,
25  STATE_UNAVAILABLE,
26  STATE_UNKNOWN,
27 )
28 from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback
29 from homeassistant.helpers import config_validation as cv, entity_registry as er
30 from homeassistant.helpers.entity_platform import AddEntitiesCallback
31 from homeassistant.helpers.event import async_track_state_change_event
32 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
33 
34 from .entity import GroupEntity
35 
36 DEFAULT_NAME = "Event group"
37 
38 # No limit on parallel updates to enable a group calling another group
39 PARALLEL_UPDATES = 0
40 
41 PLATFORM_SCHEMA = EVENT_PLATFORM_SCHEMA.extend(
42  {
43  vol.Required(CONF_ENTITIES): cv.entities_domain(EVENT_DOMAIN),
44  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
45  vol.Optional(CONF_UNIQUE_ID): cv.string,
46  }
47 )
48 
49 
51  _: HomeAssistant,
52  config: ConfigType,
53  async_add_entities: AddEntitiesCallback,
54  __: DiscoveryInfoType | None = None,
55 ) -> None:
56  """Set up the event group platform."""
58  [
59  EventGroup(
60  config.get(CONF_UNIQUE_ID),
61  config[CONF_NAME],
62  config[CONF_ENTITIES],
63  )
64  ]
65  )
66 
67 
69  hass: HomeAssistant,
70  config_entry: ConfigEntry,
71  async_add_entities: AddEntitiesCallback,
72 ) -> None:
73  """Initialize event group config entry."""
74  registry = er.async_get(hass)
75  entities = er.async_validate_entity_ids(
76  registry, config_entry.options[CONF_ENTITIES]
77  )
79  [
80  EventGroup(
81  config_entry.entry_id,
82  config_entry.title,
83  entities,
84  )
85  ]
86  )
87 
88 
89 @callback
91  hass: HomeAssistant, name: str, validated_config: dict[str, Any]
92 ) -> EventGroup:
93  """Create a preview sensor."""
94  return EventGroup(
95  None,
96  name,
97  validated_config[CONF_ENTITIES],
98  )
99 
100 
102  """Representation of an event group."""
103 
104  _attr_available = False
105  _attr_should_poll = False
106 
107  def __init__(
108  self,
109  unique_id: str | None,
110  name: str,
111  entity_ids: list[str],
112  ) -> None:
113  """Initialize an event group."""
114  self._entity_ids_entity_ids = entity_ids
115  self._attr_name_attr_name = name
116  self._attr_extra_state_attributes_attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}
117  self._attr_unique_id_attr_unique_id = unique_id
118  self._attr_event_types_attr_event_types = []
119 
120  async def async_added_to_hass(self) -> None:
121  """Register callbacks."""
122 
123  @callback
124  def async_state_changed_listener(
125  event: Event[EventStateChangedData],
126  ) -> None:
127  """Handle child updates."""
128  if not self.hasshass.is_running:
129  return
130 
131  self.async_set_contextasync_set_context(event.context)
132 
133  # Update all properties of the group
134  self.async_update_group_stateasync_update_group_stateasync_update_group_state()
135 
136  # Re-fire if one of the members fires an event, but only
137  # if the original state was not unavailable or unknown.
138  if (
139  (old_state := event.data["old_state"])
140  and old_state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
141  and (new_state := event.data["new_state"])
142  and new_state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
143  and (event_type := new_state.attributes.get(ATTR_EVENT_TYPE))
144  ):
145  event_attributes = new_state.attributes.copy()
146 
147  # We should not propagate the event properties as
148  # fired event attributes.
149  del event_attributes[ATTR_EVENT_TYPE]
150  del event_attributes[ATTR_EVENT_TYPES]
151  event_attributes.pop(ATTR_DEVICE_CLASS, None)
152  event_attributes.pop(ATTR_FRIENDLY_NAME, None)
153 
154  # Fire the group event
155  self._trigger_event_trigger_event(event_type, event_attributes)
156 
157  self.async_write_ha_stateasync_write_ha_state()
158 
159  self.async_on_removeasync_on_remove(
161  self.hasshass, self._entity_ids_entity_ids, async_state_changed_listener
162  )
163  )
164 
165  await super().async_added_to_hass()
166 
167  @callback
168  def async_update_group_state(self) -> None:
169  """Query all members and determine the event group properties."""
170  states = [
171  state
172  for entity_id in self._entity_ids_entity_ids
173  if (state := self.hasshass.states.get(entity_id)) is not None
174  ]
175 
176  # None of the members are available
177  if not states:
178  self._attr_available_attr_available_attr_available = False
179  return
180 
181  # Gather and combine all possible event types from all entities
182  self._attr_event_types_attr_event_types = list(
183  set(
184  itertools.chain.from_iterable(
185  state.attributes.get(ATTR_EVENT_TYPES, []) for state in states
186  )
187  )
188  )
189 
190  # Set group as unavailable if all members are unavailable or missing
191  self._attr_available_attr_available_attr_available = any(state.state != STATE_UNAVAILABLE for state in states)
None _trigger_event(self, str event_type, dict[str, Any]|None event_attributes=None)
Definition: __init__.py:148
None __init__(self, str|None unique_id, str name, list[str] entity_ids)
Definition: event.py:112
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_set_context(self, Context context)
Definition: entity.py:937
None async_setup_platform(HomeAssistant _, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None __=None)
Definition: event.py:55
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: event.py:72
EventGroup async_create_preview_event(HomeAssistant hass, str name, dict[str, Any] validated_config)
Definition: event.py:92
CALLBACK_TYPE async_track_state_change_event(HomeAssistant hass, str|Iterable[str] entity_ids, Callable[[Event[EventStateChangedData]], Any] action, HassJobType|None job_type=None)
Definition: event.py:314