Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for tracking the online status of a UPS."""
2 
3 from __future__ import annotations
4 
5 from typing import Final
6 
8  BinarySensorEntity,
9  BinarySensorEntityDescription,
10 )
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 from homeassistant.helpers.update_coordinator import CoordinatorEntity
14 
15 from . import APCUPSdConfigEntry
16 from .coordinator import APCUPSdCoordinator
17 
18 PARALLEL_UPDATES = 0
19 
21  key="statflag",
22  translation_key="online_status",
23 )
24 # The bit in STATFLAG that indicates the online status of the APC UPS.
25 _VALUE_ONLINE_MASK: Final = 0b1000
26 
27 
29  hass: HomeAssistant,
30  config_entry: APCUPSdConfigEntry,
31  async_add_entities: AddEntitiesCallback,
32 ) -> None:
33  """Set up an APCUPSd Online Status binary sensor."""
34  coordinator = config_entry.runtime_data
35 
36  # Do not create the binary sensor if APCUPSd does not provide STATFLAG field for us
37  # to determine the online status.
38  if _DESCRIPTION.key.upper() not in coordinator.data:
39  return
40 
41  async_add_entities([OnlineStatus(coordinator, _DESCRIPTION)])
42 
43 
44 class OnlineStatus(CoordinatorEntity[APCUPSdCoordinator], BinarySensorEntity):
45  """Representation of a UPS online status."""
46 
47  _attr_has_entity_name = True
48 
49  def __init__(
50  self,
51  coordinator: APCUPSdCoordinator,
52  description: BinarySensorEntityDescription,
53  ) -> None:
54  """Initialize the APCUPSd binary device."""
55  super().__init__(coordinator, context=description.key.upper())
56 
57  # Set up unique id and device info if serial number is available.
58  if (serial_no := coordinator.data.serial_no) is not None:
59  self._attr_unique_id_attr_unique_id = f"{serial_no}_{description.key}"
60  self.entity_descriptionentity_description = description
61  self._attr_device_info_attr_device_info = coordinator.device_info
62 
63  @property
64  def is_on(self) -> bool | None:
65  """Returns true if the UPS is online."""
66  # Check if ONLINE bit is set in STATFLAG.
67  key = self.entity_descriptionentity_description.key.upper()
68  # The daemon could either report just a hex ("0x05000008"), or a hex with a "Status Flag"
69  # suffix ("0x05000008 Status Flag") in older versions.
70  # Here we trim the suffix if it exists to support both.
71  flag = self.coordinator.data[key].removesuffix(" Status Flag")
72  return int(flag, 16) & _VALUE_ONLINE_MASK != 0
None __init__(self, APCUPSdCoordinator coordinator, BinarySensorEntityDescription description)
None async_setup_entry(HomeAssistant hass, APCUPSdConfigEntry config_entry, AddEntitiesCallback async_add_entities)