Debian Codegraph @

airthings/__init__.py

raw symbols SCIP
1 """Support for Airthings sensor."""
2 from __future__ import annotations
3
4 import asyncio
5 from dataclasses import dataclass
6 import json
7 import logging
8
9 from aiohttp import ClientError
10
11 _LOGGER = logging.getLogger(__name__)
12
13 API_URL = "https://ext-api.airthings.com/v1/"
14 TIMEOUT = 10
15
16
17 @dataclass
18 class AirthingsLocation:
19 """Airthings location."""
20 location_id: str
21 name: str
22
23 @classmethod
24 def init_from_response(cls, response):
25 """Class method."""
26 return cls(
27 response.get("id"),
28 response.get("name"),
29 )
30
31
32 @dataclass
33 class AirthingsDevice:
34 """Airthings device."""
35 device_id: str
36 name: str
37 sensors: dict[str, float | None]
38 is_active: bool
39 location_name: str
40 device_type: str | None
41 product_name: str | None
42
43 @classmethod
44 def init_from_response(cls, response, location_name, device):
45 """Class method."""
46 return cls(
47 response.get("id"),
48 response.get("segment").get("name"),
49 response.get("data"),
50 response.get("segment").get("isActive"),
51 location_name,
52 device.get('deviceType'),
53 device.get('productName'),
54 )
55
56 @property
57 def sensor_types(self):
58 """Sensor types."""
59 return self.sensors.keys()
60
61
62 class AirthingsError(Exception):
63 """General Airthings exception occurred."""
64
65
66 class AirthingsConnectionError(AirthingsError):
67 """ConnectionError Airthings occurred."""
68
69
70 class AirthingsAuthError(AirthingsError):
71 """AirthingsAuthError Airthings occurred."""
72
73
74 class Airthings:
75 """Airthings data handler."""
76
77 def __init__(self, client_id, secret, websession):
78 """Init Airthings data handler."""
79 self._client_id = client_id
80 self._secret = secret
81 self._websession = websession
82 self._access_token = None
83 self._locations = []
84 self._devices = {}
85
86 async def _fetch_locations(self):
87 response = await self._request(API_URL + "locations")
88 json_data = await response.json()
89 self._locations = []
90 for location in json_data.get("locations"):
91 self._locations.append(AirthingsLocation.init_from_response(location))
92
93 async def update_devices(self):
94 """Update data."""
95 locations_fetched = False
96
97 if not self._locations:
98 await self._fetch_locations()
99 locations_fetched = True
100 if not self._devices:
101 response = await self._request(API_URL + "devices")
102 json_data = await response.json()
103 self._devices = {}
104 for device in json_data.get("devices"):
105 self._devices[device['id']] = device
106 res = {}
107 for location in self._locations:
108 if not location.location_id:
109 continue
110 response = await self._request(
111 API_URL + f"/locations/{location.location_id}/latest-samples"
112 )
113 if response is None:
114 continue
115 json_data = await response.json()
116 if json_data is None:
117 continue
118 if devices := json_data.get("devices"):
119 for device in devices:
120 if not isinstance(device, dict) or 'id' not in device:
121 if not locations_fetched:
122 _LOGGER.debug("Device has no id, fetching locations again")
123 await self._fetch_locations()
124 locations_fetched = True
125 device_id = device.get('id')
126 res[device_id] = AirthingsDevice.init_from_response(
127 device,
128 location.name,
129 self._devices.get(device_id)
130 )
131 else:
132 _LOGGER.debug("No devices in location '%s'", location.name)
133 return res
134
135 async def _request(self, url, json_data=None, retry=3):
136 _LOGGER.debug("Request %s %s, %s", url, retry, json_data)
137 if self._access_token is None:
138 self._access_token = await get_token(
139 self._websession, self._client_id, self._secret
140 )
141 if self._access_token is None:
142 return None
143
144 headers = {"Authorization": self._access_token}
145 try:
146 async with asyncio.timeout(TIMEOUT):
147 if json_data:
148 response = await self._websession.post(
149 url, json=json_data, headers=headers
150 )
151 else:
152 response = await self._websession.get(url, headers=headers)
153 if response.status != 200:
154 if retry > 0 and response.status != 429:
155 self._access_token = None
156 return await self._request(url, json_data, retry=retry - 1)
157 _LOGGER.error(
158 "Error connecting to Airthings, response: %s %s",
159 response.status,
160 response.reason,
161 )
162 raise AirthingsError(
163 f"Error connecting to Airthings, response: {response.reason}"
164 )
165 except ClientError as err:
166 self._access_token = None
167 _LOGGER.error("Error connecting to Airthings: %s ", err, exc_info=True)
168 raise AirthingsError from err
169 except asyncio.TimeoutError as err:
170 self._access_token = None
171 if retry > 0:
172 return await self._request(url, json_data, retry=retry - 1)
173 _LOGGER.error("Timed out when connecting to Airthings")
174 raise AirthingsError from err
175 return response
176
177
178 async def get_token(websession, client_id, secret, retry=3, timeout=10):
179 """Get token for Airthings."""
180 try:
181 async with asyncio.timeout(timeout):
182 response = await websession.post(
183 "https://accounts-api.airthings.com/v1/token",
184 headers={
185 "Content-type": "application/x-www-form-urlencoded",
186 "Accept": "application/json",
187 },
188 data={
189 "grant_type": "client_credentials",
190 "client_id": client_id,
191 "client_secret": secret,
192 },
193 )
194 except ClientError as err:
195 if retry > 0:
196 return await get_token(websession, client_id, secret, retry - 1, timeout)
197 _LOGGER.error("Error getting token Airthings: %s ", err, exc_info=True)
198 raise AirthingsConnectionError from err
199 except asyncio.TimeoutError as err:
200 if retry > 0:
201 return await get_token(websession, client_id, secret, retry - 1, timeout)
202 _LOGGER.error("Timed out when connecting to Airthings for token")
203 raise AirthingsConnectionError from err
204 if response.status != 200:
205 _LOGGER.error(
206 "Airthings: Failed to login to retrieve token: %s %s",
207 response.status,
208 response.reason,
209 )
210 raise AirthingsAuthError(f"Failed to login to retrieve token {response.reason}")
211 token_data = json.loads(await response.text())
212 return token_data.get("access_token")