Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for monitoring a Sense energy sensor device."""
2 
3 import logging
4 
5 from sense_energy.sense_api import SenseDevice
6 
8  BinarySensorDeviceClass,
9  BinarySensorEntity,
10 )
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers import entity_registry as er
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 
15 from . import SenseConfigEntry
16 from .const import DOMAIN
17 from .coordinator import SenseRealtimeCoordinator
18 from .entity import SenseDeviceEntity
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
24  hass: HomeAssistant,
25  config_entry: SenseConfigEntry,
26  async_add_entities: AddEntitiesCallback,
27 ) -> None:
28  """Set up the Sense binary sensor."""
29  sense_monitor_id = config_entry.runtime_data.data.sense_monitor_id
30  realtime_coordinator = config_entry.runtime_data.rt
31 
32  devices = [
33  SenseBinarySensor(device, realtime_coordinator, sense_monitor_id)
34  for device in config_entry.runtime_data.data.devices
35  ]
36 
37  await _migrate_old_unique_ids(hass, devices)
38 
39  async_add_entities(devices)
40 
41 
43  """Implementation of a Sense energy device binary sensor."""
44 
45  _attr_device_class = BinarySensorDeviceClass.POWER
46 
47  def __init__(
48  self,
49  device: SenseDevice,
50  coordinator: SenseRealtimeCoordinator,
51  sense_monitor_id: str,
52  ) -> None:
53  """Initialize the Sense binary sensor."""
54  super().__init__(device, coordinator, sense_monitor_id, device.id)
55  self._id_id = device.id
56 
57  @property
58  def old_unique_id(self) -> str:
59  """Return the old not so unique id of the binary sensor."""
60  return self._id_id
61 
62  @property
63  def is_on(self) -> bool:
64  """Return the state of the sensor."""
65  return self._device_device.is_on
66 
67 
69  hass: HomeAssistant, devices: list[SenseBinarySensor]
70 ) -> None:
71  registry = er.async_get(hass)
72  for device in devices:
73  # Migration of old not so unique ids
74  old_entity_id = registry.async_get_entity_id(
75  "binary_sensor", DOMAIN, device.old_unique_id
76  )
77  updated_id = device.unique_id
78  if old_entity_id is not None and updated_id is not None:
79  _LOGGER.debug(
80  "Migrating unique_id from [%s] to [%s]",
81  device.old_unique_id,
82  device.unique_id,
83  )
84  registry.async_update_entity(old_entity_id, new_unique_id=updated_id)
None __init__(self, SenseDevice device, SenseRealtimeCoordinator coordinator, str sense_monitor_id)
None async_setup_entry(HomeAssistant hass, SenseConfigEntry config_entry, AddEntitiesCallback async_add_entities)
None _migrate_old_unique_ids(HomeAssistant hass, list[SenseBinarySensor] devices)