airthings-cloud 0.3.1__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/PKG-INFO +1 -1
- airthings_cloud-0.4.0/README.md +27 -0
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/airthings/__init__.py +117 -71
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/airthings_cloud.egg-info/PKG-INFO +1 -1
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/setup.py +1 -1
- airthings_cloud-0.4.0/tests/test_airthings.py +840 -0
- airthings_cloud-0.3.1/README.md +0 -6
- airthings_cloud-0.3.1/tests/test_airthings.py +0 -512
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/LICENSE +0 -0
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/airthings_cloud.egg-info/SOURCES.txt +0 -0
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/airthings_cloud.egg-info/dependency_links.txt +0 -0
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/airthings_cloud.egg-info/requires.txt +0 -0
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/airthings_cloud.egg-info/top_level.txt +0 -0
- {airthings_cloud-0.3.1 → airthings_cloud-0.4.0}/setup.cfg +0 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# pyAirthings
|
|
2
|
+
Python library for the [Airthings Consumer API](https://consumer-api-doc.airthings.com/).
|
|
3
|
+
|
|
4
|
+
Create an API client at https://consumer-api-doc.airthings.com/dashboard and use its id and secret:
|
|
5
|
+
|
|
6
|
+
```python
|
|
7
|
+
import asyncio
|
|
8
|
+
|
|
9
|
+
import aiohttp
|
|
10
|
+
from airthings import Airthings
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def main():
|
|
14
|
+
async with aiohttp.ClientSession() as session:
|
|
15
|
+
airthings = Airthings("client_id", "secret", session)
|
|
16
|
+
devices = await airthings.update_devices()
|
|
17
|
+
for serial_number, device in devices.items():
|
|
18
|
+
print(serial_number, device.name, device.sensors)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
asyncio.run(main())
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`update_devices()` returns the devices on the account that have sensors, keyed by serial number, with the latest sensor values.
|
|
25
|
+
|
|
26
|
+
Example usage in Home Assistant:
|
|
27
|
+
https://github.com/home-assistant/core/tree/dev/homeassistant/components/airthings
|
|
@@ -3,6 +3,7 @@ from __future__ import annotations
|
|
|
3
3
|
|
|
4
4
|
import asyncio
|
|
5
5
|
from dataclasses import dataclass
|
|
6
|
+
from datetime import UTC, datetime
|
|
6
7
|
import json
|
|
7
8
|
import logging
|
|
8
9
|
import time
|
|
@@ -11,9 +12,22 @@ from aiohttp import ClientError
|
|
|
11
12
|
|
|
12
13
|
_LOGGER = logging.getLogger(__name__)
|
|
13
14
|
|
|
14
|
-
API_URL = "https://
|
|
15
|
+
API_URL = "https://consumer-api.airthings.com/v1/"
|
|
15
16
|
TIMEOUT = 10
|
|
16
17
|
CACHE_TTL = 3600
|
|
18
|
+
MAX_PAGES = 100
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _parse_timestamp(value) -> datetime | None:
|
|
22
|
+
if not isinstance(value, str):
|
|
23
|
+
return None
|
|
24
|
+
try:
|
|
25
|
+
timestamp = datetime.fromisoformat(value)
|
|
26
|
+
except ValueError:
|
|
27
|
+
return None
|
|
28
|
+
if timestamp.tzinfo is None:
|
|
29
|
+
timestamp = timestamp.replace(tzinfo=UTC)
|
|
30
|
+
return timestamp
|
|
17
31
|
|
|
18
32
|
|
|
19
33
|
@dataclass
|
|
@@ -41,18 +55,27 @@ class AirthingsDevice:
|
|
|
41
55
|
location_name: str
|
|
42
56
|
device_type: str | None
|
|
43
57
|
product_name: str | None
|
|
58
|
+
recorded: datetime | None = None
|
|
44
59
|
|
|
45
60
|
@classmethod
|
|
46
61
|
def init_from_response(cls, response, location_name, device):
|
|
47
|
-
"""
|
|
62
|
+
"""Create a device from a sensors result and its device metadata."""
|
|
63
|
+
serial_number = response["serialNumber"]
|
|
64
|
+
sensors = {}
|
|
65
|
+
for sensor in response.get("sensors") or []:
|
|
66
|
+
if isinstance(sensor, dict) and sensor.get("sensorType"):
|
|
67
|
+
sensors[sensor["sensorType"]] = sensor.get("value")
|
|
68
|
+
if response.get("batteryPercentage") is not None:
|
|
69
|
+
sensors["battery"] = response["batteryPercentage"]
|
|
48
70
|
return cls(
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
71
|
+
serial_number,
|
|
72
|
+
device.get("name") or serial_number,
|
|
73
|
+
sensors,
|
|
74
|
+
True,
|
|
53
75
|
location_name,
|
|
54
|
-
device.get(
|
|
55
|
-
device.get(
|
|
76
|
+
device.get("type"),
|
|
77
|
+
device.get("productName"),
|
|
78
|
+
_parse_timestamp(response.get("recordedAt")) or _parse_timestamp(response.get("recorded")),
|
|
56
79
|
)
|
|
57
80
|
|
|
58
81
|
@property
|
|
@@ -86,40 +109,77 @@ class Airthings:
|
|
|
86
109
|
self._secret = secret
|
|
87
110
|
self._websession = websession
|
|
88
111
|
self._access_token = None
|
|
89
|
-
self.
|
|
90
|
-
self._devices = {}
|
|
112
|
+
self._accounts: list[str] = []
|
|
113
|
+
self._devices: dict[str, dict[str, dict]] = {}
|
|
91
114
|
self._cache_updated = None
|
|
92
|
-
self.
|
|
93
|
-
|
|
94
|
-
async def _fetch_locations(self):
|
|
95
|
-
return [
|
|
96
|
-
AirthingsLocation.init_from_response(location)
|
|
97
|
-
for location in await self._fetch_list("locations")
|
|
98
|
-
]
|
|
115
|
+
self._unresolved_accounts: set[str] = set()
|
|
116
|
+
self._unresolved_devices: set[tuple[str, str]] = set()
|
|
99
117
|
|
|
100
|
-
async def
|
|
101
|
-
|
|
102
|
-
for device in await self._fetch_list("devices"):
|
|
103
|
-
if not isinstance(device, dict) or "id" not in device:
|
|
104
|
-
_LOGGER.debug("Skipping device metadata entry without id")
|
|
105
|
-
continue
|
|
106
|
-
devices[device["id"]] = device
|
|
107
|
-
return devices
|
|
108
|
-
|
|
109
|
-
async def _fetch_list(self, key):
|
|
110
|
-
response = await self._request(API_URL + key)
|
|
118
|
+
async def _fetch_list(self, path, key):
|
|
119
|
+
response = await self._request(f"{API_URL}{path}?_={time.time_ns()}")
|
|
111
120
|
json_data = await response.json()
|
|
112
121
|
items = json_data.get(key) if isinstance(json_data, dict) else None
|
|
113
122
|
if not isinstance(items, list):
|
|
114
123
|
raise AirthingsError(f"Invalid {key} response from Airthings")
|
|
115
124
|
return items
|
|
116
125
|
|
|
126
|
+
async def _fetch_accounts(self):
|
|
127
|
+
items = await self._fetch_list("accounts", "accounts")
|
|
128
|
+
accounts = []
|
|
129
|
+
for account in items:
|
|
130
|
+
if not isinstance(account, dict) or not account.get("id"):
|
|
131
|
+
_LOGGER.debug("Skipping account without id")
|
|
132
|
+
continue
|
|
133
|
+
accounts.append(account["id"])
|
|
134
|
+
if items and not accounts:
|
|
135
|
+
raise AirthingsError("Invalid accounts response from Airthings")
|
|
136
|
+
return accounts
|
|
137
|
+
|
|
138
|
+
async def _fetch_devices(self, account_id):
|
|
139
|
+
devices = {}
|
|
140
|
+
for device in await self._fetch_list(f"accounts/{account_id}/devices", "devices"):
|
|
141
|
+
if not isinstance(device, dict) or not device.get("serialNumber"):
|
|
142
|
+
_LOGGER.debug("Skipping device metadata entry without serial number")
|
|
143
|
+
continue
|
|
144
|
+
devices[device["serialNumber"]] = device
|
|
145
|
+
return devices
|
|
146
|
+
|
|
147
|
+
async def _fetch_sensors(self, account_id):
|
|
148
|
+
samples = {}
|
|
149
|
+
for page in range(1, MAX_PAGES + 1):
|
|
150
|
+
response = await self._request(
|
|
151
|
+
API_URL + f"accounts/{account_id}/sensors?unit=metric&pageNumber={page}"
|
|
152
|
+
)
|
|
153
|
+
json_data = await response.json()
|
|
154
|
+
results = json_data.get("results") if isinstance(json_data, dict) else None
|
|
155
|
+
if not isinstance(results, list):
|
|
156
|
+
raise AirthingsError("Invalid sensors response from Airthings")
|
|
157
|
+
for result in results:
|
|
158
|
+
if not isinstance(result, dict) or not result.get("serialNumber"):
|
|
159
|
+
_LOGGER.debug("Skipping sensors result without serial number")
|
|
160
|
+
continue
|
|
161
|
+
samples[result["serialNumber"]] = result
|
|
162
|
+
if json_data.get("hasNext") is not True or not results:
|
|
163
|
+
return samples
|
|
164
|
+
raise AirthingsError(f"More than {MAX_PAGES} pages of sensors from Airthings")
|
|
165
|
+
|
|
117
166
|
async def _refresh_cache(self):
|
|
118
|
-
|
|
119
|
-
devices =
|
|
120
|
-
|
|
167
|
+
accounts = await self._fetch_accounts()
|
|
168
|
+
devices = {}
|
|
169
|
+
accessible = []
|
|
170
|
+
for account_id in accounts:
|
|
171
|
+
try:
|
|
172
|
+
devices[account_id] = await self._fetch_devices(account_id)
|
|
173
|
+
except AirthingsNotFoundError:
|
|
174
|
+
_LOGGER.debug("Skipping account without access to its devices")
|
|
175
|
+
continue
|
|
176
|
+
accessible.append(account_id)
|
|
177
|
+
if accounts and not accessible:
|
|
178
|
+
raise AirthingsError("No accessible Airthings account")
|
|
179
|
+
self._accounts = accessible
|
|
121
180
|
self._devices = devices
|
|
122
|
-
self.
|
|
181
|
+
self._unresolved_accounts = set()
|
|
182
|
+
self._unresolved_devices = set()
|
|
123
183
|
self._cache_updated = time.monotonic()
|
|
124
184
|
|
|
125
185
|
def _cache_expired(self):
|
|
@@ -140,51 +200,37 @@ class Airthings:
|
|
|
140
200
|
return res
|
|
141
201
|
|
|
142
202
|
async def _fetch_latest_samples(self, skip_stale):
|
|
143
|
-
"""Return None on a new unknown
|
|
203
|
+
"""Return None on a new unknown device or inaccessible account unless skip_stale."""
|
|
144
204
|
res = {}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
205
|
+
accounts, devices = self._accounts, self._devices
|
|
206
|
+
inaccessible = 0
|
|
207
|
+
for account_id in accounts:
|
|
148
208
|
try:
|
|
149
|
-
|
|
150
|
-
API_URL + f"/locations/{location.location_id}/latest-samples"
|
|
151
|
-
)
|
|
209
|
+
samples = await self._fetch_sensors(account_id)
|
|
152
210
|
except AirthingsNotFoundError as err:
|
|
153
|
-
if not skip_stale and
|
|
154
|
-
_LOGGER.debug(
|
|
155
|
-
"Location '%s' is not accessible (%s), refreshing cache",
|
|
156
|
-
location.name,
|
|
157
|
-
err,
|
|
158
|
-
)
|
|
211
|
+
if not skip_stale and account_id not in self._unresolved_accounts:
|
|
212
|
+
_LOGGER.debug("Account is not accessible (%s), refreshing cache", err)
|
|
159
213
|
return None
|
|
160
|
-
self.
|
|
161
|
-
_LOGGER.debug("Skipping inaccessible
|
|
162
|
-
|
|
163
|
-
json_data = await response.json()
|
|
164
|
-
devices = json_data.get("devices") if isinstance(json_data, dict) else None
|
|
165
|
-
if not devices:
|
|
166
|
-
_LOGGER.debug("No devices in location '%s'", location.name)
|
|
214
|
+
self._unresolved_accounts.add(account_id)
|
|
215
|
+
_LOGGER.debug("Skipping inaccessible account")
|
|
216
|
+
inaccessible += 1
|
|
167
217
|
continue
|
|
168
|
-
for
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if device_id not in self._devices:
|
|
174
|
-
if not skip_stale and device_id not in self._unresolved:
|
|
175
|
-
_LOGGER.debug(
|
|
176
|
-
"Unknown device '%s' in location '%s', refreshing cache",
|
|
177
|
-
device_id,
|
|
178
|
-
location.name,
|
|
179
|
-
)
|
|
218
|
+
for serial_number, sample in samples.items():
|
|
219
|
+
device = devices[account_id].get(serial_number)
|
|
220
|
+
if device is None:
|
|
221
|
+
if not skip_stale and (account_id, serial_number) not in self._unresolved_devices:
|
|
222
|
+
_LOGGER.debug("Unknown device '%s', refreshing cache", serial_number)
|
|
180
223
|
return None
|
|
181
|
-
self.
|
|
182
|
-
_LOGGER.debug("
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
224
|
+
self._unresolved_devices.add((account_id, serial_number))
|
|
225
|
+
_LOGGER.debug("Skipping device '%s' missing from the device list", serial_number)
|
|
226
|
+
continue
|
|
227
|
+
if device.get("sensors") == []:
|
|
228
|
+
continue
|
|
229
|
+
res[serial_number] = AirthingsDevice.init_from_response(
|
|
230
|
+
sample, device.get("home") or "", device
|
|
187
231
|
)
|
|
232
|
+
if accounts and inaccessible == len(accounts):
|
|
233
|
+
raise AirthingsError("No accessible Airthings account")
|
|
188
234
|
return res
|
|
189
235
|
|
|
190
236
|
async def _request(self, url, retry=3):
|
|
@@ -194,7 +240,7 @@ class Airthings:
|
|
|
194
240
|
self._websession, self._client_id, self._secret
|
|
195
241
|
)
|
|
196
242
|
|
|
197
|
-
headers = {"Authorization": self._access_token}
|
|
243
|
+
headers = {"Authorization": f"Bearer {self._access_token}"}
|
|
198
244
|
try:
|
|
199
245
|
async with asyncio.timeout(TIMEOUT):
|
|
200
246
|
response = await self._websession.get(url, headers=headers)
|
|
@@ -4,7 +4,7 @@ setup(
|
|
|
4
4
|
name="airthings_cloud",
|
|
5
5
|
packages=["airthings"],
|
|
6
6
|
install_requires=["aiohttp>=3.13.0"],
|
|
7
|
-
version="0.
|
|
7
|
+
version="0.4.0",
|
|
8
8
|
description="A python3 library to communicate with Airthings devices",
|
|
9
9
|
python_requires=">=3.13.0",
|
|
10
10
|
author="Daniel Hjelseth Høyer",
|