Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Support for The Things Network entities."""
2 
3 import logging
4 
5 from ttn_client import TTNBaseValue
6 
7 from homeassistant.core import callback
8 from homeassistant.helpers.device_registry import DeviceInfo
9 from homeassistant.helpers.update_coordinator import CoordinatorEntity
10 
11 from .const import DOMAIN
12 from .coordinator import TTNCoordinator
13 
14 _LOGGER = logging.getLogger(__name__)
15 
16 
17 class TTNEntity(CoordinatorEntity[TTNCoordinator]):
18  """Representation of a The Things Network Data Storage sensor."""
19 
20  _attr_has_entity_name = True
21  _ttn_value: TTNBaseValue
22 
23  def __init__(
24  self,
25  coordinator: TTNCoordinator,
26  app_id: str,
27  ttn_value: TTNBaseValue,
28  ) -> None:
29  """Initialize a The Things Network Data Storage sensor."""
30 
31  # Pass coordinator to CoordinatorEntity
32  super().__init__(coordinator)
33 
34  self._ttn_value_ttn_value = ttn_value
35 
36  self._attr_unique_id_attr_unique_id = f"{self.device_id}_{self.field_id}"
37  self._attr_name_attr_name = self.field_idfield_id
38 
39  self._attr_device_info_attr_device_info = DeviceInfo(
40  identifiers={(DOMAIN, f"{app_id}_{self.device_id}")},
41  name=self.device_iddevice_id,
42  )
43 
44  @callback
45  def _handle_coordinator_update(self) -> None:
46  """Handle updated data from the coordinator."""
47 
48  my_entity_update = self.coordinator.data.get(self.device_iddevice_id, {}).get(
49  self.field_idfield_id
50  )
51  if (
52  my_entity_update
53  and my_entity_update.received_at > self._ttn_value_ttn_value.received_at
54  ):
55  _LOGGER.debug(
56  "Received update for %s: %s", self.unique_id, my_entity_update
57  )
58  # Check that the type of an entity has not changed since the creation
59  assert isinstance(my_entity_update, type(self._ttn_value_ttn_value))
60  self._ttn_value_ttn_value = my_entity_update
61  self.async_write_ha_state()
62 
63  @property
64  def device_id(self) -> str:
65  """Return device_id."""
66  return str(self._ttn_value_ttn_value.device_id)
67 
68  @property
69  def field_id(self) -> str:
70  """Return field_id."""
71  return str(self._ttn_value_ttn_value.field_id)
None __init__(self, TTNCoordinator coordinator, str app_id, TTNBaseValue ttn_value)
Definition: entity.py:28
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88