Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """The Things Network's integration sensors."""
2 
3 import logging
4 
5 from ttn_client import TTNSensorValue
6 
7 from homeassistant.components.sensor import SensorEntity
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.core import HomeAssistant
10 from homeassistant.helpers.entity_platform import AddEntitiesCallback
11 from homeassistant.helpers.typing import StateType
12 
13 from .const import CONF_APP_ID, DOMAIN
14 from .entity import TTNEntity
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 
20  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
21 ) -> None:
22  """Add entities for TTN."""
23 
24  coordinator = hass.data[DOMAIN][entry.entry_id]
25 
26  sensors: set[tuple[str, str]] = set()
27 
28  def _async_measurement_listener() -> None:
29  data = coordinator.data
30  new_sensors = {
31  (device_id, field_id): TtnDataSensor(
32  coordinator,
33  entry.data[CONF_APP_ID],
34  ttn_value,
35  )
36  for device_id, device_uplinks in data.items()
37  for field_id, ttn_value in device_uplinks.items()
38  if (device_id, field_id) not in sensors
39  and isinstance(ttn_value, TTNSensorValue)
40  }
41  if len(new_sensors):
42  async_add_entities(new_sensors.values())
43  sensors.update(new_sensors.keys())
44 
45  entry.async_on_unload(coordinator.async_add_listener(_async_measurement_listener))
46  _async_measurement_listener()
47 
48 
50  """Represents a TTN Home Assistant Sensor."""
51 
52  _ttn_value: TTNSensorValue
53 
54  @property
55  def native_value(self) -> StateType:
56  """Return the state of the entity."""
57  return self._ttn_value_ttn_value.value
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:21