Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Demo platform that has a couple of fake sensors."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime, timedelta
6 from typing import cast
7 
9  DOMAIN as SENSOR_DOMAIN,
10  RestoreSensor,
11  SensorDeviceClass,
12  SensorEntity,
13  SensorStateClass,
14 )
15 from homeassistant.config_entries import ConfigEntry
16 from homeassistant.const import (
17  ATTR_BATTERY_LEVEL,
18  CONCENTRATION_PARTS_PER_MILLION,
19  PERCENTAGE,
20  UnitOfEnergy,
21  UnitOfPower,
22  UnitOfTemperature,
23  UnitOfVolume,
24 )
25 from homeassistant.core import HomeAssistant, callback
26 from homeassistant.helpers.device_registry import DeviceInfo
27 from homeassistant.helpers.entity_platform import AddEntitiesCallback
28 from homeassistant.helpers.event import async_track_time_interval
29 
30 from . import DOMAIN
31 
32 
34  hass: HomeAssistant,
35  config_entry: ConfigEntry,
36  async_add_entities: AddEntitiesCallback,
37 ) -> None:
38  """Set up the demo sensor platform."""
40  [
41  DemoSensor(
42  "sensor_1",
43  "Outside Temperature",
44  15.6,
45  SensorDeviceClass.TEMPERATURE,
46  SensorStateClass.MEASUREMENT,
47  UnitOfTemperature.CELSIUS,
48  12,
49  ),
50  DemoSensor(
51  "sensor_2",
52  "Outside Humidity",
53  54,
54  SensorDeviceClass.HUMIDITY,
55  SensorStateClass.MEASUREMENT,
56  PERCENTAGE,
57  None,
58  ),
59  DemoSensor(
60  "sensor_3",
61  "Carbon monoxide",
62  54,
63  SensorDeviceClass.CO,
64  SensorStateClass.MEASUREMENT,
65  CONCENTRATION_PARTS_PER_MILLION,
66  None,
67  ),
68  DemoSensor(
69  "sensor_4",
70  "Carbon dioxide",
71  54,
72  SensorDeviceClass.CO2,
73  SensorStateClass.MEASUREMENT,
74  CONCENTRATION_PARTS_PER_MILLION,
75  14,
76  ),
77  DemoSensor(
78  "sensor_5",
79  "Power consumption",
80  100,
81  SensorDeviceClass.POWER,
82  SensorStateClass.MEASUREMENT,
83  UnitOfPower.WATT,
84  None,
85  ),
87  "sensor_6",
88  "Total energy 1",
89  0.5, # 6kWh / h
90  SensorDeviceClass.ENERGY,
91  SensorStateClass.TOTAL,
92  UnitOfEnergy.KILO_WATT_HOUR,
93  None,
94  "total_energy_kwh",
95  ),
97  "sensor_7",
98  "Total energy 2",
99  0.00025, # 0.003 MWh/h (3 kWh / h)
100  SensorDeviceClass.ENERGY,
101  SensorStateClass.TOTAL,
102  UnitOfEnergy.MEGA_WATT_HOUR,
103  None,
104  "total_energy_mwh",
105  ),
107  "sensor_8",
108  "Total gas 1",
109  0.025, # 0.30 m³/h (10.6 ft³ / h)
110  SensorDeviceClass.GAS,
111  SensorStateClass.TOTAL,
112  UnitOfVolume.CUBIC_METERS,
113  None,
114  "total_gas_m3",
115  ),
117  "sensor_9",
118  "Total gas 2",
119  1.0, # 12 ft³/h (0.34 m³ / h)
120  SensorDeviceClass.GAS,
121  SensorStateClass.TOTAL,
122  UnitOfVolume.CUBIC_FEET,
123  None,
124  "total_gas_ft3",
125  ),
126  DemoSensor(
127  unique_id="sensor_10",
128  device_name="Thermostat",
129  state="eco",
130  device_class=SensorDeviceClass.ENUM,
131  state_class=None,
132  unit_of_measurement=None,
133  battery=None,
134  options=["away", "comfort", "eco", "sleep"],
135  translation_key="thermostat_mode",
136  ),
137  ]
138  )
139 
140 
142  """Representation of a Demo sensor."""
143 
144  _attr_has_entity_name = True
145  _attr_name = None
146  _attr_should_poll = False
147 
148  def __init__(
149  self,
150  unique_id: str,
151  device_name: str | None,
152  state: float | str | None,
153  device_class: SensorDeviceClass,
154  state_class: SensorStateClass | None,
155  unit_of_measurement: str | None,
156  battery: int | None,
157  options: list[str] | None = None,
158  translation_key: str | None = None,
159  ) -> None:
160  """Initialize the sensor."""
161  self._attr_device_class_attr_device_class = device_class
162  self._attr_native_unit_of_measurement_attr_native_unit_of_measurement = unit_of_measurement
163  self._attr_native_value_attr_native_value = state
164  self._attr_state_class_attr_state_class = state_class
165  self._attr_unique_id_attr_unique_id = unique_id
166  self._attr_options_attr_options = options
167  self._attr_translation_key_attr_translation_key = translation_key
168 
169  self._attr_device_info_attr_device_info = DeviceInfo(
170  identifiers={(DOMAIN, unique_id)},
171  name=device_name,
172  )
173 
174  if battery:
175  self._attr_extra_state_attributes_attr_extra_state_attributes = {ATTR_BATTERY_LEVEL: battery}
176 
177 
179  """Representation of a Demo sensor."""
180 
181  _attr_should_poll = False
182  _attr_native_value: float
183 
184  def __init__(
185  self,
186  unique_id: str,
187  device_name: str,
188  five_minute_increase: float,
189  device_class: SensorDeviceClass,
190  state_class: SensorStateClass | None,
191  unit_of_measurement: str | None,
192  battery: int | None,
193  suggested_entity_id: str,
194  ) -> None:
195  """Initialize the sensor."""
196  self.entity_identity_identity_id = f"{SENSOR_DOMAIN}.{suggested_entity_id}"
197  self._attr_device_class_attr_device_class = device_class
198  self._attr_native_unit_of_measurement_attr_native_unit_of_measurement = unit_of_measurement
199  self._attr_native_value_attr_native_value = 0
200  self._attr_state_class_attr_state_class = state_class
201  self._attr_unique_id_attr_unique_id = unique_id
202  self._five_minute_increase_five_minute_increase = five_minute_increase
203 
204  self._attr_device_info_attr_device_info = DeviceInfo(
205  identifiers={(DOMAIN, unique_id)},
206  name=device_name,
207  )
208 
209  if battery:
210  self._attr_extra_state_attributes_attr_extra_state_attributes = {ATTR_BATTERY_LEVEL: battery}
211 
212  @callback
213  def _async_bump_sum(self, now: datetime) -> None:
214  """Bump the sum."""
215  self._attr_native_value_attr_native_value += self._five_minute_increase_five_minute_increase
216  self.async_write_ha_stateasync_write_ha_state()
217 
218  async def async_added_to_hass(self) -> None:
219  """Call when entity about to be added to hass."""
220  await super().async_added_to_hass()
221  state = await self.async_get_last_sensor_dataasync_get_last_sensor_data()
222  if state:
223  self._attr_native_value_attr_native_value = cast(float, state.native_value)
224 
225  self.async_on_removeasync_on_remove(
227  self.hasshass, self._async_bump_sum_async_bump_sum, timedelta(minutes=5)
228  ),
229  )
None __init__(self, str unique_id, str|None device_name, float|str|None state, SensorDeviceClass device_class, SensorStateClass|None state_class, str|None unit_of_measurement, int|None battery, list[str]|None options=None, str|None translation_key=None)
Definition: sensor.py:159
None __init__(self, str unique_id, str device_name, float five_minute_increase, SensorDeviceClass device_class, SensorStateClass|None state_class, str|None unit_of_measurement, int|None battery, str suggested_entity_id)
Definition: sensor.py:194
SensorExtraStoredData|None async_get_last_sensor_data(self)
Definition: __init__.py:934
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:37
CALLBACK_TYPE async_track_time_interval(HomeAssistant hass, Callable[[datetime], Coroutine[Any, Any, None]|None] action, timedelta interval, *str|None name=None, bool|None cancel_on_shutdown=None)
Definition: event.py:1679