Coverage for src/homeassistant_repl/client.py: 62%
135 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-17 19:05 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-17 19:05 +0000
1"""Minimal Home Assistant websocket API client - built on niquests' websocket
2extension (a GET against a ws(s):// URL upgrades in place and hands back the
3extension on the response), the same HTTP stack `rest.py`'s REST client uses,
4rather than pulling in the separate `websockets` library for this one job."""
6from __future__ import annotations
8import asyncio
9import contextlib
10import functools
11import importlib.metadata
12import itertools
13import json
14import os
15from pathlib import Path
16from typing import Any, Self
17from urllib.parse import urlsplit, urlunsplit
19import niquests
22class HaReplError(Exception):
23 """Connection, auth or command failure (not an error in the user's code).
25 `code`/`detail` are the server's own error code and bare message when
26 this came from a failed websocket command, for a caller that wants to
27 turn a specific failure into its own exception (see sql.py's SqlTool).
28 """
30 def __init__(
31 self, message: str, *, code: str | None = None, detail: str | None = None
32 ) -> None:
33 super().__init__(message)
34 self.code = code
35 self.detail = detail
38@functools.cache
39def client_version() -> str:
40 """This package's own installed version, for the shells' startup banner
41 - "dev" if run from a checkout that was never pip/uv installed, rather
42 than raising over a cosmetic detail.
43 """
44 try:
45 return importlib.metadata.version("homeassistant-repl")
46 except importlib.metadata.PackageNotFoundError:
47 return "dev"
50@functools.cache
51def _dotenv() -> dict[str, str]:
52 """Best-effort KEY=VALUE pairs from a `.env` file in the current
53 directory, if one exists - checked only once real environment variables
54 come up empty, see resolve_url()/resolve_token(). Deliberately minimal
55 rather than pulling in python-dotenv: comments, blank lines, an optional
56 "export " prefix and quoted values are all a token/url file needs.
57 Cached since it's read-only for the life of the process and both
58 resolve_url() and resolve_token() may call it.
59 """
60 path = Path(".env")
61 if not path.is_file():
62 return {}
63 values: dict[str, str] = {}
64 for raw_line in path.read_text(encoding="utf-8").splitlines():
65 line = raw_line.strip().removeprefix("export ")
66 if not line or line.startswith("#"):
67 continue
68 key, sep, value = line.partition("=")
69 if not sep: 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true
70 continue
71 values[key.strip()] = value.strip().strip("'\"")
72 return values
75def _default_url() -> str:
76 return (
77 os.environ.get("HASS_SERVER")
78 or _dotenv().get("HASS_SERVER")
79 or "http://homeassistant.local:8123"
80 )
83def resolve_url(url: str | None) -> str:
84 """Accept http(s)://host:8123 or ws(s)://... and return the websocket endpoint."""
85 if not url:
86 # Inside a Home Assistant add-on (e.g. Studio Code Server) talk via the supervisor.
87 if os.environ.get("SUPERVISOR_TOKEN"):
88 return "ws://supervisor/core/websocket"
89 url = _default_url()
90 parts = urlsplit(url)
91 scheme = {"http": "ws", "https": "wss"}.get(parts.scheme, parts.scheme)
92 path = parts.path.rstrip("/")
93 if not path.endswith("/websocket"): 93 ↛ 95line 93 didn't jump to line 95 because the condition on line 93 was always true
94 path += "/api/websocket"
95 return urlunsplit((scheme, parts.netloc, path, "", ""))
98def resolve_rest_url(url: str | None) -> str:
99 """Accept http(s)://host:8123, ws(s)://... or an existing Client.url, and
100 return the REST API base (scheme normalised to http(s), path ending in
101 `/api`) that homeassistant_api.AsyncClient expects."""
102 if not url: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true
103 if os.environ.get("SUPERVISOR_TOKEN"):
104 return "http://supervisor/core/api"
105 url = _default_url()
106 parts = urlsplit(url)
107 scheme = {"ws": "http", "wss": "https"}.get(parts.scheme, parts.scheme)
108 path = parts.path.rstrip("/").removesuffix("/websocket")
109 if not path.endswith("/api"): 109 ↛ 111line 109 didn't jump to line 111 because the condition on line 109 was always true
110 path += "/api"
111 return urlunsplit((scheme, parts.netloc, path, "", ""))
114def resolve_token(token: str | None) -> str:
115 token = (
116 token
117 or os.environ.get("HASS_TOKEN")
118 or os.environ.get("SUPERVISOR_TOKEN")
119 or _dotenv().get("HASS_TOKEN")
120 )
121 if not token:
122 raise HaReplError(
123 "No access token: set HASS_TOKEN or pass --token "
124 "(create one under Profile > Security > Long-lived access tokens)"
125 )
126 return token
129class Client:
130 def __init__(self, url: str, token: str) -> None:
131 self.url = url
132 self._token = token
133 self._ids = itertools.count(1)
134 self._session: Any = None # set by open() - AsyncSession
135 self._ws: Any = (
136 None # set by open() - the extension: send_payload()/next_payload()/close()
137 )
138 # One command at a time: call() reads until its own reply arrives and
139 # drops anything else, so two overlapping calls (e.g. a gather() of
140 # two sql() queries) would each discard the other's reply.
141 self._call_lock = asyncio.Lock()
143 @property
144 def token(self) -> str:
145 """The resolved access token - also what a REST call (see rest.py's
146 `hass_api()`) against the same instance should authenticate with."""
147 return self._token
149 async def __aenter__(self) -> Self:
150 return await self.open()
152 async def __aexit__(self, *exc: object) -> None:
153 await self.close()
155 async def open(self) -> Self:
156 """Connect and authenticate - what `async with Client(...)` does,
157 exposed directly for callers that want to keep the connection open
158 past the enclosing scope (e.g. `connect()` in __init__.py)."""
159 self._session = niquests.AsyncSession()
160 try:
161 resp = await self._session.get(self.url)
162 resp.raise_for_status()
163 except niquests.exceptions.RequestException as err:
164 raise HaReplError(f"Cannot connect to {self.url}: {err}") from err
165 if resp.extension is None:
166 raise HaReplError(f"Server did not upgrade to WebSocket: {self.url}")
167 self._ws = resp.extension
168 msg = await self._recv()
169 if msg.get("type") != "auth_required":
170 raise HaReplError(f"Unexpected greeting: {msg}")
171 await self._send({"type": "auth", "access_token": self._token})
172 msg = await self._recv()
173 if msg.get("type") != "auth_ok":
174 raise HaReplError(f"Authentication failed: {msg.get('message', msg)}")
175 return self
177 async def close(self) -> None:
178 # Already gone - Home Assistant restarted, say - is closed enough.
179 with contextlib.suppress(niquests.exceptions.RequestException):
180 await self._ws.close()
181 await self._session.close()
183 async def _send(self, msg: dict[str, Any]) -> None:
184 try:
185 await self._ws.send_payload(json.dumps(msg))
186 except niquests.exceptions.RequestException as err:
187 raise HaReplError(f"Connection closed: {err}") from err
189 async def _recv(self) -> dict[str, Any]:
190 try:
191 payload = await self._ws.next_payload()
192 except niquests.exceptions.RequestException as err:
193 raise HaReplError(f"Connection closed: {err}") from err
194 if payload is None:
195 raise HaReplError("Connection closed")
196 return json.loads(payload)
198 async def send(self, type_: str, **payload: Any) -> None:
199 """Send a command without waiting for its reply, which call()'s own
200 loop drops - for one that has to go out while a call() is still
201 waiting, such as stopping the code that call() is waiting on."""
202 await self._send({"id": next(self._ids), "type": type_, **payload})
204 async def call(self, type_: str, **payload: Any) -> Any:
205 async with self._call_lock:
206 msg_id = next(self._ids)
207 await self._send({"id": msg_id, "type": type_, **payload})
208 while True:
209 msg = await self._recv()
210 if msg.get("id") != msg_id or msg.get("type") != "result":
211 continue
212 if not msg["success"]:
213 error = msg.get("error", {})
214 code = error.get("code")
215 if code == "unknown_command":
216 raise HaReplError(
217 f"{type_} not available: is the ha_repl_server integration "
218 "installed and `ha_repl_server:` in configuration.yaml?",
219 code=code,
220 )
221 detail = error.get("message")
222 raise HaReplError(
223 f"{type_} failed: {detail or error}", code=code, detail=detail
224 )
225 return msg["result"]