Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for getting status from a Pi-hole system."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 from typing import Any
8 
9 from hole import Hole
10 
12  BinarySensorEntity,
13  BinarySensorEntityDescription,
14 )
15 from homeassistant.const import CONF_NAME
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
19 
20 from . import PiHoleConfigEntry
21 from .entity import PiHoleEntity
22 
23 
24 @dataclass(frozen=True, kw_only=True)
26  """Describes PiHole binary sensor entity."""
27 
28  state_value: Callable[[Hole], bool]
29  extra_value: Callable[[Hole], dict[str, Any] | None] = lambda api: None
30 
31 
32 BINARY_SENSOR_TYPES: tuple[PiHoleBinarySensorEntityDescription, ...] = (
34  key="status",
35  translation_key="status",
36  state_value=lambda api: bool(api.data.get("status") == "enabled"),
37  ),
38 )
39 
40 
42  hass: HomeAssistant,
43  entry: PiHoleConfigEntry,
44  async_add_entities: AddEntitiesCallback,
45 ) -> None:
46  """Set up the Pi-hole binary sensor."""
47  name = entry.data[CONF_NAME]
48  hole_data = entry.runtime_data
49 
50  binary_sensors = [
52  hole_data.api,
53  hole_data.coordinator,
54  name,
55  entry.entry_id,
56  description,
57  )
58  for description in BINARY_SENSOR_TYPES
59  ]
60 
61  async_add_entities(binary_sensors, True)
62 
63 
65  """Representation of a Pi-hole binary sensor."""
66 
67  entity_description: PiHoleBinarySensorEntityDescription
68  _attr_has_entity_name = True
69 
70  def __init__(
71  self,
72  api: Hole,
73  coordinator: DataUpdateCoordinator[None],
74  name: str,
75  server_unique_id: str,
76  description: PiHoleBinarySensorEntityDescription,
77  ) -> None:
78  """Initialize a Pi-hole sensor."""
79  super().__init__(api, coordinator, name, server_unique_id)
80  self.entity_descriptionentity_description = description
81  self._attr_unique_id_attr_unique_id = f"{self._server_unique_id}/{description.key}"
82 
83  @property
84  def is_on(self) -> bool:
85  """Return if the service is on."""
86 
87  return self.entity_descriptionentity_description.state_value(self.apiapi)
88 
89  @property
90  def extra_state_attributes(self) -> dict[str, Any] | None:
91  """Return the state attributes of the Pi-hole."""
92  return self.entity_descriptionentity_description.extra_value(self.apiapi)
None __init__(self, Hole api, DataUpdateCoordinator[None] coordinator, str name, str server_unique_id, PiHoleBinarySensorEntityDescription description)
None async_setup_entry(HomeAssistant hass, PiHoleConfigEntry entry, AddEntitiesCallback async_add_entities)