Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Sensor support for Wireless Sensor Tags platform."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import voluptuous as vol
8 
10  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
11  SensorDeviceClass,
12  SensorEntity,
13  SensorEntityDescription,
14  SensorStateClass,
15 )
16 from homeassistant.const import CONF_MONITORED_CONDITIONS, Platform
17 from homeassistant.core import HomeAssistant, callback
19 from homeassistant.helpers.dispatcher import async_dispatcher_connect
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
22 
23 from .const import DOMAIN, SIGNAL_TAG_UPDATE
24 from .entity import WirelessTagBaseSensor
25 from .util import async_migrate_unique_id
26 
27 _LOGGER = logging.getLogger(__name__)
28 
29 SENSOR_TEMPERATURE = "temperature"
30 SENSOR_AMBIENT_TEMPERATURE = "ambient_temperature"
31 SENSOR_HUMIDITY = "humidity"
32 SENSOR_MOISTURE = "moisture"
33 SENSOR_LIGHT = "light"
34 
35 SENSOR_TYPES: dict[str, SensorEntityDescription] = {
36  SENSOR_TEMPERATURE: SensorEntityDescription(
37  key=SENSOR_TEMPERATURE,
38  device_class=SensorDeviceClass.TEMPERATURE,
39  state_class=SensorStateClass.MEASUREMENT,
40  ),
41  SENSOR_AMBIENT_TEMPERATURE: SensorEntityDescription(
42  key=SENSOR_AMBIENT_TEMPERATURE,
43  device_class=SensorDeviceClass.TEMPERATURE,
44  state_class=SensorStateClass.MEASUREMENT,
45  ),
46  SENSOR_HUMIDITY: SensorEntityDescription(
47  key=SENSOR_HUMIDITY,
48  device_class=SensorDeviceClass.HUMIDITY,
49  state_class=SensorStateClass.MEASUREMENT,
50  ),
51  SENSOR_MOISTURE: SensorEntityDescription(
52  key=SENSOR_MOISTURE,
53  device_class=SensorDeviceClass.MOISTURE,
54  state_class=SensorStateClass.MEASUREMENT,
55  ),
56  SENSOR_LIGHT: SensorEntityDescription(
57  key=SENSOR_LIGHT,
58  device_class=SensorDeviceClass.ILLUMINANCE,
59  state_class=SensorStateClass.MEASUREMENT,
60  ),
61 }
62 
63 SENSOR_KEYS: list[str] = list(SENSOR_TYPES)
64 
65 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
66  {
67  vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All(
68  cv.ensure_list, [vol.In(SENSOR_KEYS)]
69  )
70  }
71 )
72 
73 
75  hass: HomeAssistant,
76  config: ConfigType,
77  async_add_entities: AddEntitiesCallback,
78  discovery_info: DiscoveryInfoType | None = None,
79 ) -> None:
80  """Set up the sensor platform."""
81  platform = hass.data[DOMAIN]
82  sensors = []
83  tags = platform.tags
84  for tag in tags.values():
85  for key in config[CONF_MONITORED_CONDITIONS]:
86  if key not in tag.allowed_sensor_types:
87  continue
88  description = SENSOR_TYPES[key]
89  async_migrate_unique_id(hass, tag, Platform.SENSOR, description.key)
90  sensors.append(WirelessTagSensor(platform, tag, description))
91 
92  async_add_entities(sensors, True)
93 
94 
96  """Representation of a Sensor."""
97 
98  entity_description: SensorEntityDescription
99 
100  def __init__(self, api, tag, description):
101  """Initialize a WirelessTag sensor."""
102  super().__init__(api, tag)
103 
104  self._sensor_type_sensor_type = description.key
105  self.entity_descriptionentity_description = description
106  self._name_name_name = self._tag_tag_tag.name
107  self._attr_unique_id_attr_unique_id = f"{self._uuid}_{self._sensor_type}"
108 
109  # I want to see entity_id as:
110  # sensor.wirelesstag_bedroom_temperature
111  # and not as sensor.bedroom for temperature and
112  # sensor.bedroom_2 for humidity
113  self.entity_identity_identity_id = f"sensor.{DOMAIN}_{self.underscored_name}_{self._sensor_type}"
114 
115  async def async_added_to_hass(self) -> None:
116  """Register callbacks."""
117  self.async_on_removeasync_on_remove(
119  self.hasshass,
120  SIGNAL_TAG_UPDATE.format(self.tag_idtag_id, self.tag_manager_mactag_manager_mac),
121  self._update_tag_info_callback_update_tag_info_callback,
122  )
123  )
124 
125  @property
126  def underscored_name(self):
127  """Provide name savvy to be used in entity_id name of self."""
128  return self.namenamename.lower().replace(" ", "_")
129 
130  @property
131  def native_value(self):
132  """Return the state of the sensor."""
133  return self._state_state_state
134 
135  @property
137  """Return the unit of measurement."""
138  return self._sensor_sensor.unit
139 
140  @property
141  def principal_value(self):
142  """Return sensor current value."""
143  return self._sensor_sensor.value
144 
145  @property
146  def _sensor(self):
147  """Return tag sensor entity."""
148  return self._tag_tag_tag.sensor[self._sensor_type_sensor_type]
149 
150  @callback
151  def _update_tag_info_callback(self, new_tag):
152  """Handle push notification sent by tag manager."""
153  _LOGGER.debug("Entity to update state: %s with new tag: %s", self, new_tag)
154  self._tag_tag_tag = new_tag
155  self._state_state_state = self.updated_state_valueupdated_state_value()
156  self.async_write_ha_stateasync_write_ha_state()
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
str|UndefinedType|None name(self)
Definition: entity.py:738
None async_migrate_unique_id(HomeAssistant hass, ConfigEntry config_entry, Appliance device)
Definition: __init__.py:84
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:79
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103