Coverage for src/homeassistant_repl/__init__.py: 39%
19 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"""Command line client for Home Assistant REPL."""
3from __future__ import annotations
5import asyncio
6import warnings
8from .api_objtree import ApiObjTree, Cache
9from .client import Client, HaReplError
10from .config import load_config, resolve_connection
11from .rest import hass_api
13__all__ = ["ApiObjTree", "Cache", "Client", "HaReplError", "connect", "hass_api"]
16async def connect(
17 url: str | None = None, token: str | None = None, *, ttl: float | None = None
18) -> ApiObjTree:
19 """Connect to Home Assistant's websocket API and return a ready-to-use
20 `obj` tree - the one-liner version of API client mode (see
21 apirepl.py/api_objtree.py for the pieces this wires together), for
22 scripts and plain Python sessions rather than the `ha-repl` REPL.
24 `url` is a URL or the name of a server in `config.toml`, as the CLI's
25 `--server` is - `connect("house")`. `url`/`token` default to
26 $HASS_SERVER/$HASS_TOKEN, then `config.toml`'s `default` server (and,
27 inside a Home Assistant add-on, the supervisor) the same way the CLI
28 does - see config.py's resolve_connection(). Plugins are the
29 shells' own, and aren't run here. `ttl` is how long the snapshot is used
30 before it's considered stale (`config.toml`'s `ttl`, or 30 seconds);
31 this helper doesn't auto-refresh, so call `await obj.cache.refresh()`
32 yourself when you want a newer one.
34 The websocket stays open for the life of the process - call
35 `await obj.cache.client.close()` when you're done with it, if that
36 matters for your script.
37 """
38 config = load_config()
39 for warning in config.warnings:
40 warnings.warn(f"ha-repl: {warning}", stacklevel=2)
41 # In a thread: a server's `token_command` is a subprocess to wait for.
42 connection = await asyncio.to_thread(resolve_connection, url, token, config)
43 client = await Client(connection.url, connection.token).open()
44 if ttl is None:
45 ttl = 30.0 if config.ttl is None else float(config.ttl)
46 cache = Cache(client, ttl)
47 await cache.refresh()
48 return ApiObjTree(cache)