Debian Codegraph @

blebox_uniapi/sensor.py

raw symbols SCIP
1 import datetime
2 from enum import IntEnum
3 from functools import partial
4
5 from .feature import Feature
6 from typing import TYPE_CHECKING, Union, Optional
7
8 if TYPE_CHECKING:
9 from .box import Box
10
11
12 class SensorFactory:
13 device_constructors: dict[str, type] = {}
14
15 @classmethod
16 def register(cls, sensor_type: str, **kwargs):
17 if sensor_type in cls.device_constructors:
18 raise RuntimeError("Can't register same sensor type twice")
19
20 def decorator(registrable: type):
21 constructor = registrable
22 if kwargs:
23 constructor = partial(registrable, sensor_type=sensor_type, **kwargs)
24
25 cls.device_constructors[sensor_type] = constructor
26 # note: returning unmodified, so we can register registrable
27 # multiple times under different names and with different kwargs
28 return registrable
29
30 return decorator
31
32 @staticmethod
33 def _sensor_states(extended_state: dict):
34 """Read potential sensor states from extended state dictionary"""
35 # note: probably we should iterate extended state in future if there
36 # are other api flavours other than multiSensor that provide sensors
37 states = extended_state.get("multiSensor", {}).get("sensors", [])
38 # note: but for now we are only able to support non-multisensor devices
39 # that provide sensor data in extended data payload root
40 states.extend(extended_state.get("sensors", []))
41 # note: power measuring feature predates multiSensor API, so we need a small
42 # shim to adapt older shape of power measuring schema to the new sensor API
43 if "powerMeasuring" in extended_state:
44 power_states = extended_state["powerMeasuring"].get("powerConsumption", [])
45 # note: be careful of names as this has been historically named differently
46 # in home-assistant
47 states.extend({"type": "powerConsumption", **s} for s in power_states)
48 return states
49
50 @classmethod
51 def many_from_config(cls, product, box_type_config, extended_state):
52 if extended_state:
53 object_list = []
54 # note: first item was historically an alias, but it has been since
55 # abandoned. We still keep it in the box config.
56 _, methods = box_type_config[0]
57
58 for sensor in cls._sensor_states(extended_state):
59 device_class = sensor.get("type")
60 sensor_id = sensor.get("id")
61
62 alias = device_class
63 if sensor_id is not None:
64 alias = f"{device_class}_{sensor_id}"
65
66 if constructor := cls.device_constructors.get(device_class):
67 # note: methods for sensor readings are provided as template
68 # functions (lambdas) in the box config. We need to "materialize"
69 # them to make sure they are properly indexed by sensor ID
70 materialized_methods = Feature.resolve_access_method_paths(
71 methods, sensor_id
72 )
73
74 feature = constructor(
75 product=product,
76 alias=alias,
77 methods=materialized_methods,
78 sensor_id=sensor_id,
79 name=sensor.get("name"),
80 )
81 object_list.append(feature)
82
83 return object_list
84
85 # legacy handling of some old device API that do not provide extended state
86 alias, methods = box_type_config[0]
87 if alias.endswith("air"):
88 method_list = [method for method in methods if "value" in method]
89 return [
90 AirQuality(product=product, alias=method.split(".")[0], methods=methods)
91 for method in method_list
92 ]
93 if alias.endswith("temperature"):
94 return [Temperature(product=product, alias=alias, methods=methods)]
95 else:
96 return []
97
98
99 class BleboxSensorState(IntEnum):
100 """Possible states of a sensor reading, not all valid for every device type."""
101
102 IDLE = 0
103 INITIALIZING = 1
104 ACTIVE = 2
105 ERROR = 3
106 ABOVE_RANGE = 4
107 BELOW_RANGE = 5
108
109
110 class BaseSensor(Feature):
111 _unit: str
112 _device_class: str
113 _native_value: Optional[Union[float, int, str]] = None
114 _sensor_type: Optional[str]
115 _sensor_id: Optional[int]
116 _error: bool = False
117
118 def __init__(
119 self,
120 product: "Box",
121 alias: str,
122 methods: dict,
123 sensor_type: str = None,
124 sensor_id: Optional[int] = None,
125 name: Optional[str] = None,
126 ):
127 self._sensor_type = sensor_type
128 self._sensor_id = sensor_id
129 self._name = name
130 super().__init__(product, alias, methods)
131
132 @property
133 def unit(self) -> str:
134 return self._unit
135
136 @property
137 def device_class(self) -> str:
138 return self._device_class
139
140 @property
141 def native_value(self):
142 return self._native_value
143
144 @property
145 def is_error(self) -> bool:
146 return self._error
147
148 def _read_state(self, name: str) -> Optional[int]:
149 if self._product.last_data is None:
150 return None
151 raw = self.raw_value(f"{name}.state")
152 if not isinstance(raw, (int, float)):
153 return None
154 return int(raw)
155
156 @staticmethod
157 def _state_is_error(state: Optional[int]) -> bool:
158 return state == BleboxSensorState.ERROR
159
160 @staticmethod
161 def _state_is_initializing(state: Optional[int]) -> bool:
162 return state == BleboxSensorState.INITIALIZING
163
164 @property
165 def sensor_id(self):
166 return self._sensor_id
167
168 @property
169 def probe_id(self):
170 return self.sensor_id
171
172 @property
173 def index(self) -> Optional[int]:
174 return self._sensor_id
175
176 @property
177 def name(self) -> Optional[str]:
178 return self._name
179
180 @classmethod
181 def many_from_config(cls, product, box_type_config, extended_state):
182 raise NotImplementedError("Please use SensorFactory")
183
184 def __str__(self):
185 return f"<{self.__class__.__name__} sensor_type={self._sensor_type}, alias={self._alias}>"
186
187
188 @SensorFactory.register("frequency", unit="Hz", scale=1_000)
189 @SensorFactory.register("current", unit="mA")
190 @SensorFactory.register("voltage", unit="V", scale=10)
191 @SensorFactory.register("apparentPower", unit="va")
192 @SensorFactory.register("reactivePower", unit="var")
193 @SensorFactory.register("activePower", unit="W")
194 @SensorFactory.register("reverseReactiveEnergy", unit="kvarh", scale=1_000)
195 @SensorFactory.register("forwardReactiveEnergy", unit="kvarh", scale=1_000)
196 @SensorFactory.register("reverseActiveEnergy", unit="kWh", scale=1_000)
197 @SensorFactory.register("forwardActiveEnergy", unit="kWh", scale=1_000)
198 @SensorFactory.register("illuminance", unit="lx", scale=100)
199 @SensorFactory.register("humidity", unit="percentage", scale=100)
200 @SensorFactory.register("wind", unit="m/s", scale=10)
201 @SensorFactory.register("openStatus", unit="")
202 @SensorFactory.register("co2", unit="ppm")
203 @SensorFactory.register("co2Definition", unit="")
204 class GenericSensor(BaseSensor):
205 def __init__(
206 # base sensor params
207 self,
208 product: "Box",
209 alias: str,
210 methods: dict,
211 sensor_id: Optional[int],
212 name: Optional[str] = None,
213 *,
214 # generalization params
215 sensor_type: str,
216 unit: str,
217 scale: float = 1,
218 precision: Optional[int] = None,
219 ):
220 super().__init__(product, alias, methods, sensor_id=sensor_id, name=name)
221 self._unit = unit
222 self._scale = scale
223 self._precision = precision
224 # note: this seems redundant but there is at least one sensor type that
225 # has different mapping in home assistant (wind/wind_speed). Should be
226 # fixed in upstream first.
227 self._device_class = sensor_type
228 self._sensor_type = sensor_type
229
230 def after_update(self):
231 product = self._product
232 if product.last_data is None:
233 return
234
235 state = self._read_state(self._device_class)
236 if self._state_is_error(state):
237 self._error = True
238 self._native_value = None
239 return
240
241 self._error = False
242
243 if self._state_is_initializing(state):
244 self._native_value = None
245 return
246
247 raw = self.raw_value(self._device_class)
248 if not isinstance(raw, (int, float)):
249 self._native_value = None
250 return
251
252 native = raw / self._scale
253 if self._precision:
254 native = round(native, self._precision)
255
256 self._native_value = native
257
258
259 @SensorFactory.register("powerConsumption", unit="kWh")
260 class PowerConsumption(GenericSensor):
261 # note: almost the same as typical generic sensor but also provides extra property
262 # to read last reset value
263 @property
264 def last_reset(self):
265 return datetime.datetime.now() - datetime.timedelta(
266 seconds=self._read_period_of_measurement()
267 )
268
269 def _read_period_of_measurement(self) -> int:
270 product = self._product
271 if product.last_data is not None:
272 raw = self.raw_value("periodS")
273 if raw is not None:
274 alias = self._alias
275 return product.expect_int(alias, raw, 3600, 0)
276 return 0
277
278
279 @SensorFactory.register("temperature")
280 class Temperature(BaseSensor):
281 _current: Optional[Union[float, int]]
282
283 def __init__(
284 self,
285 product: "Box",
286 alias: str,
287 methods: dict,
288 sensor_id: Optional[int] = None,
289 name: Optional[str] = None,
290 ):
291 super().__init__(product, alias, methods, sensor_id=sensor_id, name=name)
292 self._unit = "celsius"
293 self._device_class = "temperature"
294
295 @property
296 def current(self) -> Optional[Union[float, int]]:
297 return self._current
298
299 def _read_temperature(self, field: str) -> Optional[Union[float, int]]:
300 product = self._product
301 if product.last_data is not None:
302 raw = self.raw_value(field)
303 if isinstance(raw, (int, float)):
304 return round(raw / 100.0, 1)
305 return None
306
307 def after_update(self) -> None:
308 state = self._read_state("temperature")
309 if self._state_is_error(state):
310 self._error = True
311 self._current = None
312 self._native_value = None
313 return
314
315 self._error = False
316
317 if self._state_is_initializing(state):
318 self._current = None
319 self._native_value = None
320 return
321
322 current = self._read_temperature("temperature")
323 self._current = current
324 self._native_value = current
325
326
327 @SensorFactory.register("airSensor")
328 class AirQuality(BaseSensor):
329 _pm: Optional[int]
330
331 def __init__(
332 self,
333 product: "Box",
334 alias: str,
335 methods: dict,
336 sensor_id: Optional[str] = None,
337 name: Optional[str] = None,
338 ):
339 super().__init__(product, alias, methods, sensor_id, name=name)
340 self._unit = "concentration_of_mp"
341 self._device_class = alias
342
343 def _pm_value(self, name: str) -> Optional[Union[int, float]]:
344 product = self._product
345 if product.last_data is not None:
346 raw = self.raw_value(name)
347 if isinstance(raw, (int, float)):
348 return raw
349 return None
350
351 def after_update(self) -> None:
352 state = self._read_state(self.device_class)
353 if self._state_is_error(state):
354 self._error = True
355 self._native_value = None
356 return
357
358 self._error = False
359
360 if self._state_is_initializing(state):
361 self._native_value = None
362 return
363
364 self._native_value = self._pm_value(f"{self.device_class}.value")