pyimatrix 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.
- pyimatrix/__init__.py +123 -0
- pyimatrix/auth.py +180 -0
- pyimatrix/client.py +176 -0
- pyimatrix/const.py +13 -0
- pyimatrix/exceptions.py +40 -0
- pyimatrix/models.py +725 -0
- pyimatrix/py.typed +0 -0
- pyimatrix/stream.py +290 -0
- pyimatrix-0.1.0.dist-info/METADATA +31 -0
- pyimatrix-0.1.0.dist-info/RECORD +12 -0
- pyimatrix-0.1.0.dist-info/WHEEL +4 -0
- pyimatrix-0.1.0.dist-info/licenses/LICENSE +201 -0
pyimatrix/__init__.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Async client for the iMatrix Cloud integration API."""
|
|
2
|
+
|
|
3
|
+
from .auth import AbstractAuth, ApiKeyAuth, TokenAuth
|
|
4
|
+
from .client import IMatrixClient
|
|
5
|
+
from .const import DEFAULT_BASE_URL, SCHEMA_VERSION, VERSION
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
IMatrixAuthError,
|
|
8
|
+
IMatrixConnectionError,
|
|
9
|
+
IMatrixError,
|
|
10
|
+
IMatrixNotFoundError,
|
|
11
|
+
IMatrixPermissionError,
|
|
12
|
+
IMatrixRateLimitError,
|
|
13
|
+
IMatrixResponseError,
|
|
14
|
+
IMatrixUnsupportedSchemaError,
|
|
15
|
+
)
|
|
16
|
+
from .models import (
|
|
17
|
+
Account,
|
|
18
|
+
AlarmLevel,
|
|
19
|
+
AlarmSide,
|
|
20
|
+
Channel,
|
|
21
|
+
ChannelMode,
|
|
22
|
+
ChannelState,
|
|
23
|
+
Connectivity,
|
|
24
|
+
ConnectivityState,
|
|
25
|
+
Device,
|
|
26
|
+
DeviceKind,
|
|
27
|
+
DeviceState,
|
|
28
|
+
Event,
|
|
29
|
+
EventPage,
|
|
30
|
+
EventType,
|
|
31
|
+
Fault,
|
|
32
|
+
FaultProtocol,
|
|
33
|
+
Faults,
|
|
34
|
+
FaultSeverity,
|
|
35
|
+
FaultStatus,
|
|
36
|
+
FloorPlanDesired,
|
|
37
|
+
FloorPlanSummary,
|
|
38
|
+
History,
|
|
39
|
+
HistoryPoint,
|
|
40
|
+
HistorySeries,
|
|
41
|
+
Lamps,
|
|
42
|
+
Latest,
|
|
43
|
+
LatLng,
|
|
44
|
+
Limits,
|
|
45
|
+
PlatformType,
|
|
46
|
+
Position,
|
|
47
|
+
Reading,
|
|
48
|
+
Trip,
|
|
49
|
+
TripStatus,
|
|
50
|
+
)
|
|
51
|
+
from .stream import (
|
|
52
|
+
ConnectivityFrame,
|
|
53
|
+
ErrorFrame,
|
|
54
|
+
EventFrame,
|
|
55
|
+
Frame,
|
|
56
|
+
IMatrixStream,
|
|
57
|
+
PositionFrame,
|
|
58
|
+
ReplayDoneFrame,
|
|
59
|
+
SubscribedFrame,
|
|
60
|
+
ValuesFrame,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
__version__ = VERSION
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
"DEFAULT_BASE_URL",
|
|
67
|
+
"SCHEMA_VERSION",
|
|
68
|
+
"AbstractAuth",
|
|
69
|
+
"Account",
|
|
70
|
+
"AlarmLevel",
|
|
71
|
+
"AlarmSide",
|
|
72
|
+
"ApiKeyAuth",
|
|
73
|
+
"Channel",
|
|
74
|
+
"ChannelMode",
|
|
75
|
+
"ChannelState",
|
|
76
|
+
"Connectivity",
|
|
77
|
+
"ConnectivityFrame",
|
|
78
|
+
"ConnectivityState",
|
|
79
|
+
"Device",
|
|
80
|
+
"DeviceKind",
|
|
81
|
+
"DeviceState",
|
|
82
|
+
"ErrorFrame",
|
|
83
|
+
"Event",
|
|
84
|
+
"EventFrame",
|
|
85
|
+
"EventPage",
|
|
86
|
+
"EventType",
|
|
87
|
+
"Fault",
|
|
88
|
+
"FaultProtocol",
|
|
89
|
+
"FaultSeverity",
|
|
90
|
+
"FaultStatus",
|
|
91
|
+
"Faults",
|
|
92
|
+
"FloorPlanDesired",
|
|
93
|
+
"FloorPlanSummary",
|
|
94
|
+
"Frame",
|
|
95
|
+
"History",
|
|
96
|
+
"HistoryPoint",
|
|
97
|
+
"HistorySeries",
|
|
98
|
+
"IMatrixAuthError",
|
|
99
|
+
"IMatrixClient",
|
|
100
|
+
"IMatrixConnectionError",
|
|
101
|
+
"IMatrixError",
|
|
102
|
+
"IMatrixNotFoundError",
|
|
103
|
+
"IMatrixPermissionError",
|
|
104
|
+
"IMatrixRateLimitError",
|
|
105
|
+
"IMatrixResponseError",
|
|
106
|
+
"IMatrixStream",
|
|
107
|
+
"IMatrixUnsupportedSchemaError",
|
|
108
|
+
"Lamps",
|
|
109
|
+
"LatLng",
|
|
110
|
+
"Latest",
|
|
111
|
+
"Limits",
|
|
112
|
+
"PlatformType",
|
|
113
|
+
"Position",
|
|
114
|
+
"PositionFrame",
|
|
115
|
+
"Reading",
|
|
116
|
+
"ReplayDoneFrame",
|
|
117
|
+
"SubscribedFrame",
|
|
118
|
+
"TokenAuth",
|
|
119
|
+
"Trip",
|
|
120
|
+
"TripStatus",
|
|
121
|
+
"ValuesFrame",
|
|
122
|
+
"__version__",
|
|
123
|
+
]
|
pyimatrix/auth.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Credential handling and the HTTP request layer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from abc import ABC, abstractmethod
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import aiohttp
|
|
10
|
+
|
|
11
|
+
from .const import API_PREFIX, DEFAULT_TIMEOUT, SCHEMA_VERSION, USER_AGENT_PRODUCT, VERSION
|
|
12
|
+
from .exceptions import (
|
|
13
|
+
IMatrixAuthError,
|
|
14
|
+
IMatrixConnectionError,
|
|
15
|
+
IMatrixNotFoundError,
|
|
16
|
+
IMatrixPermissionError,
|
|
17
|
+
IMatrixRateLimitError,
|
|
18
|
+
IMatrixResponseError,
|
|
19
|
+
IMatrixUnsupportedSchemaError,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
_LOGGER = logging.getLogger(__package__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _retry_after(value: str | None) -> float | None:
|
|
26
|
+
if value is None:
|
|
27
|
+
return None
|
|
28
|
+
try:
|
|
29
|
+
return max(float(value), 0.0)
|
|
30
|
+
except ValueError:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AbstractAuth(ABC):
|
|
35
|
+
"""Sends authenticated requests. Subclasses supply the credential header."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
session: aiohttp.ClientSession,
|
|
40
|
+
base_url: str,
|
|
41
|
+
*,
|
|
42
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
43
|
+
user_agent: str | None = None,
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Use an injected session. The caller owns and closes it."""
|
|
46
|
+
self._session = session
|
|
47
|
+
self._base_url = base_url.rstrip("/")
|
|
48
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
49
|
+
self._ws_timeout = aiohttp.ClientWSTimeout(ws_close=10)
|
|
50
|
+
agent = f"{USER_AGENT_PRODUCT}/{VERSION}"
|
|
51
|
+
self._user_agent = f"{agent} {user_agent}" if user_agent else agent
|
|
52
|
+
self.rate_limit_remaining: int | None = None
|
|
53
|
+
|
|
54
|
+
@abstractmethod
|
|
55
|
+
async def async_get_auth_headers(self) -> dict[str, str]:
|
|
56
|
+
"""Return the header that carries the credential."""
|
|
57
|
+
|
|
58
|
+
async def request(self, path: str, params: dict[str, str] | None = None) -> dict[str, Any]:
|
|
59
|
+
"""GET an integration API path and return the parsed, version-checked body."""
|
|
60
|
+
return await self.send("GET", path, params=params)
|
|
61
|
+
|
|
62
|
+
async def send(
|
|
63
|
+
self,
|
|
64
|
+
method: str,
|
|
65
|
+
path: str,
|
|
66
|
+
*,
|
|
67
|
+
params: dict[str, str] | None = None,
|
|
68
|
+
json: Any = None,
|
|
69
|
+
) -> dict[str, Any]:
|
|
70
|
+
"""Call an integration API path with any method and return the version-checked body.
|
|
71
|
+
|
|
72
|
+
Writes exist only for the opt-in floor plan device sharing (spec 822 FR-28).
|
|
73
|
+
"""
|
|
74
|
+
url = f"{self._base_url}{API_PREFIX}{path}"
|
|
75
|
+
headers = {
|
|
76
|
+
"Accept": "application/json",
|
|
77
|
+
"User-Agent": self._user_agent,
|
|
78
|
+
**await self.async_get_auth_headers(),
|
|
79
|
+
}
|
|
80
|
+
try:
|
|
81
|
+
async with self._session.request(
|
|
82
|
+
method, url, params=params, json=json, headers=headers, timeout=self._timeout
|
|
83
|
+
) as resp:
|
|
84
|
+
self._record_rate_limit(resp)
|
|
85
|
+
_LOGGER.debug("%s %s -> %s", method, path, resp.status)
|
|
86
|
+
await self._raise_for_status(resp)
|
|
87
|
+
try:
|
|
88
|
+
body = await resp.json(content_type=None)
|
|
89
|
+
except ValueError as err:
|
|
90
|
+
raise IMatrixResponseError(f"invalid JSON from {path}") from err
|
|
91
|
+
except TimeoutError as err:
|
|
92
|
+
raise IMatrixConnectionError(f"timeout calling {path}") from err
|
|
93
|
+
except aiohttp.ClientError as err:
|
|
94
|
+
raise IMatrixConnectionError(f"error calling {path}: {err}") from err
|
|
95
|
+
if not isinstance(body, dict):
|
|
96
|
+
raise IMatrixResponseError(f"expected a JSON object from {path}")
|
|
97
|
+
if body.get("schemaVersion") != SCHEMA_VERSION:
|
|
98
|
+
raise IMatrixUnsupportedSchemaError(
|
|
99
|
+
f"{path} returned schemaVersion {body.get('schemaVersion')!r}, "
|
|
100
|
+
f"expected {SCHEMA_VERSION}"
|
|
101
|
+
)
|
|
102
|
+
return body
|
|
103
|
+
|
|
104
|
+
async def ws_connect(self, path: str) -> aiohttp.ClientWebSocketResponse:
|
|
105
|
+
"""Open an authenticated WebSocket on an integration API path.
|
|
106
|
+
|
|
107
|
+
Upgrade refusals map like REST: 401 to IMatrixAuthError, 403 to
|
|
108
|
+
IMatrixPermissionError, 404 (stream disabled on the server) to
|
|
109
|
+
IMatrixNotFoundError. aiohttp answers server pings (autoping).
|
|
110
|
+
"""
|
|
111
|
+
url = f"{self._base_url}{API_PREFIX}{path}"
|
|
112
|
+
headers = {"User-Agent": self._user_agent, **await self.async_get_auth_headers()}
|
|
113
|
+
try:
|
|
114
|
+
return await self._session.ws_connect(
|
|
115
|
+
url, headers=headers, heartbeat=None, autoping=True, timeout=self._ws_timeout
|
|
116
|
+
)
|
|
117
|
+
except aiohttp.WSServerHandshakeError as err:
|
|
118
|
+
if err.status == 401:
|
|
119
|
+
raise IMatrixAuthError(f"HTTP {err.status}") from err
|
|
120
|
+
if err.status == 403:
|
|
121
|
+
raise IMatrixPermissionError(f"HTTP {err.status}") from err
|
|
122
|
+
if err.status == 404:
|
|
123
|
+
raise IMatrixNotFoundError(f"HTTP {err.status}") from err
|
|
124
|
+
raise IMatrixConnectionError(f"stream upgrade failed: HTTP {err.status}") from err
|
|
125
|
+
except (TimeoutError, aiohttp.ClientError) as err:
|
|
126
|
+
raise IMatrixConnectionError(f"stream connect failed: {err}") from err
|
|
127
|
+
|
|
128
|
+
def _record_rate_limit(self, resp: aiohttp.ClientResponse) -> None:
|
|
129
|
+
remaining = resp.headers.get("RateLimit-Remaining")
|
|
130
|
+
if remaining is not None and remaining.isdigit():
|
|
131
|
+
self.rate_limit_remaining = int(remaining)
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
async def _raise_for_status(resp: aiohttp.ClientResponse) -> None:
|
|
135
|
+
status = resp.status
|
|
136
|
+
if status < 400:
|
|
137
|
+
return
|
|
138
|
+
message = f"HTTP {status}"
|
|
139
|
+
if status == 401:
|
|
140
|
+
raise IMatrixAuthError(message)
|
|
141
|
+
if status == 403:
|
|
142
|
+
raise IMatrixPermissionError(message)
|
|
143
|
+
if status == 404:
|
|
144
|
+
raise IMatrixNotFoundError(message)
|
|
145
|
+
if status == 429:
|
|
146
|
+
raise IMatrixRateLimitError(message, _retry_after(resp.headers.get("Retry-After")))
|
|
147
|
+
if status >= 500:
|
|
148
|
+
raise IMatrixConnectionError(message)
|
|
149
|
+
raise IMatrixResponseError(message)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class ApiKeyAuth(AbstractAuth):
|
|
153
|
+
"""Authenticates with an iMatrix API key (header X-API-Key)."""
|
|
154
|
+
|
|
155
|
+
def __init__(
|
|
156
|
+
self,
|
|
157
|
+
session: aiohttp.ClientSession,
|
|
158
|
+
base_url: str,
|
|
159
|
+
api_key: str,
|
|
160
|
+
**kwargs: Any,
|
|
161
|
+
) -> None:
|
|
162
|
+
"""Store the key. It is never logged."""
|
|
163
|
+
super().__init__(session, base_url, **kwargs)
|
|
164
|
+
self._api_key = api_key
|
|
165
|
+
|
|
166
|
+
async def async_get_auth_headers(self) -> dict[str, str]:
|
|
167
|
+
"""Return the X-API-Key header."""
|
|
168
|
+
return {"X-API-Key": self._api_key}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class TokenAuth(AbstractAuth):
|
|
172
|
+
"""Base for OAuth2: subclasses return a valid access token, sent as a Bearer header."""
|
|
173
|
+
|
|
174
|
+
@abstractmethod
|
|
175
|
+
async def async_get_access_token(self) -> str:
|
|
176
|
+
"""Return a valid access token, refreshing it first if needed."""
|
|
177
|
+
|
|
178
|
+
async def async_get_auth_headers(self) -> dict[str, str]:
|
|
179
|
+
"""Return the Authorization header."""
|
|
180
|
+
return {"Authorization": f"Bearer {await self.async_get_access_token()}"}
|
pyimatrix/client.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Client for the iMatrix integration API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .auth import AbstractAuth
|
|
11
|
+
from .const import DEVICE_PAGE_SIZE, MAX_DEVICES_PER_LATEST, MAX_HISTORY_SENSORS
|
|
12
|
+
from .exceptions import IMatrixResponseError
|
|
13
|
+
from .models import (
|
|
14
|
+
Account,
|
|
15
|
+
Device,
|
|
16
|
+
DeviceState,
|
|
17
|
+
EventPage,
|
|
18
|
+
EventType,
|
|
19
|
+
Faults,
|
|
20
|
+
FloorPlanDesired,
|
|
21
|
+
FloorPlanSummary,
|
|
22
|
+
History,
|
|
23
|
+
Latest,
|
|
24
|
+
Trip,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _csv(values: Iterable[int]) -> str:
|
|
29
|
+
return ",".join(str(v) for v in values)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _window(start: datetime | None, end: datetime | None) -> dict[str, str]:
|
|
33
|
+
params: dict[str, str] = {}
|
|
34
|
+
if start is not None:
|
|
35
|
+
params["from"] = start.isoformat()
|
|
36
|
+
if end is not None:
|
|
37
|
+
params["to"] = end.isoformat()
|
|
38
|
+
return params
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class IMatrixClient:
|
|
42
|
+
"""Read-only client. One instance per credential."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, auth: AbstractAuth) -> None:
|
|
45
|
+
"""Wrap an auth object that performs the requests."""
|
|
46
|
+
self.auth = auth
|
|
47
|
+
|
|
48
|
+
async def get_account(self) -> Account:
|
|
49
|
+
"""Return the org and permissions of the credential."""
|
|
50
|
+
return Account.from_dict(await self.auth.request("/account"))
|
|
51
|
+
|
|
52
|
+
async def get_devices(self, group_ids: Iterable[int] | None = None) -> list[Device]:
|
|
53
|
+
"""Return every visible device, following pagination. group_ids include subgroups."""
|
|
54
|
+
params: dict[str, str] = {"limit": str(DEVICE_PAGE_SIZE)}
|
|
55
|
+
if group_ids is not None:
|
|
56
|
+
params["groupIds"] = _csv(group_ids)
|
|
57
|
+
devices: list[Device] = []
|
|
58
|
+
seen_cursors: set[str] = set()
|
|
59
|
+
while True:
|
|
60
|
+
body = await self.auth.request("/devices", params)
|
|
61
|
+
devices.extend(Device.from_dict(d) for d in body.get("devices") or ())
|
|
62
|
+
cursor = body.get("nextCursor")
|
|
63
|
+
if not cursor:
|
|
64
|
+
return devices
|
|
65
|
+
if cursor in seen_cursors:
|
|
66
|
+
raise IMatrixResponseError("device pagination returned a repeated cursor")
|
|
67
|
+
seen_cursors.add(cursor)
|
|
68
|
+
params["cursor"] = str(cursor)
|
|
69
|
+
|
|
70
|
+
async def get_latest(
|
|
71
|
+
self,
|
|
72
|
+
sns: Iterable[int] | None = None,
|
|
73
|
+
*,
|
|
74
|
+
group_ids: Iterable[int] | None = None,
|
|
75
|
+
since: datetime | None = None,
|
|
76
|
+
) -> Latest:
|
|
77
|
+
"""Return latest state. sns over 500 are split into several requests and merged."""
|
|
78
|
+
base: dict[str, str] = {}
|
|
79
|
+
if group_ids is not None:
|
|
80
|
+
base["groupIds"] = _csv(group_ids)
|
|
81
|
+
if since is not None:
|
|
82
|
+
base["since"] = since.isoformat()
|
|
83
|
+
if sns is None:
|
|
84
|
+
return Latest.from_dict(await self.auth.request("/latest", base))
|
|
85
|
+
|
|
86
|
+
sn_list = list(dict.fromkeys(sns))
|
|
87
|
+
if not sn_list:
|
|
88
|
+
return Latest(server_time=None, devices={})
|
|
89
|
+
merged: dict[int, DeviceState] = {}
|
|
90
|
+
server_time = None
|
|
91
|
+
for start in range(0, len(sn_list), MAX_DEVICES_PER_LATEST):
|
|
92
|
+
chunk = sn_list[start : start + MAX_DEVICES_PER_LATEST]
|
|
93
|
+
body = await self.auth.request("/latest", {**base, "sns": _csv(chunk)})
|
|
94
|
+
part = Latest.from_dict(body)
|
|
95
|
+
merged.update(part.devices)
|
|
96
|
+
# The earliest server time is the safe "since" for the next poll.
|
|
97
|
+
if part.server_time and (server_time is None or part.server_time < server_time):
|
|
98
|
+
server_time = part.server_time
|
|
99
|
+
return Latest(server_time=server_time, devices=merged)
|
|
100
|
+
|
|
101
|
+
async def get_faults(self, sn: int) -> Faults:
|
|
102
|
+
"""Return active and reported faults of the last 7 days, and the lamps."""
|
|
103
|
+
return Faults.from_dict(await self.auth.request(f"/devices/{int(sn)}/faults"))
|
|
104
|
+
|
|
105
|
+
async def get_history(
|
|
106
|
+
self,
|
|
107
|
+
sn: int,
|
|
108
|
+
sensor_ids: Iterable[int],
|
|
109
|
+
start: datetime | None = None,
|
|
110
|
+
end: datetime | None = None,
|
|
111
|
+
) -> History:
|
|
112
|
+
"""Return hourly history. Server limits: 1-20 sensors, at most 7 days."""
|
|
113
|
+
ids = list(dict.fromkeys(sensor_ids))
|
|
114
|
+
if not 1 <= len(ids) <= MAX_HISTORY_SENSORS:
|
|
115
|
+
raise ValueError(f"sensor_ids must hold 1 to {MAX_HISTORY_SENSORS} ids")
|
|
116
|
+
params = {"sensorIds": _csv(ids), "bucket": "1h", **_window(start, end)}
|
|
117
|
+
return History.from_dict(await self.auth.request(f"/devices/{int(sn)}/history", params))
|
|
118
|
+
|
|
119
|
+
async def get_trips(
|
|
120
|
+
self, sn: int, start: datetime | None = None, end: datetime | None = None
|
|
121
|
+
) -> list[Trip]:
|
|
122
|
+
"""Return trips, newest first. Server limit: 31 days, default the last 7."""
|
|
123
|
+
body = await self.auth.request(f"/devices/{int(sn)}/trips", _window(start, end))
|
|
124
|
+
return [Trip.from_dict(t) for t in body.get("trips") or ()]
|
|
125
|
+
|
|
126
|
+
async def get_events(
|
|
127
|
+
self,
|
|
128
|
+
after: int | None = None,
|
|
129
|
+
*,
|
|
130
|
+
types: Iterable[EventType | str] | None = None,
|
|
131
|
+
limit: int | None = None,
|
|
132
|
+
) -> EventPage:
|
|
133
|
+
"""Return events after a cursor, oldest first.
|
|
134
|
+
|
|
135
|
+
Without `after` the page is empty and next_after is the newest id: store it as
|
|
136
|
+
the starting cursor so events from before setup are never replayed.
|
|
137
|
+
"""
|
|
138
|
+
params: dict[str, str] = {}
|
|
139
|
+
if after is not None:
|
|
140
|
+
params["after"] = str(int(after))
|
|
141
|
+
if types is not None:
|
|
142
|
+
params["types"] = ",".join(str(t) for t in types)
|
|
143
|
+
if limit is not None:
|
|
144
|
+
params["limit"] = str(int(limit))
|
|
145
|
+
return EventPage.from_dict(await self.auth.request("/events", params))
|
|
146
|
+
|
|
147
|
+
async def get_floor_plans(self) -> list[FloorPlanSummary]:
|
|
148
|
+
"""Return the floor plans the credential can see (spec 822 FR-22)."""
|
|
149
|
+
body = await self.auth.request("/floor-plans")
|
|
150
|
+
return [FloorPlanSummary.from_dict(p) for p in body.get("list") or ()]
|
|
151
|
+
|
|
152
|
+
async def get_floor_plan_desired(
|
|
153
|
+
self, plan_id: str, *, instance_id: str | None = None, policy: dict[str, Any] | None = None
|
|
154
|
+
) -> FloorPlanDesired:
|
|
155
|
+
"""Return the desired Home Assistant state for one plan and HA instance (spec 822 FR-6)."""
|
|
156
|
+
params: dict[str, str] = {}
|
|
157
|
+
if instance_id:
|
|
158
|
+
params["instanceId"] = instance_id
|
|
159
|
+
if policy:
|
|
160
|
+
params["policy"] = json.dumps(policy, separators=(",", ":"))
|
|
161
|
+
body = await self.auth.request(f"/floor-plans/{plan_id}/ha-desired", params)
|
|
162
|
+
return FloorPlanDesired.from_dict(body)
|
|
163
|
+
|
|
164
|
+
async def put_ha_devices(self, instance_id: str, devices: list[dict[str, Any]]) -> int:
|
|
165
|
+
"""Replace the shared HA device list for one instance (spec 822 FR-28).
|
|
166
|
+
|
|
167
|
+
Returns the number of devices stored.
|
|
168
|
+
"""
|
|
169
|
+
body = await self.auth.send(
|
|
170
|
+
"PUT", "/ha-devices", json={"instanceId": instance_id, "devices": devices}
|
|
171
|
+
)
|
|
172
|
+
return int(body.get("count") or 0)
|
|
173
|
+
|
|
174
|
+
async def delete_ha_devices(self, instance_id: str) -> None:
|
|
175
|
+
"""Withdraw the shared HA device list for one instance (spec 822 FR-29)."""
|
|
176
|
+
await self.auth.send("DELETE", "/ha-devices", params={"instanceId": instance_id})
|
pyimatrix/const.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Constants shared by the client."""
|
|
2
|
+
|
|
3
|
+
from typing import Final
|
|
4
|
+
|
|
5
|
+
VERSION: Final = "0.1.0"
|
|
6
|
+
DEFAULT_BASE_URL: Final = "https://api.imatrixsys.com"
|
|
7
|
+
API_PREFIX: Final = "/api/v1/integration"
|
|
8
|
+
SCHEMA_VERSION: Final = 1
|
|
9
|
+
DEFAULT_TIMEOUT: Final = 20.0
|
|
10
|
+
USER_AGENT_PRODUCT: Final = "pyimatrix"
|
|
11
|
+
MAX_DEVICES_PER_LATEST: Final = 500
|
|
12
|
+
DEVICE_PAGE_SIZE: Final = 500
|
|
13
|
+
MAX_HISTORY_SENSORS: Final = 20
|
pyimatrix/exceptions.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Exceptions raised by pyimatrix."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class IMatrixError(Exception):
|
|
7
|
+
"""Base class for all pyimatrix errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class IMatrixAuthError(IMatrixError):
|
|
11
|
+
"""The credential is missing, invalid, expired or revoked (HTTP 401)."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class IMatrixPermissionError(IMatrixError):
|
|
15
|
+
"""The credential is valid but lacks a permission (HTTP 403)."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class IMatrixNotFoundError(IMatrixError):
|
|
19
|
+
"""The resource does not exist or is not visible to the caller (HTTP 404)."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class IMatrixRateLimitError(IMatrixError):
|
|
23
|
+
"""The per-key request limit was exceeded (HTTP 429)."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, message: str, retry_after: float | None) -> None:
|
|
26
|
+
"""Store the server's Retry-After value in seconds, if it sent one."""
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.retry_after = retry_after
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class IMatrixConnectionError(IMatrixError):
|
|
32
|
+
"""The API could not be reached, timed out, or returned a 5xx status."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class IMatrixResponseError(IMatrixError):
|
|
36
|
+
"""The API returned a body that could not be parsed."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class IMatrixUnsupportedSchemaError(IMatrixResponseError):
|
|
40
|
+
"""The API returned a schemaVersion this library does not understand."""
|