Coverage for src/homeassistant_repl/__init__.py: 60%

10 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-10-05 13:50 +0000

1"""Command line client for Home Assistant REPL.""" 

2 

3from __future__ import annotations 

4 

5from .api_objtree import ApiObjTree, Cache 

6from .client import Client, HaReplError, resolve_token, resolve_url 

7from .rest import hass_api 

8 

9__all__ = ["ApiObjTree", "Cache", "Client", "HaReplError", "connect", "hass_api"] 

10 

11 

12async def connect( 

13 url: str | None = None, token: str | None = None, *, ttl: float = 30.0 

14) -> ApiObjTree: 

15 """Connect to Home Assistant's websocket API and return a ready-to-use 

16 `obj` tree - the one-liner version of API client mode (see 

17 apirepl.py/api_objtree.py for the pieces this wires together), for 

18 scripts and plain Python sessions rather than the `ha-repl` REPL. 

19 

20 `url`/`token` default to $HASS_SERVER/$HASS_TOKEN (and, inside a Home 

21 Assistant add-on, the supervisor) the same way the CLI does - see 

22 resolve_url()/resolve_token(). `ttl` is how long the snapshot is used 

23 before it's considered stale; this helper doesn't auto-refresh, so call 

24 `await obj.cache.refresh()` yourself when you want a newer one. 

25 

26 The websocket stays open for the life of the process - call 

27 `await obj.cache.client.close()` when you're done with it, if that 

28 matters for your script. 

29 """ 

30 client = await Client(resolve_url(url), resolve_token(token)).open() 

31 cache = Cache(client, ttl) 

32 await cache.refresh() 

33 return ApiObjTree(cache)