Debian Codegraph @

aioairq/core.py

raw
1 from __future__ import annotations
2
3 import re
4 import json
5 from typing import Any, List, Literal, TypedDict
6
7 import aiohttp
8
9 from aioairq.encrypt import AESCipher
10 from aioairq.exceptions import (
11 APIAccessDenied,
12 APIAccessError,
13 InvalidAirQResponse,
14 InvalidIpAddress,
15 )
16 from aioairq.utils import is_valid_ipv4_address
17
18 LedThemeName = Literal[
19 "standard",
20 "standard (contrast)",
21 "Virus",
22 "Virus (contrast)",
23 "co2_covid19",
24 "CO2",
25 "VOC",
26 "Humidity",
27 "CO",
28 "NO2",
29 "O3",
30 "Oxygen",
31 "PM1",
32 "PM2.5",
33 "PM10",
34 "Noise",
35 "Noise (contrast)",
36 "Noise Average",
37 "Noise Average (contrast)",
38 ]
39
40
41 class DeviceInfo(TypedDict):
42 """Container for device information"""
43
44 id: str
45 name: str | None
46 model: str | None
47 suggested_area: str | None
48 sw_version: str | None
49 hw_version: str | None
50
51
52 class DeviceLedTheme(TypedDict, total=True):
53 """Complete specification of the LED themes of a device.
54
55 Each device is described by two themes, one for each side.
56 """
57
58 left: LedThemeName
59 right: LedThemeName
60
61
62 class DeviceLedThemePatch(TypedDict, total=False):
63 """Potentially incomplete specification of the LED themes.
64
65 Helpful for updating the themes.
66 """
67
68 left: LedThemeName
69 right: LedThemeName
70
71
72 class NightMode(TypedDict):
73 """Container holding night mode configuration"""
74
75 activated: bool
76 """Whether the night mode is activated"""
77
78 start_day: str
79 """End time of night mode in format 'HH:mm'. Note that the time is in UTC."""
80
81 start_night: str
82 """Start time of night mode in format 'HH:mm'. Note that the time is in UTC."""
83
84 brightness_day: float
85 """LED brightness outside of night mode.
86
87 Note:
88 Official docs say valid range is 2.2 to 20.0.
89 The valid range seems more like 1.0 to 10.0. With 0 the LEDs can be turned off completely.
90 """
91
92 brightness_night: float
93 """LED brightness during night mode.
94
95 Note:
96 Official docs say valid range is 2.2 to 20.0.
97 The valid range seems more like 1.0 to 10.0. With 0 the LEDs can be turned off completely.
98 """
99
100 fan_night_off: bool
101 """Whether the fans are turned off during night mode.
102
103 Notes from official docs:
104 Turning off the fans will disable the sensors for particle pollution (PM1, PM2.5, PM10).
105 Fire alarm will only trigger for CO and temperature, but not for smoke."""
106
107 wifi_night_off: bool
108 """Whether Wi-Fi is turned off during night mode.
109
110 Notes from official docs:
111 When turning off Wi-Fi with this setting and when cloud upload is enabled,
112 data will be cached on the SD card and uploaded eventually
113 when network link is available again."""
114
115 alarm_night_off: bool
116 """Whether alarms are turned off during night mode.
117
118 Notes from official docs:
119 This setting disables acoustic warnings. Fire and gas alarm will trigger despite."""
120
121
122 class AirQ:
123 _supported_routes = ["config", "log", "data", "average", "ping"]
124
125 def __init__(
126 self,
127 address: str,
128 passw: str,
129 session: aiohttp.ClientSession,
130 timeout: float = 15,
131 ):
132 """Class representing the API for a single AirQ device
133
134 The class holds the AESCipher object, responsible for message decoding,
135 as well as the anchor of the http address to base further requests on
136
137 Parameters
138 ----------
139 address : str
140 Either the IP address of the device, or its mDNS.
141 Device's IP might be a more robust option (across the variety of routers)
142 passw : str
143 Device's password
144 session : aiohttp.ClientSession
145 Session used to communicate to the device. Should be managed by the user
146 timeout : float
147 Maximum time in seconds used by `session.get` to connect to the device
148 before `aiohttp.ServerTimeoutError` is raised. Default: 15 seconds.
149 Hitting the timeout be an indication that the device and the host are not
150 on the same WiFi
151 """
152
153 self.address = address
154 self.anchor = "http://" + self.address
155 self.aes = AESCipher(passw)
156 self._session = session
157 self._timeout = aiohttp.ClientTimeout(connect=timeout)
158
159 async def has_api_access(self) -> bool:
160 return (await self.get_config())["APIaccess"]
161
162 async def blink(self) -> str:
163 """Let the device blink in rainbow colors for a short amount of time.
164
165 Returns the device's ID.
166 This function can be used to identify a device, when you have multiple devices.
167 """
168 json_data = await self._get_json("/blink")
169
170 return json_data["id"]
171
172 async def validate(self) -> None:
173 """Test if the password provided to the constructor is valid.
174
175 Raises InvalidAuth if the password is not correct.
176 This is merely a convenience function, relying on the exception being
177 raised down the stack (namely by AESCipher.decode from within self.get)
178 """
179 await self.get("ping")
180
181 async def restart(self) -> None:
182 """Restarts the device."""
183 post_json_data = {"reset": True}
184
185 await self._post_json_and_decode("/config", post_json_data)
186
187 async def shutdown(self) -> None:
188 """Shuts the device down."""
189 post_json_data = {"shutdown": True}
190
191 await self._post_json_and_decode("/config", post_json_data)
192
193 def __repr__(self) -> str:
194 return f"{self.__class__.__name__}({self.address})"
195
196 async def fetch_device_info(self) -> DeviceInfo:
197 """Fetch condensed device description"""
198 config: dict = await self.get("config")
199 room_type = config.get("RoomType")
200
201 try:
202 # The only required field. Should not really be missing, just a precaution
203 device_id = config["id"]
204 except KeyError as e:
205 raise InvalidAirQResponse from e
206
207 return DeviceInfo(
208 id=device_id,
209 name=config.get("devicename"),
210 model=config.get("type"),
211 suggested_area=room_type.replace("-", " ").title() if room_type else None,
212 sw_version=config.get("air-Q-Software-Version"),
213 hw_version=config.get("air-Q-Hardware-Version"),
214 )
215
216 @staticmethod
217 def drop_uncertainties_from_data(data: dict) -> dict:
218 """Filter returned dict and substitute [value, uncertainty] with the value.
219
220 The device attempts to estimate the uncertainty, or error, of certain readings.
221 These readings are returned as tuples of (value, uncertainty). Often, the latter
222 is not desired, and this is a convenience method to homogenise the dict a little
223 """
224 # `if v else None` is a precaution for the case of v being an empty list
225 # (which ought not to happen really...)
226 return {
227 k: (v[0] if v else None) if isinstance(v, (list, tuple)) else v
228 for k, v in data.items()
229 }
230
231 @staticmethod
232 def clip_negative_values(data: dict) -> dict:
233 def clip(value):
234 if isinstance(value, list):
235 return [max(0, value[0]), value[1]]
236 if isinstance(value, (float, int)):
237 return max(0, value)
238
239 return value
240
241 return {k: clip(v) for k, v in data.items()}
242
243 async def get_latest_data(
244 self,
245 return_average=True,
246 clip_negative_values=True,
247 return_uncertainties=False,
248 ):
249 data = await self.get("average" if return_average else "data")
250 if clip_negative_values:
251 data = self.clip_negative_values(data)
252 if not return_uncertainties:
253 data = self.drop_uncertainties_from_data(data)
254 return data
255
256 async def get(self, subject: str) -> dict:
257 """Return the given subject from the air-Q device.
258
259 This function only works on a limited set of subject specified in _supported_routes.
260 Prefer using more specialized functions."""
261 if subject not in self._supported_routes:
262 raise NotImplementedError(
263 "AirQ.get() is currently limited to a set of requests, returning "
264 f"a dict with a key 'content' (namely {self._supported_routes})."
265 )
266
267 return await self._get_json_and_decode("/" + subject)
268
269 async def _get_json(self, relative_url: str) -> dict:
270 """Executes a GET request to the air-Q device with the configured timeout
271 and returns JSON data as a dictionary.
272
273 relative_url is expected to start with a slash."""
274
275 async with self._session.get(
276 f"{self.anchor}{relative_url}", timeout=self._timeout
277 ) as response:
278 json_string = await response.text()
279
280 try:
281 return json.loads(json_string)
282 except json.JSONDecodeError as e:
283 raise InvalidAirQResponse(
284 "_get_json() must only be used to query endpoints returning JSON data. "
285 f"{relative_url} returned {json_string}."
286 ) from e
287
288 async def _get_json_and_decode(self, relative_url: str) -> Any:
289 """Executes a GET request to the air-Q device with the configured timeout
290 decodes the response and returns JSON data.
291
292 relative_url is expected to start with a slash."""
293
294 json_data = await self._get_json(relative_url)
295
296 encoded_message = json_data["content"]
297 decoded_json_data = self.aes.decode(encoded_message)
298
299 return json.loads(decoded_json_data)
300
301 async def _post_json_and_decode(
302 self, relative_url: str, post_json_data: dict
303 ) -> Any:
304 """Executes a POST request to the air-Q device with the configured timeout,
305 decodes the response and returns JSON data.
306
307 relative_url is expected to start with a slash."""
308
309 headers = {"Content-Type": "application/x-www-form-urlencoded"}
310 post_data = "request=" + self.aes.encode(json.dumps(post_json_data))
311
312 async with self._session.post(
313 f"{self.anchor}{relative_url}",
314 headers=headers,
315 data=post_data,
316 timeout=self._timeout,
317 ) as response:
318 json_string = await response.text()
319
320 try:
321 json_data = json.loads(json_string)
322 except json.JSONDecodeError as e:
323 raise InvalidAirQResponse(
324 "_post_json() must only be used to query endpoints returning JSON data. "
325 f"{relative_url} returned {json_string}."
326 ) from e
327
328 encoded_message = json_data["content"]
329 decoded_json_data = self.aes.decode(encoded_message)
330
331 response_decoded = json.loads(decoded_json_data)
332 if isinstance(response_decoded, str) and response_decoded.startswith("Error"):
333 _lookup_exception_from_firmware_response(response_decoded)
334 return response_decoded
335
336 @property
337 async def data(self):
338 return await self.get("data")
339
340 @property
341 async def average(self):
342 return await self.get("average")
343
344 @property
345 async def config(self):
346 """Deprecated. Use get_config() instead."""
347 return await self.get("config")
348
349 async def set_ifconfig_static(self, ip: str, subnet: str, gateway: str, dns: str):
350 """Configures the interface to use a static IP setup.
351
352 Notice: The air-Q only supports IPv4. After calling this function,
353 you should call restart() to apply the settings."""
354 if not is_valid_ipv4_address(ip):
355 raise InvalidIpAddress(f"Invalid IP address: {ip}")
356 if not is_valid_ipv4_address(subnet):
357 raise InvalidIpAddress(f"Invalid subnet address: {subnet}")
358 if not is_valid_ipv4_address(gateway):
359 raise InvalidIpAddress(f"Invalid gateway address: {gateway}")
360 if not is_valid_ipv4_address(dns):
361 raise InvalidIpAddress(f"Invalid DNS server address: {dns}")
362
363 post_json_data = {
364 "ifconfig": {"ip": ip, "subnet": subnet, "gateway": gateway, "dns": dns}
365 }
366
367 await self._post_json_and_decode("/config", post_json_data)
368
369 async def set_ifconfig_dhcp(self):
370 """Configures the interface to use DHCP.
371
372 Notice: After calling this function, you should call restart() to apply the settings.
373 """
374 post_json_data = {"DeleteKey": "ifconfig"}
375
376 await self._post_json_and_decode("/config", post_json_data)
377
378 async def get_time_server(self):
379 return (await self.get_config())["TimeServer"]
380
381 async def set_time_server(self, time_server):
382 post_json_data = {"TimeServer": time_server}
383
384 try:
385 return await self._post_json_and_decode("/config", post_json_data)
386 except APIAccessDenied:
387 # convert the culprit key as it is used by the firmware
388 # to the name of this specific class method
389 raise APIAccessDenied("set_time_server is only supported for air-Q Science")
390
391 async def get_device_name(self):
392 return (await self.get_config())["devicename"]
393
394 async def set_device_name(self, device_name):
395 post_json_data = {"devicename": device_name}
396
397 await self._post_json_and_decode("/config", post_json_data)
398
399 async def get_cloud_remote(self) -> bool:
400 return (await self._get_json_and_decode("/config"))["cloudRemote"]
401
402 async def set_cloud_remote(self, value: bool):
403 post_json_data = {"cloudRemote": value}
404
405 await self._post_json_and_decode("/config", post_json_data)
406
407 async def get_log(self) -> List[str]:
408 return await self._get_json_and_decode("/log")
409
410 async def get_config(self) -> dict:
411 return await self._get_json_and_decode("/config")
412
413 async def get_possible_led_themes(self) -> List[LedThemeName]:
414 return (await self._get_json_and_decode("/config"))["possibleLedTheme"]
415
416 async def get_led_theme(self) -> DeviceLedTheme:
417 led_theme = (await self._get_json_and_decode("/config"))["ledTheme"]
418
419 return DeviceLedTheme(left=led_theme["left"], right=led_theme["right"])
420
421 async def set_led_theme(self, theme: DeviceLedThemePatch | DeviceLedTheme):
422 # air-Q does not support setting only one side.
423 # If you do this, the API will answer a misleading error like
424 #
425 # ```
426 # Error: unsupported option for key 'ledTheme' - can be ['standard', 'standard (contrast)', ...]
427 # ```
428 #
429 # Therefore, we first read both sides, so we may set both sides at once.
430
431 # I am not too satisfied with the DeviceLedThemePatch|DeviceLedTheme annotation,
432 # necessary to pacify pyright. A better solution would be to use
433 # proper inheritance, I guess, to indicate that DeviceLedTheme is a
434 # subclass of DeviceLedThemePatch. Does not seem to work with TypedDict and
435 # total={True,False}. Consider switching to pydantic
436
437 if len(theme) < 2:
438 current_led_theme = await self.get_led_theme()
439 theme = current_led_theme | theme
440
441 await self._post_json_and_decode("/config", {"ledTheme": theme})
442
443 async def get_night_mode(self) -> NightMode:
444 night_mode = (await self.get_config())["NightMode"]
445
446 return NightMode(
447 activated=night_mode["Activated"],
448 start_day=night_mode["StartDay"],
449 start_night=night_mode["StartNight"],
450 brightness_day=night_mode["BrightnessDay"],
451 brightness_night=night_mode["BrightnessNight"],
452 fan_night_off=night_mode["FanNightOff"],
453 wifi_night_off=night_mode["WifiNightOff"],
454 alarm_night_off=night_mode["AlarmNightOff"],
455 )
456
457 async def set_night_mode(self, night_mode: NightMode):
458 post_json_data = {
459 "NightMode": {
460 "Activated": night_mode["activated"],
461 "StartDay": night_mode["start_day"],
462 "StartNight": night_mode["start_night"],
463 "BrightnessDay": night_mode["brightness_day"],
464 "BrightnessNight": night_mode["brightness_night"],
465 "FanNightOff": night_mode["fan_night_off"],
466 "WifiNightOff": night_mode["wifi_night_off"],
467 "AlarmNightOff": night_mode["alarm_night_off"],
468 }
469 }
470
471 await self._post_json_and_decode("/config", post_json_data)
472
473
474 def _lookup_exception_from_firmware_response(error_message: str):
475 """Ad hoc function attempting to parse the error message.
476
477 Tries to recognise the error message and issue a specific error.
478 If fails, issues an unspecific APIAccessError.
479 """
480 if m := re.match(
481 r"Error: (?P<message>'.*' is only available for air-Q Science)!\n",
482 error_message,
483 ):
484 raise APIAccessDenied(m.groupdict()["message"])
485 else:
486 raise APIAccessError(error_message)