Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for UPnP/IGD Binary Sensors."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 
8  BinarySensorDeviceClass,
9  BinarySensorEntity,
10  BinarySensorEntityDescription,
11 )
12 from homeassistant.const import EntityCategory
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from . import UpnpConfigEntry, UpnpDataUpdateCoordinator
17 from .const import LOGGER, WAN_STATUS
18 from .entity import UpnpEntity, UpnpEntityDescription
19 
20 
21 @dataclass(frozen=True)
23  UpnpEntityDescription, BinarySensorEntityDescription
24 ):
25  """A class that describes binary sensor UPnP entities."""
26 
27 
28 SENSOR_DESCRIPTIONS: tuple[UpnpBinarySensorEntityDescription, ...] = (
30  key=WAN_STATUS,
31  translation_key="wan_status",
32  device_class=BinarySensorDeviceClass.CONNECTIVITY,
33  entity_category=EntityCategory.DIAGNOSTIC,
34  ),
35 )
36 
37 
39  hass: HomeAssistant,
40  config_entry: UpnpConfigEntry,
41  async_add_entities: AddEntitiesCallback,
42 ) -> None:
43  """Set up the UPnP/IGD sensors."""
44  coordinator = config_entry.runtime_data
45 
46  entities = [
48  coordinator=coordinator,
49  entity_description=entity_description,
50  )
51  for entity_description in SENSOR_DESCRIPTIONS
52  if coordinator.data.get(entity_description.key) is not None
53  ]
54  async_add_entities(entities)
55  LOGGER.debug("Added binary_sensor entities: %s", entities)
56 
57 
59  """Class for UPnP/IGD binary sensors."""
60 
61  entity_description: UpnpBinarySensorEntityDescription
62 
63  def __init__(
64  self,
65  coordinator: UpnpDataUpdateCoordinator,
66  entity_description: UpnpBinarySensorEntityDescription,
67  ) -> None:
68  """Initialize the base sensor."""
69  super().__init__(coordinator=coordinator, entity_description=entity_description)
70 
71  @property
72  def is_on(self) -> bool:
73  """Return true if the binary sensor is on."""
74  return self.coordinator.data[self.entity_descriptionentity_description.key] == "Connected"
75 
76  async def async_added_to_hass(self) -> None:
77  """Subscribe to updates."""
78  await super().async_added_to_hass()
79 
80  # Register self at coordinator.
81  key = self.entity_descriptionentity_description.key
82  entity_id = self.entity_identity_id
83  unregister = self.coordinator.register_entity(key, entity_id)
84  self.async_on_removeasync_on_remove(unregister)
None __init__(self, UpnpDataUpdateCoordinator coordinator, UpnpBinarySensorEntityDescription entity_description)
Callable[[], None] register_entity(self, str key, str entity_id)
Definition: coordinator.py:41
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_entry(HomeAssistant hass, UpnpConfigEntry config_entry, AddEntitiesCallback async_add_entities)