|
1 | 1 | """Class to describe an Awair device.""" |
2 | 2 |
|
3 | 3 | import urllib |
| 4 | +from abc import ABC, abstractmethod |
4 | 5 | from datetime import datetime, timedelta |
5 | | -from typing import Any, Dict, List, Optional, Union |
| 6 | +from typing import Any, Dict, List, Optional, Union, cast |
6 | 7 |
|
7 | 8 | import voluptuous as vol |
8 | 9 |
|
|
13 | 14 | AirDataParam = Union[datetime, bool, int, None] |
14 | 15 |
|
15 | 16 |
|
16 | | -class AwairDevice: |
| 17 | +class AwairBaseDevice(ABC): |
17 | 18 | """An Awair device. |
18 | 19 |
|
19 | 20 | This class serves two purposes - it provides metadata about |
@@ -336,17 +337,25 @@ async def air_data_raw(self, **kwargs: AirDataParam) -> List[AirData]: |
336 | 337 | """ |
337 | 338 | return await self.__get_airdata("raw", **kwargs) |
338 | 339 |
|
| 340 | + @abstractmethod |
| 341 | + def _get_airdata_base_url(self) -> str: |
| 342 | + """Get the base URL to use for airdata.""" |
| 343 | + raise TypeError("expected subclass to define override") |
| 344 | + |
| 345 | + @abstractmethod |
| 346 | + def _extract_airdata(self, response: Any) -> List[Any]: |
| 347 | + """Get the data object out of a response.""" |
| 348 | + raise TypeError("expected subclass to define override") |
| 349 | + |
339 | 350 | async def __get_airdata(self, kind: str, **kwargs: AirDataParam) -> List[AirData]: |
340 | 351 | """Call one of several varying air-data API endpoints.""" |
341 | | - url = "/".join( |
342 | | - [const.DEVICE_URL, self.device_type, str(self.device_id), "air-data", kind] |
343 | | - ) |
| 352 | + url = "/".join([self._get_airdata_base_url(), "air-data", kind]) |
344 | 353 |
|
345 | 354 | if kwargs is not None: |
346 | 355 | url += self._format_args(kind, **kwargs) |
347 | 356 |
|
348 | 357 | response = await self.client.query(url) |
349 | | - return [AirData(data) for data in response.get("data", [])] |
| 358 | + return [AirData(data) for data in self._extract_airdata(response)] |
350 | 359 |
|
351 | 360 | @staticmethod |
352 | 361 | def _format_args(kind: str, **kwargs: AirDataParam) -> str: |
@@ -407,3 +416,70 @@ def validate_hours(params: Dict[str, Any]) -> Dict[str, Any]: |
407 | 416 | return "?" + urllib.parse.urlencode(args) |
408 | 417 |
|
409 | 418 | return "" |
| 419 | + |
| 420 | + |
| 421 | +class AwairDevice(AwairBaseDevice): |
| 422 | + """A cloud-based Awair device.""" |
| 423 | + |
| 424 | + def _get_airdata_base_url(self) -> str: |
| 425 | + """Get the base URL to use for airdata.""" |
| 426 | + return "/".join([const.DEVICE_URL, self.device_type, str(self.device_id)]) |
| 427 | + |
| 428 | + def _extract_airdata(self, response: Any) -> List[Any]: |
| 429 | + """Get the data object out of a response.""" |
| 430 | + return cast(List[Any], response.get("data", [])) |
| 431 | + |
| 432 | + |
| 433 | +class AwairLocalDevice(AwairBaseDevice): |
| 434 | + """A local Awair device.""" |
| 435 | + |
| 436 | + device_addr: str |
| 437 | + """The DNS or IP address of the device.""" |
| 438 | + |
| 439 | + def __init__( |
| 440 | + self, client: AwairClient, device_addr: str, attributes: Dict[str, Any] |
| 441 | + ): |
| 442 | + """Initialize an awair local device from API attributes.""" |
| 443 | + # the format of the config endpoint for local sensors is different than |
| 444 | + # the cloud API. |
| 445 | + device_uuid: str = attributes["device_uuid"] |
| 446 | + [device_type, device_id_str] = device_uuid.split("_", 1) |
| 447 | + device_id = int(device_id_str) |
| 448 | + attributes["deviceId"] = device_id |
| 449 | + attributes["deviceUUID"] = device_uuid |
| 450 | + attributes["deviceType"] = device_type |
| 451 | + attributes["macAddress"] = attributes.get("wifi_mac", None) |
| 452 | + super().__init__(client, attributes) |
| 453 | + self.device_addr = device_addr |
| 454 | + |
| 455 | + def _get_airdata_base_url(self) -> str: |
| 456 | + """Get the base URL to use for airdata.""" |
| 457 | + return f"http://{self.device_addr}" |
| 458 | + |
| 459 | + def _extract_airdata(self, response: Any) -> List[Any]: |
| 460 | + """Get the data object out of a response.""" |
| 461 | + # reformat local sensors response to match the cloud API |
| 462 | + top_level = {"timestamp", "score"} |
| 463 | + sensors = [ |
| 464 | + {"comp": k, "value": response[k]} |
| 465 | + for k in response.keys() |
| 466 | + if k not in top_level |
| 467 | + ] |
| 468 | + data = { |
| 469 | + "timestamp": response["timestamp"], |
| 470 | + "score": response["score"], |
| 471 | + "sensors": sensors, |
| 472 | + } |
| 473 | + |
| 474 | + return [data] |
| 475 | + |
| 476 | + @staticmethod |
| 477 | + def _format_args(kind: str, **kwargs: AirDataParam) -> str: |
| 478 | + if "fahrenheit" in kwargs: |
| 479 | + if kwargs["fahrenheit"]: |
| 480 | + raise ValueError("fahrenheit is not supported for local sensors yet") |
| 481 | + # if we pass any URL parameters with local sensors, it causes the |
| 482 | + # timestamp to be the empty string. |
| 483 | + del kwargs["fahrenheit"] |
| 484 | + |
| 485 | + return AwairBaseDevice._format_args(kind, **kwargs) |
0 commit comments