Debian Codegraph @

blebox_uniapi/box.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import asyncio
4 import time
5
6 from typing import Optional, Any, Dict
7
8 from .box_types import _DEFAULT_API_LEVEL, get_conf, get_conf_set
9 from .button import Button
10 from .climate import Climate
11 from .cover import Cover
12 from .light import Light
13 from .sensor import SensorFactory
14 from .binary_sensor import BinarySensor
15 from .session import ApiHost
16 from .switch import Switch
17 from .update import Update
18
19 from .error import (
20 UnsupportedBoxResponse,
21 UnsupportedBoxVersion,
22 BadFieldExceedsMax,
23 BadFieldLessThanMin,
24 BadFieldMissing,
25 BadFieldNotANumber,
26 BadFieldNotAString,
27 BadFieldNotRGBW,
28 HttpError,
29 )
30
31 DEFAULT_PORT = 80
32
33
34 class Box:
35 _name: str
36 _data_path: str
37 _last_real_update: Optional[float]
38 _last_data: Optional[Any]
39
40 api_session: ApiHost
41 info: dict
42 config: dict
43 extended_state: Optional[Dict[Any, Any]]
44
45 def __init__(
46 self,
47 api_session,
48 info,
49 config,
50 extended_state,
51 ) -> None:
52 self._last_data = None
53 self._last_real_update = None
54 self._sem = asyncio.BoundedSemaphore()
55 self._session = api_session
56
57 address = f"{api_session.host}:{api_session.port}"
58
59 location = f"Device at {address}"
60
61 # NOTE: get ID first for better error messages
62 try:
63 unique_id = info["id"]
64 except KeyError as ex:
65 raise UnsupportedBoxResponse(info, f"{location} has no id") from ex
66 location = f"Device:{unique_id} at {address}"
67
68 try:
69 type = info["type"]
70 except KeyError as ex:
71 raise UnsupportedBoxResponse(info, f"{location} has no type") from ex
72
73 try:
74 product = info["product"]
75 except KeyError:
76 product = type
77
78 # TODO: make wLightBox API support multiple products
79 # in 2020 wLightBoxS API has been deprecated and it started using wLightBox API
80 # current codebase needs a refactor to support multiple product sharing one API
81 # as a temporary workaround we are using 'alias' type wLightBoxS2
82 if type == "wLightBox" and product == "wLightBoxS":
83 type = "wLightBoxS"
84
85 location = f"{product}:{unique_id} at {address}"
86
87 try:
88 name = info["deviceName"]
89 except KeyError as ex:
90 raise UnsupportedBoxResponse(info, f"{location} has no name") from ex
91 location = f"'{name}' ({product}:{unique_id} at {address})"
92
93 try:
94 firmware_version = info["fv"]
95 except KeyError as ex:
96 raise UnsupportedBoxResponse(
97 info, f"{location} has no firmware version"
98 ) from ex
99 location = f"'{name}' ({product}:{unique_id}/{firmware_version} at {address})"
100
101 try:
102 hardware_version = info["hv"]
103 except KeyError as ex:
104 raise UnsupportedBoxResponse(
105 info, f"{location} has no hardware version"
106 ) from ex
107
108 available_firmware_version = info.get("availableFv")
109
110 level = int(info.get("apiLevel", _DEFAULT_API_LEVEL))
111
112 self._data_path = config["api_path"]
113 self._type = type
114 self._product = product
115 self._unique_id = unique_id
116 self._name = name
117 self._address = address
118 self._firmware_version = firmware_version
119 self._hardware_version = hardware_version
120 self._available_firmware_version = available_firmware_version
121 self._api_version = level
122 self._model = config.get("model", type)
123 self._api = config.get("api", {})
124 self._features = self.create_features(config, info, extended_state)
125 self._config = config
126 self._update_last_data(extended_state)
127
128 def create_features(
129 self, config: dict, info: dict, extended_state: Optional[dict]
130 ) -> dict:
131 features = {}
132 for field, klass in {
133 "covers": Cover,
134 "sensors": SensorFactory,
135 "binary_sensors": BinarySensor,
136 "lights": Light,
137 "climates": Climate,
138 "switches": Switch,
139 "buttons": Button,
140 }.items():
141 try:
142 if box_type_config := config.get(field):
143 features[field] = klass.many_from_config(
144 self,
145 box_type_config=box_type_config,
146 extended_state=extended_state,
147 )
148 except KeyError:
149 raise UnsupportedBoxResponse("Failed to initialize:", info)
150 features["updates"] = [Update(self, "update", {})]
151 return features
152
153 @classmethod
154 async def async_from_host(cls, api_host: ApiHost) -> Box:
155 try:
156 path = "/api/device/state"
157 data = await api_host.async_api_get(path)
158 except HttpError:
159 path = "/info"
160 data = await api_host.async_api_get(path)
161 if data is None:
162 raise UnsupportedBoxResponse("Device returned non-JSON response")
163 info = data.get("device", data)
164 extended_state = None
165
166 config = cls._match_device_config(info)
167 if extended_state_path := config.get("extended_state_path"):
168 try:
169 extended_state = await api_host.async_api_get(extended_state_path)
170 except (HttpError, KeyError):
171 extended_state = None
172
173 return cls(api_host, info, config, extended_state)
174
175 @classmethod
176 def _match_device_config(cls, info: dict) -> dict:
177 try:
178 device_type = info["type"]
179 except KeyError as ex:
180 raise UnsupportedBoxResponse(info, "Device info has no type key") from ex
181 try:
182 product = info["product"]
183 except KeyError:
184 product = device_type
185 if device_type == "wLightBox" and product == "wLightBoxS":
186 device_type = "wLightBoxS"
187 level = int(info.get("apiLevel", _DEFAULT_API_LEVEL))
188 config_set = get_conf_set(device_type)
189 if not config_set:
190 raise UnsupportedBoxResponse(f"{device_type} is not a supported type")
191 config = get_conf(level, config_set)
192 if not config:
193 raise UnsupportedBoxVersion(
194 f"{device_type} has unsupported version ({level})."
195 )
196
197 return config
198
199 @property
200 def name(self) -> str:
201 return self._name
202
203 @property
204 def address(self) -> str:
205 return self._address
206
207 @property
208 def last_data(self) -> Optional[Dict[Any, Any]]:
209 return self._last_data
210
211 # Used in full_name, track down and refactor.
212 @property
213 def type(self) -> str:
214 return self._type
215
216 @property
217 def product(self) -> str:
218 """Product name for informational purpose only - do not use it in any application logic."""
219 return self._product
220
221 @property
222 def unique_id(self) -> Any:
223 return self._unique_id
224
225 @property
226 def firmware_version(self) -> Any:
227 return self._firmware_version
228
229 @property
230 def hardware_version(self) -> Any:
231 return self._hardware_version
232
233 @property
234 def available_firmware_version(self) -> Any:
235 return self._available_firmware_version
236
237 @property
238 def api_version(self) -> int:
239 return self._api_version
240
241 @property
242 def features(self) -> dict:
243 return self._features
244
245 @property
246 def brand(self) -> str:
247 return "BleBox"
248
249 @property
250 def model(self) -> Any:
251 return self._model
252
253 async def async_update_data(self) -> None:
254 await self._async_api(True, "GET", self._data_path)
255
256 def _update_last_data(self, new_data: Optional[dict]) -> None:
257 # Note: on certain more complex devices that inlcude multiple features
258 # like switches and sensors (e.g. SwitchboxD) it may happen that activating
259 # single feature would result only in partial update of the self._last_data.
260 # We can know that by comparing keys of both states.
261 #
262 # Notable example of device exhibiting this behavior is SwitchboxD (20200831)
263 # It has two relays (switches) and power measurement capabilities (sensor).
264 # Toggling the relay does return state of all relays, but does not return
265 # sensor information (partial state). Accepting the new state as-is would
266 # break the update of sensory information.
267 #
268 # Note that SwitchboxD is just an example. It is possible that APIs of other
269 # box types also exhibit this kind of behavior.
270 if (
271 isinstance(self._last_data, dict)
272 and isinstance(new_data, dict)
273 and self._last_data.keys() != new_data.keys()
274 ):
275 # ... In such a case we need to merge both states instead of overwriting
276 # the old one as-is.
277 #
278 # The only risk is that if certain features are somehow coupled inside
279 # the device, we will have inconsistent information about the device.
280 # However, this should be eventually consistent as new updates arrive.
281 # In the end, it is better to have an inconsistent state, rather than
282 # have broken one (e.g. missing keys) that results in broken features.
283 #
284 # Refs:
285 # - https://github.com/blebox/blebox_uniapi/pull/152
286 # - https://github.com/blebox/blebox_uniapi/issues/137
287 new_data = {**self._last_data, **new_data}
288
289 self._last_data = new_data
290 for feature_set in self._features.values():
291 for feature in feature_set:
292 feature.after_update()
293
294 async def async_api_command(self, command: str, value: Any = None) -> None:
295 method, *args = self._api[command](value)
296 self._last_real_update = None # force update
297 return await self._async_api(False, method, *args)
298
299 def expect_int(
300 self, field: str, raw_value: int, maximum: int = -1, minimum: int = 0
301 ) -> int:
302 return self.check_int(raw_value, field, maximum, minimum)
303
304 def expect_hex_str(
305 self, field: str, raw_value: int, maximum: int = -1, minimum: int = 0
306 ) -> int:
307 return self.check_hex_str(raw_value, field, maximum, minimum)
308
309 def expect_rgbw(self, field: str, raw_value: int) -> int:
310 return self.check_rgbw(raw_value, field)
311
312 def check_int_range(
313 self, value: int, field: str, max_value: int, min_value: int
314 ) -> int:
315 if max_value >= min_value:
316 if value > max_value:
317 raise BadFieldExceedsMax(self.name, field, value, max_value)
318 if value < min_value:
319 raise BadFieldLessThanMin(self.name, field, value, min_value)
320 return value
321
322 def check_int(self, value: int, field: str, max_value: int, min_value: int) -> int:
323 if value is None:
324 raise BadFieldMissing(self.name, field)
325
326 if not isinstance(value, int):
327 raise BadFieldNotANumber(self.name, field, value)
328
329 return self.check_int_range(value, field, max_value, min_value)
330
331 def check_hex_str(
332 self, value: int, field: str, max_value: int, min_value: int
333 ) -> int:
334 if value is None:
335 raise BadFieldMissing(self.name, field)
336
337 if not isinstance(value, str):
338 raise BadFieldNotAString(self.name, field, value)
339
340 if (
341 self.check_int_range(int(value, 16), field, max_value, min_value)
342 is not None
343 ):
344 return value
345
346 def check_rgbw(self, value: int, field: str) -> int:
347 if value is None:
348 raise BadFieldMissing(self.name, field)
349
350 if not isinstance(value, str):
351 raise BadFieldNotAString(self.name, field, value)
352
353 if len(value) > 10 or len(value) % 2 != 0:
354 raise BadFieldNotRGBW(self.name, field, value)
355 return value
356
357 def _has_recent_data(self) -> bool:
358 last = self._last_real_update
359 return (time.time() - 2) <= last if last is not None else False
360
361 async def _async_api(
362 self,
363 is_update: bool,
364 method: Any,
365 path: str,
366 post_data: dict = None,
367 ) -> None:
368 if method not in ("GET", "POST"):
369 raise NotImplementedError(method) # pragma: no cover
370
371 if is_update:
372 if self._has_recent_data():
373 return
374
375 async with self._sem:
376 if is_update:
377 if self._has_recent_data():
378 return
379 if method == "GET":
380 response = await self._session.async_api_get(path)
381 else:
382 response = await self._session.async_api_post(path, post_data)
383 self._update_last_data(response)
384 self._last_real_update = time.time()
385
386 async def async_ota_check(self) -> None:
387 await self._session.async_api_get_ota("/api/ota/check")
388 for _ in range(3):
389 await asyncio.sleep(1)
390 response = await self._session.async_api_get("/info")
391 if response is None:
392 raise UnsupportedBoxResponse("Device returned non-JSON response")
393 response = response.get("device", response)
394 if response.get("availableFv") is not None:
395 self._firmware_version = response.get("fv", self._firmware_version)
396 self._available_firmware_version = response["availableFv"]
397 return
398
399 async def async_ota_update(self) -> None:
400 await self._session.async_api_get("/api/ota/update")