|
| 1 | +"""Home Assistant-aware ESPHome serial proxy URI handler for serialx.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +from typing import cast |
| 7 | + |
| 8 | +from aioesphomeapi import APIClient |
| 9 | +from serialx import register_uri_handler |
| 10 | +from serialx.platforms.serial_esphome import ( |
| 11 | + ESPHomeSerial, |
| 12 | + ESPHomeSerialTransport, |
| 13 | + InvalidSettingsError, |
| 14 | +) |
| 15 | +from yarl import URL |
| 16 | + |
| 17 | +from homeassistant.config_entries import ConfigEntryState |
| 18 | +from homeassistant.core import HomeAssistant, async_get_hass |
| 19 | + |
| 20 | +from .const import DOMAIN |
| 21 | +from .entry_data import ESPHomeConfigEntry |
| 22 | + |
| 23 | +SCHEME = "esphome-hass://" |
| 24 | + |
| 25 | +# This is required so that serialx can safely query Core for an instance of an |
| 26 | +# aioesphomeapi client. We cannot make any assumptions here, some packages run separate |
| 27 | +# asyncio event loops in dedicated threads. |
| 28 | +_HASS_LOOP: asyncio.AbstractEventLoop | None = None |
| 29 | + |
| 30 | + |
| 31 | +def set_hass_loop(loop: asyncio.AbstractEventLoop) -> None: |
| 32 | + """Store a reference to the Core event loop.""" |
| 33 | + global _HASS_LOOP # noqa: PLW0603 # pylint: disable=global-statement |
| 34 | + _HASS_LOOP = loop |
| 35 | + |
| 36 | + |
| 37 | +def build_url(entry_id: str, port_name: str) -> URL: |
| 38 | + """Build a canonical `esphome-hass://` URL.""" |
| 39 | + return URL.build( |
| 40 | + scheme="esphome-hass", |
| 41 | + host="esphome", |
| 42 | + path=f"/{entry_id}", |
| 43 | + query={"port_name": port_name}, |
| 44 | + ) |
| 45 | + |
| 46 | + |
| 47 | +async def _resolve_client(entry_id: str) -> APIClient: |
| 48 | + """Look up the `APIClient` for a specific config entry.""" |
| 49 | + |
| 50 | + # This function is async specifically so that we can get a reference to the Home |
| 51 | + # Assistant Core instance from its own thread |
| 52 | + hass: HomeAssistant = async_get_hass() |
| 53 | + entry = cast(ESPHomeConfigEntry, hass.config_entries.async_get_entry(entry_id)) |
| 54 | + |
| 55 | + if entry is None or entry.domain != DOMAIN: |
| 56 | + raise InvalidSettingsError(f"No ESPHome config entry with id {entry_id!r}") |
| 57 | + |
| 58 | + if entry.state is not ConfigEntryState.LOADED: |
| 59 | + raise InvalidSettingsError(f"ESPHome config entry {entry_id!r} is not loaded") |
| 60 | + |
| 61 | + return entry.runtime_data.client |
| 62 | + |
| 63 | + |
| 64 | +class HassESPHomeSerial(ESPHomeSerial): |
| 65 | + """ESPHomeSerial that resolves an HA config entry's APIClient from the URL.""" |
| 66 | + |
| 67 | + _api: APIClient | None |
| 68 | + _path: str | None |
| 69 | + |
| 70 | + async def _async_open(self) -> None: |
| 71 | + """Resolve the HA config entry's APIClient, then open the proxy.""" |
| 72 | + if self._api is None and self._path is not None: |
| 73 | + parsed = URL(str(self._path)) |
| 74 | + |
| 75 | + entry_id = parsed.path.lstrip("/") |
| 76 | + if not entry_id: |
| 77 | + raise InvalidSettingsError( |
| 78 | + f"No ESPHome config entry id in URL {self._path!r}" |
| 79 | + ) |
| 80 | + |
| 81 | + if "port_name" not in parsed.query: |
| 82 | + raise InvalidSettingsError("Port name is required") |
| 83 | + |
| 84 | + self._port_name = parsed.query["port_name"] |
| 85 | + |
| 86 | + hass_loop = _HASS_LOOP |
| 87 | + if hass_loop is None: |
| 88 | + raise InvalidSettingsError( |
| 89 | + "ESPHome integration has not registered its event loop" |
| 90 | + ) |
| 91 | + |
| 92 | + # Fetch the `APIClient` from the Core via the appropriate event loop |
| 93 | + self._api = await asyncio.wrap_future( |
| 94 | + asyncio.run_coroutine_threadsafe(_resolve_client(entry_id), hass_loop) |
| 95 | + ) |
| 96 | + self._client_loop = self._api._loop # noqa: SLF001 |
| 97 | + |
| 98 | + await super()._async_open() |
| 99 | + |
| 100 | + |
| 101 | +class HassESPHomeSerialTransport(ESPHomeSerialTransport): |
| 102 | + """Transport variant that constructs :class:`HassESPHomeSerial`.""" |
| 103 | + |
| 104 | + transport_name = "esphome-hass" |
| 105 | + _serial_cls = HassESPHomeSerial |
| 106 | + |
| 107 | + |
| 108 | +register_uri_handler( |
| 109 | + scheme=SCHEME, |
| 110 | + unique_scheme=SCHEME, |
| 111 | + sync_cls=HassESPHomeSerial, |
| 112 | + async_transport_cls=HassESPHomeSerialTransport, |
| 113 | +) |
0 commit comments