Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Binary sensor platform integration for Numato USB GPIO expanders."""
2 
3 from __future__ import annotations
4 
5 from functools import partial
6 import logging
7 
8 from numato_gpio import NumatoGpioError
9 
10 from homeassistant.components.binary_sensor import BinarySensorEntity
11 from homeassistant.const import DEVICE_DEFAULT_NAME
12 from homeassistant.core import HomeAssistant, callback
13 from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
16 
17 from . import (
18  CONF_BINARY_SENSORS,
19  CONF_DEVICES,
20  CONF_ID,
21  CONF_INVERT_LOGIC,
22  CONF_PORTS,
23  DATA_API,
24  DOMAIN,
25 )
26 
27 _LOGGER = logging.getLogger(__name__)
28 
29 NUMATO_SIGNAL = "numato_signal_{}_{}"
30 
31 
33  hass: HomeAssistant,
34  config: ConfigType,
35  add_entities: AddEntitiesCallback,
36  discovery_info: DiscoveryInfoType | None = None,
37 ) -> None:
38  """Set up the configured Numato USB GPIO binary sensor ports."""
39  if discovery_info is None:
40  return
41 
42  def read_gpio(device_id: int, port: int, level: bool) -> None:
43  """Send signal to entity to have it update state."""
44  dispatcher_send(hass, NUMATO_SIGNAL.format(device_id, port), level)
45 
46  api = hass.data[DOMAIN][DATA_API]
47  binary_sensors = []
48  devices = hass.data[DOMAIN][CONF_DEVICES]
49  for device in [d for d in devices if CONF_BINARY_SENSORS in d]:
50  device_id = device[CONF_ID]
51  platform = device[CONF_BINARY_SENSORS]
52  invert_logic = platform[CONF_INVERT_LOGIC]
53  ports = platform[CONF_PORTS]
54  for port, port_name in ports.items():
55  try:
56  api.setup_input(device_id, port)
57 
58  except NumatoGpioError as err:
59  _LOGGER.error(
60  (
61  "Failed to initialize binary sensor '%s' on Numato device %s"
62  " port %s: %s"
63  ),
64  port_name,
65  device_id,
66  port,
67  err,
68  )
69  continue
70  try:
71  api.edge_detect(device_id, port, partial(read_gpio, device_id))
72 
73  except NumatoGpioError as err:
74  _LOGGER.error(
75  "Notification setup failed on device %s, "
76  "updates on binary sensor %s only in polling mode: %s",
77  device_id,
78  port_name,
79  err,
80  )
81  binary_sensors.append(
83  port_name,
84  device_id,
85  port,
86  invert_logic,
87  api,
88  )
89  )
90  add_entities(binary_sensors, True)
91 
92 
94  """Represents a binary sensor (input) port of a Numato GPIO expander."""
95 
96  _attr_should_poll = False
97 
98  def __init__(self, name, device_id, port, invert_logic, api):
99  """Initialize the Numato GPIO based binary sensor object."""
100  self._attr_name_attr_name = name or DEVICE_DEFAULT_NAME
101  self._device_id_device_id = device_id
102  self._port_port = port
103  self._invert_logic_invert_logic = invert_logic
104  self._state_state = None
105  self._api_api = api
106 
107  async def async_added_to_hass(self) -> None:
108  """Connect state update callback."""
109  self.async_on_removeasync_on_remove(
111  self.hasshass,
112  NUMATO_SIGNAL.format(self._device_id_device_id, self._port_port),
113  self._async_update_state_async_update_state,
114  )
115  )
116 
117  @callback
118  def _async_update_state(self, level):
119  """Update entity state."""
120  self._state_state = level
121  self.async_write_ha_stateasync_write_ha_state()
122 
123  @property
124  def is_on(self):
125  """Return the state of the entity."""
126  return self._state_state != self._invert_logic_invert_logic
127 
128  def update(self) -> None:
129  """Update the GPIO state."""
130  try:
131  self._state_state = self._api_api.read_input(self._device_id_device_id, self._port_port)
132  except NumatoGpioError as err:
133  self._state_state = None
134  _LOGGER.error(
135  "Failed to update Numato device %s port %s: %s",
136  self._device_id_device_id,
137  self._port_port,
138  err,
139  )
def __init__(self, name, device_id, port, invert_logic, api)
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103
None dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:137