Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for Ecowitt Weather Stations."""
2 
3 import dataclasses
4 from typing import Final
5 
6 from aioecowitt import EcoWittSensor, EcoWittSensorTypes
7 
9  BinarySensorDeviceClass,
10  BinarySensorEntity,
11  BinarySensorEntityDescription,
12 )
13 from homeassistant.const import EntityCategory
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers.entity_platform import AddEntitiesCallback
16 
17 from . import EcowittConfigEntry
18 from .entity import EcowittEntity
19 
20 ECOWITT_BINARYSENSORS_MAPPING: Final = {
21  EcoWittSensorTypes.LEAK: BinarySensorEntityDescription(
22  key="LEAK", device_class=BinarySensorDeviceClass.MOISTURE
23  ),
24  EcoWittSensorTypes.BATTERY_BINARY: BinarySensorEntityDescription(
25  key="BATTERY",
26  device_class=BinarySensorDeviceClass.BATTERY,
27  entity_category=EntityCategory.DIAGNOSTIC,
28  ),
29 }
30 
31 
33  hass: HomeAssistant,
34  entry: EcowittConfigEntry,
35  async_add_entities: AddEntitiesCallback,
36 ) -> None:
37  """Add sensors if new."""
38  ecowitt = entry.runtime_data
39 
40  def _new_sensor(sensor: EcoWittSensor) -> None:
41  """Add new sensor."""
42  if sensor.stype not in ECOWITT_BINARYSENSORS_MAPPING:
43  return
44  mapping = ECOWITT_BINARYSENSORS_MAPPING[sensor.stype]
45 
46  # Setup sensor description
47  description = dataclasses.replace(
48  mapping,
49  key=sensor.key,
50  name=sensor.name,
51  )
52 
53  async_add_entities([EcowittBinarySensorEntity(sensor, description)])
54 
55  ecowitt.new_sensor_cb.append(_new_sensor)
56  entry.async_on_unload(lambda: ecowitt.new_sensor_cb.remove(_new_sensor))
57 
58  # Add all sensors that are already known
59  for sensor in ecowitt.sensors.values():
60  _new_sensor(sensor)
61 
62 
64  """Representation of a Ecowitt BinarySensor."""
65 
66  def __init__(
67  self, sensor: EcoWittSensor, description: BinarySensorEntityDescription
68  ) -> None:
69  """Initialize the sensor."""
70  super().__init__(sensor)
71  self.entity_descriptionentity_description = description
72 
73  @property
74  def is_on(self) -> bool:
75  """Return true if the binary sensor is on."""
76  return bool(self.ecowitt.value)
None __init__(self, EcoWittSensor sensor, BinarySensorEntityDescription description)
None async_setup_entry(HomeAssistant hass, EcowittConfigEntry entry, AddEntitiesCallback async_add_entities)