Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Platform for Schlage sensor integration."""
2 
3 from __future__ import annotations
4 
6  SensorDeviceClass,
7  SensorEntity,
8  SensorEntityDescription,
9  SensorStateClass,
10 )
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import PERCENTAGE, EntityCategory
13 from homeassistant.core import HomeAssistant, callback
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from .const import DOMAIN
17 from .coordinator import LockData, SchlageDataUpdateCoordinator
18 from .entity import SchlageEntity
19 
20 _SENSOR_DESCRIPTIONS: list[SensorEntityDescription] = [
22  key="battery_level",
23  device_class=SensorDeviceClass.BATTERY,
24  entity_category=EntityCategory.DIAGNOSTIC,
25  native_unit_of_measurement=PERCENTAGE,
26  state_class=SensorStateClass.MEASUREMENT,
27  ),
28 ]
29 
30 
32  hass: HomeAssistant,
33  config_entry: ConfigEntry,
34  async_add_entities: AddEntitiesCallback,
35 ) -> None:
36  """Set up sensors based on a config entry."""
37  coordinator: SchlageDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
38 
39  def _add_new_locks(locks: dict[str, LockData]) -> None:
42  coordinator=coordinator,
43  description=description,
44  device_id=device_id,
45  )
46  for description in _SENSOR_DESCRIPTIONS
47  for device_id in locks
48  )
49 
50  _add_new_locks(coordinator.data.locks)
51  coordinator.new_locks_callbacks.append(_add_new_locks)
52 
53 
55  """Schlage battery sensor entity."""
56 
57  def __init__(
58  self,
59  coordinator: SchlageDataUpdateCoordinator,
60  description: SensorEntityDescription,
61  device_id: str,
62  ) -> None:
63  """Initialize a Schlage battery sensor."""
64  super().__init__(coordinator=coordinator, device_id=device_id)
65  self.entity_descriptionentity_description = description
66  self._attr_unique_id_attr_unique_id_attr_unique_id = f"{device_id}_{description.key}"
67  self._attr_native_value_attr_native_value = getattr(self._lock_lock, self.entity_descriptionentity_description.key)
68 
69  @callback
70  def _handle_coordinator_update(self) -> None:
71  """Handle updated data from the coordinator."""
72  if self.device_iddevice_id in self.coordinator.data.locks:
73  self._attr_native_value_attr_native_value = getattr(self._lock_lock, self.entity_descriptionentity_description.key)
None __init__(self, SchlageDataUpdateCoordinator coordinator, SensorEntityDescription description, str device_id)
Definition: sensor.py:62
None _add_new_locks(dict[str, LockData] locks)
Definition: sensor.py:39
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:35