HomeAssistant-API 6.0.1__tar.gz → 6.2.0__tar.gz
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.
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/.gitignore +2 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/PKG-INFO +16 -13
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/README.md +13 -11
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/asyncwebsocket.py +185 -37
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/basewebsocket.py +16 -10
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/config_entries.py +6 -1
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/entity.py +6 -1
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/entity_registry.py +18 -6
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/processing.py +1 -3
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/websocket.py +12 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/pyproject.toml +6 -7
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/LICENSE +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/__init__.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/asyncclient.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/baseclient.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/client.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/errors.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/__init__.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/base.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/domains.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/events.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/history.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/logbook.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/states.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/websocket.py +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/py.typed +0 -0
- {homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: HomeAssistant-API
|
|
3
|
-
Version: 6.0
|
|
3
|
+
Version: 6.2.0
|
|
4
4
|
Summary: Python Wrapper for Homeassistant's REST API
|
|
5
5
|
Project-URL: Documentation, https://homeassistantapi.readthedocs.io
|
|
6
6
|
Project-URL: Homepage, https://github.com/HomeAssistant-API/HomeAssistantAPI
|
|
@@ -12,13 +12,14 @@ Requires-Python: <4.0,>=3.11
|
|
|
12
12
|
Requires-Dist: niquests[ws]>=3
|
|
13
13
|
Requires-Dist: pydantic<3,>=2
|
|
14
14
|
Requires-Dist: simplejson<4,>=3
|
|
15
|
+
Requires-Dist: urllib3-future>=2.25.900
|
|
15
16
|
Description-Content-Type: text/markdown
|
|
16
17
|
|
|
17
18
|
# HomeassistantAPI
|
|
18
19
|
|
|
19
|
-
[](https://codecov.io/gh/HomeAssistant-API/HomeAssistantAPI)
|
|
20
21
|
[](https://pypistats.org/packages/homeassistant-api)
|
|
21
|
-
](https://img.shields.io/github/commits-since/HomeAssistant-API/HomeAssistantAPI/latest/main?include_prereleases&style=for-the-badge)
|
|
22
23
|
[](https://homeassistantapi.readthedocs.io/en/latest/?badge=latest)
|
|
23
24
|
[](https://github.com/HomeAssistant-API/HomeAssistantAPI/releases)
|
|
24
25
|
|
|
@@ -38,10 +39,10 @@ Description-Content-Type: text/markdown
|
|
|
38
39
|
from homeassistant_api import Client
|
|
39
40
|
|
|
40
41
|
with Client(
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
"<API Server URL>", # i.e. 'http://homeassistant.local:8123/api/'
|
|
43
|
+
"<Your Long Lived Access-Token>",
|
|
43
44
|
) as client:
|
|
44
|
-
client.trigger_service(
|
|
45
|
+
client.trigger_service("light", "turn_on", entity_id="light.living_room")
|
|
45
46
|
```
|
|
46
47
|
|
|
47
48
|
All four client classes share the same method names.
|
|
@@ -51,12 +52,14 @@ The async clients (`AsyncClient`, `AsyncWebsocketClient`) use `async def` method
|
|
|
51
52
|
import asyncio
|
|
52
53
|
from homeassistant_api import AsyncClient
|
|
53
54
|
|
|
55
|
+
|
|
54
56
|
async def main():
|
|
55
57
|
async with AsyncClient(
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
"<REST API Server URL>", # i.e. 'http://homeassistant.local:8123/api/'
|
|
59
|
+
"<Your Long Lived Access-Token>",
|
|
58
60
|
) as client:
|
|
59
|
-
await client.trigger_service(
|
|
61
|
+
await client.trigger_service("light", "turn_on", entity_id="light.living_room")
|
|
62
|
+
|
|
60
63
|
|
|
61
64
|
asyncio.run(main())
|
|
62
65
|
```
|
|
@@ -67,10 +70,10 @@ asyncio.run(main())
|
|
|
67
70
|
from homeassistant_api import WebsocketClient
|
|
68
71
|
|
|
69
72
|
with WebsocketClient(
|
|
70
|
-
|
|
71
|
-
|
|
73
|
+
"<WS API Server URL>", # i.e. 'ws://homeassistant.local:8123/api/websocket'
|
|
74
|
+
"<Your Long Lived Access-Token>",
|
|
72
75
|
) as ws_client:
|
|
73
|
-
ws_client.trigger_service(
|
|
76
|
+
ws_client.trigger_service("light", "turn_on", entity_id="light.living_room")
|
|
74
77
|
```
|
|
75
78
|
|
|
76
79
|
## Documentation
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# HomeassistantAPI
|
|
2
2
|
|
|
3
|
-
[](https://codecov.io/gh/HomeAssistant-API/HomeAssistantAPI)
|
|
4
4
|
[](https://pypistats.org/packages/homeassistant-api)
|
|
5
|
-
](https://img.shields.io/github/commits-since/HomeAssistant-API/HomeAssistantAPI/latest/main?include_prereleases&style=for-the-badge)
|
|
6
6
|
[](https://homeassistantapi.readthedocs.io/en/latest/?badge=latest)
|
|
7
7
|
[](https://github.com/HomeAssistant-API/HomeAssistantAPI/releases)
|
|
8
8
|
|
|
@@ -22,10 +22,10 @@
|
|
|
22
22
|
from homeassistant_api import Client
|
|
23
23
|
|
|
24
24
|
with Client(
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
"<API Server URL>", # i.e. 'http://homeassistant.local:8123/api/'
|
|
26
|
+
"<Your Long Lived Access-Token>",
|
|
27
27
|
) as client:
|
|
28
|
-
client.trigger_service(
|
|
28
|
+
client.trigger_service("light", "turn_on", entity_id="light.living_room")
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
All four client classes share the same method names.
|
|
@@ -35,12 +35,14 @@ The async clients (`AsyncClient`, `AsyncWebsocketClient`) use `async def` method
|
|
|
35
35
|
import asyncio
|
|
36
36
|
from homeassistant_api import AsyncClient
|
|
37
37
|
|
|
38
|
+
|
|
38
39
|
async def main():
|
|
39
40
|
async with AsyncClient(
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
"<REST API Server URL>", # i.e. 'http://homeassistant.local:8123/api/'
|
|
42
|
+
"<Your Long Lived Access-Token>",
|
|
42
43
|
) as client:
|
|
43
|
-
await client.trigger_service(
|
|
44
|
+
await client.trigger_service("light", "turn_on", entity_id="light.living_room")
|
|
45
|
+
|
|
44
46
|
|
|
45
47
|
asyncio.run(main())
|
|
46
48
|
```
|
|
@@ -51,10 +53,10 @@ asyncio.run(main())
|
|
|
51
53
|
from homeassistant_api import WebsocketClient
|
|
52
54
|
|
|
53
55
|
with WebsocketClient(
|
|
54
|
-
|
|
55
|
-
|
|
56
|
+
"<WS API Server URL>", # i.e. 'ws://homeassistant.local:8123/api/websocket'
|
|
57
|
+
"<Your Long Lived Access-Token>",
|
|
56
58
|
) as ws_client:
|
|
57
|
-
ws_client.trigger_service(
|
|
59
|
+
ws_client.trigger_service("light", "turn_on", entity_id="light.living_room")
|
|
58
60
|
```
|
|
59
61
|
|
|
60
62
|
## Documentation
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import asyncio
|
|
3
4
|
import contextlib
|
|
4
5
|
import json
|
|
5
6
|
import logging
|
|
@@ -43,6 +44,7 @@ from homeassistant_api.utils import prepare_entity_id
|
|
|
43
44
|
|
|
44
45
|
if TYPE_CHECKING:
|
|
45
46
|
from collections.abc import AsyncGenerator
|
|
47
|
+
from collections.abc import Generator
|
|
46
48
|
from datetime import datetime
|
|
47
49
|
from types import TracebackType
|
|
48
50
|
|
|
@@ -50,10 +52,24 @@ if TYPE_CHECKING:
|
|
|
50
52
|
|
|
51
53
|
logger = logging.getLogger(__name__)
|
|
52
54
|
|
|
55
|
+
# What the reader task can hand to a waiting recv(): a response, or the error to raise.
|
|
56
|
+
_Inbound = ResultResponse | EventResponse | PingResponse | BaseException
|
|
57
|
+
|
|
58
|
+
# Commands whose id keeps receiving events after its result, until unsubscribed.
|
|
59
|
+
_STREAMING_COMMANDS = frozenset(
|
|
60
|
+
{
|
|
61
|
+
"config_entries/subscribe",
|
|
62
|
+
"render_template",
|
|
63
|
+
"subscribe_events",
|
|
64
|
+
"subscribe_trigger",
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
|
|
53
68
|
|
|
54
69
|
class AsyncWebsocketClient(BaseWebsocketClient):
|
|
55
70
|
_session: AsyncSession
|
|
56
71
|
_ws: AsyncExtensionFromHTTP
|
|
72
|
+
_reader_task: asyncio.Task[None]
|
|
57
73
|
|
|
58
74
|
def __init__(
|
|
59
75
|
self,
|
|
@@ -65,8 +81,20 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
65
81
|
) -> None:
|
|
66
82
|
super().__init__(api_url, token, max_size=max_size)
|
|
67
83
|
self._session = session if session is not None else AsyncSession()
|
|
84
|
+
# One inbox per pending request id. The reader task puts each response
|
|
85
|
+
# (or the error for it) in its owner's inbox, so a message only wakes
|
|
86
|
+
# the task waiting on that id.
|
|
87
|
+
self._inboxes: dict[int, asyncio.Queue[_Inbound]] = {}
|
|
88
|
+
self._streaming_ids: set[int] = set()
|
|
89
|
+
self._ping_starts: dict[int, int] = {}
|
|
90
|
+
self._fatal_error: BaseException | None = None
|
|
68
91
|
|
|
69
92
|
async def __aenter__(self) -> Self:
|
|
93
|
+
# Start clean if this instance is re-entered after an earlier connection.
|
|
94
|
+
self._inboxes.clear()
|
|
95
|
+
self._streaming_ids.clear()
|
|
96
|
+
self._ping_starts.clear()
|
|
97
|
+
self._fatal_error = None
|
|
70
98
|
await self._session.__aenter__()
|
|
71
99
|
resp = await self._session.get(self.api_url)
|
|
72
100
|
resp.raise_for_status()
|
|
@@ -74,8 +102,11 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
74
102
|
msg = "Server did not upgrade to WebSocket"
|
|
75
103
|
raise ReceivingError(msg)
|
|
76
104
|
self._ws = resp.extension
|
|
105
|
+
# Authenticate before starting the reader task: these messages have no "id"
|
|
106
|
+
# and aren't dispatched through it, so nothing else may read the socket yet.
|
|
77
107
|
okay = await self.authentication_phase()
|
|
78
108
|
logger.info("Authenticated with Home Assistant (%s)", okay.ha_version)
|
|
109
|
+
self._reader_task = asyncio.create_task(self._reader_loop())
|
|
79
110
|
await self.supported_features_phase()
|
|
80
111
|
return self
|
|
81
112
|
|
|
@@ -85,10 +116,106 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
85
116
|
exc_value: BaseException | None,
|
|
86
117
|
traceback: TracebackType | None,
|
|
87
118
|
) -> None:
|
|
119
|
+
self._reader_task.cancel()
|
|
120
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
121
|
+
await self._reader_task
|
|
122
|
+
if self._fatal_error is None:
|
|
123
|
+
# Nothing will be read any more: wake every pending recv() instead of
|
|
124
|
+
# leaving it waiting forever.
|
|
125
|
+
self._fail_all(ReceivingError("WebSocket client closed"))
|
|
88
126
|
await self._ws.close()
|
|
89
127
|
del self._ws
|
|
90
128
|
await self._session.__aexit__(exc_type, exc_value, traceback)
|
|
91
129
|
|
|
130
|
+
async def _reader_loop(self) -> None:
|
|
131
|
+
"""
|
|
132
|
+
Continuously read messages off the socket and dispatch them by id.
|
|
133
|
+
|
|
134
|
+
This is the only task allowed to touch the socket directly, so reads can
|
|
135
|
+
never interleave or starve a waiting `recv()` call.
|
|
136
|
+
"""
|
|
137
|
+
while True:
|
|
138
|
+
try:
|
|
139
|
+
data = await self._async_recv()
|
|
140
|
+
except Exception as e: # noqa: BLE001
|
|
141
|
+
# No message id is available yet, so there's no single owner to
|
|
142
|
+
# blame this on: the connection is dead for every pending recv().
|
|
143
|
+
self._fail_all(e)
|
|
144
|
+
return
|
|
145
|
+
self._dispatch(data)
|
|
146
|
+
if self._fatal_error is not None:
|
|
147
|
+
return # a protocol error in that message: the connection is unusable
|
|
148
|
+
|
|
149
|
+
def _dispatch(self, data: dict[str, Any]) -> None:
|
|
150
|
+
"""Hand a received message to `handle_recv`, routing any failure to its owner."""
|
|
151
|
+
try:
|
|
152
|
+
self.handle_recv(data)
|
|
153
|
+
except Exception as e: # noqa: BLE001
|
|
154
|
+
data_id = data.get("id")
|
|
155
|
+
if not isinstance(data_id, int):
|
|
156
|
+
self._fail_all(e)
|
|
157
|
+
elif (inbox := self._inboxes.get(data_id)) is not None:
|
|
158
|
+
# The message carried its own id, so only the caller waiting
|
|
159
|
+
# on that id needs to see the failure.
|
|
160
|
+
inbox.put_nowait(e)
|
|
161
|
+
else:
|
|
162
|
+
logger.warning(
|
|
163
|
+
"Dropping error for unknown message id %s: %s",
|
|
164
|
+
data_id,
|
|
165
|
+
e,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def _fail_all(self, error: BaseException) -> None:
|
|
169
|
+
"""Fail every pending recv(), and every later one, with a connection-level error."""
|
|
170
|
+
self._fatal_error = error
|
|
171
|
+
for inbox in self._inboxes.values():
|
|
172
|
+
inbox.put_nowait(error)
|
|
173
|
+
|
|
174
|
+
def _deliver(self, msg_id: int, item: _Inbound) -> None:
|
|
175
|
+
"""Put a response in the inbox of the request it answers."""
|
|
176
|
+
inbox = self._inboxes.get(msg_id)
|
|
177
|
+
if inbox is None:
|
|
178
|
+
# e.g. an event still in flight when its subscription was cancelled
|
|
179
|
+
logger.debug("Dropping message for id %s with no pending request", msg_id)
|
|
180
|
+
return
|
|
181
|
+
inbox.put_nowait(item)
|
|
182
|
+
|
|
183
|
+
def _forget(self, msg_id: int) -> None:
|
|
184
|
+
"""Release everything held for a request that will get no more responses."""
|
|
185
|
+
self._inboxes.pop(msg_id, None)
|
|
186
|
+
self._streaming_ids.discard(msg_id)
|
|
187
|
+
self._ping_starts.pop(msg_id, None)
|
|
188
|
+
|
|
189
|
+
@contextlib.contextmanager
|
|
190
|
+
def _released_on_error(self, subscription_id: int) -> Generator[None, None, None]:
|
|
191
|
+
"""
|
|
192
|
+
Release a subscription's state if the ``listen_*`` body raises or is cancelled.
|
|
193
|
+
|
|
194
|
+
Unsubscribing is skipped then, since the connection may be the problem;
|
|
195
|
+
events still in flight for the id are dropped.
|
|
196
|
+
"""
|
|
197
|
+
try:
|
|
198
|
+
yield
|
|
199
|
+
except BaseException:
|
|
200
|
+
self._forget(subscription_id)
|
|
201
|
+
raise
|
|
202
|
+
|
|
203
|
+
def _store_result(self, msg_id: int, response: ResultResponse) -> None:
|
|
204
|
+
self._deliver(msg_id, response)
|
|
205
|
+
|
|
206
|
+
def _store_event(self, msg_id: int, response: EventResponse) -> None:
|
|
207
|
+
self._deliver(msg_id, response)
|
|
208
|
+
|
|
209
|
+
def _store_pong(self, msg_id: int, end_ns: int) -> None:
|
|
210
|
+
start = self._ping_starts.pop(msg_id, None)
|
|
211
|
+
if start is None:
|
|
212
|
+
logger.debug("Dropping pong for unknown ping id %s", msg_id)
|
|
213
|
+
return
|
|
214
|
+
self._deliver(
|
|
215
|
+
msg_id,
|
|
216
|
+
PingResponse(start=start, end=end_ns, id=msg_id, type="pong"),
|
|
217
|
+
)
|
|
218
|
+
|
|
92
219
|
async def _async_send(self, data: dict[str, Any]) -> None:
|
|
93
220
|
"""Send a message to the websocket server."""
|
|
94
221
|
if data.get("type") != "auth":
|
|
@@ -124,43 +251,61 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
124
251
|
data["id"] = self._request_id()
|
|
125
252
|
|
|
126
253
|
data["type"] = msg_type
|
|
127
|
-
|
|
254
|
+
if "id" not in data:
|
|
255
|
+
await self._async_send(data)
|
|
256
|
+
return -1 # non-command messages don't have an id
|
|
128
257
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
258
|
+
msg_id = data["id"]
|
|
259
|
+
if not isinstance(msg_id, int):
|
|
260
|
+
msg = f"Expected int for message id, got {type(msg_id)}"
|
|
261
|
+
raise TypeError(msg)
|
|
262
|
+
# Register before sending: the reader task can dispatch the reply
|
|
263
|
+
# before send_payload() returns.
|
|
264
|
+
self._inboxes[msg_id] = asyncio.Queue()
|
|
265
|
+
if msg_type in _STREAMING_COMMANDS:
|
|
266
|
+
self._streaming_ids.add(msg_id)
|
|
267
|
+
if msg_type == "ping":
|
|
268
|
+
self._ping_starts[msg_id] = time.perf_counter_ns()
|
|
269
|
+
try:
|
|
270
|
+
await self._async_send(data)
|
|
271
|
+
except BaseException:
|
|
272
|
+
self._forget(msg_id)
|
|
273
|
+
raise
|
|
274
|
+
return msg_id
|
|
144
275
|
|
|
145
276
|
async def recv(
|
|
146
277
|
self,
|
|
147
278
|
msg_id: int,
|
|
148
279
|
) -> EventResponse | ResultResponse | PingResponse | None:
|
|
149
280
|
"""Receive a response to a message from the websocket server."""
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
if self.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
and self._ping_responses[msg_id].end is not None
|
|
159
|
-
):
|
|
160
|
-
return self._ping_responses.pop(msg_id)
|
|
281
|
+
inbox = self._inboxes.get(msg_id)
|
|
282
|
+
if inbox is None:
|
|
283
|
+
if self._fatal_error is not None:
|
|
284
|
+
raise self._fatal_error
|
|
285
|
+
msg = f"No pending request with id {msg_id}"
|
|
286
|
+
raise ReceivingError(msg)
|
|
287
|
+
if inbox.empty() and self._fatal_error is not None:
|
|
288
|
+
raise self._fatal_error
|
|
161
289
|
|
|
162
|
-
|
|
163
|
-
|
|
290
|
+
try:
|
|
291
|
+
item = await inbox.get()
|
|
292
|
+
except asyncio.CancelledError:
|
|
293
|
+
# e.g. a timeout around ping_latency(): nobody will read this reply.
|
|
294
|
+
# Subscriptions are released by unsubscribing instead.
|
|
295
|
+
if msg_id not in self._streaming_ids:
|
|
296
|
+
self._forget(msg_id)
|
|
297
|
+
raise
|
|
298
|
+
streaming = msg_id in self._streaming_ids
|
|
299
|
+
if isinstance(item, BaseException):
|
|
300
|
+
# A failed result ends the request; a bad event doesn't end a subscription.
|
|
301
|
+
if item is not self._fatal_error and (
|
|
302
|
+
not streaming or isinstance(item, ResponseError)
|
|
303
|
+
):
|
|
304
|
+
self._forget(msg_id)
|
|
305
|
+
raise item
|
|
306
|
+
if not streaming and isinstance(item, ResultResponse | PingResponse):
|
|
307
|
+
self._forget(msg_id) # single-shot request: nothing else will arrive
|
|
308
|
+
return item
|
|
164
309
|
|
|
165
310
|
async def recv_result(self, msg_id: int) -> ResultResponse:
|
|
166
311
|
"""Receive a ResultResponse, raising TypeError if the response is not a ResultResponse."""
|
|
@@ -481,7 +626,8 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
481
626
|
print(event)
|
|
482
627
|
"""
|
|
483
628
|
subscription = await self._async_subscribe_events(event_type)
|
|
484
|
-
|
|
629
|
+
with self._released_on_error(subscription):
|
|
630
|
+
yield self._async_wait_for(subscription)
|
|
485
631
|
await self._async_unsubscribe(subscription)
|
|
486
632
|
|
|
487
633
|
async def _async_subscribe_events(self, event_type: str | None) -> int:
|
|
@@ -531,11 +677,12 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
531
677
|
Woohoo! We can now listen to triggers in Python code!
|
|
532
678
|
"""
|
|
533
679
|
subscription = await self._async_subscribe_trigger(trigger, **trigger_fields)
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
680
|
+
with self._released_on_error(subscription):
|
|
681
|
+
yield (
|
|
682
|
+
fired_trigger.variables
|
|
683
|
+
async for fired_trigger in self._async_wait_for(subscription)
|
|
684
|
+
if isinstance(fired_trigger, FiredTrigger)
|
|
685
|
+
)
|
|
539
686
|
await self._async_unsubscribe(subscription)
|
|
540
687
|
|
|
541
688
|
async def _async_subscribe_trigger(
|
|
@@ -584,7 +731,7 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
584
731
|
msg = "Expected None result for unsubscribe"
|
|
585
732
|
raise ValueError(msg)
|
|
586
733
|
finally:
|
|
587
|
-
self.
|
|
734
|
+
self._forget(subcription_id)
|
|
588
735
|
|
|
589
736
|
async def get_config_entries(self) -> tuple[ConfigEntry, ...]:
|
|
590
737
|
"""
|
|
@@ -751,7 +898,8 @@ class AsyncWebsocketClient(BaseWebsocketClient):
|
|
|
751
898
|
subscription = (
|
|
752
899
|
await self.recv_result(await self.send("config_entries/subscribe"))
|
|
753
900
|
).id
|
|
754
|
-
|
|
901
|
+
with self._released_on_error(subscription):
|
|
902
|
+
yield self._async_wait_for_config_entries(subscription)
|
|
755
903
|
await self._async_unsubscribe(subscription)
|
|
756
904
|
|
|
757
905
|
async def _async_wait_for_config_entries(
|
|
@@ -8,7 +8,6 @@ from homeassistant_api.errors import ReceivingError
|
|
|
8
8
|
from homeassistant_api.errors import ResponseError
|
|
9
9
|
from homeassistant_api.models.websocket import ErrorResponse
|
|
10
10
|
from homeassistant_api.models.websocket import EventResponse
|
|
11
|
-
from homeassistant_api.models.websocket import PingResponse
|
|
12
11
|
from homeassistant_api.models.websocket import ResultResponse
|
|
13
12
|
|
|
14
13
|
logger = logging.getLogger(__name__)
|
|
@@ -21,9 +20,6 @@ class BaseWebsocketClient:
|
|
|
21
20
|
token: str
|
|
22
21
|
max_size: int
|
|
23
22
|
_id_counter: int
|
|
24
|
-
_result_responses: dict[int, ResultResponse | None]
|
|
25
|
-
_event_responses: dict[int, list[EventResponse]]
|
|
26
|
-
_ping_responses: dict[int, PingResponse]
|
|
27
23
|
|
|
28
24
|
def __init__(self, api_url: str, token: str, *, max_size: int = 2**24) -> None:
|
|
29
25
|
parsed = urlparse.urlparse(api_url)
|
|
@@ -38,9 +34,6 @@ class BaseWebsocketClient:
|
|
|
38
34
|
self.max_size = max_size
|
|
39
35
|
|
|
40
36
|
self._id_counter = 0
|
|
41
|
-
self._result_responses = {} # id -> response
|
|
42
|
-
self._event_responses = {} # id -> [response, ...]
|
|
43
|
-
self._ping_responses = {} # id -> (sent, received)
|
|
44
37
|
|
|
45
38
|
def __repr__(self) -> str:
|
|
46
39
|
return f"{self.__class__.__name__}({self.api_url!r})"
|
|
@@ -58,21 +51,34 @@ class BaseWebsocketClient:
|
|
|
58
51
|
self.parse_response(data)
|
|
59
52
|
|
|
60
53
|
def parse_response(self, data: dict[str, Any]) -> None:
|
|
54
|
+
"""Parse a received message by type and hand it to the matching storage hook."""
|
|
61
55
|
data_id = cast("int", data["id"])
|
|
62
56
|
if data.get("type") == "pong":
|
|
63
57
|
logger.info("Received pong message")
|
|
64
|
-
self.
|
|
58
|
+
self._store_pong(data_id, time.perf_counter_ns())
|
|
65
59
|
elif data.get("type") == "result":
|
|
66
60
|
logger.info("Received result message")
|
|
67
61
|
if data.get("success"):
|
|
68
|
-
self.
|
|
62
|
+
self._store_result(data_id, ResultResponse.model_validate(data))
|
|
69
63
|
else:
|
|
70
64
|
error_resp = ErrorResponse.model_validate(data)
|
|
71
65
|
msg = f"[{error_resp.error.code}] {error_resp.error.message}"
|
|
72
66
|
raise ResponseError(msg)
|
|
73
67
|
elif data.get("type") == "event":
|
|
74
68
|
logger.info("Received event message %s", data["event"])
|
|
75
|
-
self.
|
|
69
|
+
self._store_event(data_id, EventResponse.model_validate(data))
|
|
76
70
|
else:
|
|
77
71
|
msg = f"Received unexpected message type: {data}"
|
|
78
72
|
raise ReceivingError(msg)
|
|
73
|
+
|
|
74
|
+
def _store_result(self, msg_id: int, response: ResultResponse) -> None:
|
|
75
|
+
"""Make a successful result available to whoever waits on ``msg_id``."""
|
|
76
|
+
raise NotImplementedError
|
|
77
|
+
|
|
78
|
+
def _store_event(self, msg_id: int, response: EventResponse) -> None:
|
|
79
|
+
"""Make an event available to whoever waits on subscription ``msg_id``."""
|
|
80
|
+
raise NotImplementedError
|
|
81
|
+
|
|
82
|
+
def _store_pong(self, msg_id: int, end_ns: int) -> None:
|
|
83
|
+
"""Complete the ping ``msg_id``, which the pong arrived for at ``end_ns``."""
|
|
84
|
+
raise NotImplementedError
|
{homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/config_entries.py
RENAMED
|
@@ -30,6 +30,7 @@ class DiscoveryKey(BaseModel):
|
|
|
30
30
|
class FlowContext(BaseModel):
|
|
31
31
|
"""Base flow context"""
|
|
32
32
|
|
|
33
|
+
# No longer sent since Home Assistant 2026.11, only populated by older servers.
|
|
33
34
|
show_advanced_options: bool | None = None
|
|
34
35
|
source: str
|
|
35
36
|
|
|
@@ -39,8 +40,10 @@ class ConfigFlowContext(FlowContext):
|
|
|
39
40
|
|
|
40
41
|
alternative_domain: str | None = None
|
|
41
42
|
configuration_url: str | None = None
|
|
43
|
+
# No longer sent since Home Assistant 2026.11, only populated by older servers.
|
|
42
44
|
confirm_only: bool | None = None
|
|
43
|
-
discovery_key: DiscoveryKey
|
|
45
|
+
discovery_key: DiscoveryKey | None = None
|
|
46
|
+
dismiss_protected: bool | None = None
|
|
44
47
|
entry_id: str | None = None
|
|
45
48
|
title_placeholders: dict[str, str] | None = None
|
|
46
49
|
unique_id: str | None = None
|
|
@@ -66,6 +69,7 @@ class FlowResult(BaseModel):
|
|
|
66
69
|
reason: str | None = None
|
|
67
70
|
required: bool | None = None
|
|
68
71
|
result: Any | None = None
|
|
72
|
+
sort: bool | None = None
|
|
69
73
|
step_id: str | None = None
|
|
70
74
|
title: str | None = None
|
|
71
75
|
translation_domain: str | None = None
|
|
@@ -130,6 +134,7 @@ class ConfigEntry(BaseModel):
|
|
|
130
134
|
pref_disable_polling: bool
|
|
131
135
|
disabled_by: ConfigEntryDisabler | None
|
|
132
136
|
reason: str | None
|
|
137
|
+
error_reason_translation_domain: str | None = None
|
|
133
138
|
error_reason_translation_key: str | None
|
|
134
139
|
error_reason_translation_placeholders: dict[str, Any] | None
|
|
135
140
|
num_subentries: int
|
|
@@ -96,7 +96,12 @@ class BaseEntity(BaseModel):
|
|
|
96
96
|
|
|
97
97
|
slug: str
|
|
98
98
|
state: State
|
|
99
|
-
|
|
99
|
+
|
|
100
|
+
if TYPE_CHECKING:
|
|
101
|
+
# Subclasses declare the concrete ``group`` field. It is read-only here
|
|
102
|
+
# so they can narrow its type without an unsound mutable override.
|
|
103
|
+
@property
|
|
104
|
+
def group(self) -> BaseGroup: ...
|
|
100
105
|
|
|
101
106
|
@property
|
|
102
107
|
def entity_id(self) -> str:
|
{homeassistant_api-6.0.1 → homeassistant_api-6.2.0}/homeassistant_api/models/entity_registry.py
RENAMED
|
@@ -35,6 +35,14 @@ class EntityCategory(StrEnum):
|
|
|
35
35
|
DIAGNOSTIC = "diagnostic"
|
|
36
36
|
|
|
37
37
|
|
|
38
|
+
class NextNamePart(StrEnum):
|
|
39
|
+
"""Next registry entry whose name is used to build the full entity name."""
|
|
40
|
+
|
|
41
|
+
AREA = "area"
|
|
42
|
+
DEVICE = "device"
|
|
43
|
+
PARENT_DEVICE = "parent_device"
|
|
44
|
+
|
|
45
|
+
|
|
38
46
|
class EntityRegistryEntry(BaseModel):
|
|
39
47
|
"""An entity registry entry as returned by ``config/entity_registry/list``."""
|
|
40
48
|
|
|
@@ -47,12 +55,15 @@ class EntityRegistryEntry(BaseModel):
|
|
|
47
55
|
disabled_by: EntityDisabledBy | None = None
|
|
48
56
|
entity_category: EntityCategory | None = None
|
|
49
57
|
entity_id: str
|
|
50
|
-
|
|
58
|
+
# No longer sent since Home Assistant 2026.11, only populated by older servers.
|
|
59
|
+
has_entity_name: bool | None = None
|
|
51
60
|
hidden_by: EntityHiddenBy | None = None
|
|
52
61
|
icon: str | None = None
|
|
53
62
|
id: str
|
|
63
|
+
labels: set[str] = Field(default_factory=set)
|
|
54
64
|
modified_at: DatetimeIsoField
|
|
55
65
|
name: str | None = None
|
|
66
|
+
next_name_part: NextNamePart | None = None
|
|
56
67
|
options: dict[str, Any] = Field(default_factory=dict)
|
|
57
68
|
original_name: str | None = None
|
|
58
69
|
platform: str
|
|
@@ -63,7 +74,8 @@ class EntityRegistryEntry(BaseModel):
|
|
|
63
74
|
class EntityRegistryEntryExtended(EntityRegistryEntry):
|
|
64
75
|
"""Extended entity registry entry as returned by ``config/entity_registry/get``."""
|
|
65
76
|
|
|
66
|
-
|
|
77
|
+
# ``None`` represents the computed entity name.
|
|
78
|
+
aliases: list[str | None] = Field(default_factory=list)
|
|
67
79
|
capabilities: dict[str, Any] | None = None
|
|
68
80
|
device_class: str | None = None
|
|
69
81
|
original_device_class: str | None = None
|
|
@@ -81,11 +93,11 @@ class EntityRegistryUpdateResult(BaseModel):
|
|
|
81
93
|
class EntityRegistryUpdateParams(TypedDict):
|
|
82
94
|
"""Parameters used in ``config/entity_registry/update``."""
|
|
83
95
|
|
|
84
|
-
aliases: NotRequired[list[str]]
|
|
96
|
+
aliases: NotRequired[list[str | None]]
|
|
85
97
|
area_id: NotRequired[str | None]
|
|
86
|
-
categories: NotRequired[dict[str, str]]
|
|
98
|
+
categories: NotRequired[dict[str, str | None]]
|
|
87
99
|
device_class: NotRequired[str | None]
|
|
88
|
-
disabled_by: NotRequired[
|
|
100
|
+
disabled_by: NotRequired[EntityDisabledBy | None]
|
|
89
101
|
entity_id: str
|
|
90
102
|
hidden_by: NotRequired[EntityHiddenBy | None]
|
|
91
103
|
icon: NotRequired[str | None]
|
|
@@ -94,4 +106,4 @@ class EntityRegistryUpdateParams(TypedDict):
|
|
|
94
106
|
new_entity_id: NotRequired[str]
|
|
95
107
|
# options and options_domain are inclusive, meaning only both or none of them have to be defined
|
|
96
108
|
options_domain: NotRequired[str]
|
|
97
|
-
options: NotRequired[dict[str, Any]]
|
|
109
|
+
options: NotRequired[dict[str, Any] | None]
|
|
@@ -117,9 +117,7 @@ _PARSERS: dict[str, Callable[[ResponseType], Any]] = {
|
|
|
117
117
|
def _parse_content(response: ResponseType) -> Any:
|
|
118
118
|
"""Look up and call the appropriate parser by content-type."""
|
|
119
119
|
content_type = response.headers.get("content-type", "text/plain")
|
|
120
|
-
|
|
121
|
-
content_type = content_type.decode("utf-8") # pragma: no cover
|
|
122
|
-
mimetype = str(content_type).split(";")[0].strip().lower()
|
|
120
|
+
mimetype = content_type.split(";")[0].strip().lower()
|
|
123
121
|
|
|
124
122
|
if (parser := _PARSERS.get(mimetype)) is None:
|
|
125
123
|
msg = f"No response processor found for mimetype {mimetype!r}."
|
|
@@ -65,6 +65,18 @@ class WebsocketClient(BaseWebsocketClient):
|
|
|
65
65
|
) -> None:
|
|
66
66
|
super().__init__(api_url, token, max_size=max_size)
|
|
67
67
|
self._session = session if session is not None else Session()
|
|
68
|
+
self._result_responses: dict[int, ResultResponse | None] = {}
|
|
69
|
+
self._event_responses: dict[int, list[EventResponse]] = {}
|
|
70
|
+
self._ping_responses: dict[int, PingResponse] = {}
|
|
71
|
+
|
|
72
|
+
def _store_result(self, msg_id: int, response: ResultResponse) -> None:
|
|
73
|
+
self._result_responses[msg_id] = response
|
|
74
|
+
|
|
75
|
+
def _store_event(self, msg_id: int, response: EventResponse) -> None:
|
|
76
|
+
self._event_responses[msg_id].append(response)
|
|
77
|
+
|
|
78
|
+
def _store_pong(self, msg_id: int, end_ns: int) -> None:
|
|
79
|
+
self._ping_responses[msg_id].end = end_ns
|
|
68
80
|
|
|
69
81
|
def __repr__(self) -> str:
|
|
70
82
|
return f"{self.__class__.__name__}({self.api_url!r})"
|
|
@@ -4,7 +4,7 @@ requires = ["hatchling"]
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "HomeAssistant-API"
|
|
7
|
-
version = "6.0
|
|
7
|
+
version = "6.2.0"
|
|
8
8
|
description = "Python Wrapper for Homeassistant's REST API"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "GPL-3.0-or-later"
|
|
@@ -16,6 +16,7 @@ dependencies = [
|
|
|
16
16
|
"niquests[ws]>=3",
|
|
17
17
|
"pydantic>=2,<3",
|
|
18
18
|
"simplejson>=3,<4",
|
|
19
|
+
"urllib3-future>=2.25.900",
|
|
19
20
|
]
|
|
20
21
|
|
|
21
22
|
[project.urls]
|
|
@@ -35,7 +36,6 @@ dev = [
|
|
|
35
36
|
"types-docutils>=0.22",
|
|
36
37
|
"types-simplejson>=3.20",
|
|
37
38
|
"types-toml>=0.10",
|
|
38
|
-
"zuban>=0.7",
|
|
39
39
|
"ruff>=0.15",
|
|
40
40
|
"pytest-asyncio>=1",
|
|
41
41
|
"pytest-cov>=7",
|
|
@@ -43,12 +43,14 @@ dev = [
|
|
|
43
43
|
"aiosqlite>=0.22",
|
|
44
44
|
"prek>=0.3.8",
|
|
45
45
|
"pre-commit>=4.5.1",
|
|
46
|
-
"nimax",
|
|
46
|
+
"nimax>=1.2",
|
|
47
|
+
"ty>=1",
|
|
47
48
|
]
|
|
48
49
|
|
|
49
50
|
[tool.nimax]
|
|
50
51
|
cassette_library_dir = "tests/cassettes"
|
|
51
52
|
match_on = ["method", "uri"]
|
|
53
|
+
ws_id_extractor = "id"
|
|
52
54
|
|
|
53
55
|
[tool.pytest.ini_options]
|
|
54
56
|
asyncio_mode = "auto"
|
|
@@ -91,6 +93,7 @@ ignore = [
|
|
|
91
93
|
"FBT",
|
|
92
94
|
"TD",
|
|
93
95
|
"FIX",
|
|
96
|
+
"CPY",
|
|
94
97
|
]
|
|
95
98
|
|
|
96
99
|
[tool.ruff.lint.per-file-ignores]
|
|
@@ -109,10 +112,6 @@ ignore = [
|
|
|
109
112
|
[tool.ruff.lint.isort]
|
|
110
113
|
force-single-line = true
|
|
111
114
|
|
|
112
|
-
[tool.zuban]
|
|
113
|
-
exclude = ["^docs/"]
|
|
114
|
-
untyped_function_return_mode = "inferred"
|
|
115
|
-
|
|
116
115
|
[tool.hatch.build.targets.wheel]
|
|
117
116
|
packages = ["homeassistant_api"]
|
|
118
117
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|