Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Support for esphome entities."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Awaitable, Callable, Coroutine
6 import functools
7 import math
8 from typing import TYPE_CHECKING, Any, Concatenate, Generic, TypeVar, cast
9 
10 from aioesphomeapi import (
11  APIConnectionError,
12  EntityCategory as EsphomeEntityCategory,
13  EntityInfo,
14  EntityState,
15  build_unique_id,
16 )
17 import voluptuous as vol
18 
19 from homeassistant.const import EntityCategory
20 from homeassistant.core import HomeAssistant, callback
21 from homeassistant.exceptions import HomeAssistantError
22 from homeassistant.helpers import entity_platform
25 from homeassistant.helpers.device_registry import DeviceInfo
26 from homeassistant.helpers.entity import Entity
27 from homeassistant.helpers.entity_platform import AddEntitiesCallback
28 
29 # Import config flow so that it's added to the registry
30 from .entry_data import ESPHomeConfigEntry, RuntimeEntryData
31 from .enum_mapper import EsphomeEnumMapper
32 
33 _InfoT = TypeVar("_InfoT", bound=EntityInfo)
34 _EntityT = TypeVar("_EntityT", bound="EsphomeEntity[Any,Any]")
35 _StateT = TypeVar("_StateT", bound=EntityState)
36 
37 
38 @callback
40  hass: HomeAssistant,
41  entry_data: RuntimeEntryData,
42  platform: entity_platform.EntityPlatform,
43  async_add_entities: AddEntitiesCallback,
44  info_type: type[_InfoT],
45  entity_type: type[_EntityT],
46  state_type: type[_StateT],
47  infos: list[EntityInfo],
48 ) -> None:
49  """Update entities of this platform when entities are listed."""
50  current_infos = entry_data.info[info_type]
51  new_infos: dict[int, EntityInfo] = {}
52  add_entities: list[_EntityT] = []
53 
54  for info in infos:
55  if not current_infos.pop(info.key, None):
56  # Create new entity
57  entity = entity_type(entry_data, platform.domain, info, state_type)
58  add_entities.append(entity)
59  new_infos[info.key] = info
60 
61  # Anything still in current_infos is now gone
62  if current_infos:
63  device_info = entry_data.device_info
64  if TYPE_CHECKING:
65  assert device_info is not None
66  entry_data.async_remove_entities(
67  hass, current_infos.values(), device_info.mac_address
68  )
69 
70  # Then update the actual info
71  entry_data.info[info_type] = new_infos
72 
73  if new_infos:
74  entry_data.async_update_entity_infos(new_infos.values())
75 
76  if add_entities:
77  # Add entities to Home Assistant
78  async_add_entities(add_entities)
79 
80 
82  hass: HomeAssistant,
83  entry: ESPHomeConfigEntry,
84  async_add_entities: AddEntitiesCallback,
85  *,
86  info_type: type[_InfoT],
87  entity_type: type[_EntityT],
88  state_type: type[_StateT],
89 ) -> None:
90  """Set up an esphome platform.
91 
92  This method is in charge of receiving, distributing and storing
93  info and state updates.
94  """
95  entry_data = entry.runtime_data
96  entry_data.info[info_type] = {}
97  platform = entity_platform.async_get_current_platform()
98  on_static_info_update = functools.partial(
99  async_static_info_updated,
100  hass,
101  entry_data,
102  platform,
103  async_add_entities,
104  info_type,
105  entity_type,
106  state_type,
107  )
108  entry_data.cleanup_callbacks.append(
109  entry_data.async_register_static_info_callback(
110  info_type,
111  on_static_info_update,
112  )
113  )
114 
115 
116 def esphome_state_property[_R, _EntityT: EsphomeEntity[Any, Any]](
117  func: Callable[[_EntityT], _R],
118 ) -> Callable[[_EntityT], _R | None]:
119  """Wrap a state property of an esphome entity.
120 
121  This checks if the state object in the entity is set
122  and returns None if it is not set.
123  """
124 
125  @functools.wraps(func)
126  def _wrapper(self: _EntityT) -> _R | None:
127  return func(self) if self._has_state else None
128 
129  return _wrapper
130 
131 
132 def esphome_float_state_property[_EntityT: EsphomeEntity[Any, Any]](
133  func: Callable[[_EntityT], float | None],
134 ) -> Callable[[_EntityT], float | None]:
135  """Wrap a state property of an esphome entity that returns a float.
136 
137  This checks if the state object in the entity is set, and returns
138  None if its not set. If also prevents writing NAN values to the
139  Home Assistant state machine.
140  """
141 
142  @functools.wraps(func)
143  def _wrapper(self: _EntityT) -> float | None:
144  if not self._has_state:
145  return None
146  val = func(self)
147  # Home Assistant doesn't use NaN or inf values in state machine
148  # (not JSON serializable)
149  return None if val is None or not math.isfinite(val) else val
150 
151  return _wrapper
152 
153 
154 def convert_api_error_ha_error[**_P, _R, _EntityT: EsphomeEntity[Any, Any]](
155  func: Callable[Concatenate[_EntityT, _P], Awaitable[None]],
156 ) -> Callable[Concatenate[_EntityT, _P], Coroutine[Any, Any, None]]:
157  """Decorate ESPHome command calls that send commands/make changes to the device.
158 
159  A decorator that wraps the passed in function, catches APIConnectionError errors,
160  and raises a HomeAssistant error instead.
161  """
162 
163  async def handler(self: _EntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
164  try:
165  return await func(self, *args, **kwargs)
166  except APIConnectionError as error:
167  raise HomeAssistantError(
168  f"Error communicating with device: {error}"
169  ) from error
170 
171  return handler
172 
173 
174 ICON_SCHEMA = vol.Schema(cv.icon)
175 
176 
177 ENTITY_CATEGORIES: EsphomeEnumMapper[EsphomeEntityCategory, EntityCategory | None] = (
179  {
180  EsphomeEntityCategory.NONE: None,
181  EsphomeEntityCategory.CONFIG: EntityCategory.CONFIG,
182  EsphomeEntityCategory.DIAGNOSTIC: EntityCategory.DIAGNOSTIC,
183  }
184  )
185 )
186 
187 
188 class EsphomeEntity(Entity, Generic[_InfoT, _StateT]):
189  """Define a base esphome entity."""
190 
191  _attr_should_poll = False
192  _static_info: _InfoT
193  _state: _StateT
194  _has_state: bool
195 
196  def __init__(
197  self,
198  entry_data: RuntimeEntryData,
199  domain: str,
200  entity_info: EntityInfo,
201  state_type: type[_StateT],
202  ) -> None:
203  """Initialize."""
204  self._entry_data_entry_data = entry_data
205  self._states_states = cast(dict[int, _StateT], entry_data.state[state_type])
206  assert entry_data.device_info is not None
207  device_info = entry_data.device_info
208  self._device_info_device_info = device_info
209  self._on_entry_data_changed_on_entry_data_changed()
210  self._key_key = entity_info.key
211  self._state_type_state_type = state_type
212  self._on_static_info_update_on_static_info_update(entity_info)
213  self._attr_device_info_attr_device_info = DeviceInfo(
214  connections={(dr.CONNECTION_NETWORK_MAC, device_info.mac_address)}
215  )
216  #
217  # If `friendly_name` is set, we use the Friendly naming rules, if
218  # `friendly_name` is not set we make an exception to the naming rules for
219  # backwards compatibility and use the Legacy naming rules.
220  #
221  # Friendly naming
222  # - Friendly name is prepended to entity names
223  # - Device Name is prepended to entity ids
224  # - Entity id is constructed from device name and object id
225  #
226  # Legacy naming
227  # - Device name is not prepended to entity names
228  # - Device name is not prepended to entity ids
229  # - Entity id is constructed from entity name
230  #
231  if not device_info.friendly_name:
232  return
233  self._attr_has_entity_name_attr_has_entity_name = True
234  self.entity_identity_identity_id = f"{domain}.{device_info.name}_{entity_info.object_id}"
235 
236  async def async_added_to_hass(self) -> None:
237  """Register callbacks."""
238  entry_data = self._entry_data_entry_data
239  self.async_on_removeasync_on_remove(
240  entry_data.async_subscribe_device_updated(
241  self._on_device_update_on_device_update,
242  )
243  )
244  self.async_on_removeasync_on_remove(
245  entry_data.async_subscribe_state_update(
246  self._state_type_state_type, self._key_key, self._on_state_update_on_state_update
247  )
248  )
249  self.async_on_removeasync_on_remove(
250  entry_data.async_register_key_static_info_updated_callback(
251  self._static_info_static_info, self._on_static_info_update_on_static_info_update
252  )
253  )
254  self._update_state_from_entry_data_update_state_from_entry_data()
255 
256  @callback
257  def _on_static_info_update(self, static_info: EntityInfo) -> None:
258  """Save the static info for this entity when it changes.
259 
260  This method can be overridden in child classes to know
261  when the static info changes.
262  """
263  device_info = self._entry_data_entry_data.device_info
264  if TYPE_CHECKING:
265  static_info = cast(_InfoT, static_info)
266  assert device_info
267  self._static_info_static_info = static_info
268  self._attr_unique_id_attr_unique_id = build_unique_id(device_info.mac_address, static_info)
269  self._attr_entity_registry_enabled_default_attr_entity_registry_enabled_default = not static_info.disabled_by_default
270  self._attr_name_attr_name = static_info.name
271  if entity_category := static_info.entity_category:
272  self._attr_entity_category_attr_entity_category = ENTITY_CATEGORIES.from_esphome(entity_category)
273  else:
274  self._attr_entity_category_attr_entity_category = None
275  if icon := static_info.icon:
276  self._attr_icon_attr_icon = cast(str, ICON_SCHEMA(icon))
277  else:
278  self._attr_icon_attr_icon = None
279 
280  @callback
281  def _update_state_from_entry_data(self) -> None:
282  """Update state from entry data."""
283  key = self._key_key
284  if has_state := key in self._states_states:
285  self._state_state = self._states_states[key]
286  self._has_state_has_state = has_state
287 
288  @callback
289  def _on_state_update(self) -> None:
290  """Call when state changed.
291 
292  Behavior can be changed in child classes
293  """
294  self._update_state_from_entry_data_update_state_from_entry_data()
295  self.async_write_ha_stateasync_write_ha_state()
296 
297  @callback
298  def _on_entry_data_changed(self) -> None:
299  entry_data = self._entry_data_entry_data
300  self._api_version_api_version = entry_data.api_version
301  self._client_client = entry_data.client
302  if self._device_info_device_info.has_deep_sleep:
303  # During deep sleep the ESP will not be connectable (by design)
304  # For these cases, show it as available
305  self._attr_available_attr_available = entry_data.expected_disconnect
306  else:
307  self._attr_available_attr_available = entry_data.available
308 
309  @callback
310  def _on_device_update(self) -> None:
311  """Call when device updates or entry data changes."""
312  self._on_entry_data_changed_on_entry_data_changed()
313  if not self._entry_data_entry_data.available:
314  # Only write state if the device has gone unavailable
315  # since _on_state_update will be called if the device
316  # is available when the full state arrives
317  # through the next entity state packet.
318  self.async_write_ha_stateasync_write_ha_state()
319 
320 
322  """Define a base entity for Assist Pipeline entities."""
323 
324  _attr_has_entity_name = True
325  _attr_should_poll = False
326 
327  def __init__(self, entry_data: RuntimeEntryData) -> None:
328  """Initialize the binary sensor."""
329  self._entry_data: RuntimeEntryData = entry_data
330  assert entry_data.device_info is not None
331  device_info = entry_data.device_info
332  self._device_info_device_info = device_info
333  self._attr_unique_id_attr_unique_id = (
334  f"{device_info.mac_address}-{self.entity_description.key}"
335  )
336  self._attr_device_info_attr_device_info = DeviceInfo(
337  connections={(dr.CONNECTION_NETWORK_MAC, device_info.mac_address)}
338  )
339 
340  async def async_added_to_hass(self) -> None:
341  """Register update callback."""
342  await super().async_added_to_hass()
343  self.async_on_removeasync_on_remove(
344  self._entry_data.async_subscribe_assist_pipeline_update(
345  self.async_write_ha_stateasync_write_ha_state
346  )
347  )
None __init__(self, RuntimeEntryData entry_data)
Definition: entity.py:327
None _on_static_info_update(self, EntityInfo static_info)
Definition: entity.py:257
None __init__(self, RuntimeEntryData entry_data, str domain, EntityInfo entity_info, type[_StateT] state_type)
Definition: entity.py:202
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None platform_async_setup_entry(HomeAssistant hass, ESPHomeConfigEntry entry, AddEntitiesCallback async_add_entities, *type[_InfoT] info_type, type[_EntityT] entity_type, type[_StateT] state_type)
Definition: entity.py:89
None async_static_info_updated(HomeAssistant hass, RuntimeEntryData entry_data, entity_platform.EntityPlatform platform, AddEntitiesCallback async_add_entities, type[_InfoT] info_type, type[_EntityT] entity_type, type[_StateT] state_type, list[EntityInfo] infos)
Definition: entity.py:48