Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions changelog/highlights/319.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"de": {
"*": "Kompatibilitätsschicht für portierte Home-Assistant-Integrationen"
},
"en": {
"*": "Add a Home Assistant compat layer for ported integrations"
}
}
2 changes: 1 addition & 1 deletion dashboard/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 22 additions & 1 deletion libs/energy_node_common/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@
# Changelog

## v0.6.0 (2026-11-15)
## v0.6.1-pre.1 (2026-12-06)

### Features

- **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)

## 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
Expand Down
2 changes: 1 addition & 1 deletion libs/energy_node_common/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v0.6.0
v0.6.1-pre.1
3 changes: 3 additions & 0 deletions libs/energy_node_common/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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*"]
Expand Down
106 changes: 106 additions & 0 deletions libs/energy_node_common/src/energy_node_common/ha/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# 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 '<name>'`.

Supported surface:

- `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

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_<domain>`, 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/<lang>.json`,
with `strings.json` as the last fallback. Entity names come from
`entity.<platform>.<translation_key>.name`, placeholders included.

The configuration lives in `ha_<domain>_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 `<id>_0`, `<id>_1` and so on.

## Running

The runner starts one integration with all its configured records:

```sh
python3 -m energy_node_common.ha <domain> --config /etc/energy-node/config.json --language de
```

The systemd template `energy-node-ha@.service` runs it as
`energy-node-ha@<domain>.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, or with a devices file it cannot read, it exits with code 2.

## Topics

For a record with ID `<id>`, the base topic is `ha_<domain>/<id>`.

- Discovery: `homeassistant/<component>/<device_id>/<object_id>/config`
- `device_id` is the slugified `<identifier domain>_<identifier>` from the first
sorted `identifiers` entry of the entity's device info, otherwise the record ID
- `object_id` is the slugified `unique_id`
- State: `<base>/<object_id>`, attributes as JSON on `<base>/<object_id>/attributes`
- Availability: `<base>/status/online` plus one availability discovery per device
- Service status: `outstation/ha_<domain>/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.
11 changes: 11 additions & 0 deletions libs/energy_node_common/src/energy_node_common/ha/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
"""
143 changes: 143 additions & 0 deletions libs/energy_node_common/src/energy_node_common/ha/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Runs one ported HA integration as an energy-node service.

Usage: ``python3 -m energy_node_common.ha <domain> [--config PATH] [--language de]``

The devices file ``<devices_dir>/ha_<domain>_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:
"""Return the device records; raise ValueError naming the problem."""
if not path.exists():
return []
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:
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)
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

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())
Empty file.
Original file line number Diff line number Diff line change
@@ -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")
Loading
Loading