Debian Codegraph @

foobot_async/__init__.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 from math import trunc
2 from datetime import timezone
3 import asyncio
4 import aiohttp
5 import async_timeout
6
7 BASE_URL = "https://api.foobot.io/v2/"
8 DEVICE_URL = BASE_URL + 'owner/{username}/device/'
9 LAST_DATA_URL = BASE_URL + \
10 "device/{uuid}/datapoint/{period:d}/last/{average_by:d}/"
11 HISTORICAL_DATA_URL = BASE_URL + \
12 "device/{uuid}/datapoint/{start:d}/{end:d}/{average_by:d}/"
13
14
15 class FoobotClient():
16 """
17 Foobot API client
18
19 :param token: API secret key used for authentication, see main doc on how
20 to obtain one
21 :type token: str
22 :param username: Your username for your Foobot account
23 :type username: str
24 :param session: aiohttp session to use or None
25 :type session: object or None
26 :param timeout: seconds to wait for before triggering a timeout
27 :type timeout: integer
28 """
29
30 def __init__(self, token, username, session=None,
31 timeout=aiohttp.client.DEFAULT_TIMEOUT.total):
32 """
33 Creates a new :class:`FoobotClient` instance.
34 """
35 self._headers = {'X-API-KEY-TOKEN': token,
36 'content-type': 'application/json'}
37 self._username = username
38 self._timeout = timeout
39 if session is not None:
40 self._session = session
41
42 async def get_devices(self):
43 """
44 Get a list of devices associated with that account.
45
46 :returns: list of devices
47 :raises: ClientError, AuthFailure, BadFormat, ForbiddenAccess,
48 TooManyRequests, InternalError
49
50 .. note::
51 each device returned will be a dictionary with the following data:
52 * uuid: id of the device, used for querying data from them.
53 Not actually a UUID.
54 * userId: id of the user
55 * mac: MAC of the device, non colon seperated
56 (eg: "013843C3C20A")
57 * name: Name of the device as configured in the app
58 """
59 return (await self._get(DEVICE_URL.format(
60 username=self._username)))
61
62 async def get_last_data(self, uuid, period=0, average_by=0):
63 """
64 Get the data from one device for period till now.
65
66 :param uuid: Id of the device
67 :type uuid: str
68 :param period: Number of seconds between start time of search and now
69 :type period: integer
70 :param average_by: amount of seconds to average data over.
71 0 or 300 for no average. Use 3600 (average hourly) or a multiple
72 for long range requests (e.g. more than 1 day)
73 :type average_by: integer
74 :returns: list of datapoints
75 :raises: ClientError, AuthFailure, BadFormat, ForbiddenAccess,
76 TooManyRequests, InternalError
77
78 .. note::
79 Use period = 0 and averageBy = 0 to get the very last data point.
80 If you only need one average for a period, the average_by needs to
81 be bigger than the period (eg, for a 10 minutes average:
82 period = 600, average_by = 601)
83
84 .. seealso:: :func:`parse_data` for return data syntax
85 """
86 return self.parse_data((await self._get(
87 LAST_DATA_URL.format(uuid=uuid,
88 period=trunc(period),
89 average_by=trunc(average_by)))))
90
91 async def get_historical_data(self, uuid, start, end, average_by=0):
92 """
93 Get the data from one device for a specified time range.
94
95 .. note::
96 Can fetch a maximum of 42 days of data.
97 To speed up query processing, you can use a combination of average
98 factor multiple of 1H in seconds (e.g. 3600)
99 and o'clock start and end times
100
101 :param uuid: Id of the device
102 :type uuid: str
103 :param start: start of the range
104 :type start: datetime
105 :param end: end of the range
106 :type end: datetime
107 :param average_by: amount of seconds to average data over.
108 0 or 300 for no average. Use 3600 (average hourly) or a multiple
109 for long range requests (e.g. more than 1 day)
110 :type average_by: integer
111 :returns: list of datapoints
112 :raises: ClientError, AuthFailure, BadFormat, ForbiddenAccess,
113 TooManyRequests, InternalError
114
115 .. seealso:: :func:`parse_data` for return data syntax
116 """
117 return self.parse_data((await self._get(
118 HISTORICAL_DATA_URL.format(
119 uuid=uuid,
120 start=trunc(start.replace(tzinfo=timezone.utc).timestamp()),
121 end=trunc(end.replace(tzinfo=timezone.utc).timestamp()),
122 average_by=trunc(average_by)))))
123
124 def parse_data(self, response):
125 """
126 Convert the weird list format used for datapoints to a more usable
127 dictionnary one
128
129 :param response: dictionnary from API json response
130 :type response: dict
131 :returns: list of datapoints
132
133 .. note::
134 Datapoint content:
135 * time: UTC timestamp, unit: seconds
136 * pm: Particulate Matter, unit: ugm3
137 * tmp: temperature, unit: C
138 * hum: humidity, unit: %
139 * co2: Carbon Dioxide, unit: ppm
140 * voc: Volatile Organic Compounds, unit: ppb
141 * allpollu: `foobot index <https://help.foobot.io/hc/en-us/articles/204814371-What-does-central-number-mean->`_, unit: %
142 """
143 parsed = []
144 try:
145 items = response['sensors']
146 for datapoint in response['datapoints']:
147 line = {}
148 for index, data in enumerate(datapoint):
149 line[items[index]] = data
150 parsed.append(line)
151 return parsed
152 except (KeyError, IndexError, TypeError):
153 raise FoobotClient.InvalidData()
154
155 async def _get(self, path, **kwargs):
156 if not hasattr(self, '_session'):
157 self._session = aiohttp.ClientSession()
158 with async_timeout.timeout(self._timeout):
159 resp = await self._session.get(
160 path, headers=dict(self._headers, **kwargs))
161 resp_text = await resp.text()
162 if resp.status == 400:
163 raise FoobotClient.BadFormat(resp_text)
164 elif resp.status == 401:
165 raise FoobotClient.AuthFailure(resp_text)
166 elif resp.status == 403:
167 raise FoobotClient.ForbiddenAccess(resp_text)
168 elif resp.status == 429:
169 raise FoobotClient.TooManyRequests(resp_text)
170 elif resp.status == 500:
171 raise FoobotClient.InternalError(resp_text)
172 elif resp.status != 200:
173 raise FoobotClient.ClientError(resp_text)
174 return (await resp.json())
175
176 class ClientError(Exception):
177 """Generic Error."""
178 pass
179
180 class AuthFailure(ClientError):
181 """Failed Authentication."""
182 pass
183
184 class BadFormat(ClientError):
185 """Request is malformed."""
186 pass
187
188 class ForbiddenAccess(ClientError):
189 """Access is prohibited."""
190 pass
191
192 class TooManyRequests(ClientError):
193 """Too many requests for this time period."""
194 pass
195
196 class InternalError(ClientError):
197 """Server Internal Error."""
198 pass
199
200 class InvalidData(ClientError):
201 """Can't parse response data."""
202 pass