Home Assistant Unofficial Reference 2024.12.1
trigger_entity.py
Go to the documentation of this file.
1 """Trigger entity."""
2 
3 from __future__ import annotations
4 
5 from homeassistant.core import HomeAssistant, callback
6 from homeassistant.helpers.template import TemplateStateFromEntityId
7 from homeassistant.helpers.trigger_template_entity import TriggerBaseEntity
8 from homeassistant.helpers.update_coordinator import CoordinatorEntity
9 
10 from . import TriggerUpdateCoordinator
11 
12 
13 class TriggerEntity( # pylint: disable=hass-enforce-class-module
14  TriggerBaseEntity, CoordinatorEntity[TriggerUpdateCoordinator]
15 ):
16  """Template entity based on trigger data."""
17 
18  def __init__(
19  self,
20  hass: HomeAssistant,
21  coordinator: TriggerUpdateCoordinator,
22  config: dict,
23  ) -> None:
24  """Initialize the entity."""
25  CoordinatorEntity.__init__(self, coordinator)
26  TriggerBaseEntity.__init__(self, hass, config)
27 
28  async def async_added_to_hass(self) -> None:
29  """Handle being added to Home Assistant."""
30  await super().async_added_to_hass()
31  if self.coordinator.data is not None:
32  self._process_data()
33 
34  def _set_unique_id(self, unique_id: str | None) -> None:
35  """Set unique id."""
36  if unique_id and self.coordinator.unique_id:
37  self._unique_id = f"{self.coordinator.unique_id}-{unique_id}"
38  else:
39  self._unique_id = unique_id
40 
41  @callback
42  def _process_data(self) -> None:
43  """Process new data."""
44 
45  run_variables = self.coordinator.data["run_variables"]
46  variables = {
47  "this": TemplateStateFromEntityId(self.hass, self.entity_id),
48  **(run_variables or {}),
49  }
50 
51  self._render_templates(variables)
52 
53  self.async_set_context(self.coordinator.data["context"])
54 
55  @callback
56  def _handle_coordinator_update(self) -> None:
57  """Handle updated data from the coordinator."""
58  self._process_data()
59  self.async_write_ha_state()
None _set_unique_id(self, str|None unique_id)
None __init__(self, HomeAssistant hass, TriggerUpdateCoordinator coordinator, dict config)