aiomapit 0.1.0__py3-none-any.whl
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.
- aiomapit/__init__.py +57 -0
- aiomapit/_version.py +4 -0
- aiomapit/client.py +413 -0
- aiomapit/exceptions.py +68 -0
- aiomapit/models.py +329 -0
- aiomapit/py.typed +0 -0
- aiomapit-0.1.0.dist-info/METADATA +145 -0
- aiomapit-0.1.0.dist-info/RECORD +10 -0
- aiomapit-0.1.0.dist-info/WHEEL +4 -0
- aiomapit-0.1.0.dist-info/licenses/LICENSE +21 -0
aiomapit/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Async Python client for the Mapit API."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .client import DEFAULT_BASE_URL, MapitClient, TokenProvider
|
|
5
|
+
from .exceptions import (
|
|
6
|
+
MapitAuthError,
|
|
7
|
+
MapitConnectionError,
|
|
8
|
+
MapitError,
|
|
9
|
+
MapitNotFound,
|
|
10
|
+
MapitRateLimited,
|
|
11
|
+
MapitResponseError,
|
|
12
|
+
MapitScopeError,
|
|
13
|
+
)
|
|
14
|
+
from .models import (
|
|
15
|
+
Account,
|
|
16
|
+
Connection,
|
|
17
|
+
DeviceState,
|
|
18
|
+
IncomingTransfer,
|
|
19
|
+
Page,
|
|
20
|
+
Response,
|
|
21
|
+
RideDay,
|
|
22
|
+
RideStats,
|
|
23
|
+
RideTotals,
|
|
24
|
+
Route,
|
|
25
|
+
Subscription,
|
|
26
|
+
Summary,
|
|
27
|
+
Vehicle,
|
|
28
|
+
VehicleStatus,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"DEFAULT_BASE_URL",
|
|
33
|
+
"Account",
|
|
34
|
+
"Connection",
|
|
35
|
+
"DeviceState",
|
|
36
|
+
"IncomingTransfer",
|
|
37
|
+
"MapitAuthError",
|
|
38
|
+
"MapitClient",
|
|
39
|
+
"MapitConnectionError",
|
|
40
|
+
"MapitError",
|
|
41
|
+
"MapitNotFound",
|
|
42
|
+
"MapitRateLimited",
|
|
43
|
+
"MapitResponseError",
|
|
44
|
+
"MapitScopeError",
|
|
45
|
+
"Page",
|
|
46
|
+
"Response",
|
|
47
|
+
"RideDay",
|
|
48
|
+
"RideStats",
|
|
49
|
+
"RideTotals",
|
|
50
|
+
"Route",
|
|
51
|
+
"Subscription",
|
|
52
|
+
"Summary",
|
|
53
|
+
"TokenProvider",
|
|
54
|
+
"Vehicle",
|
|
55
|
+
"VehicleStatus",
|
|
56
|
+
"__version__",
|
|
57
|
+
]
|
aiomapit/_version.py
ADDED
aiomapit/client.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""Async client for the Mapit API (https://api.mapit.me/v1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
9
|
+
from datetime import date, datetime
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
from typing import Any, Self
|
|
12
|
+
from urllib.parse import quote, urlencode
|
|
13
|
+
|
|
14
|
+
import aiohttp
|
|
15
|
+
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
from .exceptions import (
|
|
18
|
+
MapitAuthError,
|
|
19
|
+
MapitConnectionError,
|
|
20
|
+
MapitError,
|
|
21
|
+
MapitNotFound,
|
|
22
|
+
MapitRateLimited,
|
|
23
|
+
MapitResponseError,
|
|
24
|
+
MapitScopeError,
|
|
25
|
+
)
|
|
26
|
+
from .models import (
|
|
27
|
+
Account,
|
|
28
|
+
Connection,
|
|
29
|
+
Page,
|
|
30
|
+
Response,
|
|
31
|
+
RideStats,
|
|
32
|
+
Route,
|
|
33
|
+
Subscription,
|
|
34
|
+
Summary,
|
|
35
|
+
Vehicle,
|
|
36
|
+
VehicleStatus,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
DEFAULT_BASE_URL = "https://api.mapit.me/v1"
|
|
40
|
+
CACHE_SIZE = 256
|
|
41
|
+
|
|
42
|
+
TokenProvider = Callable[[], Awaitable[str]]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _param(value: object) -> str:
|
|
46
|
+
if isinstance(value, bool):
|
|
47
|
+
return "true" if value else "false"
|
|
48
|
+
if isinstance(value, datetime):
|
|
49
|
+
if value.tzinfo is None:
|
|
50
|
+
raise ValueError("datetimes need a timezone offset")
|
|
51
|
+
return value.isoformat()
|
|
52
|
+
if isinstance(value, date):
|
|
53
|
+
return value.isoformat()
|
|
54
|
+
return str(value)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _problem(body: bytes) -> tuple[str | None, str | None]:
|
|
58
|
+
try:
|
|
59
|
+
data = json.loads(body)
|
|
60
|
+
except ValueError:
|
|
61
|
+
return None, None
|
|
62
|
+
if not isinstance(data, dict):
|
|
63
|
+
return None, None
|
|
64
|
+
title, detail = data.get("title"), data.get("detail")
|
|
65
|
+
return (title if isinstance(title, str) else None, detail if isinstance(detail, str) else None)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _retry_after(value: str | None) -> float | None:
|
|
69
|
+
try:
|
|
70
|
+
return float(value) if value is not None else None
|
|
71
|
+
except ValueError:
|
|
72
|
+
return None # an HTTP date: the caller can use its own back-off
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _missing_scope(www_authenticate: str, detail: str | None) -> str | None:
|
|
76
|
+
# The server lists "mapit:read <missing scope>": the missing one is last.
|
|
77
|
+
if (m := re.search(r'scope="([^"]*)"', www_authenticate)) and m.group(1).split():
|
|
78
|
+
return m.group(1).split()[-1]
|
|
79
|
+
if detail and (m := re.search(r"not given (\S+?)\.?$", detail)):
|
|
80
|
+
return m.group(1)
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class MapitClient:
|
|
85
|
+
"""Read-only client for one Mapit account.
|
|
86
|
+
|
|
87
|
+
``token`` is a personal key, or an async callable returning a valid access token
|
|
88
|
+
(called before every request, so it may refresh). Pass an ``aiohttp.ClientSession``
|
|
89
|
+
to share one; without it the client creates its own and closes it in :meth:`close`.
|
|
90
|
+
|
|
91
|
+
Reads send ``If-None-Match`` for what they fetched before. On 304 the cached object is
|
|
92
|
+
returned with ``Response.not_modified`` set.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
token: str | TokenProvider,
|
|
98
|
+
*,
|
|
99
|
+
session: aiohttp.ClientSession | None = None,
|
|
100
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
101
|
+
user_agent: str | None = None,
|
|
102
|
+
timeout: float = 30.0,
|
|
103
|
+
) -> None:
|
|
104
|
+
self._token = token
|
|
105
|
+
self._session = session
|
|
106
|
+
self._owns_session = session is None
|
|
107
|
+
self._base_url = base_url.rstrip("/")
|
|
108
|
+
self._user_agent = user_agent or f"aiomapit/{__version__}"
|
|
109
|
+
self._timeout_seconds = timeout
|
|
110
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
111
|
+
self._cache: dict[str, tuple[str, Any]] = {}
|
|
112
|
+
|
|
113
|
+
async def __aenter__(self) -> Self:
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
async def __aexit__(
|
|
117
|
+
self,
|
|
118
|
+
exc_type: type[BaseException] | None,
|
|
119
|
+
exc: BaseException | None,
|
|
120
|
+
tb: TracebackType | None,
|
|
121
|
+
) -> None:
|
|
122
|
+
await self.close()
|
|
123
|
+
|
|
124
|
+
async def close(self) -> None:
|
|
125
|
+
"""Close the session if the client created it."""
|
|
126
|
+
if self._owns_session and self._session is not None:
|
|
127
|
+
await self._session.close()
|
|
128
|
+
self._session = None
|
|
129
|
+
|
|
130
|
+
# -- transport ---------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
async def _bearer(self) -> str:
|
|
133
|
+
return self._token if isinstance(self._token, str) else await self._token()
|
|
134
|
+
|
|
135
|
+
@staticmethod
|
|
136
|
+
def _cache_key(token: str, path: str, query: Mapping[str, str]) -> str:
|
|
137
|
+
# The token is part of the key: a tag is only valid for the identity that got it.
|
|
138
|
+
who = hashlib.sha256(token.encode()).hexdigest()[:16]
|
|
139
|
+
return f"{who}|{path}?{urlencode(sorted(query.items()))}"
|
|
140
|
+
|
|
141
|
+
async def _send(
|
|
142
|
+
self, method: str, path: str, params: Mapping[str, str], token: str, etag: str | None
|
|
143
|
+
) -> tuple[int, Any, str | None]:
|
|
144
|
+
headers = {
|
|
145
|
+
"Authorization": f"Bearer {token}",
|
|
146
|
+
"Accept": "application/json",
|
|
147
|
+
"User-Agent": self._user_agent,
|
|
148
|
+
}
|
|
149
|
+
if etag:
|
|
150
|
+
headers["If-None-Match"] = etag
|
|
151
|
+
if self._session is None:
|
|
152
|
+
self._session = aiohttp.ClientSession()
|
|
153
|
+
try:
|
|
154
|
+
async with self._session.request(
|
|
155
|
+
method,
|
|
156
|
+
self._base_url + path,
|
|
157
|
+
params=params or None,
|
|
158
|
+
headers=headers,
|
|
159
|
+
timeout=self._timeout,
|
|
160
|
+
) as resp:
|
|
161
|
+
raw = await resp.read()
|
|
162
|
+
status = resp.status
|
|
163
|
+
response_headers = resp.headers
|
|
164
|
+
except TimeoutError as err:
|
|
165
|
+
raise MapitConnectionError(
|
|
166
|
+
f"The Mapit API did not answer within {self._timeout_seconds:g} s"
|
|
167
|
+
) from err
|
|
168
|
+
except aiohttp.ClientError as err:
|
|
169
|
+
raise MapitConnectionError(
|
|
170
|
+
f"Cannot reach the Mapit API: {err or type(err).__name__}"
|
|
171
|
+
) from err
|
|
172
|
+
if status in (204, 304):
|
|
173
|
+
return status, None, None
|
|
174
|
+
if status >= 400:
|
|
175
|
+
raise self._error(status, raw, response_headers)
|
|
176
|
+
try:
|
|
177
|
+
body = json.loads(raw)
|
|
178
|
+
except ValueError as err: # includes a body that is not valid UTF-8
|
|
179
|
+
raise MapitResponseError(
|
|
180
|
+
"The Mapit API answered with a body that is not valid JSON", status=status
|
|
181
|
+
) from err
|
|
182
|
+
return status, body, response_headers.get("ETag")
|
|
183
|
+
|
|
184
|
+
@staticmethod
|
|
185
|
+
def _error(status: int, body: bytes, headers: Mapping[str, str]) -> MapitError:
|
|
186
|
+
title, detail = _problem(body)
|
|
187
|
+
message = f"{status} {title or 'error'}" + (f": {detail}" if detail else "")
|
|
188
|
+
if status == 401:
|
|
189
|
+
return MapitAuthError(message, status=status, title=title, detail=detail)
|
|
190
|
+
if status == 403 and "insufficient_scope" in headers.get("WWW-Authenticate", ""):
|
|
191
|
+
scope = _missing_scope(headers["WWW-Authenticate"], detail)
|
|
192
|
+
return MapitScopeError(message, scope=scope, status=status, title=title, detail=detail)
|
|
193
|
+
if status == 404:
|
|
194
|
+
return MapitNotFound(message, status=status, title=title, detail=detail)
|
|
195
|
+
if status == 429:
|
|
196
|
+
return MapitRateLimited(
|
|
197
|
+
message,
|
|
198
|
+
retry_after=_retry_after(headers.get("Retry-After")),
|
|
199
|
+
status=status,
|
|
200
|
+
title=title,
|
|
201
|
+
detail=detail,
|
|
202
|
+
)
|
|
203
|
+
if status >= 500:
|
|
204
|
+
return MapitConnectionError(message, status=status, title=title, detail=detail)
|
|
205
|
+
return MapitError(message, status=status, title=title, detail=detail)
|
|
206
|
+
|
|
207
|
+
async def _get[T](
|
|
208
|
+
self, path: str, parse: Callable[[Any], T], params: Mapping[str, object] | None = None
|
|
209
|
+
) -> Response[T]:
|
|
210
|
+
query = {k: _param(v) for k, v in (params or {}).items() if v is not None}
|
|
211
|
+
token = await self._bearer()
|
|
212
|
+
key = self._cache_key(token, path, query)
|
|
213
|
+
cached = self._cache.get(key)
|
|
214
|
+
status, body, etag = await self._send(
|
|
215
|
+
"GET", path, query, token, cached[0] if cached else None
|
|
216
|
+
)
|
|
217
|
+
if status == 304:
|
|
218
|
+
if cached is None:
|
|
219
|
+
raise MapitError("The Mapit API answered 304 for a request without a tag")
|
|
220
|
+
return Response(cached[1], True, cached[0])
|
|
221
|
+
try:
|
|
222
|
+
data = parse(body)
|
|
223
|
+
except (KeyError, TypeError, ValueError, AttributeError) as err:
|
|
224
|
+
raise MapitResponseError(
|
|
225
|
+
f"Unexpected response from the Mapit API: {err!r}", status=status
|
|
226
|
+
) from err
|
|
227
|
+
self._cache.pop(key, None)
|
|
228
|
+
if etag:
|
|
229
|
+
self._cache[key] = (etag, data)
|
|
230
|
+
if len(self._cache) > CACHE_SIZE:
|
|
231
|
+
del self._cache[next(iter(self._cache))]
|
|
232
|
+
return Response(data, False, etag)
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def _id(value: str) -> str:
|
|
236
|
+
return quote(value, safe="")
|
|
237
|
+
|
|
238
|
+
# -- account -----------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
async def get_me(self) -> Response[Account]:
|
|
241
|
+
return await self._get("/me", Account.from_json)
|
|
242
|
+
|
|
243
|
+
async def get_summary(
|
|
244
|
+
self, *, vehicle_cursor: str | None = None, transfer_cursor: str | None = None
|
|
245
|
+
) -> Response[Summary]:
|
|
246
|
+
return await self._get(
|
|
247
|
+
"/summary",
|
|
248
|
+
Summary.from_json,
|
|
249
|
+
{"vehicleCursor": vehicle_cursor, "transferCursor": transfer_cursor},
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# -- vehicles ----------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
async def get_vehicles_page(self, cursor: str | None = None) -> Response[Page[Vehicle]]:
|
|
255
|
+
return await self._get(
|
|
256
|
+
"/vehicles",
|
|
257
|
+
lambda d: Page(tuple(Vehicle.from_json(v) for v in d["vehicles"]), d.get("nextCursor")),
|
|
258
|
+
{"cursor": cursor},
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def iter_vehicles(self) -> AsyncIterator[Vehicle]:
|
|
262
|
+
"""Every vehicle, following the cursors."""
|
|
263
|
+
return self._items(self.get_vehicles_page)
|
|
264
|
+
|
|
265
|
+
async def get_vehicle(self, vehicle_id: str) -> Response[Vehicle]:
|
|
266
|
+
return await self._get(f"/vehicles/{self._id(vehicle_id)}", Vehicle.from_json)
|
|
267
|
+
|
|
268
|
+
async def get_subscription(self, vehicle_id: str) -> Response[Subscription | None]:
|
|
269
|
+
"""The stored subscription status, or None when the vehicle has none."""
|
|
270
|
+
return await self._get(
|
|
271
|
+
f"/vehicles/{self._id(vehicle_id)}/subscription",
|
|
272
|
+
lambda d: Subscription.from_json(d["subscription"]) if d.get("subscription") else None,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
# -- status (needs mapit:location:read) --------------------------------
|
|
276
|
+
|
|
277
|
+
async def get_statuses_page(self, cursor: str | None = None) -> Response[Page[VehicleStatus]]:
|
|
278
|
+
"""Last reported status of every vehicle on the page, in one request."""
|
|
279
|
+
return await self._get(
|
|
280
|
+
"/status",
|
|
281
|
+
lambda d: Page(
|
|
282
|
+
tuple(VehicleStatus.from_json(v) for v in d["vehicles"]), d.get("nextCursor")
|
|
283
|
+
),
|
|
284
|
+
{"cursor": cursor},
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def iter_statuses(self) -> AsyncIterator[VehicleStatus]:
|
|
288
|
+
"""Every vehicle's status, following the cursors."""
|
|
289
|
+
return self._items(self.get_statuses_page)
|
|
290
|
+
|
|
291
|
+
async def get_vehicle_status(self, vehicle_id: str) -> Response[VehicleStatus]:
|
|
292
|
+
return await self._get(f"/vehicles/{self._id(vehicle_id)}/status", VehicleStatus.from_json)
|
|
293
|
+
|
|
294
|
+
# -- routes (needs mapit:routes:read) ----------------------------------
|
|
295
|
+
|
|
296
|
+
async def get_routes_page(
|
|
297
|
+
self,
|
|
298
|
+
vehicle_id: str,
|
|
299
|
+
*,
|
|
300
|
+
day: date | str | None = None,
|
|
301
|
+
start: datetime | str | None = None,
|
|
302
|
+
end: datetime | str | None = None,
|
|
303
|
+
timezone: str | None = None,
|
|
304
|
+
limit: int | None = None,
|
|
305
|
+
cursor: str | None = None,
|
|
306
|
+
) -> Response[Page[Route]]:
|
|
307
|
+
"""Routes of one local ``day``, or from ``start`` (inclusive) to ``end`` (exclusive,
|
|
308
|
+
at most 93 days, with offsets). Without a filter: the last 30 days, which moves on
|
|
309
|
+
every call and so never answers 304 (``Page.filter`` has the window it used)."""
|
|
310
|
+
return await self._get(
|
|
311
|
+
f"/vehicles/{self._id(vehicle_id)}/routes",
|
|
312
|
+
lambda d: Page(
|
|
313
|
+
tuple(Route.from_json(r) for r in d["routes"]),
|
|
314
|
+
d.get("nextCursor"),
|
|
315
|
+
d.get("filter"),
|
|
316
|
+
),
|
|
317
|
+
{
|
|
318
|
+
"day": day,
|
|
319
|
+
"from": start,
|
|
320
|
+
"to": end,
|
|
321
|
+
"timezone": timezone,
|
|
322
|
+
"limit": limit,
|
|
323
|
+
"cursor": cursor,
|
|
324
|
+
},
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
async def iter_routes(
|
|
328
|
+
self,
|
|
329
|
+
vehicle_id: str,
|
|
330
|
+
*,
|
|
331
|
+
day: date | str | None = None,
|
|
332
|
+
start: datetime | str | None = None,
|
|
333
|
+
end: datetime | str | None = None,
|
|
334
|
+
timezone: str | None = None,
|
|
335
|
+
limit: int | None = None,
|
|
336
|
+
) -> AsyncIterator[Route]:
|
|
337
|
+
"""Every route of the filter, newest first, following the cursors."""
|
|
338
|
+
args: dict[str, Any] = {
|
|
339
|
+
"day": day,
|
|
340
|
+
"start": start,
|
|
341
|
+
"end": end,
|
|
342
|
+
"timezone": timezone,
|
|
343
|
+
"limit": limit,
|
|
344
|
+
}
|
|
345
|
+
cursor = None
|
|
346
|
+
while True:
|
|
347
|
+
page = (await self.get_routes_page(vehicle_id, cursor=cursor, **args)).data
|
|
348
|
+
for route in page.items:
|
|
349
|
+
yield route
|
|
350
|
+
if not page.next_cursor:
|
|
351
|
+
return
|
|
352
|
+
cursor = page.next_cursor
|
|
353
|
+
# Later pages must use the window of the first, or "now" moves under the cursor.
|
|
354
|
+
f = page.filter or {}
|
|
355
|
+
args.update(
|
|
356
|
+
day=f.get("day"), start=f.get("from"), end=f.get("to"), timezone=f.get("timezone")
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
async def get_route(
|
|
360
|
+
self, vehicle_id: str, route_id: str, *, geometry: bool = False, simplify: bool = False
|
|
361
|
+
) -> Response[Route]:
|
|
362
|
+
"""One route. ``geometry`` adds GeoJSON (left out when over 40 KB); ``simplify``
|
|
363
|
+
thins it to fit and implies ``geometry``."""
|
|
364
|
+
return await self._get(
|
|
365
|
+
f"/vehicles/{self._id(vehicle_id)}/routes/{self._id(route_id)}",
|
|
366
|
+
lambda d: Route.from_json(d["route"]),
|
|
367
|
+
{"geometry": geometry or None, "simplify": simplify or None},
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
async def get_ride_stats(
|
|
371
|
+
self,
|
|
372
|
+
vehicle_id: str,
|
|
373
|
+
start: date | str,
|
|
374
|
+
end: date | str,
|
|
375
|
+
*,
|
|
376
|
+
timezone: str | None = None,
|
|
377
|
+
) -> Response[RideStats]:
|
|
378
|
+
"""Rides per local day from ``start`` to ``end`` inclusive (at most 90 days)."""
|
|
379
|
+
return await self._get(
|
|
380
|
+
f"/vehicles/{self._id(vehicle_id)}/stats",
|
|
381
|
+
RideStats.from_json,
|
|
382
|
+
{"from": start, "to": end, "timezone": timezone},
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
# -- connections (a personal key with "Manage connections") ------------
|
|
386
|
+
|
|
387
|
+
async def get_connections(self) -> Response[tuple[Connection, ...]]:
|
|
388
|
+
"""Every app and personal key connected to the account."""
|
|
389
|
+
return await self._get(
|
|
390
|
+
"/me/connections",
|
|
391
|
+
lambda d: tuple(Connection.from_json(c) for c in d["connections"]),
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
async def delete_connection(self, connection_id: str) -> None:
|
|
395
|
+
"""Revoke a connection; its tokens stop working at once. Repeating is fine."""
|
|
396
|
+
token = await self._bearer()
|
|
397
|
+
await self._send("DELETE", f"/me/connections/{self._id(connection_id)}", {}, token, None)
|
|
398
|
+
self._cache.pop(self._cache_key(token, "/me/connections", {}), None)
|
|
399
|
+
|
|
400
|
+
# -- helpers -----------------------------------------------------------
|
|
401
|
+
|
|
402
|
+
@staticmethod
|
|
403
|
+
async def _items[T](
|
|
404
|
+
fetch: Callable[[str | None], Awaitable[Response[Page[T]]]],
|
|
405
|
+
) -> AsyncIterator[T]:
|
|
406
|
+
cursor = None
|
|
407
|
+
while True:
|
|
408
|
+
page = (await fetch(cursor)).data
|
|
409
|
+
for item in page.items:
|
|
410
|
+
yield item
|
|
411
|
+
if not page.next_cursor:
|
|
412
|
+
return
|
|
413
|
+
cursor = page.next_cursor
|
aiomapit/exceptions.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Errors raised by the client. Every one derives from :class:`MapitError`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MapitError(Exception):
|
|
7
|
+
"""Base class. ``status``, ``title`` and ``detail`` come from the problem+json body."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
*,
|
|
13
|
+
status: int | None = None,
|
|
14
|
+
title: str | None = None,
|
|
15
|
+
detail: str | None = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.status = status
|
|
19
|
+
self.title = title
|
|
20
|
+
self.detail = detail
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MapitAuthError(MapitError):
|
|
24
|
+
"""401: the token or key is missing, expired or revoked."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MapitScopeError(MapitError):
|
|
28
|
+
"""403 insufficient_scope: the connection was not given ``scope``."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
message: str,
|
|
33
|
+
*,
|
|
34
|
+
scope: str | None = None,
|
|
35
|
+
status: int | None = None,
|
|
36
|
+
title: str | None = None,
|
|
37
|
+
detail: str | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__(message, status=status, title=title, detail=detail)
|
|
40
|
+
self.scope = scope
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class MapitNotFound(MapitError):
|
|
44
|
+
"""404: not available for this account. A foreign or unknown id answers the same."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class MapitRateLimited(MapitError):
|
|
48
|
+
"""429: over 30 requests a minute. ``retry_after`` is in seconds when the server said."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
message: str,
|
|
53
|
+
*,
|
|
54
|
+
retry_after: float | None = None,
|
|
55
|
+
status: int | None = None,
|
|
56
|
+
title: str | None = None,
|
|
57
|
+
detail: str | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
super().__init__(message, status=status, title=title, detail=detail)
|
|
60
|
+
self.retry_after = retry_after
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class MapitConnectionError(MapitError):
|
|
64
|
+
"""5xx, timeout or network failure: worth retrying later."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class MapitResponseError(MapitError):
|
|
68
|
+
"""A 2xx answer that is not valid JSON (or UTF-8) or lacks the expected fields."""
|
aiomapit/models.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Frozen dataclasses for what the API returns, with snake_case field names."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import date, datetime
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
type Json = Mapping[str, Any]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _dt(value: str | None) -> datetime | None:
|
|
14
|
+
return datetime.fromisoformat(value) if value else None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _req_dt(value: str) -> datetime:
|
|
18
|
+
return datetime.fromisoformat(value)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class Account:
|
|
23
|
+
"""``id`` is opaque and stable for the customer, also across email changes. It is None
|
|
24
|
+
from servers that predate it."""
|
|
25
|
+
|
|
26
|
+
name: str
|
|
27
|
+
email: str
|
|
28
|
+
id: str | None = None
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def from_json(cls, d: Json) -> Account:
|
|
32
|
+
return cls(name=d["name"], email=d["email"], id=d.get("id"))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class Subscription:
|
|
37
|
+
status: str
|
|
38
|
+
period_end: datetime | None
|
|
39
|
+
cancel_at_end: bool
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_json(cls, d: Json) -> Subscription:
|
|
43
|
+
return cls(
|
|
44
|
+
status=d["status"],
|
|
45
|
+
period_end=_dt(d.get("periodEnd")),
|
|
46
|
+
cancel_at_end=bool(d.get("cancelAtEnd", False)),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class Vehicle:
|
|
52
|
+
"""``device_model`` and ``subscription`` are only filled by the summary."""
|
|
53
|
+
|
|
54
|
+
id: str
|
|
55
|
+
name: str | None
|
|
56
|
+
registration_number: str | None
|
|
57
|
+
model: str | None
|
|
58
|
+
km: float | None
|
|
59
|
+
products: tuple[str, ...]
|
|
60
|
+
cancelled: bool
|
|
61
|
+
blocked_by_transfer: bool
|
|
62
|
+
device_model: str | None = None
|
|
63
|
+
subscription: Subscription | None = None
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_json(cls, d: Json) -> Vehicle:
|
|
67
|
+
sub = d.get("subscription")
|
|
68
|
+
device = d.get("device")
|
|
69
|
+
return cls(
|
|
70
|
+
id=d["id"],
|
|
71
|
+
name=d.get("name"),
|
|
72
|
+
registration_number=d.get("registrationNumber"),
|
|
73
|
+
model=d.get("model"),
|
|
74
|
+
km=d.get("km"),
|
|
75
|
+
products=tuple(d.get("products") or ()),
|
|
76
|
+
cancelled=bool(d.get("cancelled", False)),
|
|
77
|
+
blocked_by_transfer=bool(d.get("blockedByTransfer", False)),
|
|
78
|
+
device_model=device.get("model") if device else None,
|
|
79
|
+
subscription=Subscription.from_json(sub) if sub else None,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class DeviceState:
|
|
85
|
+
"""What the tracker last reported. ``voltage`` 0 or None is normal while parked."""
|
|
86
|
+
|
|
87
|
+
status: str | None
|
|
88
|
+
battery_percent: float | None
|
|
89
|
+
voltage: float | None
|
|
90
|
+
latitude: float | None
|
|
91
|
+
longitude: float | None
|
|
92
|
+
last_communication_at: datetime | None
|
|
93
|
+
last_location_at: datetime | None
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def from_json(cls, d: Json) -> DeviceState:
|
|
97
|
+
return cls(
|
|
98
|
+
status=d.get("status"),
|
|
99
|
+
battery_percent=d.get("batteryPercent"),
|
|
100
|
+
voltage=d.get("voltage"),
|
|
101
|
+
latitude=d.get("latitude"),
|
|
102
|
+
longitude=d.get("longitude"),
|
|
103
|
+
last_communication_at=_dt(d.get("lastCommunicationAt")),
|
|
104
|
+
last_location_at=_dt(d.get("lastLocationAt")),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True, slots=True)
|
|
109
|
+
class VehicleStatus:
|
|
110
|
+
"""``state`` is None when there is no device data; ``reason`` then says why
|
|
111
|
+
(``blocked_by_transfer``, ``subscription_cancelled`` or ``no_linked_device``)."""
|
|
112
|
+
|
|
113
|
+
vehicle_id: str
|
|
114
|
+
state: DeviceState | None
|
|
115
|
+
reason: str | None
|
|
116
|
+
voltage_note: str | None
|
|
117
|
+
source: str | None
|
|
118
|
+
fetched_at: datetime | None
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def from_json(cls, d: Json) -> VehicleStatus:
|
|
122
|
+
state = d.get("state")
|
|
123
|
+
return cls(
|
|
124
|
+
vehicle_id=d["vehicleId"],
|
|
125
|
+
state=DeviceState.from_json(state) if state else None,
|
|
126
|
+
reason=d.get("reason"),
|
|
127
|
+
voltage_note=d.get("voltageNote"),
|
|
128
|
+
source=d.get("source"),
|
|
129
|
+
fetched_at=_dt(d.get("fetchedAt")),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True, slots=True)
|
|
134
|
+
class Route:
|
|
135
|
+
"""``geometry`` is GeoJSON, only when asked for and small enough
|
|
136
|
+
(``geometry_omitted`` says it was too large)."""
|
|
137
|
+
|
|
138
|
+
id: str
|
|
139
|
+
vehicle_id: str
|
|
140
|
+
started_at: datetime
|
|
141
|
+
ended_at: datetime | None
|
|
142
|
+
distance_meters: float | None
|
|
143
|
+
duration_seconds: float | None
|
|
144
|
+
avg_speed_kmh: float | None
|
|
145
|
+
max_speed_kmh: float | None
|
|
146
|
+
start_timezone: str | None
|
|
147
|
+
max_speed_display: str | None = None
|
|
148
|
+
geometry: Json | None = None
|
|
149
|
+
geometry_omitted: bool = False
|
|
150
|
+
geometry_tolerance_meters: float | None = None
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def from_json(cls, d: Json) -> Route:
|
|
154
|
+
return cls(
|
|
155
|
+
id=d["id"],
|
|
156
|
+
vehicle_id=d["vehicleId"],
|
|
157
|
+
started_at=_req_dt(d["startedAt"]),
|
|
158
|
+
ended_at=_dt(d.get("endedAt")),
|
|
159
|
+
distance_meters=d.get("distanceMeters"),
|
|
160
|
+
duration_seconds=d.get("durationSeconds"),
|
|
161
|
+
avg_speed_kmh=d.get("avgSpeedKmh"),
|
|
162
|
+
max_speed_kmh=d.get("maxSpeedKmh"),
|
|
163
|
+
start_timezone=d.get("startTimezone"),
|
|
164
|
+
max_speed_display=d.get("maxSpeedDisplay"),
|
|
165
|
+
geometry=d.get("geometry"),
|
|
166
|
+
geometry_omitted=bool(d.get("geometryOmitted", False)),
|
|
167
|
+
geometry_tolerance_meters=d.get("geometryToleranceMeters"),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass(frozen=True, slots=True)
|
|
172
|
+
class RideTotals:
|
|
173
|
+
rides: int
|
|
174
|
+
distance_km: float
|
|
175
|
+
riding_hours: float
|
|
176
|
+
avg_speed_kmh: float | None
|
|
177
|
+
max_speed_kmh: float | None
|
|
178
|
+
|
|
179
|
+
@classmethod
|
|
180
|
+
def from_json(cls, d: Json) -> RideTotals:
|
|
181
|
+
return cls(
|
|
182
|
+
rides=d["rides"],
|
|
183
|
+
distance_km=d["distanceKm"],
|
|
184
|
+
riding_hours=d["ridingHours"],
|
|
185
|
+
avg_speed_kmh=d.get("avgSpeedKmh"),
|
|
186
|
+
max_speed_kmh=d.get("maxSpeedKmh"),
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass(frozen=True, slots=True)
|
|
191
|
+
class RideDay(RideTotals):
|
|
192
|
+
day: date
|
|
193
|
+
|
|
194
|
+
@classmethod
|
|
195
|
+
def from_json(cls, d: Json) -> RideDay:
|
|
196
|
+
t = RideTotals.from_json(d)
|
|
197
|
+
return cls(
|
|
198
|
+
rides=t.rides,
|
|
199
|
+
distance_km=t.distance_km,
|
|
200
|
+
riding_hours=t.riding_hours,
|
|
201
|
+
avg_speed_kmh=t.avg_speed_kmh,
|
|
202
|
+
max_speed_kmh=t.max_speed_kmh,
|
|
203
|
+
day=date.fromisoformat(d["date"]),
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@dataclass(frozen=True, slots=True)
|
|
208
|
+
class RideStats:
|
|
209
|
+
"""Per local day, with the Mapit app's own rules (see ``method``).
|
|
210
|
+
Days without rides are left out. ``truncated`` is set when too many routes were read."""
|
|
211
|
+
|
|
212
|
+
vehicle_id: str
|
|
213
|
+
start: date
|
|
214
|
+
end: date
|
|
215
|
+
timezone: str
|
|
216
|
+
totals: RideTotals
|
|
217
|
+
days: tuple[RideDay, ...]
|
|
218
|
+
truncated: bool
|
|
219
|
+
method: str | None
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def from_json(cls, d: Json) -> RideStats:
|
|
223
|
+
period = d["period"]
|
|
224
|
+
return cls(
|
|
225
|
+
vehicle_id=d["vehicleId"],
|
|
226
|
+
start=date.fromisoformat(period["from"]),
|
|
227
|
+
end=date.fromisoformat(period["to"]),
|
|
228
|
+
timezone=period["timezone"],
|
|
229
|
+
totals=RideTotals.from_json(d["totals"]),
|
|
230
|
+
days=tuple(RideDay.from_json(x) for x in d["days"]),
|
|
231
|
+
truncated=bool(d.get("truncated", False)),
|
|
232
|
+
method=d.get("method"),
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@dataclass(frozen=True, slots=True)
|
|
237
|
+
class IncomingTransfer:
|
|
238
|
+
products: tuple[str, ...]
|
|
239
|
+
expired: bool
|
|
240
|
+
|
|
241
|
+
@classmethod
|
|
242
|
+
def from_json(cls, d: Json) -> IncomingTransfer:
|
|
243
|
+
return cls(products=tuple(d.get("products") or ()), expired=bool(d.get("expired", False)))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@dataclass(frozen=True, slots=True)
|
|
247
|
+
class Summary:
|
|
248
|
+
"""Account, vehicles with device and subscription, and incoming transfers.
|
|
249
|
+
Page with ``next_vehicle_cursor`` and ``next_transfer_cursor``."""
|
|
250
|
+
|
|
251
|
+
generated_at: datetime | None
|
|
252
|
+
name: str
|
|
253
|
+
email: str
|
|
254
|
+
locale: str | None
|
|
255
|
+
timezone: str | None
|
|
256
|
+
subscription_balance_days: float | None
|
|
257
|
+
vehicles: tuple[Vehicle, ...]
|
|
258
|
+
incoming_transfers: tuple[IncomingTransfer, ...]
|
|
259
|
+
next_vehicle_cursor: str | None
|
|
260
|
+
next_transfer_cursor: str | None
|
|
261
|
+
|
|
262
|
+
@classmethod
|
|
263
|
+
def from_json(cls, d: Json) -> Summary:
|
|
264
|
+
account = d["account"]
|
|
265
|
+
prefs = account.get("preferences") or {}
|
|
266
|
+
page = d.get("page") or {}
|
|
267
|
+
return cls(
|
|
268
|
+
generated_at=_dt(d.get("generatedAt")),
|
|
269
|
+
name=account["name"],
|
|
270
|
+
email=account["email"],
|
|
271
|
+
locale=prefs.get("locale"),
|
|
272
|
+
timezone=prefs.get("timezone"),
|
|
273
|
+
subscription_balance_days=account.get("subscriptionBalanceDays"),
|
|
274
|
+
vehicles=tuple(Vehicle.from_json(v) for v in d["vehicles"]),
|
|
275
|
+
incoming_transfers=tuple(
|
|
276
|
+
IncomingTransfer.from_json(t) for t in d.get("incomingTransfers", ())
|
|
277
|
+
),
|
|
278
|
+
next_vehicle_cursor=page.get("nextVehicleCursor"),
|
|
279
|
+
next_transfer_cursor=page.get("nextTransferCursor"),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass(frozen=True, slots=True)
|
|
284
|
+
class Connection:
|
|
285
|
+
"""An app or personal key connected to the account."""
|
|
286
|
+
|
|
287
|
+
id: str
|
|
288
|
+
kind: str # "app" or "personal_key"
|
|
289
|
+
name: str # as the app registered it: unverified unless ``built_in``
|
|
290
|
+
built_in: bool
|
|
291
|
+
api: str # "rest" or "mcp"
|
|
292
|
+
scopes: tuple[str, ...]
|
|
293
|
+
created_at: datetime
|
|
294
|
+
expires_at: datetime
|
|
295
|
+
current: bool # the key making this request
|
|
296
|
+
|
|
297
|
+
@classmethod
|
|
298
|
+
def from_json(cls, d: Json) -> Connection:
|
|
299
|
+
return cls(
|
|
300
|
+
id=d["id"],
|
|
301
|
+
kind=d["kind"],
|
|
302
|
+
name=d["name"],
|
|
303
|
+
built_in=bool(d.get("builtIn", False)),
|
|
304
|
+
api=d["api"],
|
|
305
|
+
scopes=tuple(d.get("scopes") or ()),
|
|
306
|
+
created_at=_req_dt(d["createdAt"]),
|
|
307
|
+
expires_at=_req_dt(d["expiresAt"]),
|
|
308
|
+
current=bool(d.get("current", False)),
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@dataclass(frozen=True, slots=True)
|
|
313
|
+
class Page[T]:
|
|
314
|
+
"""One page of ``items``. ``filter`` is what the server applied to a routes list;
|
|
315
|
+
send it back unchanged (with ``next_cursor``) to get the next page."""
|
|
316
|
+
|
|
317
|
+
items: tuple[T, ...]
|
|
318
|
+
next_cursor: str | None
|
|
319
|
+
filter: Json | None = None
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@dataclass(frozen=True, slots=True)
|
|
323
|
+
class Response[T]:
|
|
324
|
+
"""``data`` is the parsed answer. ``not_modified`` is True when the server answered
|
|
325
|
+
304 and ``data`` is the object cached from the earlier 200."""
|
|
326
|
+
|
|
327
|
+
data: T
|
|
328
|
+
not_modified: bool
|
|
329
|
+
etag: str | None
|
aiomapit/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aiomapit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Python client for the Mapit API
|
|
5
|
+
Project-URL: Homepage, https://github.com/mapit-iot/aiomapit
|
|
6
|
+
Project-URL: Issues, https://github.com/mapit-iot/aiomapit/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/mapit-iot/aiomapit/blob/main/CHANGELOG.md
|
|
8
|
+
Author: Mapit IoT S.L.
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: aiohttp,api,asyncio,home-assistant,mapit
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Requires-Dist: aiohttp>=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# aiomapit
|
|
24
|
+
|
|
25
|
+
Async Python client for the [Mapit](https://mapit.me) API (`https://api.mapit.me/v1`): the account,
|
|
26
|
+
vehicles, last reported position and routes that the Mapit app shows. Read-only, apart from disconnecting
|
|
27
|
+
apps and keys (`delete_connection`, which needs the Manage connections permission). Built on `aiohttp`,
|
|
28
|
+
fully typed. Used by the Home Assistant integration.
|
|
29
|
+
|
|
30
|
+
> **Beta, free for now.** The Mapit API it talks to is a beta: it may change or stop, it has no uptime promise, and Mapit does not charge for it today. This library may need updates to follow it. Do not rely on it for emergencies or to recover a stolen bike: use the Mapit app. Use is subject to the [Mapit API Terms of Use](https://developers.mapit.me/terms) and [Privacy Notice](https://developers.mapit.me/privacy), for personal, non-commercial use.
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
pip install aiomapit
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Python 3.12 or newer.
|
|
37
|
+
|
|
38
|
+
## A personal key (your own scripts)
|
|
39
|
+
|
|
40
|
+
You need a Mapit account. Create a key at <https://login.mapit.me/connections> and pass it as the token.
|
|
41
|
+
Location, route history and managing connections each need their own permission, ticked when the key
|
|
42
|
+
is created (see [personal keys](https://developers.mapit.me/keys)).
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
|
|
47
|
+
from aiomapit import MapitClient
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def main() -> None:
|
|
51
|
+
async with MapitClient("mapit_...") as client:
|
|
52
|
+
async for status in client.iter_statuses():
|
|
53
|
+
if status.state:
|
|
54
|
+
print(status.vehicle_id, status.state.latitude, status.state.longitude)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
asyncio.run(main())
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## A token callback (apps that do OAuth themselves)
|
|
61
|
+
|
|
62
|
+
This is for apps that Mapit has approved (see [Approved apps](https://developers.mapit.me/approved-apps)); anything built for other Mapit customers needs Mapit's written approval. The
|
|
63
|
+
OAuth flow itself is described at <https://developers.mapit.me/oauth>. The library has no OAuth logic. Give it an async callable that returns a valid access token; it is
|
|
64
|
+
called before every request, so it may refresh. Share your own `aiohttp.ClientSession`:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
async def token() -> str:
|
|
68
|
+
await oauth_session.async_ensure_token_valid()
|
|
69
|
+
return oauth_session.token["access_token"]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
client = MapitClient(token, session=session, user_agent="my-app/1.0")
|
|
73
|
+
vehicles = [v async for v in client.iter_vehicles()]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Without `session`, the client creates one and closes it in `close()` (or when leaving `async with`).
|
|
77
|
+
With one, the session stays yours.
|
|
78
|
+
|
|
79
|
+
## What it covers
|
|
80
|
+
|
|
81
|
+
| Method | Endpoint |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| `get_me()` (an `Account` with `id`, `name`, `email`; `id` is stable across email changes) | `GET /me` |
|
|
84
|
+
| `get_summary(vehicle_cursor=, transfer_cursor=)` | `GET /summary` |
|
|
85
|
+
| `get_vehicles_page(cursor)`, `iter_vehicles()` | `GET /vehicles` |
|
|
86
|
+
| `get_vehicle(id)`, `get_subscription(id)` | `GET /vehicles/{id}`, `.../subscription` |
|
|
87
|
+
| `get_statuses_page(cursor)`, `iter_statuses()`, `get_vehicle_status(id)` (Location permission) | `GET /status`, `/vehicles/{id}/status` |
|
|
88
|
+
| `get_routes_page(id, day=, start=, end=, ...)`, `iter_routes(id, ...)` (Route history permission) | `GET /vehicles/{id}/routes` |
|
|
89
|
+
| `get_route(id, route_id, geometry=, simplify=)` (Route history) | `GET /vehicles/{id}/routes/{route_id}` |
|
|
90
|
+
| `get_ride_stats(id, start, end, timezone=)` (Route history) | `GET /vehicles/{id}/stats` |
|
|
91
|
+
| `get_connections()`, `delete_connection(id)` | `GET`, `DELETE /me/connections` (a personal key with "Manage connections") |
|
|
92
|
+
|
|
93
|
+
Ids and cursors are opaque: pass them back as you got them. `iter_*` follow the cursors for you.
|
|
94
|
+
The API allows 30 requests a minute per key or token, and positions are what the device last
|
|
95
|
+
reported, so poll `iter_statuses()` once a minute at most.
|
|
96
|
+
|
|
97
|
+
Every `get_*` returns a `Response` with `data` (a frozen dataclass, snake_case fields),
|
|
98
|
+
`not_modified` and `etag`.
|
|
99
|
+
|
|
100
|
+
## ETag and 304
|
|
101
|
+
|
|
102
|
+
The client remembers the `ETag` of what it fetched (in memory, per URL and query) and sends it as
|
|
103
|
+
`If-None-Match`. On `304` you get the earlier object back with `not_modified=True`:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
res = await client.get_vehicle_status(vehicle_id)
|
|
107
|
+
if not res.not_modified:
|
|
108
|
+
update(res.data)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The cache key includes the token, so two tokens never share an object; a refreshed OAuth token starts
|
|
112
|
+
with a fresh cache. A 304 saves bandwidth and parsing, not quota: it still counts towards the 30 requests a minute.
|
|
113
|
+
The routes list without a `day` or `start`/`end` is "the last 30 days to now" and never answers 304.
|
|
114
|
+
|
|
115
|
+
## Errors
|
|
116
|
+
|
|
117
|
+
All derive from `MapitError`, which has `status`, `title` and `detail` from the
|
|
118
|
+
`application/problem+json` body.
|
|
119
|
+
|
|
120
|
+
| Raised | When |
|
|
121
|
+
| --- | --- |
|
|
122
|
+
| `MapitAuthError` | 401: missing, expired or revoked token |
|
|
123
|
+
| `MapitScopeError` | 403 `insufficient_scope`; `.scope` is the missing scope |
|
|
124
|
+
| `MapitNotFound` | 404: also for a foreign or unknown id |
|
|
125
|
+
| `MapitRateLimited` | 429; `.retry_after` in seconds, or `None` |
|
|
126
|
+
| `MapitConnectionError` | 5xx, timeout, network failure |
|
|
127
|
+
| `MapitResponseError` | a 2xx answer that is not valid JSON or lacks the expected fields |
|
|
128
|
+
|
|
129
|
+
Other statuses (such as 400 for a bad filter) raise `MapitError` itself. The client never retries:
|
|
130
|
+
back off on `MapitRateLimited` and `MapitConnectionError` yourself.
|
|
131
|
+
|
|
132
|
+
## Development
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
uv sync
|
|
136
|
+
uv run ruff check . && uv run ruff format --check .
|
|
137
|
+
uv run mypy
|
|
138
|
+
uv run pytest
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Help
|
|
142
|
+
|
|
143
|
+
Docs and API reference: <https://developers.mapit.me>. Questions: atencioncliente@mapit.me.
|
|
144
|
+
|
|
145
|
+
MIT licence.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
aiomapit/__init__.py,sha256=nJwxnLzIGpZTpkc_ML_YV_LJYEagWL8nvIXuuGcCbG0,1053
|
|
2
|
+
aiomapit/_version.py,sha256=fknSN_kJN2GQ8B-Kv72qDT_S6sfJPZH2ixrlSd7r2rY,161
|
|
3
|
+
aiomapit/client.py,sha256=tYc4p3jH1hA9omi6R_4qkqscWodgPG_1amhmDuK8baw,15411
|
|
4
|
+
aiomapit/exceptions.py,sha256=X5-Gzzs1pGtheEYv5DVPY7VBx7zCbKk6YL-li_5qChE,1909
|
|
5
|
+
aiomapit/models.py,sha256=pLjHbzkUlJgaJErOmb1LgbC4iLkkARD5PK6jhTDAmb8,10074
|
|
6
|
+
aiomapit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
aiomapit-0.1.0.dist-info/METADATA,sha256=1v3AxhN0jQlh3Lh9v4YRPdXjUV4CEoPJrOp4zzI-axM,6208
|
|
8
|
+
aiomapit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
aiomapit-0.1.0.dist-info/licenses/LICENSE,sha256=JrFvIP9WX8lc5n5eweufzUmpInJR8B6miAqVbML0B3g,1071
|
|
10
|
+
aiomapit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mapit IoT S.L.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|