Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Efergy sensors."""
2 
3 from __future__ import annotations
4 
5 import dataclasses
6 from re import sub
7 from typing import cast
8 
9 from pyefergy import Efergy
10 from pyefergy.exceptions import ConnectError, DataError, ServiceError
11 
13  SensorDeviceClass,
14  SensorEntity,
15  SensorEntityDescription,
16  SensorStateClass,
17 )
18 from homeassistant.const import UnitOfEnergy, UnitOfPower
19 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 from homeassistant.helpers.typing import StateType
22 
23 from . import EfergyConfigEntry
24 from .const import CONF_CURRENT_VALUES, LOGGER
25 from .entity import EfergyEntity
26 
27 SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
29  key="instant_readings",
30  translation_key="instant_readings",
31  device_class=SensorDeviceClass.POWER,
32  native_unit_of_measurement=UnitOfPower.WATT,
33  state_class=SensorStateClass.MEASUREMENT,
34  ),
36  key="energy_day",
37  translation_key="energy_day",
38  device_class=SensorDeviceClass.ENERGY,
39  native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
40  state_class=SensorStateClass.TOTAL_INCREASING,
41  entity_registry_enabled_default=False,
42  ),
44  key="energy_week",
45  translation_key="energy_week",
46  device_class=SensorDeviceClass.ENERGY,
47  native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
48  state_class=SensorStateClass.TOTAL_INCREASING,
49  entity_registry_enabled_default=False,
50  ),
52  key="energy_month",
53  translation_key="energy_month",
54  device_class=SensorDeviceClass.ENERGY,
55  native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
56  state_class=SensorStateClass.TOTAL_INCREASING,
57  ),
59  key="energy_year",
60  translation_key="energy_year",
61  device_class=SensorDeviceClass.ENERGY,
62  native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
63  state_class=SensorStateClass.TOTAL_INCREASING,
64  entity_registry_enabled_default=False,
65  ),
67  key="budget",
68  translation_key="budget",
69  entity_registry_enabled_default=False,
70  ),
72  key="cost_day",
73  translation_key="cost_day",
74  device_class=SensorDeviceClass.MONETARY,
75  state_class=SensorStateClass.TOTAL_INCREASING,
76  entity_registry_enabled_default=False,
77  ),
79  key="cost_week",
80  translation_key="cost_week",
81  device_class=SensorDeviceClass.MONETARY,
82  state_class=SensorStateClass.TOTAL_INCREASING,
83  entity_registry_enabled_default=False,
84  ),
86  key="cost_month",
87  translation_key="cost_month",
88  device_class=SensorDeviceClass.MONETARY,
89  state_class=SensorStateClass.TOTAL_INCREASING,
90  ),
92  key="cost_year",
93  translation_key="cost_year",
94  device_class=SensorDeviceClass.MONETARY,
95  state_class=SensorStateClass.TOTAL_INCREASING,
96  entity_registry_enabled_default=False,
97  ),
99  key=CONF_CURRENT_VALUES,
100  translation_key="power_usage",
101  device_class=SensorDeviceClass.POWER,
102  native_unit_of_measurement=UnitOfPower.WATT,
103  state_class=SensorStateClass.MEASUREMENT,
104  ),
105 )
106 
107 
109  hass: HomeAssistant,
110  entry: EfergyConfigEntry,
111  async_add_entities: AddEntitiesCallback,
112 ) -> None:
113  """Set up Efergy sensors."""
114  api = entry.runtime_data
115  sensors = []
116  for description in SENSOR_TYPES:
117  if description.key != CONF_CURRENT_VALUES:
118  sensors.append(
119  EfergySensor(
120  api,
121  description,
122  entry.entry_id,
123  period=sub("^energy_|^cost_", "", description.key),
124  currency=hass.config.currency,
125  )
126  )
127  else:
128  description = dataclasses.replace(
129  description,
130  entity_registry_enabled_default=len(api.sids) > 1,
131  )
132  sensors.extend(
133  EfergySensor(
134  api,
135  description,
136  entry.entry_id,
137  sid=sid,
138  )
139  for sid in api.sids
140  )
141  async_add_entities(sensors, True)
142 
143 
145  """Implementation of an Efergy sensor."""
146 
147  _attr_has_entity_name = True
148 
149  def __init__(
150  self,
151  api: Efergy,
152  description: SensorEntityDescription,
153  server_unique_id: str,
154  period: str | None = None,
155  currency: str | None = None,
156  sid: int | None = None,
157  ) -> None:
158  """Initialize the sensor."""
159  super().__init__(api, server_unique_id)
160  self.entity_descriptionentity_description = description
161  if description.key == CONF_CURRENT_VALUES:
162  assert sid is not None
163  self._attr_translation_placeholders_attr_translation_placeholders = {"sid": str(sid)}
164  self._attr_unique_id_attr_unique_id = (
165  f"{server_unique_id}/{description.key}_{'' if sid is None else sid}"
166  )
167  if "cost" in description.key:
168  self._attr_native_unit_of_measurement_attr_native_unit_of_measurement = currency
169  self.sidsid = sid
170  self.periodperiod = period
171 
172  async def async_update(self) -> None:
173  """Get the Efergy monitor data from the web service."""
174  try:
175  data = await self.apiapi.async_get_reading(
176  self.entity_descriptionentity_description.key, period=self.periodperiod, sid=self.sidsid
177  )
178  self._attr_native_value_attr_native_value = cast(StateType, data)
179  except (ConnectError, DataError, ServiceError) as ex:
180  if self._attr_available_attr_available:
181  self._attr_available_attr_available = False
182  LOGGER.error("Error getting data: %s", ex)
183  return
184  if not self._attr_available_attr_available:
185  self._attr_available_attr_available = True
186  LOGGER.debug("Connection has resumed")
None __init__(self, Efergy api, SensorEntityDescription description, str server_unique_id, str|None period=None, str|None currency=None, int|None sid=None)
Definition: sensor.py:157
None async_setup_entry(HomeAssistant hass, EfergyConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:112