From c1260f40092bcf0bb468d19616362fe0825e35ca Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:36:42 +0100 Subject: [PATCH 01/12] feat(common): add the base modules of the HA compat layer Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 +- libs/energy_node_common/pyproject.toml | 3 + .../src/energy_node_common/ha/__init__.py | 11 ++++ .../energy_node_common/ha/config_entries.py | 41 ++++++++++++ .../src/energy_node_common/ha/const.py | 35 +++++++++++ .../src/energy_node_common/ha/core.py | 36 +++++++++++ .../src/energy_node_common/ha/exceptions.py | 23 +++++++ .../energy_node_common/ha/helpers/__init__.py | 0 .../ha/helpers/aiohttp_client.py | 13 ++++ .../ha/helpers/config_validation.py | 2 + .../ha/helpers/device_registry.py | 35 +++++++++++ .../ha/helpers/entity_platform.py | 5 ++ .../energy_node_common/ha/helpers/typing.py | 7 +++ .../energy_node_common/ha/util/__init__.py | 12 ++++ .../src/energy_node_common/ha/util/dt.py | 36 +++++++++++ libs/energy_node_common/tests/ha/__init__.py | 0 .../tests/ha/test_basics.py | 62 +++++++++++++++++++ 17 files changed, 322 insertions(+), 1 deletion(-) create mode 100644 libs/energy_node_common/src/energy_node_common/ha/__init__.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/config_entries.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/const.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/core.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/exceptions.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/__init__.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/aiohttp_client.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/config_validation.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/device_registry.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/entity_platform.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/typing.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/util/__init__.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/util/dt.py create mode 100644 libs/energy_node_common/tests/ha/__init__.py create mode 100644 libs/energy_node_common/tests/ha/test_basics.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index abe3ca753..ff5886f7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -451,7 +451,7 @@ jobs: cache-dependency-path: requirements-dev.txt - run: | python -m pip install --upgrade pip - pip install -e libs/energy_node_common -e libs/battery_soc_core pytest + pip install -e "libs/energy_node_common[ha]" -e libs/battery_soc_core pytest pip install -r requirements-dev.txt - run: pytest services libs scripts/tests -q diff --git a/libs/energy_node_common/pyproject.toml b/libs/energy_node_common/pyproject.toml index 60e8ddf26..0364589bb 100644 --- a/libs/energy_node_common/pyproject.toml +++ b/libs/energy_node_common/pyproject.toml @@ -11,6 +11,9 @@ dependencies = [ "paho-mqtt>=2.0", ] +[project.optional-dependencies] +ha = ["aiohttp>=3.9"] + [tool.setuptools.packages.find] where = ["src"] include = ["energy_node_common*"] diff --git a/libs/energy_node_common/src/energy_node_common/ha/__init__.py b/libs/energy_node_common/src/energy_node_common/ha/__init__.py new file mode 100644 index 000000000..c92ecf88f --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/__init__.py @@ -0,0 +1,11 @@ +"""Home-Assistant-compatible layer for porting simple polling integrations +to energy-node services. + +Covers the subset of the Home Assistant API that simple cloud and local +polling integrations need. Ported integrations switch their +``from homeassistant.`` imports to ``from energy_node_common.ha.``. + +Requires Python 3.11+ and the ``ha`` extra (aiohttp). See ``ha/README.md``. + +The API surface follows the Home Assistant API surface, no code is copied. +""" diff --git a/libs/energy_node_common/src/energy_node_common/ha/config_entries.py b/libs/energy_node_common/src/energy_node_common/ha/config_entries.py new file mode 100644 index 000000000..fbb2822d2 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/config_entries.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any, Callable, Generic, TypeVar + +T = TypeVar("T") + + +@dataclass +class ConfigSubentry: + data: MappingProxyType + subentry_type: str + title: str = "" + unique_id: str | None = None + subentry_id: str = "" + + +@dataclass +class ConfigEntry(Generic[T]): + """Config entry built from one ``*_devices.json`` record.""" + + entry_id: str + domain: str + title: str + data: MappingProxyType + options: MappingProxyType = field(default_factory=lambda: MappingProxyType({})) + subentries: dict[str, ConfigSubentry] = field(default_factory=dict) + version: int = 99 + runtime_data: Any = None + _on_unload: list[Callable] = field(default_factory=list) + + def get_subentries_of_type(self, subentry_type: str) -> list[ConfigSubentry]: + return [s for s in self.subentries.values() if s.subentry_type == subentry_type] + + def async_on_unload(self, func: Callable) -> None: + self._on_unload.append(func) + + def add_update_listener(self, listener: Callable) -> Callable: + # Config changes restart the service, so listeners never fire. + return lambda: None diff --git a/libs/energy_node_common/src/energy_node_common/ha/const.py b/libs/energy_node_common/src/energy_node_common/ha/const.py new file mode 100644 index 000000000..8658cb076 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/const.py @@ -0,0 +1,35 @@ +from enum import StrEnum + +CONF_API_KEY = "api_key" +CONF_LATITUDE = "latitude" +CONF_LONGITUDE = "longitude" +CONF_HOST = "host" +CONF_NAME = "name" +CONF_PASSWORD = "password" +CONF_USERNAME = "username" + + +class Platform(StrEnum): + SENSOR = "sensor" + BINARY_SENSOR = "binary_sensor" + SWITCH = "switch" + NUMBER = "number" + SELECT = "select" + BUTTON = "button" + + +class UnitOfPower(StrEnum): + WATT = "W" + KILO_WATT = "kW" + + +class UnitOfEnergy(StrEnum): + WATT_HOUR = "Wh" + KILO_WATT_HOUR = "kWh" + + +class EntityCategory(StrEnum): + CONFIG = "config" + DIAGNOSTIC = "diagnostic" + +CONF_CURRENCY = "currency" diff --git a/libs/energy_node_common/src/energy_node_common/ha/core.py b/libs/energy_node_common/src/energy_node_common/ha/core.py new file mode 100644 index 000000000..ff43403ba --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/core.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import asyncio +import functools +from dataclasses import dataclass, field +from typing import Any, Callable + + +def callback(func): + return func + + +@dataclass +class Config: + latitude: float = 0.0 + longitude: float = 0.0 + time_zone: str = "UTC" + language: str = "en" + + +@dataclass +class HomeAssistant: + """Tiny stand-in for ``hass``: loop, data, config, config_entries.""" + + loop: asyncio.AbstractEventLoop + config: Config = field(default_factory=Config) + data: dict[str, Any] = field(default_factory=dict) + config_entries: Any = None # set by runtime.ConfigEntries + + async def async_add_executor_job(self, target: Callable, *args): + return await self.loop.run_in_executor(None, functools.partial(target, *args)) + + def async_create_task(self, coro, name=None, eager_start=True): + return self.loop.create_task(coro, name=name) + + async_create_background_task = async_create_task diff --git a/libs/energy_node_common/src/energy_node_common/ha/exceptions.py b/libs/energy_node_common/src/energy_node_common/ha/exceptions.py new file mode 100644 index 000000000..26f1abeb6 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/exceptions.py @@ -0,0 +1,23 @@ +class HomeAssistantError(Exception): + def __init__(self, *args, translation_domain=None, translation_key=None, + translation_placeholders=None): + super().__init__(*args or (translation_key or "",)) + self.translation_domain = translation_domain + self.translation_key = translation_key + self.translation_placeholders = translation_placeholders + + +class ConfigEntryError(HomeAssistantError): + pass + + +class ConfigEntryNotReady(HomeAssistantError): + pass + + +class ConfigEntryAuthFailed(HomeAssistantError): + pass + + +class ServiceValidationError(HomeAssistantError): + pass diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/__init__.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/aiohttp_client.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/aiohttp_client.py new file mode 100644 index 000000000..868222e95 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/aiohttp_client.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import aiohttp + +_KEY = "energy_node_aiohttp_session" + + +def async_get_clientsession(hass, verify_ssl: bool = True) -> aiohttp.ClientSession: + session = hass.data.get(_KEY) + if session is None: + session = aiohttp.ClientSession() + hass.data[_KEY] = session + return session diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/config_validation.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/config_validation.py new file mode 100644 index 000000000..bf70a5057 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/config_validation.py @@ -0,0 +1,2 @@ +def config_entry_only_config_schema(domain): + return None diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/device_registry.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/device_registry.py new file mode 100644 index 000000000..d8179dbf9 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/device_registry.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from enum import StrEnum +from typing import TypedDict + + +class DeviceEntryType(StrEnum): + SERVICE = "service" + + +class DeviceInfo(TypedDict, total=False): + configuration_url: str + entry_type: DeviceEntryType + identifiers: set[tuple[str, str]] + manufacturer: str + model: str + name: str + sw_version: str + hw_version: str + serial_number: str + via_device: tuple[str, str] + + +class _DeviceRegistry: + def async_remove_device(self, device_id: str) -> None: + pass + + +def async_get(hass) -> _DeviceRegistry: + return _DeviceRegistry() + + +def async_entries_for_config_entry(registry, config_entry_id: str) -> list: + # No persistent device registry: nothing to clean up. + return [] diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/entity_platform.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/entity_platform.py new file mode 100644 index 000000000..ecb150ef9 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/entity_platform.py @@ -0,0 +1,5 @@ +from collections.abc import Callable, Iterable +from typing import Any + +AddConfigEntryEntitiesCallback = Callable[[Iterable[Any]], None] +AddEntitiesCallback = AddConfigEntryEntitiesCallback diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/typing.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/typing.py new file mode 100644 index 000000000..cfcd0d089 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/typing.py @@ -0,0 +1,7 @@ +from datetime import date, datetime +from decimal import Decimal +from typing import Any + +ConfigType = dict[str, Any] +StateType = str | int | float | None +_ = (date, datetime, Decimal) diff --git a/libs/energy_node_common/src/energy_node_common/ha/util/__init__.py b/libs/energy_node_common/src/energy_node_common/ha/util/__init__.py new file mode 100644 index 000000000..a4b40cf03 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/util/__init__.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +import re +import unicodedata + + +def slugify(text: str | None, *, separator: str = "_") -> str: + if not text: + return "" + text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode() + text = re.sub(r"[^a-z0-9]+", separator, text.lower()).strip(separator) + return text or "unknown" diff --git a/libs/energy_node_common/src/energy_node_common/ha/util/dt.py b/libs/energy_node_common/src/energy_node_common/ha/util/dt.py new file mode 100644 index 000000000..98494fdc6 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/util/dt.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from datetime import UTC, datetime, tzinfo +from zoneinfo import ZoneInfo + +DEFAULT_TIME_ZONE: tzinfo = UTC + + +def utcnow() -> datetime: + return datetime.now(UTC) + + +def now(time_zone: tzinfo | None = None) -> datetime: + return datetime.now(time_zone or DEFAULT_TIME_ZONE) + + +def get_time_zone(name: str) -> tzinfo | None: + try: + return ZoneInfo(name) + except Exception: # noqa: BLE001 + return None + + +def as_utc(value: datetime) -> datetime: + return value.astimezone(UTC) + + +def as_local(value: datetime) -> datetime: + return value.astimezone(DEFAULT_TIME_ZONE) + + +def parse_datetime(value: str) -> datetime | None: + try: + return datetime.fromisoformat(value) + except ValueError: + return None diff --git a/libs/energy_node_common/tests/ha/__init__.py b/libs/energy_node_common/tests/ha/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/libs/energy_node_common/tests/ha/test_basics.py b/libs/energy_node_common/tests/ha/test_basics.py new file mode 100644 index 000000000..4bf9a5909 --- /dev/null +++ b/libs/energy_node_common/tests/ha/test_basics.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import asyncio + +from energy_node_common.ha.config_entries import ConfigEntry, ConfigSubentry +from energy_node_common.ha.core import HomeAssistant +from energy_node_common.ha.exceptions import ConfigEntryError +from energy_node_common.ha.helpers.aiohttp_client import async_get_clientsession +from energy_node_common.ha.util import slugify +from energy_node_common.ha.util.dt import get_time_zone, utcnow + + +def test_subentries_by_type(): + entry = ConfigEntry( + entry_id="e1", + domain="test", + title="t", + data={}, + options={}, + subentries={ + "s1": ConfigSubentry(data={}, subentry_type="plane", title="a", unique_id=None, subentry_id="s1"), + "s2": ConfigSubentry(data={}, subentry_type="other", title="b", unique_id=None, subentry_id="s2"), + "s3": ConfigSubentry(data={}, subentry_type="plane", title="c", unique_id=None, subentry_id="s3"), + }, + ) + planes = entry.get_subentries_of_type("plane") + assert [s.subentry_id for s in planes] == ["s1", "s3"] + + +def test_exception_message_falls_back_to_translation_key(): + assert str(ConfigEntryError(translation_domain="x", translation_key="no_plane")) == "no_plane" + + +def test_slugify(): + assert slugify("Peak (08-20) Ä") == "peak_08_20_a" + assert slugify("") == "" + assert slugify("---") == "unknown" + + +def test_utcnow_is_aware(): + assert utcnow().tzinfo is not None + assert get_time_zone("Europe/Oslo") is not None + assert get_time_zone("No/Such") is None + + +def test_clientsession_is_shared(): + async def scenario(): + hass = HomeAssistant(asyncio.get_running_loop()) + first = async_get_clientsession(hass) + second = async_get_clientsession(hass) + assert first is second + await first.close() + + asyncio.run(scenario()) + + +def test_executor_job(): + async def scenario(): + hass = HomeAssistant(asyncio.get_running_loop()) + return await hass.async_add_executor_job(sum, [1, 2]) + + assert asyncio.run(scenario()) == 3 From f9b4f7ec10491190752bf7afd9969da460d38561 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:37:35 +0100 Subject: [PATCH 02/12] feat(common): add entities, coordinator and timers to the HA compat layer Co-Authored-By: Claude Sonnet 5.5 --- .../ha/components/__init__.py | 0 .../ha/components/binary_sensor/__init__.py | 34 ++++ .../ha/components/sensor/__init__.py | 67 +++++++ .../energy_node_common/ha/helpers/entity.py | 106 +++++++++++ .../energy_node_common/ha/helpers/event.py | 23 +++ .../ha/helpers/update_coordinator.py | 120 +++++++++++++ .../tests/ha/test_coordinator.py | 167 ++++++++++++++++++ .../tests/ha/test_entities.py | 66 +++++++ 8 files changed, 583 insertions(+) create mode 100644 libs/energy_node_common/src/energy_node_common/ha/components/__init__.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/components/binary_sensor/__init__.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/components/sensor/__init__.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/entity.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/event.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py create mode 100644 libs/energy_node_common/tests/ha/test_coordinator.py create mode 100644 libs/energy_node_common/tests/ha/test_entities.py diff --git a/libs/energy_node_common/src/energy_node_common/ha/components/__init__.py b/libs/energy_node_common/src/energy_node_common/ha/components/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/libs/energy_node_common/src/energy_node_common/ha/components/binary_sensor/__init__.py b/libs/energy_node_common/src/energy_node_common/ha/components/binary_sensor/__init__.py new file mode 100644 index 000000000..182bbb36b --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/components/binary_sensor/__init__.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum + +from ...helpers.entity import Entity, EntityDescription + +DOMAIN = "binary_sensor" + + +class BinarySensorDeviceClass(StrEnum): + CONNECTIVITY = "connectivity" + PROBLEM = "problem" + POWER = "power" + RUNNING = "running" + SAFETY = "safety" + + +@dataclass(frozen=True, kw_only=True) +class BinarySensorEntityDescription(EntityDescription): + pass + + +class BinarySensorEntity(Entity): + platform_domain = DOMAIN + + @property + def is_on(self) -> bool | None: + return self._attr("is_on") + + @property + def state(self): + value = self.is_on + return None if value is None else ("ON" if value else "OFF") diff --git a/libs/energy_node_common/src/energy_node_common/ha/components/sensor/__init__.py b/libs/energy_node_common/src/energy_node_common/ha/components/sensor/__init__.py new file mode 100644 index 000000000..78023ddbf --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/components/sensor/__init__.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date, datetime +from enum import StrEnum +from typing import Any + +from ...helpers.entity import Entity, EntityDescription + +DOMAIN = "sensor" + + +class SensorDeviceClass(StrEnum): + ENERGY = "energy" + POWER = "power" + TIMESTAMP = "timestamp" + TEMPERATURE = "temperature" + VOLTAGE = "voltage" + CURRENT = "current" + BATTERY = "battery" + IRRADIANCE = "irradiance" + + +class SensorStateClass(StrEnum): + MEASUREMENT = "measurement" + TOTAL = "total" + TOTAL_INCREASING = "total_increasing" + + +@dataclass(frozen=True, kw_only=True) +class SensorEntityDescription(EntityDescription): + last_reset: datetime | None = None + native_unit_of_measurement: str | None = None + options: list[str] | None = None + state_class: str | None = None + suggested_display_precision: int | None = None + suggested_unit_of_measurement: str | None = None + + +class SensorEntity(Entity): + platform_domain = DOMAIN + + @property + def native_value(self) -> Any: + return self._attr("native_value") + + @property + def native_unit_of_measurement(self): + return self._attr("native_unit_of_measurement") + + @property + def state_class(self): + return self._attr("state_class") + + @property + def suggested_display_precision(self): + return self._attr("suggested_display_precision") + + @property + def state(self) -> Any: + value = self.native_value + if isinstance(value, (datetime, date)): + return value.isoformat() + return value + + +from ...const import EntityCategory # noqa: E402,F401 (HA re-exports it here) diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/entity.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/entity.py new file mode 100644 index 000000000..35a7ad349 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/entity.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +_UNSET = object() + + +@dataclass(frozen=True, kw_only=True) +class EntityDescription: + key: str + device_class: str | None = None + entity_category: str | None = None + entity_registry_enabled_default: bool = True + entity_registry_visible_default: bool = True + has_entity_name: bool = False + icon: str | None = None + name: str | None = None + translation_key: str | None = None + translation_placeholders: dict | None = None + unit_of_measurement: str | None = None + + +class Entity: + """Attribute lookup like HA: ``_attr_``, then entity_description.""" + + entity_description: EntityDescription + entity_id: str | None = None + hass: Any = None + platform_domain: str = "" + _attr_has_entity_name: bool = False + _writer: Any = None # set by runtime when the entity is added + + def _attr(self, name: str, default: Any = None) -> Any: + value = getattr(self, f"_attr_{name}", _UNSET) + if value is not _UNSET: + return value + desc = getattr(self, "entity_description", None) + if desc is not None and hasattr(desc, name): + return getattr(desc, name) + return default + + @property + def unique_id(self) -> str | None: + return self._attr("unique_id") + + @property + def device_info(self): + return self._attr("device_info") + + @property + def has_entity_name(self) -> bool: + return self._attr("has_entity_name", False) + + @property + def name(self): + return self._attr("name") + + @property + def translation_key(self): + return self._attr("translation_key") + + @property + def translation_placeholders(self): + return self._attr("translation_placeholders") or {} + + @property + def device_class(self): + return self._attr("device_class") + + @property + def entity_category(self): + return self._attr("entity_category") + + @property + def entity_registry_enabled_default(self) -> bool: + return self._attr("entity_registry_enabled_default", True) + + @property + def icon(self): + return self._attr("icon") + + @property + def available(self) -> bool: + return self._attr("available", True) + + @property + def extra_state_attributes(self): + return self._attr("extra_state_attributes") + + @property + def state(self) -> Any: + return self._attr("state") + + async def async_added_to_hass(self) -> None: + pass + + def async_on_remove(self, func) -> None: + pass + + def async_write_ha_state(self) -> None: + if self._writer is not None: + self._writer.write_state(self) + + def async_schedule_update_ha_state(self, force_refresh: bool = False) -> None: + self.async_write_ha_state() diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/event.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/event.py new file mode 100644 index 000000000..6531fad97 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/event.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +import inspect +from datetime import datetime +from typing import Callable + +from ..util import dt as dt_util + + +def async_track_point_in_utc_time(hass, action: Callable, point_in_time: datetime) -> Callable[[], None]: + """Run ``action(now)`` once at ``point_in_time``; returns a cancel callback.""" + delay = max(0.0, (point_in_time - dt_util.utcnow()).total_seconds()) + + def _fire() -> None: + result = action(dt_util.utcnow()) + if inspect.isawaitable(result): + hass.loop.create_task(result) + + handle = hass.loop.call_later(delay, _fire) + return handle.cancel + + +async_track_point_in_time = async_track_point_in_utc_time diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py new file mode 100644 index 000000000..fa02b744f --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import asyncio +import logging +from datetime import timedelta +from typing import Any, Awaitable, Callable, Generic, TypeVar + +from ..exceptions import ConfigEntryAuthFailed, ConfigEntryError, ConfigEntryNotReady +from .entity import Entity + +T = TypeVar("T") + + +class UpdateFailed(Exception): + def __init__(self, *args, translation_domain=None, translation_key=None, + translation_placeholders=None, retry_after=None): + super().__init__(*args or (translation_key or "",)) + + +class DataUpdateCoordinator(Generic[T]): + """Polls ``_async_update_data`` on an asyncio timer and notifies entities.""" + + def __init__(self, hass, logger: logging.Logger, *, config_entry=None, + name: str, update_interval: timedelta | None = None, + update_method: Callable[[], Awaitable[T]] | None = None, + always_update: bool = True, **_: Any) -> None: + self.hass = hass + self.logger = logger + self.config_entry = config_entry + self.name = name + self.update_interval = update_interval + self.update_method = update_method + self.data: T = None # type: ignore[assignment] + self.last_update_success = True + self.last_exception: Exception | None = None + self._listeners: list[Callable[[], None]] = [] + self._task: asyncio.Task | None = None + + async def _async_update_data(self) -> T: + if self.update_method is None: + raise NotImplementedError("Update method not implemented") + return await self.update_method() + + async def _async_setup(self) -> None: + pass + + def async_add_listener(self, update_callback, context=None) -> Callable[[], None]: + self._listeners.append(update_callback) + return lambda: self._listeners.remove(update_callback) + + def async_update_listeners(self) -> None: + for listener in list(self._listeners): + listener() + + async def async_refresh(self) -> None: + try: + self.data = await self._async_update_data() + if not self.last_update_success: + self.logger.info("Fetching %s data recovered", self.name) + self.last_update_success = True + self.last_exception = None + except (ConfigEntryError, ConfigEntryAuthFailed): + raise + except Exception as err: # noqa: BLE001 - mirrors HA: any failure marks unavailable + if self.last_update_success: + self.logger.error("Error fetching %s data: %s", self.name, err) + self.last_update_success = False + self.last_exception = err + self.async_update_listeners() + + async def async_request_refresh(self) -> None: + await self.async_refresh() + + async def async_config_entry_first_refresh(self) -> None: + await self._async_setup() + await self.async_refresh() + if not self.last_update_success: + raise ConfigEntryNotReady(str(self.last_exception)) + self._start_timer() + + def _start_timer(self) -> None: + if self.update_interval is None or self._task is not None: + return + + async def _loop() -> None: + while True: + await asyncio.sleep(self.update_interval.total_seconds()) + await self.async_refresh() + + self._task = self.hass.async_create_task(_loop()) + + def async_set_updated_data(self, data: T) -> None: + self.data = data + self.last_update_success = True + self.async_update_listeners() + + async def async_shutdown(self) -> None: + if self._task is not None: + self._task.cancel() + self._task = None + + +class CoordinatorEntity(Entity, Generic[T]): + def __init__(self, coordinator, context: Any = None) -> None: + self.coordinator = coordinator + self.coordinator_context = context + + @property + def available(self) -> bool: + return self.coordinator.last_update_success + + async def async_added_to_hass(self) -> None: + await super().async_added_to_hass() + self.coordinator.async_add_listener(self._handle_coordinator_update) + + def _handle_coordinator_update(self) -> None: + self.async_write_ha_state() + + async def async_update(self) -> None: + await self.coordinator.async_request_refresh() diff --git a/libs/energy_node_common/tests/ha/test_coordinator.py b/libs/energy_node_common/tests/ha/test_coordinator.py new file mode 100644 index 000000000..dd880caca --- /dev/null +++ b/libs/energy_node_common/tests/ha/test_coordinator.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import asyncio +import logging +from datetime import timedelta + +from energy_node_common.ha.core import HomeAssistant +from energy_node_common.ha.exceptions import ConfigEntryError, ConfigEntryNotReady +from energy_node_common.ha.helpers.event import async_track_point_in_utc_time +from energy_node_common.ha.helpers.update_coordinator import ( + CoordinatorEntity, + DataUpdateCoordinator, + UpdateFailed, +) +from energy_node_common.ha.util import dt as dt_util + +LOGGER = logging.getLogger("test_coordinator") + + +class FakeWriter: + def __init__(self): + self.writes = 0 + + def write_state(self, entity): + self.writes += 1 + + +def _hass(): + return HomeAssistant(asyncio.get_running_loop()) + + +def test_first_refresh_success_notifies_listeners(): + async def scenario(): + calls = {"n": 0} + + async def update(): + return 1 + + coordinator = DataUpdateCoordinator(_hass(), LOGGER, name="t", update_method=update) + listener_calls = [] + coordinator.async_add_listener(lambda: listener_calls.append(1)) + await coordinator.async_config_entry_first_refresh() + await coordinator.async_shutdown() + return coordinator.data, len(listener_calls) + + data, listener_count = asyncio.run(scenario()) + assert data == 1 + assert listener_count == 1 + + +def test_first_refresh_failure_raises_not_ready(): + async def scenario(): + async def update(): + raise UpdateFailed("down") + + coordinator = DataUpdateCoordinator(_hass(), LOGGER, name="t", update_method=update) + try: + await coordinator.async_config_entry_first_refresh() + except ConfigEntryNotReady: + raised = True + else: + raised = False + return raised, coordinator.last_update_success + + raised, success = asyncio.run(scenario()) + assert raised is True + assert success is False + + +def test_config_entry_error_propagates(): + async def scenario(): + async def update(): + raise ConfigEntryError(translation_domain="x", translation_key="bad") + + coordinator = DataUpdateCoordinator(_hass(), LOGGER, name="t", update_method=update) + try: + await coordinator.async_refresh() + except ConfigEntryError: + return True + return False + + assert asyncio.run(scenario()) is True + + +def test_timer_refreshes(): + async def scenario(): + calls = {"n": 0} + + async def update(): + calls["n"] += 1 + return calls["n"] + + coordinator = DataUpdateCoordinator( + _hass(), LOGGER, name="t", + update_interval=timedelta(seconds=0.01), update_method=update, + ) + await coordinator.async_config_entry_first_refresh() + await asyncio.sleep(0.1) + running_count = calls["n"] + await coordinator.async_shutdown() + stopped_at = calls["n"] + await asyncio.sleep(0.03) + return running_count, stopped_at, calls["n"] + + running_count, stopped_at, after_wait = asyncio.run(scenario()) + assert running_count >= 3 + assert after_wait == stopped_at + + +def test_setup_hook_runs_once(): + async def scenario(): + calls = {"n": 0} + + class Coordinator(DataUpdateCoordinator): + async def _async_setup(self): + calls["n"] += 1 + + async def update(): + return 1 + + coordinator = Coordinator(_hass(), LOGGER, name="t", update_method=update) + await coordinator.async_config_entry_first_refresh() + await coordinator.async_shutdown() + return calls["n"] + + assert asyncio.run(scenario()) == 1 + + +def test_track_point_runs_coroutine(): + async def scenario(): + ran = [] + never = [] + + async def action(now): + ran.append(now) + + async def other(now): + never.append(now) + + hass = _hass() + async_track_point_in_utc_time(hass, action, dt_util.utcnow() + timedelta(milliseconds=10)) + cancel = async_track_point_in_utc_time(hass, other, dt_util.utcnow() + timedelta(milliseconds=10)) + cancel() + await asyncio.sleep(0.05) + return len(ran), len(never) + + ran, never = asyncio.run(scenario()) + assert ran == 1 + assert never == 0 + + +def test_coordinator_entity_writes_on_update(): + async def scenario(): + async def update(): + return 0 + + coordinator = DataUpdateCoordinator(_hass(), LOGGER, name="t", update_method=update) + entity = CoordinatorEntity(coordinator) + writer = FakeWriter() + entity._writer = writer + await entity.async_added_to_hass() + coordinator.async_set_updated_data(5) + return writer.writes, entity.available + + writes, available = asyncio.run(scenario()) + assert writes == 1 + assert available is True diff --git a/libs/energy_node_common/tests/ha/test_entities.py b/libs/energy_node_common/tests/ha/test_entities.py new file mode 100644 index 000000000..df14675f9 --- /dev/null +++ b/libs/energy_node_common/tests/ha/test_entities.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Callable + +from energy_node_common.ha.components.binary_sensor import BinarySensorEntity +from energy_node_common.ha.components.sensor import SensorEntity, SensorEntityDescription +from energy_node_common.ha.helpers.entity import Entity, EntityDescription + + +def test_attr_prefers_instance_over_description(): + desc = EntityDescription(key="k", device_class="power") + + class WithAttr(Entity): + entity_description = desc + _attr_device_class = "energy" + + class WithoutAttr(Entity): + entity_description = desc + + assert WithAttr().device_class == "energy" + assert WithoutAttr().device_class == "power" + + +def test_sensor_state_datetime_isoformat(): + class Clock(SensorEntity): + _attr_native_value = datetime(2026, 12, 6, 11, tzinfo=UTC) + + assert Clock().state == "2026-12-06T11:00:00+00:00" + + +def test_binary_sensor_state(): + class On(BinarySensorEntity): + _attr_is_on = True + + class Off(BinarySensorEntity): + _attr_is_on = False + + class Unknown(BinarySensorEntity): + _attr_is_on = None + + assert On().state == "ON" + assert Off().state == "OFF" + assert Unknown().state is None + + +def test_frozen_subclass_description(): + @dataclass(frozen=True, kw_only=True) + class PriceDescription(SensorEntityDescription): + value_fn: Callable + + desc = PriceDescription(key="price", value_fn=lambda data: data * 2) + + class Price(SensorEntity): + entity_description = desc + + def __init__(self, data): + self._data = data + + @property + def native_value(self): + return self.entity_description.value_fn(self._data) + + assert desc.key == "price" + assert Price(21).state == 42 From c4a720453228b39e2331787fb9a3d074bcc5487d Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:39:46 +0100 Subject: [PATCH 03/12] feat(common): host HA integrations and map entities to MQTT discovery Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/runtime.py | 200 ++++++++++++++++++ .../tests/ha/fake_port/__init__.py | 32 +++ .../tests/ha/fake_port/binary_sensor.py | 31 +++ .../tests/ha/fake_port/sensor.py | 71 +++++++ .../tests/ha/fake_port/strings.json | 7 + .../tests/ha/fake_port/translations/de.json | 7 + libs/energy_node_common/tests/ha/fakes.py | 28 +++ .../tests/ha/test_runtime.py | 190 +++++++++++++++++ 8 files changed, 566 insertions(+) create mode 100644 libs/energy_node_common/src/energy_node_common/ha/runtime.py create mode 100644 libs/energy_node_common/tests/ha/fake_port/__init__.py create mode 100644 libs/energy_node_common/tests/ha/fake_port/binary_sensor.py create mode 100644 libs/energy_node_common/tests/ha/fake_port/sensor.py create mode 100644 libs/energy_node_common/tests/ha/fake_port/strings.json create mode 100644 libs/energy_node_common/tests/ha/fake_port/translations/de.json create mode 100644 libs/energy_node_common/tests/ha/fakes.py create mode 100644 libs/energy_node_common/tests/ha/test_runtime.py diff --git a/libs/energy_node_common/src/energy_node_common/ha/runtime.py b/libs/energy_node_common/src/energy_node_common/ha/runtime.py new file mode 100644 index 000000000..4699b7ef0 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/runtime.py @@ -0,0 +1,200 @@ +"""Hosts one ported integration: builds config entries from a devices file, +forwards platform setup and turns entities into MQTT discovery and state.""" + +from __future__ import annotations + +import asyncio +import importlib +import json +import logging +from enum import Enum +from pathlib import Path +from types import MappingProxyType, ModuleType +from typing import Any + +from .. import mqtt as common_mqtt +from ..discovery import availability_entity_config, entity_config, publish_discovery +from .config_entries import ConfigEntry, ConfigSubentry +from .core import Config, HomeAssistant +from .helpers.update_coordinator import DataUpdateCoordinator +from .util import slugify + +log = logging.getLogger("energy_node_common.ha") + +# HA platform -> MQTT discovery component (same names today, kept explicit). +_COMPONENT = {"sensor": "sensor", "binary_sensor": "binary_sensor"} + + +class UnsupportedPlatformError(Exception): + """A platform the runtime cannot map to MQTT discovery.""" + + +def _format_state(value) -> str: + if isinstance(value, Enum): + value = value.value + if isinstance(value, (dict, list)): + return json.dumps(value, default=str) + return str(value) + + +def _translations(integration: ModuleType, language: str) -> dict: + base = Path(integration.__file__).parent + for candidate in (base / "translations" / f"{language}.json", + base / "translations" / "en.json", base / "strings.json"): + if candidate.exists(): + return json.loads(candidate.read_text(encoding="utf-8")) + return {} + + +class MqttWriter: + """Maps entities to discovery + state topics. + + One HA device (first ``identifiers`` entry of ``device_info``) becomes one + discovery device ``_``. State topics live below + ``base_topic/`` with ``object_id`` = slugified ``unique_id``. + """ + + def __init__(self, client, domain: str, fallback_id: str, base_topic: str, translations: dict): + self.client = client + self.domain = domain + self.fallback_id = fallback_id + self.base_topic = base_topic + self.translations = translations + self._devices: set[str] = set() + self._object_ids: set[str] = set() + + def _object_id(self, entity) -> str: + if entity.unique_id: + return slugify(str(entity.unique_id)) + return slugify(entity.entity_description.key) + + def _name(self, entity) -> str: + name = None + key = entity.translation_key + if key: + names = self.translations.get("entity", {}).get(entity.platform_domain, {}) + name = names.get(key, {}).get("name") + if not name or str(name).startswith("[%key:"): + # "[%key:...]" is a strings.json reference, not a usable name. + name = entity.name or entity.entity_description.key + try: + return name.format(**entity.translation_placeholders) + except (KeyError, IndexError): + return name + + def _device(self, entity) -> tuple[str, dict]: + info = dict(entity.device_info or {}) + idents = sorted(f"{d}_{i}" for d, i in info.get("identifiers", set())) + device_id = slugify(idents[0]) if idents else self.fallback_id + block = {"identifiers": [device_id], "name": info.get("name", device_id)} + for key in ("manufacturer", "model", "sw_version", "hw_version", + "serial_number", "configuration_url"): + if info.get(key): + block[key] = str(info[key]) + return device_id, block + + def add(self, entity) -> None: + component = _COMPONENT[entity.platform_domain] + object_id = self._object_id(entity) + if object_id in self._object_ids: + raise ValueError(f"duplicate object_id {object_id} (unique_id {entity.unique_id})") + self._object_ids.add(object_id) + device_id, device = self._device(entity) + if device_id not in self._devices: + self._devices.add(device_id) + publish_discovery(self.client, device_id, "binary_sensor", "online", + availability_entity_config(device_id, self.base_topic, device)) + extra: dict[str, Any] = {} + for attr, key in (("device_class", "device_class"), ("state_class", "state_class"), + ("native_unit_of_measurement", "unit_of_measurement"), + ("suggested_display_precision", "suggested_display_precision"), + ("entity_category", "entity_category"), ("icon", "icon")): + value = getattr(entity, attr, None) + if value is not None: + extra[key] = value if isinstance(value, int) else str(value) + if not entity.entity_registry_enabled_default: + extra["enabled_by_default"] = False + state_topic = f"{self.base_topic}/{object_id}" + extra["json_attributes_topic"] = f"{state_topic}/attributes" + config = entity_config(device_id, self.base_topic, object_id, self._name(entity), + device, state_topic=state_topic, **extra) + config["object_id"] = object_id + publish_discovery(self.client, device_id, component, object_id, config) + + def write_state(self, entity) -> None: + common_mqtt.publish_online_status( + self.client, self.base_topic, entity.available, + reason="" if entity.available else "update failed") + if not entity.available: + return + topic = f"{self.base_topic}/{self._object_id(entity)}" + common_mqtt.publish(self.client, topic, _format_state(entity.state)) + attrs = entity.extra_state_attributes + if attrs: + common_mqtt.publish(self.client, f"{topic}/attributes", + json.dumps(attrs, default=str)) + + +class ConfigEntries: + def __init__(self, hass: HomeAssistant, integration: ModuleType, writer: MqttWriter): + self.hass = hass + self.integration = integration + self.writer = writer + + async def async_forward_entry_setups(self, entry: ConfigEntry, platforms) -> None: + for platform in platforms: + if platform not in _COMPONENT: + raise UnsupportedPlatformError(f"unsupported platform '{platform}'") + for platform in platforms: + module = importlib.import_module(f"{self.integration.__name__}.{platform}") + added: list = [] + await module.async_setup_entry(self.hass, entry, lambda ents, *_: added.extend(ents)) + for entity in added: + entity.hass = self.hass + entity._writer = self.writer + self.writer.add(entity) + await entity.async_added_to_hass() + entity.async_write_ha_state() + + async def async_unload_platforms(self, entry, platforms) -> bool: + return True + + def async_schedule_reload(self, entry_id: str) -> None: + log.info("Reload requested for %s, restart the service to apply", entry_id) + + +def build_entry(domain: str, record: dict) -> ConfigEntry: + """``record`` mirrors a HA entry: id, name, data, options, subentries.""" + subentries = { + f"{record['id']}_{n}": ConfigSubentry( + data=MappingProxyType(sub.get("data", {})), subentry_type=sub["type"], + title=sub.get("title", ""), subentry_id=f"{record['id']}_{n}") + for n, sub in enumerate(record.get("subentries", [])) + } + return ConfigEntry(entry_id=record["id"], domain=domain, title=record.get("name", record["id"]), + data=MappingProxyType(record.get("data", {})), + options=MappingProxyType(record.get("options", {})), subentries=subentries) + + +async def run_integration(integration_package: str, domain: str, record: dict, client, + base_topic: str, language: str = "en", + ready: asyncio.Event | None = None) -> None: + """Set up one config entry and keep the loop alive until cancelled.""" + integration = importlib.import_module(integration_package) + hass = HomeAssistant(loop=asyncio.get_running_loop(), config=Config(language=language)) + writer = MqttWriter(client, domain, record["id"], base_topic, _translations(integration, language)) + hass.config_entries = ConfigEntries(hass, integration, writer) + entry = build_entry(domain, record) + try: + if not await integration.async_setup_entry(hass, entry): + raise RuntimeError(f"async_setup_entry for {domain} returned False") + if ready is not None: + ready.set() + await asyncio.Event().wait() + finally: + coordinator = entry.runtime_data + if isinstance(coordinator, DataUpdateCoordinator): + await coordinator.async_shutdown() + session = hass.data.get("energy_node_aiohttp_session") + if session is not None: + await session.close() diff --git a/libs/energy_node_common/tests/ha/fake_port/__init__.py b/libs/energy_node_common/tests/ha/fake_port/__init__.py new file mode 100644 index 000000000..5628ddfe9 --- /dev/null +++ b/libs/energy_node_common/tests/ha/fake_port/__init__.py @@ -0,0 +1,32 @@ +"""Minimal polling integration used to exercise the runtime.""" + +from __future__ import annotations + +import logging +from datetime import timedelta + +from energy_node_common.ha.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed + +log = logging.getLogger(__name__) + +# Last coordinator created by async_setup_entry, for tests that drive updates. +LAST_COORDINATOR: DataUpdateCoordinator | None = None + + +async def async_setup_entry(hass, entry) -> bool: + global LAST_COORDINATOR + + async def _update(): + if entry.data.get("fail"): + raise UpdateFailed("down") + return dict(entry.data["values"]) + + coordinator = DataUpdateCoordinator( + hass, log, config_entry=entry, name="fake", + update_interval=timedelta(hours=1), update_method=_update) + await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator + LAST_COORDINATOR = coordinator + await hass.config_entries.async_forward_entry_setups( + entry, entry.data.get("platforms", ["sensor", "binary_sensor"])) + return True diff --git a/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py b/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py new file mode 100644 index 000000000..8c17feb8d --- /dev/null +++ b/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py @@ -0,0 +1,31 @@ +"""Binary sensors of the fake integration.""" + +from __future__ import annotations + +from energy_node_common.ha.components.binary_sensor import ( + BinarySensorDeviceClass, + BinarySensorEntity, + BinarySensorEntityDescription, +) +from energy_node_common.ha.helpers.update_coordinator import CoordinatorEntity + + +class FakeBinarySensor(CoordinatorEntity, BinarySensorEntity): + def __init__(self, coordinator, description, device, unique_id): + super().__init__(coordinator) + self.entity_description = description + self._attr_unique_id = unique_id + self._attr_device_info = {"identifiers": {device}, "name": "Fake A", "manufacturer": "Fake"} + + @property + def is_on(self): + return bool(self.coordinator.data["alarm"]) + + +async def async_setup_entry(hass, entry, async_add_entities) -> None: + async_add_entities([ + FakeBinarySensor( + entry.runtime_data, + BinarySensorEntityDescription(key="alarm", device_class=BinarySensorDeviceClass.PROBLEM), + ("fake", "a"), "a_alarm"), + ]) diff --git a/libs/energy_node_common/tests/ha/fake_port/sensor.py b/libs/energy_node_common/tests/ha/fake_port/sensor.py new file mode 100644 index 000000000..c80570d33 --- /dev/null +++ b/libs/energy_node_common/tests/ha/fake_port/sensor.py @@ -0,0 +1,71 @@ +"""Sensors of the fake integration.""" + +from __future__ import annotations + +from enum import StrEnum + +from energy_node_common.ha.components.sensor import ( + SensorDeviceClass, + SensorEntity, + SensorEntityDescription, + SensorStateClass, +) +from energy_node_common.ha.helpers.update_coordinator import CoordinatorEntity + + +class Currency(StrEnum): + EUR = "eur" + + +class FakeSensor(CoordinatorEntity, SensorEntity): + def __init__(self, coordinator, description, device, unique_id, value_fn, *, attributes=None): + super().__init__(coordinator) + self.entity_description = description + self._attr_unique_id = unique_id + self._attr_device_info = { + "identifiers": {device}, + "name": f"Fake {device[1].upper()}", + "manufacturer": "Fake", + } + if attributes is not None: + self._attr_extra_state_attributes = attributes + self._value_fn = value_fn + + @property + def native_value(self): + return self._value_fn(self.coordinator.data) + + +async def async_setup_entry(hass, entry, async_add_entities) -> None: + coordinator = entry.runtime_data + device_a = ("fake", "a") + device_b = ("fake", "b") + entities = [ + FakeSensor( + coordinator, + SensorEntityDescription( + key="energy", device_class=SensorDeviceClass.ENERGY, + native_unit_of_measurement="kWh", state_class=SensorStateClass.TOTAL_INCREASING), + device_a, "a_energy", lambda d: d["energy"]), + FakeSensor( + coordinator, + SensorEntityDescription( + key="power", device_class=SensorDeviceClass.POWER, + native_unit_of_measurement="W", state_class=SensorStateClass.MEASUREMENT), + device_a, "a_power", lambda d: d["power"]), + FakeSensor( + coordinator, + SensorEntityDescription( + key="price", translation_key="price", + translation_placeholders={"area": "B"}), + device_b, "b_price", lambda d: Currency.EUR, attributes={"unit": "x"}), + FakeSensor( + coordinator, + SensorEntityDescription( + key="ref", translation_key="ref", entity_registry_enabled_default=False), + device_a, "a_ref", lambda d: None), + ] + if entry.data.get("duplicate"): + entities.append(FakeSensor( + coordinator, SensorEntityDescription(key="dup"), device_a, "a_energy", lambda d: 0)) + async_add_entities(entities) diff --git a/libs/energy_node_common/tests/ha/fake_port/strings.json b/libs/energy_node_common/tests/ha/fake_port/strings.json new file mode 100644 index 000000000..479e2109d --- /dev/null +++ b/libs/energy_node_common/tests/ha/fake_port/strings.json @@ -0,0 +1,7 @@ +{ + "entity": { + "sensor": { + "ref": {"name": "[%key:common::x%]"} + } + } +} diff --git a/libs/energy_node_common/tests/ha/fake_port/translations/de.json b/libs/energy_node_common/tests/ha/fake_port/translations/de.json new file mode 100644 index 000000000..110245663 --- /dev/null +++ b/libs/energy_node_common/tests/ha/fake_port/translations/de.json @@ -0,0 +1,7 @@ +{ + "entity": { + "sensor": { + "price": {"name": "Preis {area}"} + } + } +} diff --git a/libs/energy_node_common/tests/ha/fakes.py b/libs/energy_node_common/tests/ha/fakes.py new file mode 100644 index 000000000..8ad64e91a --- /dev/null +++ b/libs/energy_node_common/tests/ha/fakes.py @@ -0,0 +1,28 @@ +"""Test doubles for the HA compat layer runtime.""" + +from __future__ import annotations + + +class FakeClient: + """Records MQTT publishes as (topic, payload, retain) and ignores the rest.""" + + def __init__(self) -> None: + self.published: list[tuple[str, str, bool]] = [] + + def publish(self, topic, payload=None, qos=0, retain=False, properties=None): + self.published.append((topic, payload, retain)) + + def loop_start(self) -> None: + pass + + def loop_stop(self) -> None: + pass + + def will_set(self, *args, **kwargs) -> None: + pass + + def username_pw_set(self, *args, **kwargs) -> None: + pass + + def connect(self, *args, **kwargs) -> None: + pass diff --git a/libs/energy_node_common/tests/ha/test_runtime.py b/libs/energy_node_common/tests/ha/test_runtime.py new file mode 100644 index 000000000..01d345162 --- /dev/null +++ b/libs/energy_node_common/tests/ha/test_runtime.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import asyncio +import contextlib +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).parent)) + +import fake_port # noqa: E402 +from fakes import FakeClient # noqa: E402 +from energy_node_common.ha.config_entries import ConfigEntry, ConfigSubentry # noqa: E402 +from energy_node_common.ha.runtime import ( # noqa: E402 + UnsupportedPlatformError, + build_entry, + run_integration, +) + +BASE = "fake/node1" +PACKAGE = "fake_port" + + +def _record(**data): + values = {"energy": 12.5, "power": 1400, "alarm": True} + payload = {"values": values} + payload.update(data) + return {"id": "node1", "name": "Fake node", "data": payload} + + +@contextlib.asynccontextmanager +async def running(record, client, language="en"): + """Runs the integration until setup is done, then cancels it.""" + ready = asyncio.Event() + task = asyncio.create_task( + run_integration(PACKAGE, "fake", record, client, BASE, language=language, ready=ready)) + waiter = asyncio.ensure_future(ready.wait()) + await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED) + waiter.cancel() + if task.done(): + task.result() # surface setup errors + try: + yield + finally: + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + +def _discovery(client): + return {t: json.loads(p) for t, p, _ in client.published if t.startswith("homeassistant/")} + + +def _state(client): + return {t: (p, r) for t, p, r in client.published if t.startswith(BASE + "/")} + + +def test_discovery_per_entity_and_device(): + client = FakeClient() + + async def main(): + async with running(_record(), client): + pass + + asyncio.run(main()) + disc = _discovery(client) + for topic in ( + "homeassistant/sensor/fake_a/a_energy/config", + "homeassistant/sensor/fake_a/a_power/config", + "homeassistant/sensor/fake_b/b_price/config", + "homeassistant/sensor/fake_a/a_ref/config", + "homeassistant/binary_sensor/fake_a/a_alarm/config", + ): + assert topic in disc + assert disc["homeassistant/sensor/fake_b/b_price/config"]["device"]["identifiers"] == ["fake_b"] + online = sorted(t for t in disc if t.endswith("/online/config")) + assert online == [ + "homeassistant/binary_sensor/fake_a/online/config", + "homeassistant/binary_sensor/fake_b/online/config", + ] + + +def test_names_from_translation_with_placeholders(): + client = FakeClient() + + async def main(): + async with running(_record(), client, language="de"): + pass + + asyncio.run(main()) + disc = _discovery(client) + assert disc["homeassistant/sensor/fake_b/b_price/config"]["name"] == "Preis B" + + +def test_strings_reference_is_not_a_name(): + client = FakeClient() + + async def main(): + async with running(_record(), client, language="xx"): + pass + + asyncio.run(main()) + name = _discovery(client)["homeassistant/sensor/fake_a/a_ref/config"]["name"] + assert name == "ref" + assert "[%key:" not in name + + +def test_state_payloads(): + client = FakeClient() + + async def main(): + async with running(_record(), client): + pass + + asyncio.run(main()) + state = {t: p for t, (p, _) in _state(client).items()} + assert state[f"{BASE}/b_price"] == "eur" + assert state[f"{BASE}/a_ref"] == "None" + assert state[f"{BASE}/a_alarm"] == "ON" + assert state[f"{BASE}/a_energy"] == "12.5" + assert _state(client)[f"{BASE}/b_price"][1] is True + assert json.loads(state[f"{BASE}/b_price/attributes"]) == {"unit": "x"} + + +def test_disabled_by_default_flag(): + client = FakeClient() + + async def main(): + async with running(_record(), client): + pass + + asyncio.run(main()) + disc = _discovery(client) + assert disc["homeassistant/sensor/fake_a/a_ref/config"]["enabled_by_default"] is False + assert "enabled_by_default" not in disc["homeassistant/sensor/fake_a/a_energy/config"] + + +def test_unavailable_publishes_offline_only(): + client = FakeClient() + + async def main(): + async with running(_record(), client): + client.published.clear() + coordinator = fake_port.LAST_COORDINATOR + coordinator.last_update_success = False + coordinator.async_update_listeners() + + asyncio.run(main()) + assert (f"{BASE}/status/online", "0", True) in client.published + assert not [t for t in _state(client) if "/status/" not in t] + + +def test_unsupported_platform(): + record = _record(platforms=["switch"]) + with pytest.raises(UnsupportedPlatformError, match="unsupported platform 'switch'"): + asyncio.run(run_integration(PACKAGE, "fake", record, FakeClient(), BASE)) + + +def test_duplicate_object_id(): + record = _record(duplicate=True) + with pytest.raises(ValueError, match="a_energy"): + asyncio.run(run_integration(PACKAGE, "fake", record, FakeClient(), BASE)) + + +def test_build_entry_maps_record(): + record = { + "id": "n1", + "name": "Node", + "data": {"a": 1}, + "options": {"o": 2}, + "subentries": [ + {"type": "meter", "title": "M1", "data": {"x": 1}}, + {"type": "meter", "title": "M2", "data": {}}, + ], + } + entry = build_entry("fake", record) + assert isinstance(entry, ConfigEntry) + assert entry.entry_id == "n1" + assert entry.domain == "fake" + assert entry.title == "Node" + assert dict(entry.data) == {"a": 1} + assert dict(entry.options) == {"o": 2} + assert set(entry.subentries) == {"n1_0", "n1_1"} + sub = entry.subentries["n1_1"] + assert isinstance(sub, ConfigSubentry) + assert sub.subentry_type == "meter" + assert sub.title == "M2" + assert sub.subentry_id == "n1_1" From 88f91d84e551be5b7fcee059b86c122616cf48e1 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:40:16 +0100 Subject: [PATCH 04/12] fix(common): keep the coordinator timer alive after config entry errors Co-Authored-By: Claude Sonnet 5.5 --- .../ha/helpers/update_coordinator.py | 15 ++++++- .../tests/ha/test_coordinator.py | 40 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py index fa02b744f..bd6c66061 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py @@ -46,7 +46,12 @@ async def _async_setup(self) -> None: def async_add_listener(self, update_callback, context=None) -> Callable[[], None]: self._listeners.append(update_callback) - return lambda: self._listeners.remove(update_callback) + + def _unsubscribe() -> None: + if update_callback in self._listeners: + self._listeners.remove(update_callback) + + return _unsubscribe def async_update_listeners(self) -> None: for listener in list(self._listeners): @@ -85,7 +90,13 @@ def _start_timer(self) -> None: async def _loop() -> None: while True: await asyncio.sleep(self.update_interval.total_seconds()) - await self.async_refresh() + try: + await self.async_refresh() + except (ConfigEntryError, ConfigEntryAuthFailed) as err: + self.logger.error("Error fetching %s data: %s", self.name, err) + self.last_update_success = False + self.last_exception = err + self.async_update_listeners() self._task = self.hass.async_create_task(_loop()) diff --git a/libs/energy_node_common/tests/ha/test_coordinator.py b/libs/energy_node_common/tests/ha/test_coordinator.py index dd880caca..d9b60c5c5 100644 --- a/libs/energy_node_common/tests/ha/test_coordinator.py +++ b/libs/energy_node_common/tests/ha/test_coordinator.py @@ -165,3 +165,43 @@ async def update(): writes, available = asyncio.run(scenario()) assert writes == 1 assert available is True + + +def test_timer_survives_config_entry_error(): + async def scenario(): + calls = {"n": 0} + + async def update(): + calls["n"] += 1 + if calls["n"] == 1: + return 1 + raise ConfigEntryError(translation_domain="x", translation_key="bad") + + coordinator = DataUpdateCoordinator( + _hass(), LOGGER, name="t", + update_interval=timedelta(seconds=0.01), update_method=update, + ) + await coordinator.async_config_entry_first_refresh() + await asyncio.sleep(0.1) + result = (calls["n"], coordinator.last_update_success, coordinator.last_exception) + await coordinator.async_shutdown() + return result + + count, success, exc = asyncio.run(scenario()) + assert count >= 3 + assert success is False + assert isinstance(exc, ConfigEntryError) + + +def test_unsubscribe_twice_is_safe(): + async def scenario(): + async def update(): + return 0 + + coordinator = DataUpdateCoordinator(_hass(), LOGGER, name="t", update_method=update) + unsubscribe = coordinator.async_add_listener(lambda: None) + unsubscribe() + unsubscribe() + return coordinator._listeners + + assert asyncio.run(scenario()) == [] From 4a9d843076b6cf71aa87beedcc4e1eea183cd17b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:41:42 +0100 Subject: [PATCH 05/12] feat(common): add the HA port runner and its systemd template Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/__main__.py | 126 ++++++++++++++++++ .../systemd/energy-node-ha@.service | 18 +++ .../tests/ha/test_runner.py | 125 +++++++++++++++++ 3 files changed, 269 insertions(+) create mode 100644 libs/energy_node_common/src/energy_node_common/ha/__main__.py create mode 100644 libs/energy_node_common/systemd/energy-node-ha@.service create mode 100644 libs/energy_node_common/tests/ha/test_runner.py diff --git a/libs/energy_node_common/src/energy_node_common/ha/__main__.py b/libs/energy_node_common/src/energy_node_common/ha/__main__.py new file mode 100644 index 000000000..3a93280b3 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/__main__.py @@ -0,0 +1,126 @@ +"""Runs one ported HA integration as an energy-node service. + +Usage: ``python3 -m energy_node_common.ha [--config PATH] [--language de]`` + +The devices file ``/ha__devices.json`` holds +``{"devices": [...]}``, one record per device. Each record becomes one config +entry of the integration. Follows the Home Assistant API surface. +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import signal +import sys +from pathlib import Path +from typing import Sequence + +from .. import appconfig +from .. import mqtt as common_mqtt +from ..mqtt import publish_online_status +from .runtime import run_integration + +log = logging.getLogger("energy_node_common.ha") + + +def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(prog="energy_node_common.ha", + description="Run one ported HA integration.") + parser.add_argument("domain", help="integration domain, e.g. nordpool") + parser.add_argument("--config", default=appconfig.DEFAULT_CONFIG_PATH, + help="path to config.json") + parser.add_argument("--language", default="de", help="translation language") + return parser.parse_args(argv) + + +def package_for(domain: str) -> str: + return f"energy_node_ha_{domain}" + + +def service_name(domain: str) -> str: + return f"ha_{domain}" + + +def _load_devices(path: Path) -> list: + if not path.exists(): + return [] + return json.loads(path.read_text(encoding="utf-8")).get("devices", []) + + +async def run(args: argparse.Namespace, client_factory=common_mqtt.build_client) -> int: + try: + config = appconfig.load(args.config) + password = config.mqtt.password() + except appconfig.ConfigError as exc: + print(str(exc), file=sys.stderr) + return 2 + + logging.basicConfig(level=config.log_level, + format="%(asctime)s %(name)s %(levelname)s %(message)s") + + service = service_name(args.domain) + devices_path = config.devices_config(service) + devices = _load_devices(devices_path) + if not devices: + print(f"{devices_path}: keine Geräte konfiguriert", file=sys.stderr) + return 2 + + outstation = f"outstation/{service}" + client = client_factory( + client_id=f"{service}-bridge", + host=config.mqtt.host, + port=config.mqtt.port, + user=config.mqtt.username, + password=password, + will_topic=f"{outstation}/status/online", + will_payload="0", + ) + client.loop_start() + publish_online_status(client, outstation, True, reason="connected") + + loop = asyncio.get_running_loop() + stop = asyncio.Event() + signals = (signal.SIGTERM, signal.SIGINT) + for sig in signals: + loop.add_signal_handler(sig, stop.set) + + tasks: list[asyncio.Task] = [] + exit_code = 0 + try: + for rec in devices: + tasks.append(asyncio.ensure_future(run_integration( + package_for(args.domain), args.domain, rec, client, + base_topic=f"{service}/{rec['id']}", language=args.language))) + stop_wait = asyncio.ensure_future(stop.wait()) + await asyncio.wait([stop_wait, *tasks], return_when=asyncio.FIRST_COMPLETED) + stop_wait.cancel() + + failed = [t for t in tasks if t.done() and not t.cancelled() and t.exception()] + if failed: + exc = failed[0].exception() + reason = str(exc) or type(exc).__name__ + log.error("%s setup failed: %s", service, reason) + publish_online_status(client, outstation, False, reason=reason) + exit_code = 1 + else: + log.info("%s stopping", service) + publish_online_status(client, outstation, False, reason="shutdown") + finally: + for sig in signals: + loop.remove_signal_handler(sig) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + client.loop_stop() + return exit_code + + +def main(argv: Sequence[str] | None = None) -> int: + return asyncio.run(run(parse_args(argv))) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/libs/energy_node_common/systemd/energy-node-ha@.service b/libs/energy_node_common/systemd/energy-node-ha@.service new file mode 100644 index 000000000..7c887019f --- /dev/null +++ b/libs/energy_node_common/systemd/energy-node-ha@.service @@ -0,0 +1,18 @@ +[Unit] +Description=energy-node HA port %i +After=network-online.target mosquitto.service +Wants=network-online.target + +[Service] +Type=simple +User=energynode +# Konfiguration und MQTT-Zugangsdaten liegen zentral in +# /etc/energy-node/config.json bzw. der dort referenzierten +# Passwortdatei. Fehlt die Datei, bricht der Dienst mit einer Meldung ab. +# Einrichtung: docs/operating/configuration.md +ExecStart=/usr/bin/python3 -m energy_node_common.ha %i --config /etc/energy-node/config.json +Restart=on-failure +RestartSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/libs/energy_node_common/tests/ha/test_runner.py b/libs/energy_node_common/tests/ha/test_runner.py new file mode 100644 index 000000000..c975bd4ec --- /dev/null +++ b/libs/energy_node_common/tests/ha/test_runner.py @@ -0,0 +1,125 @@ +"""Tests fuer energy_node_common.ha.__main__ (Runner und systemd-Vorlage). + +Ausfuehren mit PYTHONPATH=libs/energy_node_common/src pytest libs/energy_node_common/tests +""" + +from __future__ import annotations + +import asyncio +import json +import os +import signal +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) + +import fake_port # noqa: E402 +from fakes import FakeClient # noqa: E402 + +sys.modules["energy_node_ha_fake"] = fake_port + +from energy_node_common.ha import __main__ as runner # noqa: E402 + +UNIT = Path(__file__).resolve().parents[2] / "systemd" / "energy-node-ha@.service" + + +def write_config(tmp_path: Path) -> Path: + manifests = tmp_path / "manifests" + manifests.mkdir() + (manifests / "automation.json").write_text(json.dumps({ + "service_id": "automation", "unit": "automation.service", + "schema": "config.schema.json", "required": ["service_id"], + }), encoding="utf-8") + document = { + "schema_version": 2, + "mqtt": {"host": "127.0.0.1", "port": 1883, "username": "", "password_file": ""}, + "paths": {"devices_dir": str(tmp_path), "data_dir": str(tmp_path)}, + "logging": {"level": "INFO"}, + "dashboard": { + "node_device_id": "energy_node", "node_device_name": "Energy Node", + "node_poll_interval_s": 60, "node_diagnostic_poll_multiplier": 10, + }, + "services": {"automation": {"service_id": "automation"}}, + } + path = tmp_path / "config.json" + path.write_text(json.dumps(document), encoding="utf-8") + return path + + +def write_devices(tmp_path: Path, data: dict) -> None: + devices = {"devices": [{"id": "node1", "name": "Fake node", "data": data}]} + (tmp_path / "ha_fake_devices.json").write_text(json.dumps(devices), encoding="utf-8") + + +def _values(**extra) -> dict: + data = {"values": {"energy": 12.5, "power": 1400, "alarm": True}} + data.update(extra) + return data + + +def _online_history(client) -> list[tuple[str, str]]: + return [(t, p) for t, p, _ in client.published if t == "outstation/ha_fake/status/online"] + + +def test_parse_args_defaults(): + args = runner.parse_args(["nordpool"]) + assert args.domain == "nordpool" + assert args.language == "de" + + +def test_names(): + assert runner.package_for("nordpool") == "energy_node_ha_nordpool" + assert runner.service_name("nordpool") == "ha_nordpool" + + +def test_missing_devices_file_exit_2(tmp_path, capsys): + config = write_config(tmp_path) + args = runner.parse_args(["fake", "--config", str(config)]) + client = FakeClient() + code = asyncio.run(runner.run(args, client_factory=lambda **kw: client)) + assert code == 2 + assert "keine Geräte konfiguriert" in capsys.readouterr().err + + +def test_setup_failure_exit_1_and_offline(tmp_path): + config = write_config(tmp_path) + write_devices(tmp_path, _values(fail=True)) + args = runner.parse_args(["fake", "--config", str(config)]) + client = FakeClient() + code = asyncio.run(runner.run(args, client_factory=lambda **kw: client)) + assert code == 1 + history = _online_history(client) + assert history[-1][1] == "0" + attributes = [p for t, p, _ in client.published if t == "outstation/ha_fake/status/online/attributes"] + assert json.loads(attributes[-1])["reason"] + + +def test_runs_and_stops_cleanly(tmp_path): + config = write_config(tmp_path) + write_devices(tmp_path, _values()) + args = runner.parse_args(["fake", "--config", str(config)]) + client = FakeClient() + + async def main(): + task = asyncio.create_task(runner.run(args, client_factory=lambda **kw: client)) + for _ in range(100): + if any(t.startswith("ha_fake/") for t, _, _ in client.published): + break + await asyncio.sleep(0.02) + else: + raise AssertionError("no state topics published") + os.kill(os.getpid(), signal.SIGTERM) + return await asyncio.wait_for(task, timeout=5) + + code = asyncio.run(main()) + assert code == 0 + assert _online_history(client)[-1][1] == "0" + attributes = [p for t, p, _ in client.published if t == "outstation/ha_fake/status/online/attributes"] + assert json.loads(attributes[-1])["reason"] == "shutdown" + + +def test_unit_template(): + text = UNIT.read_text(encoding="utf-8") + assert "ExecStart=/usr/bin/python3 -m energy_node_common.ha %i --config /etc/energy-node/config.json" in text + assert "Restart=on-failure" in text From fbb2196d93cab280e5f268d3657bb398f7d5f991 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:42:58 +0100 Subject: [PATCH 06/12] docs(common): describe the HA port contract Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/README.md | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 libs/energy_node_common/src/energy_node_common/ha/README.md diff --git a/libs/energy_node_common/src/energy_node_common/ha/README.md b/libs/energy_node_common/src/energy_node_common/ha/README.md new file mode 100644 index 000000000..15ca00f74 --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/README.md @@ -0,0 +1,104 @@ +# energy_node_common.ha + +A small compatibility layer that lets a ported Home Assistant integration run as +an energy-node service. It follows the Home Assistant API surface that simple +polling integrations use and turns every entity into MQTT discovery and state +topics. No Home Assistant code is copied into this package. + +Requires Python 3.11 or newer and the `ha` extra (`pip install "energy-node-common[ha]"`, +which pulls in aiohttp). No other module of `energy_node_common` imports this +package, so services on older Python versions are unaffected. + +## Scope + +Supported platforms: `sensor` and `binary_sensor`. Forwarding any other platform +fails with `unsupported platform ''`. + +Supported surface: + +- `core`: `HomeAssistant` (`loop`, `data`, `config`, `async_add_executor_job`, `async_create_task`), `callback` +- `config_entries`: `ConfigEntry`, `ConfigSubentry` +- `const`, `exceptions` (`ConfigEntryError`, `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, `HomeAssistantError`, `ServiceValidationError`) +- `helpers.update_coordinator`: `DataUpdateCoordinator`, `CoordinatorEntity`, `UpdateFailed` +- `helpers.entity`, `helpers.device_registry` (`DeviceInfo`, `DeviceEntryType`), `helpers.entity_platform`, `helpers.typing`, `helpers.config_validation` +- `helpers.aiohttp_client.async_get_clientsession` (one shared session per host) +- `helpers.event.async_track_point_in_utc_time` +- `util` (`slugify`) and `util.dt` (`utcnow`, `get_time_zone`) +- `components.sensor` and `components.binary_sensor` with their entity descriptions + +Not supported: config flows, services, recorder, repairs, bluetooth, zeroconf, +and any platform other than the two above. + +## Port contract + +A port is a Python package named `energy_node_ha_`, built as a wheel in +the ports repository. It contains the integration code with these rewrites: + +1. Every `from homeassistant.` import becomes `from energy_node_common.ha.`. +2. Every module starts with `from __future__ import annotations`. Without it, + class annotations on names imported only under `TYPE_CHECKING` fail on + Python 3.13. +3. `services.py` becomes a stub, `config_flow.py` and `diagnostics.py` are dropped. + +Ports need Python 3.12 or newer, because current integrations and their +libraries use newer syntax. That limits them to nodes on Debian Trixie or later. + +Translations stay where Home Assistant keeps them: `translations/.json`, +with `strings.json` as the last fallback. Entity names come from +`entity...name`, placeholders included. + +The configuration lives in `ha__devices.json` in the devices directory. +Each record mirrors a Home Assistant config entry: + +```json +{ + "devices": [ + { + "id": "home", + "name": "Home", + "data": {"latitude": 52.5, "longitude": 13.4}, + "options": {}, + "subentries": [ + {"type": "plane", "title": "South roof", "data": {"declination": 30}} + ] + } + ] +} +``` + +Subentries get the IDs `_0`, `_1` and so on. + +## Running + +The runner starts one integration with all its configured records: + +```sh +python3 -m energy_node_common.ha --config /etc/energy-node/config.json --language de +``` + +The systemd template `energy-node-ha@.service` runs it as +`energy-node-ha@.service` and restarts it after a failure. If setup +fails, for example because the API is not reachable, the runner reports the +service offline with the reason and exits with code 1. Without configured +devices it exits with code 2. + +## Topics + +For a record with ID ``, the base topic is `ha_/`. + +- Discovery: `homeassistant////config` +- `device_id` is the slugified `_` from the first sorted + `identifiers` entry of the entity's device info, otherwise the record ID +- `object_id` is the slugified `unique_id` +- State: `/`, attributes as JSON on `//attributes` +- Availability: `/status/online` plus one availability discovery per device +- Service status: `outstation/ha_/status/online` + +Enum values are published as their value, dicts and lists as JSON, everything +else as text. + +## License + +This layer is energy-node code under the MIT license. Ported integration code +stays under Apache-2.0 and lives in the separate ports repository, together +with its notice file. From 4985c581e1b2a8ad8c9401f48dc98adc8a7fa162 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:45:34 +0100 Subject: [PATCH 07/12] fix(common): harden the HA runner against bad listeners and device files Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/__main__.py | 21 ++++++++++++-- .../ha/helpers/update_coordinator.py | 5 +++- .../src/energy_node_common/ha/runtime.py | 2 +- .../tests/ha/fake_port/binary_sensor.py | 2 +- .../tests/ha/test_coordinator.py | 28 +++++++++++++++++++ .../tests/ha/test_runner.py | 13 +++++++++ 6 files changed, 66 insertions(+), 5 deletions(-) diff --git a/libs/energy_node_common/src/energy_node_common/ha/__main__.py b/libs/energy_node_common/src/energy_node_common/ha/__main__.py index 3a93280b3..2530d43c0 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/__main__.py +++ b/libs/energy_node_common/src/energy_node_common/ha/__main__.py @@ -45,9 +45,22 @@ def service_name(domain: str) -> str: def _load_devices(path: Path) -> list: + """Return the device records; raise ValueError naming the problem.""" if not path.exists(): return [] - return json.loads(path.read_text(encoding="utf-8")).get("devices", []) + try: + document = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + raise ValueError(f"kein gueltiges JSON ({exc})") from exc + if not isinstance(document, dict): + raise ValueError("erwartet ein Objekt mit dem Schluessel 'devices'") + devices = document.get("devices", []) + if not isinstance(devices, list): + raise ValueError("'devices' ist keine Liste") + for index, rec in enumerate(devices): + if not isinstance(rec, dict) or "id" not in rec: + raise ValueError(f"Gerät {index} ohne 'id'") + return devices async def run(args: argparse.Namespace, client_factory=common_mqtt.build_client) -> int: @@ -63,7 +76,11 @@ async def run(args: argparse.Namespace, client_factory=common_mqtt.build_client) service = service_name(args.domain) devices_path = config.devices_config(service) - devices = _load_devices(devices_path) + try: + devices = _load_devices(devices_path) + except ValueError as exc: + print(f"{devices_path}: {exc}", file=sys.stderr) + return 2 if not devices: print(f"{devices_path}: keine Geräte konfiguriert", file=sys.stderr) return 2 diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py index bd6c66061..69d45d6b2 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/update_coordinator.py @@ -55,7 +55,10 @@ def _unsubscribe() -> None: def async_update_listeners(self) -> None: for listener in list(self._listeners): - listener() + try: + listener() + except Exception: + self.logger.exception("Error in %s listener", self.name) async def async_refresh(self) -> None: try: diff --git a/libs/energy_node_common/src/energy_node_common/ha/runtime.py b/libs/energy_node_common/src/energy_node_common/ha/runtime.py index 4699b7ef0..d80309836 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/runtime.py +++ b/libs/energy_node_common/src/energy_node_common/ha/runtime.py @@ -148,7 +148,7 @@ async def async_forward_entry_setups(self, entry: ConfigEntry, platforms) -> Non for platform in platforms: module = importlib.import_module(f"{self.integration.__name__}.{platform}") added: list = [] - await module.async_setup_entry(self.hass, entry, lambda ents, *_: added.extend(ents)) + await module.async_setup_entry(self.hass, entry, lambda ents, *_, **__: added.extend(ents)) for entity in added: entity.hass = self.hass entity._writer = self.writer diff --git a/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py b/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py index 8c17feb8d..659c8ce92 100644 --- a/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py +++ b/libs/energy_node_common/tests/ha/fake_port/binary_sensor.py @@ -28,4 +28,4 @@ async def async_setup_entry(hass, entry, async_add_entities) -> None: entry.runtime_data, BinarySensorEntityDescription(key="alarm", device_class=BinarySensorDeviceClass.PROBLEM), ("fake", "a"), "a_alarm"), - ]) + ], update_before_add=False) diff --git a/libs/energy_node_common/tests/ha/test_coordinator.py b/libs/energy_node_common/tests/ha/test_coordinator.py index d9b60c5c5..7586f60a9 100644 --- a/libs/energy_node_common/tests/ha/test_coordinator.py +++ b/libs/energy_node_common/tests/ha/test_coordinator.py @@ -107,6 +107,34 @@ async def update(): assert after_wait == stopped_at +def test_listener_error_keeps_timer_running(): + async def scenario(): + async def update(): + return 1 + + coordinator = DataUpdateCoordinator( + _hass(), LOGGER, name="t", + update_interval=timedelta(seconds=0.01), update_method=update, + ) + + def broken(): + raise KeyError("missing") + + counts = {"n": 0} + + def healthy(): + counts["n"] += 1 + + coordinator.async_add_listener(broken) + coordinator.async_add_listener(healthy) + await coordinator.async_config_entry_first_refresh() + await asyncio.sleep(0.1) + await coordinator.async_shutdown() + return counts["n"] + + assert asyncio.run(scenario()) >= 3 + + def test_setup_hook_runs_once(): async def scenario(): calls = {"n": 0} diff --git a/libs/energy_node_common/tests/ha/test_runner.py b/libs/energy_node_common/tests/ha/test_runner.py index c975bd4ec..08c015938 100644 --- a/libs/energy_node_common/tests/ha/test_runner.py +++ b/libs/energy_node_common/tests/ha/test_runner.py @@ -82,6 +82,19 @@ def test_missing_devices_file_exit_2(tmp_path, capsys): assert "keine Geräte konfiguriert" in capsys.readouterr().err +def test_invalid_devices_file_exit_2(tmp_path, capsys): + config = write_config(tmp_path) + (tmp_path / "ha_fake_devices.json").write_text("{", encoding="utf-8") + args = runner.parse_args(["fake", "--config", str(config)]) + + def no_client(**kwargs): + raise AssertionError("MQTT client must not be built for an invalid devices file") + + code = asyncio.run(runner.run(args, client_factory=no_client)) + assert code == 2 + assert str(tmp_path / "ha_fake_devices.json") in capsys.readouterr().err + + def test_setup_failure_exit_1_and_offline(tmp_path): config = write_config(tmp_path) write_devices(tmp_path, _values(fail=True)) From a493cd99ff8122f8bc21e0b40142aabaa8c53c70 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:45:40 +0100 Subject: [PATCH 08/12] docs(common): align the HA port README with the runner behaviour Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libs/energy_node_common/src/energy_node_common/ha/README.md b/libs/energy_node_common/src/energy_node_common/ha/README.md index 15ca00f74..6208775f0 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/README.md +++ b/libs/energy_node_common/src/energy_node_common/ha/README.md @@ -21,7 +21,7 @@ Supported surface: - `const`, `exceptions` (`ConfigEntryError`, `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, `HomeAssistantError`, `ServiceValidationError`) - `helpers.update_coordinator`: `DataUpdateCoordinator`, `CoordinatorEntity`, `UpdateFailed` - `helpers.entity`, `helpers.device_registry` (`DeviceInfo`, `DeviceEntryType`), `helpers.entity_platform`, `helpers.typing`, `helpers.config_validation` -- `helpers.aiohttp_client.async_get_clientsession` (one shared session per host) +- `helpers.aiohttp_client.async_get_clientsession` (one session per config entry) - `helpers.event.async_track_point_in_utc_time` - `util` (`slugify`) and `util.dt` (`utcnow`, `get_time_zone`) - `components.sensor` and `components.binary_sensor` with their entity descriptions @@ -80,15 +80,15 @@ The systemd template `energy-node-ha@.service` runs it as `energy-node-ha@.service` and restarts it after a failure. If setup fails, for example because the API is not reachable, the runner reports the service offline with the reason and exits with code 1. Without configured -devices it exits with code 2. +devices, or with a devices file it cannot read, it exits with code 2. ## Topics For a record with ID ``, the base topic is `ha_/`. - Discovery: `homeassistant////config` -- `device_id` is the slugified `_` from the first sorted - `identifiers` entry of the entity's device info, otherwise the record ID +- `device_id` is the slugified `_` from the first + sorted `identifiers` entry of the entity's device info, otherwise the record ID - `object_id` is the slugified `unique_id` - State: `/`, attributes as JSON on `//attributes` - Availability: `/status/online` plus one availability discovery per device From 33c9452590baca045e37cc75d65db482ab2184de Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 6 Dec 2026 00:02:29 +0000 Subject: [PATCH 09/12] chore(release): bump component versions --- libs/energy_node_common/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/energy_node_common/VERSION b/libs/energy_node_common/VERSION index 60f634328..4b328a306 100644 --- a/libs/energy_node_common/VERSION +++ b/libs/energy_node_common/VERSION @@ -1 +1 @@ -v0.6.0 +v0.6.1-pre.1 From 8da817bc7c8a25bb7f199b0e6ab5c86021acd60b Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 6 Dec 2026 00:03:41 +0000 Subject: [PATCH 10/12] docs(changelog): update changelogs --- changelog/highlights/319.json | 8 ++++++++ dashboard/CHANGELOG.md | 2 +- libs/energy_node_common/CHANGELOG.md | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 changelog/highlights/319.json diff --git a/changelog/highlights/319.json b/changelog/highlights/319.json new file mode 100644 index 000000000..b55a028d5 --- /dev/null +++ b/changelog/highlights/319.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Kompatibilitätsschicht für portierte Home-Assistant-Integrationen" + }, + "en": { + "*": "Add a Home Assistant compat layer for ported integrations" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 7f3527294..43505c7e1 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -5,13 +5,13 @@ ### Features - **dashboard:** A compact header whose status chip names the cause of a problem (#316) (6f5aa61) +- **overview:** add a device map card to the overview (#318) (1557b48) - **overview:** add the device_map card type to the layout settings (a226f60) - **overview:** add viewport gestures and fit spring for map cards (62c9456) - **overview:** add the device map card component (a99435a) - **overview:** render the device map card with glass label, fit pill and tap modes (0d553bd) - **overview:** load the device map card lazily and keep it out of the grid swap (e6275a0) - **layout-editor:** offer the device map card with its options (6eecf34) -- **overview:** add a device map card to the overview (#318) - **health:** derive a ranked issue list from the node state (c7c1a75) - **health:** report issues and level, count only installed services (f290fb2) - **dashboard:** one title row with a status chip that names its cause (0c99637) diff --git a/libs/energy_node_common/CHANGELOG.md b/libs/energy_node_common/CHANGELOG.md index 2472264ce..19880d950 100644 --- a/libs/energy_node_common/CHANGELOG.md +++ b/libs/energy_node_common/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## v0.6.1-pre.1 (2026-12-06) + +### Features + +- **common:** add the base modules of the HA compat layer (c1260f4) +- **common:** add entities, coordinator and timers to the HA compat layer (f9b4f7e) +- **common:** host HA integrations and map entities to MQTT discovery (c4a7204) +- **common:** add the HA port runner and its systemd template (4a9d843) +- **common:** add a Home Assistant compat layer for ported integrations (#319) + +### Fixes + +- **common:** keep the coordinator timer alive after config entry errors (88f91d8) +- **common:** harden the HA runner against bad listeners and device files (4985c58) + +### Documentation + +- **common:** describe the HA port contract (fbb2196) +- **common:** align the HA port README with the runner behaviour (a493cd9) + ## v0.6.0 (2026-11-15) ### Features From 97a3e7ac50e03c54b93115a7e7983f77b39588de Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:28:25 +0100 Subject: [PATCH 11/12] feat(common): cover the Home Assistant 2026.12 surface of forecast_solar and nordpool Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/README.md | 6 +- .../energy_node_common/ha/config_entries.py | 15 +++ .../src/energy_node_common/ha/const.py | 2 + .../src/energy_node_common/ha/core.py | 35 ++++++ .../energy_node_common/ha/helpers/debounce.py | 69 +++++++++++ .../ha/helpers/entity_registry.py | 24 ++++ .../src/energy_node_common/ha/runtime.py | 10 +- .../tests/ha/test_compat_2026_12.py | 110 ++++++++++++++++++ 8 files changed, 267 insertions(+), 4 deletions(-) create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/debounce.py create mode 100644 libs/energy_node_common/src/energy_node_common/ha/helpers/entity_registry.py create mode 100644 libs/energy_node_common/tests/ha/test_compat_2026_12.py diff --git a/libs/energy_node_common/src/energy_node_common/ha/README.md b/libs/energy_node_common/src/energy_node_common/ha/README.md index 6208775f0..16b1f5464 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/README.md +++ b/libs/energy_node_common/src/energy_node_common/ha/README.md @@ -16,13 +16,15 @@ fails with `unsupported platform ''`. Supported surface: -- `core`: `HomeAssistant` (`loop`, `data`, `config`, `async_add_executor_job`, `async_create_task`), `callback` -- `config_entries`: `ConfigEntry`, `ConfigSubentry` +- `core`: `HomeAssistant` (`loop`, `data`, `config`, `bus`, `async_add_executor_job`, `async_create_task`), `callback`, `Event`, `CALLBACK_TYPE` +- `config_entries`: `ConfigEntry` (with `state`), `ConfigEntryState`, `ConfigSubentry` - `const`, `exceptions` (`ConfigEntryError`, `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, `HomeAssistantError`, `ServiceValidationError`) - `helpers.update_coordinator`: `DataUpdateCoordinator`, `CoordinatorEntity`, `UpdateFailed` - `helpers.entity`, `helpers.device_registry` (`DeviceInfo`, `DeviceEntryType`), `helpers.entity_platform`, `helpers.typing`, `helpers.config_validation` - `helpers.aiohttp_client.async_get_clientsession` (one session per config entry) - `helpers.event.async_track_point_in_utc_time` +- `helpers.debounce.Debouncer` +- `helpers.entity_registry` (empty registry, lookups return `None`) - `util` (`slugify`) and `util.dt` (`utcnow`, `get_time_zone`) - `components.sensor` and `components.binary_sensor` with their entity descriptions diff --git a/libs/energy_node_common/src/energy_node_common/ha/config_entries.py b/libs/energy_node_common/src/energy_node_common/ha/config_entries.py index fbb2822d2..ce45b1eb6 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/config_entries.py +++ b/libs/energy_node_common/src/energy_node_common/ha/config_entries.py @@ -1,12 +1,26 @@ from __future__ import annotations from dataclasses import dataclass, field +from enum import Enum from types import MappingProxyType from typing import Any, Callable, Generic, TypeVar T = TypeVar("T") +class ConfigEntryState(Enum): + """Lifecycle state of a config entry.""" + + LOADED = "loaded" + SETUP_ERROR = "setup_error" + MIGRATION_ERROR = "migration_error" + SETUP_RETRY = "setup_retry" + NOT_LOADED = "not_loaded" + FAILED_UNLOAD = "failed_unload" + SETUP_IN_PROGRESS = "setup_in_progress" + UNLOAD_IN_PROGRESS = "unload_in_progress" + + @dataclass class ConfigSubentry: data: MappingProxyType @@ -28,6 +42,7 @@ class ConfigEntry(Generic[T]): subentries: dict[str, ConfigSubentry] = field(default_factory=dict) version: int = 99 runtime_data: Any = None + state: ConfigEntryState = ConfigEntryState.NOT_LOADED _on_unload: list[Callable] = field(default_factory=list) def get_subentries_of_type(self, subentry_type: str) -> list[ConfigSubentry]: diff --git a/libs/energy_node_common/src/energy_node_common/ha/const.py b/libs/energy_node_common/src/energy_node_common/ha/const.py index 8658cb076..a26c01b1e 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/const.py +++ b/libs/energy_node_common/src/energy_node_common/ha/const.py @@ -33,3 +33,5 @@ class EntityCategory(StrEnum): DIAGNOSTIC = "diagnostic" CONF_CURRENCY = "currency" + +EVENT_CORE_CONFIG_UPDATE = "core_config_updated" diff --git a/libs/energy_node_common/src/energy_node_common/ha/core.py b/libs/energy_node_common/src/energy_node_common/ha/core.py index ff43403ba..b14fd71f8 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/core.py +++ b/libs/energy_node_common/src/energy_node_common/ha/core.py @@ -10,6 +10,40 @@ def callback(func): return func +CALLBACK_TYPE = Callable[[], None] + + +@dataclass +class Event: + event_type: str + data: dict[str, Any] = field(default_factory=dict) + + +class EventBus: + """Local event bus. Nothing in energy-node fires HA core events, so listeners + only run when a port fires its own events.""" + + def __init__(self) -> None: + self._listeners: dict[str, list[tuple[Callable, Callable | None]]] = {} + + def async_listen(self, event_type: str, listener: Callable, event_filter: Callable | None = None) -> CALLBACK_TYPE: + item = (listener, event_filter) + self._listeners.setdefault(event_type, []).append(item) + + def _remove() -> None: + listeners = self._listeners.get(event_type, []) + if item in listeners: + listeners.remove(item) + + return _remove + + def async_fire(self, event_type: str, event_data: dict[str, Any] | None = None) -> None: + event = Event(event_type, dict(event_data or {})) + for listener, event_filter in list(self._listeners.get(event_type, [])): + if event_filter is None or event_filter(event.data): + listener(event) + + @dataclass class Config: latitude: float = 0.0 @@ -26,6 +60,7 @@ class HomeAssistant: config: Config = field(default_factory=Config) data: dict[str, Any] = field(default_factory=dict) config_entries: Any = None # set by runtime.ConfigEntries + bus: EventBus = field(default_factory=EventBus) async def async_add_executor_job(self, target: Callable, *args): return await self.loop.run_in_executor(None, functools.partial(target, *args)) diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/debounce.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/debounce.py new file mode 100644 index 000000000..96d8ef28a --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/debounce.py @@ -0,0 +1,69 @@ +"""Debouncer: run a function at most once per cooldown.""" + +from __future__ import annotations + +import asyncio +import inspect +import logging +from typing import Any, Callable + + +class Debouncer: + def __init__(self, hass, logger: logging.Logger, *, cooldown: float, immediate: bool, + function: Callable[[], Any] | None = None, background: bool = False) -> None: + self.hass = hass + self.logger = logger + self.cooldown = cooldown + self.immediate = immediate + self.function = function + self._timer: asyncio.TimerHandle | None = None + self._execute_at_end = False + self._shutdown = False + + async def async_call(self) -> None: + if self._shutdown: + return + if self._timer is not None or not self.immediate: + self._execute_at_end = True + if self._timer is None: + self._schedule_timer() + return + await self._run() + self._schedule_timer() + + def async_schedule_call(self) -> None: + if not self._shutdown: + self.hass.loop.create_task(self.async_call()) + + def async_cancel(self) -> None: + if self._timer is not None: + self._timer.cancel() + self._timer = None + self._execute_at_end = False + + def async_shutdown(self) -> None: + self._shutdown = True + self.async_cancel() + + async def _run(self) -> None: + if self.function is None: + return + try: + result = self.function() + if inspect.isawaitable(result): + await result + except Exception: # noqa: BLE001 - a failing call must not kill the timer + self.logger.exception("Error in debounced function") + + def _schedule_timer(self) -> None: + self._timer = self.hass.loop.call_later(self.cooldown, self._on_timer) + + def _on_timer(self) -> None: + self._timer = None + if self._execute_at_end and not self._shutdown: + self._execute_at_end = False + self.hass.loop.create_task(self._run_and_reschedule()) + + async def _run_and_reschedule(self) -> None: + await self._run() + self._schedule_timer() diff --git a/libs/energy_node_common/src/energy_node_common/ha/helpers/entity_registry.py b/libs/energy_node_common/src/energy_node_common/ha/helpers/entity_registry.py new file mode 100644 index 000000000..8041a55bd --- /dev/null +++ b/libs/energy_node_common/src/energy_node_common/ha/helpers/entity_registry.py @@ -0,0 +1,24 @@ +"""Entity registry stand-in. energy-node keeps no registry, so lookups find nothing.""" + +from __future__ import annotations + +from typing import Any + +EVENT_ENTITY_REGISTRY_UPDATED = "entity_registry_updated" + +EventEntityRegistryUpdatedData = dict[str, Any] + + +class EntityRegistry: + def async_get(self, entity_id: str) -> None: + return None + + def async_get_entity_id(self, domain: str, platform: str, unique_id: str) -> None: + return None + + +_REGISTRY = EntityRegistry() + + +def async_get(hass) -> EntityRegistry: + return _REGISTRY diff --git a/libs/energy_node_common/src/energy_node_common/ha/runtime.py b/libs/energy_node_common/src/energy_node_common/ha/runtime.py index d80309836..d5f4a65d4 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/runtime.py +++ b/libs/energy_node_common/src/energy_node_common/ha/runtime.py @@ -14,7 +14,7 @@ from .. import mqtt as common_mqtt from ..discovery import availability_entity_config, entity_config, publish_discovery -from .config_entries import ConfigEntry, ConfigSubentry +from .config_entries import ConfigEntry, ConfigEntryState, ConfigSubentry from .core import Config, HomeAssistant from .helpers.update_coordinator import DataUpdateCoordinator from .util import slugify @@ -159,6 +159,9 @@ async def async_forward_entry_setups(self, entry: ConfigEntry, platforms) -> Non async def async_unload_platforms(self, entry, platforms) -> bool: return True + async def async_unload_platforms_or_raise(self, entry, platforms) -> None: + await self.async_unload_platforms(entry, platforms) + def async_schedule_reload(self, entry_id: str) -> None: log.info("Reload requested for %s, restart the service to apply", entry_id) @@ -186,8 +189,11 @@ async def run_integration(integration_package: str, domain: str, record: dict, c hass.config_entries = ConfigEntries(hass, integration, writer) entry = build_entry(domain, record) try: - if not await integration.async_setup_entry(hass, entry): + # Since HA 2026.12 async_setup_entry may return None on success. + if await integration.async_setup_entry(hass, entry) is False: + entry.state = ConfigEntryState.SETUP_ERROR raise RuntimeError(f"async_setup_entry for {domain} returned False") + entry.state = ConfigEntryState.LOADED if ready is not None: ready.set() await asyncio.Event().wait() diff --git a/libs/energy_node_common/tests/ha/test_compat_2026_12.py b/libs/energy_node_common/tests/ha/test_compat_2026_12.py new file mode 100644 index 000000000..334cc8117 --- /dev/null +++ b/libs/energy_node_common/tests/ha/test_compat_2026_12.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import asyncio +import logging +import sys +from pathlib import Path +from types import ModuleType + +sys.path.insert(0, str(Path(__file__).parent)) + +from fakes import FakeClient # noqa: E402 +from energy_node_common.ha.config_entries import ConfigEntry, ConfigEntryState # noqa: E402 +from energy_node_common.ha.const import EVENT_CORE_CONFIG_UPDATE # noqa: E402 +from energy_node_common.ha.core import HomeAssistant # noqa: E402 +from energy_node_common.ha.helpers import entity_registry as er # noqa: E402 +from energy_node_common.ha.helpers.debounce import Debouncer # noqa: E402 +from energy_node_common.ha.runtime import run_integration # noqa: E402 + + +def test_entry_state_defaults_to_not_loaded(): + entry = ConfigEntry(entry_id="e", domain="d", title="t", data={}) + assert entry.state is ConfigEntryState.NOT_LOADED + + +def test_bus_listen_filter_and_remove(): + async def main(): + hass = HomeAssistant(loop=asyncio.get_running_loop()) + seen = [] + remove = hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, seen.append, + event_filter=lambda data: data.get("ok")) + hass.bus.async_fire(EVENT_CORE_CONFIG_UPDATE, {"ok": False}) + hass.bus.async_fire(EVENT_CORE_CONFIG_UPDATE, {"ok": True}) + remove() + hass.bus.async_fire(EVENT_CORE_CONFIG_UPDATE, {"ok": True}) + return seen + + seen = asyncio.run(main()) + assert len(seen) == 1 + assert seen[0].data == {"ok": True} + + +def test_entity_registry_finds_nothing(): + assert er.async_get(None).async_get("sensor.x") is None + + +def test_debouncer_immediate_then_once_after_cooldown(): + async def main(): + hass = HomeAssistant(loop=asyncio.get_running_loop()) + calls = [] + + async def func(): + calls.append(1) + + debouncer = Debouncer(hass, logging.getLogger("t"), cooldown=0.05, immediate=True, function=func) + await debouncer.async_call() + await debouncer.async_call() + await debouncer.async_call() + assert calls == [1] + await asyncio.sleep(0.12) + debouncer.async_shutdown() + return calls + + assert asyncio.run(main()) == [1, 1] + + +def test_debouncer_shutdown_drops_pending_call(): + async def main(): + hass = HomeAssistant(loop=asyncio.get_running_loop()) + calls = [] + debouncer = Debouncer(hass, logging.getLogger("t"), cooldown=0.05, immediate=False, + function=lambda: calls.append(1)) + await debouncer.async_call() + debouncer.async_shutdown() + await asyncio.sleep(0.1) + return calls + + assert asyncio.run(main()) == [] + + +def _integration(result, tmp_path): + module = ModuleType("none_port") + module.__file__ = str(tmp_path / "none_port" / "__init__.py") + + async def async_setup_entry(hass, entry): + await hass.config_entries.async_unload_platforms_or_raise(entry, []) + return result + + module.async_setup_entry = async_setup_entry + return module + + +def test_setup_entry_returning_none_counts_as_success(tmp_path): + sys.modules["none_port"] = _integration(None, tmp_path) + ready = asyncio.Event() + + async def main(): + task = asyncio.create_task(run_integration( + "none_port", "none_port", {"id": "n1", "name": "N"}, FakeClient(), "x/n1", ready=ready)) + await asyncio.wait_for(ready.wait(), 2) + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + try: + asyncio.run(main()) + finally: + del sys.modules["none_port"] + assert ready.is_set() From 602bbc5c6b3e67d094b10e81e8d2ab3a5619b3cf Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 6 Dec 2026 00:37:48 +0000 Subject: [PATCH 12/12] docs(changelog): update changelogs --- libs/energy_node_common/CHANGELOG.md | 31 ++++++++++++++-------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/libs/energy_node_common/CHANGELOG.md b/libs/energy_node_common/CHANGELOG.md index 19880d950..225c67bec 100644 --- a/libs/energy_node_common/CHANGELOG.md +++ b/libs/energy_node_common/CHANGELOG.md @@ -4,36 +4,37 @@ ### Features -- **common:** add the base modules of the HA compat layer (c1260f4) -- **common:** add entities, coordinator and timers to the HA compat layer (f9b4f7e) -- **common:** host HA integrations and map entities to MQTT discovery (c4a7204) -- **common:** add the HA port runner and its systemd template (4a9d843) +- **common:** cover the Home Assistant 2026.12 surface of forecast_solar and nordpool (97a3e7a) - **common:** add a Home Assistant compat layer for ported integrations (#319) -### Fixes - -- **common:** keep the coordinator timer alive after config entry errors (88f91d8) -- **common:** harden the HA runner against bad listeners and device files (4985c58) - -### Documentation - -- **common:** describe the HA port contract (fbb2196) -- **common:** align the HA port README with the runner behaviour (a493cd9) - -## v0.6.0 (2026-11-15) +## v0.6.0 (2026-12-06) ### Features +- **common:** add the base modules of the HA compat layer (c1260f4) +- **common:** add entities, coordinator and timers to the HA compat layer (f9b4f7e) +- **common:** host HA integrations and map entities to MQTT discovery (c4a7204) +- **common:** add the HA port runner and its systemd template (4a9d843) - **automation:** react to measurement chains in automations (#226) (0066f15) - **storage:** Add an additional drive for running data and backups (#233) (015cc2c) - **performance:** show how much load the node puts on the device (#260) (b93bc98) - **common:** report the poll round duration in the service status (5a94108) - **performance:** add the poll floor and the budget setting (7f324af) +### Fixes + +- **common:** keep the coordinator timer alive after config entry errors (88f91d8) +- **common:** harden the HA runner against bad listeners and device files (4985c58) + ### Refactors - **common:** keep battery paths out of the common library (0e615bc) +### Documentation + +- **common:** describe the HA port contract (fbb2196) +- **common:** align the HA port README with the runner behaviour (a493cd9) + ## v0.5.1 (2026-11-06) ### Refactors