Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Qwikswitch Sensors."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from pyqwikswitch.qwikswitch import SENSORS
9 
10 from homeassistant.components.sensor import SensorEntity
11 from homeassistant.core import HomeAssistant, callback
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
14 
15 from . import DOMAIN as QWIKSWITCH
16 from .entity import QSEntity
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
22  hass: HomeAssistant,
23  _: ConfigType,
24  add_entities: AddEntitiesCallback,
25  discovery_info: DiscoveryInfoType | None = None,
26 ) -> None:
27  """Add sensor from the main Qwikswitch component."""
28  if discovery_info is None:
29  return
30 
31  qsusb = hass.data[QWIKSWITCH]
32  _LOGGER.debug("Setup qwikswitch.sensor %s, %s", qsusb, discovery_info)
33  devs = [QSSensor(sensor) for sensor in discovery_info[QWIKSWITCH]]
34  add_entities(devs)
35 
36 
38  """Sensor based on a Qwikswitch relay/dimmer module."""
39 
40  _val: Any | None = None
41 
42  def __init__(self, sensor):
43  """Initialize the sensor."""
44 
45  super().__init__(sensor["id"], sensor["name"])
46  self.channelchannel = sensor["channel"]
47  sensor_type = sensor["type"]
48 
49  self._decode, self.unitunit = SENSORS[sensor_type]
50  # this cannot happen because it only happens in bool and this should be redirected to binary_sensor
51  assert not isinstance(
52  self.unitunit, type
53  ), f"boolean sensor id={sensor['id']} name={sensor['name']}"
54 
55  @callback
56  def update_packet(self, packet):
57  """Receive update packet from QSUSB."""
58  val = self._decode(packet, channel=self.channelchannel)
59  _LOGGER.debug(
60  "Update %s (%s:%s) decoded as %s: %s",
61  self.entity_identity_id,
62  self.qsidqsid,
63  self.channelchannel,
64  val,
65  packet,
66  )
67  if val is not None:
68  self._val_val = val
69  self.async_write_ha_stateasync_write_ha_state()
70 
71  @property
72  def native_value(self):
73  """Return the value of the sensor."""
74  return None if self._val_val is None else str(self._val_val)
75 
76  @property
77  def unique_id(self):
78  """Return a unique identifier for this sensor."""
79  return f"qs{self.qsid}:{self.channel}"
80 
81  @property
83  """Return the unit the value is expressed in."""
84  return self.unitunit
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None async_setup_platform(HomeAssistant hass, ConfigType _, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:26