Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for wired binary sensors attached to a Konnected device."""
2 
3 from homeassistant.components.binary_sensor import BinarySensorEntity
4 from homeassistant.config_entries import ConfigEntry
5 from homeassistant.const import (
6  ATTR_ENTITY_ID,
7  ATTR_STATE,
8  CONF_BINARY_SENSORS,
9  CONF_DEVICES,
10  CONF_NAME,
11  CONF_TYPE,
12 )
13 from homeassistant.core import HomeAssistant, callback
14 from homeassistant.helpers.device_registry import DeviceInfo
15 from homeassistant.helpers.dispatcher import async_dispatcher_connect
16 from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 
18 from .const import DOMAIN as KONNECTED_DOMAIN
19 
20 
22  hass: HomeAssistant,
23  config_entry: ConfigEntry,
24  async_add_entities: AddEntitiesCallback,
25 ) -> None:
26  """Set up binary sensors attached to a Konnected device from a config entry."""
27  data = hass.data[KONNECTED_DOMAIN]
28  device_id = config_entry.data["id"]
29  sensors = [
30  KonnectedBinarySensor(device_id, pin_num, pin_data)
31  for pin_num, pin_data in data[CONF_DEVICES][device_id][
32  CONF_BINARY_SENSORS
33  ].items()
34  ]
35  async_add_entities(sensors)
36 
37 
39  """Representation of a Konnected binary sensor."""
40 
41  _attr_should_poll = False
42 
43  def __init__(self, device_id, zone_num, data):
44  """Initialize the Konnected binary sensor."""
45  self._data_data = data
46  self._attr_is_on_attr_is_on = data.get(ATTR_STATE)
47  self._attr_device_class_attr_device_class = data.get(CONF_TYPE)
48  self._attr_unique_id_attr_unique_id = f"{device_id}-{zone_num}"
49  self._attr_name_attr_name = data.get(CONF_NAME)
50  self._attr_device_info_attr_device_info = DeviceInfo(
51  identifiers={(KONNECTED_DOMAIN, device_id)},
52  )
53 
54  async def async_added_to_hass(self) -> None:
55  """Store entity_id and register state change callback."""
56  self._data_data[ATTR_ENTITY_ID] = self.entity_identity_id
57  self.async_on_removeasync_on_remove(
59  self.hasshass, f"konnected.{self.entity_id}.update", self.async_set_stateasync_set_state
60  )
61  )
62 
63  @callback
64  def async_set_state(self, state):
65  """Update the sensor's state."""
66  self._attr_is_on_attr_is_on = state
67  self.async_write_ha_stateasync_write_ha_state()
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103