python-steronix 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.
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.5
2
+ Name: python-steronix
3
+ Version: 0.1.0
4
+ Summary: Async Python client of the Steronix integrations API: read a Steronix device and open its relays
5
+ Project-URL: Homepage, https://github.com/gate-control-dev/python-steronix
6
+ Project-URL: Issues, https://github.com/gate-control-dev/python-steronix/issues
7
+ Project-URL: Changelog, https://github.com/gate-control-dev/python-steronix/blob/main/CHANGELOG.md
8
+ Author: EVO Lab
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: asyncio,gate,home-assistant,relay,steronix
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Home Automation
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.13
22
+ Requires-Dist: aiohttp>=3.10
23
+ Requires-Dist: yarl>=1.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # python-steronix
27
+
28
+ Async Python client of the Steronix integrations API (`integrations-v1`,
29
+ contract version 1.1.0). It reads one Steronix device and opens its relays
30
+ with an integration token. It is the library behind the Steronix Home
31
+ Assistant integration.
32
+
33
+ - Typed models: `TokenInfo`, `Device` (relays and inputs), `OpenResult`.
34
+ - One error class per answer of the API.
35
+ - Opens with an idempotency key per button press; never retried on their own.
36
+ - Long polling for live changes, with plain polling as the fallback.
37
+ - HTTPS only: the client refuses an `http://` base URL and never follows a
38
+ redirect, so the token is never sent in clear.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install python-steronix
44
+ ```
45
+
46
+ Python 3.13 or newer; the only dependency is `aiohttp`.
47
+
48
+ ## The token
49
+
50
+ The device's owner creates a token on the portal, **Controls →
51
+ Integrations → Create token**. It is shown once. A token is for one device
52
+ and the relays chosen when it was made. It ends when it expires, when it is
53
+ revoked, when the device changes owner, or when its creator's account is
54
+ deleted. Treat it as an opaque string and keep it secret.
55
+
56
+ ## Use
57
+
58
+ ```python
59
+ import asyncio
60
+
61
+ import aiohttp
62
+
63
+ from steronix import Actor, ActorType, SteronixClient
64
+
65
+
66
+ async def main() -> None:
67
+ async with aiohttp.ClientSession() as session:
68
+ client = SteronixClient(session, "stx_…")
69
+
70
+ token = await client.get_token()
71
+ print(token.name, token.relays, token.expires_at)
72
+
73
+ result = await client.get_device()
74
+ device = result.device
75
+ print(device.name, device.online, [i.active for i in device.inputs])
76
+
77
+ opened = await client.open_relay(1, Actor(ActorType.USER, name="Ivan", login="ivan"))
78
+ print("opened, log event", opened.open_number)
79
+
80
+
81
+ asyncio.run(main())
82
+ ```
83
+
84
+ The default base URL is production, `https://evo-lab.cloud/api/integrations/v1`.
85
+ Pass `base_url=` for another server.
86
+
87
+ ### Following the device
88
+
89
+ `DeviceWatcher` yields the device's state at start and after every change.
90
+ It asks `GET /device?wait=30` with the last `ETag`; the server answers as
91
+ soon as the state changes, else after 30 s with `304`, and it asks again at
92
+ once. When long polling fails it polls every 10 s and tries long polling
93
+ again after 5 minutes.
94
+
95
+ ```python
96
+ from steronix import DeviceWatcher, SteronixAuthenticationError, SteronixError
97
+
98
+ watcher = DeviceWatcher(client)
99
+ try:
100
+ async for update in watcher.updates():
101
+ if isinstance(update, SteronixError):
102
+ ... # the API cannot be reached now; show the device as unavailable
103
+ else:
104
+ ... # a new state of the device
105
+ except SteronixAuthenticationError:
106
+ ... # the token no longer works: ask for a new one
107
+ ```
108
+
109
+ For one wait yourself: `await client.wait_for_change(etag, wait=30)` returns
110
+ the new state, or `None` when nothing changed.
111
+
112
+ ## Errors
113
+
114
+ Every error is a `SteronixError`.
115
+
116
+ | Error | When |
117
+ |---|---|
118
+ | `SteronixConnectionError` | The API cannot be reached: network, TLS or timeout |
119
+ | `SteronixInvalidResponseError` | An answer the contract does not describe |
120
+ | `SteronixBadRequestError` | 400: the request does not match the contract |
121
+ | `SteronixAuthenticationError` | 401: the token is missing, unknown, expired or revoked, or its grant ended |
122
+ | `SteronixRelayNotAllowedError` | 403: the token may not open this relay |
123
+ | `SteronixDeviceOfflineError` | 409 `DEVICE_OFFLINE`: nothing was sent to the device |
124
+ | `SteronixRelayBlockedError` | 409 `RELAY_BLOCKED`: the schedule or the manual lock holds the relay |
125
+ | `SteronixRateLimitError` | 429: too many requests; wait `retry_after` seconds |
126
+ | `SteronixUnavailableError` | 503: integrations are off or the token cannot be checked now |
127
+ | `SteronixNoAnswerError` | 504: the open was sent, the device did not answer; whether it opened is unknown |
128
+ | `SteronixResponseError` | Any other error status; the base class of the ones above |
129
+
130
+ A response error has `status`, `code`, `problem` (the RFC 9457 body, or
131
+ `None`) and `retry_after` (from `Retry-After`, or `None`). A 429 from the
132
+ edge's flood brake has no body; it is the same `SteronixRateLimitError`.
133
+
134
+ ## Limits
135
+
136
+ The server limits each token: one open per relay every 2 seconds, 60 opens
137
+ an hour, a few immediate reads a minute and at most 2 waiting reads at once.
138
+ Over a limit the answer is 429 with `Retry-After`.
139
+
140
+ ## Development
141
+
142
+ ```bash
143
+ uv sync
144
+ uv run pytest
145
+ uv run ruff check . && uv run ruff format --check . && uv run mypy src
146
+ uv build
147
+ ```
148
+
149
+ The tests run a fake API over real HTTPS. `contract/` holds the pinned
150
+ contract the tests check against. `examples/smoke.py` tries a real token:
151
+
152
+ ```bash
153
+ STX_TOKEN=stx_… uv run python examples/smoke.py --seconds 60
154
+ ```
155
+
156
+ ## Licence
157
+
158
+ Apache-2.0
@@ -0,0 +1,11 @@
1
+ steronix/__init__.py,sha256=w9G-JRoFDyyqSWxzfF8neqeBqYjs3gbElGDBGE7wFeU,1503
2
+ steronix/client.py,sha256=8lQTq__EoBi4s7GUTZSZUJQoa2U_tYHVaZM9cd2ESrA,9288
3
+ steronix/const.py,sha256=52G0WigiimIECTUHFmRwb22jBU77k41IHEfTCqwus_Q,782
4
+ steronix/exceptions.py,sha256=BvIKaFAZJLNwVA8Qw69BUFjHOBU1T3P0wPf7BY5R0n4,3235
5
+ steronix/models.py,sha256=UUm6yy-xZ48pmmaxcDxODwtbXTlEQ6_KRpS9nRvXE-Q,7964
6
+ steronix/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ steronix/watch.py,sha256=ZkzjJA7pztdPADuAJykxh-7ZgtCArwJm1idxTqRO5hk,5509
8
+ python_steronix-0.1.0.dist-info/METADATA,sha256=fCQS0PWZ27lxfHlyjIbJVdDPA7UhIMP55asR3I4AsTE,5747
9
+ python_steronix-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ python_steronix-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ python_steronix-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
steronix/__init__.py ADDED
@@ -0,0 +1,65 @@
1
+ """Async Python client of the Steronix integrations API (integrations-v1.1.0)."""
2
+
3
+ from .client import SteronixClient, check_base_url
4
+ from .const import API_VERSION, DEFAULT_BASE_URL, MAX_WAIT
5
+ from .exceptions import (
6
+ Problem,
7
+ SteronixAuthenticationError,
8
+ SteronixBadRequestError,
9
+ SteronixConnectionError,
10
+ SteronixDeviceOfflineError,
11
+ SteronixError,
12
+ SteronixInvalidResponseError,
13
+ SteronixNoAnswerError,
14
+ SteronixRateLimitError,
15
+ SteronixRelayBlockedError,
16
+ SteronixRelayNotAllowedError,
17
+ SteronixResponseError,
18
+ SteronixUnavailableError,
19
+ )
20
+ from .models import (
21
+ KIND_HOME_ASSISTANT,
22
+ Actor,
23
+ ActorType,
24
+ Device,
25
+ DeviceResult,
26
+ Input,
27
+ OpenResult,
28
+ Relay,
29
+ TokenInfo,
30
+ )
31
+ from .watch import DeviceWatcher
32
+
33
+ __version__ = "0.1.0"
34
+
35
+ __all__ = [
36
+ "API_VERSION",
37
+ "DEFAULT_BASE_URL",
38
+ "KIND_HOME_ASSISTANT",
39
+ "MAX_WAIT",
40
+ "Actor",
41
+ "ActorType",
42
+ "Device",
43
+ "DeviceResult",
44
+ "DeviceWatcher",
45
+ "Input",
46
+ "OpenResult",
47
+ "Problem",
48
+ "Relay",
49
+ "SteronixAuthenticationError",
50
+ "SteronixBadRequestError",
51
+ "SteronixClient",
52
+ "SteronixConnectionError",
53
+ "SteronixDeviceOfflineError",
54
+ "SteronixError",
55
+ "SteronixInvalidResponseError",
56
+ "SteronixNoAnswerError",
57
+ "SteronixRateLimitError",
58
+ "SteronixRelayBlockedError",
59
+ "SteronixRelayNotAllowedError",
60
+ "SteronixResponseError",
61
+ "SteronixUnavailableError",
62
+ "TokenInfo",
63
+ "__version__",
64
+ "check_base_url",
65
+ ]
steronix/client.py ADDED
@@ -0,0 +1,261 @@
1
+ """The async client of the Steronix integrations API (integrations-v1.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import uuid
8
+ from datetime import UTC, datetime
9
+ from email.utils import parsedate_to_datetime
10
+ from typing import Any
11
+
12
+ import aiohttp
13
+ from multidict import CIMultiDictProxy
14
+ from yarl import URL
15
+
16
+ from .const import DEFAULT_BASE_URL, DEFAULT_REQUEST_TIMEOUT, MAX_WAIT, OPEN_TIMEOUT, RELAYS
17
+ from .exceptions import (
18
+ Problem,
19
+ SteronixAuthenticationError,
20
+ SteronixBadRequestError,
21
+ SteronixConnectionError,
22
+ SteronixDeviceOfflineError,
23
+ SteronixInvalidResponseError,
24
+ SteronixNoAnswerError,
25
+ SteronixRateLimitError,
26
+ SteronixRelayBlockedError,
27
+ SteronixRelayNotAllowedError,
28
+ SteronixResponseError,
29
+ SteronixUnavailableError,
30
+ )
31
+ from .models import Actor, Device, DeviceResult, OpenResult, TokenInfo
32
+
33
+ _IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,64}$")
34
+
35
+ # A waiting request may take the whole wait; the client allows that plus a
36
+ # plain request's time.
37
+ _WAIT_SLACK = DEFAULT_REQUEST_TIMEOUT
38
+
39
+
40
+ def check_base_url(base_url: str) -> URL:
41
+ """The base URL as the client uses it; ``ValueError`` unless it is HTTPS.
42
+
43
+ The token must never travel in clear: a redirect from ``http://`` comes
44
+ after the token was already sent.
45
+ """
46
+ url = URL(base_url)
47
+ if url.scheme != "https":
48
+ raise ValueError("the base URL must start with https://")
49
+ if not url.host:
50
+ raise ValueError("the base URL has no host")
51
+ if url.query_string or url.fragment or url.user or url.password:
52
+ raise ValueError("the base URL must not have a query, a fragment or credentials")
53
+ return url.with_path(url.path.rstrip("/"))
54
+
55
+
56
+ class SteronixClient:
57
+ """Read one Steronix device and open its relays with an integration token.
58
+
59
+ The token is created on the portal's Controls → Integrations and is for
60
+ one device. It is opaque: the client does not check its shape.
61
+
62
+ The client never retries an open and never follows a redirect.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ session: aiohttp.ClientSession,
68
+ token: str,
69
+ *,
70
+ base_url: str = DEFAULT_BASE_URL,
71
+ request_timeout: float = DEFAULT_REQUEST_TIMEOUT,
72
+ ) -> None:
73
+ if not token or not token.strip():
74
+ raise ValueError("the token is empty")
75
+ self._session = session
76
+ self._token = token.strip()
77
+ self._base_url = check_base_url(base_url)
78
+ self._request_timeout = request_timeout
79
+
80
+ def __repr__(self) -> str:
81
+ # Never show the token.
82
+ return f"SteronixClient(base_url={str(self._base_url)!r})"
83
+
84
+ @property
85
+ def base_url(self) -> str:
86
+ return str(self._base_url)
87
+
88
+ async def get_token(self) -> TokenInfo:
89
+ """What the token may do: its name, relays, expiry and device."""
90
+ _, _, data = await self._request("GET", "/token")
91
+ return TokenInfo.from_json(data)
92
+
93
+ async def get_device(self) -> DeviceResult:
94
+ """The device's state now, with the ETag to wait for its next change."""
95
+ _, headers, data = await self._request("GET", "/device")
96
+ return DeviceResult(Device.from_json(data), headers.get("ETag"))
97
+
98
+ async def wait_for_change(self, etag: str, *, wait: int = MAX_WAIT) -> DeviceResult | None:
99
+ """Wait up to ``wait`` seconds for the device to differ from ``etag``.
100
+
101
+ Returns the new state as soon as it differs, or ``None`` when nothing
102
+ changed within the wait (304). A token that ended while the request
103
+ waited raises ``SteronixAuthenticationError``.
104
+ """
105
+ if not 1 <= wait <= MAX_WAIT:
106
+ raise ValueError(f"wait must be 1 to {MAX_WAIT} seconds")
107
+ if not etag:
108
+ raise ValueError("etag is empty")
109
+ status, headers, data = await self._request(
110
+ "GET",
111
+ "/device",
112
+ params={"wait": str(wait)},
113
+ headers={"If-None-Match": etag},
114
+ seconds=wait + _WAIT_SLACK,
115
+ )
116
+ if status == 304:
117
+ return None
118
+ return DeviceResult(Device.from_json(data), headers.get("ETag"))
119
+
120
+ async def open_relay(
121
+ self,
122
+ relay: int,
123
+ actor: Actor,
124
+ *,
125
+ idempotency_key: str | None = None,
126
+ ) -> OpenResult:
127
+ """Open a relay and wait for the device's answer.
128
+
129
+ ``idempotency_key`` identifies one button press; a new random one is
130
+ made when it is not given. Sending the same key again within 60 s
131
+ returns the first answer and opens nothing.
132
+
133
+ Raises ``SteronixNoAnswerError`` when the device did not answer in
134
+ time: whether the relay opened is unknown, so this is never retried.
135
+ """
136
+ if relay not in RELAYS:
137
+ raise ValueError(f"relay must be one of {RELAYS}")
138
+ key = idempotency_key if idempotency_key is not None else uuid.uuid4().hex
139
+ if not _IDEMPOTENCY_KEY.match(key):
140
+ raise ValueError("idempotency_key must be 1-64 characters of A-Z a-z 0-9 . _ : -")
141
+ _, _, data = await self._request(
142
+ "POST",
143
+ f"/relays/{relay}/open",
144
+ headers={"Idempotency-Key": key},
145
+ json_body={"actor": actor.to_json()},
146
+ seconds=OPEN_TIMEOUT,
147
+ )
148
+ return OpenResult.from_json(data)
149
+
150
+ async def _request(
151
+ self,
152
+ method: str,
153
+ path: str,
154
+ *,
155
+ params: dict[str, str] | None = None,
156
+ headers: dict[str, str] | None = None,
157
+ json_body: dict[str, Any] | None = None,
158
+ seconds: float | None = None,
159
+ ) -> tuple[int, CIMultiDictProxy[str], Any]:
160
+ url = self._base_url.with_path(self._base_url.path + path)
161
+ if params:
162
+ url = url.with_query(params)
163
+ request_headers = {
164
+ "Authorization": f"Bearer {self._token}",
165
+ "Accept": "application/json",
166
+ **(headers or {}),
167
+ }
168
+ try:
169
+ async with self._session.request(
170
+ method,
171
+ url,
172
+ headers=request_headers,
173
+ json=json_body,
174
+ allow_redirects=False,
175
+ timeout=aiohttp.ClientTimeout(total=seconds or self._request_timeout),
176
+ ) as response:
177
+ body = await response.read()
178
+ status = response.status
179
+ response_headers = response.headers
180
+ except TimeoutError as err:
181
+ raise SteronixConnectionError("the request to the Steronix API timed out") from err
182
+ except aiohttp.ClientError as err:
183
+ raise SteronixConnectionError(f"cannot reach the Steronix API: {err}") from err
184
+
185
+ if status == 304:
186
+ return status, response_headers, None
187
+ if 200 <= status < 300:
188
+ try:
189
+ return status, response_headers, json.loads(body)
190
+ except ValueError as err:
191
+ raise SteronixInvalidResponseError("the answer is not JSON") from err
192
+ raise _error(status, response_headers, body)
193
+
194
+
195
+ def _error(status: int, headers: CIMultiDictProxy[str], body: bytes) -> SteronixResponseError:
196
+ problem = _problem(status, body)
197
+ retry_after = _retry_after(headers.get("Retry-After"))
198
+ code = problem.code if problem else None
199
+ cls: type[SteronixResponseError] = SteronixResponseError
200
+ if status == 400:
201
+ cls = SteronixBadRequestError
202
+ elif status == 401:
203
+ cls = SteronixAuthenticationError
204
+ elif status == 403 and code == "RELAY_NOT_ALLOWED":
205
+ cls = SteronixRelayNotAllowedError
206
+ elif status == 409 and code == "DEVICE_OFFLINE":
207
+ cls = SteronixDeviceOfflineError
208
+ elif status == 409 and code == "RELAY_BLOCKED":
209
+ cls = SteronixRelayBlockedError
210
+ elif status == 429:
211
+ # From the backend with a body or from the edge without: alike.
212
+ cls = SteronixRateLimitError
213
+ elif status == 503:
214
+ cls = SteronixUnavailableError
215
+ elif status == 504 and code == "NO_ANSWER":
216
+ cls = SteronixNoAnswerError
217
+ return cls(status, problem, retry_after)
218
+
219
+
220
+ def _problem(status: int, body: bytes) -> Problem | None:
221
+ """The problem body, read as JSON whatever its content type says."""
222
+ if not body.strip():
223
+ return None
224
+ try:
225
+ data = json.loads(body)
226
+ except ValueError:
227
+ return None
228
+ if not isinstance(data, dict):
229
+ return None
230
+
231
+ def text(key: str) -> str | None:
232
+ value = data.get(key)
233
+ return value if isinstance(value, str) else None
234
+
235
+ return Problem(
236
+ status=status,
237
+ code=text("code"),
238
+ type=text("type"),
239
+ title=text("title"),
240
+ detail=text("detail"),
241
+ instance=text("instance"),
242
+ )
243
+
244
+
245
+ def _retry_after(value: str | None, now: datetime | None = None) -> float | None:
246
+ """``Retry-After`` in seconds: delay-seconds or an HTTP date."""
247
+ if value is None:
248
+ return None
249
+ value = value.strip()
250
+ if value.isdigit():
251
+ return float(value)
252
+ try:
253
+ when = parsedate_to_datetime(value)
254
+ except (TypeError, ValueError):
255
+ return None
256
+ if when.tzinfo is None:
257
+ when = when.replace(tzinfo=UTC)
258
+ return max(0.0, (when - (now or datetime.now(UTC))).total_seconds())
259
+
260
+
261
+ __all__ = ["SteronixClient", "check_base_url"]
steronix/const.py ADDED
@@ -0,0 +1,25 @@
1
+ """Constants of the Steronix integrations API (integrations-v1.1.0)."""
2
+
3
+ from typing import Final
4
+
5
+ #: The production base URL of the integrations API.
6
+ DEFAULT_BASE_URL: Final = "https://evo-lab.cloud/api/integrations/v1"
7
+
8
+ #: The contract version this library is written against.
9
+ API_VERSION: Final = "1.1.0"
10
+
11
+ #: The longest a ``GET /device`` may wait for a change, in seconds.
12
+ MAX_WAIT: Final = 30
13
+
14
+ #: How long a plain request may take, in seconds.
15
+ DEFAULT_REQUEST_TIMEOUT: Final = 15.0
16
+
17
+ #: An open waits for the device's answer up to 10 s on the server; the
18
+ #: client allows that plus the way there and back.
19
+ OPEN_TIMEOUT: Final = 25.0
20
+
21
+ #: The longest string the server takes in an actor field.
22
+ ACTOR_FIELD_MAX: Final = 128
23
+
24
+ #: Relays a Steronix device has.
25
+ RELAYS: Final = (1, 2)
steronix/exceptions.py ADDED
@@ -0,0 +1,107 @@
1
+ """Errors of the Steronix client, one per answer of the integrations API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class Problem:
10
+ """An RFC 9457 problem body as the API sends it.
11
+
12
+ The backend and the edge both send one, except the edge's flood brake,
13
+ whose 429 has no body.
14
+ """
15
+
16
+ status: int
17
+ code: str | None = None
18
+ type: str | None = None
19
+ title: str | None = None
20
+ detail: str | None = None
21
+ instance: str | None = None
22
+
23
+
24
+ class SteronixError(Exception):
25
+ """Base class of every error this library raises."""
26
+
27
+
28
+ class SteronixConnectionError(SteronixError):
29
+ """The API could not be reached: network, TLS or timeout."""
30
+
31
+
32
+ class SteronixInvalidResponseError(SteronixError):
33
+ """The API answered with something the contract does not describe."""
34
+
35
+
36
+ class SteronixResponseError(SteronixError):
37
+ """The API answered with an error status.
38
+
39
+ ``problem`` is the problem body when there is one. ``retry_after`` is the
40
+ ``Retry-After`` header in seconds, when the answer has it.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ status: int,
46
+ problem: Problem | None = None,
47
+ retry_after: float | None = None,
48
+ ) -> None:
49
+ self.status = status
50
+ self.problem = problem
51
+ self.retry_after = retry_after
52
+ detail = problem.detail if problem and problem.detail else None
53
+ code = problem.code if problem and problem.code else None
54
+ text = f"HTTP {status}"
55
+ if code:
56
+ text += f" {code}"
57
+ if detail:
58
+ text += f": {detail}"
59
+ super().__init__(text)
60
+
61
+ @property
62
+ def code(self) -> str | None:
63
+ """The problem's ``code``, when the answer has a problem body."""
64
+ return self.problem.code if self.problem else None
65
+
66
+
67
+ class SteronixBadRequestError(SteronixResponseError):
68
+ """400: the request does not match the contract. Nothing was done."""
69
+
70
+
71
+ class SteronixAuthenticationError(SteronixResponseError):
72
+ """401: the token is missing, unknown, expired or revoked, or its grant ended.
73
+
74
+ Every case is the same answer. A new token is needed.
75
+ """
76
+
77
+
78
+ class SteronixRelayNotAllowedError(SteronixResponseError):
79
+ """403: the token may not open this relay."""
80
+
81
+
82
+ class SteronixDeviceOfflineError(SteronixResponseError):
83
+ """409 DEVICE_OFFLINE: the device is offline; nothing was sent to it."""
84
+
85
+
86
+ class SteronixRelayBlockedError(SteronixResponseError):
87
+ """409 RELAY_BLOCKED: the schedule or the manual lock holds the relay."""
88
+
89
+
90
+ class SteronixRateLimitError(SteronixResponseError):
91
+ """429: too many requests; nothing was sent to the device.
92
+
93
+ It comes from the backend (over a limit of the token or the device, with
94
+ a problem body) or from the edge's flood brake (no body). Both are
95
+ treated alike: wait ``retry_after`` seconds when it is set.
96
+ """
97
+
98
+
99
+ class SteronixUnavailableError(SteronixResponseError):
100
+ """503: integrations are switched off or the token cannot be checked now."""
101
+
102
+
103
+ class SteronixNoAnswerError(SteronixResponseError):
104
+ """504: the open was sent but the device did not answer in time.
105
+
106
+ Whether the relay opened is unknown. Do not retry on your own.
107
+ """
steronix/models.py ADDED
@@ -0,0 +1,276 @@
1
+ """Typed models of the integrations API (integrations-v1.1.0).
2
+
3
+ Parsing is strict about the fields the contract requires and lenient about
4
+ fields it does not know, so a later minor version of the API still parses.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from datetime import datetime
11
+ from enum import StrEnum
12
+ from typing import Any
13
+
14
+ from .const import ACTOR_FIELD_MAX
15
+ from .exceptions import SteronixInvalidResponseError
16
+
17
+ #: The kind of a Home Assistant token.
18
+ KIND_HOME_ASSISTANT = "home_assistant"
19
+
20
+
21
+ class ActorType(StrEnum):
22
+ """Who pressed the button, as the integration knows it."""
23
+
24
+ USER = "user"
25
+ AUTOMATION = "automation"
26
+ UNKNOWN = "unknown"
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Actor:
31
+ """The actor an open reports; the location's log shows it as reported.
32
+
33
+ Strings are trimmed; an empty one is left out. Longer than 128
34
+ characters after trimming raises ``ValueError``, as the server would
35
+ refuse it with 400.
36
+ """
37
+
38
+ type: ActorType
39
+ id: str | None = None
40
+ name: str | None = None
41
+ login: str | None = None
42
+
43
+ def __post_init__(self) -> None:
44
+ if not isinstance(self.type, ActorType):
45
+ object.__setattr__(self, "type", ActorType(self.type))
46
+ for attr in ("id", "name", "login"):
47
+ value = getattr(self, attr)
48
+ if value is None:
49
+ continue
50
+ value = value.strip()
51
+ if len(value) > ACTOR_FIELD_MAX:
52
+ raise ValueError(f"actor {attr} is longer than {ACTOR_FIELD_MAX} characters")
53
+ object.__setattr__(self, attr, value or None)
54
+
55
+ @classmethod
56
+ def automation(cls) -> Actor:
57
+ """The actor of an open no user started."""
58
+ return cls(ActorType.AUTOMATION)
59
+
60
+ def to_json(self) -> dict[str, str]:
61
+ """The actor as the request body carries it."""
62
+ body = {"type": self.type.value}
63
+ for attr in ("id", "name", "login"):
64
+ value = getattr(self, attr)
65
+ if value is not None:
66
+ body[attr] = value
67
+ return body
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class TokenInfo:
72
+ """What a token may do (``GET /token``)."""
73
+
74
+ id: str
75
+ name: str
76
+ kind: str
77
+ device_id: str
78
+ relays: tuple[int, ...]
79
+ expires_at: datetime | None = None
80
+
81
+ @classmethod
82
+ def from_json(cls, data: object) -> TokenInfo:
83
+ obj = _object(data, "token")
84
+ return cls(
85
+ id=_str(obj, "id"),
86
+ name=_str(obj, "name"),
87
+ kind=_str(obj, "kind"),
88
+ device_id=_str(obj, "deviceId"),
89
+ relays=tuple(_int_item(v, "relays") for v in _list(obj, "relays")),
90
+ expires_at=_opt_datetime(obj, "expiresAt"),
91
+ )
92
+
93
+
94
+ @dataclass(frozen=True, slots=True)
95
+ class Relay:
96
+ """A relay of the device; ``allowed`` says whether the token may open it."""
97
+
98
+ number: int
99
+ allowed: bool
100
+ name: str | None = None
101
+
102
+ @classmethod
103
+ def from_json(cls, data: object) -> Relay:
104
+ obj = _object(data, "relay")
105
+ return cls(
106
+ number=_int(obj, "number"),
107
+ allowed=_bool(obj, "allowed"),
108
+ name=_opt_str(obj, "name"),
109
+ )
110
+
111
+
112
+ @dataclass(frozen=True, slots=True)
113
+ class Input:
114
+ """An input of the device.
115
+
116
+ ``active`` is ``True`` when the device reports the input active (a closed
117
+ contact), ``None`` until the device has reported it. ``name`` is the
118
+ portal's name, ``None`` without one.
119
+ """
120
+
121
+ number: int
122
+ name: str | None = None
123
+ active: bool | None = None
124
+
125
+ @classmethod
126
+ def from_json(cls, data: object) -> Input:
127
+ obj = _object(data, "input")
128
+ return cls(
129
+ number=_int(obj, "number"),
130
+ name=_opt_str(obj, "name"),
131
+ active=_opt_bool(obj, "active"),
132
+ )
133
+
134
+
135
+ @dataclass(frozen=True, slots=True)
136
+ class Device:
137
+ """The device a token is for (``GET /device``)."""
138
+
139
+ id: str
140
+ serial: str
141
+ name: str
142
+ online: bool
143
+ relays: tuple[Relay, ...]
144
+ inputs: tuple[Input, ...]
145
+ model: str | None = None
146
+ model_name: str | None = None
147
+ firmware_version: str | None = None
148
+ #: When the device was last heard from. Not part of the ETag: a change of
149
+ #: only this field does not end a wait.
150
+ last_seen_at: datetime | None = field(default=None, compare=False)
151
+
152
+ @classmethod
153
+ def from_json(cls, data: object) -> Device:
154
+ obj = _object(data, "device")
155
+ return cls(
156
+ id=_str(obj, "id"),
157
+ serial=_str(obj, "serial"),
158
+ name=_str(obj, "name"),
159
+ online=_bool(obj, "online"),
160
+ relays=tuple(Relay.from_json(v) for v in _list(obj, "relays")),
161
+ inputs=tuple(Input.from_json(v) for v in _list(obj, "inputs")),
162
+ model=_opt_str(obj, "model"),
163
+ model_name=_opt_str(obj, "modelName"),
164
+ firmware_version=_opt_str(obj, "firmwareVersion"),
165
+ last_seen_at=_opt_datetime(obj, "lastSeenAt"),
166
+ )
167
+
168
+ def relay(self, number: int) -> Relay | None:
169
+ """The relay with this number, if the device lists it."""
170
+ return next((r for r in self.relays if r.number == number), None)
171
+
172
+ def input(self, number: int) -> Input | None:
173
+ """The input with this number, if the device lists it."""
174
+ return next((i for i in self.inputs if i.number == number), None)
175
+
176
+
177
+ @dataclass(frozen=True, slots=True)
178
+ class DeviceResult:
179
+ """A device read, with the ``ETag`` to wait for its next change."""
180
+
181
+ device: Device
182
+ etag: str | None
183
+
184
+
185
+ @dataclass(frozen=True, slots=True)
186
+ class OpenResult:
187
+ """The relay opened. ``open_number`` is the event's number in the log."""
188
+
189
+ relay: int
190
+ open_number: int
191
+ result: str = "opened"
192
+
193
+ @classmethod
194
+ def from_json(cls, data: object) -> OpenResult:
195
+ obj = _object(data, "open result")
196
+ return cls(
197
+ relay=_int(obj, "relay"),
198
+ open_number=_int(obj, "openNumber"),
199
+ result=_str(obj, "result"),
200
+ )
201
+
202
+
203
+ # --- parsing helpers ---------------------------------------------------------
204
+
205
+
206
+ def _object(data: object, what: str) -> dict[str, Any]:
207
+ if not isinstance(data, dict):
208
+ raise SteronixInvalidResponseError(f"{what} is not a JSON object")
209
+ return data
210
+
211
+
212
+ def _missing(key: str) -> SteronixInvalidResponseError:
213
+ return SteronixInvalidResponseError(f"field {key!r} is missing or has the wrong type")
214
+
215
+
216
+ def _str(obj: dict[str, Any], key: str) -> str:
217
+ value = obj.get(key)
218
+ if not isinstance(value, str):
219
+ raise _missing(key)
220
+ return value
221
+
222
+
223
+ def _opt_str(obj: dict[str, Any], key: str) -> str | None:
224
+ value = obj.get(key)
225
+ if value is None:
226
+ return None
227
+ if not isinstance(value, str):
228
+ raise _missing(key)
229
+ return value
230
+
231
+
232
+ def _bool(obj: dict[str, Any], key: str) -> bool:
233
+ value = obj.get(key)
234
+ if not isinstance(value, bool):
235
+ raise _missing(key)
236
+ return value
237
+
238
+
239
+ def _opt_bool(obj: dict[str, Any], key: str) -> bool | None:
240
+ value = obj.get(key)
241
+ if value is None:
242
+ return None
243
+ if not isinstance(value, bool):
244
+ raise _missing(key)
245
+ return value
246
+
247
+
248
+ def _int(obj: dict[str, Any], key: str) -> int:
249
+ return _int_item(obj.get(key), key)
250
+
251
+
252
+ def _int_item(value: object, key: str) -> int:
253
+ # bool is an int in Python; the contract never means one.
254
+ if not isinstance(value, int) or isinstance(value, bool):
255
+ raise _missing(key)
256
+ return value
257
+
258
+
259
+ def _list(obj: dict[str, Any], key: str) -> list[Any]:
260
+ value = obj.get(key)
261
+ if not isinstance(value, list):
262
+ raise _missing(key)
263
+ return value
264
+
265
+
266
+ def _opt_datetime(obj: dict[str, Any], key: str) -> datetime | None:
267
+ value = _opt_str(obj, key)
268
+ if value is None:
269
+ return None
270
+ try:
271
+ parsed = datetime.fromisoformat(value)
272
+ except ValueError as err:
273
+ raise _missing(key) from err
274
+ if parsed.tzinfo is None:
275
+ raise _missing(key)
276
+ return parsed
steronix/py.typed ADDED
File without changes
steronix/watch.py ADDED
@@ -0,0 +1,145 @@
1
+ """Follow a device: long polling, with plain polling as the fallback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import time
8
+ from collections.abc import AsyncIterator, Awaitable, Callable
9
+
10
+ from .client import SteronixClient
11
+ from .const import MAX_WAIT
12
+ from .exceptions import (
13
+ SteronixAuthenticationError,
14
+ SteronixError,
15
+ SteronixRateLimitError,
16
+ )
17
+ from .models import Device, DeviceResult
18
+
19
+ _LOGGER = logging.getLogger(__name__)
20
+
21
+ #: Plain polling interval while long polling does not work, in seconds.
22
+ DEFAULT_FALLBACK_INTERVAL = 10.0
23
+
24
+ #: How long the watcher stays on plain polling before it tries long polling
25
+ #: again, in seconds.
26
+ DEFAULT_LONG_POLL_RETRY = 300.0
27
+
28
+ Sleep = Callable[[float], Awaitable[None]]
29
+
30
+
31
+ class DeviceWatcher:
32
+ """Yield the device's state at start and after every change.
33
+
34
+ It asks ``GET /device?wait=…`` with the last ``ETag``; the server answers
35
+ as soon as the state changes, else after the wait with 304, and the
36
+ watcher asks again at once. When long polling fails, it polls every
37
+ ``fallback_interval`` seconds and tries long polling again after
38
+ ``long_poll_retry`` seconds.
39
+
40
+ ``updates()`` yields a ``Device`` for each new state and a
41
+ ``SteronixError`` for a failure it keeps going after (the API cannot be
42
+ reached, 503, 429, an unexpected answer), so the caller can show the
43
+ device as unavailable. After a failure the next successful read is
44
+ yielded even if the state did not change. A ``SteronixAuthenticationError``
45
+ is raised and ends the watch: the token no longer works.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ client: SteronixClient,
51
+ *,
52
+ wait: int = MAX_WAIT,
53
+ fallback_interval: float = DEFAULT_FALLBACK_INTERVAL,
54
+ long_poll_retry: float = DEFAULT_LONG_POLL_RETRY,
55
+ sleep: Sleep = asyncio.sleep,
56
+ clock: Callable[[], float] = time.monotonic,
57
+ ) -> None:
58
+ if not 1 <= wait <= MAX_WAIT:
59
+ raise ValueError(f"wait must be 1 to {MAX_WAIT} seconds")
60
+ if fallback_interval <= 0:
61
+ raise ValueError("fallback_interval must be positive")
62
+ self._client = client
63
+ self._wait = wait
64
+ self._fallback_interval = fallback_interval
65
+ self._long_poll_retry = long_poll_retry
66
+ self._sleep = sleep
67
+ self._clock = clock
68
+ self._etag: str | None = None
69
+ self._last: Device | None = None
70
+ self._failed = True # nothing yielded yet: the first read is news
71
+ self._fallback_since: float | None = None
72
+
73
+ @property
74
+ def long_polling(self) -> bool:
75
+ """Whether the watcher is long polling now (not on the fallback)."""
76
+ return self._fallback_since is None
77
+
78
+ @property
79
+ def device(self) -> Device | None:
80
+ """The last state yielded."""
81
+ return self._last
82
+
83
+ async def updates(self) -> AsyncIterator[Device | SteronixError]:
84
+ while True:
85
+ try:
86
+ result = await self._next()
87
+ except SteronixAuthenticationError:
88
+ raise
89
+ except SteronixError as err:
90
+ self._failed = True
91
+ yield err
92
+ await self._sleep(self._pause_after(err))
93
+ continue
94
+ if result is not None and self._is_news(result):
95
+ self._failed = False
96
+ self._last = result.device
97
+ yield result.device
98
+
99
+ async def _next(self) -> DeviceResult | None:
100
+ if self._etag is None:
101
+ # Start, or no ETag from the server: a plain read.
102
+ if self._last is not None:
103
+ await self._sleep(self._fallback_interval)
104
+ return self._remember(await self._client.get_device())
105
+
106
+ if self._fallback_since is not None:
107
+ if self._clock() - self._fallback_since >= self._long_poll_retry:
108
+ _LOGGER.debug("trying long polling again")
109
+ self._fallback_since = None
110
+ else:
111
+ await self._sleep(self._fallback_interval)
112
+ return self._remember(await self._client.get_device())
113
+
114
+ try:
115
+ result = await self._client.wait_for_change(self._etag, wait=self._wait)
116
+ except SteronixAuthenticationError:
117
+ raise
118
+ except SteronixRateLimitError:
119
+ # A limit, not a broken long poll: wait as told, stay on it.
120
+ raise
121
+ except SteronixError as err:
122
+ _LOGGER.debug(
123
+ "long polling failed (%s); polling every %ss", err, self._fallback_interval
124
+ )
125
+ self._fallback_since = self._clock()
126
+ raise
127
+ if result is None:
128
+ # 304: no change within the wait. Still news after a failure.
129
+ if self._failed and self._last is not None:
130
+ return DeviceResult(self._last, self._etag)
131
+ return None
132
+ return self._remember(result)
133
+
134
+ def _remember(self, result: DeviceResult) -> DeviceResult:
135
+ self._etag = result.etag or None
136
+ return result
137
+
138
+ def _is_news(self, result: DeviceResult) -> bool:
139
+ return self._failed or result.device != self._last
140
+
141
+ def _pause_after(self, err: SteronixError) -> float:
142
+ if isinstance(err, SteronixRateLimitError) and err.retry_after is not None:
143
+ return max(err.retry_after, 1.0)
144
+ # The fallback read sleeps on its own; avoid a busy loop otherwise.
145
+ return 0.0 if self._fallback_since is not None else self._fallback_interval