Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for DHT and DS18B20 sensors attached to a Konnected device."""
2 
3 from __future__ import annotations
4 
6  SensorDeviceClass,
7  SensorEntity,
8  SensorEntityDescription,
9 )
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import (
12  CONF_DEVICES,
13  CONF_NAME,
14  CONF_SENSORS,
15  CONF_TYPE,
16  CONF_ZONE,
17  PERCENTAGE,
18  UnitOfTemperature,
19 )
20 from homeassistant.core import HomeAssistant, callback
21 from homeassistant.helpers.device_registry import DeviceInfo
22 from homeassistant.helpers.dispatcher import async_dispatcher_connect
23 from homeassistant.helpers.entity_platform import AddEntitiesCallback
24 
25 from .const import DOMAIN as KONNECTED_DOMAIN, SIGNAL_DS18B20_NEW
26 
27 SENSOR_TYPES: dict[str, SensorEntityDescription] = {
28  "temperature": SensorEntityDescription(
29  key="temperature",
30  name="Temperature",
31  native_unit_of_measurement=UnitOfTemperature.CELSIUS,
32  device_class=SensorDeviceClass.TEMPERATURE,
33  ),
34  "humidity": SensorEntityDescription(
35  key="humidity",
36  name="Humidity",
37  native_unit_of_measurement=PERCENTAGE,
38  device_class=SensorDeviceClass.HUMIDITY,
39  ),
40 }
41 
42 
44  hass: HomeAssistant,
45  config_entry: ConfigEntry,
46  async_add_entities: AddEntitiesCallback,
47 ) -> None:
48  """Set up sensors attached to a Konnected device from a config entry."""
49  data = hass.data[KONNECTED_DOMAIN]
50  device_id = config_entry.data["id"]
51 
52  # Initialize all DHT sensors.
53  dht_sensors = [
54  sensor
55  for sensor in data[CONF_DEVICES][device_id][CONF_SENSORS]
56  if sensor[CONF_TYPE] == "dht"
57  ]
58  entities = [
59  KonnectedSensor(device_id, data=sensor_config, description=description)
60  for sensor_config in dht_sensors
61  for description in SENSOR_TYPES.values()
62  ]
63 
64  async_add_entities(entities)
65 
66  @callback
67  def async_add_ds18b20(attrs):
68  """Add new KonnectedSensor representing a ds18b20 sensor."""
69  sensor_config = next(
70  (
71  s
72  for s in data[CONF_DEVICES][device_id][CONF_SENSORS]
73  if s[CONF_TYPE] == "ds18b20" and s[CONF_ZONE] == attrs.get(CONF_ZONE)
74  ),
75  None,
76  )
77 
79  [
81  device_id,
82  sensor_config,
83  SENSOR_TYPES["temperature"],
84  addr=attrs.get("addr"),
85  initial_state=attrs.get("temp"),
86  )
87  ],
88  True,
89  )
90 
91  # DS18B20 sensors entities are initialized when they report for the first
92  # time. Set up a listener for that signal from the Konnected component.
93  async_dispatcher_connect(hass, SIGNAL_DS18B20_NEW, async_add_ds18b20)
94 
95 
97  """Represents a Konnected DHT Sensor."""
98 
99  def __init__(
100  self,
101  device_id,
102  data,
103  description: SensorEntityDescription,
104  addr=None,
105  initial_state=None,
106  ) -> None:
107  """Initialize the entity for a single sensor_type."""
108  self.entity_descriptionentity_description = description
109  self._addr_addr = addr
110  self._data_data = data
111  self._zone_num_zone_num = self._data_data.get(CONF_ZONE)
112  self._attr_unique_id_attr_unique_id = addr or f"{device_id}-{self._zone_num}-{description.key}"
113 
114  # set initial state if known at initialization
115  self._attr_native_value_attr_native_value = initial_state
116  if initial_state:
117  self._attr_native_value_attr_native_value = round(float(initial_state), 1)
118 
119  # set entity name if given
120  if name := self._data_data.get(CONF_NAME):
121  name += f" {description.name}"
122  self._attr_name_attr_name = name
123 
124  self._attr_device_info_attr_device_info = DeviceInfo(identifiers={(KONNECTED_DOMAIN, device_id)})
125 
126  async def async_added_to_hass(self) -> None:
127  """Store entity_id and register state change callback."""
128  entity_id_key = self._addr_addr or self.entity_descriptionentity_description.key
129  self._data_data[entity_id_key] = self.entity_identity_id
131  self.hasshass, f"konnected.{self.entity_id}.update", self.async_set_stateasync_set_state
132  )
133 
134  @callback
135  def async_set_state(self, state):
136  """Update the sensor's state."""
137  if self.entity_descriptionentity_description.key == "humidity":
138  self._attr_native_value_attr_native_value = int(float(state))
139  else:
140  self._attr_native_value_attr_native_value = round(float(state), 1)
141  self.async_write_ha_stateasync_write_ha_state()
None __init__(self, device_id, data, SensorEntityDescription description, addr=None, initial_state=None)
Definition: sensor.py:106
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:47
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103