Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """WiZ integration binary sensor platform."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 
7 from pywizlight.bulb import PIR_SOURCE
8 
10  BinarySensorDeviceClass,
11  BinarySensorEntity,
12 )
13 from homeassistant.const import Platform
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.helpers import entity_registry as er
16 from homeassistant.helpers.dispatcher import async_dispatcher_connect
17 from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 
19 from . import WizConfigEntry
20 from .const import DOMAIN, SIGNAL_WIZ_PIR
21 from .entity import WizEntity
22 from .models import WizData
23 
24 OCCUPANCY_UNIQUE_ID = "{}_occupancy"
25 
26 
28  hass: HomeAssistant,
29  entry: WizConfigEntry,
30  async_add_entities: AddEntitiesCallback,
31 ) -> None:
32  """Set up the WiZ binary sensor platform."""
33  mac = entry.runtime_data.bulb.mac
34 
35  if er.async_get(hass).async_get_entity_id(
36  Platform.BINARY_SENSOR, DOMAIN, OCCUPANCY_UNIQUE_ID.format(mac)
37  ):
38  async_add_entities([WizOccupancyEntity(entry.runtime_data, entry.title)])
39  return
40 
41  cancel_dispatcher: Callable[[], None] | None = None
42 
43  @callback
44  def _async_add_occupancy_sensor() -> None:
45  nonlocal cancel_dispatcher
46  assert cancel_dispatcher is not None
47  cancel_dispatcher()
48  cancel_dispatcher = None
49  async_add_entities([WizOccupancyEntity(entry.runtime_data, entry.title)])
50 
51  cancel_dispatcher = async_dispatcher_connect(
52  hass, SIGNAL_WIZ_PIR.format(mac), _async_add_occupancy_sensor
53  )
54 
55  @callback
56  def _async_cancel_dispatcher() -> None:
57  nonlocal cancel_dispatcher
58  if cancel_dispatcher is not None:
59  cancel_dispatcher()
60  cancel_dispatcher = None
61 
62  entry.async_on_unload(_async_cancel_dispatcher)
63 
64 
66  """Representation of WiZ Occupancy sensor."""
67 
68  _attr_device_class = BinarySensorDeviceClass.OCCUPANCY
69 
70  def __init__(self, wiz_data: WizData, name: str) -> None:
71  """Initialize an WiZ device."""
72  super().__init__(wiz_data, name)
73  self._attr_unique_id_attr_unique_id_attr_unique_id = OCCUPANCY_UNIQUE_ID.format(self._device_device.mac)
74  self._async_update_attrs_async_update_attrs_async_update_attrs()
75 
76  @callback
77  def _async_update_attrs(self) -> None:
78  """Handle updating _attr values."""
79  if self._device_device.state.get_source() == PIR_SOURCE:
80  self._attr_is_on_attr_is_on = self._device_device.status
None async_setup_entry(HomeAssistant hass, WizConfigEntry entry, AddEntitiesCallback async_add_entities)
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103