Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Sensors on Zigbee Home Automation networks."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import functools
7 import logging
8 from typing import Any
9 
11  SensorDeviceClass,
12  SensorEntity,
13  SensorStateClass,
14 )
15 from homeassistant.config_entries import ConfigEntry
16 from homeassistant.const import Platform
17 from homeassistant.core import HomeAssistant
18 from homeassistant.helpers.dispatcher import async_dispatcher_connect
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import StateType
21 
22 from .entity import ZHAEntity
23 from .helpers import (
24  SIGNAL_ADD_ENTITIES,
25  EntityData,
26  async_add_entities as zha_async_add_entities,
27  exclude_none_values,
28  get_zha_data,
29 )
30 
31 _LOGGER = logging.getLogger(__name__)
32 
33 # For backwards compatibility and transparency, all expected extra state attributes are
34 # explicitly listed below. These should have been sensors themselves but for whatever
35 # reason were not created as such. They will be migrated to independent sensor entities
36 # in a future release.
37 _EXTRA_STATE_ATTRIBUTES: set[str] = {
38  # Battery
39  "battery_size",
40  "battery_quantity",
41  "battery_voltage",
42  # Power
43  "measurement_type",
44  "apparent_power_max",
45  "rms_current_max",
46  "rms_voltage_max",
47  "ac_frequency_max",
48  "power_factor_max",
49  "active_power_max",
50  # Smart Energy metering
51  "device_type",
52  "status",
53  "zcl_unit_of_measurement",
54  # Danfoss bitmaps
55  "In_progress",
56  "Valve_characteristic_found",
57  "Valve_characteristic_lost",
58  "Top_pcb_sensor_error",
59  "Side_pcb_sensor_error",
60  "Non_volatile_memory_error",
61  "Unknown_hw_error",
62  "Motor_error",
63  "Invalid_internal_communication",
64  "Invalid_clock_information",
65  "Radio_communication_error",
66  "Encoder_jammed",
67  "Low_battery",
68  "Critical_low_battery",
69 }
70 
71 
73  hass: HomeAssistant,
74  config_entry: ConfigEntry,
75  async_add_entities: AddEntitiesCallback,
76 ) -> None:
77  """Set up the Zigbee Home Automation sensor from config entry."""
78  zha_data = get_zha_data(hass)
79  entities_to_create = zha_data.platforms[Platform.SENSOR]
80 
82  hass,
83  SIGNAL_ADD_ENTITIES,
84  functools.partial(
85  zha_async_add_entities, async_add_entities, Sensor, entities_to_create
86  ),
87  )
88  config_entry.async_on_unload(unsub)
89 
90 
91 # pylint: disable-next=hass-invalid-inheritance # needs fixing
93  """ZHA sensor."""
94 
95  def __init__(self, entity_data: EntityData, **kwargs: Any) -> None:
96  """Initialize the ZHA select entity."""
97  super().__init__(entity_data, **kwargs)
98  entity = self.entity_data.entity
99 
100  if entity.device_class is not None:
101  self._attr_device_class_attr_device_class = SensorDeviceClass(entity.device_class)
102 
103  if entity.state_class is not None:
104  self._attr_state_class_attr_state_class = SensorStateClass(entity.state_class)
105 
106  if hasattr(entity.info_object, "unit") and entity.info_object.unit is not None:
107  self._attr_native_unit_of_measurement_attr_native_unit_of_measurement = entity.info_object.unit
108 
109  if (
110  hasattr(entity, "entity_description")
111  and entity.entity_description is not None
112  ):
113  entity_description = entity.entity_description
114 
115  if entity_description.state_class is not None:
116  self._attr_state_class_attr_state_class = SensorStateClass(
117  entity_description.state_class.value
118  )
119 
120  if entity_description.scale is not None:
121  self._attr_scale_attr_scale = entity_description.scale
122 
123  if entity_description.native_unit_of_measurement is not None:
124  self._attr_native_unit_of_measurement_attr_native_unit_of_measurement = (
125  entity_description.native_unit_of_measurement
126  )
127 
128  if entity_description.device_class is not None:
129  self._attr_device_class_attr_device_class = SensorDeviceClass(
130  entity_description.device_class.value
131  )
132 
133  @property
134  def native_value(self) -> StateType:
135  """Return the state of the entity."""
136  return self.entity_data.entity.native_value
137 
138  @property
139  def extra_state_attributes(self) -> Mapping[str, Any] | None:
140  """Return entity specific state attributes."""
141  entity = self.entity_data.entity
142  if entity.extra_state_attribute_names is None:
143  return None
144 
145  if not entity.extra_state_attribute_names <= _EXTRA_STATE_ATTRIBUTES:
146  _LOGGER.warning(
147  "Unexpected extra state attributes found for sensor %s: %s",
148  entity,
149  entity.extra_state_attribute_names - _EXTRA_STATE_ATTRIBUTES,
150  )
151 
152  return exclude_none_values(
153  {
154  name: entity.state.get(name)
155  for name in entity.extra_state_attribute_names
156  }
157  )
None __init__(self, EntityData entity_data, **Any kwargs)
Definition: sensor.py:95
Mapping[str, Any]|None extra_state_attributes(self)
Definition: sensor.py:139
HAZHAData get_zha_data(HomeAssistant hass)
Definition: helpers.py:1020
dict[str, Any] exclude_none_values(Mapping[str, Any] obj)
Definition: helpers.py:1342
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:76
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103