airthings-cloud 0.3.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: airthings_cloud
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A python3 library to communicate with Airthings devices
5
5
  Home-page: https://github.com/Danielhiversen/pyAirthings
6
6
  Author: Daniel Hjelseth Høyer
@@ -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
@@ -0,0 +1,316 @@
1
+ """Support for Airthings sensor."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from dataclasses import dataclass
6
+ from datetime import UTC, datetime
7
+ import json
8
+ import logging
9
+ import time
10
+
11
+ from aiohttp import ClientError
12
+
13
+ _LOGGER = logging.getLogger(__name__)
14
+
15
+ API_URL = "https://consumer-api.airthings.com/v1/"
16
+ TIMEOUT = 10
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
31
+
32
+
33
+ @dataclass
34
+ class AirthingsLocation:
35
+ """Airthings location."""
36
+ location_id: str
37
+ name: str
38
+
39
+ @classmethod
40
+ def init_from_response(cls, response):
41
+ """Class method."""
42
+ return cls(
43
+ response.get("id"),
44
+ response.get("name"),
45
+ )
46
+
47
+
48
+ @dataclass
49
+ class AirthingsDevice:
50
+ """Airthings device."""
51
+ device_id: str
52
+ name: str
53
+ sensors: dict[str, float | None]
54
+ is_active: bool
55
+ location_name: str
56
+ device_type: str | None
57
+ product_name: str | None
58
+ recorded: datetime | None = None
59
+
60
+ @classmethod
61
+ def init_from_response(cls, response, location_name, device):
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"]
70
+ return cls(
71
+ serial_number,
72
+ device.get("name") or serial_number,
73
+ sensors,
74
+ True,
75
+ location_name,
76
+ device.get("type"),
77
+ device.get("productName"),
78
+ _parse_timestamp(response.get("recordedAt")) or _parse_timestamp(response.get("recorded")),
79
+ )
80
+
81
+ @property
82
+ def sensor_types(self):
83
+ """Sensor types."""
84
+ return self.sensors.keys()
85
+
86
+
87
+ class AirthingsError(Exception):
88
+ """General Airthings exception occurred."""
89
+
90
+
91
+ class AirthingsConnectionError(AirthingsError):
92
+ """ConnectionError Airthings occurred."""
93
+
94
+
95
+ class AirthingsAuthError(AirthingsError):
96
+ """AirthingsAuthError Airthings occurred."""
97
+
98
+
99
+ class AirthingsNotFoundError(AirthingsError):
100
+ """Requested resource does not exist or is no longer accessible."""
101
+
102
+
103
+ class Airthings:
104
+ """Airthings data handler."""
105
+
106
+ def __init__(self, client_id, secret, websession):
107
+ """Init Airthings data handler."""
108
+ self._client_id = client_id
109
+ self._secret = secret
110
+ self._websession = websession
111
+ self._access_token = None
112
+ self._accounts: list[str] = []
113
+ self._devices: dict[str, dict[str, dict]] = {}
114
+ self._cache_updated = None
115
+ self._unresolved_accounts: set[str] = set()
116
+ self._unresolved_devices: set[tuple[str, str]] = set()
117
+
118
+ async def _fetch_list(self, path, key):
119
+ response = await self._request(f"{API_URL}{path}?_={time.time_ns()}")
120
+ json_data = await response.json()
121
+ items = json_data.get(key) if isinstance(json_data, dict) else None
122
+ if not isinstance(items, list):
123
+ raise AirthingsError(f"Invalid {key} response from Airthings")
124
+ return items
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
+
166
+ async def _refresh_cache(self):
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
180
+ self._devices = devices
181
+ self._unresolved_accounts = set()
182
+ self._unresolved_devices = set()
183
+ self._cache_updated = time.monotonic()
184
+
185
+ def _cache_expired(self):
186
+ return (
187
+ self._cache_updated is None
188
+ or time.monotonic() - self._cache_updated > CACHE_TTL
189
+ )
190
+
191
+ async def update_devices(self):
192
+ """Update data."""
193
+ refreshed = self._cache_expired()
194
+ if refreshed:
195
+ await self._refresh_cache()
196
+ res = await self._fetch_latest_samples(skip_stale=refreshed)
197
+ if res is None:
198
+ await self._refresh_cache()
199
+ res = await self._fetch_latest_samples(skip_stale=True)
200
+ return res
201
+
202
+ async def _fetch_latest_samples(self, skip_stale):
203
+ """Return None on a new unknown device or inaccessible account unless skip_stale."""
204
+ res = {}
205
+ accounts, devices = self._accounts, self._devices
206
+ inaccessible = 0
207
+ for account_id in accounts:
208
+ try:
209
+ samples = await self._fetch_sensors(account_id)
210
+ except AirthingsNotFoundError as err:
211
+ if not skip_stale and account_id not in self._unresolved_accounts:
212
+ _LOGGER.debug("Account is not accessible (%s), refreshing cache", err)
213
+ return None
214
+ self._unresolved_accounts.add(account_id)
215
+ _LOGGER.debug("Skipping inaccessible account")
216
+ inaccessible += 1
217
+ continue
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)
223
+ return None
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
231
+ )
232
+ if accounts and inaccessible == len(accounts):
233
+ raise AirthingsError("No accessible Airthings account")
234
+ return res
235
+
236
+ async def _request(self, url, retry=3):
237
+ _LOGGER.debug("Request %s %s", url, retry)
238
+ if self._access_token is None:
239
+ self._access_token = await get_token(
240
+ self._websession, self._client_id, self._secret
241
+ )
242
+
243
+ headers = {"Authorization": f"Bearer {self._access_token}"}
244
+ try:
245
+ async with asyncio.timeout(TIMEOUT):
246
+ response = await self._websession.get(url, headers=headers)
247
+ if response.status != 200:
248
+ response.release()
249
+ if response.status in (403, 404):
250
+ raise AirthingsNotFoundError(
251
+ f"No access to {url}, response: {response.status} {response.reason}"
252
+ )
253
+ if response.status != 200:
254
+ if retry > 0 and response.status != 429:
255
+ self._access_token = None
256
+ return await self._request(url, retry=retry - 1)
257
+ _LOGGER.error(
258
+ "Error connecting to Airthings, response: %s %s",
259
+ response.status,
260
+ response.reason,
261
+ )
262
+ raise AirthingsError(
263
+ f"Error connecting to Airthings, response: {response.reason}"
264
+ )
265
+ except ClientError as err:
266
+ self._access_token = None
267
+ _LOGGER.error("Error connecting to Airthings: %s ", err, exc_info=True)
268
+ raise AirthingsError from err
269
+ except asyncio.TimeoutError as err:
270
+ self._access_token = None
271
+ if retry > 0:
272
+ return await self._request(url, retry=retry - 1)
273
+ _LOGGER.error("Timed out when connecting to Airthings")
274
+ raise AirthingsError from err
275
+ return response
276
+
277
+
278
+ async def get_token(websession, client_id, secret, retry=3, timeout=10):
279
+ """Get token for Airthings."""
280
+ try:
281
+ async with asyncio.timeout(timeout):
282
+ response = await websession.post(
283
+ "https://accounts-api.airthings.com/v1/token",
284
+ headers={
285
+ "Content-type": "application/x-www-form-urlencoded",
286
+ "Accept": "application/json",
287
+ },
288
+ data={
289
+ "grant_type": "client_credentials",
290
+ "client_id": client_id,
291
+ "client_secret": secret,
292
+ },
293
+ )
294
+ except ClientError as err:
295
+ if retry > 0:
296
+ return await get_token(websession, client_id, secret, retry - 1, timeout)
297
+ _LOGGER.error("Error getting token Airthings: %s ", err, exc_info=True)
298
+ raise AirthingsConnectionError from err
299
+ except asyncio.TimeoutError as err:
300
+ if retry > 0:
301
+ return await get_token(websession, client_id, secret, retry - 1, timeout)
302
+ _LOGGER.error("Timed out when connecting to Airthings for token")
303
+ raise AirthingsConnectionError from err
304
+ if response.status != 200:
305
+ _LOGGER.error(
306
+ "Airthings: Failed to login to retrieve token: %s %s",
307
+ response.status,
308
+ response.reason,
309
+ )
310
+ raise AirthingsAuthError(f"Failed to login to retrieve token {response.reason}")
311
+ token_data = json.loads(await response.text())
312
+ access_token = token_data.get("access_token")
313
+ if not access_token:
314
+ _LOGGER.error("Airthings: Token response did not contain an access token")
315
+ raise AirthingsAuthError("Token response did not contain an access token")
316
+ return access_token
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: airthings_cloud
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A python3 library to communicate with Airthings devices
5
5
  Home-page: https://github.com/Danielhiversen/pyAirthings
6
6
  Author: Daniel Hjelseth Høyer
@@ -6,4 +6,5 @@ airthings_cloud.egg-info/PKG-INFO
6
6
  airthings_cloud.egg-info/SOURCES.txt
7
7
  airthings_cloud.egg-info/dependency_links.txt
8
8
  airthings_cloud.egg-info/requires.txt
9
- airthings_cloud.egg-info/top_level.txt
9
+ airthings_cloud.egg-info/top_level.txt
10
+ tests/test_airthings.py
@@ -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.3.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",