From d5fbcacaa40be5c1b924e3e44a98232d50222674 Mon Sep 17 00:00:00 2001 From: "Setti Solutions S.R.L" Date: Fri, 30 Oct 2026 08:26:45 +0200 Subject: [PATCH] cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source --- .dockerignore | 6 + .gitignore | 5 + NOTICE | 9 + README.md | 83 ++ THIRD-PARTY-NOTICES.md | 1541 +++++++++++++++++++++ cantabile_edge/CHANGELOG.md | 27 + cantabile_edge/Dockerfile | 28 +- cantabile_edge/addon-run | 4 +- cantabile_edge/config.yaml | 8 +- cantabile_edge/platform/.gitignore | 5 + cantabile_edge/platform/README.md | 25 + cantabile_eebus/CHANGELOG.md | 27 + cantabile_eebus/DOCS.md | 81 ++ cantabile_eebus/Dockerfile | 23 + cantabile_eebus/config.yaml | 41 + cantabile_eebus/icon.png | Bin 0 -> 12462 bytes cantabile_eebus/logo.png | Bin 0 -> 15401 bytes cantabile_eebus/translations/de.yaml | 34 + cantabile_eebus/translations/en.yaml | 33 + cantabile_modbus/DOCS.md | 51 + cantabile_modbus/Dockerfile | 16 + cantabile_modbus/config.yaml | 44 + cantabile_modbus/ha_source.py | 138 ++ cantabile_modbus/icon.png | Bin 0 -> 12462 bytes cantabile_modbus/logo.png | Bin 0 -> 15401 bytes cantabile_modbus/page.py | 438 ++++++ cantabile_modbus/run.py | 274 ++++ cantabile_modbus/sim.py | 125 ++ cantabile_modbus/translations/de.yaml | 16 + cantabile_modbus/translations/en.yaml | 16 + src/edge/Dockerfile | 33 + src/edge/cantabile_edge/__init__.py | 5 + src/edge/cantabile_edge/__main__.py | 4 + src/edge/cantabile_edge/agent.py | 343 +++++ src/edge/cantabile_edge/announce.py | 441 ++++++ src/edge/cantabile_edge/areas.py | 75 + src/edge/cantabile_edge/backfill.py | 64 + src/edge/cantabile_edge/building.py | 151 ++ src/edge/cantabile_edge/bundles.py | 209 +++ src/edge/cantabile_edge/cli.py | 95 ++ src/edge/cantabile_edge/config.py | 105 ++ src/edge/cantabile_edge/consent.py | 64 + src/edge/cantabile_edge/controller.py | 589 ++++++++ src/edge/cantabile_edge/controls.py | 272 ++++ src/edge/cantabile_edge/dashboards.py | 1004 ++++++++++++++ src/edge/cantabile_edge/devpage.py | 776 +++++++++++ src/edge/cantabile_edge/devprofiles.py | 697 ++++++++++ src/edge/cantabile_edge/devview.py | 321 +++++ src/edge/cantabile_edge/executor.py | 296 ++++ src/edge/cantabile_edge/gridorder.py | 231 +++ src/edge/cantabile_edge/guard.py | 202 +++ src/edge/cantabile_edge/ha.py | 216 +++ src/edge/cantabile_edge/i18n.py | 116 ++ src/edge/cantabile_edge/i18n_de.py | 350 +++++ src/edge/cantabile_edge/inputs.py | 309 +++++ src/edge/cantabile_edge/inventory.py | 166 +++ src/edge/cantabile_edge/joinpage.py | 603 ++++++++ src/edge/cantabile_edge/limits.py | 82 ++ src/edge/cantabile_edge/mapping.py | 336 +++++ src/edge/cantabile_edge/mqtt.py | 128 ++ src/edge/cantabile_edge/names.py | 142 ++ src/edge/cantabile_edge/optimizer.py | 490 +++++++ src/edge/cantabile_edge/policy.py | 122 ++ src/edge/cantabile_edge/propose.py | 491 +++++++ src/edge/cantabile_edge/shades.py | 250 ++++ src/edge/cantabile_edge/sinks.py | 263 ++++ src/edge/cantabile_edge/store.py | 54 + src/edge/cantabile_edge/switchover.py | 132 ++ src/edge/cantabile_edge/telemetry.py | 95 ++ src/edge/link/bundles.go | 114 ++ src/edge/link/bundles_test.go | 149 ++ src/edge/link/endpoints.go | 272 ++++ src/edge/link/endpoints_test.go | 288 ++++ src/edge/link/fingerprint.go | 203 +++ src/edge/link/fingerprint_test.go | 161 +++ src/edge/link/go.mod | 18 + src/edge/link/go.sum | 14 + src/edge/link/gridorder.go | 154 ++ src/edge/link/gridorder_test.go | 93 ++ src/edge/link/hub.go | 551 ++++++++ src/edge/link/hub_setup_test.go | 25 + src/edge/link/hubcmd.go | 160 +++ src/edge/link/hwreason.go | 246 ++++ src/edge/link/hwreason_test.go | 128 ++ src/edge/link/hwresolve.go | 179 +++ src/edge/link/hwresolve_test.go | 56 + src/edge/link/local.go | 235 ++++ src/edge/link/main.go | 959 +++++++++++++ src/edge/link/main_test.go | 255 ++++ src/edge/link/panel.go | 279 ++++ src/edge/link/panel_test.go | 61 + src/edge/link/reinstall.go | 119 ++ src/edge/link/serial.go | 49 + src/edge/link/serial_test.go | 79 ++ src/edge/link/sign_test.go | 31 + src/edge/link/terminal.go | 272 ++++ src/edge/link/terminal_test.go | 82 ++ src/edge/pyproject.toml | 31 + src/edge/run.sh | 41 + src/edge/tests/test_agent.py | 199 +++ src/edge/tests/test_announce.py | 191 +++ src/edge/tests/test_areas.py | 56 + src/edge/tests/test_building.py | 116 ++ src/edge/tests/test_consent.py | 56 + src/edge/tests/test_control_parts.py | 362 +++++ src/edge/tests/test_dashboard_homes.py | 505 +++++++ src/edge/tests/test_dashboards.py | 280 ++++ src/edge/tests/test_devpage.py | 301 ++++ src/edge/tests/test_devprofiles.py | 144 ++ src/edge/tests/test_flats_bundle.py | 45 + src/edge/tests/test_gridorder.py | 183 +++ src/edge/tests/test_integration_ha.py | 87 ++ src/edge/tests/test_joinpage.py | 205 +++ src/edge/tests/test_joinpage_i18n.py | 118 ++ src/edge/tests/test_link_sink.py | 80 ++ src/edge/tests/test_mapping.py | 140 ++ src/edge/tests/test_optimizer.py | 114 ++ src/edge/tests/test_policy.py | 155 +++ src/edge/tests/test_propose.py | 220 +++ src/edge/tests/test_shades.py | 441 ++++++ src/edge/tests/test_store.py | 32 + src/edge/tests/test_switchover.py | 162 +++ src/edge/tests/test_telemetry.py | 73 + src/edge/tests/test_thermostat.py | 161 +++ src/eebus-bridge/THIRD-PARTY-NOTICES.md | 990 +++++++++++++ src/eebus-bridge/consent.go | 52 + src/eebus-bridge/core.go | 937 +++++++++++++ src/eebus-bridge/core_test.go | 449 ++++++ src/eebus-bridge/discovery.go | 234 ++++ src/eebus-bridge/eebus.go | 570 ++++++++ src/eebus-bridge/eebus_test.go | 320 +++++ src/eebus-bridge/go.mod | 35 + src/eebus-bridge/go.sum | 58 + src/eebus-bridge/grid.go | 332 +++++ src/eebus-bridge/main.go | 239 ++++ src/eebus-bridge/model.go | 273 ++++ src/eebus-bridge/notices.sh | 30 + src/eebus-bridge/order.go | 87 ++ src/eebus-bridge/page.go | 435 ++++++ src/eebus-bridge/page_test.go | 94 ++ src/eebus-bridge/profiles.go | 120 ++ src/eebus-bridge/profiles_test.go | 72 + src/eebus-bridge/protect.go | 86 ++ src/eebus-bridge/sim.go | 240 ++++ src/eebus-bridge/sim_test.go | 62 + src/eebus-bridge/store.go | 112 ++ src/modbus-bridge/bridge.py | 371 +++++ src/modbus-bridge/cantabile_modbus.py | 220 +++ src/profiles/README.md | 145 ++ src/profiles/eebus-bosch-compress.json | 89 ++ src/profiles/eebus-control-box.json | 93 ++ src/profiles/eebus-heatpump.json | 82 ++ src/profiles/eebus-inverter.json | 78 ++ src/profiles/eebus-vaillant-arotherm.json | 90 ++ src/profiles/eebus-viessmann-vitocal.json | 87 ++ src/profiles/eebus-wallbox.json | 116 ++ src/profiles/fronius-gen24.json | 38 + src/profiles/go-e-charger.json | 33 + src/profiles/ha-climate-sensor.json | 37 + src/profiles/ha-cover.json | 33 + src/profiles/ha-thermostat.json | 44 + src/profiles/ha-weather.json | 25 + src/profiles/hm8042-hybrid.json | 439 ++++++ src/profiles/huawei-sun2000.json | 66 + src/profiles/shelly-pro-3em.json | 32 + src/profiles/sma-sunny-boy.json | 50 + src/profiles/solaredge-sunspec.json | 43 + src/profiles/sonoff-snzb-02.json | 23 + src/profiles/sonoff-spm.json | 101 ++ src/profiles/vaillant-mypyllant.json | 36 + src/profiles/victron-gx.json | 37 + src/profiles/viessmann-vicare.json | 40 + src/profiles/waveshare-relay-30ch.json | 459 ++++++ tests/test_addon.py | 249 ++++ tests/test_eebus.py | 90 ++ tests/test_modbus.py | 307 ++++ 176 files changed, 32511 insertions(+), 19 deletions(-) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 NOTICE create mode 100644 README.md create mode 100644 THIRD-PARTY-NOTICES.md create mode 100644 cantabile_edge/platform/.gitignore create mode 100644 cantabile_edge/platform/README.md create mode 100644 cantabile_eebus/CHANGELOG.md create mode 100644 cantabile_eebus/DOCS.md create mode 100644 cantabile_eebus/Dockerfile create mode 100644 cantabile_eebus/config.yaml create mode 100644 cantabile_eebus/icon.png create mode 100644 cantabile_eebus/logo.png create mode 100644 cantabile_eebus/translations/de.yaml create mode 100644 cantabile_eebus/translations/en.yaml create mode 100644 cantabile_modbus/DOCS.md create mode 100644 cantabile_modbus/Dockerfile create mode 100644 cantabile_modbus/config.yaml create mode 100644 cantabile_modbus/ha_source.py create mode 100644 cantabile_modbus/icon.png create mode 100644 cantabile_modbus/logo.png create mode 100644 cantabile_modbus/page.py create mode 100644 cantabile_modbus/run.py create mode 100644 cantabile_modbus/sim.py create mode 100644 cantabile_modbus/translations/de.yaml create mode 100644 cantabile_modbus/translations/en.yaml create mode 100644 src/edge/Dockerfile create mode 100644 src/edge/cantabile_edge/__init__.py create mode 100644 src/edge/cantabile_edge/__main__.py create mode 100644 src/edge/cantabile_edge/agent.py create mode 100644 src/edge/cantabile_edge/announce.py create mode 100644 src/edge/cantabile_edge/areas.py create mode 100644 src/edge/cantabile_edge/backfill.py create mode 100644 src/edge/cantabile_edge/building.py create mode 100644 src/edge/cantabile_edge/bundles.py create mode 100644 src/edge/cantabile_edge/cli.py create mode 100644 src/edge/cantabile_edge/config.py create mode 100644 src/edge/cantabile_edge/consent.py create mode 100644 src/edge/cantabile_edge/controller.py create mode 100644 src/edge/cantabile_edge/controls.py create mode 100644 src/edge/cantabile_edge/dashboards.py create mode 100644 src/edge/cantabile_edge/devpage.py create mode 100644 src/edge/cantabile_edge/devprofiles.py create mode 100644 src/edge/cantabile_edge/devview.py create mode 100644 src/edge/cantabile_edge/executor.py create mode 100644 src/edge/cantabile_edge/gridorder.py create mode 100644 src/edge/cantabile_edge/guard.py create mode 100644 src/edge/cantabile_edge/ha.py create mode 100644 src/edge/cantabile_edge/i18n.py create mode 100644 src/edge/cantabile_edge/i18n_de.py create mode 100644 src/edge/cantabile_edge/inputs.py create mode 100644 src/edge/cantabile_edge/inventory.py create mode 100644 src/edge/cantabile_edge/joinpage.py create mode 100644 src/edge/cantabile_edge/limits.py create mode 100644 src/edge/cantabile_edge/mapping.py create mode 100644 src/edge/cantabile_edge/mqtt.py create mode 100644 src/edge/cantabile_edge/names.py create mode 100644 src/edge/cantabile_edge/optimizer.py create mode 100644 src/edge/cantabile_edge/policy.py create mode 100644 src/edge/cantabile_edge/propose.py create mode 100644 src/edge/cantabile_edge/shades.py create mode 100644 src/edge/cantabile_edge/sinks.py create mode 100644 src/edge/cantabile_edge/store.py create mode 100644 src/edge/cantabile_edge/switchover.py create mode 100644 src/edge/cantabile_edge/telemetry.py create mode 100644 src/edge/link/bundles.go create mode 100644 src/edge/link/bundles_test.go create mode 100644 src/edge/link/endpoints.go create mode 100644 src/edge/link/endpoints_test.go create mode 100644 src/edge/link/fingerprint.go create mode 100644 src/edge/link/fingerprint_test.go create mode 100644 src/edge/link/go.mod create mode 100644 src/edge/link/go.sum create mode 100644 src/edge/link/gridorder.go create mode 100644 src/edge/link/gridorder_test.go create mode 100644 src/edge/link/hub.go create mode 100644 src/edge/link/hub_setup_test.go create mode 100644 src/edge/link/hubcmd.go create mode 100644 src/edge/link/hwreason.go create mode 100644 src/edge/link/hwreason_test.go create mode 100644 src/edge/link/hwresolve.go create mode 100644 src/edge/link/hwresolve_test.go create mode 100644 src/edge/link/local.go create mode 100644 src/edge/link/main.go create mode 100644 src/edge/link/main_test.go create mode 100644 src/edge/link/panel.go create mode 100644 src/edge/link/panel_test.go create mode 100644 src/edge/link/reinstall.go create mode 100644 src/edge/link/serial.go create mode 100644 src/edge/link/serial_test.go create mode 100644 src/edge/link/sign_test.go create mode 100644 src/edge/link/terminal.go create mode 100644 src/edge/link/terminal_test.go create mode 100644 src/edge/pyproject.toml create mode 100755 src/edge/run.sh create mode 100644 src/edge/tests/test_agent.py create mode 100644 src/edge/tests/test_announce.py create mode 100644 src/edge/tests/test_areas.py create mode 100644 src/edge/tests/test_building.py create mode 100644 src/edge/tests/test_consent.py create mode 100644 src/edge/tests/test_control_parts.py create mode 100644 src/edge/tests/test_dashboard_homes.py create mode 100644 src/edge/tests/test_dashboards.py create mode 100644 src/edge/tests/test_devpage.py create mode 100644 src/edge/tests/test_devprofiles.py create mode 100644 src/edge/tests/test_flats_bundle.py create mode 100644 src/edge/tests/test_gridorder.py create mode 100644 src/edge/tests/test_integration_ha.py create mode 100644 src/edge/tests/test_joinpage.py create mode 100644 src/edge/tests/test_joinpage_i18n.py create mode 100644 src/edge/tests/test_link_sink.py create mode 100644 src/edge/tests/test_mapping.py create mode 100644 src/edge/tests/test_optimizer.py create mode 100644 src/edge/tests/test_policy.py create mode 100644 src/edge/tests/test_propose.py create mode 100644 src/edge/tests/test_shades.py create mode 100644 src/edge/tests/test_store.py create mode 100644 src/edge/tests/test_switchover.py create mode 100644 src/edge/tests/test_telemetry.py create mode 100644 src/edge/tests/test_thermostat.py create mode 100644 src/eebus-bridge/THIRD-PARTY-NOTICES.md create mode 100644 src/eebus-bridge/consent.go create mode 100644 src/eebus-bridge/core.go create mode 100644 src/eebus-bridge/core_test.go create mode 100644 src/eebus-bridge/discovery.go create mode 100644 src/eebus-bridge/eebus.go create mode 100644 src/eebus-bridge/eebus_test.go create mode 100644 src/eebus-bridge/go.mod create mode 100644 src/eebus-bridge/go.sum create mode 100644 src/eebus-bridge/grid.go create mode 100644 src/eebus-bridge/main.go create mode 100644 src/eebus-bridge/model.go create mode 100755 src/eebus-bridge/notices.sh create mode 100644 src/eebus-bridge/order.go create mode 100644 src/eebus-bridge/page.go create mode 100644 src/eebus-bridge/page_test.go create mode 100644 src/eebus-bridge/profiles.go create mode 100644 src/eebus-bridge/profiles_test.go create mode 100644 src/eebus-bridge/protect.go create mode 100644 src/eebus-bridge/sim.go create mode 100644 src/eebus-bridge/sim_test.go create mode 100644 src/eebus-bridge/store.go create mode 100644 src/modbus-bridge/bridge.py create mode 100644 src/modbus-bridge/cantabile_modbus.py create mode 100644 src/profiles/README.md create mode 100644 src/profiles/eebus-bosch-compress.json create mode 100644 src/profiles/eebus-control-box.json create mode 100644 src/profiles/eebus-heatpump.json create mode 100644 src/profiles/eebus-inverter.json create mode 100644 src/profiles/eebus-vaillant-arotherm.json create mode 100644 src/profiles/eebus-viessmann-vitocal.json create mode 100644 src/profiles/eebus-wallbox.json create mode 100644 src/profiles/fronius-gen24.json create mode 100644 src/profiles/go-e-charger.json create mode 100644 src/profiles/ha-climate-sensor.json create mode 100644 src/profiles/ha-cover.json create mode 100644 src/profiles/ha-thermostat.json create mode 100644 src/profiles/ha-weather.json create mode 100644 src/profiles/hm8042-hybrid.json create mode 100644 src/profiles/huawei-sun2000.json create mode 100644 src/profiles/shelly-pro-3em.json create mode 100644 src/profiles/sma-sunny-boy.json create mode 100644 src/profiles/solaredge-sunspec.json create mode 100644 src/profiles/sonoff-snzb-02.json create mode 100644 src/profiles/sonoff-spm.json create mode 100644 src/profiles/vaillant-mypyllant.json create mode 100644 src/profiles/victron-gx.json create mode 100644 src/profiles/viessmann-vicare.json create mode 100644 src/profiles/waveshare-relay-30ch.json create mode 100644 tests/test_addon.py create mode 100644 tests/test_eebus.py create mode 100644 tests/test_modbus.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..19095b7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +**/__pycache__ +**/*.pyc +**/.pytest_cache +cantabile_edge/platform/README.md +cantabile_edge/platform/.gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c7f94c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +__pycache__/ +*.pyc +.pytest_cache/ +*.egg-info/ diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..01a750d --- /dev/null +++ b/NOTICE @@ -0,0 +1,9 @@ +Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. + +Setti Solutions S.R.L, www.setti.md, info@setti.solutions + +This notice applies to every file in this repository that is not a +third-party component, including files that cannot carry a comment of their +own (the device profiles in src/profiles/*.json, go.sum, the icons). The +terms are in LICENSE; third-party components and their licences are listed +in THIRD-PARTY-NOTICES.md. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1b86262 --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +# Cantabile add-ons for Home Assistant + +Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. This notice covers every file in this +repository, including those that cannot carry a comment (the device +profiles' JSON, `go.sum`, images): see `LICENSE` and `NOTICE`. + +Cantabile plans a home's energy (solar, battery, heating, charging) and, +with the owner's consent, runs the devices the owner chooses. These add-ons +bring it to any Home Assistant (HA OS or Supervised). + +| Add-on | What it does | +|---|---| +| `cantabile_edge`: **Cantabile Edge Agent** | Connects this Home Assistant to Cantabile: reads the devices the owner chose (only with the owner's consent), plans, and with consent to control runs them through Home Assistant. Python agent and a Go link (the site's key and its connection to the platform). | +| `cantabile_modbus`: **Cantabile Modbus bridge** | Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus TCP, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection. | +| `cantabile_eebus`: **Cantabile EEBUS** | Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant and hands the grid operator's §14a limit to the agent. Go, on enbility's eebus-go. | + +Each add-on's `DOCS.md` is what the owner reads in Home Assistant. + +## Install + +Settings → Add-ons → Add-on store → ⋮ → Repositories, add +`https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the +add-on. The Supervisor pulls the prebuilt images +(`git.setti.solutions/daniel/cantabile-ha--:`, +named by `image:` in each `config.yaml`); this version: `0.1.400`, arch amd64. + +## Layout + +| Path | What | +|---|---| +| `repository.yaml` | The add-on repository (HA reads it here). | +| `cantabile_edge/`, `cantabile_modbus/`, `cantabile_eebus/` | The add-ons: manifest (`config.yaml`), `Dockerfile`, start scripts, owner's documentation, translations, icons. | +| `src/edge/` | The Edge Agent image: `cantabile_edge/` (Python), `link/` (Go: `cantabile-link`), `run.sh`, `Dockerfile`, `tests/`. | +| `src/modbus-bridge/` | The Modbus bridge (`bridge.py`) and its Modbus TCP code (`cantabile_modbus.py`). | +| `src/eebus-bridge/` | The EEBUS bridge (Go) and its third-party notices. | +| `src/profiles/` | Cantabile's device profiles (JSON; `README.md` describes the format). | +| `tests/` | The add-ons' tests (manifests, `addon-run`, the Modbus add-on, the EEBUS add-on). | + +## Build the images + +From the repository's root, with Docker (BuildKit). `VERSION` is the +add-on's version (`config.yaml`); `ARCH` is HA's arch name (`amd64`, +`aarch64`; add `--platform linux/arm64` for aarch64). + +``` +# Cantabile Edge Agent: the agent image first, then the add-on on top. +# The platform's files go to cantabile_edge/platform/ first (README.md there). +docker build -t cantabile-edge:local --build-arg VERSION=$VERSION src/edge +docker build -f cantabile_edge/Dockerfile --build-arg EDGE_IMAGE=cantabile-edge:local \ + --build-arg VERSION=$VERSION -t cantabile-ha-edge-amd64:$VERSION . + +# Cantabile Modbus bridge +docker build -f cantabile_modbus/Dockerfile --build-arg VERSION=$VERSION -t cantabile-ha-modbus-amd64:$VERSION . + +# Cantabile EEBUS +docker build -f cantabile_eebus/Dockerfile --build-arg VERSION=$VERSION -t cantabile-ha-eebus-amd64:$VERSION . +``` + +To run an image you built instead of the published one, push it to a +registry you control and point `image:` in the add-on's `config.yaml` at it, +in a fork of this repository. (The Supervisor's own local build uses an +add-on's folder alone as build context; these images need `src/`, so they +are built as above.) + +## Tests + +``` +# the add-ons (Python 3.12+, pytest, PyYAML, paho-mqtt, websocket-client) +python -m pytest tests +# the Edge Agent (from src/edge: pip install '.[test]') +cd src/edge && python -m pytest tests +# the link and the EEBUS bridge (Go 1.26) +(cd src/edge/link && go test ./...) && (cd src/eebus-bridge && go test ./...) +``` + +## Licence + +Proprietary: see `LICENSE`. Third-party components and their licences: +`THIRD-PARTY-NOTICES.md`. + +--- + +Copyright © 2026 Setti Solutions S.R.L, www.setti.md, [www.setti.md](https://www.setti.md). All rights reserved. diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..705a758 --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,1541 @@ +# Third-party notices + +Copyright © 2026 Setti Solutions S.R.L, www.setti.md. Cantabile's add-ons use the open-source components below. Their +licences permit use and redistribution with these notices. + +## Summary + +| Component | Used by | Licence | +|---|---|---| +| Go modules of the EEBUS bridge (enbility's eebus-go, ship-go, spine-go and their dependencies) | `cantabile_eebus` | MIT, BSD, Apache-2.0, EPL-2.0/EDL-1.0: `src/eebus-bridge/THIRD-PARTY-NOTICES.md` | +| Go modules of the link (nats.go, nkeys, x/crypto, x/sys, pty, compress, nuid) | `cantabile_edge` | Apache-2.0, BSD-3-Clause, MIT: below | +| websockets, nats-py, PyYAML, highspy (HiGHS) | `cantabile_edge` | BSD-3-Clause, Apache-2.0, MIT, MIT: below | +| paho-mqtt, websocket-client | `cantabile_modbus` | EPL-2.0 or EDL-1.0 (used under EDL-1.0), Apache-2.0: below | +| Base images: `python:3.12.12-slim-bookworm` (Debian 12), `python:3.13-alpine`, `alpine:3.22`, `golang:1.26.9-bookworm` (build only) | all | Their own licences (Python: PSF-2.0; Go: BSD-3-Clause; Debian and Alpine packages: each package's licence, in the image under /usr/share/doc and /lib/apk) | + +## Go modules of the link (src/edge/link) + +### github.com/creack/pty v1.1.24 + +``` +Copyright (c) 2011 Keith Rarick + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall +be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +### github.com/klauspost/compress v1.20.0 + +``` +Copyright (c) 2012 The Go Authors. All rights reserved. +Copyright (c) 2019 Klaus Post. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------ + +Files: gzhttp/* + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016-2017 The New York Times Company + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------ + +Files: s2/cmd/internal/readahead/* + +The MIT License (MIT) + +Copyright (c) 2015 Klaus Post + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------- +Files: snappy/* +Files: internal/snapref/* + +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----------------- + +Files: s2/cmd/internal/filepathx/* + +Copyright 2016 The filepathx Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +### github.com/nats-io/nats.go v1.54.0 + +``` + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### github.com/nats-io/nkeys v0.4.16 + +``` + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### github.com/nats-io/nuid v1.0.1 + +``` + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### golang.org/x/crypto v0.58.0 + +``` +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +### golang.org/x/sys v0.49.0 + +``` +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + + +## Python packages (src/edge, cantabile_modbus) + +### websockets 15.0.1 (BSD-3-Clause) + +``` +Copyright (c) Aymeric Augustin and contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +### nats_py 2.10.0 (Apache 2 License) + +``` + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### PyYAML 6.0.2 (MIT) + +``` +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### highspy 1.11.0 + +``` +MIT License + +Copyright (c) 2024 HiGHS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### paho_mqtt 2.1.0 (EPL-2.0 OR BSD-3-Clause) + +``` +This project is dual licensed under the Eclipse Public License 2.0 and the +Eclipse Distribution License 1.0 as described in the epl-v20 and edl-v10 files. + +``` + +### websocket_client 1.8.0 (Apache-2.0) + +``` + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 engn33r + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +``` + diff --git a/cantabile_edge/CHANGELOG.md b/cantabile_edge/CHANGELOG.md index 1024c41..6483093 100644 --- a/cantabile_edge/CHANGELOG.md +++ b/cantabile_edge/CHANGELOG.md @@ -6,6 +6,33 @@ names the commit; the agent inside is the Edge Agent image of that commit. ## 0.1.x +- Blinds, curtains, shutters and awnings: the Devices page offers any of + Home Assistant's covers (never a garage door, gate, door, damper or + window). You set the room it shades and which way the window faces. + Cantabile then moves it by the sun: in summer it closes it (partly, while + someone is home) when the sun is on that window and the room is warm or + dear hours are coming, and opens it again when the sun has gone; in + winter it opens it for the sun's warmth and closes it in the evening to + keep the warmth in, never opening it in the dark. It never moves between + 22:00 and 07:00, at most once in 30 minutes, and after you move it by + hand it waits 4 hours. A new shade is protected: Cantabile does not move + it until you allow that on the Devices page (and only with your consent + to control, in auto mode). On the dashboard it is a tile with its + position slider (open and close for one without positions), and "Coming + up" says what is next in words ("Bedroom curtains: close to 30 % at + 14:00, sun on the west facade"). +- Temperature and humidity sensors: any such sensor (ESPHome, Zigbee, + Bluetooth) that has no profile of its own is offered, never Home + Assistant's or a device's own system temperatures. You choose indoor + (which room; a room that has a temperature already gets a second one) or + outdoor: then it is Cantabile's outside temperature, before the weather + service's. On the dashboard each is a small card with its temperature and + humidity. +- Weather: a weather service (met.no, OpenWeatherMap and others) is offered + as "Weather (forecast)": its hourly forecast plans solar, heating, + cooling and the shades, its temperature and humidity are the outside's + where no outdoor sensor measures them. With several, you choose the one + Cantabile plans with. - Your consent at installation, in the add-on's configuration: sharing energy data with Cantabile (needed: without it the add-on does not connect, and its page says why) and, separately, control. The same texts diff --git a/cantabile_edge/Dockerfile b/cantabile_edge/Dockerfile index d87bf8c..87408f1 100644 --- a/cantabile_edge/Dockerfile +++ b/cantabile_edge/Dockerfile @@ -1,20 +1,22 @@ # Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. -# The add-on's image: the Edge Agent image of the same commit (edge/build.sh) -# with addon-run in front, and the platform it belongs to (the devices URL, -# the command and bundle certificates), as a Hub build bakes them in. -# Built by ha-addon/build.sh, one image per arch; the Supervisor pulls it. -ARG EDGE_IMAGE +# The add-on's image: the Edge Agent image (src/edge) with addon-run in +# front, Cantabile's device profiles (src/profiles; the agent proposes a +# mapping from them, propose.py), and the platform it belongs to: the devices +# URL and the command and bundle certificates (cantabile_edge/platform/, +# README.md there). Built from the repository's root: +# docker build -t cantabile-edge:local src/edge +# docker build -f cantabile_edge/Dockerfile --build-arg EDGE_IMAGE=cantabile-edge:local \ +# --build-arg VERSION= -t cantabile-ha-edge-amd64: . +ARG EDGE_IMAGE=cantabile-edge:local FROM ${EDGE_IMAGE} -ARG VERSION ARCH REVISION +ARG VERSION ARCH=amd64 REVISION LABEL io.hass.version="${VERSION}" io.hass.type="addon" io.hass.arch="${ARCH}" \ org.opencontainers.image.revision="${REVISION}" -# bundles.pem is optional (no bundle key: the agent plans with its flat price); -# devices-ca.pem too (the direct path, docs/direct-link.md). -COPY addon.env commands.pem bundles.pem* devices-ca.pem* /etc/cantabile/ -COPY addon-run /usr/local/bin/addon-run -# Cantabile's device profiles (hub/profiles, copied in by build.sh): the -# agent proposes a mapping from them (propose.py). -COPY profiles/ /usr/share/cantabile/profiles/ +# addon.env and commands.pem are needed at run time; bundles.pem and +# devices-ca.pem are optional. +COPY cantabile_edge/platform/ /etc/cantabile/ +COPY cantabile_edge/addon-run /usr/local/bin/addon-run +COPY src/profiles/*.json /usr/share/cantabile/profiles/ # addon-run starts as root (it reads Home Assistant's instance id) and runs # the agent as uid 10001. USER root diff --git a/cantabile_edge/addon-run b/cantabile_edge/addon-run index 48506c6..2a65fbb 100755 --- a/cantabile_edge/addon-run +++ b/cantabile_edge/addon-run @@ -3,10 +3,10 @@ """The Edge Agent's start as a Home Assistant add-on (runs as root). - Home Assistant's instance id: .storage/core.uuid is root-only; a copy in - /data for the link (the site id comes from it, as on the Hub and THR-Home). + /data for the link (the site id comes from it, as on the Hub). - The add-on's options (/data/options.json): the owner's consent, mode, claim code, dashboards. -- Consent (HANDOVER 0, the owner's decision of 2026-10-30): given when the +- Consent (the owner's decision of 2026-10-30): given when the add-on is installed from Cantabile's repository, in its configuration: sharing the energy data of the devices chosen for Cantabile (needed: until it is given the add-on does not enrol or connect, and its page says why) diff --git a/cantabile_edge/config.yaml b/cantabile_edge/config.yaml index bc21f5d..8f583b9 100644 --- a/cantabile_edge/config.yaml +++ b/cantabile_edge/config.yaml @@ -1,9 +1,9 @@ # Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. -# The Edge Agent as a Home Assistant add-on (HANDOVER 3e): the same image as -# the Hub's, wrapped by addon-run (Dockerfile). ha-addon/build.sh sets -# version and arch for each build; the image is prebuilt, per arch. +# The Edge Agent as a Home Assistant add-on: the same image as +# the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt, +# per arch (README.md: building it from src/). name: Cantabile Edge Agent -version: "0.1.389" +version: "0.1.400" slug: cantabile_edge description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose. url: https://cantabile.cloud diff --git a/cantabile_edge/platform/.gitignore b/cantabile_edge/platform/.gitignore new file mode 100644 index 0000000..c6a3c74 --- /dev/null +++ b/cantabile_edge/platform/.gitignore @@ -0,0 +1,5 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +# The platform's files are put here for a build, never committed. +* +!.gitignore +!README.md diff --git a/cantabile_edge/platform/README.md b/cantabile_edge/platform/README.md new file mode 100644 index 0000000..1f200e6 --- /dev/null +++ b/cantabile_edge/platform/README.md @@ -0,0 +1,25 @@ +# The platform files + +The Edge Agent add-on belongs to one Cantabile platform. Its image carries +these files in `/etc/cantabile/`; they are not part of this repository. +Put them here before building `cantabile_edge/Dockerfile`: + +| File | What | +|---|---| +| `addon.env` | `CANTABILE_DEVICES_URL=`, one `KEY=value` per line (optionally `CANTABILE_DEVICES_DIRECT`, `CANTABILE_DEVICES_SPKI`). | +| `commands.pem` | The certificate of the platform's command key: the link accepts only commands signed with it. | +| `bundles.pem` | Optional: the certificate of the platform's bundle key (tariffs, models). | +| `devices-ca.pem` | Optional: the CA of the direct path to the device API. | + +These are public certificates, not secrets. To rebuild the published image +for the same platform, take them from it: + +``` +docker create --name ce git.setti.solutions/daniel/cantabile-ha-edge-amd64: +docker cp ce:/etc/cantabile/. cantabile_edge/platform/ +docker rm ce +``` + +--- + +Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. diff --git a/cantabile_eebus/CHANGELOG.md b/cantabile_eebus/CHANGELOG.md new file mode 100644 index 0000000..66aa6be --- /dev/null +++ b/cantabile_eebus/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +## 0.1.x + +- First version (experimental, not yet tried with real devices): pairs + with EEBUS devices on your network on the add-on's page, after you + compare their SKI: the grid operator's control box (§14a), heat pumps + (Vaillant aroTHERM, Viessmann Vitocal, Bosch Compress and others), + wallboxes and inverters. +- Shows each paired device in Home Assistant in the area "Cantabile": + power and energy (kWh), the heat pump's power limit, the wallbox's car, + charging power, energy and current limit, an inverter's solar and + battery, the grid connection point. +- The grid operator's limit: shown on the page, passed on to the heat + pumps and wallboxes at once and handed to the Cantabile agent, which + plans within it. It can't be lifted from Home Assistant. +- Every control starts protected: Cantabile never sets a heat pump to + 0 W or a wallbox to 0 A unless you lift that on the page. +- Your consent to control in the add-on's configuration; without it the + add-on only reads. +- A simulator (option "Simulate") with a control box, a heat pump and a + wallbox to try it without devices. +- The page in English or German, light or dark as Home Assistant. + +--- + +© 2026 Setti Solutions S.R.L, [www.setti.md](https://www.setti.md). All rights reserved. diff --git a/cantabile_eebus/DOCS.md b/cantabile_eebus/DOCS.md new file mode 100644 index 0000000..d245507 --- /dev/null +++ b/cantabile_eebus/DOCS.md @@ -0,0 +1,81 @@ +# Cantabile EEBUS + +The add-on speaks EEBUS with the devices in your home: the grid +operator's control box (§14a EnWG), heat pumps (Vaillant, Viessmann, +Bosch and others), wallboxes and inverters. It shows them in Home +Assistant under Cantabile's names and units, so the Cantabile agent maps +them exactly, and it hands the grid operator's limit to the agent. + +## Your consent + +In the add-on's configuration, **Cantabile may control devices** is your +consent (the same text as Cantabile's other add-ons and the Cantabile +Hub's setup). Without it the add-on pairs and reads your devices, shows +them in Home Assistant and tells the Cantabile agent about the grid +operator's limit, but writes nothing to them: no command, and not the +grid operator's limit either. The page says so at the top. You can give +or take back the consent there at any time; the add-on restarts with it +and records when. + +The add-on sends nothing out of your home: its values go to Home +Assistant, the grid operator's limit to the Cantabile agent on the same +Home Assistant (which shares data with Cantabile only with your consent +in its own configuration). + +## Pairing + +EEBUS devices trust each other by their SKI (a fingerprint of the +device's certificate). Open the add-on's page (Cantabile EEBUS): + +1. Switch EEBUS on in the device's app or menu (for example the + myVAILLANT or ViCare app, or the wallbox's web page). The device + appears under **Found on the network**, or asks to be paired. +2. Compare the SKI on the page with the one the device shows (its app, + display or label; for the control box, the installer or the grid + operator gives it). +3. **Pair**. In the device's app, trust "Cantabile EEBUS bridge" if it + asks. The page shows the bridge's own two SKIs at the bottom: one for + heat pumps, wallboxes and inverters, one for the grid operator's + control box (give that one to the installer). + +Each device is paired once; the add-on keeps its own certificate in its +data, so the pairing survives updates. A device's page opens with a link +`#` (from Cantabile's dashboard). + +## The grid operator's limit (§14a) + +A paired control box is **sealed**: nothing in Home Assistant or Cantabile +lifts its limit, and it can't be unpaired on the page (only the grid +operator, through Cantabile). While it limits the home, the add-on passes +the limit on to the heat pumps and wallboxes at once and the Cantabile +agent plans within it. Without the control box's heartbeat for two +minutes the failsafe limit holds (4.2 kW unless the control box set +another) for its failsafe time. + +## Protection + +Every control of a heat pump or wallbox starts **protected**: Cantabile +never sets a heat pump to 0 W or a wallbox to 0 A. Only you lift a +protection, on the add-on's page, one control at a time; every change is +logged with who and when. + +## Options + +- **Cantabile may control devices**: your consent, above (off until you + give it). +- **Simulate**: a simulated control box, heat pump and wallbox, with + buttons on the page to send a limit or lose the heartbeat. +- **Read only**: commands are checked and logged, never written. +- **Pass on the grid operator's limit**: on by default. + +The add-on uses the host's network: EEBUS devices find it by mDNS and +connect to TCP ports 4712 (the control box) and 4713 (the other +devices). The devices' support differs by model and +firmware; the profiles are untested on real hardware so far. + +Open-source components and their licences: see +`/usr/share/doc/cantabile-eebus/THIRD-PARTY-NOTICES.md` in the image. + +--- + +© 2026 Setti Solutions S.R.L, [www.setti.md](https://www.setti.md). All rights reserved. diff --git a/cantabile_eebus/Dockerfile b/cantabile_eebus/Dockerfile new file mode 100644 index 0000000..a39685a --- /dev/null +++ b/cantabile_eebus/Dockerfile @@ -0,0 +1,23 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +# The EEBUS bridge add-on's image: the Hub's bridge (one Go binary) and the +# device profiles; -ha reads the add-on's options and the Supervisor's +# broker. Built from the repository's root: +# docker build -f cantabile_eebus/Dockerfile --build-arg VERSION= \ +# -t /cantabile-ha-eebus-amd64: . +FROM docker.io/library/golang:1.26.9-bookworm AS build +WORKDIR /src +COPY src/eebus-bridge/go.mod src/eebus-bridge/go.sum ./ +RUN go mod download +COPY src/eebus-bridge/*.go ./ +ARG VERSION=0.0.0-dev +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /cantabile-eebus . + +FROM docker.io/library/alpine:3.22 +ARG VERSION ARCH=amd64 REVISION +LABEL io.hass.version="${VERSION}" io.hass.type="addon" io.hass.arch="${ARCH}" \ + org.opencontainers.image.revision="${REVISION}" +COPY --from=build /cantabile-eebus /usr/bin/cantabile-eebus +COPY src/eebus-bridge/THIRD-PARTY-NOTICES.md /usr/share/doc/cantabile-eebus/ +COPY src/profiles/*.json /app/profiles/ +ENV DATA_DIR=/data PROFILES_DIR=/app/profiles PAGE_PORT=8099 +ENTRYPOINT ["/usr/bin/cantabile-eebus", "-ha"] diff --git a/cantabile_eebus/config.yaml b/cantabile_eebus/config.yaml new file mode 100644 index 0000000..7b18671 --- /dev/null +++ b/cantabile_eebus/config.yaml @@ -0,0 +1,41 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +# Cantabile's EEBUS bridge as a Home Assistant add-on: the Hub's bridge +# (src/eebus-bridge) with Cantabile's device profiles, for a Home +# Assistant that isn't a Cantabile Hub. Devices are paired on its page +# (ingress), by their SKI. +name: Cantabile EEBUS +version: "0.1.400" +slug: cantabile_eebus +description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection. +url: https://cantabile.cloud +arch: [amd64] +image: git.setti.solutions/daniel/cantabile-ha-eebus-{arch} +stage: experimental +startup: application +boot: auto +services: + - mqtt:need +# EEBUS: devices find the bridge by mDNS and connect to the address it +# announces (SHIP, TCP 4712); both need the host's network. +host_network: true +ingress: true +ingress_port: 8099 +panel_icon: mdi:transmission-tower +panel_title: Cantabile EEBUS +panel_admin: true +# consent_control: the owner's consent, given here when installing: without +# it the add-on reads and writes nothing to the devices (DOCS.md "Your +# consent"). It sends nothing out of the home, so it asks no data consent. +options: + consent_control: false + simulate: false + read_only: false + pass_on_limits: true +schema: + consent_control: bool + simulate: bool + read_only: bool + pass_on_limits: bool + port: "port?" + interfaces: + - str? diff --git a/cantabile_eebus/icon.png b/cantabile_eebus/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..21af6267a93ecf60ad695a9218b0672417745b8e GIT binary patch literal 12462 zc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Eg)fEp09xy#d| zLjM9Bo(bqBJ_r7Pp|ay2`td8h#>NQdH|mf+_)#wYv!FdKpM0NN3<7f(ZtdU~_%*Of zB#fOs&zEbBW?Z{vU-3lHgme?KweSCIertD*6@LnUd6QKHCh;QI6L;1cX1fPQj2JHE z-1S=WQB~p`oPKqjw(*4-B?{HF8M%QJ<4|Pcl-d4yHqh}4O1Qy?Li_p<#rGMqZygL> zhJU_K{TKQf1I-hoDV+LE=(43+i@c8}kM<`r)DGB0wat({7hm;w_Om`g4pgjhw<9;< z+rZk>K?Dq_!WGA%{Ms8P8c_8SseXMi^Nt=UYvnxHmEzozBz--Z`U$Wqgkk zW?`#E3%xJKf0>3p7|Dsz%@UtdUW%8dQ6wfjU^JGZk0zl0pTifl_YN!par-t*oBjIu Q4*?)AtpffnWfb)P01bP_umAu6 literal 0 HcmV?d00001 diff --git a/cantabile_eebus/logo.png b/cantabile_eebus/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..b002d1915d3aaafacb5ffce48f894d0ffd0a1ba6 GIT binary patch literal 15401 zcmbW8Wmg?du(mhu?hYG*y9Hq+zIX;+}+)6<8V0VAG~j`H8Y=j zW_op3RrghQMJdWlp&$|>0ssJ%AJXE=U(c7X%M>2=>s}McgbD!gU;hvnQT1HC==8|a zQ)~VF^vY=hZyw41q)rV*C%;F?m!qX~q>h9nRO;dQ?ZXs_+2d{}T;u)l?^t8-OpQf? zvsWMeNLK;|2IdDUG(3e^GBUcTG$aCr9s5N}=aTl+Rf6AS5xQvLwC}~^S?ZFk`Q-VB z)|u7W3P|+-x%F*Q^47YFLx%07Lu_3 z6%-2VzTC~XNHeD|U}5SDb2#CJ!!RS|8~keRVlDh{!r@^ofd7T>L`dY^Zdm$+MXK9t z>4JueYT&w}Q_MOdwfZ+~YpWUdM9}Dg{ytlyS=u4?KMJ{!S2#Mijum2w>yhXJEC9fS zW3)0S@md=}k7^h&{WxqT^|$U+oAY@I)s@7>+k!?M*BtC`zSS570aEq_5G%`XI}Iv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>tMj)63ssHcGTF2SwoGn8&aE+H9lcVN5k9fE*BV${P7jS$@*tK6}tqf_GO=i34 zu{n+d+XF8YO?C$kzrkqTn&cD|I|kTZD0s6}|G({=@*_Z_- + Ihre Einwilligung: Cantabile darf die von Ihnen gewählten Geräte + (Heizung, Laden, Batterie, Beschattung) innerhalb der von Ihnen + gesetzten Grenzen steuern. Hier: die gekoppelten Wärmepumpen und + Wallboxen, auch das Weitergeben des Limits des Netzbetreibers. Ohne + sie liest das Add-on sie nur. + simulate: + name: Simulieren + description: >- + Eine simulierte Steuerbox, Wärmepumpe und Wallbox statt des Netzwerks + (zum Ausprobieren: Koppeln, Werte, ein Limit des Netzbetreibers), ohne + echte Geräte zu berühren. + read_only: + name: Nur lesen + description: >- + Befehle werden geprüft und protokolliert, aber nie an die Geräte + geschrieben (Probelauf). Werte werden wie gewohnt gelesen. + pass_on_limits: + name: Limit des Netzbetreibers weitergeben + description: >- + Wenn die Steuerbox das Haus begrenzt (§14a), das Limit sofort an die + gekoppelten Wärmepumpen und Wallboxen weitergeben; der Cantabile-Agent + verteilt es dann innerhalb des Limits. + port: + name: EEBUS-Port + description: Der TCP-Port für EEBUS (SHIP) zur Steuerbox (4712); die anderen Geräte nutzen den nächsten (4713). + interfaces: + name: Netzwerkschnittstellen + description: >- + Nur diese Schnittstellen für mDNS (z. B. eth0); leer: alle. diff --git a/cantabile_eebus/translations/en.yaml b/cantabile_eebus/translations/en.yaml new file mode 100644 index 0000000..5b3bb22 --- /dev/null +++ b/cantabile_eebus/translations/en.yaml @@ -0,0 +1,33 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +configuration: + consent_control: + name: Cantabile may control devices + description: >- + Your consent: allow Cantabile to control the devices you choose + (heating, charging, battery, shades) within the limits you set. Here: + the paired heat pumps and wallboxes, including passing the grid + operator's limit on to them. Without it the add-on only reads them. + simulate: + name: Simulate + description: >- + A simulated control box, heat pump and wallbox instead of the network + (for trying the add-on: pairing, values, a grid operator's limit), + never touching real devices. + read_only: + name: Read only + description: >- + Commands are checked and logged but never written to the devices (a + dry run). Values are read as usual. + pass_on_limits: + name: Pass on the grid operator's limit + description: >- + When the control box limits the home (§14a), pass the limit on to the + paired heat pumps and wallboxes at once; the Cantabile agent then + shares it out within the limit. + port: + name: EEBUS port + description: The TCP port for EEBUS (SHIP) toward the control box (4712); the other devices use the next one (4713). + interfaces: + name: Network interfaces + description: >- + Only these interfaces for mDNS (e.g. eth0); empty: all. diff --git a/cantabile_modbus/DOCS.md b/cantabile_modbus/DOCS.md new file mode 100644 index 0000000..c0985ee --- /dev/null +++ b/cantabile_modbus/DOCS.md @@ -0,0 +1,51 @@ +# Cantabile Modbus bridge + +The bridge reads inverters, meters and batteries over Modbus TCP by +Cantabile's device profiles and shows them in Home Assistant (MQTT +discovery, the device under its own name), in Cantabile's units, so the +Cantabile agent maps them exactly. + +## Devices + +Add each device in the options: its profile (for example `hm8042-hybrid`), +a name, the address and port of its Modbus TCP gateway, and its Modbus id. +The add-on makes everything else from the profile at every start; nothing +is kept by hand. + +One Modbus master per gateway: if Home Assistant's own modbus integration +already reads a device, keep that, or stop it before the bridge reads it. +Some RS485 gateways send every answer to every connected client, so a +second master's answers reach the first one too. + +Per device, optionally: `poll_s` (seconds between reads, at least 10), +`read_only` (commands are checked and logged but never written: a dry run) +and `simulate` (this device only). + +## Circuits from Home Assistant + +A SONOFF SPM-4Relay (profile `sonoff-spm`) is read from the SonoffLAN +integration's entities (LAN mode is enough): give its eWeLink id as +`device` (the `ab40...` in `switch.sonoff_ab40..._1`). Each of its four +circuits shows its switch, power, current and voltage under Cantabile's +names; the energy is added up from the power (SonoffLAN reads energy only +from the cloud). A circuit is switched only through this add-on's switch, +after its protection check. + +## Protection + +Each control has a protection: **none**, **protected** (commands that would +switch it off are refused; for a control without an off, every command) or +**sealed** (set by Cantabile, locked). Every relay and circuit, and the +inverter's settings, start protected. Only +you lift a protection, on the add-on's page (Cantabile devices in the +sidebar); every change is written to the add-on's log with who and when. + +## Simulate + +With **Simulate** on, the add-on answers for the devices itself, from a +recorded trace in `/share/cantabile/trace-.json`, and never +touches the real devices. + +--- + +© 2026 Setti Solutions S.R.L, [www.setti.md](https://www.setti.md). All rights reserved. diff --git a/cantabile_modbus/Dockerfile b/cantabile_modbus/Dockerfile new file mode 100644 index 0000000..3391295 --- /dev/null +++ b/cantabile_modbus/Dockerfile @@ -0,0 +1,16 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +# The Modbus bridge add-on's image: the Hub's bridge, its Modbus code and the +# device profiles, with run.py in front (the add-on's options, MQTT from the +# Supervisor, the page). Built from the repository's root: +# docker build -f cantabile_modbus/Dockerfile --build-arg VERSION= \ +# -t /cantabile-ha-modbus-amd64: . +FROM docker.io/library/python:3.13-alpine +ARG VERSION ARCH=amd64 REVISION +LABEL io.hass.version="${VERSION}" io.hass.type="addon" io.hass.arch="${ARCH}" \ + org.opencontainers.image.revision="${REVISION}" +RUN pip install --no-cache-dir paho-mqtt==2.1.0 websocket-client==1.8.0 +COPY src/modbus-bridge/cantabile_modbus.py /app/cantabile_modbus.py +COPY src/modbus-bridge/bridge.py /app/bridge.py +COPY src/profiles/*.json /app/profiles/ +COPY cantabile_modbus/run.py cantabile_modbus/sim.py cantabile_modbus/ha_source.py cantabile_modbus/page.py /app/ +ENTRYPOINT ["python3", "-u", "/app/run.py"] diff --git a/cantabile_modbus/config.yaml b/cantabile_modbus/config.yaml new file mode 100644 index 0000000..c016290 --- /dev/null +++ b/cantabile_modbus/config.yaml @@ -0,0 +1,44 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +# Cantabile's Modbus bridge as a Home Assistant add-on: the Hub's bridge +# (src/modbus-bridge) with its device profiles (src/profiles), for a +# Home Assistant that isn't a Cantabile Hub. Devices come from the options; +# the page (ingress) shows them and each control's protection. +name: Cantabile Modbus bridge +version: "0.1.400" +slug: cantabile_modbus +description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection. +url: https://cantabile.cloud +arch: [amd64] +image: git.setti.solutions/daniel/cantabile-ha-modbus-{arch} +stage: experimental +startup: application +boot: auto +services: + - mqtt:need +# Devices read from Home Assistant's own entities (SONOFF SPM through +# SonoffLAN): their states, and switch.turn_on/off after the protection check. +homeassistant_api: true +ingress: true +ingress_port: 8098 +panel_icon: mdi:solar-power-variant +panel_title: Cantabile devices +panel_admin: true +# The simulator's traces (/share/cantabile/trace-.json). +map: + - type: share + read_only: true +options: + devices: [] + simulate: false +schema: + devices: + - profile: str + name: str + host: str? + port: "int(1,65535)?" + unit_id: "int(0,247)?" + device: str? + poll_s: "int(10,3600)?" + read_only: bool? + simulate: bool? + simulate: bool diff --git a/cantabile_modbus/ha_source.py b/cantabile_modbus/ha_source.py new file mode 100644 index 0000000..fbbac4c --- /dev/null +++ b/cantabile_modbus/ha_source.py @@ -0,0 +1,138 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Devices read from Home Assistant's own entities (a profile's "ha" map, e.g. +SONOFF SPM circuits through SonoffLAN in LAN mode): the bridge's source "ha". +The entities are found by their unique ids in HA's entity registry (an owner +may have renamed them), the profile's entity id the fallback. Values from +HA's states (through the Supervisor), a circuit's energy added +from its power where the integration has none, a command as HA's +switch.turn_on/turn_off on the entity, after the bridge's protection check. +""" +import json +import os +import time +import urllib.request + +import cantabile_modbus as mb + +API = "http://supervisor/core/api" +WS = "ws://supervisor/core/websocket" +ENERGY = "/data/energy-{}.json" # per device: "/" -> Wh, kept over restarts +GAP_S = 300 # no power for longer: that time is not counted + + +def call(method, path, body=None): + req = urllib.request.Request(API + path, method=method, data=None if body is None else json.dumps(body).encode(), + headers={"Authorization": f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}", + "Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=10) as r: + return json.load(r) + + +def registry(): + """({(domain, platform, unique id): entity id}, {entity id: its name}) + from HA's entity registry (a unique id is unique per domain only: + SonoffLAN's circuit switch and its power-on select share one; a disabled + entity has a name there but no state).""" + import websocket + ws = websocket.create_connection(WS, timeout=20) + try: + ws.recv() + ws.send(json.dumps({"type": "auth", "access_token": os.environ.get("SUPERVISOR_TOKEN", "")})) + if json.loads(ws.recv()).get("type") != "auth_ok": + raise OSError("Home Assistant refused the add-on's token") + ws.send(json.dumps({"id": 1, "type": "config/entity_registry/list"})) + while True: + m = json.loads(ws.recv()) + if m.get("id") == 1: + break + finally: + ws.close() + entries = m.get("result") or [] + ids = {(x["entity_id"].split(".", 1)[0], x["platform"], x["unique_id"]): x["entity_id"] for x in entries} + names = {x["entity_id"]: x.get("name") or x.get("original_name") for x in entries} + return ids, names + + +def expand(profile, device, name_of=None, ids=None): + """A profile's "ha" registers for one device: {n} the channel, {device} + its id. ids: {(domain, platform, unique id): entity id} (HA's registry); + name_of(entity) gives a control's name from HA (the circuit's).""" + out = [] + ha = profile["ha"] + for n in range(1, int(ha.get("channels", 1)) + 1): + for t in ha["registers"]: + r = {k: (v.replace("{n}", str(n)).replace("{device}", device) if isinstance(v, str) else v) for k, v in t.items()} + r.update(table="ha", type="ha", address=0) + if "unique_id" in r: + key = (r["entity"].split(".", 1)[0], ha["domain"], r.pop("unique_id")) + r["entity"] = (ids or {}).get(key, r["entity"]) + if r.get("write") and name_of: + r["name"] = name_of(r["entity"]) or r["name"] + out.append(r) + return out + + +def number(r, state): + if r.get("write"): + return {"on": 1, "off": 0}.get(state) + try: + return float(state) + except (TypeError, ValueError): + return None + + +class HASource: + def __init__(self, dev, states=None, service=None, energy=None): + self.dev, self.path = dev, energy or ENERGY.format(dev["id"]) + self.states = states or (lambda: call("GET", "/states")) + self.service = service or (lambda domain, svc, body: call("POST", f"/services/{domain}/{svc}", body)) + self.last = {} # key -> (time, power) + try: + with open(self.path) as f: + self.energy = json.load(f) + except (OSError, ValueError): + self.energy = {} + + def read_values(self, regs, now=None): + now = now or time.time() + try: + st = {s["entity_id"]: s["state"] for s in self.states()} + except Exception as e: # HA restarting: nothing read this time + return {}, {r["key"]: f"Home Assistant: {e}" for r in regs} + values, errors = {}, {} + for r in regs: + if "entity" in r: + v = number(r, st.get(r["entity"])) + if v is None: + errors[r["key"]] = f"{r['entity']}: {st.get(r['entity'], 'missing')}" + else: + values[r["key"]] = v + changed = False + for r in regs: + if "integrate" not in r: + continue + k = f"{self.dev['id']}/{r['key']}" + p = values.get(r["integrate"]) + if p is not None: + t0, p0 = self.last.get(r["key"], (None, None)) + if t0 is not None and 0 < now - t0 <= GAP_S: + self.energy[k] = self.energy.get(k, 0.0) + (p + p0) / 2 * (now - t0) / 3600 + changed = True + self.last[r["key"]] = (now, p) + if k in self.energy: + values[r["key"]] = round(self.energy[k], 1) + if changed: + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(self.energy, f) + os.replace(tmp, self.path) + return values, errors + + def write_value(self, r, v): + if "entity" not in r or not r.get("write"): + raise mb.ModbusError(f"{r['key']} is not written") + domain = r["entity"].split(".", 1)[0] + try: + self.service(domain, "turn_on" if v else "turn_off", {"entity_id": r["entity"]}) + except Exception as e: + raise mb.ModbusError(f"Home Assistant: {e}") from None diff --git a/cantabile_modbus/icon.png b/cantabile_modbus/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..21af6267a93ecf60ad695a9218b0672417745b8e GIT binary patch literal 12462 zcmaKTRZv__*X|5DSa5fDcb5$AgaiogZozeMcXtW$LV)1z?hqgh?(PuW4_}@8zp8uh z>bqWDyVrVT?MO8hSu|uKWB>qwCNBrp_;?5WZ-Nj$p8aCR;{X7Mn><)j({uSu-^=&w zeB&E*{dtuWiBdvsU_0Q81P1IBQQ7x{qelKNn~L1LZ^Grdm1oyjE5{X$!PR$+H}jut z{3fg1hQ3!|kVsG>TLr<66$EgZcl8VUT-?419IUT~aL5O#*FWe}&>!UaoIgSh`kSHa z!~{u{g#YJwv_gg*xJ|gdP57+3V+!(*&u=}LCZ|^?m%T(X0&LRLlN@+eM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xHmEzozBz--Z`U$Wqgkk zW?`#E3%xJKf0>3p7|Dsz%@UtdUW%8dQ6wfjU^JGZk0zl0pTifl_YN!par-t*oBjIu Q4*?)AtpffnWfb)P01bP_umAu6 literal 0 HcmV?d00001 diff --git a/cantabile_modbus/logo.png b/cantabile_modbus/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..b002d1915d3aaafacb5ffce48f894d0ffd0a1ba6 GIT binary patch literal 15401 zcmbW8Wmg?du(mhu?hYG*y9Hq+zIX;+}+)6<8V0VAG~j`H8Y=j zW_op3RrghQMJdWlp&$|>0ssJ%AJXE=U(c7X%M>2=>s}McgbD!gU;hvnQT1HC==8|a zQ)~VF^vY=hZyw41q)rV*C%;F?m!qX~q>h9nRO;dQ?ZXs_+2d{}T;u)l?^t8-OpQf? zvsWMeNLK;|2IdDUG(3e^GBUcTG$aCr9s5N}=aTl+Rf6AS5xQvLwC}~^S?ZFk`Q-VB z)|u7W3P|+-x%F*Q^47YFLx%07Lu_3 z6%-2VzTC~XNHeD|U}5SDb2#CJ!!RS|8~keRVlDh{!r@^ofd7T>L`dY^Zdm$+MXK9t z>4JueYT&w}Q_MOdwfZ+~YpWUdM9}Dg{ytlyS=u4?KMJ{!S2#Mijum2w>yhXJEC9fS zW3)0S@md=}k7^h&{WxqT^|$U+oAY@I)s@7>+k!?M*BtC`zSS570aEq_5G%`XI}Ivj zTu|PC6chKGsi`{DIbI4RkO4Wr6`VpI-D&wa1R=LH*SP4ypBdQPW?ev6;)3$QcTZlF2Mg6d>Lr=Il&fHAg8LZ zF0W_C@D}Z}5h}zZ2B;RaJsXYMt3-1qLw6~VjU4nW&+l2!+#h}a6gegUgC8wm>tNF? z_4*6f;Q-<+^2d;g(&`JkF`=R2$1G5%p;)8k7)KlJgAl?ubN>$NHF2(Er-*&_b*xa4 zZ<%~@7WhG+1Q>uZF*E}!Iz>sT155>FHm(u#e1=_yZjcFjdA$o^O^>q-tAc6<~js1ecBEM~blFA5E z*`h>B$RVA&lr{&4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l&VUVunbCG>vhScW8XL5&9Zz)Zl2ydzwcHAJaISUwitJp z+|WiGJaI{j_cQ2^4hrrDTCW|gKC0CWXayx|hHEZHtL6#DzXl1LMISok$KVQFKbt*5 zil*ykGW(V*_LlyFqx>3Q7v-g=j7f%MSmw{ncUSanDY6e#lD4hhr$rQvZMc><>a?0~uY4bA^y^8k?e zwV@4Rfc@jMIgy$=+K_n7g4}8DGii=<>&5>(i?t;VVW1GNjJn9+0`G)MIUA=4h^^Z` zU0d4);zbo6Ap^~UB;D!}T-Fn`Mhw)m89vK<#Y&c!?)#T4Xn$!m{My^mK)N|AYhzP% zSF+O5pV!p-!^(tD8x|&Jes?|f>&JhxpB~w>-OfW{vPFX< z5sUhr_ZkuYyVHg(!5c`l?Pa?To=;+bLW*@nQ*##Y7n1BK$r^gZjums_M6LSRoVa?{xDRha<<^X*AsY( zM=_I~fF!$GS?Ji*d(`?7`t@$_%o!I$@_wuwg8NR;do)+>Q7n$}COS&!QO)Pc`_DwX zo5U-GWSw7$wO2bDW@Lg)gxN4>Ru69Ac`t5f3^uKl35%uA`;T@s!81l-3@_0>B8}rv z+uvWE(B3@H0vtiPb*W_qz6U=nySmK%A03kHZZtN1UB0#AARsuX&b=3?qan2wLLD`A z;nBUD*f9BY$*(xyH#C{F3kT=m#=YIb=M8MhOM8k<9`mw#x03+egFf(I%jIGG$Fw{O zw@N>tMj)63ssHcGTF2SwoGn8&aE+H9lcVN5k9fE*BV${P7jS$@*tK6}tqf_GO=i34 zu{n+d+XF8YO?C$kzrkqTn&cD|I|kTZD0s6}|G({=@*_Z_, so a +reload stays there) its values in sets, its channels as tiles, an inverter's +power flow, sparklines of the last hour, and its controls with their +protection. Plain HTML, CSS and SVG; HA's light and dark; English and German +(the browser's language). + +Value sets: a register's "group", else its key's first word; a set of one +value is a line, not a card. Registers with "bits" are under "details" +unless not zero. Keys ending _ on two or more channels are a channel grid +(SPM circuits). The bridge's derived values (modbus.derived) come like +registers. A profile's "view": {"headline": [refs], "flow": {"pv", "grid", +"load", "battery", "soc", "bypass": ref}, "energy": [refs]}; a ref is a +register key or a quantity (the register that gives it). The rest of the +view (card, values, channels) is for the dashboard in Home Assistant. + +In HA's app panel the page is in an iframe whose own address has no +#: the parent's hash is read at start and kept in step. +""" +import html +import re +import time + +e = html.escape +HIST_MIN = 60 # sparklines: the last hour, a value a minute + +T = { + "en": {"title": "Cantabile devices", "back": "All devices", "online": "online", "offline": "offline", + "ro": "read only", "sim": "simulated", "every": "every {} s", "ha": "Home Assistant", + "prot_sum": "{} of {} controls protected", "no_controls": "no controls", "values": "Values", + "controls": "Controls", "details": "Details", "total": "Total", "on_of": "{} of {} on", + "protected": "protected", "none": "not protected", "sealed": "sealed", "lift": "Lift", + "protect": "Protect", "protect_all": "Protect all", "never_off": "Off refused", "all_refused": "every command refused", + "confirm": "Lift the protection of {}? Cantabile may then switch it.", "history": "Protection changes", + "none_yet": "none yet", "lock": "set by Cantabile, locked", "pv": "Solar", "grid": "Grid", "load": "Output", + "battery": "Battery", "inverter": "Inverter", "charging": "charging", "discharging": "discharging", + "energy": "Energy", "intro": "A protected control refuses the commands that would switch it off; " + "only you lift a protection, here, one control at a time. Sealed ones are set by Cantabile and locked.", + "ro_note": "Read only: commands are checked and logged, never written.", "voltage": "Voltage", "circuit": "Circuit {}", "all": "All:", + "bypass": "bypass", "bypass_est": "via bypass, estimated"}, + "de": {"title": "Cantabile-Geräte", "back": "Alle Geräte", "online": "online", "offline": "offline", + "ro": "nur lesen", "sim": "simuliert", "every": "alle {} s", "ha": "Home Assistant", + "prot_sum": "{} von {} Steuerungen geschützt", "no_controls": "keine Steuerungen", "values": "Werte", + "controls": "Steuerungen", "details": "Details", "total": "Gesamt", "on_of": "{} von {} an", + "protected": "geschützt", "none": "nicht geschützt", "sealed": "versiegelt", "lift": "Aufheben", + "protect": "Schützen", "protect_all": "Alle schützen", "never_off": "Aus wird abgelehnt", "all_refused": "jeder Befehl abgelehnt", + "confirm": "Schutz von {} aufheben? Cantabile darf es dann schalten.", "history": "Änderungen am Schutz", + "none_yet": "noch keine", "lock": "von Cantabile gesetzt, gesperrt", "pv": "Solar", "grid": "Netz", "load": "Ausgang", + "battery": "Batterie", "inverter": "Wechselrichter", "charging": "lädt", "discharging": "entlädt", + "energy": "Energie", "intro": "Eine geschützte Steuerung lehnt Befehle ab, die sie ausschalten würden; " + "nur Sie heben einen Schutz auf, hier, je Steuerung. Versiegelte setzt Cantabile, sie sind gesperrt.", + "ro_note": "Nur lesen: Befehle werden geprüft und protokolliert, nie geschrieben.", "voltage": "Spannung", + "circuit": "Stromkreis {}", "all": "Alle:", + "bypass": "Bypass", "bypass_est": "über Bypass, geschätzt"}, +} + +CSS = """:root{--bg:#f6f8f7;--fg:#1d2a24;--card:#fff;--line:#d5ded9;--soft:#e3e9e5;--mute:#5a6b62;--acc:#2f6f55;--prot:#1f6b45;--warn:#7a4b00;--bar:#cfe3d8} +@media (prefers-color-scheme:dark){:root{--bg:#111915;--fg:#e3ebe6;--card:#18221d;--line:#2b3a32;--soft:#22302a;--mute:#9fb0a6;--acc:#5fb38c;--prot:#7fd1a6;--warn:#e0a54a;--bar:#2c4a3b}} +body{font-family:system-ui,sans-serif;margin:0;padding:16px;overflow-wrap:anywhere;max-width:56rem;color:var(--fg);background:var(--bg)} +h2{margin:.2rem 0 1rem}h3{margin:0 0 .4rem;font-size:1rem}a{color:inherit} +.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.7rem .8rem;margin:.5rem 0} +a.card{display:block;text-decoration:none}a.card:hover{border-color:var(--acc)} +.row{display:flex;flex-wrap:wrap;gap:.3rem .9rem;align-items:baseline}.grow{flex:1} +.note{color:var(--mute);font-size:.88rem}.big{font-size:1.5rem;font-weight:600}.small{font-size:.82rem;color:var(--mute)} +.badge{display:inline-block;font-size:.75rem;padding:.05rem .45rem;border-radius:9px;background:var(--soft);color:var(--mute)} +.ok{color:var(--prot)}.bad{color:var(--warn)}.prot{background:var(--bar);color:var(--prot);font-weight:600}.lock{color:var(--warn)} +.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(10.5rem,100%),1fr));gap:.5rem} +.tiles{grid-template-columns:repeat(auto-fill,minmax(min(8rem,100%),1fr))}.tiles .card{padding:.45rem .6rem} +table.sparks td{border:0;padding:.15rem .4rem;vertical-align:middle}table.sparks td:first-child{width:40%} +.sets{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(14rem,100%),1fr));gap:.5rem} +.bar{height:6px;border-radius:3px;background:var(--soft);margin:.3rem 0}.bar i{display:block;height:100%;border-radius:3px;background:var(--acc)} +table{border-collapse:collapse;width:100%}td,th{text-align:left;padding:.3rem .4rem;border-bottom:1px solid var(--soft);font-size:.9rem} +td.v{text-align:right;white-space:nowrap} +button{font:inherit;font-size:.82rem;padding:.2rem .7rem;border:0;border-radius:6px;background:var(--acc);color:#fff;cursor:pointer} +button.off{background:var(--soft);color:var(--fg)}form{display:inline;margin:0} +details summary{cursor:pointer;color:var(--mute);font-size:.88rem}pre{white-space:pre-wrap;font-size:.8rem} +section.dev{display:none}section.dev:target{display:block}body:has(section.dev:target) #list{display:none} +svg text{fill:var(--fg);font-size:12px}svg text.sub{font-size:9.5px}svg .mute{fill:var(--mute)}svg .ln{stroke:var(--acc);fill:none}svg .box{fill:var(--card);stroke:var(--line)} +svg .soc{fill:var(--acc)}svg .spark{stroke:var(--acc);fill:none;stroke-width:1.5}""" + + +# HA's app panel shows the page in an iframe (same origin) without the +# # of its own address: take the parent's at start and keep both in +# step, so a link, back and reload land on the device. Reload every 30 s. +SCRIPT = """(function(){var P=null;try{if(window.parent!==window){P=window.parent;P.location.hash}}catch(x){P=null} +function dev(h){return h&&h.length>1&&document.getElementById(decodeURIComponent(h.slice(1)))?h:''} +if(P&&!location.hash){var h=dev(P.location.hash);if(h)location.replace(h)} +if(P){window.addEventListener('hashchange',function(){try{var h=location.hash;if(P.location.hash!==h&&!(h===''&&P.location.hash==='#'))P.location.hash=h}catch(x){}}); +P.addEventListener('hashchange',function(){var h=dev(P.location.hash);if(h!==location.hash&&!(h===''&&location.hash==='#'))location.hash=h})} +setTimeout(function(){location.reload()},30000)})();""" + + +def lang_of(accept): + return "de" if (accept or "").lower().startswith("de") else "en" + + +def num(s): + try: + return float(s) + except (TypeError, ValueError): + return None + + +def fmt(v, unit): + """A value for people: W to kW and Wh to kWh above 1000, sensible digits.""" + x = num(v) + if x is None: + return "–" if v is None else e(str(v)) + if unit == "Wh": + return f"{x / 1000:,.1f} kWh" if abs(x) >= 1000 else f"{x:.0f} Wh" + if unit == "W": + return f"{x / 1000:.2f} kW" if abs(x) >= 1000 else f"{x:.0f} W" if abs(x) >= 100 or x == 0 else f"{x:.1f} W" + digits = {"V": 1, "A": 2, "%": 0, "°C": 1, "Hz": 2}.get(unit, 2) + s = f"{x:.{digits}f}" + return f"{s} {e(unit)}" if unit else s + + +def channel_of(key): + m = re.fullmatch(r"(.+)_(\d+)", key) + return (m.group(1), int(m.group(2))) if m else (None, None) + + +def is_switch(r): + return set((r.get("write") or {}).get("options") or {}) == {"0", "1"} + + +class View: + """One device's values for the page: the registers' and the derived ones + (the bridge publishes both; energy comes in kWh, kept here in Wh), and + their last hour.""" + + def __init__(self, dev, values, hist): + self.dev, self.hist = dev, hist + self.regs = {r["key"]: r for r in dev["registers"]} + self.regs.update({d["key"]: dict(d, type="derived") for d in dev.get("derived") or []}) + self.v = {k: values.get(f"{dev['id']}/{k}") for k in self.regs} + for k, r in self.regs.items(): + if r.get("unit") == "Wh" and num(self.v[k]) is not None: + self.v[k] = num(self.v[k]) * 1000 + # the view's references as register keys (a quantity: its register) + by_q = {} + for k, r in self.regs.items(): + if r.get("quantity"): + by_q.setdefault(r["quantity"], k) + v = dev.get("view") or {} + ref = lambda x: by_q.get(x, x) if isinstance(x, str) else x # noqa: E731 + self.view = dict(v, headline=[ref(x) for x in v.get("headline") or []], + energy=[ref(x) for x in v.get("energy") or []]) + if v.get("flow"): + self.view["flow"] = {k: ref(x) for k, x in v["flow"].items()} + + def series(self, key): + """[value per minute] of the last hour.""" + now = int(time.time() // 60) + return [self.hist.get(f"{self.dev['id']}/{key}", {}).get(m) for m in range(now - HIST_MIN + 1, now + 1)] + + def channels(self): + """{n: {base: key}} when two or more channels carry values.""" + ch = {} + for k, r in self.regs.items(): + base, n = channel_of(k) + if n is not None: + ch.setdefault(n, {})[base] = k + valued = {n: c for n, c in ch.items() if any(not self.regs[k].get("write") for k in c.values())} + return valued if len(valued) >= 2 else {} + + def headline(self, t): + out = [] + for k in self.view.get("headline") or []: + if k in self.regs: + out.append((self.regs[k].get("name") or k, fmt(self.v.get(k), self.regs[k].get("unit", "")))) + ch = self.channels() + if not out and ch: + tot = sum(num(self.v.get(c.get("power"))) or 0 for c in ch.values()) + out.append((t["total"], fmt(tot, "W"))) + sw = [k for k, r in self.regs.items() if is_switch(r)] + if len(sw) >= 3 and not ch: + on = sum(1 for k in sw if str(self.v.get(k)) == (self.regs[k]["write"]["options"]["1"])) + out.append(("", t["on_of"].format(on, len(sw)))) + return out + + +def spark(vals, w=120, h=26): + pts = [(i, v) for i, v in enumerate(vals) if v is not None] + if len(pts) < 2: + return "" + lo, hi = min(v for _, v in pts), max(v for _, v in pts) + span = (hi - lo) or 1 + xy = " ".join(f"{i * w / (len(vals) - 1):.1f},{h - 2 - (v - lo) / span * (h - 4):.1f}" for i, v in pts) + return f"" + + +def flow(vw): + """The flow's powers: pv, grid (into the inverter +), load, battery + (charge +), soc, and whether the grid figure is estimated: with the + bypass on the utility feeds the output directly, which no register + counts (the grid register is the utility's charging power only).""" + f = vw.view["flow"] + p = {k: num(vw.v.get(f.get(k))) for k in ("pv", "grid", "load", "battery", "soc")} + p["bypass"] = bool(num(vw.v.get(f.get("bypass")))) # the grid's value then includes the output (estimated) + return p + + +def flow_svg(vw, t): + """Four nodes around the inverter: solar above, grid left, output right, + battery below (its charge as a bar inside); each arrow along the flow.""" + p = flow(vw) + bp, soc = p["battery"], p["soc"] + + def width(x): + return 1.5 + min(6, abs(x or 0) / 300) + + def line(x1, y1, x2, y2, power): + """From (x1, y1) to (x2, y2) when power > 0, the other way when < 0.""" + if not power or abs(power) < 1: + return f"" + if power < 0: + x1, y1, x2, y2 = x2, y2, x1, y1 + return f"" + + def node(cx, cy, label, value, sub=""): + return (f"" + f"{e(label)}" + f"{value}" + + (f"{e(sub)}" if sub else "")) + grid_sub = t["bypass_est"] if p["bypass"] else "" + bat_sub = t["charging"] if (bp or 0) >= 1 else t["discharging"] if (bp or 0) <= -1 else "" + bat_label = t["battery"] + (f" · {soc:.0f} %" if soc is not None else "") + socbar = "" + if soc is not None: + w = max(0, min(100, soc)) * 0.96 + socbar = (f"") + # inverter 130..230 x 124..176 (centre 180,150); nodes 46 px away from it on each side + return "".join([ + "", + "" + "", + line(180, 54, 180, 124, p["pv"]), # solar -> inverter + line(112, 150, 130, 150, p["grid"]), # grid -> inverter (+) + line(230, 150, 248, 150, p["load"]), # inverter -> output + line(180, 176, 180, 246, bp), # inverter -> battery (charge +) + node(180, 28, t["pv"], fmt(p["pv"], "W")), + node(56, 150, t["grid"], ("≈ " if p["bypass"] else "") + fmt(p["grid"], "W"), grid_sub), + f"{t['inverter']}" + + (f"{t['bypass']}" if p["bypass"] else ""), + node(304, 150, t["load"], fmt(p["load"], "W")), + f"" + f"{e(bat_label)}" + f"{fmt(abs(bp) if bp is not None else None, 'W')}" + f"{e(bat_sub)}", + socbar, ""]) + + +def badge(level, refuse, t): + if level == "sealed": + return f"🔒 {t['sealed']}" + if level == "protected": + what = t["never_off"] if refuse is not None and set(refuse) == {0.0} else t["all_refused"] + return f"{t['protected']} · {e(what)}" + return f"{t['none']}" + + +def toggle(dev, r, level, t): + if level == "sealed": + return f"{t['lock']}" + name = r.get("name") or r["key"] + if level == "protected": + msg = t["confirm"].format(name).replace("'", "’") + return (f"
" + f"" + f"
") + return (f"
" + f"" + f"
") + + +def controls(dev, vw, level_of, refuse_of, t): + ctl = [r for r in dev["registers"] if r.get("write")] + if not ctl: + return "" + prot = dev.get("protection") or {} + notes = {(prot.get(r["key"]) or prot.get("*") or {}).get("note", "") for r in ctl} + out = [f"

{t['controls']}

"] + if len(notes) == 1 and next(iter(notes)): + out.append(f"

{e(next(iter(notes)))}

") + if dev.get("read_only"): + out.append(f"

{t['ro_note']}

") + levels = {r["key"]: level_of(dev, r["key"]) for r in ctl} + if len(ctl) >= 8 and all(is_switch(r) for r in ctl): + same = len({(levels[r["key"]], str(refuse_of(dev, r["key"]))) for r in ctl}) == 1 + if same: + out.append(f"

{t['all']} {badge(levels[ctl[0]['key']], refuse_of(dev, ctl[0]['key']), t)}

") + out.append("
") + for r in ctl: + on = str(vw.v.get(r["key"])) == r["write"]["options"]["1"] + out.append(f"
{e(r.get('name') or r['key'])}" + f"{e(str(vw.v.get(r['key']) or '–'))}
" + f"
{'' if same else badge(levels[r['key']], refuse_of(dev, r['key']), t)}" + f"{toggle(dev, r, levels[r['key']], t)}
") + out.append("
") + else: + out.append("") + for r in ctl: + n = (prot.get(r["key"]) or {}).get("note", "") if len(notes) > 1 else "" + out.append(f"" + f"") + out.append("
{e(r.get('name') or r['key'])}" + (f"
{e(n)}" if n else "") + + f"
{e(str(vw.v.get(r['key']) or '–'))}{badge(levels[r['key']], refuse_of(dev, r['key']), t)}{toggle(dev, r, levels[r['key']], t)}
") + if sum(1 for lv in levels.values() if lv == "none") >= 2: + out.append(f"

" + f"" + f"

") + out.append("
") + return "".join(out) + + +def value_sets(vw, skip, t): + """The values not shown elsewhere, in sets; one value: a line.""" + groups, bits = {}, [] + for k, r in vw.regs.items(): + if r.get("write") or k in skip or r.get("type") == "string": + continue + if r.get("bits"): + x = num(vw.v.get(k)) + if not x: + bits.append((r, vw.v.get(k))) + continue + groups.setdefault(r.get("group") or k.split("_")[0].capitalize(), []).append(r) + cards, lines = [], [] + for g, rs in groups.items(): + if len(rs) == 1: + r = rs[0] + lines.append(f"
{e(r.get('name') or r['key'])}{fmt(vw.v.get(r['key']), r.get('unit', ''))}
") + continue + rows = "".join(f"{e(r.get('name') or r['key'])}{fmt(vw.v.get(r['key']), r.get('unit', ''))}" + + (f"
{spark(vw.series(r['key']), 80, 18)}" if r.get("unit") == "W" else "") + "" for r in rs) + cards.append(f"

{e(g)}

{rows}
") + out = "" + if cards: + out += f"
{''.join(cards)}
" + if lines: + out += f"
{''.join(lines)}
" + if bits: + out += (f"
{t['details']}" + + "".join(f"" for r, v in bits) + + "
{e(r.get('name') or r['key'])}{e(str(v if v is not None else '–'))}
") + return out + + +def channel_grid(vw, t): + ch = vw.channels() + pw = {n: num(vw.v.get(c.get("power"))) for n, c in ch.items()} + total = sum(x or 0 for x in pw.values()) + volts = [num(vw.v.get(c.get("voltage"))) for c in ch.values() if c.get("voltage")] + volts = [x for x in volts if x is not None] + one_v = volts and max(volts) - min(volts) <= 5 + head = (f"
{t['total']}{fmt(total, 'W')}" + f"{spark([sum(x or 0 for x in s) if any(x is not None for x in s) else None for s in zip(*[vw.series(c['power']) for c in ch.values() if c.get('power')])])}
" + + (f"
{t['voltage']} {fmt(sum(volts) / len(volts), 'V')}
" if one_v else "") + "
") + tiles = [] + for n in sorted(ch): + c = ch[n] + sw = c.get("circuit") or next((k for k in c.values() if vw.regs[k].get("write")), None) + name = (vw.regs[sw].get("name") if sw else None) or t["circuit"].format(n) + state = f" {e(str(vw.v.get(sw) or '–'))}" if sw else "" + share = (pw[n] or 0) / total * 100 if total else 0 + small = [fmt(vw.v.get(c[b]), vw.regs[c[b]].get("unit", "")) for b in ("current", "energy") if c.get(b)] + if c.get("voltage") and not one_v: + small.append(fmt(vw.v.get(c["voltage"]), "V")) + tiles.append(f"
{e(name)}{state}
" + f"
{fmt(pw[n], 'W')}
" + f"
{' · '.join(small)}
") + return head + f"
{''.join(tiles)}
", {k for c in ch.values() for k in c.values()} + + +def device_view(dev, vw, status, level_of, refuse_of, t): + out = [f"

← {t['back']}

", + f"

{e(dev['name'])}

{e(dev['manufacturer'])} {e(dev['model'])} · {where(dev, t)} · " + f"{t['every'].format(dev.get('poll_s', 10))} {state_badges(dev, status, t)}

"] + skip = set() + if vw.view.get("flow"): + f = vw.view["flow"] + skip |= {f.get(k) for k in ("pv", "grid", "load", "battery", "soc", "bypass")} + for d in vw.dev.get("derived") or []: + skip |= set(d.get("product") or []) + sparks = "" + "".join( + f"" + for k in (f.get("pv"), f.get("load"), f.get("battery"), f.get("grid")) if k in vw.regs) + "
{e(vw.regs[k].get('name') or k)}{fmt(vw.v.get(k), 'W')}{spark(vw.series(k), 160, 32)}
" + energy = " · ".join(f"{e(vw.regs[k].get('name') or k)} {fmt(vw.v.get(k), 'Wh')}" for k in vw.view.get("energy") or [] if k in vw.regs) + skip |= set(vw.view.get("energy") or []) + out.append(f"
{flow_svg(vw, t)}{sparks}" + (f"

{t['energy']}: {energy}

" if energy else "") + "
") + if vw.channels(): + grid, used = channel_grid(vw, t) + out.append(grid) + skip |= used + out.append(value_sets(vw, skip, t)) + out.append(controls(dev, vw, level_of, refuse_of, t)) + out.append("
") + return "".join(out) + + +def where(dev, t): + if dev.get("source") == "ha": + return f"{t['ha']} ({e(dev.get('device', ''))})" + return f"{e(dev['host'])}:{dev['port']} · unit {dev['unit_id']}" + + +def state_badges(dev, status, t): + b = [f"{t['online'] if status == 'online' else t['offline']}"] \ + if status else [] + if dev.get("read_only"): + b.append(f"{t['ro']}") + if dev.get("simulated"): + b.append(f"{t['sim']}") + return " ".join(b) + + +def render(devs, values, statuses, hist, level_of, refuse_of, lang="en", plog=()): + t = T.get(lang, T["en"]) + out = [f"" + f"{t['title']}

{t['title']}

{t['intro']}

"] + views = {d["id"]: View(d, values, hist) for d in devs} + for d in devs: + vw = views[d["id"]] + ctl = [r for r in d["registers"] if r.get("write")] + n_prot = sum(1 for r in ctl if level_of(d, r["key"]) in ("protected", "sealed")) + heads = " · ".join((f"{e(k)} {v}" if k else f"{v}") for k, v in vw.headline(t)) + summary = t["prot_sum"].format(n_prot, len(ctl)) if ctl else t["no_controls"] + out.append(f"

{e(d['name'])}

" + f"{state_badges(d, statuses.get(d['id']), t)}
" + f"
{e(d['model'])} · {where(d, t)}
" + + (f"
{heads}
" if heads else "") + + f"
{summary}
") + out.append(f"
{t['history']}
{e(chr(10).join(plog)) or t['none_yet']}
") + for d in devs: + out.append(device_view(d, views[d["id"]], statuses.get(d["id"]), level_of, refuse_of, t)) + out.append("") + return "".join(out).encode() diff --git a/cantabile_modbus/run.py b/cantabile_modbus/run.py new file mode 100644 index 0000000..9d321cf --- /dev/null +++ b/cantabile_modbus/run.py @@ -0,0 +1,274 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The Modbus bridge add-on's start: its devices from the add-on's options and +Cantabile's profiles (parameters only: /data/devices.json is made again at +every start, never edited), the simulator when asked, the broker from the +Supervisor, the bridge, and the page (ingress): devices, values, and each +control's protection. + +A device is read over Modbus (the profile's register map) or, for a profile +with an "ha" map (SONOFF SPM through SonoffLAN), from Home Assistant's own +entities (ha_source). Per device: "read_only" (commands are checked and +logged, never written: a dry run), "simulate" (only this device), "poll_s" +(at least 10 s: a gateway may have another master, e.g. HA's own modbus). + +Protection (none | protected | sealed): the profile's default, over it the +owner's choice in /data/policy.json, set only on this page by a Home +Assistant administrator, by hand. Every change is logged (who, when) in the +add-on's log and in /data/protection.log. Sealed is shown locked: it changes +only by a signed policy from Cantabile, never here. +""" +import json +import os +import sys +import threading +import time +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, "/app") +import bridge # noqa: E402 +import ha_source # noqa: E402 +import page as view # noqa: E402 +import sim # noqa: E402 + +DATA = "/data" +PROFILES = "/app/profiles" +DEVICES = f"{DATA}/devices.json" +POLICY = f"{DATA}/policy.json" +PLOG = f"{DATA}/protection.log" +INGRESS_PEER = "172.30.32.2" # the Supervisor's ingress proxy +SIM_PORT = 15020 +MIN_POLL_S = 10 +values = {} # "/" -> last value (from MQTT) +statuses = {} # "" -> online | offline +hist = {} # "/" -> {minute: value}, the last hour (sparklines) +lock = threading.Lock() + + +def log(msg): + print(f"cantabile-modbus: {msg}", flush=True) + + +def slug(s): + return "".join(c if c.isalnum() else "_" for c in s.lower()).strip("_")[:40] or "device" + + +def profiles(): + out = {} + for n in sorted(os.listdir(PROFILES)): + if not n.endswith(".json"): + continue + with open(os.path.join(PROFILES, n)) as f: + p = json.load(f) + if p.get("modbus", {}).get("registers") or p.get("ha", {}).get("registers"): + out[p["id"]] = p + return out + + +def ha_names(): + """(entity id -> its name in HA (a circuit's name), (domain, platform, + unique id) -> entity id); empty without HA.""" + try: + ids, reg_names = ha_source.registry() + names = {k: v for k, v in reg_names.items() if v} + names.update({s["entity_id"]: s["attributes"].get("friendly_name") for s in ha_source.call("GET", "/states") + if s["attributes"].get("friendly_name")}) + return names, ids + except Exception as e: + log(f"Home Assistant's entities not read ({e}): the profile's entity ids and names") + return {}, {} + + +def make_devices(opts, ps, names=None, ids=None): + """devices.json for the bridge, from the options (the same shape the + Hub's devices tool writes).""" + out = [] + for i, d in enumerate(opts.get("devices", [])): + p = ps.get(d["profile"]) + if not p: + log(f"{d['name']}: no profile {d['profile']!r} with a register map: left out") + continue + base = p.get("modbus") or p["ha"] + dev = {"id": slug(d["name"]), "name": d["name"], "manufacturer": p["manufacturer"], "model": p["name"], + "poll_s": max(MIN_POLL_S, int(d.get("poll_s") or base.get("poll_s", 10))), + "protection": p.get("register_protection", {}), "read_only": bool(d.get("read_only")), "view": p.get("view", {}), + "node": "cantabile_modbus", "profile": p["id"]} + if p.get("modbus", {}).get("registers"): + if not d.get("host") or not d.get("port") or d.get("unit_id") is None: + log(f"{d['name']}: {p['id']} needs host, port and unit_id: left out") + continue + host, port = d["host"], d["port"] + if opts.get("simulate") or d.get("simulate"): + trace = sim.load_trace(f"/share/cantabile/trace-{p['id']}.json") + host, port = "127.0.0.1", SIM_PORT + i + sim.serve(p, trace, d["unit_id"], port) + dev["simulated"] = True + log(f"{d['name']}: simulated on {host}:{port} ({'a recorded trace' if trace else 'zeros: no trace'})") + dev.update(host=host, port=port, unit_id=d["unit_id"], registers=p["modbus"]["registers"], + derived=p["modbus"].get("derived", [])) + else: + if not d.get("device"): + log(f"{d['name']}: {p['id']} needs the device's id in Home Assistant (device): left out") + continue + if names is None: + names, ids = ha_names() + dev.update(source="ha", host="Home Assistant", port=0, unit_id=0, device=d["device"], + registers=ha_source.expand(p, d["device"], names.get, ids)) + out.append(dev) + with open(DEVICES, "w") as f: + json.dump({"devices": out}, f, indent=1) + return out + + +def mqtt_service(): + req = urllib.request.Request("http://supervisor/services/mqtt", + headers={"Authorization": f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}"}) + with urllib.request.urlopen(req, timeout=10) as r: + return json.load(r)["data"] + + +def policy(): + try: + with open(POLICY) as f: + return json.load(f) + except (OSError, ValueError): + return {} + + +def level_of(dev, key): + return bridge.protection(dev, key)[0] + + +def set_level(dev, key, new, who): + old = level_of(dev, key) + if old == "sealed" or new not in ("none", "protected") or old == new: + return False + p = policy() + p[f"{dev['id']}/{key}"] = new + tmp = POLICY + ".tmp" + with open(tmp, "w") as f: + json.dump(p, f, indent=1) + os.replace(tmp, POLICY) + line = f"{time.strftime('%Y-%m-%d %H:%M:%S %Z')}: {dev['name']} / {key}: {old} -> {new}, by {who} (the add-on's page)" + with open(PLOG, "a") as f: + f.write(line + "\n") + log("protection " + line) + return True + + +def record(dev, key, payload, now=None): + """A value from MQTT: the last one, and one a minute for the last hour.""" + with lock: + if key == "status": + statuses[dev] = payload + return + values[f"{dev}/{key}"] = payload + x = view.num(payload) + if x is not None: + m = int((now or time.time()) // 60) + h = hist.setdefault(f"{dev}/{key}", {}) + h[m] = x + for old in [k for k in h if k <= m - view.HIST_MIN]: + del h[old] + + +def watch_values(svc): + import paho.mqtt.client as paho + m = paho.Client(paho.CallbackAPIVersion.VERSION2, client_id="cantabile-modbus-page") + if svc.get("username"): + m.username_pw_set(svc["username"], svc.get("password", "")) + + def on_message(_c, _u, msg): + parts = msg.topic.split("/") + if len(parts) == 3: + record(parts[1], parts[2], msg.payload.decode(errors="replace")) + m.on_connect = lambda c, *_a: c.subscribe(f"{bridge.BASE}/#") + m.on_message = on_message + m.connect(svc["host"], int(svc.get("port", 1883))) + m.loop_start() + + +def page(devs, lang="en"): + try: + with open(PLOG) as f: + plog = f.read().strip().splitlines()[-20:] + except OSError: + plog = [] + with lock: + vs, st, hs = dict(values), dict(statuses), {k: dict(v) for k, v in hist.items()} + return view.render(devs, vs, st, hs, level_of, lambda d, k: bridge.protection(d, k)[1], lang, plog) + + +def protect_all(dev, who): + """Every control of the device that is not protected: protected (the + safe way only; lifting is always one control at a time).""" + return [r["key"] for r in dev["registers"] if r.get("write") and set_level(dev, r["key"], "protected", who)] + + +def serve_page(devs): + by_id = {d["id"]: d for d in devs} + + class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def allowed(self): + if self.client_address[0] != INGRESS_PEER: + self.send_error(403) + return False + return True + + def send(self, body, code=200): + self.send_response(code) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.allowed(): + self.send(page(devs, view.lang_of(self.headers.get("Accept-Language")))) + + def do_POST(self): + if not self.allowed(): + return + n = int(self.headers.get("Content-Length") or 0) + q = urllib.parse.parse_qs(self.rfile.read(n).decode()) + dev = by_id.get((q.get("dev") or [""])[0]) + key = (q.get("key") or [""])[0] + who = self.headers.get("X-Remote-User-Display-Name") or self.headers.get("X-Remote-User-Name") or "?" + level = (q.get("level") or [""])[0] + if dev and key == "*" and level == "protected": + protect_all(dev, who) + elif dev and any(r["key"] == key and r.get("write") for r in dev["registers"]): + set_level(dev, key, level, who) + self.send_response(303) + self.send_header("Location", (self.headers.get("X-Ingress-Path") or "") + "/" + (f"#{dev['id']}" if dev else "")) + self.end_headers() + + ThreadingHTTPServer(("0.0.0.0", 8098), H).serve_forever() + + +def main(): + with open(f"{DATA}/options.json") as f: + opts = json.load(f) + devs = make_devices(opts, profiles()) + svc = mqtt_service() + if svc.get("ssl"): + log("the broker wants TLS, which the bridge does not speak yet") + sys.exit(1) + with open(f"{DATA}/mqtt-password", "w") as f: + f.write(svc.get("password", "")) + os.environ.update(MQTT_HOST=str(svc["host"]), MQTT_PORT=str(svc.get("port", 1883)), MQTT_USERNAME=svc.get("username", ""), + MQTT_PASSWORD_FILE=f"{DATA}/mqtt-password") + bridge.CONFIG, bridge.POLICY = DEVICES, POLICY + bridge.SOURCES["ha"] = ha_source.HASource + log(f"{len(devs)} devices; broker {svc['host']}:{svc.get('port', 1883)}") + threading.Thread(target=bridge.main, daemon=True).start() + watch_values(svc) + serve_page(devs) + + +if __name__ == "__main__": + main() diff --git a/cantabile_modbus/sim.py b/cantabile_modbus/sim.py new file mode 100644 index 0000000..5b8e5df --- /dev/null +++ b/cantabile_modbus/sim.py @@ -0,0 +1,125 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""A Modbus TCP device from a profile's register map, for showing the bridge +without the real device (the add-on's "simulate" option): one server per +device on 127.0.0.1, answering reads (functions 1-4) and writes (5, 6 and +16) of the profile's registers and coils. Values come from a trace (a device's history +as Home Assistant recorded it, one value per register key and step), played +in a loop; a written control keeps the value written. + +Trace (/share/cantabile/trace-.json): + {"step_s": 60, "values": {"": [v0, v1, ...], ...}} +""" +import json +import socketserver +import struct +import threading +import time + +import cantabile_modbus as mb + + +class Device: + def __init__(self, profile, trace): + self.regs = [r for r in profile["modbus"]["registers"] if r["type"] != "string"] + self.trace = trace or {"step_s": 60, "values": {}} + self.written = {} + self.lock = threading.Lock() + + def value(self, r): + if r["key"] in self.written: + return self.written[r["key"]] + vs = self.trace["values"].get(r["key"]) or [0] + i = int(time.time() // max(1, self.trace.get("step_s", 60))) % len(vs) + return vs[i] if vs[i] is not None else 0 + + def words(self, table, start, count): + out = {} + for r in self.regs: + if r.get("table", "holding") != table: + continue + try: + ws = mb.encode(r, self.value(r)) + except mb.ModbusError: + ws = [0] * mb.size(r) + for i, w in enumerate(ws): + out[r["address"] + i] = w + return [out.get(a, 0) for a in range(start, start + count)] + + def write(self, start, words, table="holding"): + with self.lock: + for r in self.regs: + if r.get("write") and r.get("table", "holding") == table and r["address"] == start \ + and len(words) >= mb.size(r): + self.written[r["key"]] = mb.decode(r, words) + return True + return False + + +def handler(dev, unit): + class H(socketserver.BaseRequestHandler): + def handle(self): + s = self.request + while True: + head = recv(s, 7) + if not head: + return + tid, _proto, length, uid = struct.unpack(">HHHB", head) + pdu = recv(s, length - 1) + if not pdu: + return + fc = pdu[0] + if uid != unit: + reply = bytes([fc | 0x80, 11]) + elif fc in (1, 2): + start, count = struct.unpack(">HH", pdu[1:5]) + bits = dev.words("coil" if fc == 1 else "discrete", start, count) + packed = bytes(sum(b << i for i, b in enumerate(bits[j:j + 8]) if b) for j in range(0, count, 8)) + reply = bytes([fc, len(packed)]) + packed + elif fc == 5: + start, w = struct.unpack(">HH", pdu[1:5]) + reply = pdu[:5] if dev.write(start, [1 if w == 0xFF00 else 0], "coil") else bytes([fc | 0x80, 2]) + elif fc in (3, 4): + start, count = struct.unpack(">HH", pdu[1:5]) + ws = dev.words("holding" if fc == 3 else "input", start, count) + reply = bytes([fc, 2 * count]) + struct.pack(f">{count}H", *ws) + elif fc == 6: + start, w = struct.unpack(">HH", pdu[1:5]) + reply = pdu[:5] if dev.write(start, [w]) else bytes([fc | 0x80, 2]) + elif fc == 16: + start, count = struct.unpack(">HH", pdu[1:5]) + ws = list(struct.unpack(f">{count}H", pdu[6:6 + 2 * count])) + reply = pdu[:5] if dev.write(start, ws) else bytes([fc | 0x80, 2]) + else: + reply = bytes([fc | 0x80, 1]) + s.sendall(struct.pack(">HHHB", tid, 0, len(reply) + 1, uid) + reply) + return H + + +def recv(s, n): + out = b"" + while len(out) < n: + c = s.recv(n - len(out)) + if not c: + return b"" + out += c + return out + + +class Server(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True + + +def serve(profile, trace, unit, port): + """Start one simulated device on 127.0.0.1: (a thread).""" + srv = Server(("127.0.0.1", port), handler(Device(profile, trace), unit)) + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv + + +def load_trace(path): + try: + with open(path) as f: + return json.load(f) + except (OSError, ValueError): + return None diff --git a/cantabile_modbus/translations/de.yaml b/cantabile_modbus/translations/de.yaml new file mode 100644 index 0000000..d90e43c --- /dev/null +++ b/cantabile_modbus/translations/de.yaml @@ -0,0 +1,16 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +configuration: + devices: + name: Geräte + description: >- + Je Gerät: sein Cantabile-Profil (z. B. hm8042-hybrid), ein Name, und + für Modbus Adresse und Port seines Gateways und seine Modbus-ID; für + ein Gerät aus Home Assistant (sonoff-spm) seine ID dort (device, z. B. + ab00000001). Wahlweise: poll_s (Sekunden, mindestens 10), read_only + (Befehle werden geprüft und protokolliert, nie geschrieben), simulate + (nur dieses Gerät). + simulate: + name: Simulieren + description: >- + Für die Geräte aus einer Aufzeichnung antworten, statt sie zu lesen + (zum Ausprobieren, ohne die echten Geräte zu berühren). diff --git a/cantabile_modbus/translations/en.yaml b/cantabile_modbus/translations/en.yaml new file mode 100644 index 0000000..7d3d3bd --- /dev/null +++ b/cantabile_modbus/translations/en.yaml @@ -0,0 +1,16 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +configuration: + devices: + name: Devices + description: >- + Each device: its Cantabile profile (e.g. hm8042-hybrid), a name, and + for Modbus the address and port of its gateway and its Modbus id; for + a device read from Home Assistant (sonoff-spm) its id there (device, + e.g. ab00000001). Optional: poll_s (seconds, at least 10), read_only + (commands are checked and logged, never written), simulate (this + device only). + simulate: + name: Simulate + description: >- + Answer for the devices from a recorded trace instead of reading them + (for trying the bridge without touching the real devices). diff --git a/src/edge/Dockerfile b/src/edge/Dockerfile new file mode 100644 index 0000000..b83e1e0 --- /dev/null +++ b/src/edge/Dockerfile @@ -0,0 +1,33 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +# Cantabile Edge Agent: one image for both wrappers (the HA add-on and the +# Cantabile Hub's own service): the agent (Python) and the site's link (Go, +# edge/link: the site's key and NATS connection). State in /data (the +# add-on's persistent directory as well), runs as non-root. +# Multi-arch (edge/build.sh): amd64 and arm64 (Raspberry Pi 4). The link is +# cross-compiled on the build machine; amd64 at the x86-64 baseline (v1), +# because Hub hardware includes CPUs without SSE4 (AMD G-T40N bench). +FROM --platform=$BUILDPLATFORM golang:1.26.9-bookworm AS link +WORKDIR /src +COPY link/go.mod link/go.sum ./ +RUN go mod download +COPY link/*.go ./ +ARG VERSION=0.0.0-dev +ARG TARGETARCH +RUN CGO_ENABLED=0 GOARCH=$TARGETARCH GOAMD64=v1 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /cantabile-link . + +FROM python:3.12.12-slim-bookworm +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +WORKDIR /src +COPY pyproject.toml ./ +COPY cantabile_edge ./cantabile_edge +RUN pip install --no-cache-dir . && rm -rf /src \ + && useradd --system --uid 10001 --home /data cantabile && mkdir -p /data /run/cantabile \ + && chown cantabile /data /run/cantabile +COPY --from=link /cantabile-link /usr/local/bin/cantabile-link +COPY run.sh /usr/local/bin/cantabile-run +USER 10001 +WORKDIR /data +# cantabile-run: the link and the agent together (CANTABILE_LINK=0: the +# agent alone, e.g. with the file or NATS sink in tests). +ENTRYPOINT ["cantabile-run"] +CMD ["--config", "/data/config.yaml", "run"] diff --git a/src/edge/cantabile_edge/__init__.py b/src/edge/cantabile_edge/__init__.py new file mode 100644 index 0000000..9eeda9f --- /dev/null +++ b/src/edge/cantabile_edge/__init__.py @@ -0,0 +1,5 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Cantabile Edge Agent v0: reads Home Assistant, +turns mapped entities into 1-minute telemetry and sends it upstream through +a store-and-forward queue. v0 never acts on devices.""" +__version__ = "0.1.0" diff --git a/src/edge/cantabile_edge/__main__.py b/src/edge/cantabile_edge/__main__.py new file mode 100644 index 0000000..ef8b2dd --- /dev/null +++ b/src/edge/cantabile_edge/__main__.py @@ -0,0 +1,4 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +from .cli import main + +main() diff --git a/src/edge/cantabile_edge/agent.py b/src/edge/cantabile_edge/agent.py new file mode 100644 index 0000000..ecb9908 --- /dev/null +++ b/src/edge/cantabile_edge/agent.py @@ -0,0 +1,343 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The agent's run loop: HA connection -> aggregator -> queue -> uplink. + +Three tasks: the HA connection (samples), the ticker (closes a window every +interval and queues it) and the uploader (sends queued batches in order). +They only share the aggregator and the queue, so an HA outage or an uplink +outage never stops the others: telemetry waits in the queue until the +uplink is back. Nothing is collected or sent without the owner's consent +for the site (consent.py), on top of the mapping's per entity. With an MQTT +broker (cfg.mqtt_host) the agent also shows itself in Home Assistant +(announce.py): read only, its connection to the platform. +""" +import asyncio +import logging +import os +import time + +from . import areas, ha, propose, sinks +from .announce import Announcer +from .consent import Consent +from .controller import Controller +from .inventory import Inventory +from .dashboards import Dashboards +from .devpage import App, Devices +from .joinpage import Fleet +from .mapping import Mapping, convert, scaled, value_of +from .store import Queue +from .telemetry import Aggregator + +log = logging.getLogger(__name__) + +RESTART = 75 # the exit status that asks addon-run to start the agent again +RESTART_DELAY_S = 1.0 + + +def number(state: str | None) -> float | None: + try: + v = float(state) + except (TypeError, ValueError): + return None # unavailable, unknown, text + return v if v == v and abs(v) != float("inf") else None + + +class Agent: + def __init__(self, cfg, mapping: Mapping, queue: Queue, sink): + self.cfg, self.mapping, self.queue, self.sink = cfg, mapping, queue, sink + self.agg = Aggregator(cfg.interval_s) + self.units: dict[str, str | None] = {} + self.parts: dict[str, float | None] = {} # parts' last values (their totals: mapping.py) + self.attrs: dict[str, dict] = {} # entity -> its last attributes (assets reading one) + self.states: dict[str, str | None] = {} + self.stop = asyncio.Event() + self.inventory_now = asyncio.Event() + self.consent = Consent(cfg.state_dir) + self.last_sent = 0.0 # when a batch was last stored on the other side + self.started = 0.0 + self.clock = time.time # tests set their own + self.ha_language = "en" # HA's language (its config): names in HA (names.py) + self.dashboards = Dashboards(self) if cfg.dashboards else None + # v1: plans and actions for the mapping's controls (controller.py) + self.control = Controller(cfg, mapping, self.consent, sink) if mapping.controls else None + if self.control is not None and hasattr(sink, "on_command"): + sink.on_command = self.control.command + # the devices' specs for the cloud (inventory.py) + self.inventory = Inventory(cfg, mapping, self.consent, sink, + self.control.policy if self.control is not None else None) + self.client = None + self.exit_code = 0 # RESTART: start again (restart()) + # A mapping for a site without one (propose.py): the HA add-on + self.profiles = propose.load_profiles() if cfg.propose else [] + + # -- the mapping ------------------------------------------------------ + async def ensure_mapping(self, client) -> bool: + """Import or propose a mapping while it is ours to write (propose.py); + True when the mapping changed (loaded again at once).""" + if not self.cfg.propose or propose.source_of(self.cfg.mapping) is None: + return False + states = await client.send("get_states") or [] + reg = await client.registries() + done = await asyncio.to_thread(propose.ensure, self.cfg.mapping, self.cfg.state_dir, states, reg, + self.profiles) + if not done: + return False + try: + m = Mapping.load(self.cfg.mapping) + except Exception as e: # propose.write checked it; a hand edit since? + log.warning("mapping not loaded again: %s", e) + return False + self.mapping = self.inventory.mapping = m + if m.controls and self.control is None: + log.info("the mapping has controls now: they are planned for after the next start") + if self.dashboards is not None: + self.dashboards.poke.set() + self.inventory_now.set() + return True + + async def mapping_loop(self): + """New devices into a proposed mapping (every EVERY_S).""" + while not self.stop.is_set(): + try: + await asyncio.wait_for(self.stop.wait(), areas.EVERY_S) + except asyncio.TimeoutError: + pass + if self.client is not None and not self.stop.is_set(): + try: + await self.ensure_mapping(self.client) + except Exception as e: + log.warning("mapping: %s", e) + + def restart(self): + """Stop and be started again (exit RESTART: the HA add-on's addon-run + starts the agent again), as the Hub's devices tool restarts it after + a consent or control change: the consented entities' subscription + and the controls' planner are made at start.""" + log.info("restarting for the devices' new consent or controls") + self.exit_code = RESTART + # a moment later: the page that asked answers first + asyncio.get_running_loop().call_later(RESTART_DELAY_S, self.stop.set) + + async def devices_changed(self, restart: bool = False): + """The add-on's Devices page wrote a device's fragment (devpage.py): + the proposal yields to it, the mapping is loaded again, the device + goes to the area "Cantabile" (without an area of its own) and onto + the dashboard. restart: a consent or a control changed (as on the + Hub, the agent starts again; restart()).""" + if restart: + self.restart() + return + if self.client is not None: + try: + await self.ensure_mapping(self.client) + except Exception as e: + log.warning("mapping: %s", e) + try: + m = Mapping.load(self.cfg.mapping) + except Exception as e: + log.warning("mapping not loaded again: %s", e) + return + self.mapping = self.inventory.mapping = m + if self.dashboards is not None: + self.dashboards.poke.set() + self.inventory_now.set() + if self.client is not None: + try: + await areas.place(self.client, f"cantabile_{self.cfg.site_id}", self.ha_language, + areas.used(self.cfg.state_dir)) + except Exception as e: + log.warning("areas: %s", e) + + # -- samples ---------------------------------------------------------- + def set_consent(self, share: bool, by: str): + self.consent.set(share, by) + log.info("consent to share energy data: %s (from %s)", "on" if share else "off", by) + if not share: + self.agg.flush(self.clock()) # the open window too + self.queue.clear() + + async def cloud(self) -> bool: + """The uplink's own word on its connection, else its last send.""" + q = getattr(self.sink, "cloud", None) + if q is not None: + return await q() + return self.last_sent > 0 + + def sample(self, entity_id: str, state: str | None, ts: float): + if not self.consent.share: + return # the owner has not (or no longer) agreed + for a in self.mapping.consented_all(entity_id): # none: not mapped or no consent, never leaves + raw = value_of(a, state, self.attrs.get(entity_id)) + v = number(raw) + if v is not None and not a.equals: + # an attribute is in HA's units (a climate's temperature): the asset's own + unit = a.unit if a.attribute else self.units.get(entity_id) + v = scaled(convert(v, unit, a.unit), a) + if v is None: + log.warning("%s: unit %s cannot become %s; value dropped", a.asset, unit, a.unit) + self.agg.sample(a.asset, a.kind, v, ts) + total = self.mapping.part_total.get(a.asset) + if total: + self.sample_total(self.mapping.totals[total], a.asset, v, ts) + + def sample_total(self, t, part: str, v: float | None, ts: float): + """A total of parts (pv.power from pv.1.power, pv.2.power: mapping.py) + from its consented parts' last values: their sum (the mean for % and + °C); unknown while a part is (a counter then waits: a missing part + must not look like a meter reset).""" + self.parts[part] = v + parts = [p for p in t.parts if getattr(self.mapping.by_asset.get(p), "consent", False)] + vals = [self.parts.get(p) for p in parts] + if not vals or None in vals: + if t.kind == "gauge": + self.agg.sample(t.asset, t.kind, None, ts) + return + self.agg.sample(t.asset, t.kind, sum(vals) / (len(vals) if t.mean else 1), ts) + + def on_entities(self, ev: dict): + now = self.clock() + for eid, s in (ev.get("a") or {}).items(): + self.units[eid] = (s.get("a") or {}).get("unit_of_measurement") + self.attrs[eid] = dict(s.get("a") or {}) + self.states[eid] = s.get("s") + self.sample(eid, s.get("s"), now) # the value as of now + for eid, c in (ev.get("c") or {}).items(): + plus = c.get("+") or {} + if "unit_of_measurement" in (plus.get("a") or {}): + self.units[eid] = plus["a"]["unit_of_measurement"] + if plus.get("a"): + self.attrs.setdefault(eid, {}).update(plus["a"]) + for k in (c.get("-") or {}).get("a") or []: + self.attrs.get(eid, {}).pop(k, None) + if "s" in plus: + self.states[eid] = plus["s"] + if "s" in plus or plus.get("a"): # an attribute alone (hvac_action) is news too + self.sample(eid, self.states.get(eid), min(plus.get("lu") or plus.get("lc") or now, now)) + + async def on_connect(self, client: ha.HAClient): + try: + self.ha_language = (await client.send("get_config") or {}).get("language") or "en" + except Exception as e: + log.info("get_config: %s", e) + try: + await self.ensure_mapping(client) + except Exception as e: # never keeps the agent from reading + log.warning("mapping: %s", e) + ids = list(dict.fromkeys(a.entity for a in self.mapping.assets if a.consent)) # one entity may feed several + await client.subscribe_entities(ids, self.on_entities) + log.info("subscribed to %d consented entities (mapping v%d)", len(ids), self.mapping.version) + if self.control is not None: + await self.control.on_connect(client) + if self.dashboards is not None: + self.dashboards.connected(client) + self.client = client + self.inventory_now.set() + + async def inventory_loop(self): + """The inventory at connecting, then every 30 minutes if it changed + (and once a day anyway).""" + while not self.stop.is_set(): + try: + await asyncio.wait_for(self.inventory_now.wait(), 1800) + except asyncio.TimeoutError: + pass + self.inventory_now.clear() + if self.stop.is_set(): + return + try: + await self.inventory.maybe_send(self.client) + except Exception as e: + log.warning("inventory: %s", e) + + # -- windows and uplink ----------------------------------------------- + def close_window(self, end: float): + start = self.agg.start + records = self.agg.flush(end) + if not records: + return + seq = self.queue.put("tel", { + "window_start": start, "window_end": end, "mapping_version": self.mapping.version, + # partial: the agent started or stopped inside this window + "partial": start < self.started or end - start < self.cfg.interval_s, + "records": records}) + log.info("window %s queued as %d (%d records; queue %d, dropped %d)", + time.strftime("%H:%M", time.gmtime(start)), seq, len(records), + self.queue.depth(), self.queue.dropped()) + + async def ticker(self): + i = self.cfg.interval_s + while not self.stop.is_set(): + end = self.agg.start + i + try: + await asyncio.wait_for(self.stop.wait(), max(0.0, end - time.time())) + except asyncio.TimeoutError: + self.close_window(end) + + async def uploader(self): + wait = 1.0 + while not self.stop.is_set(): + failed = False + if not self.consent.share and self.queue.depth(): + log.info("no consent: %d queued batches deleted, not sent", self.queue.depth()) + self.queue.clear() # the switch may have changed in the file (the panel) + for seq, kind, payload in self.queue.peek(50): + if not await self.sink.send(seq, kind, payload): + failed = True # keep order: nothing after it goes first + break + self.queue.ack(seq) + self.last_sent = time.time() + # back off while the uplink is down (1 s doubling to 60 s) + wait = min(wait * 2, 60) if failed else 1.0 + try: + await asyncio.wait_for(self.stop.wait(), wait) + except asyncio.TimeoutError: + pass + + async def run(self): + self.started = time.time() + self.agg.begin(self.started) + if self.cfg.mode == "off": + log.info("mode off: not reading Home Assistant") + await self.stop.wait() + return + tasks = [asyncio.create_task(ha.run_forever(self.cfg.ha_url, self.cfg.ha_token, self.on_connect, + self.stop)), + asyncio.create_task(self.ticker()), asyncio.create_task(self.uploader()), + asyncio.create_task(self.inventory_loop())] + if self.cfg.mqtt_host: + tasks.append(asyncio.create_task(Announcer( + self, self.cfg.mqtt_host, self.cfg.mqtt_port, username=self.cfg.mqtt_user, + password_file=self.cfg.mqtt_password_file, password=self.cfg.mqtt_password).run())) + if self.control is not None: + tasks.append(asyncio.create_task(self.control.run(self.stop))) + if self.dashboards is not None: + tasks.append(asyncio.create_task(self.dashboards.run(self.stop))) + tasks.append(asyncio.create_task(areas.run(self, self.stop))) + if self.cfg.propose: + tasks.append(asyncio.create_task(self.mapping_loop())) + if self.cfg.join_page_port: + # the add-on's pages: Devices (HA's devices a profile knows) and + # Building or community + page = App(Fleet(self.cfg.state_dir, site_id=self.cfg.site_id), + Devices(self.cfg.mapping, self.cfg.state_dir, self.profiles or propose.load_profiles(), + ha=lambda: self.client, changed=self.devices_changed)) + tasks.append(asyncio.create_task(page.run(self.cfg.join_page_port, self.stop))) + await self.stop.wait() + self.inventory_now.set() + self.close_window(time.time()) # the open window, marked partial by its end + await asyncio.gather(*tasks, return_exceptions=True) + # last chance to send what is queued; the rest waits on disk + for seq, kind, payload in self.queue.peek(50) if self.consent.share else (): + if not await self.sink.send(seq, kind, payload): + break + self.queue.ack(seq) + await self.sink.close() + log.info("stopped; %d batches stay queued", self.queue.depth()) + + +def open_queue(cfg) -> Queue: + os.makedirs(cfg.state_dir, exist_ok=True) + return Queue(os.path.join(cfg.state_dir, "queue.db"), cfg.queue_max) + + +def build(cfg) -> Agent: + return Agent(cfg, Mapping.load(cfg.mapping), open_queue(cfg), sinks.make(cfg)) diff --git a/src/edge/cantabile_edge/announce.py b/src/edge/cantabile_edge/announce.py new file mode 100644 index 0000000..56cae8a --- /dev/null +++ b/src/edge/cantabile_edge/announce.py @@ -0,0 +1,441 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The agent in Home Assistant, through MQTT discovery: a device +"Cantabile" (one per site) under HA's MQTT integration, in the area +"Cantabile" (suggested_area, in HA's language: names.py), with +availability (offline when the agent stops: MQTT's last will, or said +before a clean stop). Read only: nothing in HA changes the agent; the +owner's consent is given in the box's setup wizard and panel only (sensitive). + +What it shows (what goes between the cloud or the +building and the home, and what the agent does to each device): + binary_sensor cloud the link's connection to the platform + sensor control_mode, next_action, plan_ + (controls by their names: the mapping's `name`, + else the id in words) + the plan, in advisory and auto (in shadow and + off taken out of HA again: an empty retained config) + sensor price_import_now, price_import_next, price_export_now, price_ + the tariff in force, its 48 h curve as attributes + sensor model the forecast model (source, issued, expires) + event commands each command or bundle received: mode, control, + release, limits, tariff, model, building; who + sent it (cloud, building, grid), its arguments + (no signatures or proofs), applied or refused and why + sensor received the last 10 of them as a list (attribute commands: + at, what in words, by, result, why), kept across + restarts (the dashboard's "Commands received") + sensor set_ per control: the value the agent wants it at now + and from whom (plan, cloud, building, owner, safe + default), whether it acts, the limits per level +On a building's own box (flats.json, a signed `flats` bundle from the +cloud: bundles.py) each flat is a device of its own ("Flat", via the +building's Cantabile device, area "Flats"): its grid power, its +flexibility, the building's requests to it. + +Topics: homeassistant//cantabile_[_flat_]//config +(retained); cantabile//state, /availability, /plan, /tariff, /model, +/actuators, /command (not retained), /flat/. + +On the Cantabile Hub the broker is Mosquitto on the box (127.0.0.1:1883, with +the agent's own user: hub mqtt-users); without a broker this does nothing. +""" +import asyncio +import time +import json +import logging +import re + +from . import gridorder +from . import __version__ +from . import names, shades +from .bundles import Bundles +from .mqtt import Client + +log = logging.getLogger(__name__) +INTERVAL = 30 # state at least this often (seconds) +RETIRED = (("switch", "share"), ("sensor", "queued"), ("sensor", "last_sent"), ("sensor", "mode")) +RECEIVED = 10 # commands listed in HA (sensor received) +COMMANDS = ("mode", "control", "release", "limits", "tariff", "model", "building") +MAX_FLATS = 200 + + +def _slug(s: str) -> str: + return re.sub(r"[^a-z0-9_]", "_", str(s).lower())[:48] + + +class Announcer: + def __init__(self, agent, host: str, port: int, prefix: str = "homeassistant", + username: str = "", password_file: str = "", password: str = ""): + self.agent, self.host, self.port, self.prefix = agent, host, port, prefix + self.username, self.password_file, self.password = username, password_file, password + site = agent.cfg.site_id + self.site = site + self.base = f"cantabile/{site}" + self.uid = f"cantabile_{site}" + self.client = None + self.changed = asyncio.Event() + self.sent: dict[tuple, str] = {} # (node, component, object) -> config sent (JSON) + ctl = getattr(agent, "control", None) + self.bundles = ctl.bundles if ctl is not None else Bundles(agent.cfg.state_dir, site) + if ctl is not None: + ctl.on_plan.append(self._planned) + ctl.on_received.append(self._received) + + @property + def lang(self) -> str: + return getattr(self.agent, "ha_language", None) or "en" + + async def _planned(self, plan): + self.changed.set() + + async def _received(self, ev: dict): + """A command or bundle arrived: an event in HA now.""" + if self.client is not None and not self.client.closed.is_set(): + try: + await self.client.publish(f"{self.base}/command", + json.dumps({"event_type": ev["cmd"], **{k: v for k, v in ev.items() + if k != "cmd"}})) + except Exception as e: + log.info("mqtt: command event not shown: %s", e) + self.changed.set() + + # -- what HA should have ------------------------------------------------- + def _device(self): + return {"identifiers": [self.uid], "name": "Cantabile", "manufacturer": "Cantabile", + "model": "Edge Agent", "sw_version": __version__, + "suggested_area": names.area("cantabile", self.lang)} + + def _avail(self): + return {"availability_topic": f"{self.base}/availability"} + + def _configs(self): + """The agent's own entities: always there.""" + return { + ("binary_sensor", "cloud"): { + "name": names.name("cloud", self.lang), + "unique_id": f"{self.uid}_cloud", "device_class": "connectivity", + "state_topic": f"{self.base}/state", "value_template": "{{ value_json.cloud }}", + "payload_on": "on", "payload_off": "off", **self._avail(), "device": self._device()}, + } + + def _plan_objects(self) -> dict: + """The plan's entities, when the mode shows them (advisory, auto).""" + ctl = getattr(self.agent, "control", None) + if ctl is None or ctl.mode() not in ("advisory", "auto"): + return {} + common = {"state_topic": f"{self.base}/plan", **self._avail(), "device": self._device()} + out = {("sensor", "control_mode"): {"name": names.name("mode", self.lang), + "unique_id": f"{self.uid}_control_mode", + "value_template": "{{ value_json.mode }}", **common}, + ("sensor", "next_action"): {"name": names.name("next_action", self.lang), + "unique_id": f"{self.uid}_next_action", + "value_template": "{{ value_json.next }}", + "json_attributes_topic": f"{self.base}/plan", + "json_attributes_template": "{{ value_json.attrs | tojson }}", + **common}} + for c in ctl.controls: + out[("sensor", f"plan_{c.id}")] = { + "name": names.name("plan", self.lang, c.label()), "unique_id": f"{self.uid}_plan_{c.id}", + "value_template": "{{ value_json.controls['%s'].now }}" % c.id, + "json_attributes_topic": f"{self.base}/plan", + "json_attributes_template": "{{ value_json.controls['%s'] | tojson }}" % c.id, **common} + return out + + def _exchange_objects(self, tariff: dict | None, model: dict | None) -> dict: + """What came from the cloud or the building, and the agent's wish per + control: in every mode but off.""" + ctl = getattr(self.agent, "control", None) + dev, out = self._device(), {} + if ctl is not None and ctl.mode() == "off": + return out + if tariff is not None: + # In /kWh, as HA's Energy dashboard takes a price + # (dashboards.py; ct/kWh it would not take), shown with 3 + # decimals (0.167 EUR/kWh); the bundle's ct/kWh curve as + # attributes. The dashboard shows ct/kWh. + t = {"state_topic": f"{self.base}/tariff", "unit_of_measurement": f"{tariff['currency']}/kWh", + "suggested_display_precision": 3, "state_class": "measurement", "icon": "mdi:cash", **self._avail(), "device": dev, + "json_attributes_topic": f"{self.base}/tariff", + "json_attributes_template": "{{ value_json.curve | tojson }}"} + + def per_kwh(path): + return ("{% set v = value_json." + path + " %}" + "{{ (v / 100) | round(4) if v is not none else none }}") + out[("sensor", "price_import_now")] = {"name": names.name("price_import_now", self.lang), + "unique_id": f"{self.uid}_price_import_now", + "value_template": per_kwh("import_now"), **t} + out[("sensor", "price_import_next")] = {"name": names.name("price_import_next", self.lang), + "unique_id": f"{self.uid}_price_import_next", + "value_template": per_kwh("import_next"), **t} + if any(x is not None for x in tariff["curve"].get("export") or []): + out[("sensor", "price_export_now")] = {"name": names.name("price_export_now", self.lang), + "unique_id": f"{self.uid}_price_export_now", + "value_template": per_kwh("export_now"), **t} + for carrier in sorted(tariff.get("other") or {})[:8]: + k = _slug(carrier) + out[("sensor", f"price_{k}")] = { + "name": names.name("price_other", self.lang, carrier), "unique_id": f"{self.uid}_price_{k}", + "value_template": per_kwh("other['%s']" % carrier), **t} + if model is not None: + out[("sensor", "model")] = {"name": names.name("model", self.lang), "unique_id": f"{self.uid}_model", + "state_topic": f"{self.base}/model", "icon": "mdi:chart-bell-curve", + "value_template": "{{ value_json.source }}", + "json_attributes_topic": f"{self.base}/model", **self._avail(), "device": dev} + if ctl is not None: + out[("event", "commands")] = {"name": names.name("commands", self.lang), "unique_id": f"{self.uid}_commands", + "state_topic": f"{self.base}/command", "event_types": list(COMMANDS), + "icon": "mdi:message-arrow-left", **self._avail(), "device": dev} + # the last commands as a list (the event entity has only the + # last one, and goes unknown at each restart): the dashboard's + out[("sensor", "received")] = {"name": names.name("received", self.lang), "unique_id": f"{self.uid}_received", + "state_topic": f"{self.base}/received", "icon": "mdi:message-arrow-left", + "value_template": "{{ value_json.commands | count }}", + "json_attributes_topic": f"{self.base}/received", + "json_attributes_template": "{{ {'commands': value_json.commands} | tojson }}", + "device": dev} + for c in ctl.controls: + out[("sensor", f"set_{c.id}")] = { + "name": names.name("commanded", self.lang, c.label()), "unique_id": f"{self.uid}_set_{c.id}", + "state_topic": f"{self.base}/actuators", "icon": "mdi:tune-variant", + "value_template": "{{ value_json['%s'].value }}" % c.id, + "json_attributes_topic": f"{self.base}/actuators", + "json_attributes_template": "{{ value_json['%s'] | tojson }}" % c.id, + **self._avail(), "device": dev} + return out + + def _flat_objects(self, flats: list[dict]) -> dict: + """Each flat of the building a device of its own (node: the flat).""" + out = {} + for f in flats[:MAX_FLATS]: + fid = _slug(f["id"]) + node = f"{self.uid}_flat_{fid}" + dev = {"identifiers": [node], "name": f.get("label") or f["id"], "manufacturer": "Cantabile", + "model": "Flat", "via_device": self.uid, "suggested_area": names.area("flats", self.lang)} + common = {"state_topic": f"{self.base}/flat/{fid}", **self._avail(), "device": dev} + out[(node, "sensor", "grid")] = { + "name": names.name("flat_grid", self.lang), "unique_id": f"{node}_grid", + "value_template": "{{ value_json.grid_w }}", "unit_of_measurement": "W", "device_class": "power", + "state_class": "measurement", "json_attributes_topic": f"{self.base}/flat/{fid}", + "json_attributes_template": "{{ value_json.state | tojson }}", **common} + out[(node, "sensor", "flex")] = { + "name": names.name("flat_flex", self.lang), "unique_id": f"{node}_flex", + "value_template": "{{ value_json.flex_now }}", "unit_of_measurement": "W", "device_class": "power", + "state_class": "measurement", "json_attributes_topic": f"{self.base}/flat/{fid}", + "json_attributes_template": "{{ value_json.flex | tojson }}", **common} + out[(node, "sensor", "request")] = { + "name": names.name("flat_request", self.lang), "unique_id": f"{node}_request", + "value_template": "{{ value_json.request }}", "icon": "mdi:office-building", + "json_attributes_topic": f"{self.base}/flat/{fid}", + "json_attributes_template": "{{ {'commands': value_json.commands} | tojson }}", **common} + return out + + def objects(self) -> dict: + """Every discovery config HA should have now: (node, component, + object) -> config; node is the site's or a flat's.""" + now = time.time() + tariff, model = self.bundles.tariff_now(now), self.bundles.model_info() + out = {} + for (comp, obj), conf in {**self._configs(), **self._plan_objects(), + **self._exchange_objects(tariff, model)}.items(): + out[(self.uid, comp, obj)] = conf + out.update(self._flat_objects(self.bundles.flat_list())) + # The entity ids themselves (HA 2025.10+): without them HA makes them + # from the device's and the entity's names, which gave + # binary_sensor.cantabile_cantabile_cloud on 0.3.0's check; ids stay + # the same in every language. A flat's: cantabile_flat__. + for (node, comp, obj), conf in out.items(): + prefix = "cantabile" + node[len(self.uid):] + conf.setdefault("default_entity_id", f"{comp}.{prefix}_{obj}") + return out + + # -- state --------------------------------------------------------------- + def _plan_state(self) -> dict: + ctl = self.agent.control + plan, now = ctl.plan or {}, time.time() + nxt, upcoming, per = "no plan yet", [], {} + kinds = {c.id: c.kind for c in ctl.controls} + for cid, entries in (plan.get("devices") or {}).items(): + cur = None + future = [] + for e in entries: + if e["t"] <= now: + cur = e + elif e.get("set") is not None: # a shade's hold between its moves: nothing to do + future.append(e) + if kinds.get(cid) == "cover": + # a shade's moves in words: "close to 30 %", "open" + future = [dict(e, set=shades.say(e["set"], self.lang), why=shades.why_words(e["why"], self.lang)) + for e in future] + per[cid] = {"now": str("-" if (cur or {}).get("set") is None else cur["set"]), "why": (cur or {}).get("why", ""), + "next": [{"at": time.strftime("%H:%M", time.localtime(e["t"])), "set": e["set"], + "why": e["why"]} for e in future[:12]]} + upcoming += [(e["t"], cid, e) for e in future[:3]] + for c in ctl.controls: + per.setdefault(c.id, {"now": "-", "why": "", "next": []}) + upcoming.sort(key=lambda x: x[0]) + label = {c.id: c.label() for c in ctl.controls} + if upcoming: + t, cid, e = upcoming[0] + when = time.strftime('%H:%M', time.localtime(t)) + nxt = (f"{label.get(cid, cid)}: {e['set']} at {when} — {e['why']}" if kinds.get(cid) == "cover" else + f"{label.get(cid, cid)}: {e['set']} at {when} ({e['why']})")[:250] + attrs = {"next": [{"at": time.strftime("%H:%M", time.localtime(t)), "control": cid, + "name": label.get(cid, cid), "set": e["set"], "why": e["why"]} + for t, cid, e in upcoming[:10]], + "cost_eur": plan.get("cost_eur"), "baseline_eur": plan.get("baseline_eur"), + "prices": plan.get("price_note", ""), "made": plan.get("made")} + return {"mode": ctl.mode(), "next": nxt, "attrs": attrs, "controls": per} + + def received_list(self, ctl) -> list[dict]: + """The last commands, newest first, as people read them: when, what + (the control's name, not its id), from whom, applied or refused and + why.""" + label = {c.id: c.label() for c in ctl.controls} + out = [] + for ev in reversed(ctl.received[-RECEIVED:]): + a = ev.get("args") or {} + cid = a.get("asset", "") + what = names.name(f"cmd_{ev['cmd']}", self.lang, label.get(cid, cid), a.get("set", ""), + a.get("mode", "")) if f"cmd_{ev['cmd']}" in names.NAMES else ev["cmd"] + out.append({"at": ev["at"], "what": what.strip(), "by": ev.get("by", ""), "result": ev.get("result", ""), + "why": str(ev.get("why", ""))[:120]}) + return out + + @staticmethod + def flat_state(f: dict, now: float) -> dict: + """A flat's values for HA: grid power, the flexibility now and its + curve, the building's requests in force (a short summary).""" + st = dict(f.get("state") or {}) + flex = f.get("flex") or {} + shed = flex.get("shed_w") or [] + k = int((now - flex["start"]) // flex.get("step_s", 900)) if flex.get("start") else 0 + cmds = [c for c in f.get("commands") or [] if not c.get("until") or c["until"] > now][:10] + req = "; ".join(f"{c.get('control')} {c.get('value')} ({c.get('level')})" for c in cmds)[:250] or "none" + return {"grid_w": st.get("grid_w"), "state": st, "flex_now": shed[k] if 0 <= k < len(shed) else None, + "flex": flex, "request": req, "commands": cmds} + + async def _states(self): + c, now = self.client, time.time() + st = {"cloud": "on" if await self.agent.cloud() else "off"} + await c.publish(f"{self.base}/state", json.dumps(st), retain=True) + ctl = getattr(self.agent, "control", None) + if ctl is not None and ctl.mode() in ("advisory", "auto"): + await c.publish(f"{self.base}/plan", json.dumps(self._plan_state()), retain=True) + tariff = self.bundles.tariff_now(now) + if tariff is not None: + await c.publish(f"{self.base}/tariff", json.dumps(tariff), retain=True) + model = self.bundles.model_info() + if model is not None: + await c.publish(f"{self.base}/model", json.dumps(model), retain=True) + if ctl is not None and ctl.mode() != "off": + await c.publish(f"{self.base}/actuators", json.dumps(ctl.actuators(), default=str), retain=True) + if ctl is not None and ctl.received: + # kept (retained) across restarts until new ones come + await c.publish(f"{self.base}/received", json.dumps({"commands": self.received_list(ctl)}), retain=True) + for f in self.bundles.flat_list()[:MAX_FLATS]: + await c.publish(f"{self.base}/flat/{_slug(f['id'])}", json.dumps(self.flat_state(f, now)), retain=True) + + async def _sync(self): + """Configs in or out of HA as they should be now, then the states.""" + want = {k: json.dumps(v, sort_keys=True) for k, v in self.objects().items()} + for key in set(self.sent) - set(want): + node, component, obj = key + await self.client.publish(f"{self.prefix}/{component}/{node}/{obj}/config", b"", retain=True) + del self.sent[key] + for key, conf in want.items(): + if self.sent.get(key) != conf: + node, component, obj = key + await self.client.publish(f"{self.prefix}/{component}/{node}/{obj}/config", conf, retain=True) + self.sent[key] = conf + await self._states() + + async def _retained(self, c, wait: float = 1.0) -> dict: + """The retained discovery configs of this site's nodes (its own and + its flats'), read for a moment after subscribing.""" + found: dict[tuple, str] = {} + pat = re.compile(rf"^{re.escape(self.prefix)}/([^/]+)/({re.escape(self.uid)}(?:_flat_[a-z0-9_]+)?)/([^/]+)/config$") + + def on(topic, payload): + m = pat.match(topic) + if m and payload: + found[(m.group(2), m.group(1), m.group(3))] = payload.decode(errors="replace") + c.on_message = on + try: + await c.subscribe(f"{self.prefix}/+/+/+/config") + await asyncio.sleep(wait) + except Exception as e: + log.info("mqtt: earlier configs not read: %s", e) + c.on_message = None + return found + + async def _grid_orders(self, c): + """The EEBUS bridge's grid order (gridorder.py), to the + controller: the grid operator's limit as a higher-rank decision.""" + ctl = getattr(self.agent, "control", None) + if ctl is None: + return + + def on(topic, payload): + if topic == gridorder.TOPIC and payload: + asyncio.ensure_future(ctl.grid_order(payload)) + c.on_message = on + try: + await c.subscribe(gridorder.TOPIC) + except Exception as e: + log.info("mqtt: grid orders not subscribed: %s", e) + + def _password(self) -> str: + if self.password_file: + try: + with open(self.password_file) as f: + return f.read().strip() + except OSError: + return "" + return self.password + + async def _session(self): + c = self.client = Client(self.host, self.port, f"cantabile-edge-{self.site[:12]}", + username=self.username, password=self._password()) + await c.connect(f"{self.base}/availability", b"offline") + # Entities of earlier builds (the consent switch, diagnostics): gone from HA. + for component, obj in RETIRED: + await c.publish(f"{self.prefix}/{component}/{self.uid}/{obj}/config", b"", retain=True) + await c.publish(f"{self.base}/share", b"", retain=True) + # What the broker keeps from earlier sessions (retained configs of + # this site and its flats): anything not wanted now is taken out, + # the rest sent again (HA may have restarted). + self.sent = await self._retained(c) + for key in self.sent: + self.sent[key] = "" + await self._sync() + await c.publish(f"{self.base}/availability", "online", retain=True) + log.info("in Home Assistant through MQTT discovery (%s:%d)", self.host, self.port) + await self._grid_orders(c) + while not c.closed.is_set() and not self.agent.stop.is_set(): + self.changed.clear() + waits = [asyncio.create_task(e.wait()) for e in (self.changed, c.closed, self.agent.stop)] + await asyncio.wait(waits, timeout=INTERVAL, return_when=asyncio.FIRST_COMPLETED) + for t in waits: + t.cancel() + if not c.closed.is_set() and not self.agent.stop.is_set(): + await self._sync() + + async def run(self): + wait = 2.0 + while not self.agent.stop.is_set(): + try: + await self._session() + wait = 2.0 + except Exception as e: + log.warning("mqtt %s:%d: %s", self.host, self.port, str(e) or type(e).__name__) + if self.client is not None: + if self.agent.stop.is_set(): + try: # a clean stop sends no last will: say it + await self.client.publish(f"{self.base}/availability", "offline", retain=True) + except Exception: + pass + await self.client.close() + try: + await asyncio.wait_for(self.agent.stop.wait(), wait) + except asyncio.TimeoutError: + wait = min(wait * 2, 60) diff --git a/src/edge/cantabile_edge/areas.py b/src/edge/cantabile_edge/areas.py new file mode 100644 index 0000000..51a6e03 --- /dev/null +++ b/src/edge/cantabile_edge/areas.py @@ -0,0 +1,75 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Cantabile's devices in HA's area "Cantabile" (part of +installing and of moving a site onto Cantabile). MQTT discovery's +suggested_area only places a device when HA first makes it, so this places +what came before, or what came without the hint: the agent's own device, +the Modbus and EEBUS bridges' devices (identifiers cantabile_modbus_*, +cantabile_eebus_*) and Cantabile's +HA add-ons (the Supervisor's devices, slugs *cantabile_*), and on an HA +add-on site the devices the owner uses with Cantabile on its Devices page +(devpage.py; /devices.json). A device the owner put in an area +stays there (a thermostat in its room keeps its room); the flats keep their own area. At connecting, +then every EVERY_S.""" +import asyncio +import json +import logging +import os + +from . import names + +log = logging.getLogger(__name__) + +EVERY_S = 600 + + +def used(state_dir: str) -> set: + """The HA devices the owner uses with Cantabile (the add-on's Devices page).""" + try: + with open(os.path.join(state_dir, "devices.json")) as f: + devs = json.load(f) + except (OSError, ValueError): + return set() + return {d.get("ha_device") for d in (devs.values() if isinstance(devs, dict) else []) if isinstance(d, dict)} - {None} + + +def ours(d: dict, uid: str, used_ids=()) -> bool: + """A device Cantabile made (the agent's, the bridge's or an add-on's) or + one the owner uses with it.""" + if d.get("id") in used_ids: + return True + for domain, ident in (tuple(i) for i in d.get("identifiers") or [] if len(i) == 2): + if domain == "mqtt" and (ident == uid or str(ident).startswith(("cantabile_modbus_", "cantabile_eebus_"))): + return True + if domain == "hassio" and "cantabile_" in str(ident): + return True + return False + + +async def place(client, uid: str, language: str | None, used_ids=()) -> int: + """Puts our devices without an area into "Cantabile" (made if missing); + how many it moved.""" + devices = [d for d in await client.send("config/device_registry/list") or [] + if ours(d, uid, used_ids) and not d.get("area_id")] + if not devices: + return 0 + name = names.area("cantabile", language) + areas = await client.send("config/area_registry/list") or [] + a = next((x for x in areas if x.get("name") == name), None) or await client.create_area(name, "mdi:leaf") + for d in devices: + await client.place_device(d["id"], a["area_id"]) + log.info("%s put in the area %s", d.get("name_by_user") or d.get("name"), name) + return len(devices) + + +async def run(agent, stop: asyncio.Event): + while not stop.is_set(): + if agent.client is not None: + try: + await place(agent.client, f"cantabile_{agent.cfg.site_id}", getattr(agent, "ha_language", "en"), + used(agent.cfg.state_dir)) + except Exception as e: + log.warning("areas: %s", e) + try: # soon after starting (HA not connected yet), then every EVERY_S + await asyncio.wait_for(stop.wait(), EVERY_S if agent.client is not None else 30) + except asyncio.TimeoutError: + pass diff --git a/src/edge/cantabile_edge/backfill.py b/src/edge/cantabile_edge/backfill.py new file mode 100644 index 0000000..470ad6a --- /dev/null +++ b/src/edge/cantabile_edge/backfill.py @@ -0,0 +1,64 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""History backfill: HA's long-term statistics (hourly mean/min/max for +gauges, the running sum for counters) for consented assets, queued as +"stats" batches and sent like telemetry. Chunks of a week keep each HA +answer and each batch small.""" +import logging +from datetime import datetime, timedelta, timezone + +from .agent import number +from .ha import HAClient +from .mapping import convert, scaled + +log = logging.getLogger(__name__) +CHUNK = timedelta(days=7) + + +def _ts(v) -> float: + # HA sends epoch milliseconds (newer) or ISO strings (older) + if isinstance(v, (int, float)): + return v / 1000 + return datetime.fromisoformat(v).timestamp() + + +async def backfill(client: HAClient, mapping, queue, since: datetime, until: datetime, + period: str = "hour") -> int: + """period: hour (kept for ever) or 5minute (HA keeps those ~10 days).""" + assets = {a.entity: a for a in mapping.assets if a.consent} + meta = await client.send("recorder/list_statistic_ids") # no type: both mean and sum + units = {m["statistic_id"]: m.get("statistics_unit_of_measurement") for m in meta} + ids = [e for e in assets if e in units] + log.info("backfill %d of %d consented entities have statistics", len(ids), len(assets)) + batches, start = 0, since + while start < until and ids: + end = min(start + CHUNK, until) + res = await client.send("recorder/statistics_during_period", timeout=300, + start_time=start.isoformat(), end_time=end.isoformat(), + statistic_ids=ids, period=period, + types=["mean", "min", "max", "sum", "state"]) + records = [] + for eid, rows in sorted((res or {}).items()): + a, unit = assets[eid], units.get(eid) + out = [] + for r in rows: + row = {"start": _ts(r["start"])} + for k in (("sum", "state") if a.kind == "counter" else ("mean", "min", "max")): + v = number(r.get(k)) + row[k] = None if v is None else scaled(convert(v, unit, a.unit), a) + out.append(row) + records.append({"asset": a.asset, "kind": a.kind, "rows": out}) + if records: + queue.put("stats", {"period": period, "window_start": start.timestamp(), + "window_end": end.timestamp(), "mapping_version": mapping.version, + "records": records}) + batches += 1 + start = end + return batches + + +def parse_since(s: str) -> datetime: + """An ISO date/time (UTC unless it says otherwise) or days back, e.g. 30d.""" + if s.endswith("d") and s[:-1].isdigit(): + return datetime.now(timezone.utc) - timedelta(days=int(s[:-1])) + d = datetime.fromisoformat(s) + return d if d.tzinfo else d.replace(tzinfo=timezone.utc) diff --git a/src/edge/cantabile_edge/building.py b/src/edge/cantabile_edge/building.py new file mode 100644 index 0000000..5e34699 --- /dev/null +++ b/src/edge/cantabile_edge/building.py @@ -0,0 +1,151 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The building's requests to this flat (agreed with the building side, +2026-10-28). Fleet sends a signed command `building` (the link checks it +like every command) with string args: + + {"v": "1", "id", "building", "level": "flexible|binding", + "control": "load_limit|shift_request|thermostat_cap", "value", + "from": unix, "until": unix (<= from + 24 h), "why"} + + load_limit the flat's highest grid import, W, in [from, until) + shift_request kWh the flat is asked to move out of [from, until): the + optimiser decides how and where (a soft target) + thermostat_cap the highest heating setpoint, °C (cooling: the lowest) + +Rules: always within the flat's own floors (a cap below the comfort floor +of the owner or the tenant is refused: "floor"); a newer command for the +same control replaces the older; each is dropped at `until`. The level sits +in the 3b ladder: binding, the flat's owner cannot lift it (applied again); +flexible, the owner's change by hand ends it. Everything else is in each +command. Kept in /building.json across restarts. + +Membership (2026-10-29, joining a building): the Hub's panel writes +/membership.json {"buildings": [ids]} after the owner joined +or left (the buildings and communities this site belongs to, and the +building whose own box it is; /usr/lib/cantabile/building). With it, a +command from any other building is refused ("not a member"), besides +fleet's own check. Without it (an HA add-on, an older panel), fleet's +check alone decides. + +The optimiser takes them as constraints (a cap, a limit: binding nearly +hard, flexible with a price) and a soft target (a shift). Results go out as +`action` messages with entity "building:", service +"building.". +""" +import json +import os +import time + +CONTROLS = ("load_limit", "shift_request", "thermostat_cap") +PENALTY = { # EUR per unit across a building's request in the plan + "binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0}, # per kWh, per kWh, per K·h + "flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0}, + # a grid operator's order relayed by the building (§14a), with proof the + # link checked (edge/link/gridorder.go): nobody overrides it + "emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0}, +} + + +class Building: + def __init__(self, state_dir: str, clock=time.time): + self.path, self.clock = os.path.join(state_dir, "building.json"), clock + self.membership_path = os.path.join(state_dir, "membership.json") + self.active: dict[str, dict] = {} # control -> the command's args (parsed) + try: + with open(self.path) as f: + self.active = {k: v for k, v in json.load(f).items() if k in CONTROLS} + except (OSError, ValueError, AttributeError): + pass + self.drop_ended() + + def memberships(self) -> set[str] | None: + """The buildings this site belongs to (membership.json), or None + when the panel wrote none.""" + try: + with open(self.membership_path) as f: + ids = json.load(f).get("buildings") + except (OSError, ValueError, AttributeError): + return None + return {str(i) for i in ids} if isinstance(ids, list) else None + + def _save(self): + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(self.active, f) + os.replace(tmp, self.path) + + def drop_ended(self) -> list[dict]: + now = self.clock() + ended = [c for c in self.active.values() if now >= c["until"]] + if ended: + self.active = {k: c for k, c in self.active.items() if now < c["until"]} + self._save() + return ended + + @staticmethod + def parse(a: dict) -> dict: + try: + c = {"id": a["id"], "building": a["building"], "level": a.get("level", "flexible"), + "control": a["control"], "value": float(a["value"]), "from": int(float(a["from"])), + "until": int(float(a["until"])), "why": a.get("why", "")[:120], "proof": a.get("proof", "")} + except (KeyError, ValueError, TypeError) as e: + raise ValueError(f"building: {e} (id, building, control, value, from, until needed)") + if str(a.get("v", "1")) != "1": + raise ValueError("building: v 1 only") + if c["level"] not in ("flexible", "binding", "emergency"): + raise ValueError("building: level flexible, binding or emergency") + if c["level"] == "emergency" and not (c["proof"].startswith("verified:") and c["control"] == "load_limit"): + # only a grid operator's order the link verified (2026-10-29) + raise ValueError("building: an emergency needs the grid operator's verified proof (a relayed load_limit)") + if c["control"] not in CONTROLS: + raise ValueError(f"building: control one of {', '.join(CONTROLS)}") + if not c["from"] < c["until"] <= c["from"] + 86400: + raise ValueError("building: from < until <= from + 24 h") + if c["control"] in ("load_limit", "shift_request") and c["value"] < 0: + raise ValueError(f"building: {c['control']} must not be negative") + return c + + def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]: + """A parsed command. floors: (control id, the flat's floor, the + flat's limit, kind) of each heating/cooling room, for the cap.""" + if self.clock() >= c["until"]: + return False, "already over" + members = self.memberships() + if members is not None and c["building"] not in members: + return False, "not a member of that building" + if c["control"] == "thermostat_cap": + for cid, lo, hi, kind in floors: + if kind == "heating" and c["value"] < lo: + return False, f"floor: {cid}'s comfort floor is {lo:g} °C, the cap {c['value']:g} °C" + if kind == "cooling" and c["value"] > hi: + return False, f"floor: {cid}'s limit is {hi:g} °C, the cap {c['value']:g} °C" + old = self.active.get(c["control"]) + self.active[c["control"]] = c + self._save() + replaced = f" (replaces {old['id']})" if old and old["id"] != c["id"] else "" + return True, f"{c['control']} {c['value']:g} {c['level']} until {time.strftime('%H:%M UTC', time.gmtime(c['until']))}{replaced}" + + def lift(self, control: str): + """The owner overrode a flexible request: it ends.""" + if self.active.pop(control, None) is not None: + self._save() + + def for_model(self, start: int, step_s: int, steps: int) -> dict: + """The requests as the optimiser takes them: per step, or a window.""" + self.drop_ended() + out = {} + for ctl, c in self.active.items(): + a = max(0, (c["from"] - start) // step_s) + b = min(steps, -(-(c["until"] - start) // step_s)) + if a >= b: + continue + out[ctl] = {"value": c["value"], "level": c["level"], "from_step": int(a), "to_step": int(b), + "penalty": PENALTY[c["level"]][ctl], "id": c["id"], "building": c["building"]} + return out + + def cap(self, kind: str, now: float) -> tuple[float | None, dict | None]: + """The thermostat cap in force now for a heating/cooling room.""" + c = self.active.get("thermostat_cap") + if c and c["from"] <= now < c["until"] and kind in ("heating", "cooling"): + return c["value"], c + return None, None diff --git a/src/edge/cantabile_edge/bundles.py b/src/edge/cantabile_edge/bundles.py new file mode 100644 index 0000000..73db879 --- /dev/null +++ b/src/edge/cantabile_edge/bundles.py @@ -0,0 +1,209 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Data bundles the optimiser reads: tariffs and the forecast model. + +Both arrive as signed commands; the link checks the signature with the +bundle key, the kind, site and expiry, keeps only the newest, and writes the +JSON into the state directory (edge/link/bundles.go). Here they are read +(again when the file changes), their form checked, and turned into series +for the planning horizon. Data only: nothing in a bundle is ever run. + +Tariff v1 (agreed with the cloud side, 2026-10-28): + {"v":1, "kind":"tariff", "id", "site", "issued", "start": , "step_s": 900, "steps": 192, "expires", "currency": "EUR", + "unit": "ct/kWh", "import": [192 numbers|null], "export": [...], + "estimated": [indexes], "other": {...}, "sources": [...]} + After `expires` (or outside its steps): the last known flat price (the + mean of its import prices), and the plan says so. Without any tariff: + the configured default price. + +Model v1 (the forecasts' data; the ML in ml/ is a placeholder, 2026-10-28): + {"v":1, "kind":"model", "id", "site" (or "*"), "issued", "expires"?, + "forecasts": {"load_w": {"profile": "hour_of_week", "values": [168]}, + "pv_w": {"profile": "hour_of_week", "values": [168]}}, + "source": "..."} + hour_of_week = weekday (Monday 0) * 24 + hour, in the site's time zone. + Without a model (or a series): the same quarter hour yesterday from the + agent's own history (inputs.History), else 0. +""" +import json +import logging +import os +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from zoneinfo import ZoneInfo + +log = logging.getLogger(__name__) + + +class _File: + """A JSON file re-read when it changes (inode, mtime, size).""" + + def __init__(self, path: str, check): + self.path, self.check = path, check + self._key, self.data, self.error = None, None, "" + + def stamp(self): + """The file's identity now (inode, mtime, size), or None: cheap, to + notice a new bundle without reading it.""" + try: + st = os.stat(self.path) + return (st.st_ino, st.st_mtime_ns, st.st_size) + except OSError: + return None + + def get(self): + try: + st = os.stat(self.path) + key = (st.st_ino, st.st_mtime_ns, st.st_size) + except OSError: + self._key, self.data, self.error = None, None, "" + return None + if key != self._key: + self._key = key + try: + with open(self.path) as f: + d = json.load(f) + self.check(d) + self.data, self.error = d, "" + except (OSError, ValueError, KeyError, TypeError) as e: + self.data, self.error = None, f"{os.path.basename(self.path)}: {e}" + log.warning("bundle refused: %s", self.error) + return self.data + + +def _check_tariff(d: dict): + if d.get("v") != 1 or d.get("kind") != "tariff": + raise ValueError("not a v1 tariff") + if int(d["step_s"]) != 900 or int(d["start"]) % 900: + raise ValueError("steps of 900 s from a quarter hour") + for k in ("import", "export"): + v = d.get(k) or [] + if not isinstance(v, list) or not all(x is None or isinstance(x, (int, float)) for x in v): + raise ValueError(f"{k}: numbers or null") + if not [x for x in d.get("import") or [] if x is not None]: + raise ValueError("no import price") + + +def _check_model(d: dict): + if d.get("v") != 1 or d.get("kind") != "model": + raise ValueError("not a v1 model") + for name, f in (d.get("forecasts") or {}).items(): + if f.get("profile") != "hour_of_week" or len(f.get("values") or []) != 168: + raise ValueError(f"{name}: an hour_of_week profile of 168 values") + if not all(isinstance(x, (int, float)) for x in f["values"]): + raise ValueError(f"{name}: numbers") + + +def _check_flats(d: dict): + """A building's flats, for the building's own box (announce.py: each + flat a device in HA). Written by the link from a signed `flats` bundle, + like a tariff; only flats whose owner granted the building operator are in it, the cloud decides that.""" + if d.get("v") != 1 or d.get("kind") != "flats": + raise ValueError("not a v1 flats bundle") + for f in d.get("flats") or []: + if not isinstance(f.get("id"), str) or not f["id"] or len(f["id"]) > 64: + raise ValueError("flat id: a string") + if not isinstance(f.get("label", ""), str): + raise ValueError("flat label: a string") + + +@dataclass +class Prices: + import_ct: list[float] + export_ct: list[float] + note: str # what the prices are ("tariff ", "flat fallback ...") + + +class Bundles: + def __init__(self, state_dir: str, site: str, default_price_ct: float = 30.0): + self.site, self.default = site, default_price_ct + self.tariff = _File(os.path.join(state_dir, "tariff.json"), _check_tariff) + self.model = _File(os.path.join(state_dir, "model.json"), _check_model) + self.flats = _File(os.path.join(state_dir, "flats.json"), _check_flats) + self.flat: float | None = None # the last known tariff's mean import price + + def stamps(self): + """The tariff's and the model's file identities: a change means a new + bundle arrived (the controller plans again at once).""" + return (self.tariff.stamp(), self.model.stamp()) + + def prices(self, start: int, step_s: int, steps: int, now: float) -> Prices: + t = self.tariff.get() + if t is not None and t.get("site") not in (self.site, None, ""): + t = None # the link refuses these; a copied file must not count either + if t is not None: + imp = [x for x in t["import"] if x is not None] + self.flat = sum(imp) / len(imp) + flat = self.flat if self.flat is not None else self.default + if t is None: + note = "no tariff yet: default price" if self.flat is None else "no tariff: last known flat price" + return Prices([flat] * steps, [0.0] * steps, note) + expired = now >= t.get("expires", 0) + out_i, out_e, outside = [], [], 0 + for k in range(steps): + i = (start + k * step_s - t["start"]) // 900 + pi = t["import"][i] if not expired and 0 <= i < len(t["import"]) else None + pe = (t.get("export") or [])[i] if not expired and 0 <= i < len(t.get("export") or []) else None + outside += pi is None + out_i.append(pi if pi is not None else flat) + out_e.append(pe if pe is not None else 0.0) + if expired: + note = f"tariff {t.get('id')} expired: flat {flat:.1f} ct/kWh" + elif outside: + note = f"tariff {t.get('id')}; {outside} of {steps} steps at the flat {flat:.1f} ct/kWh" + else: + note = f"tariff {t.get('id')}" + return Prices(out_i, out_e, note) + + def tariff_now(self, now: float) -> dict | None: + """The tariff in force for HA: import now and next step, export now, + the curves and where they come from; None without one (or expired).""" + t = self.tariff.get() + if t is None or t.get("site") not in (self.site, None, "") or now >= t.get("expires", 0): + return None + i = int((now - t["start"]) // t["step_s"]) + imp, exp = t.get("import") or [], t.get("export") or [] + + def at(v, k): + return v[k] if 0 <= k < len(v) else None + return {"import_now": at(imp, i), "import_next": at(imp, i + 1), "export_now": at(exp, i), + "other": dict(t.get("other") or {}), "currency": t.get("currency") or "EUR", + "curve": {"id": t.get("id"), "start": t["start"], "step_s": t["step_s"], "import": imp, + "export": exp, "estimated": t.get("estimated") or [], "sources": t.get("sources") or [], + "issued": t.get("issued"), "expires": t.get("expires"), "unit": t.get("unit", "ct/kWh")}} + + def model_info(self) -> dict | None: + m = self.model.get() + if m is None or m.get("site") not in (self.site, "*"): + return None + return {"id": m.get("id"), "source": m.get("source") or m.get("id"), "issued": m.get("issued"), + "expires": m.get("expires"), "series": sorted((m.get("forecasts") or {}))} + + def flat_list(self) -> list[dict]: + d = self.flats.get() + if d is None or d.get("site") not in (self.site, None, ""): + return [] + if d.get("expires") and d["expires"] <= time.time(): + return [] + return list(d.get("flats") or []) + + def forecast(self, name: str, start: int, step_s: int, steps: int, tz: str) -> list[float] | None: + """A model series for the horizon, or None (no model or no such + series: the caller falls back to history).""" + m = self.model.get() + if m is None or m.get("site") not in (self.site, "*") or (m.get("expires") and m["expires"] <= start): + return None + f = (m.get("forecasts") or {}).get(name) + if f is None: + return None + zone = ZoneInfo(tz or "UTC") + out = [] + for k in range(steps): + d = datetime.fromtimestamp(start + k * step_s, timezone.utc).astimezone(zone) + out.append(float(f["values"][d.weekday() * 24 + d.hour])) + return out + + def model_id(self) -> str: + m = self.model.get() + return m.get("id", "") if m else "" diff --git a/src/edge/cantabile_edge/cli.py b/src/edge/cantabile_edge/cli.py new file mode 100644 index 0000000..2a30b78 --- /dev/null +++ b/src/edge/cantabile_edge/cli.py @@ -0,0 +1,95 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""cantabile-edge run | suggest-mapping | backfill + +Logs go to stderr as JSON lines (stdout stays free for the stdout sink and +for the mapping draft); SIGTERM stops gracefully. +""" +import argparse +import asyncio +import json +import logging +import signal +import sys +from datetime import datetime, timezone + +import yaml + +from . import __version__, agent, config, ha, sinks +from .backfill import backfill, parse_since +from .mapping import Mapping, suggest + + +class _Json(logging.Formatter): + def format(self, r): + return json.dumps({"time": self.formatTime(r, "%Y-%m-%dT%H:%M:%S"), "level": r.levelname, + "logger": r.name, "msg": r.getMessage()}) + + +def _logging(): + h = logging.StreamHandler(sys.stderr) + h.setFormatter(_Json()) + logging.basicConfig(level=logging.INFO, handlers=[h]) + logging.getLogger("websockets").setLevel(logging.WARNING) + + +async def _run(cfg): + a = agent.build(cfg) + loop = asyncio.get_running_loop() + for s in (signal.SIGTERM, signal.SIGINT): + loop.add_signal_handler(s, a.stop.set) + logging.info("cantabile-edge %s site %s mode %s", __version__, cfg.site_id, cfg.mode) + await a.run() + return a.exit_code + + +async def _suggest(cfg): + c = ha.HAClient(cfg.ha_url, cfg.ha_token) + await c.connect() + try: + draft = suggest(await c.send("get_states"), await c.registries()) + finally: + await c.close() + print("# Mapping draft: check each asset id and kind, then set consent: true") + print("# for the assets that may leave the site.") + yaml.safe_dump(draft, sys.stdout, sort_keys=False, allow_unicode=True) + + +async def _backfill(cfg, since, until, period): + q = agent.open_queue(cfg) + c = ha.HAClient(cfg.ha_url, cfg.ha_token) + await c.connect() + try: + n = await backfill(c, Mapping.load(cfg.mapping), q, since, until, period) + finally: + await c.close() + logging.info("backfill queued %d batches; sending", n) + sink = sinks.make(cfg) + for seq, kind, payload in q.peek(1_000_000): + if not await sink.send(seq, kind, payload): + logging.warning("uplink down: %d batches stay queued for the agent", q.depth()) + break + q.ack(seq) + await sink.close() + + +def main(): + p = argparse.ArgumentParser(prog="cantabile-edge") + p.add_argument("--config", "-c", help="YAML config file") + sub = p.add_subparsers(dest="cmd", required=True) + sub.add_parser("run", help="read HA, aggregate, send (shadow mode: never acts)") + sub.add_parser("suggest-mapping", help="print a mapping draft from HA's entities") + b = sub.add_parser("backfill", help="send HA's long-term statistics") + b.add_argument("--since", required=True, help="ISO date/time or e.g. 30d") + b.add_argument("--until", help="ISO date/time (default now)") + b.add_argument("--period", choices=("hour", "5minute"), default="hour") + args = p.parse_args() + _logging() + cfg = config.load(args.config, require_site=args.cmd != "suggest-mapping") + if args.cmd == "run": + # 75: the agent asks to be started again (the HA add-on: addon-run) + sys.exit(asyncio.run(_run(cfg)) or 0) + elif args.cmd == "suggest-mapping": + asyncio.run(_suggest(cfg)) + else: + until = parse_since(args.until) if args.until else datetime.now(timezone.utc) + asyncio.run(_backfill(cfg, parse_since(args.since), until, args.period)) diff --git a/src/edge/cantabile_edge/config.py b/src/edge/cantabile_edge/config.py new file mode 100644 index 0000000..9121b23 --- /dev/null +++ b/src/edge/cantabile_edge/config.py @@ -0,0 +1,105 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Configuration: one YAML file; environment variables win (the container +and add-on wrappers set them). Secrets only as files, never in the YAML.""" +import os +import re +from dataclasses import dataclass, field + +import yaml + +SITE_ID = re.compile(r"^[0-9a-f]{32}$") # the format of box ids +# The configuration may only say off or shadow: a new site starts in shadow; +# advisory and auto come by command from the console (controller.py). +MODES = ("off", "shadow") + + +@dataclass +class SinkConfig: + kind: str = "file" # file | stdout | nats | link + path: str = "/data/telemetry.jsonl" # file sink; link: its socket (/run/cantabile/link.sock) + url: str = "nats://127.0.0.1:4222" # nats sink + subject_prefix: str = "ctb.site" # -> ..tel + ensure_stream: bool = False # tests only: create the stream + + +@dataclass +class Config: + site_id: str = "" + mode: str = "shadow" + ha_url: str = "ws://127.0.0.1:8123/api/websocket" + ha_token: str = field(default="", repr=False) + mapping: str = "/data/mapping.yaml" + state_dir: str = "/data" + interval_s: int = 60 + queue_max: int = 43200 # batches: 30 days at one per minute + sink: SinkConfig = field(default_factory=SinkConfig) + # MQTT broker for Home Assistant's discovery (announce.py); empty: none. + mqtt_host: str = "" + mqtt_port: int = 1883 + mqtt_user: str = "" # the Hub's Mosquitto has no anonymous access + mqtt_password: str = field(default="", repr=False) + mqtt_password_file: str = "" # read at each connection (it may come later) + dashboards: bool = True # Cantabile's dashboards in HA (dashboards.py) + # The Building page for HA's ingress (joinpage.py): HA add-on sites only + # (the Hub's panel has its own); 0 = off. On by default in an add-on. + join_page_port: int = 0 + # Import or propose a mapping while the site has none (propose.py): HA + # add-on sites (addon-run sets CANTABILE_PROPOSE=1); the Hub's panel + # writes its devices' fragments itself. + propose: bool = False + # v1: plans and actions (controller.py, guard.py) + control_interval_s: int = 900 # a new plan every 15 minutes + act_interval_s: int = 60 # the executor's round + bundle_poll_s: float = 2.0 # how often a new tariff/model file is looked for + replan_debounce_s: float = 3.0 # a pause after a change before planning again + solve_timeout_s: float = 60.0 # the optimiser's subprocess is killed after this + plan_stale_s: int = 1800 # older plans: the safe defaults + default_price_ct: float = 30.0 # ct/kWh when no tariff ever came + override_hold_s: int = 7200 # hands off a control the owner changed by hand + min_switch_s: int = 600 # anti-cycling: a switch stays on/off at least this long + max_actions_per_hour: int = 12 # per control + + +def _read_secret(path: str) -> str: + with open(path) as f: + return f.read().strip() + + +def load(path: str | None, require_site: bool = True) -> Config: + raw = {} + if path: + with open(path) as f: + raw = yaml.safe_load(f) or {} + sink = SinkConfig(**(raw.pop("sink", None) or {})) + ha = raw.pop("ha", None) or {} + token_file = os.environ.get("HA_TOKEN_FILE", ha.get("token_file", "")) + cfg = Config(sink=sink, ha_url=ha.get("url", Config.ha_url), **raw) + env = os.environ + cfg.site_id = env.get("CANTABILE_SITE_ID", cfg.site_id) + # With the link the site id is the link's (edge/link writes it into its + # state directory): one id, made from Home Assistant's instance id. + if not cfg.site_id and env.get("CANTABILE_SITE_ID_FILE"): + cfg.site_id = _read_secret(env["CANTABILE_SITE_ID_FILE"]) + cfg.mode = env.get("CANTABILE_MODE", cfg.mode) + cfg.ha_url = env.get("HA_URL", cfg.ha_url) + cfg.mqtt_host = env.get("CANTABILE_MQTT_HOST", cfg.mqtt_host) + cfg.mqtt_port = int(env.get("CANTABILE_MQTT_PORT", cfg.mqtt_port)) + cfg.mqtt_user = env.get("CANTABILE_MQTT_USER", cfg.mqtt_user) + cfg.mqtt_password_file = env.get("CANTABILE_MQTT_PASSWORD_FILE", cfg.mqtt_password_file) + if env.get("CANTABILE_DASHBOARDS") in ("0", "false", "off"): + cfg.dashboards = False + if env.get("CANTABILE_PROPOSE") in ("1", "true", "on"): + cfg.propose = True + if token_file: + cfg.ha_token = _read_secret(token_file) + # Inside a Supervisor add-on the Supervisor proxies Core's API and hands + # the add-on its own token: no long-lived token exists. + cfg.join_page_port = int(env.get("CANTABILE_JOIN_PAGE_PORT", cfg.join_page_port or (8099 if env.get("SUPERVISOR_TOKEN") else 0))) + if env.get("SUPERVISOR_TOKEN") and not cfg.ha_token: + cfg.ha_url = env.get("HA_URL", "ws://supervisor/core/websocket") + cfg.ha_token = env["SUPERVISOR_TOKEN"] + if require_site and not SITE_ID.match(cfg.site_id or ""): + raise ValueError("site_id must be 32 lowercase hex characters") + if cfg.mode not in MODES: + raise ValueError(f"mode must be one of {MODES} here (advisory and auto: by command from the console)") + return cfg diff --git a/src/edge/cantabile_edge/consent.py b/src/edge/cantabile_edge/consent.py new file mode 100644 index 0000000..3c4f18c --- /dev/null +++ b/src/edge/cantabile_edge/consent.py @@ -0,0 +1,64 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The owner's consent to share energy data with Cantabile: one switch for +the whole site, on top of the mapping's per-entity consent (mapping.py). +Off until the owner turns it on. Kept in /consent.json +({"share": bool, "at": unix time, "by": "panel"|"ha-addon-config", +"source", "text_version"}), written by the Hub's setup wizard and panel +(/usr/lib/cantabile/web) or, on an HA add-on site, by addon-run from the +add-on's configuration at installation; +never by support; re-read when it changes. +Off means: nothing is collected, and what is queued is not sent (deleted). + +Control (v1) has its own switch in the same file, "control": true, off +unless set: the owner allows Cantabile to act on the devices whose controls +have their own consent (controls.py). Data sharing alone never allows +control. The Hub's panel writes it with the consent text that covers control +(pre-launch notes: a working text until the legal team's).""" +import json +import os +import time + + +class Consent: + def __init__(self, state_dir: str): + self.path = os.path.join(state_dir, "consent.json") + self._key = None + self._share = False + self._control = False + + def _stat(self): + try: + st = os.stat(self.path) + return (st.st_ino, st.st_mtime_ns, st.st_size) + except OSError: + return None + + def _load(self): + key = self._stat() + if key != self._key: + self._key = key + try: + with open(self.path) as f: + d = json.load(f) + self._share, self._control = d.get("share") is True, d.get("control") is True + except (OSError, ValueError, AttributeError): + self._share = self._control = False + + @property + def share(self) -> bool: + self._load() + return self._share + + @property + def control(self) -> bool: + self._load() + return self._control + + def set(self, share: bool, by: str): + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + # keeps the control switch as it was (the panel sets both) + json.dump({"share": bool(share), "control": self.control and bool(share), "at": int(time.time()), + "by": by}, f) + os.replace(tmp, self.path) + self._key = None diff --git a/src/edge/cantabile_edge/controller.py b/src/edge/cantabile_edge/controller.py new file mode 100644 index 0000000..5ce7b44 --- /dev/null +++ b/src/edge/cantabile_edge/controller.py @@ -0,0 +1,589 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""v1's control loop beside the telemetry: inputs -> plan -> actions. + + every control_interval_s (15 min): the model state (inputs.py), a plan + from the optimiser in a subprocess with a time limit (optimizer.py), + published: to the link in every mode (ctb.site..plan, for the + console), to Home Assistant in advisory and auto (announce.py) + every minute: owner overrides; in auto the executor's actions through the + guard (executor.py, guard.py) + +Modes: off, shadow (plan and publish, act on nothing), +advisory (also show the plan in Home Assistant), auto (act through the +guard). The configuration may only say off or shadow: a new site starts in +shadow; advisory and auto come only by command from the console (`mode`), +and are kept in /mode.json across restarts. No mode acts on a +control without its consent. + +Commands (from the console through the link, which checked the signature): + mode {"mode": "off|shadow|advisory|auto"} + control {"asset", "set", "level": "flexible|binding|emergency", + "until": unix time | "minutes": n, "why"?} + release {"asset"}: back to the plan + limits {"asset", "quantity", "level": "cloud|building|grid", + "floor"?, "limit"? (empty: none), "until"?} + building {"v", "id", "building", "level", "control", "value", "from", + "until", "why"}: the building's requests (building.py) +""" +import asyncio +import json +import logging +import os +import sys +import time + +from . import inputs as inputs_mod +from .building import Building +from .bundles import Bundles +from .executor import Executor, building_msg +from .gridorder import GridOrders +from .guard import Guard +from .policy import Policy +from .switchover import Switchover +from .inputs import Collector, History + +log = logging.getLogger(__name__) + +MODES = ("off", "shadow", "advisory", "auto") + + +class Mode: + def __init__(self, state_dir: str, default: str): + self.path, self.default = os.path.join(state_dir, "mode.json"), default + try: + with open(self.path) as f: + m = json.load(f).get("mode") + self.current = m if m in MODES else default + except (OSError, ValueError, AttributeError): + self.current = default + + def set(self, mode: str, by: str): + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump({"mode": mode, "at": int(time.time()), "by": by}, f) + os.replace(tmp, self.path) + self.current = mode + + def __call__(self) -> str: + return self.current + + +class Controller: + def __init__(self, cfg, mapping, consent, sink, clock=time.time): + self.cfg, self.mapping, self.sink, self.clock = cfg, mapping, sink, clock + self.controls = mapping.controls + self.inputs = mapping.inputs + self.mode = Mode(cfg.state_dir, cfg.mode) + self.col = Collector() + self.history = History(os.path.join(cfg.state_dir, "history.json")) + self.bundles = Bundles(cfg.state_dir, cfg.site_id, cfg.default_price_ct) + self.guard = Guard(self.controls, consent, self.mode, override_hold_s=cfg.override_hold_s, + min_switch_s=cfg.min_switch_s, max_actions_per_hour=cfg.max_actions_per_hour, clock=clock) + self.saved_limits = self._load_limits() # the console's (limits.json) + self.gridorders = GridOrders(cfg.state_dir, clock) # the grid operator's, from the EEBUS bridge (3q) + self.guard.extra_limits = self.saved_limits + self.policy = Policy(cfg.state_dir, cfg.site_id, clock) + self.guard.policy = self.policy + # a thermostat that heats and cools: one of its two controls at a time + self.switchover = Switchover(cfg.state_dir) + self.guard.switchover = self.switchover + self.tz = "UTC" + self.switchover.update(self.controls, clock(), self.tz, None) + self.building = Building(cfg.state_dir, clock) + self.executor = Executor(self.controls, self.guard, self.col, self._publish, stale_s=cfg.plan_stale_s, + clock=clock, building=self.building) + self.col.observers.append(self._observe) + self.client = None + self.tz = "UTC" + self.location: dict = {} # the site's latitude and longitude (HA's configuration) + self.plan: dict | None = None + self.plan_error = "" + self.forecast: list[dict] = [] # the weather entity's hourly forecast + self.wake = asyncio.Event() + self.act_now = asyncio.Event() # a control, release or new plan: act at once + self.on_plan = [] # callbacks (the announcer) when a plan is made + self.received: list[dict] = [] # the last commands and bundles (shown in HA, announce.py) + self.on_received = [] # callbacks (the announcer) for each + + # -- Home Assistant ---------------------------------------------------- + def outside_entity(self) -> str: + """The outdoor temperature: the inputs' (outside_temp), else the + mapped outside.temp.""" + if self.inputs.outside_temp: + return self.inputs.outside_temp + a = self.mapping.by_asset.get("outside.temp") if hasattr(self.mapping, "by_asset") else None + return a.entity if a else "" + + def switch_sides(self) -> bool: + """Heating or cooling for each thermostat that does both (switchover.py); + True when a side changed (plan again).""" + ent = self.outside_entity() + t_out = self.col.value(ent) if ent else None + return self.switchover.update(self.controls, self.clock(), self.tz, t_out) + + def entities(self) -> list[str]: + out = set(self.inputs.entities()) + if self.outside_entity() and any(c.switchover or c.kind == "cover" for c in self.controls): + out.add(self.outside_entity()) + for c in self.controls: + out.update(c.entities.values()) + if c.kind == "cover": + out.update(a.entity for a in self.room_assets(c) if a) + return sorted(out) + + # -- shades --------------------------------------------------------------- + def room_assets(self, c) -> tuple: + """A shade's room readings in the mapping: room..temp and + .setpoint (params.area), or None each.""" + area = str(c.p("area") or "") + by = getattr(self.mapping, "by_asset", {}) or {} + return (by.get(f"room.{area}.temp"), by.get(f"room.{area}.setpoint")) if area else (None, None) + + def _asset_value(self, a): + if a is None: + return None + return inputs_mod.number(self.col.attr(a.entity, a.attribute) if a.attribute else self.col.state(a.entity)) + + def shade_ctx(self) -> dict: + """Per shade its room for the rules (shades.py): the temperature and + setpoint (its room's heating or cooling control, else the mapping's + room..temp and .setpoint) and the season (the room control's + kind, of a thermostat that does both its active side).""" + by_id = {c.id: c for c in self.controls} + out = {} + for c in self.controls: + if c.kind != "cover": + continue + ctx = {} + room = by_id.get(str(c.p("room") or "")) + if room is not None: + side = room + if room.switchover and not self.switchover.active(room): + side = next((o for o in self.controls if o.switchover and o.id != room.id + and o.entities.get("climate") == room.entities.get("climate")), room) + ctx["season"] = side.kind + st = inputs_mod.device_state(room, self.col, self.clock()) + ctx["temp_c"], ctx["setpoint_c"] = st.get("temp_c"), st.get("target_c") + ta, sa = self.room_assets(c) + if ctx.get("temp_c") is None: + ctx["temp_c"] = self._asset_value(ta) + if ctx.get("setpoint_c") is None: + ctx["setpoint_c"] = self._asset_value(sa) + out[c.id] = ctx + return out + + async def on_connect(self, client): + self.client = client + try: + cfg = await client.send("get_config") + self.tz = (cfg or {}).get("time_zone") or "UTC" + lat, lon = (cfg or {}).get("latitude"), (cfg or {}).get("longitude") + if isinstance(lat, (int, float)) and isinstance(lon, (int, float)): + self.location = {"latitude": float(lat), "longitude": float(lon)} + except Exception as e: + log.warning("get_config: %s", e) + ids = self.entities() + if ids: + await client.subscribe_entities(ids, self.col.on_entities) + log.info("control: %d controls, %d inputs, mode %s", len(self.controls), len(ids), self.mode()) + self.wake.set() + + def _observe(self, eid: str, st: dict, now: float): + for c in self.controls: + if not self.switchover.active(c): + continue # the other control of the thermostat watches it + for role, ent in c.writable().items(): + if ent != eid: + continue + if c.kind == "cover": + if st.get("s") in ("opening", "closing"): + return # still moving to what it was told + value = st["a"].get("current_position") + if value is None: # open and close only + value = {"open": 100.0, "closed": 0.0}.get(st.get("s")) + elif ent.startswith("climate."): + value = st["a"].get("temperature") + cmd = self.guard._t(c.id).commanded.get(ent) + if cmd and inputs_mod.number(cmd[1]) is None: + value = st.get("s") # the agent last set the mode + else: + value = st.get("s") + self.guard.observe(c.id, eid, value, now) + + # -- plans --------------------------------------------------------------- + def model_state(self) -> dict: + now = self.clock() + start = int(now // inputs_mod.STEP_S * inputs_mod.STEP_S) + # sealed devices are not planned at all + # and of a thermostat that heats and cools only its active side + self.switch_sides() + controls = [c for c in self.controls if self.policy.plannable(c) and self.switchover.active(c)] + return inputs_mod.model_state(now, controls, self.inputs, self.col, self.bundles, + self.history, self.tz, self.forecast, self.guard.extra_limits, + building=self.building.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS), + location=self.location, shade_ctx=self.shade_ctx(), + grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS)) + + async def make_plan(self) -> dict | None: + self.forecast = [] + if self.client is not None and self.inputs.weather: + try: + self.forecast = await self.client.weather_forecast(self.inputs.weather) + except Exception as e: + log.info("weather forecast: %s", e) + state = self.model_state() + plan = await solve(state, self.cfg.solve_timeout_s) + if "error" in plan: + self.plan_error = plan["error"] + log.warning("no new plan: %s (the last one stays while fresh)", plan["error"]) + return None + plan["mode"] = self.mode() + plan["id"] = f"{self.cfg.site_id[:8]}-{plan['made']}" + plan["model"] = self.bundles.model_id() + self.plan, self.plan_error = plan, "" + self.executor.plan = plan + self.executor.inputs_ok = self.inputs_fresh() + self.act_now.set() # carry out a new plan now + n = sum(len(v) for v in plan["devices"].values()) + log.info("plan %s (%s, %.1f s): %d changes in 48 h, %.2f EUR vs %.2f EUR baseline; %s", + plan["id"], plan["status"], plan["solve_s"], n, plan["cost_eur"], plan["baseline_eur"], + plan.get("price_note", "")) + await self._publish("plan", self.public_plan(plan)) + for cb in self.on_plan: + await cb(plan) + return plan + + def public_plan(self, plan: dict) -> dict: + """The agreed form (v1): the plan's steps per asset, cost, baseline.""" + return {"v": 1, "id": plan["id"], "made": plan["made"], "start": plan["start"], "step_s": plan["step_s"], + "mode": plan["mode"], "devices": plan["devices"], "cost_eur": plan["cost_eur"], + "baseline_eur": plan["baseline_eur"], "status": plan["status"], + "prices": plan.get("price_note", ""), "model": plan.get("model", ""), + "sources": plan.get("sources", {}), + # for the building (shed_w/grid_w per step, 24 h): absent from older agents + "flex": plan.get("flex", {})} + + def inputs_fresh(self) -> bool: + """The plan's room temperatures and the battery's state are not older + than an hour (a sensor that stopped must not steer).""" + now = self.clock() + for c in self.controls: + for role in ("temp", "soc"): + if role in c.entities and self.col.age(c.entities[role], now) > 3600: + return False + return True + + async def _publish(self, kind, data): + pub = getattr(self.sink, "publish", None) + if pub is not None: + await pub(kind, data) + + def actuators(self) -> dict: + """Per control what the agent wants it at now and from whom (plan, + cloud: a hand control from the console, building, owner: an override + by hand that holds, safe default), whether it acts (auto and the + control's consent), and the limits in force per level and quantity + with the effective bounds. Shown in HA (announce.py).""" + now = self.clock() + out = {} + for c in self.controls: + want, level, why = self.executor.wanted(c, now) + if self.guard.overridden(c.id): + source = "owner" + elif why.startswith("building"): + source = "building" + elif level in ("flexible", "binding", "emergency") and c.id in self.executor.commands: + source = "cloud" + elif why.startswith("safe default"): + source = "safe default" + else: + source = "plan" + extra = self.guard.extra_limits.get(c.id) or {} + lims = {} + for q in set(c.limits) | set(extra): + layers = {**c.limits.get(q, {}), **extra.get(q, {})} + b = c.bounds(q, extra) + lims[q] = {"levels": {lvl: list(v) for lvl, v in layers.items()}, + "effective": [b.lo, b.hi], "floor_by": b.lo_by, "limit_by": b.hi_by} + value = want.get("set") if isinstance(want, dict) else want + active = self.switchover.active(c) + attrs = {"source": source, "level": level, "why": why, "limits": lims, + "acting": self.mode() == "auto" and bool(c.consent) and active, "kind": c.kind} + if c.switchover: + attrs["switchover"] = dict(c.switchover, active=active) + if isinstance(want, dict) and "grid" in want: + attrs["charge_from_grid"] = bool(want["grid"]) + out[c.id] = {"value": value, **attrs} + return out + + # -- loops --------------------------------------------------------------- + async def run(self, stop: asyncio.Event): + if not self.controls: + log.info("control: no controls in the mapping (v3): nothing to plan") + await stop.wait() + return + tasks = [asyncio.create_task(self._planner(stop)), asyncio.create_task(self._actor(stop)), + asyncio.create_task(self._bundle_watch(stop))] + await stop.wait() + await asyncio.gather(*tasks, return_exceptions=True) + + async def _bundle_watch(self, stop): + """A new tariff or model (the link writes them) plans again at once, + not at the next 15-minute plan (a test run priced a plan made one + second before the tariff came with the old one).""" + last = self.bundles.stamps() + while not stop.is_set(): + try: + await asyncio.wait_for(stop.wait(), self.cfg.bundle_poll_s) + except asyncio.TimeoutError: + pass + now = self.bundles.stamps() + if now != last: + for kind, a, b in zip(("tariff", "model"), last, now): + if a != b and b is not None: + f = self.bundles.tariff if kind == "tariff" else self.bundles.model + d = f.get() or {} + await self._received(kind, {"id": d.get("id", "")}, "cloud", + d != {}, f.error or "stored") + last = now + log.info("plan: a new tariff or model: planning again") + self.wake.set() + + async def _planner(self, stop): + woken = False + while not stop.is_set(): + if woken and self.cfg.replan_debounce_s > 0: + # several changes often come together (mode, limits, a + # tariff): one plan after a short pause, not one each + try: + await asyncio.wait_for(stop.wait(), self.cfg.replan_debounce_s) + except asyncio.TimeoutError: + pass + if self.mode() != "off" and self.client is not None: + try: + await self.make_plan() + except Exception as e: + log.warning("plan: %s", e) + self.wake.clear() + woken = False + try: + await asyncio.wait_for(asyncio.wait([asyncio.ensure_future(stop.wait()), + asyncio.ensure_future(self.wake.wait())], + return_when=asyncio.FIRST_COMPLETED), + self.cfg.control_interval_s) + woken = self.wake.is_set() + except asyncio.TimeoutError: + pass + + async def _actor(self, stop): + while not stop.is_set(): + now = self.clock() + self.history.add("load_w", self.col.total(self.inputs.load_power), now) + self.history.add("pv_w", self.col.total(self.inputs.pv_power), now) + if int(now) % 900 < 60: + try: + self.history.save(now) + except OSError as e: + log.warning("history: %s", e) + self.executor.inputs_ok = self.inputs_fresh() + self.grid_tick() + if self.switch_sides(): + self.wake.set() # heating <-> cooling: a plan for the new side + try: + await self.executor.tick(self.client, self.mode() == "auto") + except Exception as e: + log.warning("actions: %s", e) + self.act_now.clear() + try: + await asyncio.wait_for(asyncio.wait([asyncio.ensure_future(stop.wait()), + asyncio.ensure_future(self.act_now.wait())], + return_when=asyncio.FIRST_COMPLETED), + self.cfg.act_interval_s) + except asyncio.TimeoutError: + pass + + # -- commands ------------------------------------------------------------ + async def command(self, cmd: str, args: dict) -> tuple[bool, str]: + ok, why = await self._command(cmd, args) + await self._received(cmd, args, sender(cmd, args), ok, why) + return ok, why + + async def _received(self, cmd: str, args: dict, by: str, ok: bool, why: str): + ev = {"at": int(self.clock()), "cmd": cmd, "by": by, "args": public_args(args), + "result": "applied" if ok else "refused", "why": why} + self.received = (self.received + [ev])[-50:] + for cb in self.on_received: + try: + await cb(ev) + except Exception as e: + log.warning("received: %s", e) + + async def _command(self, cmd: str, args: dict) -> tuple[bool, str]: + now = self.clock() + if cmd == "mode": + m = args.get("mode", "") + if m not in MODES: + return False, f"mode: one of {', '.join(MODES)}" + self.mode.set(m, args.get("by", "console")) + log.info("mode %s (console)", m) + self.wake.set() # a plan in the new mode now + if m in ("advisory", "auto") and not any(c.consent for c in self.controls): + return True, f"mode {m}; note: no control has consent, nothing will be acted on" + return True, f"mode {m}" + if cmd == "control": + ok, msg = self.executor.command(args, now) + if ok: + self.act_now.set() + return ok, msg + if cmd == "release": + ok, msg = self.executor.release(args.get("asset", "")) + if ok: + self.act_now.set() # back to the plan now, not at the next round + return ok, msg + if cmd == "limits": + ok, msg = self.set_limit(args, now) + if ok: + self.wake.set() # a plan within the new limits now + return ok, msg + if cmd == "building": + return await self.building_command(args, now) + return False, f"unknown command {cmd!r}" + + async def building_command(self, args: dict, now: float) -> tuple[bool, str]: + try: + c = Building.parse(args) + except ValueError as e: + return False, str(e) + floors = [] + for ctl in self.controls: + if ctl.kind in ("heating", "cooling"): + b = ctl.bounds("temp_c", self.guard.extra_limits.get(ctl.id)) + floors.append((ctl.id, b.lo, b.hi, ctl.kind)) + ok, msg = self.building.take(c, floors) + await self._publish("action", building_msg(c, "done" if ok else "refused", msg if ok else msg, now)) + if ok: + self.wake.set() # a plan with it now + return ok, msg + + def set_limit(self, a: dict, now: float) -> tuple[bool, str]: + from .limits import QUANTITIES + c = {c.id: c for c in self.controls}.get(a.get("asset", "")) + if c is None: + return False, f"no control {a.get('asset')!r}" + q, lvl = a.get("quantity", ""), a.get("level", "") + if q not in QUANTITIES or lvl not in ("cloud", "building", "grid"): + return False, "quantity: one of " + ", ".join(QUANTITIES) + "; level: cloud, building or grid" + try: + f = float(a["floor"]) if a.get("floor") not in (None, "") else None + lim = float(a["limit"]) if a.get("limit") not in (None, "") else None + except ValueError: + return False, "floor and limit: numbers (or empty: none)" + if f is not None and lim is not None and f > lim: + return False, "floor above limit" + per = self.saved_limits.setdefault(c.id, {}).setdefault(q, {}) + if f is None and lim is None: + per.pop(lvl, None) + else: + per[lvl] = (f, lim) + self._save_limits() + self._merge_limits() + b = c.bounds(q, self.guard.extra_limits.get(c.id)) + self.wake.set() + return True, f"{c.id} {q}: {b.lo:g}..{b.hi:g} now (floor by {b.lo_by}, limit by {b.hi_by})" + + def _load_limits(self) -> dict: + try: + with open(os.path.join(self.cfg.state_dir, "limits.json")) as f: + raw = json.load(f) + return {c: {q: {lvl: tuple(v) for lvl, v in lv.items()} for q, lv in qs.items()} for c, qs in raw.items()} + except (OSError, ValueError, AttributeError): + return {} + + def _save_limits(self): + p = os.path.join(self.cfg.state_dir, "limits.json") + with open(p + ".tmp", "w") as f: + json.dump(self.saved_limits, f) + os.replace(p + ".tmp", p) + + + # -- the grid operator's limit (EEBUS LPC, gridorder.py) ----------------- + def _merge_limits(self): + """The guard's limits: the console's, and over them the grid order's + at level grid (the lower limit of the two holds).""" + merged = {c: {q: dict(lv) for q, lv in qs.items()} for c, qs in self.saved_limits.items()} + for cid, qs in self.gridorders.limits(self.controls).items(): + for q, (f, lim) in qs.items(): + per = merged.setdefault(cid, {}).setdefault(q, {}) + old = per.get("grid") + if old and old[1] is not None and lim is not None: + lim = min(lim, old[1]) + per["grid"] = (old[0] if old else f, lim) + self.guard.extra_limits = merged + + async def grid_order(self, payload: bytes) -> bool: + """A message on cantabile-eebus/gridorder (the announcer's MQTT + session): a changed order is a grid operator's decision: limits now, + a plan within them now, and shown to the owner like a command.""" + changed, why = self.gridorders.take(payload) + if not changed: + return False + self._merge_limits() + o = self.gridorders.active() + args = {"level": "emergency", "control": "load_limit", "source": "eebus-lpc"} + if o: + args.update(id=o["id"], value=str(o["limit_w"]), until=str(o.get("until") or ""), state=o.get("state", ""), + proof=self.gridorders.proof()) + log.warning("grid operator's limit %.0f W (%s, order %s): planning within it", o["limit_w"], o.get("state"), o["id"]) + else: + args.update(value="", state="normal") + log.info("grid operator's limit ended") + await self._received("grid", args, "grid", True, "limited" if o else "ended") + self.wake.set() + self.act_now.set() + return True + + def grid_tick(self): + """An order that went stale or ended takes its limits away.""" + if self.gridorders.order and not self.gridorders.active() and any( + "grid" in lv for qs in self.guard.extra_limits.values() for lv in qs.values()) \ + and not any("grid" in lv for qs in self.saved_limits.values() for lv in qs.values()): + self._merge_limits() + self.wake.set() + + +def sender(cmd: str, args: dict) -> str: + """Who a command comes from, for the owner (HA): the building's requests + (a relayed grid order: the grid operator), limits at their level, the + rest from Cantabile's cloud (the console).""" + if cmd == "building": + return "grid" if args.get("level") == "emergency" else "building" + if cmd == "limits" and args.get("level") in ("building", "grid"): + return args["level"] + return "cloud" + + +SECRET_ARGS = ("proof", "sig", "bundle", "token", "password") + + +def public_args(args: dict) -> dict: + """A command's arguments as HA may show them: no signatures, proofs or + bundles, short values.""" + return {k: str(v)[:120] for k, v in (args or {}).items() if k not in SECRET_ARGS} + + +async def solve(state: dict, timeout: float) -> dict: + """The optimiser in a subprocess: a bad model or a long solve never + stops the agent; past the timeout it is killed.""" + proc = await asyncio.create_subprocess_exec( + sys.executable, "-m", "cantabile_edge.optimizer", str(max(5.0, timeout - 5)), + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + try: + out, err = await asyncio.wait_for(proc.communicate(json.dumps(state).encode()), timeout) + except asyncio.TimeoutError: + proc.kill() + await proc.wait() + return {"error": f"the optimiser took longer than {timeout:g} s"} + try: + return json.loads(out) + except ValueError: + return {"error": (err.decode(errors="replace").strip().splitlines() or ["no output"])[-1][:300]} diff --git a/src/edge/cantabile_edge/controls.py b/src/edge/cantabile_edge/controls.py new file mode 100644 index 0000000..31ba841 --- /dev/null +++ b/src/edge/cantabile_edge/controls.py @@ -0,0 +1,272 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""What the agent may control (mapping v3, `controls:`), and how. + +A control is one device the optimiser plans for and the executor may act +on, always through Home Assistant service calls on the control's own +entities (the agent never talks to devices). Every control has its own +consent, separate from the reading consent of the mapping's assets and off +by default: an installer or the owner turns it on per control. On top of +that the owner's consent for the whole site must cover control +(consent.py, "control": true). + + controls: + - id: battery # the asset id plans and actions use + name: Home battery # optional: how HA and the dashboard call it + kind: battery + consent: false + entities: {charge_from_grid: switch.inverter_charge_from_grid, + setpoint: number.battery_power, soc: sensor.battery_soc} + params: {capacity_wh: 10000, max_charge_w: 3000, max_discharge_w: 3000} + limits: {soc_pct: {owner: [20, 100]}} + safe: {charge_from_grid: false} + +params.min_switch_s: how long an on/off switch or mode stays before it +may change again (anti-cycling). It protects equipment that wears from +short cycles (compressors, burners): heating and cooling 600 s by default; +0 for batteries, EV chargers and covers, which a release or a new plan may +change at once. + +Kinds, their entities (* needed) and what the executor sets (channels): + battery charge_from_grid (switch) and/or setpoint (number, W: + charge, + - discharge); mode (select: the inverter's own mode, set to + params.manual_option while the plan sets power, else to + params.auto_option); soc (sensor %), power (sensor W). + With a setpoint the agent sets the power there (and the mode) + and keeps charge_from_grid OFF: on many inverters (and the + simulated ones) the switch means "charge at full power" and would + override the setpoint (seen in simulation: 5000 W for 3000). + Only a battery without a setpoint (an HM8042 as the + profile has it: the switch alone) is driven through charge_from_grid. + heating climate* (target temperature) or switch* (on/off, a boiler); + temp (sensor °C, else the climate's current temperature) + cooling climate* (hvac_mode cool/off, target temperature); temp + A climate's own range (its min_temp..max_temp) narrows the + kind's range, and a target temperature is rounded to its + target_temp_step (any thermostat: hub/profiles/ha-thermostat.json). + ev switch* (charging on/off); current (number A); connected + (binary_sensor); soc (sensor %); energy_needed (sensor Wh/kWh) + and departure (sensor: a time) override params need_wh/departure + cover cover* (position %; open/close only where the cover cannot be + set to a position); room: the heating/cooling control whose + room it shades (params.room), area: the room's name (its + room..temp and .setpoint), facing: the window's + orientation (degrees from north, -1 not known); its moves come + from rules on the sun (shades.py): quiet_from..quiet_to no + moves (night_moves 1: allowed), min_move_s between moves, + override_hold_s off it after the owner moved it by hand + +Two controls never write the same entity, with one exception: a heating +and a cooling control on one climate that both have `switchover` (a +thermostat that can do both); only one of them is active at a time +(switchover.py). Any other control that writes an entity an earlier one +writes is left out (mapping.py, logged). +""" +import logging +import re +from dataclasses import dataclass, field + +from . import limits as limits_mod +from . import switchover as switchover_mod + +log = logging.getLogger(__name__) + +# kind -> {entity role: allowed domains}; the roles the executor writes +ENTITIES = { + "battery": {"charge_from_grid": ("switch", "input_boolean"), "setpoint": ("number", "input_number"), + "mode": ("select", "input_select"), "soc": ("sensor", "input_number"), "power": ("sensor",)}, + "heating": {"climate": ("climate",), "switch": ("switch", "input_boolean"), "temp": ("sensor",)}, + "cooling": {"climate": ("climate",), "temp": ("sensor",)}, + "ev": {"switch": ("switch", "input_boolean"), "current": ("number", "input_number"), + "connected": ("binary_sensor", "input_boolean"), "soc": ("sensor", "input_number"), + "energy_needed": ("sensor",), "departure": ("sensor", "input_datetime")}, + "cover": {"cover": ("cover",)}, +} +WRITES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover"} +NEEDED = {"battery": (("charge_from_grid", "setpoint"),), "heating": (("climate", "switch"),), + "cooling": (("climate",),), "ev": (("switch",),), "cover": (("cover",),)} +# defaults per kind (params may override each) +PARAMS = { + "battery": {"capacity_wh": 5000.0, "max_charge_w": 2500.0, "max_discharge_w": 2500.0, "efficiency": 0.95, + "soc_pct": 50.0, # soc_pct: the estimate when no sensor says + "manual_option": "manual", "auto_option": "self-consumption", "min_switch_s": 0.0}, + "heating": {"r_k_per_kw": 10.0, "c_kwh_per_k": 3.0, "max_power_w": 2000.0, "comfort_c": 21.0, + "setback_c": 17.0, "cop": 1.0, # cop 1: electric; a heat pump ~3 + "min_switch_s": 600.0}, + "cooling": {"r_k_per_kw": 10.0, "c_kwh_per_k": 3.0, "max_power_w": 1500.0, "comfort_c": 25.0, + "setup_c": 28.0, "cop": 3.0, "min_switch_s": 600.0}, + "ev": {"need_wh": 10000.0, "departure": "07:00", "min_current_a": 6.0, "max_current_a": 16.0, + "phases": 1.0, "voltage": 230.0, "min_switch_s": 0.0}, + "cover": {"room": "", "gain_w": 800.0, "min_switch_s": 0.0, "area": "", "facing": -1.0, + "open_pct": 100.0, "shade_pct": 30.0, "closed_pct": 0.0, "quiet_from": "22:00", "quiet_to": "07:00", + "night_moves": 0.0, "min_move_s": 1800.0, "override_hold_s": 14400.0}, +} +HHMM_RE = re.compile(r"^([01][0-9]|2[0-3]):[0-5][0-9]$") +# each kind's device range per quantity (firmware's; limits.effective) +RANGE = { + "battery": {"soc_pct": (0.0, 100.0)}, + "heating": {"temp_c": (5.0, 30.0)}, + "cooling": {"temp_c": (16.0, 32.0)}, + "ev": {"current_a": (0.0, 32.0)}, + "cover": {"position_pct": (0.0, 100.0)}, +} + + +@dataclass +class Control: + id: str + kind: str + entities: dict[str, str] + consent: bool = False + params: dict = field(default_factory=dict) + limits: dict = field(default_factory=dict) # quantity -> level -> (floor, limit) + safe: dict = field(default_factory=dict) # channel -> value when plans or data are stale + device: str = "" # the box's device it came with (mapping.d; policy.py) + entity_range: dict = field(default_factory=dict) # quantity -> (lo, hi) the device itself reports (a climate's) + switchover: dict = field(default_factory=dict) # heating/cooling pair on one climate (switchover.py) + name: str = "" # the owner's name for it (mapping `name`), else label() guesses + + def label(self) -> str: + """A name for people: the mapping's, else the id in words + ("living_room_cooling": "Living room cooling").""" + return self.name or (self.id.replace("_", " ").strip().capitalize() or self.id) + + def p(self, name: str) -> float | str: + return self.params.get(name, PARAMS[self.kind][name]) + + def device_range(self, q: str) -> tuple[float, float]: + if self.kind == "battery" and q == "power_w": + return (-float(self.p("max_discharge_w")), float(self.p("max_charge_w"))) + if self.kind == "ev" and q == "current_a": + return (0.0, float(self.p("max_current_a"))) + lo, hi = RANGE[self.kind][q] + own = self.entity_range.get(q) + if own and max(lo, own[0]) <= min(hi, own[1]): + lo, hi = max(lo, own[0]), min(hi, own[1]) + return (lo, hi) + + def learn_range(self, col): + """A climate's own min_temp..max_temp (HA's attributes, from the + collector): the setpoint never goes outside it.""" + ent = self.entities.get("climate") + if not ent or col is None: + return + lo, hi = _num(col.attr(ent, "min_temp")), _num(col.attr(ent, "max_temp")) + if lo is not None and hi is not None and lo <= hi: + self.entity_range["temp_c"] = (lo, hi) + + def temp_step(self, col) -> float: + ent = self.entities.get("climate") + step = _num(col.attr(ent, "target_temp_step")) if ent and col is not None else None + return step if step and step > 0 else 0.0 + + def bounds(self, q: str, extra: dict | None = None) -> limits_mod.Bounds: + """Effective bounds: the mapping's levels plus those commands set + (cloud, building, grid: extra).""" + layers = dict(self.limits.get(q, {})) + layers.update((extra or {}).get(q, {})) + return limits_mod.effective(self.device_range(q), layers) + + def writable(self) -> dict[str, str]: + """role -> entity for the entities the executor may write.""" + return {r: e for r, e in self.entities.items() if r in WRITES} + + +def _num(v) -> float | None: + try: + x = float(v) + except (TypeError, ValueError): + return None + return x if x == x and abs(x) != float("inf") else None + + +def _check_cover(cid: str, p: dict): + for k in ("open_pct", "shade_pct", "closed_pct"): + if k in p and (_num(p[k]) is None or not 0 <= float(p[k]) <= 100): + raise ValueError(f"control {cid}: {k} is 0-100 (%)") + if "facing" in p and (_num(p["facing"]) is None or not (float(p["facing"]) == -1 or 0 <= float(p["facing"]) <= 360)): + raise ValueError(f"control {cid}: facing is degrees from north (0-360), -1 when not known") + for k in ("quiet_from", "quiet_to"): + if k in p and not HHMM_RE.match(str(p[k])): + raise ValueError(f"control {cid}: {k} is a time, HH:MM") + for k in ("min_move_s", "override_hold_s", "night_moves", "gain_w"): + if k in p and (_num(p[k]) is None or float(p[k]) < 0): + raise ValueError(f"control {cid}: {k} is a number, 0 or more") + + +def parse(raw: list | None, reading_assets: set[str], rooms: set[str] | None = None, + strict: bool = True) -> list[Control]: + """The controls of one list (the mapping's or a device's fragment). + rooms: heating and cooling controls elsewhere on the site (a cover in a + device's fragment shades a room another device heats). A cover's room + that is no heating or cooling control is an error (strict: the + mapping's own), else dropped (logged: a device's fragment).""" + out, seen = [], set() + for c in raw or []: + cid, kind = c.get("id", ""), c.get("kind", "") + if kind not in ENTITIES: + raise ValueError(f"control {cid!r}: kind must be one of {', '.join(ENTITIES)}") + if not cid or cid in seen or cid in reading_assets: + raise ValueError(f"control id {cid!r}: needed, and unique among controls and assets") + seen.add(cid) + ents = c.get("entities") or {} + for role, eid in ents.items(): + doms = ENTITIES[kind].get(role) + if doms is None: + raise ValueError(f"control {cid}: a {kind} has no entity role {role!r}") + if eid.split(".", 1)[0] not in doms: + raise ValueError(f"control {cid}: {role} must be a {' or '.join(doms)} entity, not {eid}") + for alts in NEEDED[kind]: + if not any(a in ents for a in alts): + raise ValueError(f"control {cid}: needs {' or '.join(alts)}") + params = dict(c.get("params") or {}) + unknown = set(params) - set(PARAMS[kind]) + if unknown: + raise ValueError(f"control {cid}: unknown params {', '.join(sorted(unknown))}") + if kind == "cover": + _check_cover(cid, params) + sw = {} + if c.get("switchover") is not None: + if kind not in ("heating", "cooling") or "climate" not in ents: + raise ValueError(f"control {cid}: switchover only on a heating or cooling climate") + sw = switchover_mod.check(c["switchover"]) + out.append(Control(cid, kind, dict(ents), bool(c.get("consent", False)), params, + limits_mod.parse(c.get("limits")), dict(c.get("safe") or {}), switchover=sw, + name=str(c.get("name") or "")[:60])) + # a cover's room is a heating or cooling control + known = {c.id for c in out if c.kind in ("heating", "cooling")} | set(rooms or ()) + for c in out: + if c.kind == "cover" and c.p("room") and c.p("room") not in known: + if strict: + raise ValueError(f"control {c.id}: room {c.p('room')!r} is no heating or cooling control") + log.warning("control %s: room %r is no heating or cooling control: left out", c.id, c.p("room")) + c.params.pop("room", None) + return out + + +@dataclass +class Inputs: + """Sensors the optimiser reads (mapping v3, `inputs:`); they never + leave the site (the plan does, not these).""" + presence: list[str] = field(default_factory=list) # binary_sensor / input_boolean / person + outside_temp: str = "" + weather: str = "" # weather.* (now and its hourly forecast) + sun: str = "sun.sun" + load_power: str | list = "" # sensor W: the house's load (history fallback) + pv_power: str | list = "" # sensor W: PV (history fallback); a list: their sum + humidity: list[str] = field(default_factory=list) + + def entities(self) -> list[str]: + one = [self.outside_temp, self.weather, self.sun] + summed = [e for x in (self.load_power, self.pv_power) for e in ([x] if isinstance(x, str) else x)] + return [e for e in self.presence + self.humidity + one + summed if e] + + +def parse_inputs(raw: dict | None) -> Inputs: + raw = dict(raw or {}) + for k in ("presence", "humidity"): + if isinstance(raw.get(k), str): + raw[k] = [raw[k]] + unknown = set(raw) - set(Inputs.__dataclass_fields__) + if unknown: + raise ValueError(f"inputs: unknown keys {', '.join(sorted(unknown))}") + return Inputs(**raw) diff --git a/src/edge/cantabile_edge/dashboards.py b/src/edge/cantabile_edge/dashboards.py new file mode 100644 index 0000000..2d8f5bb --- /dev/null +++ b/src/edge/cantabile_edge/dashboards.py @@ -0,0 +1,1004 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Dashboards the agent keeps in Home Assistant for the owner, on the Hub and on any HA (the add-on case too): + +- HA's Energy dashboard: grid import and export, solar, battery, gas and + heat from the mapping, our electricity and feed-in price sensors as the + prices. Only while the owner has none (empty preferences): never + overwritten. +- One Lovelace dashboard "Cantabile" (storage mode, url_path + "cantabile-main"): one entry in HA's sidebar (status + and devices in one dashboard: connectivity when there are no devices, + otherwise the devices under it), in HA's language (names.py), HA's built-in cards + only (sections, tile, gauge, statistic, distribution, history and + statistics graphs, markdown): + overview bands from top to bottom, each the view's full width (two + columns at most: max_columns 2, column_span 2; one column + on a phone; widths of halves and quarters, rows without + holes): the status in one row (cloud, mode, next action); + energy now, four equal tiles a row (solar, home, grid with + a 6 h trend; the battery's charge as a bar; a tile per part + of several devices); the devices, a section each (devview.py: + its profile's view, else HA's device classes), two a row, + alike in height side by side: its name opening its page + (the Modbus bridge add-on's /app/#, else its + own sub-view with all its values), 2-4 values not shown in + energy now, a thermostat as a line in words ("Off · fan + low") and a tile with the room's temperature and setpoint, + circuits as their total and one bar (only there), relays as + how many are on; devices: Cantabile's (HA's area + "Cantabile"), those a profile describes and those the + mapping uses (not rooms); energy today (small statistics, + four a row); the plan (prices in ct/kWh: now, the cheapest + and dearest hour of the next 24; the coming actions by + the controls' names or "nothing planned", the prices of 48 h + as a table, what Cantabile sets in words: only in auto, the + commands received: only when there are any); the building + the home is in or asked to join + energy power and price over time, energy per day and month (if mapped) + climate rooms, thermostats, heat pump (if mapped) + flats a building's flats (only on a building's own box) + Sensors gone or unavailable for an hour are left out. The add-ons' pages + are not in the sidebar; HA's "app" panel opens them (/app/, or + /hassio/ingress/ before HA had it). + Owned by Cantabile: saved again when what it shows changes (the mapping, + the devices, the language, the flats), removed when it has nothing to show. + The dashboards of earlier versions (cantabile-electricity, -solar, + -climate, -energy, -flats) are removed. Other dashboards are never touched + (ha.py: dashboard() allows only "cantabile-*"); an owner who wants changes + copies it. +""" +import asyncio +import hashlib +import json +import logging +import os +import re +import time +from datetime import datetime + +from . import devview, names, propose +from .ha import HAError, OURS +from .mapping import part_of + +log = logging.getLogger(__name__) +EVERY_S = 600 # look again this often (new entities, flats, a new mapping) +URL = f"{OURS}main" +RETIRED = tuple(f"{OURS}{k}" for k in ("electricity", "solar", "climate", "energy", "flats")) +# a device's sub-view lists its entities of these domains +VALUES = ("sensor", "binary_sensor", "switch", "select", "number", "climate", "water_heater", "light", "cover", "fan") +DEAD_S = 3600 # unavailable this long: left out (a sensor gone, not one rebooting) + + +def _slug(s: str) -> str: + return re.sub(r"[^a-z0-9_]", "_", str(s).lower())[:48] + + +class Home: + """What the home has: the mapping, the agent's own entities in HA + (entity ids by unique id: HA names them, in its language), HA's + registries and states (Cantabile's devices), the add-ons' pages.""" + + def __init__(self, mapping, uid: str, ours: dict[str, str], flats: list[dict], lang: str, + mode: str = "shadow", reg: dict | None = None, states: list[dict] | None = None, + links: dict[str, str] | None = None, joining: dict | None = None, + profiles: list[dict] | None = None): + self.m, self.uid, self.ours, self.flats, self.lang = mapping, uid, ours, flats, lang + self.mode, self.links, self.joining, self.profiles = mode, links or {}, joining, profiles or [] + self._views: dict[str, devview.DeviceView] = {} + self.assets = {a.asset: a for a in mapping.assets} + reg = reg or {} + self.devices = reg.get("devices") or [] + self.entities = [e for e in reg.get("entities") or [] if not e.get("disabled_by") and not e.get("hidden_by")] + self.areas = reg.get("areas") or [] + # None: HA's states unknown (nothing is left out) + self.states = None if states is None else {s["entity_id"]: s for s in states} + + def alive(self, entity: str) -> bool: + """In HA and measuring, or not for long: a dashboard shows no + sensor that is gone or has been unavailable for an hour.""" + if self.states is None: + return True + s = self.states.get(entity) + if s is None: + return False + if s.get("state") not in ("unavailable", "unknown"): + return True + try: + since = datetime.fromisoformat(str(s.get("last_changed"))).timestamp() + except ValueError: + return False + return time.time() - since < DEAD_S + + def asset(self, name: str) -> str | None: + a = self.assets.get(name) + return a.entity if a and self.alive(a.entity) else None + + def each(self, name: str) -> list[tuple[str, str]]: + """(n, entity) of a quantity: ("", its entity) when mapped as one, + else its parts' (pv.1.power, pv.2.power: several devices).""" + one = self.asset(name) + if one: + return [("", one)] + out = [] + for a in self.m.assets: + p = part_of(a.asset) + if p and p[0] == name and self.alive(a.entity): + out.append((str(p[1]), a.entity)) + return out + + def all(self, *names) -> list[str]: + return [e for n in names for _, e in self.each(n)] + + def ents_of(self, d: dict) -> list[dict]: + return [e for e in self.entities if e.get("device_id") == d["id"]] + + def view(self, d: dict) -> devview.DeviceView: + if d["id"] not in self._views: + self._views[d["id"]] = devview.view_of(d, self.ents_of(d), self.states, self.profiles, self.alive) + return self._views[d["id"]] + + def prefixed(self, head: str, tail: str) -> list[str]: + """circuit.*.power -> their entities, in the mapping's order.""" + return [a.entity for a in self.m.assets if a.asset.startswith(head + ".") and a.asset.endswith("." + tail) + and a.asset.count(".") == 2 and self.alive(a.entity)] + + def counters(self, prefix: str = "") -> list[str]: + return [a.entity for a in self.m.assets + if a.kind == "counter" and a.asset.startswith(prefix) and self.alive(a.entity)] + + def our(self, suffix: str) -> str | None: + return self.ours.get(f"{self.uid}_{suffix}") + + def controls(self, *kinds) -> list: + return [c for c in self.m.controls if not kinds or c.kind in kinds] + + def n(self, key, *a) -> str: + return names.name(key, self.lang, *a) + + +def _history(title, ents, hours=24) -> dict | None: + ents = [e for e in ents if e] + return {"type": "history-graph", "title": title, "hours_to_show": hours, "entities": ents, + "grid_options": {"columns": "full"}} if ents else None + + +def _stats(title, ents, period="day", days=30) -> dict | None: + ents = [e for e in ents if e] + return {"type": "statistics-graph", "title": title, "entities": ents, "period": period, "chart_type": "bar", + "stat_types": ["change"], "days_to_show": days, "grid_options": {"columns": "full"}} if ents else None + + +def _heading(text, icon=None, link=None) -> dict: + h = {"type": "heading", "heading": text, "heading_style": "title"} + if icon: + h["icon"] = icon + if link: + h["tap_action"] = {"action": "navigate", "navigation_path": link} + return h + + +def _tile(entity, name=None, icon=None, color=None, trend=False, cols=6) -> dict | None: + if not entity: + return None + t = {"type": "tile", "entity": entity, "grid_options": {"columns": cols}} + if name: + t["name"] = name + if icon: + t["icon"] = icon + if color: + t["color"] = color + if trend: + t["features"] = [{"type": "trend-graph", "hours_to_show": TREND_H}] + t["features_position"] = "bottom" + if entity.split(".")[0] in ("switch", "light", "fan", "input_boolean"): + t["icon_tap_action"] = {"action": "more-info"} # a tile never switches by a tap + return t + + +def _section(*cards) -> dict | None: + """A section with its heading, only if anything follows the heading.""" + cards = [c for c in cards if c] + return {"type": "grid", "cards": cards} if len(cards) > 1 else None + + +def _view(title, path, icon, *sections, columns=3) -> dict | None: + sections = [s for s in sections if s] + return {"type": "sections", "title": title, "path": path, "icon": icon, "max_columns": columns, + "dense_section_placement": True, "sections": sections} if sections else None + + +def _gauge(entity, name=None, cols=6) -> dict: + g = {"type": "gauge", "entity": entity, "min": 0, "max": 100, "needle": True, + "severity": {"red": 0, "yellow": 20, "green": 50}, "grid_options": {"columns": cols}} + if name: + g["name"] = name + return g + + +def _today(entity, name=None, icon=None, cols=6) -> dict: + """Energy today (kWh): four a row on a desktop, two on a phone (HA's + statistic card is never narrower).""" + c = {"type": "statistic", "entity": entity, "period": {"calendar": {"period": "day"}}, "stat_type": "change", + "grid_options": {"columns": cols}} + if name: + c["name"] = name + if icon: + c["icon"] = icon + return c + + +def _sum(label, ents, unit="W") -> dict: + """A markdown line with the sum of some entities' states.""" + return {"type": "markdown", "grid_options": {"columns": "full"}, "content": + "{% set e = " + json.dumps(ents) + " %}" + label + " **{{ e | map('states') | map('float', 0) | sum" + " | round(0) | int }} " + unit + "**"} + + +DECIMAL_COMMA = ("de", "fr", "it", "es", "nl", "ro", "ru", "pt", "pl", "cs", "da", "sv", "nb", "fi", "tr", "uk") +TREND_H = 6 # hours a tile's trend shows (24 h: mostly a flat line, gaps drawn as ramps) +WIDE = 2 # the overview's columns on a desktop: bands span both, devices two a row + + +def _band(*cards, heading=None, icon=None) -> dict | None: + """A full-width band of the overview (both columns; one on a phone), + with a small heading if any; None when it has nothing.""" + cards = [c for c in cards if c] + if not cards: + return None + if heading: + cards.insert(0, {"type": "heading", "heading": heading, "heading_style": "subtitle", "icon": icon}) + return {"type": "grid", "column_span": WIDE, "cards": cards} + + +def _fill(cards: list[dict], width: int = 12 * WIDE) -> list[dict]: + """Rows without a hole: the cards of a row cut short share the rest + of it (equally where they stay quarters or halves, else the last takes + it): no card a phone would show at two thirds of its width.""" + row, used = [], 0 + + def close(): + extra = width - used + if row and extra > 0: + even = extra % len(row) == 0 and (extra // len(row)) % 6 == 0 # halves and quarters only + each = [extra // len(row)] * len(row) if even else [0] * (len(row) - 1) + [extra] + for c, x in zip(row, each): + c["grid_options"] = dict(c["grid_options"], columns=c["grid_options"]["columns"] + x) + for c in cards: + w = c["grid_options"]["columns"] + w = width if w == "full" else w + if used + w > width: + close() + row, used = [], 0 + row.append(c) + used += w + close() + return cards + + +def _powers(h: "Home", name, key, icon, color) -> list[dict]: + """A power of the home as tiles with their trend: one, or one per part + (two inverters: "Solar 1", "Solar 2").""" + return [_tile(e, f"{h.n(key)} {n}".strip(), icon, color, trend=True) for n, e in h.each(name)] + + +def energy_now(h: "Home") -> list[dict]: + """Solar, home, grid and battery now: equal tiles, four a row on a + desktop, two on a phone; the battery's tile is its charge (a bar).""" + now = _powers(h, "pv.power", "solar", "mdi:solar-power-variant", "amber") + now += _powers(h, "load.power", "home", "mdi:home-lightning-bolt", "deep-purple") + now += _powers(h, "grid.power" if h.each("grid.power") else "grid.import_power", "grid", + "mdi:transmission-tower", "blue") + if not h.each("grid.power"): + now += _powers(h, "grid.export_power", "feed_in", "mdi:transmission-tower-export", "cyan") + socs = h.each("battery.soc") + for n, soc in socs: + t = _tile(soc, f"{h.n('battery')} {n}".strip(), "mdi:battery-high", "green") + t["features"], t["features_position"] = [{"type": "bar-gauge", "min": 0, "max": 100}], "bottom" + now.append(t) + if not socs: + now += _powers(h, "battery.power", "battery", "mdi:battery-charging", "green") + return now + + +def _label(h: "Home", c) -> str: + """A control as people call it: the mapping's name, else the name HA + shows for its device's main entity, else its id in words.""" + if c.name: + return c.name + for role in ("climate", "switch", "setpoint", "charge_from_grid", "cover"): + e = c.entities.get(role) + n = (((h.states or {}).get(e) or {}).get("attributes") or {}).get("friendly_name") if e else None + if n: + return str(n) + return c.label() + + +def _md(content, cols="full", **kw) -> dict: + return {"type": "markdown", "grid_options": {"columns": cols}, "content": content, **kw} + + +def _jinja_str(s: str) -> str: + return json.dumps(str(s)) + + +def plan_cards(h: "Home") -> list[dict]: + """The plan: the prices now, the coming actions by name (or "nothing + planned"), the prices of the next 48 h as a small table, what + Cantabile sets on each device in words (only when it acts: auto), the + commands received (only when there are any).""" + nxt, price, feed = h.our("next_action"), h.our("price_import_now"), h.our("price_export_now") + dec = "," if h.lang.split("-")[0] in DECIMAL_COMMA else "." + + def ct(x): # a price in ct/kWh, one decimal, the language's decimal mark + return "('%.1f' | format(" + x + ") | replace('.', '" + dec + "'))" + out = [] + if price: + # now (the sensor is in /kWh, as HA's Energy takes it), + # the cheapest and dearest hour of the next 24 + out.append(_md( + "{% set n = states('" + price + "') | float(none) %}" + "{% set s = state_attr('" + price + "', 'start') %}{% set p = state_attr('" + price + "', 'import') or [] %}" + "{% if n is not none %}" + h.n("price_now") + " **{{ " + ct("n * 100") + " }} ct/kWh**" + + ("{% set f = states('" + feed + "') | float(none) %}{% if f is not none %} · " + h.n("feed_in_now") + + " {{ " + ct("f * 100") + " }} ct/kWh{% endif %}" if feed else "") + "{% endif %}" + "{% if s and p %}{% set w = namespace(lo=none, hi=none, li=0, hi_i=0) %}" + "{% for i in range(0, [p | count, 96] | min) %}{% if p[i] is not none %}" + "{% if w.lo is none or p[i] < w.lo %}{% set w.lo = p[i] %}{% set w.li = i %}{% endif %}" + "{% if w.hi is none or p[i] > w.hi %}{% set w.hi = p[i] %}{% set w.hi_i = i %}{% endif %}" + "{% endif %}{% endfor %}{% if w.lo is not none %} \n" + h.n("cheapest") + + " **{{ (s + w.li * 900) | timestamp_custom('%H:%M') }}** {{ " + ct("w.lo") + " }} ct · " + + h.n("dearest") + " **{{ (s + w.hi_i * 900) | timestamp_custom('%H:%M') }}** {{ " + ct("w.hi") + + " }} ct{% endif %}{% endif %}", 24)) + base = {c.id: _label(h, c) for c in h.controls()} + # one thermostat that heats and cools: two controls of one name, told apart + names_ = {c.id: base[c.id] + (f" ({h.n('kind_' + c.kind)})" if list(base.values()).count(base[c.id]) > 1 + and f"kind_{c.kind}" in names.NAMES else "") for c in h.controls()} + if nxt: + out.append(_md( + "{% set names = " + json.dumps(names_) + " %}{% set n = state_attr('" + nxt + "', 'next') or [] %}" + "{% if n %}| " + h.n("time") + " | " + h.n("control") + " | " + h.n("value") + " | " + h.n("why") + + " |\n|---|---|---|---|\n{% for s in n[:8] %}" + "| {{ s.at }} | {{ names.get(s.control) or s.get('name') or s.control }} | " + "{% if s.set == 'release' %}" + h.n("your_settings") + "{% else %}**{{ s.set }}**{% endif %} | " + "{{ s.get('why', '') }} |\n" + "{% endfor %}{% else %}" + h.n("nothing_planned") + "{% endif %}", title=h.n("coming"))) + if price: + # every 4 h of the next 48 (the curve is in quarter hours), a row a day: fits a phone + out.append(_md( + "{% set s = state_attr('" + price + "', 'start') %}{% set p = state_attr('" + price + "', 'import') or [] %}" + "{% if s and p %}| | 00 | 04 | 08 | 12 | 16 | 20 |\n|---|---|---|---|---|---|---|\n" + "{% set day0 = (s | int) - ((s | int) % 86400) %}" + "{% for d in range(0, 3) %}{% set row = namespace(cells=[], any=false) %}" + "{% for k in range(0, 6) %}{% set t = day0 + d * 86400 + k * 14400 %}{% set i = ((t - s) / 900) | int %}" + "{% if t >= s and i < p | count and p[i] is not none %}" + "{% set row.cells = row.cells + [" + ct("p[i] | float") + "] %}{% set row.any = true %}" + "{% else %}{% set row.cells = row.cells + ['·'] %}{% endif %}{% endfor %}" + "{% if row.any %}| **{{ (day0 + d * 86400) | timestamp_custom('%a', false) }}** | " + "{{ row.cells | join(' | ') }} |\n{% endif %}{% endfor %}{% endif %}", title=h.n("card_prices"))) + if h.mode == "auto": + rows = [] + for c in h.controls(): + e = h.our(f"set_{c.id}") + if not e: + continue + unit = " °C" if c.kind in ("heating", "cooling") else " W" if c.kind == "battery" else \ + " %" if c.kind == "cover" else "" + rows.append( + "{% set v = states('" + e + "') %}{% set src = state_attr('" + e + "', 'source') %}" + "**" + names_[c.id] + "**: {% if v in ['release', 'unknown', 'unavailable', 'None', '', '-'] %}" + + h.n("sets_release") + "{% else %}" + h.n("sets_holds") + " **{{ v }}" + unit + "**{% endif %} \n" + "{{ " + json.dumps({k: h.n("from_" + k.replace(" ", "_")) for k in + ("plan", "cloud", "building", "owner", "safe default")}) + + ".get(src, src or '') }}") + if rows: + out.append(_md("\n\n".join(rows), title=h.n("card_devices"))) + rec = h.our("received") + if rec: + by = {k: h.n("by_" + k) for k in ("cloud", "building", "grid", "console")} + out.append(_md( + "{% set by = " + json.dumps(by) + " %}| " + h.n("time") + " | " + h.n("what") + " | " + h.n("from") + + " | |\n|---|---|---|---|\n{% for c in (state_attr('" + rec + "', 'commands') or [])[:6] %}" + "| {{ c.at | timestamp_custom('%d.%m. %H:%M') }} | {{ c.what }} | {{ by.get(c.by, c.by) }} | " + "{% if c.result == 'applied' %}✓{% else %}✗ {{ c.why }}{% endif %} |\n{% endfor %}", + title=h.n("commands"), visibility=[{"condition": "numeric_state", "entity": rec, "above": 0}])) + # the prices' line, then the lists two a row on a desktop (a phone: one) + out = [c for c in out if c] + for c in out[1 if price else 0:]: + c["grid_options"] = {"columns": 12} + return out[:1 if price else 0] + _fill(out[1 if price else 0:]) + + +# -- the views ---------------------------------------------------------------------- + +def view_overview(h: Home) -> dict | None: + """Bands from top to bottom, each the view's full width (one column on + a phone): the status (one row), energy now (equal tiles), the devices + (a card each, two a row), energy today (small figures), the plan; the + building only when there is one.""" + cloud, mode, nxt = h.our("cloud"), h.our("control_mode"), h.our("next_action") + # cloud and mode half a row each beside the next action, else a half each + w = 6 if nxt else 12 + status = [_tile(cloud, h.n("card_cloud"), cols=w)] + if mode: + status.append(_tile(mode, h.n("mode"), "mdi:robot-outline", cols=w)) + elif cloud: + status.append(_md(f"**{h.n('mode_' + h.mode)}** · {h.n('mode_' + h.mode + '_why')}", w)) + status.append(_tile(nxt, h.n("next_action"), "mdi:calendar-clock", cols=12)) + status = _fill([c for c in status if c]) + + shown_now = set() + now = _fill(energy_now(h)) + shown_now |= {c["entity"] for c in now} + devices = [_clean(x) for x in _pairs([x for x in (device_card(h, d, shown_now) for d in shown_devices(h)) if x])] + + today = [] + for asset, key, icon in (("pv.energy", "solar", "mdi:solar-power-variant"), ("load.energy", "home", "mdi:home"), + ("grid.import_energy", "from_grid", "mdi:transmission-tower-import"), + ("grid.export_energy", "to_grid", "mdi:transmission-tower-export"), + ("battery.charge_energy", "battery_in", "mdi:battery-arrow-up"), + ("battery.discharge_energy", "battery_out", "mdi:battery-arrow-down"), + ("heatpump.energy", "heat_pump", "mdi:heat-pump"), ("ev.energy", "ev", "mdi:car-electric")): + for n, e in h.each(asset): + today.append(_today(e, f"{h.n(key)} {n}".strip(), icon)) + today = _fill(today) + + return _view(h.n("dash_main"), "overview", "mdi:leaf", + _band(*status), _band(*now), + devices_heading(h, bool(devices)), *devices, + _band(*today, heading=h.n("today"), icon="mdi:calendar-today"), + _band(*plan_cards(h), heading=h.n("card_plan"), icon="mdi:chart-timeline-variant"), + building_section(h), columns=WIDE) + + +def view_energy(h: Home) -> dict | None: + socs = [c.entities.get("soc") for c in h.controls("battery")] + power = h.all("pv.power", "load.power", "grid.power", "grid.import_power", "grid.export_power", "battery.power") + every = h.counters() + return _view(h.n("view_energy"), "energy", "mdi:chart-bar", + _section(_heading(h.n("card_power"), "mdi:flash"), + _history(h.n("card_power"), power), + _history(h.n("battery_soc"), h.all("battery.soc") + socs + + [h.our(f"set_{c.id}") for c in h.controls("battery")])), + _section(_heading(h.n("card_price"), "mdi:cash"), + _history(h.n("card_price"), [h.our("price_import_now"), h.our("price_export_now")], 48)), + _section(_heading(h.n("card_daily"), "mdi:calendar"), + _stats(h.n("card_daily"), every), _stats(h.n("card_monthly"), every, "month", 365))) + + +def view_climate(h: Home) -> dict | None: + rooms = h.controls("heating", "cooling") + temps = [c.entities.get("temp") for c in rooms] + h.prefixed("room", "temp") + return _view(h.n("dash_climate"), "climate", "mdi:thermostat", + _section(_heading(h.n("card_rooms"), "mdi:home-thermometer"), + # one card per thermostat (one that heats and cools has two controls) + *[{"type": "thermostat", "entity": e, "grid_options": {"columns": 6}} + for e in dict.fromkeys(c.entities["climate"] for c in rooms if "climate" in c.entities)], + _history(h.n("card_rooms"), list(dict.fromkeys(e for e in temps if e)) + + [h.our(f"set_{c.id}") for c in rooms] + [h.asset("outside.temp")])), + _section(_heading(h.n("heat_pump"), "mdi:heat-pump"), + _history(h.n("card_power"), h.all("heatpump.power", "heat.power")), + _stats(h.n("card_daily"), h.all("heatpump.energy", "heat.energy")))) + + +def _short(name: str, device: str) -> str: + """"HM8042 PV power" on the device HM8042: "PV power".""" + if device and name.lower().startswith(device.lower() + " "): + name = name[len(device) + 1:] + return name[:1].upper() + name[1:] + + +def shown_devices(h: Home) -> list[dict]: + """The devices the overview shows, by name: Cantabile's (HA's area + "Cantabile"), those a profile with a view describes, and those the + mapping uses (a value other than a room's, or a control). Never the + agent itself (the status), the add-ons (the Supervisor's devices), a + device with nothing to show, or an HA device the Modbus bridge mirrors + (the bridge's device of the same profile and name is shown instead).""" + area = next((a["area_id"] for a in h.areas if a.get("name") == names.area("cantabile", h.lang)), None) + used = {a.entity for a in h.m.assets if a.asset.split(".")[0] not in ("room", "outside", "weather")} + used |= {e for c in h.controls() for e in c.entities.values()} + out, mirrored = [], set() + for d in h.devices: + idents = [tuple(i) for i in d.get("identifiers") or [] if len(i) == 2] + if d.get("disabled_by") or any(x == "hassio" for x, _ in idents) \ + or any(str(i).startswith(h.uid) for _, i in idents): + continue + dv = h.view(d) + ours = bool(area) and d.get("area_id") == area + if not ours and dv.profile is None and not any(e["entity_id"] in used for e in h.ents_of(d)): + continue + if not ours and dv.empty(): + continue # (a room's sensor: a compact card, and on the climate view) + if devview.bridge_device(d): + mirrored.add((dv.profile, _name(d))) + out.append(d) + out = [d for d in out if devview.bridge_device(d) or (h.view(d).profile, _name(d)) not in mirrored + or h.view(d).profile is None] + return sorted(out, key=_name) + + +def _name(d: dict) -> str: + return d.get("name_by_user") or d.get("name") or "" + + +def _link(h: Home, d: dict) -> str: + """The bridge's page for its devices, else the device's own sub-view.""" + bridge_id = devview.bridge_device(d) + page = h.links.get(_bridge_link(d)) + if bridge_id and page: + return f"{page}#{bridge_id}" + return f"/{URL}/{_subpath(d)}" + + +def _bridge_link(d: dict) -> str: + """Which bridge's page a bridge device opens: "eebus" or "bridge" (Modbus).""" + return "eebus" if devview.bridge_prefix(d) == "cantabile_eebus_" else "bridge" + + +def _subpath(d: dict) -> str: + return "device-" + _slug(d["id"])[:12] + + +def device_cards(h: Home, d: dict, detail: bool = False) -> list[dict]: + """A device's cards by its view's kind: an inverter's flow (its charge + as a gauge, solar, home, grid and battery power with their trend), a + battery's gauge, circuits as their total and one bar, relays as how many + are on, a thermostat, a charger's or meter's values and energy today.""" + dv = h.view(d) + dev_name = _name(d) + by_id = {e["entity_id"]: e for e in h.ents_of(d)} + + def st(eid): + return ((h.states or {}).get(eid) or {}).get("attributes") or {} + + def nm(eid): + e = by_id.get(eid) or {} + return _short(st(eid).get("friendly_name") or e.get("original_name") or "", dev_name) or None + + def power(eid): + return st(eid).get("device_class") == "power" or st(eid).get("unit_of_measurement") in ("W", "kW") + + cards, used = [], set() + + def tile(eid, trend=None, cols=6): + if eid and eid not in used: + used.add(eid) + cards.append(_tile(eid, nm(eid), trend=power(eid) if trend is None else trend, cols=cols)) + soc = dv.flow.get("soc") or next((e for e in dv.headline if st(e).get("device_class") == "battery"), None) + if dv.card in ("flow", "gauge") and soc: + used.add(soc) + cards.append(_gauge(soc, nm(soc))) + if dv.climate: + used.add(dv.climate) + cards.append({"type": "thermostat", "entity": dv.climate, "grid_options": {"columns": 6}}) + if dv.climate_state: + # what it is doing and its fan, in words + cards.append(dict(_climate_line(h, dv.climate), grid_options={"columns": 6})) + if dv.assumed: + cards.append({"type": "markdown", "grid_options": {"columns": "full"}, + "content": "ⓘ " + h.n("assumed_hint")}) + if dv.cover: + used.add(dv.cover) + cards.append({"type": "tile", "entity": dv.cover, "name": nm(dv.cover) or dev_name, + "features": cover_features(st(dv.cover)), "features_position": "bottom", + "grid_options": {"columns": 6}}) + if dv.weather: + used.add(dv.weather) + cards.append({"type": "weather-forecast", "entity": dv.weather, "forecast_type": "hourly", + "grid_options": {"columns": "full"}}) + if dv.card == "flow": + for k in ("pv", "load", "grid", "battery"): + tile(dv.flow.get(k), True) + for e in dv.headline: + tile(e, None if dv.card in ("flow", "meter", "charger") or detail else False) + if dv.channels: + power_ch = [c for c in dv.channels if c.get("power")] + if power_ch: + cards.append(_sum(h.n("total"), [c["power"] for c in power_ch])) + cards.append({"type": "distribution", "grid_options": {"columns": "full"}, + "entities": [{"entity": c["power"], "name": nm(c.get("switch") or c["power"])} + for c in power_ch]}) + used |= {c["power"] for c in power_ch} + switches = list(dv.switches) + if dv.channels and not any(c.get("power") for c in dv.channels): + switches += [c["switch"] for c in dv.channels if c.get("switch")] + if switches: + cards.append({"type": "markdown", "grid_options": {"columns": "full"}, "content": + "{% set e = " + json.dumps(switches) + " %}" + "**{{ e | select('is_state', 'on') | list | count }}** " + h.n("of") + " {{ e | count }} " + + h.n("switched_on")}) + if dv.card in ("flow", "meter", "charger") or detail: + for e in dv.energy[:4]: + if e not in used: + used.add(e) + cards.append(_today(e, nm(e))) + return cards + + +ICONS = {"flow": "mdi:solar-power-variant", "gauge": "mdi:home-battery", "circuits": "mdi:flash", + "switches": "mdi:electric-switch", "climate": "mdi:thermostat", "charger": "mdi:ev-station", + "meter": "mdi:meter-electric", "sensor": "mdi:thermometer", "cover": "mdi:blinds", + "weather": "mdi:weather-partly-cloudy"} +HEADLINE = 4 # values on a device's card + + +def _pairs(secs: list[dict]) -> list[dict]: + """Devices two a row, those of about the same height side by side (by + name among equals); of an odd number, the one whose leaving out pairs + the rest best takes a whole row (at its place by height).""" + secs = sorted(secs, key=_height) + if len(secs) % 2 == 0: + return secs + + def cost(rest): + return sum(abs(_height(rest[i])[0] - _height(rest[i + 1])[0]) for i in range(0, len(rest) - 1, 2)) + best = min(range(len(secs)), key=lambda i: (cost(secs[:i] + secs[i + 1:]), i)) + secs[best]["column_span"] = WIDE + _widths(secs[best]["cards"], 12 * WIDE) + if best % 2: # a whole row between a pair's two: after them + secs.insert(best + 1, secs.pop(best)) + return secs + + +def _widths(cards: list[dict], width: int): + """A device's values two a row (four in a whole row), the rest full.""" + vals = [c for c in cards if c.get("_value")] + for c in cards: + c["grid_options"] = {"columns": 6 if c.get("_value") else "full"} + _fill(vals, width) + + +def _height(sec: dict) -> tuple: + """A device's height in rows, about (to pair devices alike).""" + rows, vals = 0.0, 0 + for c in sec["cards"]: + rows += {"heading": 0.7, "markdown": 0.6, "distribution": 2.0, "weather-forecast": 3.0}.get(c["type"], 0) + if c["type"] == "tile" and c.get("_value"): + vals += 1 + elif c["type"] == "tile": + rows += 1 + len(c.get("features") or []) + return (round(rows + -(-vals // 2), 1), sec["cards"][0]["heading"].lower()) + + +def _climate_line(h: "Home", e: str) -> dict: + """What a thermostat is doing, in words: "Off · fan low", "Cool · + idle · fan auto" (its action only when it says more than its mode).""" + return {"type": "markdown", "text_only": True, "content": + "{% set e = '" + e + "' %}{% set s = states(e) %}{% set a = state_attr(e, 'hvac_action') %}" + "{% set f = state_attr(e, 'fan_mode') %}{{ state_translated(e) }}" + "{% if a and a != s and a != 'off' and not (a | string).startswith(s) %}" + " · {{ state_attr_translated(e, 'hvac_action') | lower }}{% endif %}" + "{% if f %} · " + h.n("fan") + " {{ state_attr_translated(e, 'fan_mode') | lower }}{% endif %}"} + + +def device_card(h: Home, d: dict, skip: set[str] = frozenset()) -> dict | None: + """One device as a section of its own (its name right above its + values, the devices apart from each other): its name opening its page + (the Modbus bridge's, else its own sub-view), then 2-4 values (not + those energy now shows already), its thermostat as a tile with the room + temperature and its setpoint and a line saying what it does, circuits + as their total and one bar (shown here only), relays as how many are + on.""" + dv = h.view(d) + dev_name = _name(d) + by_id = {e["entity_id"]: e for e in h.ents_of(d)} + + def st(eid): + return ((h.states or {}).get(eid) or {}).get("attributes") or {} + + def nm(eid): + e = by_id.get(eid) or {} + return _short(st(eid).get("friendly_name") or e.get("original_name") or "", dev_name) or None + + cards = [{"type": "heading", "heading": dev_name, "heading_style": "title", "icon": ICONS.get(dv.card), + "tap_action": {"action": "navigate", "navigation_path": _link(h, d)}}] + used = set(skip) + room = None + if dv.climate: + used.add(dv.climate) + room = st(dv.climate).get("current_temperature") + cards.append(_climate_line(h, dv.climate)) # under its name: "Off · fan low" + cards.append({"type": "tile", "entity": dv.climate, "name": nm(dv.climate) or dev_name, + "state_content": ["current_temperature"] if room is not None else ["state"], + "features": [{"type": "target-temperature"}], "features_position": "bottom"}) + if dv.assumed: + cards.append({"type": "markdown", "text_only": True, "content": "ⓘ " + h.n("assumed_hint") + + ""}) + + def same_as_room(e): # the thermostat's own temperature sensor: on its tile already + try: + return room is not None and st(e).get("device_class") == "temperature" and \ + float(((h.states or {}).get(e) or {}).get("state")) == float(room) + except (TypeError, ValueError): + return False + if dv.cover: + # a shade: HA's tile with its features (a position slider where it + # can be set to one, else open/close; its tilt where it has one) + used.add(dv.cover) + cards.append({"type": "tile", "entity": dv.cover, "name": nm(dv.cover) or dev_name, + "features": cover_features(st(dv.cover)), "features_position": "bottom"}) + if dv.weather: + used.add(dv.weather) + cards.append({"type": "weather-forecast", "entity": dv.weather, "forecast_type": "hourly", + "show_current": True, "show_forecast": True}) + soc = dv.flow.get("soc") or next((e for e in dv.headline if st(e).get("device_class") == "battery"), None) + values = [soc] if dv.card in ("flow", "gauge") else [] + if dv.card == "flow": + values += [dv.flow.get(k) for k in ("battery", "pv", "load", "grid")] + values += dv.headline + picked = [] + for e in values: + if e and e not in used and e not in picked and not same_as_room(e): + picked.append(e) + for e in values: # at least two: those energy now shows too, if need be + if len(picked) < 2 and e and e in skip and e not in picked and e not in used - set(skip): + picked.append(e) + picked = picked[:HEADLINE] + used |= set(picked) + cards += [{"type": "tile", "entity": e, "name": nm(e), "_value": True, + **({"icon_tap_action": {"action": "more-info"}} + if e.split(".")[0] in ("switch", "light", "fan", "input_boolean") else {})} for e in picked] + power_ch = [c for c in dv.channels if c.get("power") and c["power"] not in skip] + if power_ch: + cards.append({"type": "markdown", "text_only": True, "content": + "{% set e = " + json.dumps([c["power"] for c in power_ch]) + " %}" + h.n("total") + + " **{{ e | map('states') | map('float', 0) | sum | round(0) | int }} W**"}) + cards.append({"type": "distribution", + "entities": [{"entity": c["power"], "name": nm(c.get("switch") or c["power"])} + for c in power_ch]}) + switches = list(dv.switches) + if dv.channels and not any(c.get("power") for c in dv.channels): + switches += [c["switch"] for c in dv.channels if c.get("switch")] + if switches: + cards.append({"type": "markdown", "text_only": True, "content": + "{% set e = " + json.dumps(switches) + " %}" + "**{{ e | select('is_state', 'on') | list | count }}** " + h.n("of") + " {{ e | count }} " + + h.n("switched_on")}) + if len(cards) == 1: + return None + _widths(cards, 12) + return {"type": "grid", "column_span": 1, "cards": cards} + + +def cover_features(attrs: dict) -> list[dict]: + """HA's tile features for a cover: its position (a slider) where it can + be set to one, else open/close (and stop); its tilt where it has one.""" + try: + f = int(attrs.get("supported_features") or 0) + except (TypeError, ValueError): + f = 0 + out = [{"type": "cover-position"}] if f & 4 or not f else [{"type": "cover-open-close"}] + if f & 128: + out.append({"type": "cover-tilt-position"}) + return out + + +def devices_heading(h: Home, any_: bool) -> dict | None: + """The devices band's heading; on an HA add-on site it opens the + add-on's Devices page (devpage.py: the way to use HA's devices with + Cantabile), there even with no device yet.""" + edge = h.links.get("edge") + if not any_ and not edge: + return None + head = {"type": "heading", "heading": h.n("devices_page" if edge else "devices"), "heading_style": "subtitle", + "icon": "mdi:devices"} + if edge: + head["tap_action"] = {"action": "navigate", "navigation_path": edge + "#devices"} + return {"type": "grid", "column_span": WIDE, "cards": [head]} + + +def _clean(sec: dict) -> dict: + for c in sec["cards"]: + c.pop("_value", None) + return sec + + +def device_subview(h: Home, d: dict) -> dict | None: + """A device without the bridge's page: its view's cards, every other + value it has (not diagnostic), and its power over the last day.""" + dv = h.view(d) + cards = device_cards(h, d, detail=True) + shown = {x if isinstance(x, str) else x.get("entity") for c in cards for x in [c, *(c.get("entities") or [])]} + shown |= set(dv.switches) + rest = [e["entity_id"] for e in h.ents_of(d) if not e.get("entity_category") and e["entity_id"] not in shown + and e["entity_id"].split(".")[0] in VALUES and h.alive(e["entity_id"])] + powers = [e for e in dv.entities() | set(rest) if (((h.states or {}).get(e) or {}).get("attributes") or {}) + .get("device_class") == "power"] + return {"type": "sections", "title": _name(d), "path": _subpath(d), "subview": True, + "back_path": f"/{URL}/overview", "max_columns": 3, "sections": [x for x in ( + _section(_heading(_name(d), "mdi:information-outline"), *cards), + _section(_heading(h.n("values"), "mdi:format-list-bulleted"), + {"type": "entities", "entities": rest, "grid_options": {"columns": "full"}} if rest else None), + _section(_heading(h.n("card_power"), "mdi:flash"), _history(h.n("card_power"), sorted(powers)))) + if x]} + + +def view_flats(h: Home) -> dict | None: + cards = [_heading(names.area("flats", h.lang), "mdi:office-building")] + for f in h.flats: + node = f"flat_{_slug(f['id'])}" + ents = [e for e in (h.our(f"{node}_grid"), h.our(f"{node}_flex"), h.our(f"{node}_request")) if e] + if ents: + cards.append({"type": "entities", "title": f.get("label") or f["id"], "entities": ents, + "grid_options": {"columns": 6}}) + return _view(names.area("flats", h.lang), "flats", "mdi:office-building", _section(*cards)) + + +def building_section(h: Home) -> dict | None: + """Only when the home is in a building or asked to join one: what it + is, and the add-on's page (joining, leaving).""" + st = h.joining or {} + m = st.get("membership") + lines = [] + if m: + lines.append(h.n("member_of", (m.get("building") or {}).get("name", ""), m.get("unit") or "–")) + lines += [h.n("community_of", c.get("name", "")) for c in st.get("communities") or []] + lines += [h.n("request_to", r.get("name", "")) for r in st.get("requests") or [] if r.get("state") == "pending"] + if not lines: + return None + edge = h.links.get("edge") + cards = [_heading(h.n("view_building"), "mdi:office-building-outline", edge and edge + "#building"), + {"type": "markdown", "grid_options": {"columns": "full"}, "content": " \n".join(lines)}] + return dict(_section(*cards), column_span=WIDE) + + +def dashboard(h: Home) -> dict | None: + """The dashboard's config, or None: nothing to show.""" + views = [view_overview(h), view_energy(h)] + if h.controls("heating", "cooling") or h.each("heatpump.power") or h.prefixed("room", "temp"): + views.append(view_climate(h)) + if h.flats: + views.append(view_flats(h)) + if views[0]: + views += [device_subview(h, d) for d in shown_devices(h) + if not (devview.bridge_device(d) and h.links.get(_bridge_link(d)))] + views = [v for v in views if v] + return {"views": views} if views else None + + +def energy_prefs(h: Home) -> dict | None: + """HA's Energy preferences from the mapping, or None (nothing to show). + Parts (two inverters, two batteries) are each a source of their own.""" + src = [] + imp, exp = h.all("grid.import_energy"), h.all("grid.export_energy") + if imp or exp: + src.append({"type": "grid", "cost_adjustment_day": 0, + "flow_from": [{"stat_energy_from": e, "stat_cost": None, "number_energy_price": None, + "entity_energy_price": h.our("price_import_now")} for e in imp], + "flow_to": [{"stat_energy_to": e, "stat_compensation": None, "number_energy_price": None, + "entity_energy_price": h.our("price_export_now")} for e in exp]}) + for e in h.all("pv.energy"): + src.append({"type": "solar", "stat_energy_from": e, "config_entry_solar_forecast": None}) + ins, outs = dict(h.each("battery.charge_energy")), dict(h.each("battery.discharge_energy")) + for n in [n for n in outs if n in ins]: + src.append({"type": "battery", "stat_energy_from": outs[n], "stat_energy_to": ins[n]}) + # gas (HA's Energy has no source for delivered heat: a heat meter stays + # on the Total energy dashboard) + if h.asset("gas.energy"): + src.append({"type": "gas", "stat_energy_from": h.asset("gas.energy"), "stat_cost": None, + "entity_energy_price": h.our("price_gas"), "number_energy_price": None}) + devices = [{"stat_consumption": e} for e in h.all("heatpump.energy", "ev.energy")] + if not src and not devices: + return None + return {"energy_sources": src, "device_consumption": devices} + + +class Dashboards: + def __init__(self, agent): + self.agent = agent + self.client = None + self.poke = asyncio.Event() + self.path = os.path.join(agent.cfg.state_dir, "dashboards.json") + # the device profiles' views (the add-on's image; on the Hub the + # devices tool's copies next to the mapping: /profiles) + self.profiles = propose.load_profiles( + extra=[os.path.join(os.path.dirname(agent.cfg.mapping) or ".", "profiles")]) + try: + with open(self.path) as f: + self.saved = json.load(f) # url_path -> hash of the config saved + except (OSError, ValueError): + self.saved = {} + + def connected(self, client): + self.client = client + self.poke.set() + + def mode(self) -> str: + ctl = getattr(self.agent, "control", None) + return ctl.mode() if ctl is not None else self.agent.cfg.mode + + def joining(self) -> dict | None: + try: + with open(os.path.join(self.agent.cfg.state_dir, "joining.json")) as f: + return json.load(f) + except (OSError, ValueError): + return None + + def home(self, ours: dict[str, str], reg: dict | None = None, states: list[dict] | None = None, + links: dict[str, str] | None = None) -> Home: + ctl = getattr(self.agent, "control", None) + flats = ctl.bundles.flat_list() if ctl is not None else [] + return Home(self.agent.mapping, f"cantabile_{self.agent.cfg.site_id}", ours, flats, + getattr(self.agent, "ha_language", "en"), self.mode(), reg, states, links, + self.joining() if self.agent.cfg.join_page_port else None, self.profiles) + + @staticmethod + async def links(client, devices: list[dict]) -> dict[str, str]: + """The pages of Cantabile's add-ons (the Supervisor's devices name + their slugs): HA's "app" panel, else the older ingress route.""" + try: + panels = await client.send("get_panels") or {} + except HAError: + panels = {} + base = "/app/" if "app" in panels else "/hassio/ingress/" + out = {} + for d in devices: + for x, slug in (tuple(i) for i in d.get("identifiers") or [] if len(i) == 2): + if x == "hassio" and str(slug).endswith("cantabile_edge"): + out["edge"] = base + slug + elif x == "hassio" and str(slug).endswith("cantabile_modbus"): + out["bridge"] = base + slug + elif x == "hassio" and str(slug).endswith("cantabile_eebus"): + out["eebus"] = base + slug + return out + + async def ensure(self, client): + reg = await client.registries() + uid = f"cantabile_{self.agent.cfg.site_id}" + ours = {e["unique_id"]: e["entity_id"] for e in reg["entities"] or [] + if e.get("platform") == "mqtt" and str(e.get("unique_id", "")).startswith(uid)} + states = await client.send("get_states") + h = self.home(ours, reg, states, await self.links(client, reg["devices"] or [])) + await self._energy(client, h) + config = dashboard(h) + title = h.n("dash_main") + listed = await client.dashboard("lovelace/dashboards/list") or [] + have = {d["url_path"]: d for d in listed if str(d.get("url_path", "")).startswith(OURS)} + if config is not None: + if URL not in have: + await client.dashboard("lovelace/dashboards/create", url_path=URL, title=title, icon="mdi:leaf", + show_in_sidebar=True, require_admin=False, mode="storage") + self.saved.pop(URL, None) + log.info("dashboard %s made", URL) + elif have[URL].get("title") != title: + await client.dashboard("lovelace/dashboards/update", dashboard_id=have[URL]["id"], title=title) + digest = hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest() + if self.saved.get(URL) != digest: + await client.dashboard("lovelace/config/save", url_path=URL, config=config) + self.saved[URL] = digest + log.info("dashboard %s saved: %s", URL, ", ".join(v["path"] for v in config["views"])) + for url, d in have.items(): + if url in RETIRED or (url == URL and config is None): + await client.dashboard("lovelace/dashboards/delete", dashboard_id=d["id"]) + self.saved.pop(url, None) + log.info("dashboard %s removed", url) + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(self.saved, f) + os.replace(tmp, self.path) + + async def _energy(self, client, h: Home): + try: + prefs = await client.dashboard("energy/get_prefs") + except HAError: + prefs = None # never configured + if prefs and (prefs.get("energy_sources") or prefs.get("device_consumption")): + return # the owner's: never overwritten + want = energy_prefs(h) + if want is not None: + await client.dashboard("energy/save_prefs", **want) + log.info("HA's Energy dashboard set up from the mapping") + + async def run(self, stop: asyncio.Event): + while not stop.is_set(): + try: + await asyncio.wait_for(self.poke.wait(), EVERY_S) + await asyncio.sleep(30) # our MQTT entities register first + except asyncio.TimeoutError: + pass + self.poke.clear() + if self.client is not None and not stop.is_set(): + try: + await self.ensure(self.client) + except Exception as e: + log.warning("dashboards: %s", e) diff --git a/src/edge/cantabile_edge/devpage.py b/src/edge/cantabile_edge/devpage.py new file mode 100644 index 0000000..00611a0 --- /dev/null +++ b/src/edge/cantabile_edge/devpage.py @@ -0,0 +1,776 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The add-on's Devices page ("HA-only sites"): what the Hub +panel's Devices section does with devices Home Assistant has already, on +the add-on's own page (HA's ingress; reached from Cantabile's dashboard, +not the sidebar). With the Building or community page (joinpage.py) it +makes the add-on's small app (App): ?p=devices (the first page) and +?p=building; Cantabile's dashboard opens them as /app/#devices and +#building (the page takes HA's hash at start, as the Modbus bridge's does). + +For each HA device a device profile recognises (specific profiles first; a +generic one such as ha-thermostat only where none fits) the page shows what +Cantabile would read and could control. "Use with Cantabile" writes the +device's mapping fragment, /mapping.d/.yaml, as the Hub's +devices tool does and with the same shared code (devprofiles.py): every +value and control with consent off, the profile's protection defaults in +/protection.json, the device in /devices.json and its +specs for the inventory (devices-specs.json). The agent then loads the +mapping again (agent.devices_changed): the device is on Cantabile's +dashboard, and in HA's area "Cantabile" when it has no area of its own. +Nothing is installed or set up in HA here: no add-on installs, no +integrations (the owner's own HA does that); only devices HA has. + +The mapping's proposal (propose.py) and the owner's devices: a proposal is +a starting point; "Use with Cantabile" is the owner's confirmation, and +from then on the proposal leaves that device (its entities, ids and summed +systems) to its fragment. Removing the device gives it back to the +proposal. A mapping written by hand is never changed: its entries win and +are left out of a device's fragment (shown). One writer per entity: a +control on an entity another control writes is left out. + +Owner only, both pages: every request must come from a Home Assistant +administrator. +panel_admin only keeps the sidebar entry from other users; HA lets any +signed-in user open an add-on's ingress session. So the page asks HA who +the user is (the ingress proxy's X-Remote-User-Id) and refuses anyone else. + +Consent: an HA add-on site's consent is +given when the add-on is installed from Cantabile's repository, in its +configuration (addon-run records it in /consent.json: share, +control, the texts' version, source). With it, each device's reading and +control are switched on here as on the Hub's Devices page (the agent starts +again, as the Hub's tool restarts it); without it the page points to the +add-on's configuration. Protection (protected / not, never sealed) and a thermostat's heating or +cooling choice are the owner's, here as on the Hub. +""" +import asyncio +import json +import logging +import os +import time +import urllib.parse + +import yaml + +from . import devprofiles as dp +from .consent import Consent +from . import i18n +from .i18n import M, T, TN +from .joinpage import CSS, E, JoinPage + +log = logging.getLogger(__name__) + +PAGES = ("devices", "building") +SWITCHOVER_WORDS = {"heating": M("Heating"), "cooling": M("Cooling"), + "season": M("By season (heating October to April, cooling May to September)"), + "outdoor": M("By outdoor temperature")} +CUSTODIAN_WORDS = {"building_operator": M("the building's operator"), "grid_operator": M("the grid operator"), + "metering_operator": M("the metering operator"), "community_operator": M("the energy community's operator")} +PROFILE_STATUS = {"verified": M("Checked on a device"), + "documented": M("From the maker's documentation, not yet checked on a device"), + "draft": M("Draft: check the values before you turn reading on")} +CONTROL_WORDS = {"battery": M("battery"), "heating": M("heating"), "cooling": M("cooling"), "ev": M("charging"), + "cover": M("blinds and curtains")} +MORE_CSS = """nav{display:flex;gap:1rem;margin:0 0 1rem;border-bottom:1px solid #d5ded9;padding-bottom:.5rem} +nav a{color:inherit;text-decoration:none}nav a.on{font-weight:600;border-bottom:2px solid #2f6f55} +.badge{display:inline-block;font-size:.8rem;padding:.05rem .45rem;border-radius:4px;background:#e2e9e5;margin-left:.3rem} +ul.plain{margin:.3rem 0;padding-left:1.2rem}form.inline{display:inline}form.inline button{margin:0 0 0 .4rem;padding:.2rem .6rem} +@media (prefers-color-scheme:dark){nav{border-color:#2b3a32}.badge{background:#2b3a32}}""" +# HA's hash (#devices, #building: Cantabile's dashboard) to this page's ?p= +HASH_SCRIPT = ("(function(){try{var P=window.parent;if(P===window)return;var m=/^#(devices|building)$/.exec(P.location.hash||'');" + "if(m&&location.search.indexOf('p=')<0&&location.search.indexOf('code=')<0)location.replace('?p='+m[1])}" + "catch(x){}})();") + + +def _read_json(path: str, default): + try: + with open(path) as f: + v = json.load(f) + except (OSError, ValueError): + return default + return v if isinstance(v, type(default)) else default + + +def _write_json(path: str, data, mode: int = 0o644): + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + tmp = path + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode) + with os.fdopen(fd, "w") as f: + json.dump(data, f, indent=1, sort_keys=True, ensure_ascii=False) + f.write("\n") + os.replace(tmp, path) + + +def quantity_words(q: str) -> str: + return q.replace("_", " ").replace(".", ": ", 1) + + +def with_attrs(ents: list[dict], states: dict) -> list[dict]: + """Registry entries with HA's attributes now (where the state is known: + the profiles' conditions on attributes, as the Hub's registry has them).""" + out = [] + for e in ents: + st = states.get(e["entity_id"]) + if st and st.get("state") not in ("unavailable", "unknown"): + e = dict(e, attributes=st.get("attributes") or {}) + out.append(e) + return out + + +class Devices: + """The devices used with Cantabile on this site and HA's offers; the + page's actions. ha(): the agent's HA client (None while not connected); + changed(): the agent loads the mapping again.""" + + def __init__(self, mapping_path: str, state_dir: str, profiles: list[dict], ha=lambda: None, changed=None): + self.mapping_path, self.state_dir, self.profiles = mapping_path, state_dir, profiles + self.ha, self.changed = ha, changed + self.mapping_d = os.path.join(os.path.dirname(mapping_path) or ".", "mapping.d") + self.devices_path = os.path.join(state_dir, "devices.json") + self.lock = asyncio.Lock() + + # -- files ------------------------------------------------------------------------ + def load(self) -> dict: + return {k: v for k, v in _read_json(self.devices_path, {}).items() if isinstance(v, dict)} + + def save(self, devs: dict): + _write_json(self.devices_path, devs, 0o600) + + def frag_path(self, dev_id: str) -> str: + return os.path.join(self.mapping_d, f"{dev_id}.yaml") + + def frag(self, dev_id: str) -> dict: + return _read_json(self.frag_path(dev_id), {}) + + def write_frag(self, dev_id: str, frag: dict): + os.makedirs(self.mapping_d, mode=0o755, exist_ok=True) + _write_json(self.frag_path(dev_id), frag, 0o644) # JSON is YAML + + def main(self) -> dict: + """The site's own mapping (mapping.yaml).""" + try: + with open(self.mapping_path) as f: + raw = yaml.safe_load(f) or {} + except (OSError, yaml.YAMLError): + raw = {} + return raw if isinstance(raw, dict) else {} + + def local(self) -> dict: + return dp.local_entries(_read_json(os.path.join(self.state_dir, "protection.json"), {})) + + def save_local(self, entries: dict): + _write_json(os.path.join(self.state_dir, "protection.json"), {"v": 1, "entries": entries}) + + def policy(self) -> dict: + return dp.merge_policy(dp.acl_entries(_read_json(os.path.join(self.state_dir, "acl.json"), {})), self.local()) + + def profile(self, pid: str) -> dict | None: + return next((p for p in self.profiles if p.get("id") == pid), None) + + def write_specs(self, devs: dict): + """Each device's specs for the agent's inventory (as the Hub's tool).""" + policy, out = self.policy(), {} + for d in devs.values(): + p = self.profile(d["profile"]) or {} + frag = self.frag(d["id"]) + lvl, e = dp.level_of(policy, [f"device:{d['id']}"]) + out[d["id"]] = {"name": d["name"], "profile": d["profile"], "profile_version": d.get("profile_version", ""), + "category": d.get("category") or p.get("category", ""), "manufacturer": p.get("manufacturer", ""), + "model": p.get("name", d["profile"]), "path": "existing", "ratings": d.get("ratings") or {}, + "ha_device": d.get("ha_device"), "entry_id": None, "entities": dp.fragment_entities(frag), + "controls": [c["id"] for c in frag.get("controls", [])], "protection": lvl, + "custodian": (e or {}).get("custodian")} + _write_json(os.path.join(self.state_dir, "devices-specs.json"), {"v": 1, "made": int(time.time()), "devices": out}) + + # -- HA --------------------------------------------------------------------------- + async def snapshot(self) -> tuple[dict, dict]: + client = self.ha() + if client is None: + raise dp.Fail(T("Home Assistant is not connected yet; try again in a moment.")) + reg = dict(await client.registries()) + # each device's integrations, as the Hub's registry gives them: its + # entities' platforms (the profiles' recognise.ha "domain") + plat = {} + for e in reg.get("entities") or []: + if e.get("device_id") and e.get("platform"): + plat.setdefault(e["device_id"], set()).add(e["platform"]) + reg["devices"] = [dict(d, domains=sorted(plat.get(d["id"], ()))) for d in reg.get("devices") or []] + states = {s["entity_id"]: s for s in await client.send("get_states") or []} + # each entity's device class (HA's state attribute: the owner's choice + # in HA wins; also while unavailable): which profile fits (a garage + # door is never a shade, a CPU temperature never a room's) + reg["entities"] = [dict(e, device_class=((states.get(e.get("entity_id")) or {}).get("attributes") or {}) + .get("device_class") or e.get("device_class") or e.get("original_device_class")) + for e in reg.get("entities") or []] + return reg, states + + # -- what a device would give ---------------------------------------------------------- + def plan(self, reg: dict, states: dict, ha_device: str, p: dict, dev_id: str, devs: dict) -> tuple: + """(setup path, fragment, missing, left out, entities) for an HA + device with this profile, as "Use with Cantabile" would write it.""" + dv = next((d for d in reg.get("devices") or [] if d["id"] == ha_device), None) + if not dv: + raise dp.Fail(T("Home Assistant has no such device.")) + s = dp.setup_for(p, dv.get("domains") or []) + if not s: + raise dp.Fail(T("{profile}: this profile does not know the device's integration.", profile=p["name"])) + s = dict(s, path="existing", fields=[]) + ents = with_attrs([e for e in reg.get("entities") or [] if e.get("device_id") == ha_device + and not e.get("disabled_by")], states) + main = self.main() + proposed = main.get("source") == "proposed" # yields to the owner's devices (propose.py) + others = [self.frag(i) for i in devs if i != dev_id] + m_assets = [] if proposed else [a for a in main.get("assets") or [] if isinstance(a, dict)] + m_controls = [] if proposed else [c for c in main.get("controls") or [] if isinstance(c, dict)] + main_ids = {a.get("asset") for a in m_assets} | {c.get("id") for c in m_controls} + taken = set(main_ids) | {a["asset"] for f in others for a in f.get("assets", [])} \ + | {c["id"] for f in others for c in f.get("controls", [])} + frag, missing = dp.mapping_for(dev_id, p, s, ents, dp.area_of(reg, ents, ha_device), taken, main_ids) + busy = {a.get("entity") for a in m_assets} | {a["entity"] for f in others for a in f.get("assets", [])} + writes = dp.control_writes(m_controls) | {e for f in others for e in dp.control_writes(f.get("controls"))} + gone_a, gone_c = dp.leave_out(frag, busy, writes) + return s, frag, missing, {"values": gone_a, "controls": gone_c}, ents + + async def view(self) -> dict: + """The page's data: the devices used here, HA's devices with a + profile (and what each would give), the rest, or HA's error.""" + devs, policy = self.load(), self.policy() + used = [] + for d in sorted(devs.values(), key=lambda d: d.get("added", 0)): + frag, p = self.frag(d["id"]), self.profile(d["profile"]) or {} + targets = dp.device_targets(d, frag, self.local()) + used.append(dict(d, manufacturer=p.get("manufacturer", ""), model=p.get("name", d["profile"]), + status=p.get("status", ""), assets=frag.get("assets", []), controls=frag.get("controls", []), + switchover=dp.switchover_of(frag), shade=dp.shade_of(frag), place=dp.place_of(frag), + weather=dp.weather_of(frag), policy={t: policy[t] for t in targets if t in policy}, + protection=dp.level_of(policy, [f"device:{d['id']}"])[0])) + try: + reg, states = await self.snapshot() + except Exception as e: + return {"devices": used, "offers": [], "rest": [], "ha_error": str(e), "site": self.site(), "rooms": []} + main = self.main() + src = main.get("source") + mapped = {} + for a in main.get("assets") or []: + if isinstance(a, dict): + mapped.setdefault(a.get("entity"), []).append(a.get("asset")) + by_dev = {} + for e in reg.get("entities") or []: + by_dev.setdefault(e.get("device_id"), []).append(e["entity_id"]) + offers, rest = [], [] + for h in dp.offers(reg, self.profiles, {d.get("ha_device") for d in devs.values()}): + if not h["profiles"]: + rest.append(h) + continue + p = self.profile(h["profiles"][0]) + try: + _, frag, missing, gone, _ = self.plan(reg, states, h["id"], p, "preview", devs) + except dp.Fail as e: + frag, missing, gone = {"assets": [], "controls": []}, [str(e)], {"values": [], "controls": []} + ids = [i for e in by_dev.get(h["id"], []) for i in mapped.get(e, [])] + offers.append(dict(h, profile=p, assets=frag["assets"], controls=frag["controls"], missing=missing, + left_out=gone, in_mapping=ids, mapping_source=src)) + rooms = sorted({a.get("name") for a in reg.get("areas") or [] if a.get("name")}) + return {"devices": used, "offers": offers, "rest": rest, "site": self.site(), "rooms": rooms} + + # -- actions -------------------------------------------------------------------------- + def site(self) -> dict: + """The site's consent (the add-on's configuration): share, control.""" + c = Consent(self.state_dir) + return {"share": c.share, "control": c.control} + + async def _done(self, devs: dict, restart: bool = False): + self.write_specs(devs) + if self.changed is not None: + await (self.changed(restart=True) if restart else self.changed()) + + async def use(self, ha_device: str, pid: str, name: str = "") -> dict: + async with self.lock: + p = self.profile(pid) + if not p: + raise dp.Fail(T("No such profile.")) + devs = self.load() + if any(d.get("ha_device") == ha_device for d in devs.values()): + raise dp.Fail(T("This device is used with Cantabile already.")) + reg, states = await self.snapshot() + dev_id = dp.new_id(p, devs) + s, frag, missing, gone, ents = self.plan(reg, states, ha_device, p, dev_id, devs) + if not frag["assets"] and not frag["controls"]: + raise dp.Fail(T("Home Assistant shows none of the values this profile knows, or your mapping has them " + "all already.")) + dv = next(d for d in reg["devices"] if d["id"] == ha_device) + name = (name or "").strip()[:60] or dv.get("name_by_user") or dv.get("name") or f"{p['manufacturer']} {p['name']}" + dev = {"id": dev_id, "name": name, "profile": p["id"], "profile_version": p.get("version", ""), + "path": "existing", "ha_device": ha_device, "added": int(time.time()), "read": False, + "control": False, "category": p.get("category", ""), "ratings": dp.ratings_of(p, {}), + "missing": missing, "left_out": gone} + dp.one_weather(frag, [self.frag(i) for i in devs]) # one weather service plans + self.write_frag(dev_id, frag) + defaults = dp.profile_protection(dev_id, p, s, ents, frag) + if defaults: + entries = self.local() + entries.update(defaults) + self.save_local(entries) + devs[dev_id] = dev + self.save(devs) + log.info("device %s (%s) used with Cantabile: %d values, %d controls, consent off", name, p["id"], + len(frag["assets"]), len(frag["controls"])) + await self._done(devs) + return dev + + def _dev(self, devs: dict, dev_id: str) -> dict: + d = devs.get(dev_id) + if not d: + raise dp.Fail(T("No such device.")) + return d + + async def remove(self, dev_id: str): + async with self.lock: + devs = self.load() + dev = self._dev(devs, dev_id) + frag = self.frag(dev_id) + seal = dp.sealed(self.policy(), dev_id) + if seal: + raise dp.Fail(T("Sealed: only {who} can remove it.", who=custodian(seal))) + mine = set(dp.device_targets(dev, frag, self.local())) + try: + os.remove(self.frag_path(dev_id)) + except OSError: + pass + entries = self.local() + if mine & set(entries): + self.save_local({t: e for t, e in entries.items() if t not in mine}) + del devs[dev_id] + self.save(devs) + log.info("device %s no longer used with Cantabile", dev["name"]) + await self._done(devs, restart=bool(dev.get("read") or dev.get("control"))) + + async def consent(self, dev_id: str, read: bool, control: bool): + if not self.site()["share"]: + raise dp.Fail(T("First give your consent in the add-on's configuration (Settings, Add-ons, Cantabile Edge " + "Agent, Configuration).")) + async with self.lock: + devs = self.load() + dev = self._dev(devs, dev_id) + frag = self.frag(dev_id) + if not frag: + raise dp.Fail(T("The device's mapping is gone; use it with Cantabile again.")) + seal = dp.sealed(self.policy(), dev_id) + if seal and bool(control) != bool(dev.get("control")): + raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal))) + dev["read"], dev["control"] = bool(read), bool(control) + dp.set_consent(frag, dev["read"], dev["control"]) + self.write_frag(dev_id, frag) + self.save(devs) + log.info("consent: %s: reading %s, control %s", dev["name"], "on" if dev["read"] else "off", + "on" if dev["control"] else "off") + await self._done(devs, restart=True) + + async def protect(self, dev_id: str, target: str, level: str, by: str): + async with self.lock: + devs = self.load() + dev = self._dev(devs, dev_id) + frag = self.frag(dev_id) + entries = self.local() + target = target or f"device:{dev_id}" + entries[target] = dp.owner_entry(self.policy(), dp.device_targets(dev, frag, entries), dev_id, target, + level, by) + self.save_local(entries) + log.info("protection: %s: %s %s (by %s)", dev["name"], target, level, by) + await self._done(devs) + + async def switchover(self, dev_id: str, data: dict): + async with self.lock: + devs = self.load() + dev = self._dev(devs, dev_id) + frag = self.frag(dev_id) + seal = dp.sealed(self.policy(), dev_id) + if seal: + raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal))) + sw = dp.set_switchover(frag, data) + self.write_frag(dev_id, frag) + log.info("heating or cooling: %s: %s", dev["name"], sw["mode"]) + await self._done(devs, restart=True) + + + async def _setting(self, dev_id: str): + devs = self.load() + dev = self._dev(devs, dev_id) + frag = self.frag(dev_id) + if not frag: + raise dp.Fail(T("The device's mapping is gone; use it with Cantabile again.")) + seal = dp.sealed(self.policy(), dev_id) + if seal: + raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal))) + return devs, dev, frag + + async def shade(self, dev_id: str, data: dict): + """A shade's room and its window's orientation.""" + async with self.lock: + devs, dev, frag = await self._setting(dev_id) + sh = dp.set_shade(frag, data, [self.frag(i) for i in devs if i != dev_id]) + self.write_frag(dev_id, frag) + log.info("shade: %s: room %s, facing %g", dev["name"], sh["area"] or "-", sh["facing"]) + await self._done(devs, restart=True) + + async def place(self, dev_id: str, data: dict): + """A temperature sensor indoor (its room) or outdoor.""" + async with self.lock: + devs, dev, frag = await self._setting(dev_id) + main = self.main() + taken = {a.get("asset") for a in main.get("assets") or [] if isinstance(a, dict)} \ + | {a["asset"] for i in devs if i != dev_id for a in self.frag(i).get("assets", [])} + pl = dp.set_place(frag, data, taken) + self.write_frag(dev_id, frag) + log.info("place: %s: %s %s", dev["name"], pl["place"], pl["area"]) + await self._done(devs, restart=True) + + async def weather(self, dev_id: str): + """This weather service's forecast plans; the others are kept, unused.""" + async with self.lock: + devs, dev, _ = await self._setting(dev_id) + frags = {i: self.frag(i) for i in devs} + dp.set_weather(frags, dev_id) + for i, f in frags.items(): + if f.get("profile") == "ha-weather": + self.write_frag(i, f) + log.info("weather: %s plans", dev["name"]) + await self._done(devs, restart=True) + + +def custodian(e: dict | None) -> str: + c = (e or {}).get("custodian") + return T(CUSTODIAN_WORDS[c]) if c in CUSTODIAN_WORDS else T("its custodian") + + +# ---- the page ----------------------------------------------------------------------------- + +def form(do: str, inner: str, button: str, cls: str = "", inline: bool = False) -> str: + return (f'
' + f'{inner}' + f'{E(button)}') + + +def hidden(**kw) -> str: + return "".join(f'' for k, v in kw.items()) + + +def what_lines(assets: list, controls: list, would: bool) -> str: + reads = ", ".join(quantity_words(a["asset"]) for a in assets) or T("nothing") + kinds = ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in controls)) + if would: + out = T("Cantabile would read: {values}.", values=reads) + if kinds: + out += " " + T("It could control: {controls}.", controls=kinds) + else: + out = T("Cantabile reads: {values}.", values=reads) + if kinds: + out += " " + T("It may control: {controls}.", controls=kinds) + return f'

{E(out)}

' + + +def notes(d: dict) -> str: + out = [] + if d.get("missing"): + out.append(T("Not found in Home Assistant: {entities}.", entities=", ".join(d["missing"]))) + gone = d.get("left_out") or {} + if gone.get("values"): + out.append(T("Read by your own mapping already, so left out here: {values}.", + values=", ".join(quantity_words(q) for q in gone["values"]))) + if gone.get("controls"): + out.append(T("Another control writes to this device already, so Cantabile leaves out: {controls}.", + controls=", ".join(T(CONTROL_WORDS.get(k, k)) for k in gone["controls"]))) + assumed = [a["asset"] for a in d.get("assets") or [] if a.get("assumed")] + if assumed: + out.append(T("Assumed, not measured: {values}. This device does not report back (infrared): Cantabile shows " + "what was last sent to it and never takes it as feedback.", + values=", ".join(quantity_words(q) for q in assumed))) + return "".join(f'

{E(x)}

' for x in out) + + +def consent_html(d: dict, site: dict) -> str: + """Reading and control, the owner's per device, as on the Hub's Devices + page; only with the site's consent (the add-on's configuration).""" + kinds = ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in d.get("controls") or [])) + if not site.get("share"): + return ('

' + E(T("Reading and control are off. To switch them on, first give your consent in the " + "add-on's configuration (Settings, Add-ons, Cantabile Edge Agent, Configuration).")) + + "

") + ctl = ('") if kinds else "" + note = ('

' + E(T("Control also needs your consent to control devices in the add-on's configuration.")) + + "

") if kinds and not site.get("control") else "" + return form("consent", hidden(id=d["id"]) + '{ctl}", T("Save")) + note + + +def switchover_html(d: dict) -> str: + sw = d.get("switchover") + if not sw: + return "" + mode = sw.get("mode", "season") + lo, hi = sw.get("heat_below_c", 15), sw.get("cool_above_c", 22) + radios = "".join(f'" for k, w in SWITCHOVER_WORDS.items()) + inner = (hidden(id=d["id"]) + f'

{E(T("This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched."))}

' + + radios + + f'' + f'' + f'' + f'' + f'

{E(T("Between the two it stays as it is, so it does not switch back and forth on a mild day."))}

') + return f"
{E(T('Heating or cooling'))}{form('switchover', inner, T('Save'))}
" + + +FACING_WORDS = {"": M("Not known"), "N": M("North"), "NE": M("North-east"), "E": M("East"), "SE": M("South-east"), + "S": M("South"), "SW": M("South-west"), "W": M("West"), "NW": M("North-west")} + + +def _room_options(rooms, current: str) -> str: + names = list(rooms) + if current and current not in {dp.slug(r) for r in names}: + names.append(current) + return f'' + "".join( + f'' for r in names) + + +def shade_html(d: dict, rooms) -> str: + """A shade (ha-cover): the room it shades and the window's orientation.""" + sh = d.get("shade") + if not sh: + return "" + face = sh.get("facing", -1) + cur = next((k for k, v in dp.ORIENTATIONS.items() if face >= 0 and abs(v - face) < 0.5), "" if face < 0 else None) + opts = "".join(f'' for k, w in FACING_WORDS.items()) + if cur is None: + opts += f'' + inner = (hidden(id=d["id"]) + '

' + E(T( + "Cantabile moves it by the sun: in summer it closes it while the sun is on the window and the room is warm; in " + "winter it opens it for the sun's warmth and closes it at night. Never between 22:00 and 07:00, and after you " + "move it by hand it waits 4 hours.")) + "

" + f'' + f'' + '

' + E(T("Without the window's direction Cantabile only closes it at night in winter.")) + "

") + return f"
{E(T('Room and window'))}{form('shade', inner, T('Save'))}
" + + +def place_html(d: dict, rooms) -> str: + """A temperature sensor (ha-climate-sensor): indoor (its room) or outdoor.""" + pl = d.get("place") + if not pl: + return "" + chk = lambda k: " checked" if pl["place"] == k else "" # noqa: E731 + inner = (hidden(id=d["id"]) + + f'' + + f'' + + f'' + + '

' + E(T("An outdoor sensor counts before the weather service's temperature.")) + "

") + return f"
{E(T('Indoor or outdoor'))}{form('place', inner, T('Save'))}
" + + +def weather_html(d: dict) -> str: + """A weather service (ha-weather): whether its forecast plans.""" + w = d.get("weather") + if not w: + return "" + if w.get("active"): + return '

' + E(T("Cantabile plans with this forecast: solar, heating, cooling and the shades.")) + "

" + return ('

' + E(T("Not used for planning: Cantabile plans with one weather forecast, another one's.")) + + "

" + form("weather", hidden(id=d["id"]), T("Plan with this forecast"), "secondary")) + + +def protection_html(d: dict) -> str: + """Per target a switch for the owner; sealed ones locked with their + custodian.""" + pol = d.get("policy") or {} + targets = [f"device:{d['id']}"] + [f"control:{c['id']}" for c in d.get("controls") or [] if c.get("id")] + targets += [t for t in pol if t not in targets] + seal = (pol.get(f"device:{d['id']}") or {}) if d.get("protection") == "sealed" else None + rows = [] + covers = {f"control:{c['id']}" for c in d.get("controls") or [] if c.get("kind") == "cover" and c.get("id")} + for t in targets: + e = pol.get(t) or {} + kind, _, name = t.partition(":") + what = {"device": T("The whole device"), "control": T("Control {name}", name=name)}.get(kind, name) + lift = T("Allow Cantabile to move it") if t in covers else T("Allow switching off") + lvl = "sealed" if seal else e.get("level", "none") + if lvl == "sealed": + why = (seal or e).get("why") + rows.append(f'
  • {E(what)}: {E(T("Sealed"))} · {E(T("only {who} can change it", who=custodian(seal or e)))}' + f'{": " + E(why) if why else ""}
  • ') + continue + why = f" ({E(e['why'])})" if e.get("why") and lvl == "protected" else "" + state = f"{E(T('protected'))}" if lvl == "protected" else E(T("not protected")) + rows.append(f"
  • {E(what)}: {state}{why} " + + form("protect", hidden(id=d["id"], target=t, level="none" if lvl == "protected" else "protected"), + lift if lvl == "protected" else T("Protect"), "secondary", inline=True) + + "
  • ") + return (f"
    {E(T('Protection'))}

    " + + E(T("Protected: Cantabile never switches it off or cuts it; you still can, by hand. Sealed: only its " + "custodian can change it.")) + ("" if not covers else " " + E(T( + "A protected blind or curtain is not moved by Cantabile at all."))) + + f'

      {"".join(rows)}
    ') + + +def badges(d: dict) -> str: + st = PROFILE_STATUS.get(d.get("status")) + out = f'{E(d.get("manufacturer", ""))} {E(d.get("model", ""))}' + if d.get("generic"): + out += f'{E(T("generic profile"))}' + if st: + out += f'{E(T(st))}' + return out + + +def device_card(d: dict, site: dict, rooms=()) -> str: + return (f'
    {E(d["name"])}{badges(d)}{what_lines(d.get("assets") or [], d.get("controls") or [], False)}' + f'{notes(d)}{consent_html(d, site)}{switchover_html(d)}{shade_html(d, rooms)}{place_html(d, rooms)}' + f'{weather_html(d)}{protection_html(d)}' + f"
    {E(T('Remove'))}

    " + + E(T("Cantabile stops using it. Home Assistant keeps the device as it is.")) + + "

    " + form("remove", hidden(id=d["id"]), T("Stop using it with Cantabile"), "secondary") + "
    ") + + +def offer_card(h: dict) -> str: + p = h["profile"] + name = h["name"] or h["model"] + proposed = "" + if h.get("in_mapping"): + ids = ", ".join(quantity_words(i) for i in h["in_mapping"]) + proposed = '

    ' + E( + T("Proposed by Cantabile (not checked yet): {values}. Use it with Cantabile to confirm it as this profile " + "sees it.", values=ids) if h.get("mapping_source") in ("proposed", "imported") + else T("In your own mapping: {values}. Those stay as they are.", values=ids)) + "

    " + body = what_lines(h["assets"], h["controls"], True) + notes(h) + proposed + view = dict(h, status=p.get("status")) + if not h["assets"] and not h["controls"]: + return f'
    {E(name)}{badges(view)}{body}
    ' + return (f'
    {E(name)}{badges(view)}{body}' + + form("use", hidden(ha_device=h["id"], profile=p["id"], name=name), T("Use with Cantabile")) + "
    ") + + +def nav(page: str) -> str: + items = (("devices", T("Devices")), ("building", T("Building or community"))) + return "" + + +def html(title: str, body: str, page: str) -> str: + return (f"{E(title)}" + f"{nav(page)}{body}") + + +def page_devices(v: dict, msg: str = "", err: str = "") -> str: + body = [f"

    {E(T('Devices'))}

    " + + E(T("Home Assistant's devices that a Cantabile device profile knows. Use one with Cantabile to see it on " + "Cantabile's dashboard and to let Cantabile read it once you have given your consent.")) + "

    "] + if msg: + body.append(f'
    {E(msg)}
    ') + if err: + body.append(f'
    {E(err)}
    ') + if v.get("devices"): + body.append(f"

    {E(T('Used with Cantabile'))}

    ") + body += [device_card(d, v.get("site") or {}, v.get("rooms") or []) for d in v["devices"]] + if v.get("offers"): + body.append(f"

    {E(T('In Home Assistant, with a profile'))}

    ") + body += [offer_card(h) for h in v["offers"]] + elif not v.get("ha_error") and not v.get("devices"): + body.append('

    ' + E(T("No device in Home Assistant fits a Cantabile profile yet.")) + "

    ") + if v.get("rest"): + n = len(v["rest"]) + body.append(f"
    {E(TN('{n} more in Home Assistant without a profile (not used by Cantabile)', '{n} more in Home Assistant without a profile (not used by Cantabile)', n))}
      " + + "".join(f"
    • {E(h['name'] or h['model'])} {E(h['manufacturer'])} {E(h['model'])}
    • " + for h in v["rest"]) + "
    ") + if v.get("ha_error"): + body.append('

    ' + E(T("Home Assistant's devices could not be read: {error}", error=v["ha_error"])) + "

    ") + return html(T("Cantabile: devices"), "".join(body), "devices") + + +def page_refused(why: str, page: str = "devices") -> str: + head = T("Devices") if page == "devices" else T("Building or community") + return html("Cantabile", f"

    {E(head)}

    {E(why)}
    ", page) + + +class App(JoinPage): + """The add-on's pages: Devices (the first) and Building or community.""" + + def __init__(self, fleet, devices: Devices, location=None, admin=None): + super().__init__(fleet, **({"location": location} if location else {})) + self.devices = devices + # admin(user_id) -> bool: the agent's HA client asks HA (ha.is_admin) + self.admin = admin or self._admin + + async def _admin(self, user_id: str) -> bool: + client = self.devices.ha() + if client is None: + raise dp.Fail(T("Home Assistant is not connected yet; try again in a moment.")) + return await client.is_admin(user_id) + + async def respond(self, method, url, hdr, data, peer): + q = urllib.parse.parse_qs(url.query) + page = (q.get("p") or [""])[0] + if page not in PAGES: + page = "building" if q.get("code") else "devices" + # owner only, both pages: an administrator of Home Assistant (HA's + # ingress names the user; this container itself is trusted) + user = hdr.get("x-remote-user-id", "") + if peer not in ("127.0.0.1", "::1"): + try: + ok = bool(user) and await self.admin(user) + except Exception as e: + return 200, page_refused(T("Cantabile could not ask Home Assistant who you are ({error}).", error=e), page) + if not ok: + return 200, page_refused(T("Only an administrator of Home Assistant can use this page."), page) + if page == "building": + status, out = await super().respond(method, url, hdr, data, peer) + if status == 200: + out = out.replace("", f"\n{MORE_CSS}", 1) \ + .replace("", "" + nav("building"), 1) + return status, out + if url.path not in ("/", "") or method not in ("GET", "POST"): + return 404, T("Not found") + if method == "GET": + return 200, page_devices(await self.devices.view()) + f = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode("utf-8", "replace")).items()} + by = hdr.get("x-remote-user-display-name") or hdr.get("x-remote-user-name") or "owner" + return 200, await self.post_devices(f, by) + + async def post_devices(self, f: dict, by: str = "owner") -> str: + dv, do, msg, err = self.devices, f.get("do", ""), "", "" + try: + if do == "use": + d = await dv.use(f.get("ha_device", ""), f.get("profile", ""), f.get("name", "")) + msg = T("{name} is used with Cantabile now. It is on Cantabile's dashboard; reading and control are off " + "until you switch them on below.", + name=d["name"]) + elif do == "remove": + await dv.remove(f.get("id", "")) + msg = T("Cantabile no longer uses it.") + elif do == "consent": + await dv.consent(f.get("id", ""), f.get("read") == "1", f.get("control") == "1") + msg = T("Saved. Cantabile starts again to apply it (a few seconds).") + elif do == "protect": + await dv.protect(f.get("id", ""), f.get("target", ""), f.get("level", ""), by) + msg = T("Saved.") + elif do == "shade": + await dv.shade(f.get("id", ""), {"area": f.get("area", ""), "facing": f.get("facing", "")}) + msg = T("Saved. Cantabile starts again to apply it (a few seconds).") + elif do == "place": + await dv.place(f.get("id", ""), {"place": f.get("place", ""), "area": f.get("area", "")}) + msg = T("Saved. Cantabile starts again to apply it (a few seconds).") + elif do == "weather": + await dv.weather(f.get("id", "")) + msg = T("Saved. Cantabile starts again to apply it (a few seconds).") + elif do == "switchover": + data = {"mode": f.get("mode", "")} + if data["mode"] == "outdoor": + data.update(heat_below_c=f.get("heat_below_c", ""), cool_above_c=f.get("cool_above_c", "")) + await dv.switchover(f.get("id", ""), data) + msg = T("Saved. Cantabile starts again to apply it (a few seconds).") + except dp.Fail as e: + err = str(e) + return page_devices(await dv.view(), msg, err) diff --git a/src/edge/cantabile_edge/devprofiles.py b/src/edge/cantabile_edge/devprofiles.py new file mode 100644 index 0000000..51b88d4 --- /dev/null +++ b/src/edge/cantabile_edge/devprofiles.py @@ -0,0 +1,697 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Device profiles applied to Home Assistant's devices, shared +by both places a device is taken into Cantabile: +- the Hub's devices tool (/usr/lib/cantabile/devices; the build installs + this file there as /usr/lib/cantabile/python/cantabile_devprofiles.py); +- the HA add-on: its Devices page (devpage.py), the mapping's proposal + (propose.py) and the dashboard's device views (devview.py). +Standard library only, no imports from the edge package: the Hub runs it +outside the agent's image. + +What is here: Cantabile's quantities, which profile recognises an HA device +(specific profiles first, a generic one such as ha-thermostat only where +none fits), a profile's matchers on HA's entities, the agent's mapping +fragment for one device (consent off), per-device consent, and the +protection rules (protected = never switched off by +Cantabile, lifted only by the owner; sealed = only its custodian, from the +cloud). Where the files live and how HA is asked is each caller's own. +""" +import fnmatch +import re +import time + + +class Fail(Exception): + pass + + +# Cantabile's quantities: the asset ids the agent, the dashboards and the +# cloud use, with unit and kind. Signs: grid import +, battery charge +. +QUANTITIES = { + "grid.power": ("W", "gauge"), "grid.import_power": ("W", "gauge"), "grid.export_power": ("W", "gauge"), + "grid.import_energy": ("Wh", "counter"), "grid.export_energy": ("Wh", "counter"), + "pv.power": ("W", "gauge"), "pv.energy": ("Wh", "counter"), + "battery.power": ("W", "gauge"), "battery.soc": ("%", "gauge"), + "battery.charge_energy": ("Wh", "counter"), "battery.discharge_energy": ("Wh", "counter"), + "load.power": ("W", "gauge"), "load.energy": ("Wh", "counter"), + "heatpump.power": ("W", "gauge"), "heatpump.energy": ("Wh", "counter"), + "heat.power": ("W", "gauge"), "heat.energy": ("Wh", "counter"), + "heatpump.flow_temp": ("°C", "gauge"), "heatpump.dhw_temp": ("°C", "gauge"), + "outside.temp": ("°C", "gauge"), "outside.humidity": ("%", "gauge"), "heating.state": ("", "gauge"), "cooling.state": ("", "gauge"), "gas.energy": ("Wh", "counter"), + "ev.power": ("W", "gauge"), "ev.energy": ("Wh", "counter"), + "room.temp": ("°C", "gauge"), "room.humidity": ("%", "gauge"), "room.setpoint": ("°C", "gauge"), + "room.setpoint_low": ("°C", "gauge"), "room.setpoint_high": ("°C", "gauge"), + "room.shade_position": ("%", "gauge"), "room.shade_tilt": ("%", "gauge"), "circuit.power": ("W", "gauge"), + "circuit.energy": ("Wh", "counter"), +} +# room.* and circuit.* are per place: room..temp (the device's area). +PER_PLACE = ("room", "circuit") +# Systems whose quantities may come from several devices: the agent numbers +# them (pv.1.power, pv.2.power) and sums their total (edge mapping.py). +SUMMED = ("grid", "pv", "battery", "load", "heatpump", "heat", "ev", "gas") +PART_RE = re.compile(r"^(" + "|".join(SUMMED) + r")\.(\d{1,3})\.([a-z_]+)$") +# A control's roles that write to the device. +WRITE_ROLES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover"} +# Heating or cooling for a thermostat that does both (the agent's +# switchover.py): the owner's choice; by season at first. +SWITCHOVER_MODES = ("heating", "cooling", "season", "outdoor") +SWITCHOVER_DEFAULT = {"mode": "season"} +# Cantabile's Modbus bridge: its entities' unique ids and devices' identifiers. +BRIDGE = "cantabile_modbus_" +LEVELS = ("none", "protected", "sealed") +RANK = {"none": 0, "protected": 1, "sealed": 2} +# Asset and control ids in a mapping's text (the Hub's base has no YAML +# parser: the ids are found by their keys). +IDS_RE = re.compile(r"""(?:^|[\s{,-])["']?(?:asset|id)["']?\s*:\s*["']?([A-Za-z0-9_.-]+)""", re.M) + + +def part_of(asset: str): + """pv.2.power -> ("pv.power", 2); None for anything else.""" + m = PART_RE.match(asset) + return (f"{m.group(1)}.{m.group(3)}", int(m.group(2))) if m else None + + +def quantity_of(q: str): + """(unit, kind) of a quantity: room.kitchen.temp and room.{area}.temp + as room.temp, pv.2.power as pv.power; None if it is not one.""" + head, _, rest = q.partition(".") + if head in PER_PLACE and "." in rest: + return QUANTITIES.get(f"{head}.{rest.rsplit('.', 1)[1]}") + part = part_of(q) + return QUANTITIES.get(part[0] if part else q) + + +def slug(s) -> str: + return re.sub(r"[^a-z0-9]+", "_", str(s).lower()).strip("_") or "x" + + +def ids_in(text: str) -> set: + return set(IDS_RE.findall(text or "")) + + +def free_id(want: str, taken: set) -> str: + out, n = want, 2 + while out in taken: + out, n = f"{want}_{n}", n + 1 + taken.add(out) + return out + + +def bridge_uid(dev_id: str, key: str) -> str: + return f"{BRIDGE}{slug(dev_id)}_{key}" + + +# --- which profile fits an HA device ------------------------------------------------------ + +def glob_match(pattern, value) -> bool: + return value is not None and fnmatch.fnmatch(str(value).lower(), str(pattern).lower()) + + +def _fits(h: dict, d: dict, domains, entity_domains) -> bool: + return all((k == "domain" and any(glob_match(v, x) for x in domains)) or + (k == "entity_domain" and any(glob_match(v, x) for x in entity_domains)) or + (k not in ("domain", "entity_domain") and glob_match(v, d.get(k))) for k, v in h.items()) + + +def recognise(p: dict, d: dict, domains=(), entity_domains=()) -> bool: + """Does this HA device fit the profile (recognise.ha patterns: maker, + model, domain: its integration's, entity_domain: a domain of one of its + entities, e.g. climate, or a domain with the entity's device class, + e.g. cover.curtain, sensor.temperature)? A device that fits one of + recognise.exclude (the same patterns) never fits: a garage door is never + a shade, the box's own CPU temperature never a room's.""" + rec = p.get("recognise") or {} + if any(_fits(h, d, domains, entity_domains) for h in rec.get("exclude", [])): + return False + return any(_fits(h, d, domains, entity_domains) for h in rec.get("ha", [])) + + +def fallback(p: dict) -> bool: + """A generic profile (any climate device): only where no specific one fits.""" + return bool((p.get("recognise") or {}).get("fallback")) + + +def by_priority(profiles) -> list: + """Specific profiles first, generic (fallback) ones last.""" + return sorted(profiles, key=fallback) + + +def fitting(profiles, d: dict, domains=(), entity_domains=()) -> list: + """The profiles that recognise an HA device, specific ones first; a + fallback profile only when none of those does.""" + fits = [p for p in profiles if recognise(p, d, domains, entity_domains)] + specific = [p for p in fits if not fallback(p)] + return sorted(specific or fits, key=lambda p: p["id"]) + + +def device_class(e: dict, attrs=None): + """The entity's device class: HA's state attribute (the owner's choice + in HA wins there), else the registry's.""" + a = attrs if isinstance(attrs, dict) else attrs_of(e) or {} + return a.get("device_class") or e.get("device_class") or e.get("original_device_class") + + +def kinds_of(e: dict, attrs=None) -> set: + """An entity's domain, and with its device class "." + (cover.curtain, sensor.temperature); a diagnostic or configuration + entity (a device's own CPU temperature) only its domain.""" + dom = str(e.get("entity_id", "")).split(".")[0] + dc = None if e.get("entity_category") else device_class(e, attrs) + return {dom} | ({f"{dom}.{dc}"} if dc else set()) + + +def entity_domains(reg: dict, dev_id: str) -> list: + return sorted({k for e in reg.get("entities") or [] if e.get("device_id") == dev_id and not e.get("disabled_by") + and "." in str(e.get("entity_id")) for k in kinds_of(e)}) + + +def setup_for(p: dict, domains) -> dict | None: + """The setup path of a device HA has already: its integration's (its + entities have that path's names), else the profile's "existing" path.""" + for s in p.get("setup") or []: + if s.get("domain") and s["domain"] in (domains or []): + return s + return next((s for s in p.get("setup") or [] if s["path"] == "existing"), None) + + +# --- matchers on HA's entities ------------------------------------------------------------ + +_KNOWN = object() + + +def attrs_of(e: dict) -> dict | None: + """The entity's attributes, where the caller put them with it (the Hub's + ha-setup registry; the add-on adds them from HA's states).""" + a = e.get("attributes") + return a if isinstance(a, dict) else None + + +def assumed_state(e: dict, attrs: dict | None) -> bool | None: + """No feedback from the device: HA assumes its state (assumed_state; a + climate without hvac_action: ESPHome's infrared climates). None when + HA's state is not known.""" + if attrs is None: + return None + if attrs.get("assumed_state"): + return True + return e["entity_id"].startswith("climate.") and attrs.get("hvac_action") is None + + +def entity_matches(m: dict, e: dict, attrs=_KNOWN) -> bool: + """A profile's matcher on an entity, with its conditions on HA's + attributes (attribute: has it; supports: an hvac mode; assumed; + device_class: HA's class of it, never a diagnostic entity). Where the + state is not known the conditions hold (and the entity is taken as + reporting back), except device_class (the registry's then, else no). + attrs: the entity's attributes, else attrs_of(e).""" + if attrs is _KNOWN: + attrs = attrs_of(e) + for k in ("entity_id", "unique_id", "original_name"): + if k in m and not re.search(m[k], str(e.get(k) or "")): + return False + if "translation_key" in m and e.get("translation_key") != m["translation_key"]: + return False + if "device_class" in m and (e.get("entity_category") or device_class(e, attrs) != m["device_class"]): + return False # a diagnostic entity (an inverter's own temperature) never + if attrs is not None: + if m.get("attribute") and attrs.get(m["attribute"]) is None: + return False + if m.get("supports") and m["supports"] not in (attrs.get("hvac_modes") or []): + return False + if "assumed" in m and bool(assumed_state(e, attrs)) != m["assumed"]: + return False + return True + + +def alternatives(m) -> list: + """A value's matcher, or its list of alternatives (the first that finds).""" + return [x for x in (m if isinstance(m, list) else [m]) if isinstance(x, dict)] + + +# --- the agent's mapping fragment for one device ------------------------------------------ + +def mapping_for(dev_id, p, s, ents, area, taken, main=()): + """The agent's fragment for one device: its assets and controls, consent + off; and what could not be found (shown to the owner). ents: the + device's entities (registry entries, attributes where known); taken: + the ids in use (grows); main: the ids of the site's own mapping (a + summed system's quantity there makes this device's an id of its own).""" + assets, controls, missing = [], [], [] + values = dict(s.get("values") or {}) + if s["path"] == "modbus": + for r in p["modbus"]["registers"]: + if "quantity" in r: + values.setdefault(r["quantity"], {"key": r["key"]}) + for q in (r.get("split") or {}).values(): + values.setdefault(q, {"key": r["key"], "part": q}) + + def find(m): + hits = [e for e in ents if entity_matches(m, e)] if s["path"] != "modbus" else \ + [e for e in ents if e.get("unique_id") == bridge_uid(dev_id, m.get("part") and slug(m["part"]) or m["key"])] + return hits[0] if hits else None + + for q, alts in values.items(): + e = m = None + for m in (alts if isinstance(alts, list) else [alts]): + e = find(m) + if e: + break + if not e: + missing.append(q) + continue + quantity = q.replace("{area}", slug(area or "home")) + unit, kind = quantity_of(q) + # pv.power of a second inverter stays pv.power here: the agent numbers + # the devices' parts (pv.1.power, pv.2.power) and sums their total + own = quantity.split(".")[0] in SUMMED and quantity not in main + a = {"entity": e["entity_id"], "asset": quantity if own else free_id(quantity, taken), "kind": kind, + "unit": unit, "consent": False} + if m.get("scale", 1) != 1: + a["scale"] = m["scale"] + for k in ("attribute", "equals"): + if m.get(k): + a[k] = m[k] + if m.get("assumed"): + a["assumed"] = True # no feedback: never taken as measured + if m.get("fallback"): + a["fallback"] = True # yields its id to a measured one (the weather's outside.temp) + assets.append(a) + written = {} # entity -> the control that writes it + for c in s.get("controls", []): + ents_c, lost = {}, [] + for role, m in c["entities"].items(): + e = find(m) + if e: + ents_c[role] = e["entity_id"] + elif m.get("supports") and find({k: v for k, v in m.items() if k != "supports"}): + lost.append(None) # the device has no such mode (a cooling-only A/C: no heating) + else: + lost.append(role) + if None in lost: + continue + if lost: + missing.append(f"{c['kind']} control ({', '.join(lost)})") + continue + writes = {e for r, e in ents_c.items() if r in WRITE_ROLES} + ctl = {"id": free_id(c["kind"], taken) if not writes & set(written) else None, "kind": c["kind"], + "consent": False, "entities": ents_c} + if writes & set(written): + # one control per entity; a thermostat that heats and cools has + # both, paired: the agent uses one at a time (switchover) + other = written[next(iter(writes & set(written)))] + if not (set(ents_c) == {"climate"} == set(other["entities"]) and {c["kind"], other["kind"]} + == {"heating", "cooling"} and "switchover" not in other): + continue + other["switchover"] = dict(SWITCHOVER_DEFAULT) + ctl["id"] = free_id(c["kind"], taken) + ctl["switchover"] = dict(SWITCHOVER_DEFAULT) + for e in writes: + written.setdefault(e, ctl) + if c.get("params"): + ctl["params"] = dict(c["params"]) + if c["kind"] == "cover" and area: + ctl.setdefault("params", {})["area"] = slug(area) # the room it shades: its device's area at first + if c.get("safe"): + ctl["safe"] = c["safe"] + controls.append(ctl) + frag = {"version": 3, "device": dev_id, "profile": p["id"], "assets": assets, "controls": controls} + # the optimiser's inputs the device gives (a weather entity: its forecast) + for k, m in (s.get("inputs") or {}).items(): + e = next((x for x in (find(y) for y in alternatives(m)) if x), None) + if e: + frag.setdefault("inputs", {})[k] = e["entity_id"] + return frag, missing + + +def leave_out(frag: dict, entities=(), written=()) -> tuple[list, list]: + """Takes out of a fragment what the site already has elsewhere: values of + entities another mapping reads (entities), and controls writing to an + entity another control writes (written): one writer per entity. In + place; (the values' ids, the controls' kinds) left out.""" + entities, written = set(entities), set(written) + gone_a = [a["asset"] for a in frag.get("assets", []) if a["entity"] in entities] + frag["assets"] = [a for a in frag.get("assets", []) if a["entity"] not in entities] + gone_c, keep = [], [] + for c in frag.get("controls", []): + writes = {e for r, e in (c.get("entities") or {}).items() if r in WRITE_ROLES} + (gone_c.append(c["kind"]) if writes & written else keep.append(c)) + frag["controls"] = keep + return gone_a, gone_c + + +def control_writes(controls) -> set: + """The entities some control writes to.""" + return {e for c in controls or [] for r, e in (c.get("entities") or {}).items() if r in WRITE_ROLES} + + +def switchover_of(frag: dict) -> dict | None: + """The heating/cooling choice of a device that has both, or None.""" + pair = [c for c in frag.get("controls", []) if "switchover" in c] + return dict(pair[0]["switchover"]) if len(pair) >= 2 else None + + +def set_switchover(frag: dict, data: dict) -> dict: + """The owner's choice for a thermostat that heats and cools: heating, + cooling, by season (October-April heating), or by the outdoor + temperature (heating below heat_below_c, cooling above cool_above_c, the + side it was on between them). Into both its controls (in place).""" + pair = [c for c in frag.get("controls", []) if "switchover" in c] + if len(pair) < 2: + raise Fail("this device has no heating and cooling to choose between") + mode = data.get("mode") + if mode not in SWITCHOVER_MODES: + raise Fail(f"mode is one of {', '.join(SWITCHOVER_MODES)}") + sw = {"mode": mode} + if mode == "outdoor": + try: + lo, hi = float(data.get("heat_below_c", 15)), float(data.get("cool_above_c", 22)) + except (TypeError, ValueError): + raise Fail("the temperatures are numbers") from None + if not -30 <= lo < hi <= 45: + raise Fail("heat below a lower temperature than cool above (-30 to 45 °C)") + sw.update(heat_below_c=lo, cool_above_c=hi) + for c in pair: + c["switchover"] = dict(sw) + return sw + + +def area_of(reg: dict, ents, ha_device=None): + areas = {a["area_id"]: a["name"] for a in reg.get("areas") or []} + devices = {d["id"]: d for d in reg.get("devices") or []} + for e in ents: + a = e.get("area_id") or (devices.get(e.get("device_id")) or {}).get("area_id") + if a in areas: + return areas[a] + return areas.get((devices.get(ha_device) or {}).get("area_id")) + + +def fragment_entities(frag: dict) -> list: + out = [a["entity"] for a in frag.get("assets", [])] + for c in frag.get("controls", []): + out += list((c.get("entities") or {}).values()) + return sorted(set(out)) + + +def set_consent(frag: dict, read: bool, control: bool): + """The owner's consent for one device: every value read, every control + (in place).""" + for a in frag.get("assets", []): + a["consent"] = bool(read) + for c in frag.get("controls", []): + c["consent"] = bool(control) + + +def offers(reg: dict, profiles, taken=()) -> list: + """HA's devices with the profiles that fit each (none: not used by + Cantabile), without those taken (used already: an HA device id or a + config entry id); with a profile first.""" + taken = set(taken) + out = [] + for dv in reg.get("devices") or []: + if dv.get("disabled_by") or not (dv.get("manufacturer") or dv.get("model") or dv.get("entry_type") == "service"): + continue + # HA's services (Backup, Google Translate, the Supervisor's apps) and + # Cantabile's own agent are no devices to offer + # (a weather service, met.no's "Forecast", is offered: its forecast plans) + edoms = entity_domains(reg, dv["id"]) + if (dv.get("entry_type") == "service" and "weather" not in edoms) or dv.get("manufacturer") == "Cantabile" \ + or "hassio" in (dv.get("domains") or []): + continue + if dv["id"] in taken or set(dv.get("config_entries") or []) & taken: + continue + fits = fitting(profiles, dv, dv.get("domains") or [], edoms) + out.append({"id": dv["id"], "name": dv.get("name_by_user") or dv.get("name") or "", + "manufacturer": dv.get("manufacturer") or "", "model": dv.get("model") or "", + "domains": dv.get("domains") or [], "profiles": [p["id"] for p in fits], + "generic": bool(fits) and fallback(fits[0])}) + return sorted(out, key=lambda x: (not x["profiles"], x["manufacturer"], x["name"])) + + +def new_id(p: dict, devs) -> str: + base = slug(p["id"]).replace("_", "-") + n = 1 + while f"{base}-{n}" in devs: + n += 1 + return f"{base}-{n}" + + +def ratings_of(p: dict, vals: dict) -> dict: + """The device's ratings: the profile's, the owner's answers over them.""" + out = dict(p.get("ratings") or {}) + for f in p.get("fields", []): + if f.get("rating") and f["name"] in vals: + out[f["rating"]] = vals[f["name"]] + return out + + +# --- protection ------------------------------------------------------------- +# Targets: "device:", "control:", +# "entity:". An entry: {level: none|protected|sealed, +# custodian (sealed), set_by, role, at, why, source: cloud|owner|profile}. +# In force per target: a sealed entry from the cloud always; the box's own +# never lowers it; otherwise the newer entry (a custodian lifting a +# profile's seal from the cloud is newer than the profile's default). + +def acl_entries(acl: dict) -> dict: + """The cloud's entries (the link checked the bundle's signature, site + and expiry; here its form).""" + if not isinstance(acl, dict) or acl.get("v") != 1 or acl.get("kind") != "acl": + return {} + out = {} + for e in acl.get("entries") or []: + if isinstance(e, dict) and isinstance(e.get("target"), str) and e.get("level") in LEVELS: + out[e["target"]] = dict(e, source="cloud") + return out + + +def local_entries(prot: dict) -> dict: + """The box's own entries (protection.json: the owner's, a profile's).""" + return {t: e for t, e in ((prot if isinstance(prot, dict) else {}).get("entries") or {}).items() + if isinstance(e, dict) and e.get("level") in LEVELS} + + +def merge_policy(cloud: dict, local: dict) -> dict: + out = dict(cloud) + for t, e in local.items(): + cur = out.get(t) + if cur and cur["level"] == "sealed": + continue # only its custodian, from the cloud + if cur is None or float(e.get("at", 0)) > float(cur.get("at", 0)): + out[t] = e + return out + + +def level_of(policy: dict, targets) -> tuple: + """The strongest level among the targets (a device's covers its + controls and entities), and its entry.""" + best = ("none", None) + for t in targets: + e = policy.get(t) + if e and RANK[e["level"]] > RANK[best[0]]: + best = (e["level"], e) + return best + + +def device_targets(dev: dict, frag: dict, local: dict) -> list: + """The device, its controls and entities, and what its profile + protects (an entity Cantabile does not map, e.g. an inverter's output + switch).""" + ts = [f"device:{dev['id']}"] + ts += [f"control:{c['id']}" for c in frag.get("controls", [])] + ts += [f"entity:{e}" for e in fragment_entities(frag)] + ts += [t for t, e in local.items() if e.get("device") == dev["id"] and t not in ts] + return ts + + +def profile_protection(dev_id, p, s, ents, frag, now=None) -> dict: + """A new device's entries from its profile: the device's, its controls' + and the entities its setup path protects.""" + now = time.time() if now is None else now + out = {} + + def put(target, x): + out[target] = {"level": x["level"], **({"custodian": x["custodian"]} if x.get("custodian") else {}), + "why": x.get("why") or f"{p['manufacturer']} {p['name']}", "set_by": f"profile {p['id']}", + "role": "profile", "at": now, "source": "profile", "device": dev_id} + if p.get("protection"): + put(f"device:{dev_id}", p["protection"]) + kinds = {} + for c in s.get("controls", []): + if c.get("protection"): + kinds[c["kind"]] = {"level": c["protection"], "custodian": c.get("custodian") or (p.get("protection") or {}).get("custodian")} + for c in frag.get("controls", []): + if c["kind"] in kinds: + put(f"control:{c['id']}", kinds[c["kind"]]) + for x in s.get("protect", []): + m = x["match"] + if s["path"] == "modbus": + hits = [e for e in ents if e.get("unique_id") == bridge_uid(dev_id, m["key"])] + else: + hits = [e for e in ents if entity_matches(m, e)] + for e in hits: + put(f"entity:{e['entity_id']}", x) + return out + + +def custodian_words(e: dict | None) -> str: + return (e or {}).get("custodian", "?").replace("_", " ") + + +def owner_entry(policy: dict, targets, dev_id: str, target: str, level: str, by: str = "owner", + why: str = "", now=None) -> dict: + """The owner's protection of one of the device's targets: none or + protected, never a sealed one, never to sealed (a custodian's, from + Cantabile). The new entry for the box's own policy.""" + if target not in targets: + raise Fail("not this device's") + if level not in ("none", "protected"): + raise Fail("the owner sets none or protected; sealed is a custodian's, from Cantabile") + cur, entry = level_of(policy, targets) + own = policy.get(target) + if (own and own["level"] == "sealed") or (cur == "sealed" and target == f"device:{dev_id}"): + raise Fail(f"sealed by its custodian ({custodian_words(entry or own)}): only they can change it") + return {"level": level, "set_by": str(by or "owner")[:60], "role": "owner", + "at": time.time() if now is None else now, "why": str(why or "")[:200], "source": "owner", "device": dev_id} + + +def sealed(policy: dict, dev_id: str) -> dict | None: + """The seal on the whole device, if any.""" + lvl, e = level_of(policy, [f"device:{dev_id}"]) + return e if lvl == "sealed" else None + + +# --- the owner's settings per device kind ------------------------------------------------- +# A shade (ha-cover): the room it shades and its window's orientation. +ORIENTATIONS = {"N": 0, "NE": 45, "E": 90, "SE": 135, "S": 180, "SW": 225, "W": 270, "NW": 315} + + +def parse_facing(v) -> float: + """"N", "SW", degrees (0-360) or "" (not known: -1).""" + t = str(v if v is not None else "").strip().upper() + if t in ("", "-1", "?"): + return -1.0 + if t in ORIENTATIONS: + return float(ORIENTATIONS[t]) + try: + x = float(t) + except ValueError: + raise Fail("the window faces N, NE, E, SE, S, SW, W, NW or degrees (0-360)") from None + if not 0 <= x <= 360: + raise Fail("the window faces N, NE, E, SE, S, SW, W, NW or degrees (0-360)") + return x % 360 + + +def shade_of(frag: dict) -> dict | None: + """A shade's settings (its first cover control): area, facing, room.""" + c = next((c for c in frag.get("controls", []) if c.get("kind") == "cover"), None) + if c is None: + return None + p = c.get("params") or {} + return {"area": p.get("area", ""), "facing": float(p.get("facing", -1)), "room": p.get("room", "")} + + +def room_control(frags, area_slug: str) -> str: + """The heating or cooling control of a room (a device whose values are + that room's), "" when none: the optimiser counts a shade's sun there.""" + for f in frags: + if any(str(a.get("asset", "")).startswith(f"room.{area_slug}.") for a in f.get("assets") or []): + for c in f.get("controls") or []: + if c.get("kind") in ("heating", "cooling") and c.get("id"): + return c["id"] + return "" + + +def set_shade(frag: dict, data: dict, others=()) -> dict: + """The owner's shade settings into its cover controls (in place): area + (a room's name or its slug; "" none), facing (see parse_facing); the + room's heating or cooling control from the other devices' fragments.""" + covers = [c for c in frag.get("controls", []) if c.get("kind") == "cover"] + if not covers: + raise Fail("this device is no shade") + area = slug(data.get("area")) if str(data.get("area") or "").strip() else "" + face = parse_facing(data.get("facing")) + room = room_control(others, area) if area else "" + for c in covers: + p = c.setdefault("params", {}) + p["area"], p["facing"] = area, face + if room: + p["room"] = room + else: + p.pop("room", None) + return shade_of(frag) + + +# A temperature and humidity sensor (ha-climate-sensor): indoor (a room) or outdoor. +PLACES = ("indoor", "outdoor") + + +def place_of(frag: dict) -> dict | None: + """Indoor (its room) or outdoor: a temperature sensor's place.""" + if frag.get("profile") != "ha-climate-sensor": + return None + out = any(str(a.get("asset", "")).startswith("outside.") for a in frag.get("assets", [])) + area = next((str(a["asset"]).split(".")[1] for a in frag.get("assets", []) + if str(a.get("asset", "")).startswith("room.")), "") + return {"place": "outdoor" if out else "indoor", "area": area} + + +def set_place(frag: dict, data: dict, taken=()) -> dict: + """Indoor in a room (room..temp, .humidity; temp_2 where the room + has one already) or outdoor (outside.temp, outside.humidity, and the + optimiser's outside temperature: a measured one, over the weather's). + taken: the ids the site's other mappings use. In place.""" + if frag.get("profile") != "ha-climate-sensor": + raise Fail("this device is no temperature sensor") + where = data.get("place") + if where not in PLACES: + raise Fail("indoor or outdoor") + area = slug(data.get("area") or "home") + taken = set(taken) - {a["asset"] for a in frag.get("assets", [])} + temp = None + for a in frag.get("assets", []): + what = "humidity" if "humidity" in a["asset"] else "temp" + want = f"outside.{what}" if where == "outdoor" else f"room.{area}.{what}" + a["asset"] = free_id(want, taken) + if what == "temp": + temp = a["entity"] + frag.pop("inputs", None) + if where == "outdoor" and temp: + frag["inputs"] = {"outside_temp": temp} + return place_of(frag) + + +# A weather service (ha-weather): only one plans (the mapping's inputs.weather). +def weather_of(frag: dict) -> dict | None: + if frag.get("profile") != "ha-weather": + return None + return {"active": bool((frag.get("inputs") or {}).get("weather")), + "entity": next((a["entity"] for a in frag.get("assets", []) if a["entity"].startswith("weather.")), + (frag.get("inputs") or {}).get("weather") or (frag.get("weather_entity") or ""))} + + +def set_weather(frags: dict, dev_id: str) -> None: + """This weather device's forecast plans; every other weather device's + is kept but not used (one weather source). frags: {device: fragment}, + in place.""" + if (frags.get(dev_id) or {}).get("profile") != "ha-weather": + raise Fail("this device is no weather service") + for i, f in frags.items(): + if f.get("profile") != "ha-weather": + continue + ent = (f.get("inputs") or {}).get("weather") or f.get("weather_entity") + if not ent: + continue + f["weather_entity"] = ent + if i == dev_id: + f["inputs"] = {"weather": ent} + else: + f.pop("inputs", None) + + +def one_weather(frag: dict, others) -> None: + """A new weather device plans only when no other one does (in place).""" + ent = (frag.get("inputs") or {}).get("weather") + if ent: + frag["weather_entity"] = ent + if any((o.get("inputs") or {}).get("weather") for o in others): + frag.pop("inputs", None) diff --git a/src/edge/cantabile_edge/devview.py b/src/edge/cantabile_edge/devview.py new file mode 100644 index 0000000..4b4ecfc --- /dev/null +++ b/src/edge/cantabile_edge/devview.py @@ -0,0 +1,321 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""What one device shows on Cantabile's dashboard (dashboards.py): its +device profile's "view" (hub/profiles/README.md) resolved to the device's +entities in HA, or, for a device no profile describes, a view guessed from +HA's device classes. + +A profile's view names values by reference: +- a quantity of Cantabile's ("pv.power", "room.{area}.temp"): on Cantabile's + Modbus bridge, the register that gives it; on a device of an HA + integration, the matcher of the profile's setup path for that integration + (else its "existing" path), as the mapping's proposal does (propose.py); +- a name in view.values: {name: matcher}, a matcher with a register "key" + (the bridge) and/or HA's entity fields (entity_id, unique_id, + original_name: regular expressions; translation_key, domain, device_class: + exact); +- a register key (the bridge's devices). +Channels (circuits, phases, relays) are view.channels: {role: matcher} +with "{n}" where the channel's number or letter is; the roles are power, +energy, current, voltage and switch. + +Devices of the bridges are known by their identifiers (mqtt, +cantabile_modbus_, or the EEBUS bridge's cantabile_eebus_) and their +model (the profile's name); others by the +profile's recognise.ha patterns, as on the Hub's Devices page (specific +profiles first; a generic one, recognise.fallback, such as ha-thermostat +for any climate device, only where none fits). + +A cover card (a shade) shows HA's tile of the cover with its features +(position slider where it can be set to one, else open/close; tilt where +it has one); a weather card the service's hourly forecast. + +A climate card shows the thermostat, its view.climate_state attributes +(hvac_action, fan_mode) read-only, and, for a thermostat that does not +report back (HA's assumed_state, or no hvac_action: an infrared one), a +note that what it shows is assumed. +""" +import re +from dataclasses import dataclass, field + +from .devprofiles import kinds_of +from .propose import alternatives, assumed_state, bridge_device, bridge_prefix, by_priority, recognise + +CARDS = ("flow", "gauge", "circuits", "switches", "climate", "charger", "meter", "sensor", "cover", "weather") +ROLES = ("power", "energy", "current", "voltage", "switch") +FLOW = ("pv", "grid", "load", "battery", "soc") +N_RE = r"(?P[0-9]+|[a-z])" +HEADLINE_MAX = 6 + + +@dataclass +class DeviceView: + card: str + profile: str | None = None + category: str | None = None # the profile's (inverter, sensor, ...) + headline: list[str] = field(default_factory=list) # entity ids, in order + flow: dict[str, str] = field(default_factory=dict) # pv/grid/load/battery/soc -> entity + energy: list[str] = field(default_factory=list) # counters (energy today) + channels: list[dict] = field(default_factory=list) # [{"n", role: entity}], in order + climate: str | None = None + switches: list[str] = field(default_factory=list) + climate_state: list[str] = field(default_factory=list) # the thermostat's attributes shown read-only + assumed: bool = False # the thermostat does not report back + cover: str | None = None # a shade's cover entity (HA's tile with its features) + weather: str | None = None # a weather service's entity (its forecast card) + + def entities(self) -> set[str]: + out = set(self.headline) | set(self.flow.values()) | set(self.energy) | set(self.switches) + out |= {e for c in self.channels for k, e in c.items() if k != "n"} + out |= {e for e in (self.cover, self.weather) if e} + return out | ({self.climate} if self.climate else set()) + + def empty(self) -> bool: + return not (self.headline or self.flow or self.channels or self.climate or self.switches or self.cover + or self.weather) + + +class Device: + """One HA device with its entities (not hidden, not disabled, not + diagnostic or configuration) and their states.""" + + def __init__(self, d: dict, ents: list[dict], states: dict | None): + self.d, self.states = d, states + self.ents = [e for e in ents if not e.get("entity_category")] + self.bridge = bridge_device(d) + self.prefix = bridge_prefix(d) # cantabile_modbus_ or cantabile_eebus_ + self.domains = sorted({e.get("platform") for e in ents if e.get("platform")}) + # domains, and with the device class (cover.curtain, sensor.temperature) + self.entity_domains = sorted({k for e in ents for k in kinds_of(e, self._attrs(e))}) + self.by_uid = {str(e.get("unique_id")): e for e in self.ents} + + def _attrs(self, e: dict) -> dict | None: + st = (self.states or {}).get(e["entity_id"]) + return (st or {}).get("attributes") if st else None + + def attr(self, e: dict, name: str): + return (((self.states or {}).get(e["entity_id"]) or {}).get("attributes") or {}).get(name) + + def device_class(self, e: dict): + return self.attr(e, "device_class") or e.get("device_class") or e.get("original_device_class") + + def matches(self, m: dict, e: dict, n_ok: bool = False) -> re.Match | bool | None: + """Does the matcher's HA part fit the entity (with {n}: the match, + whose group "n" is the channel)?""" + found = True + for k in ("entity_id", "unique_id", "original_name"): + if k in m: + pat = m[k].replace("{n}", N_RE) if n_ok else m[k] + x = re.search(pat, str(e.get(k) or "")) + if not x: + return None + if "n" in x.groupdict(): + found = x + if "translation_key" in m and e.get("translation_key") != m["translation_key"]: + return None + if "domain" in m and e["entity_id"].split(".")[0] != m["domain"]: + return None + if "device_class" in m and self.device_class(e) != m["device_class"]: + return None + return found + + def find(self, m: dict | None) -> str | None: + """The entity a matcher names on this device.""" + if not m: + return None + if self.bridge and "key" in m: + e = self.by_uid.get(f"{self.prefix}{self.bridge}_{m['key']}") + return e["entity_id"] if e else None + if not set(m) & {"entity_id", "unique_id", "original_name", "translation_key", "domain", "device_class"}: + return None + return next((e["entity_id"] for e in self.ents if self.matches(m, e)), None) + + def channel(self, m: dict) -> dict[str, str]: + """{channel: entity} of a matcher with {n}.""" + out = {} + if self.bridge and "key" in m: + pat = re.compile(re.escape(f"{self.prefix}{self.bridge}_") + m["key"].replace("{n}", N_RE) + "$") + for uid, e in self.by_uid.items(): + x = pat.match(uid) + if x: + out[x.group("n")] = e["entity_id"] + return out + if not set(m) & {"entity_id", "unique_id", "original_name"}: + return out + for e in self.ents: + x = self.matches(m, e, n_ok=True) + if isinstance(x, re.Match): + out.setdefault(x.group("n"), e["entity_id"]) + return out + + +def _order(n: str): + return (0, int(n), "") if n.isdigit() else (1, 0, n) + + +def profile_of(dev: Device, profiles: list[dict]) -> dict | None: + """The profile of a bridge device (its model is the profile's name) or + of an HA device it recognises; only profiles with a view.""" + with_view = [p for p in profiles if isinstance(p.get("view"), dict) and p["view"].get("card")] + if dev.bridge: + return next((p for p in with_view if p.get("name") == dev.d.get("model")), None) + if dev.d.get("manufacturer") or dev.d.get("model"): + return next((p for p in by_priority(with_view) if recognise(p, dev.d, dev.domains, dev.entity_domains)), None) + return None + + +def _registers(p: dict) -> list[dict]: + mb = p.get("modbus") or {} + return [*(mb.get("registers") or []), *(mb.get("derived") or []), *((p.get("ha") or {}).get("registers") or []), + *((p.get("eebus") or {}).get("values") or [])] + + +def _ref_matcher(p: dict, dev: Device, ref: str) -> dict | None: + """A reference (quantity, value name, register key) as a matcher on this device.""" + view = p.get("view") or {} + if ref in (view.get("values") or {}): + return view["values"][ref] + if "." not in ref: + return {"key": ref} if dev.bridge else None + if dev.bridge: + for r in _registers(p): + if r.get("quantity") == ref: + return {"key": r["key"]} + for q in (r.get("split") or {}).values(): + if q == ref: + return {"key": q.replace(".", "_")} + return None + paths = [s for s in p.get("setup") or [] if s.get("path") != "modbus"] + s = next((s for s in paths if s.get("domain") and s["domain"] in dev.domains), None) or \ + next((s for s in paths if s["path"] == "existing"), None) or (paths[0] if paths else None) + # an entity's own value (not one read from its attributes); of + # alternatives the first this device has + alts = [{k: v for k, v in m.items() if k != "scale"} + for m in alternatives(((s or {}).get("values") or {}).get(ref)) if not m.get("attribute") and not m.get("equals")] + alts = [{k: v for k, v in m.items() if k not in ("assumed", "supports")} for m in alts] + return next((m for m in alts if dev.find(m)), alts[-1] if alts else None) + + +def from_profile(p: dict, dev: Device) -> DeviceView: + view = p["view"] + dv = DeviceView(view["card"], p["id"], p.get("category")) + + def ref(r): + return dev.find(_ref_matcher(p, dev, r)) if isinstance(r, str) else None + dv.flow = {k: e for k in FLOW if (e := ref((view.get("flow") or {}).get(k)))} + dv.energy = [e for e in (ref(r) for r in view.get("energy") or []) if e] + chans: dict[str, dict] = {} + for role, m in (view.get("channels") or {}).items(): + for n, e in dev.channel(m).items(): + chans.setdefault(n, {"n": n})[role] = e + dv.channels = [chans[n] for n in sorted(chans, key=_order)] + if dv.card == "circuits" and not any("power" in c for c in dv.channels): + dv.channels = [] + dv.climate = ref(view.get("climate")) if view.get("climate") else \ + next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("climate.")), None) \ + if dv.card == "climate" else None + if dv.climate: + e = next((x for x in dev.ents if x["entity_id"] == dv.climate), {"entity_id": dv.climate}) + st = ((dev.states or {}).get(dv.climate) or {}) + attrs = None if dev.states is None or not st or st.get("state") in ("unavailable", "unknown") \ + else st.get("attributes") or {} + # HA's assumed_state always; no hvac_action (an infrared climate) for + # a view that shows the climate's state (the generic thermostat) + dv.assumed = bool((attrs or {}).get("assumed_state")) or \ + ("climate_state" in view and bool(assumed_state(e, attrs))) + dv.climate_state = [a for a in view.get("climate_state") or [] + if dev.states is None or dev.attr(e, a) is not None] + if dv.card == "switches": + dv.switches = [c["switch"] for c in dv.channels if c.get("switch")] + dv.channels = [] + if dv.card == "cover": + dv.cover = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("cover.")), None) + if dv.card == "weather": + dv.weather = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("weather.")), None) + seen = set(dv.flow.values()) | ({dv.climate} if dv.climate else set()) | {e for e in (dv.cover, dv.weather) if e} + for r in view.get("headline") or []: + e = ref(r) + if e and e not in dv.headline and e not in seen: + dv.headline.append(e) + dv.headline = dv.headline[:HEADLINE_MAX] + return dv + + +# -- devices without a profile: HA's device classes ------------------------------------ + +MAIN = ("battery", "power", "temperature", "humidity") + + +def _stem(uid: str) -> tuple[str, str] | None: + m = re.fullmatch(r"(.*\D)(\d+)", uid) + return (m.group(1), m.group(2)) if m else None + + +def guessed(dev: Device, alive=lambda e: True) -> DeviceView: + """Today's heuristic, widened: battery and power first (then temperature + and humidity); power sensors numbered alike (…_power_1, …_power_2) are + channels, named after the switch of the same number; a climate entity is + a thermostat; a plug sensor makes a charger.""" + sensors = [e for e in dev.ents if e["entity_id"].startswith("sensor.") and dev.device_class(e) in MAIN + and alive(e["entity_id"])] + power = [e for e in sensors if dev.device_class(e) == "power"] + stems: dict[str, dict[str, dict]] = {} + for e in power: + s = _stem(str(e.get("unique_id"))) + if s: + stems.setdefault(s[0], {})[s[1]] = e + chan = max(stems.values(), key=len, default={}) + channels = [] + if len(chan) > 1: + switches: dict[str, dict[str, dict]] = {} + for e in dev.ents: + s = _stem(str(e.get("unique_id"))) + if s and e["entity_id"].split(".")[0] in ("switch", "light"): + switches.setdefault(s[0], {})[s[1]] = e + sw = max((x for x in switches.values() if set(chan) <= set(x)), key=len, default={}) + for n in sorted(chan, key=_order): + c = {"n": n, "power": chan[n]["entity_id"]} + if n in sw: + c["switch"] = sw[n]["entity_id"] + channels.append(c) + sensors = [e for e in sensors if e not in chan.values()] + order = {c: i for i, c in enumerate(MAIN)} + main = [e for e in sensors if dev.device_class(e) in ("battery", "power")] or sensors + headline = [e["entity_id"] for e in sorted(main, key=lambda e: order[dev.device_class(e)])][:4] + climate = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("climate.")), None) + plug = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("binary_sensor.") + and dev.device_class(e) in ("plug", "battery_charging")), None) + soc = next((e["entity_id"] for e in sensors if dev.device_class(e) == "battery"), None) + dv = DeviceView("sensor", headline=headline, channels=channels, climate=climate) + cover = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("cover.")), None) + weather = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("weather.")), None) + if climate: + dv.card = "climate" + elif cover: + dv.card, dv.cover = "cover", cover + elif weather and not headline: + dv.card, dv.weather = "weather", weather + elif plug: + dv.card, dv.headline = "charger", [plug] + headline + elif channels: + dv.card = "circuits" + elif soc and power: + dv.card = "gauge" + if dv.empty(): + sw = [e["entity_id"] for e in dev.ents if e["entity_id"].startswith("switch.")] + if sw: + dv.card, dv.switches = "switches", sw + return dv + + +def view_of(d: dict, ents: list[dict], states: dict | None, profiles: list[dict], + alive=lambda e: True) -> DeviceView: + dev = Device(d, ents, states) + p = profile_of(dev, profiles) + if p is not None: + dv = from_profile(p, dev) + if not dv.empty(): + dv.headline = [e for e in dv.headline if alive(e)] + dv.flow = {k: e for k, e in dv.flow.items() if alive(e)} + dv.energy = [e for e in dv.energy if alive(e)] + return dv + return guessed(dev, alive) diff --git a/src/edge/cantabile_edge/executor.py b/src/edge/cantabile_edge/executor.py new file mode 100644 index 0000000..3433546 --- /dev/null +++ b/src/edge/cantabile_edge/executor.py @@ -0,0 +1,296 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""From what is wanted to Home Assistant service calls, through the guard. + +Each control has one wanted value at a time, from (highest first): + 1. a command from the console (`control`, with its level: flexible, + binding, emergency), until it ends or is released; + 2. the current plan's step, while the plan is fresh (made in the last + stale_s) and its inputs were fresh; + 3. the control's safe defaults (mapping `safe:`), when the plan or its + data is stale; a battery's default is no grid charging and power 0. +The wanted value becomes actions on the control's channels, but only where +the device differs from it (no repeated calls), each checked by the guard. +Every action, refusal and owner override is reported (`action` messages: +ctb.site..action) and logged; a refusal once per control and reason +per hour. + +A flexible command the owner overrides by hand ends (reported "overridden"); +binding and emergency commands are applied again (the flat cannot lift them). +""" +import logging +import time + +from .guard import Action +from .inputs import cover_position, cover_positions, number + +log = logging.getLogger(__name__) + +RELEASE = "release" # a safe value meaning: leave the device as it is + + +def _plan_value(plan: dict, cid: str, now: float): + cur = None + for e in (plan or {}).get("devices", {}).get(cid, []): + if e["t"] <= now: + cur = e + return cur + + +def actions_for(c, want, col, level="plan", why="") -> list[Action]: + """The actions that bring control c to `want` (a plan entry's set, a + command's set, or a safe value), only where the device differs.""" + e = c.entities + out = [] + + def act(channel, service, data, value, quantity=""): + ent = e[channel] + out.append(Action(c.id, channel, ent, ent.split(".", 1)[0], service, data, value, quantity, level, why)) + + def switch(channel, on: bool): + if channel in e and (col.state(e[channel]) == "on") != on: + act(channel, "turn_on" if on else "turn_off", {}, "on" if on else "off") + + def setnum(channel, v: float, quantity: str): + if channel in e and (number(col.state(e[channel])) is None or abs(number(col.state(e[channel])) - v) > 0.5): + act(channel, "set_value", {"value": v}, v, quantity) + + if want is None or want == RELEASE: + return out + if c.kind == "battery": + if isinstance(want, dict): # a plan entry: power and whether from the grid + power, grid = float(want.get("set", 0)), bool(want.get("grid")) + else: + power, grid = float(want), float(want) > 0 + # With a setpoint the power is set there and the grid switch stays + # off (it means "full power" on many inverters and would override + # the setpoint); a battery with the switch alone is driven by it. + switch("charge_from_grid", grid and "setpoint" not in e) + if "mode" in e: + # the inverter's own mode: manual while the plan sets power, + # its self-consumption otherwise (the setpoint counts in manual only) + opt = str(c.p("manual_option") if abs(power) >= 50 else c.p("auto_option")) + if col.state(e["mode"]) != opt: + act("mode", "select_option", {"option": opt}, opt) + setnum("setpoint", power, "power_w") + elif c.kind in ("heating", "cooling"): + v = want.get("set") if isinstance(want, dict) else want + if "climate" in e: + c.learn_range(col) + step = c.temp_step(col) + if number(v) is not None and step: + # the thermostat's step (0.5, 1): a value it can take + lo, hi = c.device_range("temp_c") + r = round(float(v) / step) * step + r = r + step if r < lo - 1e-9 else r - step if r > hi + 1e-9 else r + v = round(r, 3) + state = col.state(e["climate"]) + mode = "cool" if c.kind == "cooling" else "heat" + if v == "off": + if state not in ("off", None): + act("climate", "set_hvac_mode", {"hvac_mode": "off"}, "off") + elif number(v) is not None: + if state != mode: + act("climate", "set_hvac_mode", {"hvac_mode": mode}, mode) + cur = number(col.attr(e["climate"], "temperature")) + if cur is None or abs(cur - float(v)) > 0.25: + act("climate", "set_temperature", {"temperature": float(v)}, float(v), "temp_c") + elif v in ("on", "off"): + switch("switch", v == "on") + elif c.kind == "ev": + v = want.get("set") if isinstance(want, dict) else want + if v == "off": + switch("switch", False) + elif number(v) is not None: + setnum("current", float(v), "current_a") + switch("switch", True) + elif c.kind == "cover": + v = number(want.get("set") if isinstance(want, dict) else want) + if v is not None: + if col.state(e["cover"]) in ("opening", "closing"): + return out # moving: wait for it to stop + cur = cover_position(col, e["cover"]) + if cover_positions(col, e["cover"]): + if cur is None or abs(cur - v) > 2: + act("cover", "set_cover_position", {"position": int(round(v))}, v, "position_pct") + elif v >= 50 and cur != 100.0: + # open and close only: halfway or more is open + act("cover", "open_cover", {}, 100.0, "position_pct") + elif v < 50 and cur != 0.0: + act("cover", "close_cover", {}, 0.0, "position_pct") + return out + + +def building_msg(c: dict, result: str, why: str, at: float) -> dict: + """An `action` message about a building request (agreed form).""" + return {"v": 1, "at": int(at), "asset": "", "entity": f"building:{c['building']}", + "service": f"building.{c['control']}", "value": c["value"], "result": result, "why": why, + "level": c["level"], "id": c["id"]} + + +def safe_want(c): + """The control's safe value when plans or data are stale.""" + if c.kind == "battery": + s = c.safe or {} + return {"set": float(s.get("setpoint", 0)), "grid": bool(s.get("charge_from_grid", False))} + v = (c.safe or {}).get(next(iter(c.writable()), ""), RELEASE) + return v + + +class Executor: + def __init__(self, controls, guard, col, publish, *, stale_s=1800, clock=time.time, building=None): + self.building = building # the building's requests (building.py), or None + self.controls = {c.id: c for c in controls} + self.guard, self.col, self.publish, self.stale, self.clock = guard, col, publish, stale_s, clock + self.plan: dict | None = None + self.inputs_ok = True + self.commands: dict[str, dict] = {} # control -> {"set", "level", "until", "id", "why"} + self._refused: dict[tuple, float] = {} + self.log: list[dict] = [] # the last actions (tests, status) + + # -- what is wanted ------------------------------------------------------ + def wanted(self, c, now): + want, level, why = self._wanted(c, now) + return self._capped(c, want, level, why, now) + + def _wanted(self, c, now): + cmd = self.commands.get(c.id) + if cmd and now < cmd["until"]: + return cmd["set"], cmd["level"], cmd.get("why") or f"{cmd['level']} command" + if cmd: + self.commands.pop(c.id, None) + fresh = self.plan is not None and now - self.plan.get("made", 0) <= self.stale and self.inputs_ok + if fresh: + e = _plan_value(self.plan, c.id, now) + return e, "plan", (e or {}).get("why", "") + return safe_want(c), "plan", "safe default: the plan or its data is stale" + + def _capped(self, c, want, level, why, now): + """The building's thermostat cap on a climate's setpoint (heating: at + most, cooling: at least), at the cap's level: a binding cap applies + again when the owner changes it by hand.""" + if self.building is None or "climate" not in c.entities: + return want, level, why + cap, cmd = self.building.cap(c.kind, now) + if cap is None: + return want, level, why + v = want.get("set") if isinstance(want, dict) else want + if number(v) is None: + return want, level, why + v = float(v) + capped = min(v, cap) if c.kind == "heating" else max(v, cap) + if capped == v and level != "plan": + return want, level, why + lvl = cmd["level"] if level in ("plan", "flexible") else level + return {"set": capped}, lvl, f"building {cmd['building']}: {cmd['why'] or 'thermostat cap'} ({cap:g} °C)" + + # -- one round --------------------------------------------------------------- + async def tick(self, client, auto: bool): + """One round: overrides seen since the last, then each control. With + auto False only overrides are reported (the guard refuses anyway).""" + now = self.clock() + await self._overrides(now) + if not auto or client is None: + return + sw = self.guard.switchover + for c in self.controls.values(): + if sw is not None and not sw.active(c): + continue # the thermostat's other control acts (switchover.py) + want, level, why = self.wanted(c, now) + acts = actions_for(c, want, self.col, level, why) + if why.startswith("building") and not any(a.channel == "climate" for a in acts): + # the room is within the building's cap already: a change by + # hand still counts as an override of the cap + self.guard.expect(c.id, c.entities["climate"], want["set"]) + for a in acts: + await self._do(client, a, now) + + async def _do(self, client, a: Action, now): + ok, reason = self.guard.check(a) + if not ok: + key = (a.control, reason.split(" ")[0] + reason[-12:]) + if now - self._refused.get(key, 0) >= 3600: + self._refused[key] = now + await self._report(a, "refused", reason, now) + return + try: + await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a)) + except Exception as e: + await self._report(a, "failed", str(e)[:200], now) + return + self.guard.done(a) + await self._report(a, "done", a.why, now) + + @staticmethod + def _allowed(a: Action): + """The HA client's check: exactly this action and nothing else.""" + return lambda d, s, ent: (d, s, ent) == (a.domain, a.service, a.entity) + + async def _overrides(self, now): + while self.guard.events: + ev = self.guard.events.pop(0) + c = self.controls.get(ev["control"]) + cap, bcmd = self.building.cap(c.kind, now) if self.building is not None and c else (None, None) + if bcmd is not None and "climate" in c.entities and ev["entity"] == c.entities["climate"]: + await self._building_override(bcmd, ev) + cmd = self.commands.get(ev["control"]) + if cmd and cmd["level"] == "flexible": + self.commands.pop(ev["control"], None) # the owner wins over a flexible command + why = f"the owner changed it by hand: flexible command {cmd.get('id', '')} ended" + elif cmd: + why = f"the owner changed it by hand: {cmd['level']} command applied again" + else: + why = f"the owner changed it by hand: hands off until {time.strftime('%H:%M UTC', time.gmtime(ev['until']))}" + await self.publish("action", {"v": 1, "at": ev["at"], "asset": ev["control"], "entity": ev["entity"], + "service": "", "value": ev["value"], "result": "overridden", "why": why}) + log.info("override: %s %s=%s (%s)", ev["control"], ev["entity"], ev["value"], why) + self.log.append({"result": "overridden", **ev}) + + async def _building_override(self, bcmd, ev): + """The owner changed a room the building's cap holds: a flexible cap + ends, a binding one stays (applied again).""" + if bcmd["level"] == "flexible": + self.building.lift("thermostat_cap") + why = "the owner changed it by hand: the flexible cap ended" + else: + why = "the owner changed it by hand: the binding cap applied again" + await self.publish("action", building_msg(bcmd, "overridden", why, ev["at"])) + + async def _report(self, a: Action, result, why, now): + msg = {"v": 1, "at": int(now), "asset": a.control, "entity": a.entity, + "service": f"{a.domain}.{a.service}", "value": a.value, "result": result, "why": why, + "level": a.level} + self.log.append(msg) + self.log = self.log[-200:] + log.info("action %s: %s %s %s=%s (%s)", result, a.control, msg["service"], a.entity, a.value, why) + await self.publish("action", msg) + + # -- commands from the console ------------------------------------------ + def command(self, args: dict, now: float) -> tuple[bool, str]: + cid = args.get("asset", "") + c = self.controls.get(cid) + if c is None: + return False, f"no control {cid!r}" + sw = self.guard.switchover + if sw is not None and not sw.active(c): + return False, f"{cid}: not active now (the thermostat is on its other side: switchover)" + level = args.get("level", "flexible") + if level not in ("flexible", "binding", "emergency"): + return False, "level: flexible, binding or emergency" + try: + until = float(args["until"]) if args.get("until") else now + 60 * float(args.get("minutes", 60)) + except ValueError: + return False, "until: unix time, or minutes" + if until <= now: + return False, "already over" + v = args.get("set", "") + want = float(v) if number(v) is not None else v + if want in ("", None): + return False, "set: a value" + self.commands[cid] = {"set": want, "level": level, "until": until, "id": args.get("id", ""), + "why": args.get("why") or f"{level} command"} + return True, f"{cid}: {want} ({level}) until {time.strftime('%H:%M UTC', time.gmtime(until))}" + + def release(self, cid: str) -> tuple[bool, str]: + if self.commands.pop(cid, None) is None: + return False, f"no command for {cid!r}" + return True, f"{cid}: back to the plan" diff --git a/src/edge/cantabile_edge/gridorder.py b/src/edge/cantabile_edge/gridorder.py new file mode 100644 index 0000000..aba5c44 --- /dev/null +++ b/src/edge/cantabile_edge/gridorder.py @@ -0,0 +1,231 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The grid operator's limit from the EEBUS bridge: §14a EnWG +dimming through the grid operator's control box (EEBUS LPC), as a +higher-rank decision of the agent. + +The bridge (hub/addons/eebus-bridge, order.go) publishes retained on +`cantabile-eebus/gridorder`: + + {"order": "", "sig": base64, "key": base64} + +the order text signed with the bridge's own Ed25519 key: + + {"v": 1, "kind": "eebus-lpc", "id", "state": "normal|limited|failsafe|autonomous", + "active", "limit_w", "from", "until" (0: until changed), "failsafe_w", + "failsafe_s", "control_box": {"ski", "device"}, "scope": "controllable", + "issued"} + +Trust chain (what makes this the "verified proof" an emergency needs, +building.py; the link's relayed grid orders are the cloud's way, this is +the local one): + 1. control box -> bridge: SHIP's mutual TLS; the bridge trusts the control + box's SKI only after the owner or installer compared it with the box's + own and paired it on the bridge's page; only that SKI's LPC writes are + approved, and the paired control box is sealed (custodian + grid_operator): it can't be unpaired or overridden on the box. + 2. bridge -> agent: the order signed with the bridge's key. The agent pins + the first key it sees (/eebus-bridge.key, trust on first use) + and refuses a different one until the pin is removed on the box (a + reinstalled bridge; logged). On the Hub the broker's ACL also lets + only the bridge's user and HA's publish there. + 3. agent: a good order from a control box becomes the proof + "verified:eebus-lpc::" and a grid-level + limit: the optimiser's constraint on the controllable consumers' draw, + the guard's bound per controllable device. The control box's SKI goes + to the cloud in the inventory, so the grid operator can see which box + limits. +A box's root owner can always change software on their own box (3n): +this makes tampering visible, not impossible. + +An order older than STALE_S (the bridge sends it every 15 s) is dropped: +the bridge's own failsafe (LPC) holds the devices then. +""" +import base64 +import hashlib +import json +import logging +import os +import time + +log = logging.getLogger(__name__) + +TOPIC = "cantabile-eebus/gridorder" +STALE_S = 300 +PENALTY_EUR_KWH = 500.0 # like a relayed emergency (building.py): nobody overrides it + +# -- Ed25519 verification (RFC 8032, 5.1.7), pure Python ---------------------- + +_P = 2 ** 255 - 19 +_L = 2 ** 252 + 27742317777372353535851937790883648493 +_D = -121665 * pow(121666, _P - 2, _P) % _P +_I = pow(2, (_P - 1) // 4, _P) + + +def _xrecover(y: int, sign: int) -> int | None: + xx = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P + x = pow(xx, (_P + 3) // 8, _P) + if (x * x - xx) % _P: + x = x * _I % _P + if (x * x - xx) % _P: + return None + if x == 0 and sign: + return None + if x & 1 != sign: + x = _P - x + return x + + +def _decode(b: bytes): + if len(b) != 32: + return None + y = int.from_bytes(b, "little") + sign, y = y >> 255, y & ((1 << 255) - 1) + if y >= _P: + return None + x = _xrecover(y, sign) + return None if x is None else (x, y, 1, x * y % _P) + + +def _add(a, b): + x1, y1, z1, t1 = a + x2, y2, z2, t2 = b + A = (y1 - x1) * (y2 - x2) % _P + B = (y1 + x1) * (y2 + x2) % _P + C = t1 * 2 * _D * t2 % _P + Dd = z1 * 2 * z2 % _P + E, F, G, H = B - A, Dd - C, Dd + C, B + A + return (E * F % _P, G * H % _P, F * G % _P, E * H % _P) + + +def _mul(s: int, p): + q = (0, 1, 1, 0) + while s: + if s & 1: + q = _add(q, p) + p = _add(p, p) + s >>= 1 + return q + + +def _eq(a, b) -> bool: + return (a[0] * b[2] - b[0] * a[2]) % _P == 0 and (a[1] * b[2] - b[1] * a[2]) % _P == 0 + + +_GY = 4 * pow(5, _P - 2, _P) % _P +_G = (_xrecover(_GY, 0), _GY, 1, _xrecover(_GY, 0) * _GY % _P) + + +def verify(key: bytes, msg: bytes, sig: bytes) -> bool: + """An Ed25519 signature (RFC 8032), checked.""" + if len(sig) != 64: + return False + A, R = _decode(key), _decode(sig[:32]) + s = int.from_bytes(sig[32:], "little") + if A is None or R is None or s >= _L: + return False + h = int.from_bytes(hashlib.sha512(sig[:32] + key + msg).digest(), "little") % _L + return _eq(_mul(s, _G), _add(R, _mul(h, A))) + + +# -- orders ------------------------------------------------------------------- + +class GridOrders: + def __init__(self, state_dir: str, clock=time.time): + self.pin_path = os.path.join(state_dir, "eebus-bridge.key") + self.clock = clock + self.order: dict | None = None # the last good order + self.received = 0.0 + self.error = "" + + def pinned(self) -> str: + try: + with open(self.pin_path) as f: + return f.read().strip() + except OSError: + return "" + + def take(self, payload: bytes | str) -> tuple[bool, str]: + """A message from the bridge: (changed, why). A bad one changes + nothing (the last good order holds until it is stale).""" + try: + msg = json.loads(payload) + text, key = msg["order"], msg["key"] + raw_key, sig = base64.b64decode(key), base64.b64decode(msg["sig"]) + except (ValueError, KeyError, TypeError) as e: + return self._bad(f"not a grid order: {e}") + pin = self.pinned() + if pin and pin != key: + return self._bad("signed by another key than the paired bridge's (remove eebus-bridge.key on the box after a reinstall)") + if not verify(raw_key, text.encode(), sig): + return self._bad("bad signature") + try: + o = json.loads(text) + except ValueError: + return self._bad("the order is not JSON") + if o.get("v") != 1 or o.get("kind") != "eebus-lpc" or o.get("scope") != "controllable": + return self._bad("not an EEBUS LPC order v1") + if o.get("active") and not (o.get("control_box") or {}).get("ski"): + return self._bad("an active order without its control box") + if not pin: + tmp = self.pin_path + ".tmp" + with open(tmp, "w") as f: + f.write(key) + os.replace(tmp, self.pin_path) + log.info("grid order: the EEBUS bridge's key pinned") + old = self.active() + self.order, self.received, self.error = o, self.clock(), "" + new = self.active() + changed = (old or {}).get("id") != (new or {}).get("id") or (old or {}).get("limit_w") != (new or {}).get("limit_w") \ + or bool(old) != bool(new) + return changed, "taken" + + def _bad(self, why: str) -> tuple[bool, str]: + if why != self.error: + log.warning("grid order refused: %s", why) + self.error = why + return False, why + + def active(self) -> dict | None: + """The order in force now, or None (none, ended, stale).""" + o, now = self.order, self.clock() + if not o or not o.get("active") or now - self.received > STALE_S: + return None + if o.get("until") and now >= o["until"]: + return None + return o + + def proof(self) -> str: + o = self.active() + return f"verified:eebus-lpc:{o['control_box']['ski']}:{o['id']}" if o else "" + + def for_model(self, start: int, step_s: int, steps: int) -> dict: + """The optimiser's constraint: the controllable consumers' draw from + the grid at most limit_w (state["grid_order"]).""" + o = self.active() + if not o: + return {} + until = o.get("until") or (start + steps * step_s) + a = max(0, (int(o.get("from") or start) - start) // step_s) + b = min(steps, -(-(int(until) - start) // step_s)) + if a >= b: + return {} + return {"limit_w": float(o["limit_w"]), "from_step": int(a), "to_step": int(b), "penalty": PENALTY_EUR_KWH, + "id": o["id"], "proof": self.proof(), "state": o.get("state", "")} + + def limits(self, controls) -> dict: + """Grid-level bounds per controllable device (§14a: chargers, + batteries' charging; heat pumps are held by the bridge itself): no + single one above the whole limit. {control id: {quantity: (floor, + limit)}}.""" + o = self.active() + if not o: + return {} + w = float(o["limit_w"]) + out = {} + for c in controls: + if c.kind == "ev": + volts = float(c.params.get("voltage", 230)) * float(c.params.get("phases", 3)) + out[c.id] = {"current_a": (None, round(w / volts, 1))} + elif c.kind == "battery": + out[c.id] = {"power_w": (None, w)} + return out diff --git a/src/edge/cantabile_edge/guard.py b/src/edge/cantabile_edge/guard.py new file mode 100644 index 0000000..b7054f8 --- /dev/null +++ b/src/edge/cantabile_edge/guard.py @@ -0,0 +1,202 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The actuation guard: every action the agent would take goes through +check() first, and only an allowed one becomes a Home Assistant service +call (executor.py). In this order: + + 0. policy the device's protection (policy.py): never + anything on a sealed device, never off on a protected one, + whatever the command's level + 0b. switchover a thermostat that heats and cools: only its active control + (heating or cooling, switchover.py) may act + 1. mode only in `auto` (shadow and advisory never act) + 2. consent the owner's for the site ("control" in consent.json) and the + control's own (mapping v3), both off by default + 3. allow-list the control's own entities, with the service its kind uses + 4. bounds inside the effective floors and limits (limits.py: the + device's range, the owner's, the building's, the cloud's, the + grid operator's) + 5. override the owner changed it by hand: the agent keeps off it for + override_hold_s (flexible), unless a binding or emergency + command says otherwise (3b command levels) + 6. cycling a switch stays on/off for its minimum time (anti-cycling; only + for equipment that wears from short cycles: heating, cooling) + 7. rate at most max_actions_per_hour per control; a cover moves at + most once in its params.min_move_s (default 30 min) + +Emergency commands skip 5-7 (nobody overrides them; device safety and the +bounds still hold). Binding ones skip 5: the flat cannot lift them, only the +building or the cloud. Every refusal has a reason, and is reported once per +control and reason per hour (not every minute). +""" +import time +from dataclasses import dataclass, field + +LEVELS = ("plan", "flexible", "binding", "emergency") # plan: the optimiser's own + + +@dataclass +class Action: + control: str + channel: str # the entity role (charge_from_grid, setpoint, climate, switch, current, cover) + entity: str + domain: str + service: str + data: dict + value: float | str # what is set (W, °C, A, %, "on"/"off"/"cool"/...) + quantity: str = "" # what bounds it (temp_c, power_w, current_a, position_pct; "" for on/off) + level: str = "plan" + why: str = "" + + +@dataclass +class _Track: + times: list = field(default_factory=list) # when actions were taken (rate limit) + switched: dict = field(default_factory=dict) # channel -> (time, value) of the last on/off change + commanded: dict = field(default_factory=dict) # entity -> (time, value) the agent last set + override_until: float = 0.0 + override_entity: str = "" + moved: float = -1e18 # when a cover was last moved by the agent + + +# The service each channel uses, by domain: nothing else can be called. +SERVICES = { + "switch": {"turn_on", "turn_off"}, + "input_boolean": {"turn_on", "turn_off"}, + "number": {"set_value"}, + "input_number": {"set_value"}, + "climate": {"set_temperature", "set_hvac_mode"}, + "cover": {"set_cover_position", "open_cover", "close_cover"}, + "select": {"select_option"}, + "input_select": {"select_option"}, +} + + +class Guard: + def __init__(self, controls, consent, mode=lambda: "shadow", *, override_hold_s=7200, min_switch_s=600, + max_actions_per_hour=12, settle_s=90, clock=time.time): + self.controls = {c.id: c for c in controls} + self.consent, self.mode, self.clock = consent, mode, clock + self.hold, self.min_switch, self.max_rate, self.settle = override_hold_s, min_switch_s, max_actions_per_hour, settle_s + self.extra_limits: dict = {} # control -> quantity -> level -> (floor, limit), from commands + self.policy = None # policy.Policy: the devices' protection + self.switchover = None # switchover.Switchover: heating or cooling now + self.track: dict[str, _Track] = {} + self.events: list[dict] = [] # overrides seen (the executor reports them) + + def min_switch_for(self, c) -> float: + """Anti-cycling time for this control: the mapping's + params.min_switch_s if set; else the guard's min_switch_s for kinds + whose equipment wears from short cycles (heating, cooling: their + default is > 0), and 0 for batteries, EV chargers and covers.""" + if "min_switch_s" in (c.params or {}): + return float(c.params["min_switch_s"]) + from .controls import PARAMS + return float(self.min_switch) if PARAMS.get(c.kind, {}).get("min_switch_s", 0) > 0 else 0.0 + + def _t(self, cid) -> _Track: + return self.track.setdefault(cid, _Track()) + + def bounds(self, c, q): + return c.bounds(q, self.extra_limits.get(c.id)) + + def check(self, a: Action) -> tuple[bool, str]: + now = self.clock() + c = self.controls.get(a.control) + if c is None: + return False, "no such control" + if self.policy is not None: + why = self.policy.refuses(a, c) + if why: + return False, why + if self.switchover is not None and not self.switchover.active(c): + return False, f"{c.kind} is not active now (switchover: the thermostat's other control is)" + if self.mode() != "auto": + return False, f"mode {self.mode()}: the agent does not act" + if not self.consent.control: + return False, "the owner has not allowed control (site consent)" + if not c.consent: + return False, "no consent for this control" + if c.writable().get(a.channel) != a.entity: + return False, f"{a.entity} is not this control's {a.channel}" + if a.service not in SERVICES.get(a.domain, ()) or a.entity.split(".", 1)[0] != a.domain: + return False, f"{a.domain}.{a.service} is not allowed for {a.entity}" + if a.quantity: + b = self.bounds(c, a.quantity) + try: + v = float(a.value) + except (TypeError, ValueError): + return False, f"{a.value!r} is not a number" + if not b.holds(v): + return False, (f"{v:g} outside {b.lo:g}..{b.hi:g} {a.quantity} " + f"(floor by {b.lo_by}, limit by {b.hi_by})") + tr = self._t(c.id) + urgent = a.level == "emergency" + if now < tr.override_until and a.level not in ("binding", "emergency"): + return False, f"the owner changed {tr.override_entity} by hand: hands off until {_hhmm(tr.override_until)}" + min_switch = self.min_switch_for(c) + if not urgent and min_switch > 0 and a.quantity == "" and a.channel in tr.switched: + when, last = tr.switched[a.channel] + if last != a.value and now - when < min_switch: + return False, f"switched {last} {int(now - when)} s ago (minimum {min_switch:g} s)" + tr.times = [t for t in tr.times if now - t < 3600] + if not urgent and c.kind == "cover" and now - tr.moved < float(c.p("min_move_s")): + return False, (f"moved {int(now - tr.moved)} s ago (at most once in {float(c.p('min_move_s')):g} s)") + if not urgent and len(tr.times) >= self.max_rate: + return False, f"{len(tr.times)} actions in the last hour (at most {self.max_rate})" + return True, "" + + def done(self, a: Action): + """An action was carried out: count it, remember what was set.""" + now = self.clock() + tr = self._t(a.control) + tr.times.append(now) + tr.commanded[a.entity] = (now, a.value) + if a.domain == "cover": + tr.moved = now + if a.quantity == "": + prev = tr.switched.get(a.channel) + if prev is None or prev[1] != a.value: + tr.switched[a.channel] = (now, a.value) + + def expect(self, control_id: str, entity: str, value): + """The agent wants this value and the device already has it (no + action needed): a later change by hand counts as an override, as if + the agent had set it (not counted as an action).""" + tr = self._t(control_id) + if entity not in tr.commanded: + tr.commanded[entity] = (self.clock() - self.settle, value) + + def observe(self, control_id: str, entity: str, value, now: float | None = None): + """A state change of a control's entity: if it differs from what the + agent set, and not right after the agent set it, the owner changed + it by hand.""" + now = self.clock() if now is None else now + tr = self._t(control_id) + cmd = tr.commanded.get(entity) + if cmd is None: + return + when, want = cmd + c = self.controls.get(control_id) + cover = c is not None and c.kind == "cover" + if now - when < self.settle or _same(value, want, 3.0 if cover else 0.26): + return + # a shade the owner moved: off it for its own pause (params.override_hold_s) + tr.override_until = now + (float(c.p("override_hold_s")) if cover else self.hold) + tr.override_entity = entity + tr.commanded.pop(entity, None) + self.events.append({"control": control_id, "entity": entity, "value": value, "agent_set": want, + "until": int(tr.override_until), "at": int(now)}) + + def overridden(self, control_id: str) -> bool: + return self.clock() < self._t(control_id).override_until + + +def _same(a, b, tol: float = 0.26) -> bool: + try: + return abs(float(a) - float(b)) < tol + except (TypeError, ValueError): + return str(a) == str(b) + + +def _hhmm(t: float) -> str: + return time.strftime("%H:%M UTC", time.gmtime(t)) diff --git a/src/edge/cantabile_edge/ha.py b/src/edge/cantabile_edge/ha.py new file mode 100644 index 0000000..9d5b4d5 --- /dev/null +++ b/src/edge/cantabile_edge/ha.py @@ -0,0 +1,216 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Home Assistant connector: the WebSocket API only (no REST, no MQTT), so +the agent needs nothing from HA but a token. Reconnects with backoff. + +Read-only by construction: send() refuses every message type that is not +in READ_ONLY. v1 adds exactly two ways past it: +- call_service(), for an action the actuation guard allowed: it takes the + guard's check (allowed(domain, service, entity)) and refuses anything it + doesn't allow; nothing else in the agent calls services; +- weather_forecast(): weather.get_forecasts, a service that only reads. +and one for the dashboards Cantabile keeps for the owner (dashboards.py): +- dashboard(): Lovelace dashboards whose url_path starts with "cantabile-" + (create, change, delete only those it listed itself, their config), and + HA's Energy preferences (the caller saves them only while they are empty: + the owner's own are never overwritten). +And for Cantabile's area (areas.py): create_area() and place_device(), a +device's area only. +""" +import asyncio +import json +import logging +import random +from collections.abc import Awaitable, Callable + +import websockets + +log = logging.getLogger(__name__) + +READ_ONLY = frozenset({ + "get_states", + "get_panels", + "get_config", + "subscribe_events", + "subscribe_entities", + "config/entity_registry/list", + "config/device_registry/list", + "config/area_registry/list", + "recorder/statistics_during_period", + "recorder/list_statistic_ids", + "ping", +}) + + +# dashboard(): what it may send, and for which dashboards +DASHBOARD = frozenset({"lovelace/dashboards/list", "lovelace/dashboards/create", "lovelace/dashboards/update", + "lovelace/dashboards/delete", "lovelace/config", "lovelace/config/save", + "energy/get_prefs", "energy/save_prefs"}) +OURS = "cantabile-" + + +class HAError(Exception): + pass + + +class HAClient: + def __init__(self, url: str, token: str): + self.url, self._token = url, token + self._ws = None + self._id = 0 + self._pending: dict[int, asyncio.Future] = {} + self._subs: dict[int, Callable[[dict], None]] = {} + self.version = None + self._our_dashboards: set[str] = set() # ids of "cantabile-" dashboards HA listed + + async def connect(self): + self._ws = await websockets.connect(self.url, max_size=64 * 1024 * 1024, ping_interval=30) + hello = json.loads(await self._ws.recv()) + if hello.get("type") != "auth_required": + raise HAError(f"unexpected greeting {hello.get('type')}") + await self._ws.send(json.dumps({"type": "auth", "access_token": self._token})) + ok = json.loads(await self._ws.recv()) + if ok.get("type") != "auth_ok": + raise HAError("authentication failed") # never log the token + self.version = ok.get("ha_version") + self._reader = asyncio.create_task(self._read()) + + async def close(self): + if self._ws: + await self._ws.close() + + async def _read(self): + try: + async for raw in self._ws: + msg = json.loads(raw) + # HA may coalesce several messages into one JSON array. + for m in msg if isinstance(msg, list) else [msg]: + self._dispatch(m) + finally: + for f in self._pending.values(): + if not f.done(): + f.set_exception(HAError("connection closed")) + self._pending.clear() + + def _dispatch(self, m: dict): + if m.get("type") == "event" and m.get("id") in self._subs: + self._subs[m["id"]](m["event"]) + elif m.get("type") in ("result", "pong") and m.get("id") in self._pending: + f = self._pending.pop(m["id"]) + if m.get("type") == "pong" or m.get("success"): + f.set_result(m.get("result")) + else: + f.set_exception(HAError(str(m.get("error")))) + + async def send(self, type_: str, timeout: float = 60, _events=None, **fields): + if type_ not in READ_ONLY: + raise HAError(f"{type_} is not allowed: reads only (actions go through call_service)") + return await self._send(type_, timeout, _events, **fields) + + async def call_service(self, domain: str, service: str, entity_id: str, data: dict, + allowed: Callable[[str, str, str], bool], timeout: float = 30): + """One action on one entity, only if the guard allows exactly it.""" + if not allowed(domain, service, entity_id): + raise HAError(f"{domain}.{service} on {entity_id} is not allowed") + return await self._send("call_service", timeout, domain=domain, service=service, + service_data=dict(data), target={"entity_id": entity_id}) + + async def dashboard(self, type_: str, timeout: float = 30, **fields): + """Cantabile's own dashboards and the Energy preferences, nothing else.""" + if type_ not in DASHBOARD: + raise HAError(f"{type_} is not a dashboard message") + if type_ in ("lovelace/dashboards/create", "lovelace/config", "lovelace/config/save") \ + and not str(fields.get("url_path") or "").startswith(OURS): + raise HAError(f"{type_}: only Cantabile's own dashboards ({OURS}*)") + if type_ in ("lovelace/dashboards/update", "lovelace/dashboards/delete") \ + and fields.get("dashboard_id") not in self._our_dashboards: + raise HAError(f"{type_}: not one of Cantabile's dashboards") + r = await self._send(type_, timeout, **fields) + if type_ == "lovelace/dashboards/list": + self._our_dashboards = {d["id"] for d in r or [] if str(d.get("url_path", "")).startswith(OURS)} + elif type_ == "lovelace/dashboards/create" and isinstance(r, dict) and r.get("id"): + self._our_dashboards.add(r["id"]) + return r + + async def create_area(self, name: str, icon: str) -> dict: + """An area (areas.py: "Cantabile"); nothing else in the area registry.""" + return await self._send("config/area_registry/create", 30, name=name, icon=icon) + + async def place_device(self, device_id: str, area_id: str): + """A device's area and only that (areas.py: Cantabile's own devices).""" + return await self._send("config/device_registry/update", 30, device_id=device_id, area_id=area_id) + + async def is_admin(self, user_id: str) -> bool: + """Is this HA user an administrator (the owner, or in the admin + group)? The add-on's pages: HA's ingress names the user + (X-Remote-User-Id); only what that needs is kept from the list.""" + for u in await self._send("config/auth/list", 30) or []: + if u.get("id") == user_id: + return bool(u.get("is_active", True)) and (bool(u.get("is_owner")) + or "system-admin" in (u.get("group_ids") or [])) + return False + + async def weather_forecast(self, entity_id: str, kind: str = "hourly") -> list[dict]: + """A weather entity's forecast (a service that only reads).""" + r = await self._send("call_service", 30, domain="weather", service="get_forecasts", + service_data={"type": kind}, target={"entity_id": entity_id}, return_response=True) + return ((r or {}).get("response") or {}).get(entity_id, {}).get("forecast") or [] + + async def _send(self, type_: str, timeout: float = 60, _events=None, **fields): + self._id += 1 + mid = self._id # taken before any await: sends may overlap + fut = asyncio.get_running_loop().create_future() + self._pending[mid] = fut + if _events: + self._subs[mid] = _events # events may arrive right after the result + await self._ws.send(json.dumps({"id": mid, "type": type_, **fields})) + return await asyncio.wait_for(fut, timeout) + + async def subscribe(self, event_type: str, handler: Callable[[dict], None]): + await self.send("subscribe_events", event_type=event_type, _events=handler) + + async def subscribe_entities(self, entity_ids: list[str], handler: Callable[[dict], None]): + """Only these entities, in HA's compact form: first {"a": all}, + then {"c": changes}. Far less traffic than every state_changed.""" + await self.send("subscribe_entities", entity_ids=entity_ids, _events=handler) + + async def wait_closed(self): + await self._reader + + async def registries(self) -> dict: + return { + "entities": await self.send("config/entity_registry/list"), + "devices": await self.send("config/device_registry/list"), + "areas": await self.send("config/area_registry/list"), + } + + +async def run_forever(url: str, token: str, on_connect: Callable[[HAClient], Awaitable[None]], + stop: asyncio.Event): + """Keep a connection: on_connect runs after each (re)connect; backoff + 1 s doubling to 60 s with jitter, reset after a connection held 60 s.""" + wait = 1.0 + while not stop.is_set(): + client = HAClient(url, token) + started = asyncio.get_running_loop().time() + try: + await client.connect() + log.info("connected to Home Assistant %s", client.version) + await on_connect(client) + done, _ = await asyncio.wait([asyncio.ensure_future(client.wait_closed()), + asyncio.ensure_future(stop.wait())], + return_when=asyncio.FIRST_COMPLETED) + except (OSError, HAError, websockets.WebSocketException, asyncio.TimeoutError) as e: + log.warning("Home Assistant connection: %s", e) + finally: + await client.close() + if stop.is_set(): + return + if asyncio.get_running_loop().time() - started > 60: + wait = 1.0 + delay = wait * (0.8 + 0.4 * random.random()) + log.info("reconnecting in %.1f s", delay) + try: + await asyncio.wait_for(stop.wait(), delay) + except asyncio.TimeoutError: + pass + wait = min(wait * 2, 60) diff --git a/src/edge/cantabile_edge/i18n.py b/src/edge/cantabile_edge/i18n.py new file mode 100644 index 0000000..37456d1 --- /dev/null +++ b/src/edge/cantabile_edge/i18n.py @@ -0,0 +1,116 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The language of the add-on's own page (joinpage.py): English or German, +from the browser's Accept-Language (HA's ingress forwards it), else +English. Home Assistant's own language (names.py) is another setting. + +The pattern of the box's panel (cantabile_i18n.py there; the edge package +is separate, so its own copy): the texts stay English in the code, +T("Join"), T("Unit {unit}", unit=x) with str.format values, TN("{n} day", +"{n} days", n) for plurals, M("...") in tables built at import (T() where +shown). German is cantabile_edge/i18n_de.py, MESSAGES {English: German}; a +plural's key is the tuple (one, other). A text missing there shows in +English; tests/test_joinpage_i18n.py finds every text of the page missing. + +The language is a context variable: each connection of the page is its own +asyncio task, and asyncio.to_thread carries the context into the thread. +""" +import contextvars +import datetime +import importlib + +LANGUAGES = {"en": "English", "de": "Deutsch"} +DEFAULT = "en" +PLURAL = {"en": lambda n: 0 if n == 1 else 1, "de": lambda n: 0 if n == 1 else 1} +MONTHS = { + "en": ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), + "de": ("Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez."), +} +DECIMAL = {"en": ".", "de": ","} + +_lang = contextvars.ContextVar("cantabile_edge_lang", default=DEFAULT) +_catalogues = {} + + +def use(lang): + """The language of what this request renders (its context).""" + return _lang.set(lang if lang in LANGUAGES else DEFAULT) + + +def current(): + return _lang.get() + + +def from_accept(header): + """The best of ours in an Accept-Language header ("de-DE,de;q=0.9,en;q=0.8"), or None.""" + best, best_q = None, 0.0 + for i, part in enumerate((header or "").split(",")): + tag, _, params = part.strip().partition(";") + code = tag.strip().lower().split("-")[0] + q = 1.0 + for p in params.split(";"): + k, _, v = p.strip().partition("=") + if k.strip() == "q": + try: + q = float(v) + except ValueError: + q = 0.0 + q -= i * 1e-6 # equal weights: the first wins + if code in LANGUAGES and q > best_q: + best, best_q = code, q + return best + + +def catalogue(lang): + if lang == DEFAULT: + return {} + if lang not in _catalogues: + try: + _catalogues[lang] = importlib.import_module(f"{__package__}.i18n_{lang}").MESSAGES + except ImportError: + _catalogues[lang] = {} + return _catalogues[lang] + + +def T(text, **values): + """text in the current language; {name}s filled from values.""" + s = catalogue(current()).get(text, text) + return s.format(**values) if values else s + + +def M(text): + """A text marked for the catalogue but kept English here (tables built at + import); T(table[k]) translates it where it is shown.""" + return text + + +def TN(one, other, n, **values): + """The plural for n ({n} is filled too).""" + lang = current() + forms = catalogue(lang).get((one, other)) or (one, other) + s = forms[min(PLURAL.get(lang, PLURAL[DEFAULT])(n), len(forms) - 1)] + return s.format(n=n, **values) + + +def date(d, year=True): + """29 Oct 2026 / 29. Okt. 2026 (a date or datetime).""" + lang = current() + m = MONTHS.get(lang, MONTHS[DEFAULT])[d.month - 1] + day = f"{d.day}." if lang == "de" else f"{d.day}" + return f"{day} {m} {d.year}" if year else f"{day} {m}" + + +def iso_date(s): + """An ISO time from Cantabile ("2026-10-29T10:00:00Z") as a date: kept as + 2026-10-29 in English, 29. Okt. 2026 in German.""" + s = (s or "")[:10] + if current() == DEFAULT: + return s + try: + return date(datetime.date.fromisoformat(s)) + except ValueError: + return s + + +def number(v): + """A short number as :g writes it, with the language's decimal mark (1.5 / 1,5).""" + return f"{v:g}".replace(".", DECIMAL.get(current(), ".")) diff --git a/src/edge/cantabile_edge/i18n_de.py b/src/edge/cantabile_edge/i18n_de.py new file mode 100644 index 0000000..33828d1 --- /dev/null +++ b/src/edge/cantabile_edge/i18n_de.py @@ -0,0 +1,350 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""German for the add-on's pages (joinpage.py, devpage.py): {English: German}; a plural's +key is (one, other), its value (one, other) in German. Formal "Sie"; the +words of the console's German manual (Beitrittscode, Betreiber, Gemeinschaft, +Einwilligung, Kündigungsfrist, Zählpunkt, austreten).""" + +MESSAGES = { + # the page + "Cantabile: building or community": "Cantabile: Gebäude oder Gemeinschaft", + "Building or community": "Gebäude oder Gemeinschaft", + "Open this page from Home Assistant.": "Öffnen Sie diese Seite über Home Assistant.", + "Not found": "Nicht gefunden", + "Cantabile could not be reached ({error}); this is what it said last.": + "Cantabile war nicht erreichbar ({error}); angezeigt wird der zuletzt bekannte Stand.", + "Cantabile could not be reached ({error}).": "Cantabile war nicht erreichbar ({error}).", + "given": "erteilt", + "not given": "nicht erteilt", + # a membership + "Your flat is a member of this building (unit {unit}, since {since}).": + "Ihre Wohnung ist Mitglied dieses Gebäudes (Einheit {unit}, seit {since}).", + "The building's operator ended your membership: it ends on {date}.": + "Der Betreiber des Gebäudes hat Ihre Mitgliedschaft beendet: Sie endet am {date}.", + "The building's rules": "Regeln des Gebäudes", + "Your consent for the building's operator: {state}.": "Ihre Einwilligung für den Betreiber des Gebäudes: {state}.", + "Leave this building. Its requests to your home end now; to join again you need a new code from the operator.": + "Aus diesem Gebäude austreten. Die Anfragen des Gebäudes an Ihr Zuhause enden sofort; für einen erneuten Beitritt brauchen " + "Sie einen neuen Code vom Betreiber.", + "Leave the building": "Aus dem Gebäude austreten", + "Your home is a member of the energy community {name} (run by {operator}, since {since}).": + "Ihr Zuhause ist Mitglied der Energiegemeinschaft {name} (betrieben von {operator}, seit {since}).", + "Your home is a member of the energy community {name} (run by {operator}).": + "Ihr Zuhause ist Mitglied der Energiegemeinschaft {name} (betrieben von {operator}).", + "The community's operator ended your membership: it ends on {date}.": + "Der Betreiber der Gemeinschaft hat Ihre Mitgliedschaft beendet: Sie endet am {date}.", + "The community's rules": "Regeln der Gemeinschaft", + "Your consent for the community's operator: {state}.": "Ihre Einwilligung für den Betreiber der Gemeinschaft: {state}.", + "Leave this community. Its requests to your home end now; to join again you need a new code or its operator's yes.": + "Aus dieser Gemeinschaft austreten. Die Anfragen der Gemeinschaft an Ihr Zuhause enden sofort; für einen erneuten Beitritt " + "brauchen Sie einen neuen Code oder die Zusage ihres Betreibers.", + "Leave the community": "Aus der Gemeinschaft austreten", + "Your membership of {name} ended on {date}: {reason}.": "Ihre Mitgliedschaft bei {name} endete am {date}: {reason}.", + # requests + "unit {unit}": "Einheit {unit}", + "You asked to join {name}: waiting for the community's operator.": + "Sie haben den Beitritt zu {name} angefragt: Die Antwort des Betreibers der Gemeinschaft steht noch aus.", + "You asked to join {name}: waiting for the building's operator.": + "Sie haben den Beitritt zu {name} angefragt: Die Antwort des Betreibers des Gebäudes steht noch aus.", + "Withdraw the request": "Anfrage zurückziehen", + "{name} declined your request: {reason}.": "{name} hat Ihre Anfrage abgelehnt: {reason}.", + "{name} declined your request.": "{name} hat Ihre Anfrage abgelehnt.", + # joining + "Join": "Beitreten", + "Join {name}": "{name} beitreten", + "Its rules": "Regeln", + "Unit {unit} of this building:": "Einheit {unit} in diesem Gebäude:", + "This energy community (energy shared between buildings and homes):": + "Diese Energiegemeinschaft (Energie, die zwischen Gebäuden und Häusern geteilt wird):", + "Your meter point (on your meter or your electricity bill)": "Ihr Zählpunkt (auf Ihrem Zähler oder Ihrer Stromrechnung)", + "Join with a code": "Mit einem Code beitreten", + "A building's operator gives each flat a code; an energy community's operator gives each home a code (or a QR code: " + "open its link here, or type the code).": + "Der Betreiber eines Gebäudes gibt jeder Wohnung einen Code, der Betreiber einer Energiegemeinschaft jedem " + "Zuhause (oder einen QR-Code: Öffnen Sie seinen Link hier oder geben Sie den Code ein).", + "Join code": "Beitrittscode", + "Continue": "Weiter", + "No building or energy community using Cantabile was found near your home.": + "In der Nähe Ihres Zuhauses wurde kein Gebäude und keine Energiegemeinschaft mit Cantabile gefunden.", + "Your flat (as on your door or contract)": "Ihre Wohnung (wie an Ihrer Tür oder im Vertrag)", + "An energy community.": "Eine Energiegemeinschaft.", + "A note for the operator (optional)": "Eine Nachricht an den Betreiber (optional)", + "Ask to join": "Beitritt anfragen", + "No code?": "Kein Code?", + "Look for buildings and energy communities using Cantabile near your home (Home Assistant's location goes to " + "Cantabile only when you press this).": + "Suchen Sie Gebäude und Energiegemeinschaften mit Cantabile in der Nähe Ihres Zuhauses (der Standort aus Home " + "Assistant geht erst an Cantabile, wenn Sie hier klicken).", + "Near my home": "In meiner Nähe", + "{m} m away": "{m} m entfernt", + "Run by {operator}": "Betrieben von {operator}", + "Share my flat's energy data with the building's operator (per flat, every 15 minutes, if the building's rules ask " + "for it).": + "Die Energiedaten meiner Wohnung mit dem Betreiber des Gebäudes teilen (je Wohnung, alle 15 Minuten, wenn die " + "Regeln des Gebäudes es vorsehen).", + "Share my home's energy data with the community's operator (every 15 minutes, if the community's rules ask for it).": + "Die Energiedaten meines Zuhauses mit dem Betreiber der Gemeinschaft teilen (alle 15 Minuten, wenn die Regeln " + "der Gemeinschaft es vorsehen).", + # answers + "A join code has 12 letters and digits: XXXX-XXXX-XXXX.": + "Ein Beitrittscode besteht aus 12 Buchstaben und Ziffern: XXXX-XXXX-XXXX.", + "Welcome: your home is a member of the community now.": "Willkommen: Ihr Zuhause ist jetzt Mitglied der Gemeinschaft.", + "Welcome: your flat is a member now.": "Willkommen: Ihre Wohnung ist jetzt Mitglied.", + "Home Assistant has no home location (Settings, System, General).": + "In Home Assistant ist kein Standort für Ihr Zuhause eingetragen (Einstellungen, System, Allgemein).", + "Which building or community?": "Welches Gebäude oder welche Gemeinschaft?", + "Asked. The community's operator decides; this page shows the answer.": + "Angefragt. Der Betreiber der Gemeinschaft entscheidet; diese Seite zeigt die Antwort.", + "Asked. The building's operator decides; this page shows the answer.": + "Angefragt. Der Betreiber des Gebäudes entscheidet; diese Seite zeigt die Antwort.", + "Your request was withdrawn.": "Ihre Anfrage wurde zurückgezogen.", + "Tick the box to leave.": "Setzen Sie das Häkchen, um auszutreten.", + "You left.": "Sie sind ausgetreten.", + # errors + "this Home Assistant is not connected to Cantabile yet": "dieses Home Assistant ist noch nicht mit Cantabile verbunden", + "cannot sign: {error}": "Signieren nicht möglich: {error}", + "no key yet": "noch kein Schlüssel", + "Cantabile answered {code}": "Cantabile antwortete mit {code}", + "Cantabile cannot be reached: {error}": "Cantabile ist nicht erreichbar: {error}", + # the rules + "The building sees your flat's energy use every 15 minutes, if you allow it below.": + "Das Gebäude sieht den Energieverbrauch Ihrer Wohnung alle 15 Minuten, wenn Sie es unten erlauben.", + "The building sees your energy use only summed up with the other flats.": + "Das Gebäude sieht Ihren Energieverbrauch nur zusammengefasst mit dem der anderen Wohnungen.", + "Your 15-minute consumption is used for the building's bills (for example shared solar power), never shown to the " + "operator as a time series.": + "Ihr 15-Minuten-Verbrauch wird für die Abrechnungen des Gebäudes verwendet (zum Beispiel für gemeinsamen " + "Solarstrom) und dem Betreiber nie als Zeitreihe gezeigt.", + "Cantabile makes no bills for this building.": "Cantabile erstellt für dieses Gebäude keine Abrechnungen.", + "The community sees your home's energy use every 15 minutes, if you allow it below.": + "Die Gemeinschaft sieht den Energieverbrauch Ihres Zuhauses alle 15 Minuten, wenn Sie es unten erlauben.", + "The community sees your energy use only summed up with its other members.": + "Die Gemeinschaft sieht Ihren Energieverbrauch nur zusammengefasst mit dem ihrer anderen Mitglieder.", + "Your 15-minute values are used to settle the energy shared in the community, never shown to its operator as a " + "time series.": + "Ihre 15-Minuten-Werte werden zur Abrechnung der in der Gemeinschaft geteilten Energie verwendet und ihrem " + "Betreiber nie als Zeitreihe gezeigt.", + "Cantabile settles nothing for this community.": "Cantabile rechnet für diese Gemeinschaft nichts ab.", + "a limit on what your home draws from the grid": "eine Begrenzung dessen, was Ihr Zuhause aus dem Netz bezieht", + "requests to move some of your energy use to another time": + "Anfragen, einen Teil Ihres Energieverbrauchs auf eine andere Zeit zu verschieben", + "a cap on your heating's setpoints": "eine Obergrenze für die Solltemperaturen Ihrer Heizung", + "at least {v} {unit}": "mindestens {v} {unit}", + "at most {v} {unit}": "höchstens {v} {unit}", + "The building may send {controls}.": "Das Gebäude darf Folgendes senden: {controls}.", + "The community may send {controls}.": "Die Gemeinschaft darf Folgendes senden: {controls}.", + "You can always override them.": "Sie können sie jederzeit übersteuern.", + "They apply until they end; your comfort settings always win.": + "Sie gelten bis zu ihrem Ende; Ihre Komforteinstellungen haben immer Vorrang.", + "The building sends your home no requests.": "Das Gebäude sendet Ihrem Zuhause keine Anfragen.", + "The community sends your home no requests.": "Die Gemeinschaft sendet Ihrem Zuhause keine Anfragen.", + ("Notice when the operator ends your membership or closes the building: {days} day.", + "Notice when the operator ends your membership or closes the building: {days} days."): + ("Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder das Gebäude schließt: {days} Tag.", + "Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder das Gebäude schließt: {days} Tage."), + ("Notice when the operator ends your membership or closes the community: {days} day.", + "Notice when the operator ends your membership or closes the community: {days} days."): + ("Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder die Gemeinschaft schließt: {days} Tag.", + "Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder die Gemeinschaft schließt: {days} Tage."), + "Shared solar power: {pv} ct/kWh; grid power when no tariff covers you: {grid} ct/kWh.": + "Gemeinsamer Solarstrom: {pv} ct/kWh; Netzstrom, wenn kein Tarif für Sie gilt: {grid} ct/kWh.", + # a community's terms + "the day-ahead price (around {ct} ct/kWh)": "dem Day-Ahead-Börsenpreis (etwa {ct} ct/kWh)", + "Energy shared in the community: {delta} ct/kWh below {reference}; a surplus nobody in it takes goes to the grid at " + "{feed_in} ct/kWh.": + "In der Gemeinschaft geteilte Energie: {delta} ct/kWh unter {reference}; ein Überschuss, den niemand in der " + "Gemeinschaft abnimmt, wird für {feed_in} ct/kWh ins Netz eingespeist.", + "Energy shared in the community: {delta} ct/kWh above {reference}; a surplus nobody in it takes goes to the grid at " + "{feed_in} ct/kWh.": + "In der Gemeinschaft geteilte Energie: {delta} ct/kWh über {reference}; ein Überschuss, den niemand in der " + "Gemeinschaft abnimmt, wird für {feed_in} ct/kWh ins Netz eingespeist.", + "{v} kW guaranteed": "{v} kW garantiert", + "at least {v} kWh": "mindestens {v} kWh", + "at most {v} kW": "höchstens {v} kW", + "{v} ct/kWh for a deviation": "{v} ct/kWh bei einer Abweichung", + "{v} ct/kWh for overriding a request": "{v} ct/kWh für das Übersteuern einer Anfrage", + "Per quarter-hour: {terms}, summed per {period} (Cantabile records these; it does not apply or bill them yet).": + "Je Viertelstunde: {terms}, summiert je {period} (Cantabile erfasst diese Werte, wendet sie aber noch nicht an " + "und rechnet sie noch nicht ab).", + "month": "Monat", + "quarter": "Quartal", + "year": "Jahr", + # the restore offer (a reinstall recognised) + "Its name": "Sein Name", + "Its tags": "Seine Tags", + "Its building": "Sein Gebäude", + "Its energy communities": "Seine Energiegemeinschaften", + "Its tariff": "Sein Tarif", + "Its device protection": "Sein Geräteschutz", + "Its devices' details": "Die Angaben zu seinen Geräten", + "Your building's operator receives this home's energy data every 15 minutes": + "Der Betreiber Ihres Gebäudes erhält die Energiedaten dieses Zuhauses alle 15 Minuten", + "Your energy community's operator receives this home's energy data every 15 minutes": + "Der Betreiber Ihrer Energiegemeinschaft erhält die Energiedaten dieses Zuhauses alle 15 Minuten", + "of this home": "dieses Zuhauses", + "Kept by Cantabile already:": "Bereits bei Cantabile gespeichert:", + "Your earlier consents, as you gave them. They count only with your yes below.": + "Ihre früheren Einwilligungen, so wie Sie sie erteilt hatten. Sie gelten nur mit Ihrem Ja unten.", + "Yes, I give these consents again.": "Ja, ich erteile diese Einwilligungen erneut.", + "Cantabile keeps no backup of your home: which entities it may read, the devices and the add-on's options are set up again in Home Assistant.": + "Cantabile speichert keine Sicherung Ihres Zuhauses: Welche Entitäten es lesen darf, die Geräte und die Optionen des Add-ons richten Sie in Home Assistant neu ein.", + "This looks like your earlier Cantabile box {name}. Restore its settings?": + "Das sieht nach Ihrer früheren Cantabile-Box {name} aus. Ihre Einstellungen wiederherstellen?", + "Not now": "Jetzt nicht", + "Restore what is ticked": "Ausgewähltes wiederherstellen", + "consents given again": "Einwilligungen erneut erteilt", + "Restored: {what}.": "Wiederhergestellt: {what}.", + "Nothing restored.": "Nichts wiederhergestellt.", + # the Devices page (devpage.py; the Hub panel's words where it has them) + "Devices": "Geräte", + "Cantabile: devices": "Cantabile: Geräte", + "Home Assistant's devices that a Cantabile device profile knows. Use one with Cantabile to see it on Cantabile's " + "dashboard and to let Cantabile read it once you have given your consent.": + "Geräte aus Home Assistant, die ein Geräteprofil von Cantabile kennt. Nutzen Sie eines mit Cantabile, um es im " + "Dashboard von Cantabile zu sehen und, sobald Sie eingewilligt haben, von Cantabile auslesen zu lassen.", + "Used with Cantabile": "Mit Cantabile genutzt", + "In Home Assistant, with a profile": "In Home Assistant, mit Profil", + "No device in Home Assistant fits a Cantabile profile yet.": + "Noch passt kein Gerät in Home Assistant zu einem Profil von Cantabile.", + ("{n} more in Home Assistant without a profile (not used by Cantabile)", + "{n} more in Home Assistant without a profile (not used by Cantabile)"): + ("{n} weiteres Gerät in Home Assistant ohne Profil (von Cantabile nicht genutzt)", + "{n} weitere Geräte in Home Assistant ohne Profil (von Cantabile nicht genutzt)"), + "Home Assistant's devices could not be read: {error}": "Die Geräte von Home Assistant konnten nicht gelesen werden: {error}", + "Use with Cantabile": "Mit Cantabile nutzen", + "generic profile": "allgemeines Profil", + "Checked on a device": "An einem Gerät geprüft", + "From the maker's documentation, not yet checked on a device": + "Aus der Dokumentation des Herstellers, noch nicht an einem Gerät geprüft", + "Draft: check the values before you turn reading on": "Entwurf: Prüfen Sie die Werte, bevor Sie das Auslesen einschalten", + "nothing": "nichts", + "battery": "Batterie", + "heating": "Heizen", + "cooling": "Kühlen", + "charging": "Laden", + "blinds and curtains": "Jalousien und Vorhänge", + "Not known": "Unbekannt", + "North": "Norden", + "North-east": "Nordosten", + "East": "Osten", + "South-east": "Südosten", + "South": "Süden", + "South-west": "Südwesten", + "West": "Westen", + "North-west": "Nordwesten", + "No room": "Kein Raum", + "Room": "Raum", + "Room and window": "Raum und Fenster", + "Cantabile moves it by the sun: in summer it closes it while the sun is on the window and the room is warm; in " + "winter it opens it for the sun's warmth and closes it at night. Never between 22:00 and 07:00, and after you move " + "it by hand it waits 4 hours.": + "Cantabile bewegt sie nach der Sonne: im Sommer schließt es sie, solange die Sonne auf das Fenster scheint und " + "der Raum warm ist; im Winter öffnet es sie für die Wärme der Sonne und schließt sie nachts. Nie zwischen 22:00 " + "und 07:00 Uhr, und nachdem Sie sie von Hand bewegt haben, wartet es 4 Stunden.", + "Room it shades": "Raum, den sie beschattet", + "The window faces": "Das Fenster zeigt nach", + "Without the window's direction Cantabile only closes it at night in winter.": + "Ohne die Richtung des Fensters schließt Cantabile sie nur im Winter nachts.", + "Indoor or outdoor": "Innen oder außen", + "Indoor, in the room:": "Innen, im Raum:", + "Outdoor: Cantabile's outside temperature": "Außen: die Außentemperatur für Cantabile", + "An outdoor sensor counts before the weather service's temperature.": + "Ein Außensensor geht der Temperatur des Wetterdienstes vor.", + "Cantabile plans with this forecast: solar, heating, cooling and the shades.": + "Cantabile plant mit dieser Vorhersage: Solarstrom, Heizen, Kühlen und die Beschattung.", + "Not used for planning: Cantabile plans with one weather forecast, another one's.": + "Nicht für die Planung genutzt: Cantabile plant mit einer Wettervorhersage, einer anderen.", + "Plan with this forecast": "Mit dieser Vorhersage planen", + "Allow Cantabile to move it": "Bewegen durch Cantabile erlauben", + "A protected blind or curtain is not moved by Cantabile at all.": + "Eine geschützte Jalousie oder ein geschützter Vorhang wird von Cantabile gar nicht bewegt.", + "Cantabile would read: {values}.": "Cantabile würde auslesen: {values}.", + "It could control: {controls}.": "Steuern könnte es: {controls}.", + "Cantabile reads: {values}.": "Cantabile liest aus: {values}.", + "It may control: {controls}.": "Steuern darf es: {controls}.", + "Not found in Home Assistant: {entities}.": "In Home Assistant nicht gefunden: {entities}.", + "Read by your own mapping already, so left out here: {values}.": + "Schon von Ihrer eigenen Zuordnung ausgelesen, daher hier weggelassen: {values}.", + "Another control writes to this device already, so Cantabile leaves out: {controls}.": + "Eine andere Steuerung schreibt schon auf dieses Gerät, daher lässt Cantabile weg: {controls}.", + "Assumed, not measured: {values}. This device does not report back (infrared): Cantabile shows what was last sent " + "to it and never takes it as feedback.": + "Angenommen, nicht gemessen: {values}. Dieses Gerät meldet nichts zurück (Infrarot): Cantabile zeigt, was zuletzt " + "an es gesendet wurde, und wertet das nie als Rückmeldung.", + "Proposed by Cantabile (not checked yet): {values}. Use it with Cantabile to confirm it as this profile sees it.": + "Von Cantabile vorgeschlagen (noch nicht geprüft): {values}. Nutzen Sie es mit Cantabile, um es so zu bestätigen, " + "wie dieses Profil es sieht.", + "In your own mapping: {values}. Those stay as they are.": "In Ihrer eigenen Zuordnung: {values}. Diese bleiben, wie sie sind.", + "Cantabile may read these values": "Cantabile darf diese Werte auslesen", + "Save": "Speichern", + "Saved.": "Gespeichert.", + "Heating or cooling": "Heizen oder Kühlen", + "Heating": "Heizen", + "Cooling": "Kühlen", + "By season (heating October to April, cooling May to September)": + "Nach Jahreszeit (Heizen Oktober bis April, Kühlen Mai bis September)", + "By outdoor temperature": "Nach Außentemperatur", + "This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched.": + "Dieses Thermostat kann heizen und kühlen. Cantabile nutzt immer nur eines; das andere bleibt unberührt.", + "By outdoor temperature: heat below (°C)": "Nach Außentemperatur: heizen unter (°C)", + "cool above (°C)": "kühlen über (°C)", + "Between the two it stays as it is, so it does not switch back and forth on a mild day.": + "Dazwischen bleibt es, wie es ist, damit es an einem milden Tag nicht hin und her schaltet.", + "Protection": "Schutz", + "Protected: Cantabile never switches it off or cuts it; you still can, by hand. Sealed: only its custodian can " + "change it.": + "Geschützt: Cantabile schaltet es nie ab und drosselt es nie; Sie selbst können es weiterhin von Hand. " + "Versiegelt: Nur sein Verwalter kann das ändern.", + "The whole device": "Das ganze Gerät", + "Control {name}": "Steuerung {name}", + "Sealed": "Versiegelt", + "only {who} can change it": "nur {who} kann es ändern", + "protected": "geschützt", + "not protected": "nicht geschützt", + "Allow switching off": "Abschalten erlauben", + "Protect": "Schützen", + "its custodian": "sein Verwalter", + "the building's operator": "der Betreiber des Gebäudes", + "the grid operator": "der Netzbetreiber", + "the metering operator": "der Messstellenbetreiber", + "the energy community's operator": "der Betreiber der Energiegemeinschaft", + "Remove": "Entfernen", + "Cantabile stops using it. Home Assistant keeps the device as it is.": + "Cantabile nutzt es nicht mehr. Home Assistant behält das Gerät, wie es ist.", + "Stop using it with Cantabile": "Nicht mehr mit Cantabile nutzen", + "Cantabile no longer uses it.": "Cantabile nutzt es nicht mehr.", + "Cantabile could not ask Home Assistant who you are ({error}).": + "Cantabile konnte Home Assistant nicht fragen, wer Sie sind ({error}).", + "Home Assistant is not connected yet; try again in a moment.": + "Home Assistant ist noch nicht verbunden; versuchen Sie es gleich noch einmal.", + "Home Assistant has no such device.": "Dieses Gerät gibt es in Home Assistant nicht.", + "{profile}: this profile does not know the device's integration.": + "{profile}: Dieses Profil kennt die Integration des Geräts nicht.", + "No such profile.": "Dieses Profil gibt es nicht.", + "No such device.": "Dieses Gerät gibt es nicht.", + "This device is used with Cantabile already.": "Dieses Gerät wird schon mit Cantabile genutzt.", + "Home Assistant shows none of the values this profile knows, or your mapping has them all already.": + "Home Assistant zeigt keinen der Werte, die dieses Profil kennt, oder Ihre Zuordnung hat sie alle schon.", + "Sealed: only {who} can remove it.": "Versiegelt: Nur {who} kann es entfernen.", + "Sealed: only {who} can change its control.": "Versiegelt: Nur {who} kann seine Steuerung ändern.", + "The device's mapping is gone; use it with Cantabile again.": + "Die Zuordnung des Geräts fehlt; nutzen Sie es erneut mit Cantabile.", + "Reading and control are off. To switch them on, first give your consent in the add-on's configuration (Settings, " + "Add-ons, Cantabile Edge Agent, Configuration).": + "Auslesen und Steuern sind aus. Um sie einzuschalten, geben Sie zuerst Ihre Einwilligung in der Konfiguration " + "des Add-ons (Einstellungen, Add-ons, Cantabile Edge Agent, Konfiguration).", + "First give your consent in the add-on's configuration (Settings, Add-ons, Cantabile Edge Agent, Configuration).": + "Geben Sie zuerst Ihre Einwilligung in der Konfiguration des Add-ons (Einstellungen, Add-ons, Cantabile Edge " + "Agent, Konfiguration).", + "Cantabile may control it ({controls}), within your limits": + "Cantabile darf es steuern ({controls}), innerhalb Ihrer Grenzen", + "Control also needs your consent to control devices in the add-on's configuration.": + "Zum Steuern braucht es außerdem Ihre Einwilligung zum Steuern von Geräten in der Konfiguration des Add-ons.", + "Saved. Cantabile starts again to apply it (a few seconds).": + "Gespeichert. Cantabile startet neu, um es zu übernehmen (einige Sekunden).", + "{name} is used with Cantabile now. It is on Cantabile's dashboard; reading and control are off until you switch " + "them on below.": + "{name} wird jetzt mit Cantabile genutzt. Es steht im Dashboard von Cantabile; Auslesen und Steuern sind aus, " + "bis Sie sie unten einschalten.", + "Only an administrator of Home Assistant can use this page.": + "Nur ein Administrator von Home Assistant kann diese Seite nutzen.", +} diff --git a/src/edge/cantabile_edge/inputs.py b/src/edge/cantabile_edge/inputs.py new file mode 100644 index 0000000..3a4afd7 --- /dev/null +++ b/src/edge/cantabile_edge/inputs.py @@ -0,0 +1,309 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Inputs for the optimiser: the latest states of the controls' and the +inputs' entities (presence, temperatures, humidity, outside temperature, +sun, weather), a short local history of load and PV (the fallback when no +model bundle says), and the 15-minute model state for the horizon. + +None of this leaves the site; only the plan does (controller.py). + +Placeholders (quality is not a goal yet): +- occupancy beyond the next hour: the presence now for one hour, then + 06:00-22:00 local as "occupied" (a learned schedule comes later); +- sun: the PV forecast scaled to its peak, else the sun's elevation. +""" +import json +import logging +import math +import os +import time +from datetime import datetime, timezone +from zoneinfo import ZoneInfo + +log = logging.getLogger(__name__) + +STEP_S = 900 +STEPS = 192 # 48 h +HISTORY_S = 3 * 86400 + + +def number(v) -> float | None: + try: + x = float(v) + except (TypeError, ValueError): + return None + return x if x == x and abs(x) != math.inf else None + + +class Collector: + """States of the entities the agent watches, in HA's compact + subscribe_entities form. Observers (the guard) see every change.""" + + def __init__(self): + self.states: dict[str, dict] = {} + self.observers = [] + + def on_entities(self, ev: dict, now: float | None = None): + now = time.time() if now is None else now + for eid, s in (ev.get("a") or {}).items(): + self.states[eid] = {"s": s.get("s"), "a": dict(s.get("a") or {}), "t": s.get("lc") or now} + for eid, c in (ev.get("c") or {}).items(): + cur = self.states.setdefault(eid, {"s": None, "a": {}, "t": now}) + plus, minus = c.get("+") or {}, c.get("-") or {} + if "s" in plus: + cur["s"] = plus["s"] + cur["a"].update(plus.get("a") or {}) + for k in minus.get("a") or []: + cur["a"].pop(k, None) + cur["t"] = plus.get("lc") or plus.get("lu") or now + for obs in self.observers: + obs(eid, cur, now) + + def state(self, eid: str): + return (self.states.get(eid) or {}).get("s") + + def attr(self, eid: str, name: str): + return ((self.states.get(eid) or {}).get("a") or {}).get(name) + + def value(self, eid: str) -> float | None: + return number(self.state(eid)) if eid else None + + def total(self, eids: str | list) -> float | None: + """One entity's value, or the sum of several (parts: pv.1.power, ...); + None while any of them has none.""" + if isinstance(eids, str): + return self.value(eids) + vals = [self.value(e) for e in eids or []] + return None if not vals or None in vals else sum(vals) + + def age(self, eid: str, now: float) -> float: + st = self.states.get(eid) + return now - float(st["t"]) if st and st.get("t") else math.inf + + +class History: + """Quarter-hour means of load and PV (W) for the last 3 days, kept on + disk, for "the same quarter hour yesterday".""" + + def __init__(self, path: str): + self.path = path + self.slots: dict[str, dict[int, list[float]]] = {"load_w": {}, "pv_w": {}} + try: + with open(path) as f: + raw = json.load(f) + self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in self.slots} + except (OSError, ValueError, AttributeError): + pass + + def add(self, name: str, value: float | None, now: float): + if value is None: + return + slot = int(now // STEP_S * STEP_S) + s, n = self.slots[name].get(slot, [0.0, 0]) + self.slots[name][slot] = [s + value, n + 1] + + def mean(self, name: str, slot: int) -> float | None: + s = self.slots[name].get(slot) + return s[0] / s[1] if s and s[1] else None + + def save(self, now: float): + cut = now - HISTORY_S + for k in self.slots: + self.slots[k] = {t: v for t, v in self.slots[k].items() if t >= cut} + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(self.slots, f) + os.replace(tmp, self.path) + + +def _hourly(forecast: list[dict], key: str, start: int, steps: int) -> list[float] | None: + """A weather forecast's hourly value, held for each quarter hour.""" + pts = [] + for f in forecast or []: + v = number(f.get(key)) + try: + ts = datetime.fromisoformat(str(f["datetime"]).replace("Z", "+00:00")).timestamp() + except (KeyError, ValueError): + continue + if v is not None: + pts.append((ts, v)) + if not pts: + return None + pts.sort() + out, j = [], 0 + for k in range(steps): + t = start + k * STEP_S + while j + 1 < len(pts) and pts[j + 1][0] <= t: + j += 1 + out.append(pts[j][1]) + return out + + +def _series(name, start, bundles, history, tz, now_value, default): + s = bundles.forecast(name, start, STEP_S, STEPS, tz) if bundles else None + if s is not None: + return s, "model" + out, have = [], 0 + for k in range(STEPS): + t = start + k * STEP_S + v = None + for back in (86400, 2 * 86400): # the same quarter hour yesterday (or the day before) + v = history.mean(name, t - back) if history else None + if v is not None: + break + have += v is not None + out.append(v if v is not None else (now_value if now_value is not None else default)) + return out, ("history" if have else ("now" if now_value is not None else "default")) + + +def _hhmm(v: str, device_class) -> str | None: + """A departure as HH:MM: from "07:00(:00)" or a timestamp (local time + of the timestamp as given).""" + v = str(v) + if len(v) in (5, 8) and v[2] == ":": + return v[:5] + try: + d = datetime.fromisoformat(v.replace("Z", "+00:00")) + except ValueError: + return None + return d.strftime("%H:%M") + + +def device_state(c, col: Collector, now: float) -> dict: + """What the optimiser needs to know about a control now.""" + e = c.entities + st = {} + if c.kind == "battery": + soc = col.value(e.get("soc", "")) + st["soc_pct"] = soc if soc is not None else float(c.p("soc_pct")) + st["soc_estimated"] = soc is None + st["charge_from_grid"] = col.state(e.get("charge_from_grid", "")) == "on" + elif c.kind in ("heating", "cooling"): + t = col.value(e.get("temp", "")) + if t is None and e.get("climate"): + t = number(col.attr(e["climate"], "current_temperature")) + st["temp_c"] = t + if e.get("climate"): + st["target_c"] = number(col.attr(e["climate"], "temperature")) + st["hvac"] = col.state(e["climate"]) + else: + st["on"] = col.state(e.get("switch", "")) == "on" + elif c.kind == "ev": + conn = e.get("connected") + st["connected"] = col.state(conn) == "on" if conn else True + st["on"] = col.state(e.get("switch", "")) == "on" + st["current_a"] = col.value(e.get("current", "")) + st["soc_pct"] = col.value(e.get("soc", "")) + need = col.value(e.get("energy_needed", "")) + if need is not None: + unit = col.attr(e["energy_needed"], "unit_of_measurement") + st["need_wh"] = need * 1000.0 if unit == "kWh" else need + dep = col.state(e.get("departure", "")) if e.get("departure") else None + if dep: + st["departure"] = _hhmm(dep, col.attr(e["departure"], "device_class")) + elif c.kind == "cover": + st["position_pct"] = cover_position(col, e["cover"]) + st["set_position"] = cover_positions(col, e["cover"]) + return st + + +SET_POSITION = 4 # HA's CoverEntityFeature.SET_POSITION + + +def cover_positions(col: Collector, ent: str) -> bool: + """Can the cover be set to a position (else only opened and closed)? + True while HA has not said (the guard and the executor check again).""" + f = number(col.attr(ent, "supported_features")) + return True if f is None else bool(int(f) & SET_POSITION) + + +def cover_position(col: Collector, ent: str) -> float | None: + """A cover's position (0 closed, 100 open): its current_position, else + from its state (open 100, closed 0) for one that has no position.""" + v = number(col.attr(ent, "current_position")) + if v is not None: + return v + return {"open": 100.0, "closed": 0.0}.get(col.state(ent)) + + +def model_state(now: float, controls, inputs, col: Collector, bundles, history, tz: str, + weather_forecast: list[dict] | None, extra_limits: dict | None = None, + occupied_hours=(6, 22), building: dict | None = None, location: dict | None = None, + shade_ctx: dict | None = None, grid_order: dict | None = None) -> dict: + """The 48 h, 15-minute input for the optimiser (JSON: it runs in a + subprocess). location: the site's latitude and longitude (HA's + configuration); shade_ctx: per cover control its room (temp_c, + setpoint_c, season: shades.py).""" + start = int(now // STEP_S * STEP_S) + zone = ZoneInfo(tz or "UTC") + prices = bundles.prices(start, STEP_S, STEPS, now) + load, load_src = _series("load_w", start, bundles, history, tz, col.total(inputs.load_power), 500.0) + pv, pv_src = _series("pv_w", start, bundles, history, tz, None, 0.0) + t_out = _hourly(weather_forecast or [], "temperature", start, STEPS) + t_src = "weather forecast" + measured = col.value(inputs.outside_temp) if inputs.outside_temp else None + if t_out is not None and measured is not None: + # a thermometer outside says better than the forecast what it is + # now: the forecast moved by the difference, fading over 6 hours + bias = measured - t_out[0] + t_out = [v + bias * max(0.0, 1 - k / 24) for k, v in enumerate(t_out)] + t_src = "weather forecast, from the outdoor sensor now" + if t_out is None: + now_out = col.value(inputs.outside_temp) + if now_out is None and inputs.weather: + now_out = number(col.attr(inputs.weather, "temperature")) + t_out, t_src = [now_out if now_out is not None else 10.0] * STEPS, ("now" if now_out is not None else "default") + peak = max(pv) if pv else 0.0 + if peak > 100: + sun = [max(0.0, p / peak) for p in pv] + else: + # the sun's elevation now, held: a placeholder until a forecast says + elev = number(col.attr(inputs.sun, "elevation")) if inputs.sun else None + sun = [max(0.0, math.sin(math.radians(elev))) if elev is not None else 0.0] * STEPS + present = None + if inputs.presence: + vals = [col.state(p) for p in inputs.presence] + present = any(v in ("on", "home") for v in vals) if any(v is not None for v in vals) else None + occupied = [] + for k in range(STEPS): + if k < 4 and present is not None: + occupied.append(1 if present else 0) + continue + h = datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).hour + occupied.append(1 if occupied_hours[0] <= h < occupied_hours[1] else 0) + devices = [] + for c in controls: + if hasattr(c, "learn_range"): + c.learn_range(col) # a climate's own min_temp..max_temp + bounds = {} + for q in _quantities(c): + b = c.bounds(q, (extra_limits or {}).get(c.id)) + bounds[q] = [b.lo, b.hi, b.lo_by, b.hi_by] + devices.append({"id": c.id, "kind": c.kind, "params": {k: c.p(k) for k in _param_names(c)}, + "state": device_state(c, col, now), "bounds": bounds, + "channels": sorted(c.writable())}) + clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS) + sky = [max(0.0, min(1.0, 1 - c / 100.0)) for c in clouds] if clouds else [1.0] * STEPS + out = {"v": 1, "start": start, "step_s": STEP_S, "steps": STEPS, "tz": tz, + "price_import": prices.import_ct, "price_export": prices.export_ct, "price_note": prices.note, + "load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky, + "location": location or {}, + "sources": {"load": load_src, "pv": pv_src, "t_out": t_src, "model": bundles.model_id(), + "sky": "weather forecast" if clouds else "clear"}, + "devices": devices, "building": building or {}, "grid_order": grid_order or {}} + # a shade's moves by rules on the sun and its room (shades.py); the + # optimiser takes them as they are + from . import shades + for d in devices: + if d["kind"] == "cover": + d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"])) + return out + + +def _quantities(c) -> list[str]: + return {"battery": ["soc_pct", "power_w"], "heating": ["temp_c"], "cooling": ["temp_c"], + "ev": ["current_a"], "cover": ["position_pct"]}[c.kind] + + +def _param_names(c) -> list[str]: + from .controls import PARAMS + return list(PARAMS[c.kind]) diff --git a/src/edge/cantabile_edge/inventory.py b/src/edge/cantabile_edge/inventory.py new file mode 100644 index 0000000..cf348e4 --- /dev/null +++ b/src/edge/cantabile_edge/inventory.py @@ -0,0 +1,166 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""The site's devices for the cloud: what each is (maker, +model, firmware, the profile), its ratings (inverter kW, PV kWp, battery +kWh and kW, heat pump kW, ...), what Cantabile reads and controls of it +(asset and control ids) and its protection, for model training and the +planners' capacity. Only with the owner's consent to share; never HA's +entity ids or names (a device is its maker and model, its readings their +asset ids). The box's own changes of protection go with it (the cloud's +audit). + +Sources: the mapping (assets, controls, mapping.d fragments), HA's device +and entity registries (maker, model, firmware of the devices the mapped +entities belong to), and on a Hub the devices tool's specs +(devices-specs.json: profile, category, ratings, protection). + + {"v":1, "made", "devices": [{"id", "source": "devices"|"ha", + "manufacturer", "model", "model_id", "sw_version", "hw_version", + "eebus_ski" (EEBUS devices), "category", "profile", "profile_version", "ratings": {...}, + "assets": [...], "assumed": [...], "controls": [...], "protection", + "custodian"}], + "protection": [{"target", "level", "custodian", "source", "set_by", + "role", "at", "why"}]} +Sent when it changed, and once a day. +""" +import hashlib +import json +import logging +import os +import re +import time + +from .policy import Policy + +log = logging.getLogger(__name__) + +RESEND_S = 24 * 3600 +MIN_GAP_S = 600 # the link passes one every 10 minutes +VERSION_KEYS = ("manufacturer", "model", "model_id", "sw_version", "hw_version") + + +def _eebus(d: dict) -> dict: + """An EEBUS device's SKI (the EEBUS bridge's devices: their serial + number in HA): the cloud and the grid operator see which + control box limits a site. Not a secret: a certificate's key hash.""" + if any(len(i) == 2 and i[0] == "mqtt" and str(i[1]).startswith("cantabile_eebus_") for i in d.get("identifiers") or []): + ski = str(d.get("serial_number") or "").lower() + if re.fullmatch(r"[0-9a-f]{40}", ski): # the platform refuses anything else + return {"eebus_ski": ski} + return {} + + +def _hash(eid: str) -> str: + return "h" + hashlib.sha256(eid.encode()).hexdigest()[:12] + + +def build(mapping, registries: dict, specs: dict, policy: dict, now: float) -> dict: + ents = {e["entity_id"]: e for e in registries.get("entities") or []} + devs = {d["id"]: d for d in registries.get("devices") or []} + asset_of = {a.entity: a.asset for a in mapping.assets} + of_entity = {} + for a in mapping.assets: + of_entity.setdefault(a.entity, []).append(a) + + def assumed_of(eids): + """The readings that are assumed, not measured (mapping.py).""" + return sorted({a.asset for e in eids for a in of_entity.get(e, []) if getattr(a, "assumed", False)}) + control_of = {} + for c in mapping.controls: + for e in c.entities.values(): + control_of.setdefault(e, c.id) + + def ha_device(entity_ids, hint=None): + if hint and hint in devs: + return devs[hint] + for eid in entity_ids: + d = devs.get((ents.get(eid) or {}).get("device_id")) + if d: + return d + return {} + + out, covered = [], set() + for did, s in sorted((specs.get("devices") or {}).items()): + mine = list(s.get("entities") or []) + covered |= set(mine) + hd = ha_device(mine, s.get("ha_device")) + out.append({"id": did, "source": "devices", + **{k: hd.get(k) or "" for k in VERSION_KEYS}, **_eebus(hd), + # the profile's maker and model where HA has none + "manufacturer": hd.get("manufacturer") or s.get("manufacturer", ""), + "model": hd.get("model") or s.get("model", ""), + "category": s.get("category", ""), "profile": s.get("profile", ""), + "profile_version": s.get("profile_version", ""), "ratings": s.get("ratings") or {}, + "assets": sorted({asset_of[e] for e in mine if e in asset_of}), + "assumed": assumed_of(mine), + "controls": sorted(s.get("controls") or []), + "protection": s.get("protection") or "none", "custodian": s.get("custodian")}) + # the mapping's own entities (an installer's mapping; an HA add-on site): + # one entry per HA device they belong to + groups: dict[str, list[str]] = {} + for eid in list(asset_of) + list(control_of): + if eid in covered: + continue + d = (ents.get(eid) or {}).get("device_id") + groups.setdefault(d or "", []).append(eid) + for d, eids in sorted(groups.items()): + hd = devs.get(d) or {} + if not d: + continue # entities without a device: nothing to tell + out.append({"id": "ha:" + hashlib.sha256(d.encode()).hexdigest()[:12], "source": "ha", + **{k: hd.get(k) or "" for k in VERSION_KEYS}, **_eebus(hd), + "category": "", "profile": "", "profile_version": "", "ratings": {}, + "assets": sorted({asset_of[e] for e in eids if e in asset_of}), + "assumed": assumed_of(eids), + "controls": sorted({control_of[e] for e in eids if e in control_of}), + "protection": "none", "custodian": None}) + prot = [] + for t, e in sorted(policy.items()): + if e.get("source") == "cloud": + continue # the cloud has its own + kind, _, name = t.partition(":") + if kind == "entity": + t = f"asset:{asset_of[name]}" if name in asset_of else f"entity:{_hash(name)}" + prot.append({"target": t, **{k: e.get(k) for k in ("level", "custodian", "source", "set_by", "role", "at", "why")}}) + return {"v": 1, "made": int(now), "devices": out, "protection": prot} + + +class Inventory: + """Sends the inventory through the sink (the link: op "inventory").""" + + def __init__(self, cfg, mapping, consent, sink, policy: Policy | None = None, clock=time.time): + self.cfg, self.mapping, self.consent, self.sink, self.clock = cfg, mapping, consent, sink, clock + self.policy = policy or Policy(cfg.state_dir, cfg.site_id, clock) + self.specs_path = os.path.join(cfg.state_dir, "devices-specs.json") + self.sent_digest, self.sent_at = "", 0.0 + + def specs(self) -> dict: + try: + with open(self.specs_path) as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + async def maybe_send(self, client) -> bool: + if not self.consent.share: + return False + pub = getattr(self.sink, "publish", None) + if pub is None or client is None: + return False + try: + reg = await client.registries() + except Exception as e: + log.info("inventory: HA's registries: %s", e) + return False + now = self.clock() + if self.sent_at and now - self.sent_at < MIN_GAP_S: + return False + inv = build(self.mapping, reg, self.specs(), self.policy.entries(), now) + body = {k: v for k, v in inv.items() if k != "made"} + digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + if digest == self.sent_digest and now - self.sent_at < RESEND_S: + return False + await pub("inventory", inv) + self.sent_digest, self.sent_at = digest, now + log.info("inventory sent: %d devices", len(inv["devices"])) + return True diff --git a/src/edge/cantabile_edge/joinpage.py b/src/edge/cantabile_edge/joinpage.py new file mode 100644 index 0000000..461354f --- /dev/null +++ b/src/edge/cantabile_edge/joinpage.py @@ -0,0 +1,603 @@ +# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. +"""Joining a building or a community from Home Assistant ("Joining"), for sites that run the agent as an HA add-on: no Hub panel +there, so the add-on's own page (HA's ingress: Settings, Add-ons, Cantabile, +Open web UI, or the sidebar) offers what the Hub panel's Building or +community section does: join with the operator's code (or a QR code's +?code=), ask a building near Home Assistant's location to take the flat or +an energy community to take the home (a villa), withdraw a request, leave. + +The same requests as the Hub's /usr/lib/cantabile/building, to fleet's +POST /api/devices/building, signed with the site's key by the +link in this container (`cantabile-link sign "building::