From 6de2287dec43e542a0fe199267628d541860f6b3 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:04:58 -0800 Subject: [PATCH 01/22] build: run on ebus-panel-sim 0.11.0 Pin the emitter at 0.11.0; ebus-sdk stays at 0.22.0, still its ceiling. The cascade capture and the shed-forecast estimates of r202645-g and r202639-f are what the emitter itself cannot reproduce from their definitions, so they take its exceptions with its reasons. --- pyproject.toml | 4 +-- src/panelbench/firmware.py | 5 ++-- tests/fidelity/reproduction.py | 46 +++++++++++++++++++++++++++++++++- uv.lock | 8 +++--- 4 files changed, 54 insertions(+), 9 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0b62888..37de466 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,7 @@ dependencies = [ # `pformat` are both still absent from `homie.py` and the logger is still NOTSET at # import, so the filter remains a guard rather than a live need. # - # 0.22.0, which is the ceiling `ebus-panel-sim` 0.10.0 allows: it declares + # 0.22.0, which is the ceiling `ebus-panel-sim` 0.11.0 allows: it declares # `ebus-sdk<0.23,>=0.20.1`, so 0.23.x is out of range until the emitter widens it. That # costs nothing here. Everything 0.21.0 through 0.23.1 adds is the producer-side # declarative tree API — `DeviceSpec`, `DeviceTreeBuilder`, `build_from_declarations` and @@ -67,7 +67,7 @@ dependencies = [ # `RecordingTransport` (last-wins per topic, like a broker's retained store) and # therefore to the fidelity captures. "ebus-sdk==0.22.0", - "ebus-panel-sim==0.10.0", + "ebus-panel-sim==0.11.0", "paho-mqtt>=2.1,<2.2", ] diff --git a/src/panelbench/firmware.py b/src/panelbench/firmware.py index fb2b53d..ddc5ea7 100644 --- a/src/panelbench/firmware.py +++ b/src/panelbench/firmware.py @@ -5,8 +5,9 @@ and advertises it over mDNS, because a consumer reading any two of those must see one panel. -The emitter decides the BESS meter's sign and the EVSE user limit from the string -itself. PanelBench needs the same release for what the emitter does not derive, +The emitter decides the BESS meter's sign, the EVSE user limit and, from release +202645 under ``span-alpha-test-b2``, the circuits' ``connection/connection-point`` +from the string itself. PanelBench needs the same release for what the emitter does not derive, the per-inverter PV devices and the REST status, so it reads it here by the same rule: SPAN firmware strings are ``/``-separated, and the segment ``r`` plus six digits names the release as year and week (``spanos2/r202639/03`` is release diff --git a/tests/fidelity/reproduction.py b/tests/fidelity/reproduction.py index 92931ae..085722f 100644 --- a/tests/fidelity/reproduction.py +++ b/tests/fidelity/reproduction.py @@ -24,6 +24,26 @@ "and upstream lugs run the other way." ) +_FED_BY_ENCLOSURE: Final = ( + "The upstream lugs are fed by another enclosure, which a definition cannot express." +) + +_SHED_FORECAST_KEYS: Final = ( + "full-charge-time-to-priority-shed", + "full-charge-total-time-remaining", + "time-to-priority-shed", + "total-time-remaining", +) + + +def _shed_forecast(reason: str) -> dict[str, str]: + """The four shed-forecast estimates a panel values and the variant leaves unvalued.""" + return { + f"distribution-enclosure #1: shed-forecast/{key}: valued only by the capture": reason + for key in _SHED_FORECAST_KEYS + } + + EMITTER_EXCEPTIONS: Final[dict[str, dict[str, str]]] = { "r202639-b": { "distribution-enclosure #1: power-flows/site sign": ( @@ -49,10 +69,34 @@ }, "main32_r202633": { f"lugs UPSTREAM: connection/fed-by-device-{key}: valued only by the capture": ( - "The upstream lugs are fed by another enclosure, which a definition cannot express." + _FED_BY_ENCLOSURE ) for key in ("id", "status", "type") }, + "main32_r202645-cascade": { + "distribution-enclosure #1: power-flows/site shape": ( + "Fed by another panel, with its battery and PV upstream of it, the panel writes " + "site as an integer (2873), as main32_r202639-upstream-pv does with its PV and " + "battery upstream; the span profile keeps one decimal." + ), + **{ + f"lugs UPSTREAM: connection/fed-by-device-{key}: valued only by the capture": ( + _FED_BY_ENCLOSURE + ) + for key in ("id", "status", "type") + }, + }, + "r202645-g": _shed_forecast( + "On spanos3/r202645/02 the panel values the four shed-forecast estimates, as " + "r202639-f on spanos3/r202639/04 does; the variant keeps them unvalued." + ), + "r202639-f": _shed_forecast( + "On spanos3/r202639/04 the panel values four shed-forecast estimates (the total " + "and priority-shed times, from now and from a full charge) that both captures " + "with a battery on /03 leave unvalued, as the variant does. One capture does not " + "show whether that firmware always values them, or how it estimates them, so the " + "variant keeps them unvalued." + ), } """What the emitter cannot reproduce from a capture's own definition, by line prefix. diff --git a/uv.lock b/uv.lock index a2d9258..f159961 100644 --- a/uv.lock +++ b/uv.lock @@ -365,15 +365,15 @@ wheels = [ [[package]] name = "ebus-panel-sim" -version = "0.10.0" +version = "0.11.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ebus-sdk" }, { name = "pyyaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/6b/e1/5d2c79bea81269ca6a4785031790b71c105065011c64202fdd2da780ba21/ebus_panel_sim-0.10.0.tar.gz", hash = "sha256:1c109d5318a4850f25235343574ce9460d92c8cd20328e11cd35ad37fe1dfcc7", size = 344928, upload-time = "2026-11-10T18:03:44.678Z" } +sdist = { url = "https://files.pythonhosted.org/packages/98/10/0e113d8cf3c1702f5bf3e15761855f97c8458ec805caee8b53964e17ce79/ebus_panel_sim-0.11.0.tar.gz", hash = "sha256:b3d34385ee88a1d83f13ccbc03632ee92b8f6d8b17d24241302727af68f391c5", size = 509122, upload-time = "2026-11-20T02:45:38.708Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/ee/2964ad5073b96908903fc5ebb33ce0f7ebfa4fb6a7fb1139c84fea9b6151/ebus_panel_sim-0.10.0-py3-none-any.whl", hash = "sha256:c294e0a0d54a2b0a89e8718d70ffa00460a52ce4ee8e1817cbe5c17d08ce528b", size = 220938, upload-time = "2026-11-10T18:03:43.139Z" }, + { url = "https://files.pythonhosted.org/packages/8c/a4/970addcf188c3bbc8df292849e4bac3f538c5c7f49415e913f9324d8279f/ebus_panel_sim-0.11.0-py3-none-any.whl", hash = "sha256:36c34bb59ad226e6e6318788734988285b5617dffffb7834b9fe7f3e780da900", size = 317961, upload-time = "2026-11-20T02:45:37.347Z" }, ] [[package]] @@ -763,7 +763,7 @@ requires-dist = [ { name = "aiohttp-jinja2", specifier = ">=1.6" }, { name = "aiomqtt", specifier = ">=2.5.1,<2.6" }, { name = "cryptography", specifier = ">=42.0.0" }, - { name = "ebus-panel-sim", specifier = "==0.10.0" }, + { name = "ebus-panel-sim", specifier = "==0.11.0" }, { name = "ebus-sdk", specifier = "==0.22.0" }, { name = "jinja2", specifier = ">=3.1.0" }, { name = "paho-mqtt", specifier = ">=2.1,<2.2" }, From 7a8c76263855420c910a8cd8892e4268294833c9 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:11:14 -0800 Subject: [PATCH 02/22] feat(templates): the r202645 captures take their panels' template names The emitter's 0.11.0 captures of four panels PanelBench already templates, on release 202645, take those templates' names, and the release 202639 captures of the same panels, which keep their masked serials, are retired, as main32_r202633 was. ref_MAIN_40 is that panel recommissioned, with 38 circuits and no battery. Three captures of other panels become ref_MAIN_32_CASCADE, ref_MAIN_16_BESS and ref_MLO_48_HYBRID. The dashboard's first template is the release 202645 MAIN 32, and the startup test reads its serial from the file rather than naming it. Both changelogs' Unreleased sections had two Fixed headings; the cycling entry joins the first. --- CHANGELOG.md | 16 ++++--- README.md | 13 ++++-- panelbench/CHANGELOG.md | 13 ++++-- panelbench/DOCS.md | 7 ++- src/panelbench/reference_templates.py | 28 ++++++++---- ...hboard_never_saves_an_unloadable_config.py | 3 +- tests/test_hardware_version.py | 3 ++ tests/test_reference_templates.py | 43 +++++++++++++------ 8 files changed, 89 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74d1cfa..c86a080 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ **The shipped templates are all `ref_` templates: the two tandem templates are renamed, and the three `default_MAIN_` templates are removed.** +### Added + +- **Three templates of real panels**, generated from the emitter's reference captures: `ref_MAIN_32_CASCADE`, a MAIN 32 fed by another panel, with a battery; + `ref_MAIN_16_BESS`, a MAIN 16 with a hybrid battery and an EVSE; and `ref_MLO_48_HYBRID`, an MLO 48 whose battery's inverter takes its solar. + ### Changed - **The tandem templates are now `ref_MAIN_32_TANDEMS.yaml` and `ref_MLO_48_TANDEMS.yaml`**, formerly `default_MAIN_32_TANDEMS.yaml` and @@ -20,6 +25,9 @@ badge naming the serial. Delete the leftover `default_*` files, or clone the `ref_` equivalent. - **The README lists every template in one table**, and the conformance profile in `DEVELOPER.md` is the regenerated one: 452 match, 4 divergence, 69 extension and 1327 omission. +- **Four generated templates are their panels' later captures, on release 202645**: `ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48`, where + they were the release 202639 captures of the same panels. `ref_MAIN_40` is that panel recommissioned, with 38 circuits and no battery, where it had 5 and + a battery fed by a circuit, and `ref_UNKNOWN_16` adds an EVSE. - **A `pv` section listing `inverters` must set `enabled`, and `pv.enabled` must be `true` or `false`.** The inverters no circuit feeds publish only while `pv.enabled` is `true`, and a config listing them without it loaded and published none of them; it is now refused, saying to set `enabled` to `true` to publish them or `false` to keep them off. An `enabled` that is empty or quoted, such as `"false"`, which published the opposite of what it says, is refused @@ -37,6 +45,9 @@ generated `ref_` templates, clones, history databases, and `configs/.secrets/` and `configs/rates/`, which hold credentials and API keys. `.dockerignore` now keeps all but the presets and the two tracked templates out, as a build from git has it, and leaves local state and caches out of the build context; images built by CI were not affected. +- **A cycling load reads the same at a given simulated time on every run.** Its on and off phases follow the panel's clock, counted from the epoch, where they + ran from the moment the panel started on the real clock. A panel set to a simulated time could read a cycling load on in one run and off in the next, and + a panel no longer starts every cycling load at the start of its on phase. ### Removed @@ -46,11 +57,6 @@ one its reference capture shows, with circuits on spaces 9 to 24; the MAIN 40 range is the client's own choice, and its capture's circuits sit on spaces 9 to 45. -### Fixed - -- **A cycling load reads the same at a given simulated time on every run.** Its on and off phases follow the panel's clock, counted from the epoch, where they - ran from the moment the panel started on the real clock. A panel set to a simulated time could read a cycling load on in one run and off in the next, and - a panel no longer starts every cycling load at the start of its on phase. ## 2.8.0 — Tandem and quad breakers, and several panels on one broker diff --git a/README.md b/README.md index 205d036..c4fc025 100644 --- a/README.md +++ b/README.md @@ -390,15 +390,20 @@ leftover `default_*` files, or clone the `ref_` equivalent. | `ref_MAIN_32_TANDEMS.yaml` | 1-32 | tracked | MAIN 32 with solar, battery, 1 EVSE, 20-20 and 15-20 tandems and a 20-30 package | | `ref_MLO_48_TANDEMS.yaml` | 1-48 | tracked | Main-lug-only on hardware 3.0, 1 EVSE, four tandems, a quad and a tandem-quad | | `ref_MAIN_32.yaml` | 1-32 | generated | MAIN 32 with a battery | +| `ref_MAIN_32_CASCADE.yaml` | 1-32 | generated | MAIN 32 fed by another panel, with a battery | | `ref_MAIN_32_UPSTREAM_PV.yaml` | 1-32 | generated | MAIN 32 with two inverters and a battery upstream of the panel | | `ref_MAIN_16.yaml` | 9-24 | generated | MAIN 16 with a meter outside the panel | -| `ref_MAIN_40.yaml` | 9-48 | generated | MAIN 40 with a battery fed by a circuit | +| `ref_MAIN_16_BESS.yaml` | 9-24 | generated | MAIN 16 with a hybrid battery and 1 EVSE | +| `ref_MAIN_40.yaml` | 9-48 | generated | MAIN 40 with 38 circuits and no battery | | `ref_MLO_24.yaml` | 1-24 | generated | MLO 24, with no main breaker and a battery fed by a circuit | | `ref_MLO_48.yaml` | 1-48 | generated | MLO 48, with no main breaker and circuits sharing a meter and relay | -| `ref_UNKNOWN_16.yaml` | 1-16 | generated | 16-space panel that publishes no model, with a meter outside it | +| `ref_MLO_48_HYBRID.yaml` | 1-48 | generated | MLO 48, with no main breaker, 1 EVSE and a hybrid battery | +| `ref_UNKNOWN_16.yaml` | 1-16 | generated | 16-space panel that publishes no model, with 1 EVSE and a meter outside it | -Each generated template is that panel as it published itself on `spanos3/r202639/03`, with serials, ids and site details masked. Read them with the `span-panel` -integration v2.2.0 or later. +Each generated template is that panel as it published itself, with serials, ids and site details masked, on the firmware it reports as `firmware_version`: +`spanos3/r202645/02` for `ref_MAIN_32`, `ref_MAIN_32_CASCADE`, `ref_MAIN_16_BESS`, `ref_MAIN_40` and `ref_UNKNOWN_16`, `spanos3/r202645/01` for `ref_MLO_48`, +`spanos3/r202639/04` for `ref_MLO_48_HYBRID`, and `spanos3/r202639/03` for the rest. Where a panel was captured on both releases, the template is its later +capture. Read them with the `span-panel` integration v2.2.0 or later. #### Tandem and quad breakers diff --git a/panelbench/CHANGELOG.md b/panelbench/CHANGELOG.md index cb8ae00..52c7b9b 100644 --- a/panelbench/CHANGELOG.md +++ b/panelbench/CHANGELOG.md @@ -4,6 +4,11 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_` templates are removed. +### Added + +- **`ref_MAIN_32_CASCADE`, `ref_MAIN_16_BESS` and `ref_MLO_48_HYBRID`**: a MAIN 32 fed by another panel, a MAIN 16 with a hybrid battery and an EVSE, and an + MLO 48 whose battery's inverter takes its solar. + ### Changed - **The tandem templates are now `ref_MAIN_32_TANDEMS` and `ref_MLO_48_TANDEMS`.** @@ -15,6 +20,8 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ integration's positions warning continues. A leftover `default_MAIN_32_TANDEMS.yaml` or `default_MLO_48_TANDEMS.yaml` keeps its `ref_` twin's serial (`sim-32t-tandems-001`, `sim-48t-tandems-001`), so running both starts one and the other shows an `error` badge naming the serial. Delete the leftover `default_*` files, or clone the `ref_` equivalent. +- **`ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48` are their panels' later captures, on release 202645.** `ref_MAIN_40` now has 38 + circuits and no battery, and `ref_UNKNOWN_16` an EVSE. - **A `pv` section listing `inverters` must set `enabled`, to `true` or `false`**: without it they published nothing, and a quoted `"false"` published them; now the config is refused, saying so. @@ -22,16 +29,14 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ - **A clone of a MAIN 16 or MAIN 40 offers only its model's spaces**, 9 to 24 or 9 to 48, where a circuit added to it could land on space 1 and the integration warned about its breaker positions. +- **A cycling load, such as a pool pump or a dryer, reads the same at a given simulated time on every run**, where it could read on in one run and off in the + next. ### Removed - **`default_MAIN_16`, `default_MAIN_32` and `default_MAIN_40`**; use `ref_MAIN_16`, `ref_MAIN_32` and `ref_MAIN_40`. The first and last numbered their spaces from 1, where the SpanPanel integration's client places those models at 9 to 24 and 9 to 48, so the integration warned about their breaker positions. -### Fixed - -- **A cycling load, such as a pool pump or a dryer, reads the same at a given simulated time on every run**, where it could read on in one run and off in the - next. ## 2.8.0 — 2026-11-15 diff --git a/panelbench/DOCS.md b/panelbench/DOCS.md index d11a2da..4c0b195 100644 --- a/panelbench/DOCS.md +++ b/panelbench/DOCS.md @@ -140,8 +140,11 @@ System, light, or dark theme via the header selector. ## Firmware version -The shipped templates are SPAN panels on firmware release 202639 and -report `spanos3/r202639/03`. On `ref_MAIN_32_TANDEMS` the battery's +The two tracked templates report `spanos3/r202639/03`. Each template +from a real panel reports the firmware it was captured on: release +202645 for `ref_MAIN_32`, `ref_MAIN_32_CASCADE`, `ref_MAIN_16_BESS`, +`ref_MAIN_40`, `ref_MLO_48` and `ref_UNKNOWN_16`, and 202639 for the +rest. On `ref_MAIN_32_TANDEMS` the battery's power reading is positive while discharging, the solar circuit is the locked "Commissioned PV System" circuit, and the status endpoint reports hardware version `1.2`. Read it with the SpanPanel/span diff --git a/src/panelbench/reference_templates.py b/src/panelbench/reference_templates.py index dbc03ef..d017613 100644 --- a/src/panelbench/reference_templates.py +++ b/src/panelbench/reference_templates.py @@ -45,13 +45,16 @@ dashboard keeps every file under it read-only (``is_template``).""" _TEMPLATE_NAMES: Final[Mapping[str, str]] = { - "main32_r202639": "MAIN_32", + "main32_r202645": "MAIN_32", + "main32_r202645-cascade": "MAIN_32_CASCADE", "main32_r202639-upstream-pv": "MAIN_32_UPSTREAM_PV", - "r202639-a": "UNKNOWN_16", + "r202645-a": "UNKNOWN_16", "r202639-b": "MAIN_16", - "r202639-c": "MAIN_40", + "r202645-g": "MAIN_16_BESS", + "r202645-c": "MAIN_40", "r202639-d": "MLO_24", - "r202639-e": "MLO_48", + "r202645-e": "MLO_48", + "r202639-f": "MLO_48_HYBRID", } """What each reference capture's template is called, by the capture's handle: the model its panel publishes, or ``UNKNOWN`` and its spaces where it publishes none, then @@ -60,9 +63,16 @@ from the capture, so publishing a capture again never renames the template a ``--config`` names.""" -_RETIRED_CAPTURES: Final = frozenset({"main32_r202633"}) -"""Captures written as no template: a panel on a release before 202639, whose name -would be ``MAIN_32`` as the r202639 capture's is.""" +_RETIRED_CAPTURES: Final = frozenset( + {"main32_r202633", "main32_r202639", "r202639-a", "r202639-c", "r202639-e"} +) +"""Captures written as no template, whose names later captures take. + +``main32_r202633`` is a MAIN 32 on a release before 202639, whose name would be +``MAIN_32`` as the later MAIN 32 capture's is. ``main32_r202639``, ``r202639-a``, +``r202639-c`` and ``r202639-e`` give their names to the r202645 captures of the same +panels, which keep their masked serials; ``r202645-c`` is that MAIN 40 recommissioned, +with 38 circuits and no battery.""" def is_template(filename: str) -> bool: @@ -85,9 +95,9 @@ def template_filename(name: str) -> str: return f"{TEMPLATE_PREFIX}{_TEMPLATE_NAMES.get(name, name)}.yaml" -FIRST_TEMPLATE: Final = template_filename("main32_r202639") +FIRST_TEMPLATE: Final = template_filename("main32_r202645") """The template the dashboard opens when it has no config to open: a real MAIN 32 on -release 202639, as it published itself.""" +release 202645, as it published itself.""" def first_template(config_dir: Path) -> Path | None: diff --git a/tests/test_dashboard_never_saves_an_unloadable_config.py b/tests/test_dashboard_never_saves_an_unloadable_config.py index 243e526..2025a59 100644 --- a/tests/test_dashboard_never_saves_an_unloadable_config.py +++ b/tests/test_dashboard_never_saves_an_unloadable_config.py @@ -180,7 +180,8 @@ async def test_the_dashboard_starts_on_an_unloadable_active_config(tmp_path: Pat # The first template, read-only, rather than an empty panel, and never the refused # file, so nothing can be saved over it. assert app[APP_KEY_DASHBOARD_CONTEXT].config_filter == _FIRST_VIEW - assert "sim-main32_r202639" in html + first = yaml.safe_load((tmp_path / _FIRST_VIEW).read_text(encoding="utf-8")) + assert first["panel_config"]["serial_number"] in html def test_with_no_config_to_resume_the_dashboard_opens_the_first_template( diff --git a/tests/test_hardware_version.py b/tests/test_hardware_version.py index ef5b09c..65b3e2b 100644 --- a/tests/test_hardware_version.py +++ b/tests/test_hardware_version.py @@ -42,6 +42,9 @@ "ref_MAIN_32_TANDEMS.yaml": "1.2", "ref_MLO_48_TANDEMS.yaml": "3.0", "ref_MAIN_32.yaml": "1.2", + "ref_MAIN_32_CASCADE.yaml": "1.2", + "ref_MAIN_16_BESS.yaml": "3.0", + "ref_MLO_48_HYBRID.yaml": "3.0", "ref_MAIN_32_UPSTREAM_PV.yaml": "1.2", "ref_UNKNOWN_16.yaml": "3.0", "ref_MAIN_16.yaml": "3.0", diff --git a/tests/test_reference_templates.py b/tests/test_reference_templates.py index a06b1ee..b13b025 100644 --- a/tests/test_reference_templates.py +++ b/tests/test_reference_templates.py @@ -12,7 +12,7 @@ import logging import subprocess from pathlib import Path -from typing import ClassVar +from typing import ClassVar, Final import pytest import yaml @@ -44,20 +44,39 @@ def test_every_reference_capture_is_written_as_a_template(tmp_path: Path) -> Non assert all(is_template(path.name) for path in written) -def test_a_retired_capture_is_written_as_no_template(tmp_path: Path) -> None: - """The r202633 capture would take the r202639 one's name, so it gets none.""" - assert "main32_r202633" in reference_capture_names() - assert "main32_r202633" not in template_capture_names() +# Each capture retired for a later one of the same panel, that later capture, and the +# name it takes. +_SUCCESSORS: Final = { + "main32_r202639": ("main32_r202645", "ref_MAIN_32.yaml"), + "r202639-a": ("r202645-a", "ref_UNKNOWN_16.yaml"), + "r202639-c": ("r202645-c", "ref_MAIN_40.yaml"), + "r202639-e": ("r202645-e", "ref_MLO_48.yaml"), +} + + +def _panel_serial(name: str) -> str: + """The masked serial *name*'s panel publishes, which it keeps from one capture to + the next.""" + tree = load_reference_capture(name).tree + (panel,) = [d for d in tree.values() if d.type == "distribution-enclosure"] + return str(panel.value("info/serial-number")) + +def test_a_retired_capture_is_written_as_no_template(tmp_path: Path) -> None: + """A capture of a panel the emitter also ships a later capture of gets no template: + the later capture of the same panel, which keeps its masked serial, takes its name. + ``main32_r202633``, masked before panels kept theirs, is a MAIN 32 on a release + before 202639, whose name the later MAIN 32 capture takes.""" write_reference_templates(tmp_path) - assert (tmp_path / "ref_MAIN_32.yaml").exists() - assert ( - yaml.safe_load((tmp_path / "ref_MAIN_32.yaml").read_text(encoding="utf-8"))[ - "panel_config" - ]["serial_number"] - == "sim-main32_r202639" - ) + assert "main32_r202633" in reference_capture_names() + assert "main32_r202633" not in template_capture_names() + for retired, (successor, filename) in _SUCCESSORS.items(): + assert retired in reference_capture_names(), retired + assert retired not in template_capture_names(), retired + assert _panel_serial(retired) == _panel_serial(successor), retired + written = yaml.safe_load((tmp_path / filename).read_text(encoding="utf-8")) + assert written["panel_config"]["serial_number"] == f"sim-{successor}", retired @pytest.mark.parametrize("name", template_capture_names()) From a97ba8cbf586598085e9f956d2907e87190a11fa Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:16:29 -0800 Subject: [PATCH 03/22] feat(lugs): a panel without a feedthrough publishes no downstream lugs from release 202645 panel_config.feedthrough (default true) records whether the panel has a feedthrough module. From SPAN release 202645 a hardware 3.0 panel without one publishes its upstream lugs alone, as the emitter's r202645 captures show, so the spec generator leaves the downstream lugs out under span-alpha-test-b2 on that release or a firmware naming none. Earlier releases publish both whatever the panel has, as every r202639 capture does, and no capture shows a MAIN 32 leaving them out, so there the flag changes nothing. A clone of a panel publishing its upstream lugs alone writes feedthrough: false; a lugs.downstream section for lugs the panel does not publish is refused, and a feedthrough that is not a bool. --- src/panelbench/clone.py | 12 ++ src/panelbench/config_types.py | 4 + .../emitter_adapter/spec_generator.py | 8 +- src/panelbench/firmware.py | 5 + src/panelbench/hardware.py | 25 ++- src/panelbench/validation.py | 24 +++ tests/test_feedthrough.py | 151 ++++++++++++++++++ 7 files changed, 227 insertions(+), 2 deletions(-) create mode 100644 tests/test_feedthrough.py diff --git a/src/panelbench/clone.py b/src/panelbench/clone.py index 244d12f..4dacb44 100644 --- a/src/panelbench/clone.py +++ b/src/panelbench/clone.py @@ -347,6 +347,10 @@ def translate_panel_tree( lugs = _lugs_config(devices, panel_device_id, unvalued) if lugs: config["lugs"] = lugs + # A panel publishing its upstream lugs alone has no feedthrough, as release 202645 + # publishes a hardware 3.0 panel without one; earlier releases publish both. + if _lugs_directions(devices, panel_device_id) == {"upstream"}: + panel_config["feedthrough"] = False # The panel's firmware decides which side of SPAN release 202639 the clone # publishes (the BESS meter's sign, the EVSE limit), so a clone of a panel on an @@ -1118,6 +1122,14 @@ def _outside_meter(ordinal: int, unvalued: list[str]) -> dict[str, object]: return meter +def _lugs_directions(devices: Mapping[str, DiscoveredDevice], panel_device_id: str) -> set[str]: + """The directions of the lugs the panel publishes, ``upstream`` and ``downstream``.""" + return { + (_get_prop(devices, lugs_id, "info", "direction") or "").lower() + for lugs_id in _devices_of_type(devices, panel_device_id, TYPE_LUGS) + } + + def _lugs_config( devices: Mapping[str, DiscoveredDevice], panel_device_id: str, diff --git a/src/panelbench/config_types.py b/src/panelbench/config_types.py index 2bbe1b2..18d0e34 100644 --- a/src/panelbench/config_types.py +++ b/src/panelbench/config_types.py @@ -69,6 +69,10 @@ class PanelConfig(TypedDict): service_voltage_v: NotRequired[float] # service voltage (default 240.0) line_voltage_v: NotRequired[float] # per-leg voltage (default 120.0) islandable: NotRequired[bool] # Explicit override for whether the panel can island. + # Whether the panel has a feedthrough module (default true). From SPAN release 202645 a + # hardware 3.0 panel without one publishes no downstream lugs + # (`hardware.publishes_downstream_lugs`); a clone of such a panel writes false. + feedthrough: NotRequired[bool] vendor_name: NotRequired[str] # info/vendor-name (default "Span"); a clone keeps its panel's model: NotRequired[str] # info/model (default: from total_tabs); a clone keeps its panel's # The panel's network configuration, as a clone reads it from its panel. Defaults: diff --git a/src/panelbench/emitter_adapter/spec_generator.py b/src/panelbench/emitter_adapter/spec_generator.py index 0b2abda..2eeeed3 100644 --- a/src/panelbench/emitter_adapter/spec_generator.py +++ b/src/panelbench/emitter_adapter/spec_generator.py @@ -29,7 +29,12 @@ stable_circuit_uuid, ) from panelbench.firmware import SPAN_RELEASE_202639, panel_firmware_version, predates -from panelbench.hardware import panel_hardware_version, panel_variant, publishes_pv_devices +from panelbench.hardware import ( + panel_hardware_version, + panel_variant, + publishes_downstream_lugs, + publishes_pv_devices, +) from panelbench.inverter import ( normalise_inverter_type, template_inverter_type, @@ -169,6 +174,7 @@ def _lugs_instances(profile: SimulationConfig) -> list[DeviceInstance]: (upstream_id, "upstream", lugs.get("upstream") or {}), (downstream_id, "downstream", lugs.get("downstream") or {}), ) + if direction == "upstream" or publishes_downstream_lugs(profile) ] diff --git a/src/panelbench/firmware.py b/src/panelbench/firmware.py index ddc5ea7..91f96e1 100644 --- a/src/panelbench/firmware.py +++ b/src/panelbench/firmware.py @@ -35,6 +35,11 @@ name in ``info/name``, as the emitter's captured MAIN 32 on the release shows. """ +SPAN_RELEASE_202645: Final = 202645 +"""The SPAN release from which a hardware 3.0 panel publishes each circuit's +``connection/connection-point``, and one without a feedthrough module publishes its +upstream lugs alone, as the emitter's r202645 captures show.""" + _RELEASE_SEGMENT: Final = re.compile(r"r(\d{6})") diff --git a/src/panelbench/hardware.py b/src/panelbench/hardware.py index cb3104b..2aab830 100644 --- a/src/panelbench/hardware.py +++ b/src/panelbench/hardware.py @@ -16,7 +16,12 @@ from typing import TYPE_CHECKING, Final -from panelbench.firmware import SPAN_RELEASE_202639, panel_firmware_version, predates +from panelbench.firmware import ( + SPAN_RELEASE_202639, + SPAN_RELEASE_202645, + panel_firmware_version, + predates, +) if TYPE_CHECKING: from collections.abc import Mapping @@ -148,6 +153,24 @@ def publishes_shared_breakers(variant: Variant) -> bool: return variant == _EXTENDED_VARIANT +def publishes_downstream_lugs(config: Mapping[str, object]) -> bool: + """Whether the panel *config* describes publishes its downstream lugs. + + From SPAN release 202645 a hardware 3.0 panel without a feedthrough module + publishes its upstream lugs alone, as the emitter's r202645 captures show. + Earlier releases publish both whatever the panel has, and no capture shows a + span-variant panel leaving them out, so ``panel_config.feedthrough: false`` + removes them only under the variant hardware 3.0 selects, on release 202645 or + a firmware naming no release. + """ + panel = config.get("panel_config") + if not isinstance(panel, dict) or panel.get("feedthrough", True) is not False: + return True + return panel_variant(config) != _EXTENDED_VARIANT or predates( + panel_firmware_version(config), SPAN_RELEASE_202645 + ) + + def relay_locks_priority(variant: Variant) -> bool: """Whether a circuit's locked relay also locks its shed priority under *variant*. diff --git a/src/panelbench/validation.py b/src/panelbench/validation.py index 58f7f3c..1f4730c 100644 --- a/src/panelbench/validation.py +++ b/src/panelbench/validation.py @@ -17,6 +17,7 @@ from panelbench.hardware import ( declares_variant, panel_variant, + publishes_downstream_lugs, publishes_outside_meters, publishes_pv_devices, publishes_shared_breakers, @@ -66,6 +67,7 @@ def validate_yaml_config(config_data: Any) -> None: validate_outside_meters(config_data) validate_shared_circuits(config_data) validate_unvalued_lists(config_data) + validate_downstream_lugs(config_data) if "panel_source" in config_data: validate_panel_source(config_data["panel_source"]) @@ -80,6 +82,10 @@ def validate_panel_config(panel_config: Any) -> None: for field in required_panel_fields: if field not in panel_config: raise ValueError(f"Missing required panel_config field: {field}") + if "feedthrough" in panel_config and not isinstance(panel_config["feedthrough"], bool): + raise ValueError( + f"panel_config.feedthrough must be true or false, not {panel_config['feedthrough']!r}" + ) registration_limit(panel_config) @@ -612,6 +618,24 @@ def section(where: str, value: object, *keys: str) -> None: raise ValueError(f"{where} must be a list of node/property paths, got {paths!r}") +def validate_downstream_lugs(config_data: dict[str, object]) -> None: + """Refuse commissioning for downstream lugs the panel does not publish. + + A hardware 3.0 panel with ``feedthrough: false`` publishes none from release + 202645, so a ``lugs.downstream`` section would describe nothing; on an earlier + release it still describes the downstream lugs that release publishes. + """ + lugs = config_data.get("lugs") + if not isinstance(lugs, dict) or "downstream" not in lugs: + return + if not publishes_downstream_lugs(config_data): + raise ValueError( + "lugs.downstream commissions downstream lugs this panel does not publish: " + "from SPAN release 202645 a hardware 3.0 panel with panel_config.feedthrough " + "false publishes none. Remove lugs.downstream, or set feedthrough to true." + ) + + def _listed(value: object) -> list[object]: return value if isinstance(value, list) else [] diff --git a/tests/test_feedthrough.py b/tests/test_feedthrough.py new file mode 100644 index 0000000..0a4c2fd --- /dev/null +++ b/tests/test_feedthrough.py @@ -0,0 +1,151 @@ +"""A panel without a feedthrough module publishes no downstream lugs from release 202645. + +From SPAN release 202645 a hardware 3.0 panel without a feedthrough publishes its +upstream lugs alone, as the emitter's r202645 captures show. Earlier releases publish +both whatever the panel has, as every release 202639 capture does, and no capture shows +a MAIN 32 leaving them out. ``panel_config.feedthrough: false`` records the hardware +fact, and the lugs it publishes follow the panel's variant and firmware. +""" + +from __future__ import annotations + +import copy +import json +from typing import TYPE_CHECKING, Final + +import pytest +import yaml +from ebus_panel_sim import load_reference_capture + +from panelbench.clone import translate_panel_tree +from panelbench.emitter_adapter.instance_ids import lugs_device_ids +from panelbench.emitter_adapter.wire_capture import recorded_panel +from panelbench.validation import validate_yaml_config +from tests._helpers import CONFIGS, discovered_from_tree, panel_config, write_config + +if TYPE_CHECKING: + from pathlib import Path + + from panelbench.config_types import SimulationConfig + +_R202645: Final = "spanos3/r202645/02" +_R202639: Final = "spanos3/r202639/03" + + +def _hardware_3(*, firmware: str | None, feedthrough: bool | None = None) -> SimulationConfig: + """The tracked hardware 3.0 template on *firmware*, without its downstream lugs' + commissioning, with ``feedthrough`` set unless it is None.""" + config: SimulationConfig = yaml.safe_load( + (CONFIGS / "ref_MLO_48_TANDEMS.yaml").read_text(encoding="utf-8") + ) + if firmware is None: + config.pop("firmware_version", None) + else: + config["firmware_version"] = firmware + lugs = config.get("lugs") + if lugs is not None: + lugs.pop("downstream", None) + if feedthrough is not None: + config["panel_config"]["feedthrough"] = feedthrough + return config + + +async def _published_lugs(tmp_path: Path, config: SimulationConfig) -> set[str]: + """Which of the panel's two lugs devices it publishes, as its children.""" + runtime, recorder = await recorded_panel(write_config(tmp_path / "panel.yaml", config)) + del runtime + serial = config["panel_config"]["serial_number"] + upstream, downstream = lugs_device_ids(serial) + children = set(json.loads(recorder.retained[f"ebus/5/{serial}/$description"])["children"]) + published = {topic.split("/")[2] for topic in recorder.retained} + return { + direction + for direction, device_id in (("upstream", upstream), ("downstream", downstream)) + if device_id in children and device_id in published + } + + +@pytest.mark.asyncio +async def test_a_hardware_3_panel_on_202645_without_a_feedthrough_publishes_upstream_lugs_only( + tmp_path: Path, +) -> None: + assert await _published_lugs(tmp_path, _hardware_3(firmware=_R202645, feedthrough=False)) == { + "upstream" + } + + +@pytest.mark.asyncio +async def test_a_firmware_naming_no_release_is_taken_to_be_current(tmp_path: Path) -> None: + """As the emitter takes it: a simulator string gets release 202645's behaviour.""" + assert await _published_lugs(tmp_path, _hardware_3(firmware=None, feedthrough=False)) == { + "upstream" + } + + +@pytest.mark.parametrize( + ("firmware", "feedthrough"), + [ + pytest.param(_R202639, False, id="release 202639 publishes both"), + pytest.param(_R202645, True, id="with a feedthrough"), + pytest.param(_R202645, None, id="by default"), + ], +) +@pytest.mark.asyncio +async def test_otherwise_a_hardware_3_panel_publishes_both_lugs( + tmp_path: Path, firmware: str, feedthrough: bool | None +) -> None: + published = await _published_lugs( + tmp_path, _hardware_3(firmware=firmware, feedthrough=feedthrough) + ) + assert published == {"upstream", "downstream"} + + +@pytest.mark.asyncio +async def test_a_main_32_publishes_both_lugs_whatever_its_feedthrough(tmp_path: Path) -> None: + """No capture shows a span-variant panel leaving its downstream lugs out.""" + config = panel_config() + config["firmware_version"] = _R202645 + config["panel_config"]["feedthrough"] = False + assert await _published_lugs(tmp_path, config) == {"upstream", "downstream"} + + +@pytest.mark.parametrize("value", ["false", "no", 0, None, ""]) +def test_a_feedthrough_that_is_not_true_or_false_is_refused(value: object) -> None: + raw = yaml.safe_load(yaml.safe_dump(dict(_hardware_3(firmware=_R202645)))) + raw["panel_config"]["feedthrough"] = value + with pytest.raises(ValueError, match=r"panel_config\.feedthrough must be true or false"): + validate_yaml_config(raw) + + +def test_downstream_lugs_commissioning_on_a_panel_that_publishes_none_is_refused() -> None: + config = _hardware_3(firmware=_R202645, feedthrough=False) + config.setdefault("lugs", {})["downstream"] = {"feeds_role": "UNUSED"} + with pytest.raises(ValueError, match=r"lugs\.downstream"): + validate_yaml_config(config) + + +def test_on_release_202639_downstream_lugs_commissioning_stands_without_a_feedthrough() -> None: + """That release publishes the downstream lugs whatever the panel has, so their + commissioning still describes them.""" + config = _hardware_3(firmware=_R202639, feedthrough=False) + config.setdefault("lugs", {})["downstream"] = {"feeds_role": "UNUSED"} + validate_yaml_config(copy.deepcopy(config)) + + +@pytest.mark.parametrize( + ("capture", "feedthrough"), + [ + pytest.param("r202645-c", False, id="a 202645 tree without downstream lugs"), + pytest.param("r202639-c", None, id="a 202639 tree with both"), + pytest.param("main32_r202645", None, id="a MAIN 32 with both"), + ], +) +def test_a_clone_records_a_panel_without_downstream_lugs( + capture: str, feedthrough: bool | None +) -> None: + tree = load_reference_capture(capture).tree + (panel,) = [i for i, d in tree.items() if d.type == "distribution-enclosure"] + config = translate_panel_tree(panel, discovered_from_tree(tree)) + panel_section = config["panel_config"] + assert isinstance(panel_section, dict) + assert panel_section.get("feedthrough") == feedthrough From d4bd9ed48826e875bd52a083fb30e3cff5127f3a Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:24:26 -0800 Subject: [PATCH 04/22] feat(battery): a hybrid battery takes its own solar bess.inverter_type (ac-coupled by default, or hybrid) says whether the battery's own inverter also takes PV, published as its inverter-type, and bess.pv_array.nameplate_capacity_w rates the array a hybrid takes. The engine produces that array with the model PV circuits use, by the panel's location and weather, and the runtime hands it to the emitter as the battery's bess_pv, which the emitter adds to power-flows/pv, to what the battery's dispatch sees and to the grid; the battery is still dispatched by the emitter. The Model view books the array the same way in both passes. A clone takes a battery's coupling from the emitter's own reading of the tree, which writes hybrid where the panel publishes power-flows/pv and nothing but its one battery could bring it solar, rather than keeping a second rule; an import keeps its definition's coupling. The fidelity replay carries a capture's bess_pv onto the reproduction's battery, so r202639-f reproduces on both routes. The recorder history helper moves to tests/_helpers for the Model view tests. --- src/panelbench/clone.py | 22 +- src/panelbench/config_types.py | 10 + src/panelbench/definition_import.py | 9 + src/panelbench/emitter_adapter/runtime.py | 12 + .../emitter_adapter/spec_generator.py | 2 + src/panelbench/engine.py | 44 +++- src/panelbench/validation.py | 41 ++++ tests/_helpers.py | 31 +++ tests/fidelity/replay.py | 1 + tests/test_hybrid_battery.py | 208 ++++++++++++++++++ tests/test_modeling_data.py | 37 +--- 11 files changed, 378 insertions(+), 39 deletions(-) create mode 100644 tests/test_hybrid_battery.py diff --git a/src/panelbench/clone.py b/src/panelbench/clone.py index 4dacb44..3a40d7a 100644 --- a/src/panelbench/clone.py +++ b/src/panelbench/clone.py @@ -213,7 +213,8 @@ def translate_panel_tree( bess_nodes = _devices_of_type(devices, panel_device_id, TYPE_BESS) pv_nodes = _devices_of_type(devices, panel_device_id, TYPE_PV) evse_nodes = _devices_of_type(devices, panel_device_id, TYPE_EVSE) - unvalued = _unvalued_by_device(_emitter_reading(devices, panel_device_id)) + reading = _emitter_reading(devices, panel_device_id) + unvalued = _unvalued_by_device(reading) hardware = _get_prop(devices, panel_device_id, "info", "hardware-version") or "" inferred = variant_for(hardware) published = inferred if variant is None else variant @@ -373,6 +374,8 @@ def translate_panel_tree( devices, panel_device_id, bess_id, mid_nodes, circuit_nodes, unvalued, keys ) if bess_cfg is not None: + if bess_id in _hybrid_batteries(reading): + bess_cfg["inverter_type"] = "hybrid" config["bess"] = bess_cfg if host is not None: @@ -1222,6 +1225,23 @@ def _as_tree(devices: Mapping[str, DiscoveredDevice]) -> Tree: return tree +def _hybrid_batteries(reading: PanelDefinition | None) -> set[str]: + """The batteries the emitter's capture writes hybrid, by device id on the panel. + + A panel does not publish its battery's coupling. The emitter's capture reads it + from the tree's topology: a panel publishing ``power-flows/pv`` with one battery + and nothing else that could bring it solar takes that solar through the battery. + The clone takes the emitter's reading rather than keeping a second rule. + """ + if reading is None: + return set() + return { + instance.instance_id + for instance in reading.manifest.of_class("bess") + if instance.metadata.get("inverter-type") == "hybrid" + } + + def _unvalued_by_device(reading: PanelDefinition | None) -> dict[str, list[str]]: """Each device's declared and unvalued properties, by its device id on the panel.""" if reading is None: diff --git a/src/panelbench/config_types.py b/src/panelbench/config_types.py index 18d0e34..8c26688 100644 --- a/src/panelbench/config_types.py +++ b/src/panelbench/config_types.py @@ -159,6 +159,12 @@ class CircuitTemplate(TypedDict): priority: str # "MUST_HAVE", "NON_ESSENTIAL" +class PVArrayYAML(TypedDict): + """The PV array a hybrid battery's own inverter takes, on its DC side.""" + + nameplate_capacity_w: float # the array's rating; it produces by the panel's sun + + class BESSConfigYAML(TypedDict, total=False): """Top-level BESS configuration in the simulator YAML.""" @@ -184,6 +190,10 @@ class BESSConfigYAML(TypedDict, total=False): firmware_version: str relative_position: Literal["UPSTREAM", "DOWNSTREAM", "IN_PANEL"] feed: str # the `id` of the circuit feeding a battery in the panel + # Whether the battery's own inverter also takes PV (default ac-coupled); a hybrid's + # array, if rated, produces into power-flows/pv as the emitter's `bess_pv`. + inverter_type: Literal["ac-coupled", "hybrid"] + pv_array: PVArrayYAML nameplate_capacity_kwh: float max_charge_w: float max_discharge_w: float diff --git a/src/panelbench/definition_import.py b/src/panelbench/definition_import.py index 92fafbc..594f4c0 100644 --- a/src/panelbench/definition_import.py +++ b/src/panelbench/definition_import.py @@ -108,6 +108,15 @@ def _overlay_emitter_options(config: dict[str, object], definition: PanelDefinit "would silently drop the battery" ) bess.update(bess_dispatch_yaml(definition.bess_configs[0], definition.manifest)) + # The definition says what the panel is, so its battery's coupling outranks the + # one the clone reads from the tree's topology. + if any( + battery.metadata.get("inverter-type") == "hybrid" + for battery in definition.manifest.of_class("bess") + ): + bess["inverter_type"] = "hybrid" + else: + bess.pop("inverter_type", None) if definition.load_shedding is not None: panel = config["panel_config"] if not isinstance(panel, dict): diff --git a/src/panelbench/emitter_adapter/runtime.py b/src/panelbench/emitter_adapter/runtime.py index 2013fcf..3aca9d8 100644 --- a/src/panelbench/emitter_adapter/runtime.py +++ b/src/panelbench/emitter_adapter/runtime.py @@ -248,6 +248,7 @@ async def publish_tick(runtime: CloneRuntime) -> EbusPanelSnapshot: evse=_evse_tick_inputs(runtime.engine.config, raw.circuits), envelope=_panel_envelope(runtime.engine.config), bess_communication=_bess_communication(runtime.engine, raw.bess_link), + bess_pv=_bess_pv(runtime.engine, raw.bess_pv_w), ) return runtime.emitter.publish_tick(tick) @@ -266,6 +267,17 @@ def _bess_communication( return {} if battery is None else {battery.instance_id: link} +def _bess_pv(engine: DynamicSimulationEngine, watts: float) -> dict[str, float]: + """A hybrid battery's own array production, keyed by the battery the engine's + config enables now. Empty for any other battery, which the emitter refuses to + give PV, and with none.""" + bess = engine.config.get("bess") or {} + if bess.get("inverter_type") != "hybrid": + return {} + battery = bess_config_from_engine(engine) + return {} if battery is None else {battery.instance_id: watts} + + async def stop_clone(runtime: CloneRuntime, *, graceful: bool = True) -> None: """Tear down, letting the loop turn before the client goes away. diff --git a/src/panelbench/emitter_adapter/spec_generator.py b/src/panelbench/emitter_adapter/spec_generator.py index 2eeeed3..7a0ed3e 100644 --- a/src/panelbench/emitter_adapter/spec_generator.py +++ b/src/panelbench/emitter_adapter/spec_generator.py @@ -347,6 +347,8 @@ def _bess_instance(profile: SimulationConfig) -> DeviceInstance | None: "nameplate-capacity-kwh": str(bess_cfg.get("nameplate_capacity_kwh", 13.5)), "relative-position": str(bess_cfg.get("relative_position", "UPSTREAM")), } + if "inverter_type" in bess_cfg: + bess_meta["inverter-type"] = str(bess_cfg["inverter_type"]) model = bess_cfg.get("model") or bess_cfg.get("product_name") if model is not None: bess_meta["model"] = str(model) diff --git a/src/panelbench/engine.py b/src/panelbench/engine.py index 11459d1..afbe1f2 100644 --- a/src/panelbench/engine.py +++ b/src/panelbench/engine.py @@ -33,6 +33,8 @@ from panelbench.inverter import template_is_hybrid if TYPE_CHECKING: + from collections.abc import Mapping + from ebus_panel_sim import BESSCommunication, BESSDevice from panelbench.config_types import ( @@ -65,6 +67,8 @@ class EngineTick: """Signed instant power per circuit, keyed by emitter instance id.""" bess_link: BESSCommunication """The requested health of the panel's link to its battery.""" + bess_pv_w: float + """What a hybrid battery's own array produces, in watts, positive; 0 for any other.""" # --------------------------------------------------------------------------- @@ -295,6 +299,11 @@ def _apply_time_of_day_modulation( return base_power * 0.3 return base_power + def solar_output_w(self, nameplate_w: float, timestamp: float) -> float: + """What an array rated *nameplate_w* produces at *timestamp*, in watts, by the + panel's location and weather, as a PV circuit's does.""" + return self._apply_solar_day_night_cycle(nameplate_w, timestamp) + def _apply_solar_day_night_cycle(self, base_power: float, current_time: float) -> float: """Apply solar day/night cycle using geographic sine model + weather.""" lat = self._config["panel_config"].get("latitude", 37.7) @@ -984,7 +993,27 @@ async def get_tick_inputs(self) -> EngineTick: grid_online=self.grid_online, circuits=circuit_powers, bess_link=self._bess_link, + bess_pv_w=self._hybrid_array_w(self._config, current_time), + ) + + def _hybrid_array_w(self, config: Mapping[str, object] | None, ts: float) -> float: + """What the hybrid battery *config* describes takes from its own array at *ts*, + in watts, positive: 0 for a battery that is off, not hybrid, or has no rated + array.""" + behavior = self._behavior_engine + bess = config.get("bess") if config is not None else None + if ( + behavior is None + or not isinstance(bess, dict) + or not bess.get("enabled") + or bess.get("inverter_type") != "hybrid" + ): + return 0.0 + array = bess.get("pv_array") + nameplate = ( + float(array.get("nameplate_capacity_w", 0.0)) if isinstance(array, dict) else 0.0 ) + return behavior.solar_output_w(nameplate, ts) if nameplate > 0 else 0.0 # ------------------------------------------------------------------ # Modeling computation @@ -1137,6 +1166,9 @@ async def compute_modeling_data(self, horizon_hours: int) -> dict[str, Any]: use_recorder_baseline=True, ) inputs_b = self._powers_to_energy_inputs(powers_b) + # A hybrid battery's own array, booked as the emitter books its PV: in the + # solar, in what the battery's dispatch sees, and off the grid. + array_b = self._hybrid_array_w(baseline_config or self._config, ts) if before_energy_system is not None: state_b = before_energy_system.tick(ts, inputs_b) pre_grid_before = state_b.grid_power_w @@ -1149,9 +1181,10 @@ async def compute_modeling_data(self, horizon_hours: int) -> dict[str, Any]: current_time=ts, grid_online=True, load_demand_w=inputs_b.load_demand_w, - pv_available_w=inputs_b.pv_available_w, + pv_available_w=inputs_b.pv_available_w + array_b, ) - grid_before = pre_grid_before - batt_before + grid_before = pre_grid_before - batt_before - array_b + pv_before += array_b # --- After pass: all current circuits --- powers_a = self._collect_circuit_powers_at_ts( @@ -1163,19 +1196,20 @@ async def compute_modeling_data(self, horizon_hours: int) -> dict[str, Any]: inputs_a = self._powers_to_energy_inputs(powers_a) state_a = after_energy_system.tick(ts, inputs_a) + array_a = self._hybrid_array_w(self._config, ts) batt_after = _bess_dispatch( after_bess, current_time=ts, grid_online=True, load_demand_w=inputs_a.load_demand_w, - pv_available_w=inputs_a.pv_available_w, + pv_available_w=inputs_a.pv_available_w + array_a, ) - grid_after = state_a.grid_power_w - batt_after + grid_after = state_a.grid_power_w - batt_after - array_a site_power_arr.append(round(grid_before, 1)) pv_before_arr.append(round(pv_before, 1)) grid_power_arr.append(round(grid_after, 1)) - pv_after_arr.append(round(state_a.pv_power_w, 1)) + pv_after_arr.append(round(state_a.pv_power_w + array_a, 1)) battery_power_arr.append(round(batt_after, 1)) battery_before_arr.append(round(batt_before, 1)) diff --git a/src/panelbench/validation.py b/src/panelbench/validation.py index 1f4730c..29b6ded 100644 --- a/src/panelbench/validation.py +++ b/src/panelbench/validation.py @@ -7,6 +7,7 @@ from __future__ import annotations import logging +import math from typing import TYPE_CHECKING, Any, Final from panelbench.breakers import breaker_misfit, crowded_spaces, crowding @@ -68,6 +69,7 @@ def validate_yaml_config(config_data: Any) -> None: validate_shared_circuits(config_data) validate_unvalued_lists(config_data) validate_downstream_lugs(config_data) + validate_battery_coupling(config_data) if "panel_source" in config_data: validate_panel_source(config_data["panel_source"]) @@ -636,6 +638,45 @@ def validate_downstream_lugs(config_data: dict[str, object]) -> None: ) +_BATTERY_INVERTER_TYPES: Final = ("ac-coupled", "hybrid") + + +def validate_battery_coupling(config_data: dict[str, object]) -> None: + """A battery's inverter type, and the array only a hybrid battery's inverter takes.""" + bess = config_data.get("bess") + if not isinstance(bess, dict): + return + inverter_type = bess.get("inverter_type", "ac-coupled") + if inverter_type not in _BATTERY_INVERTER_TYPES: + raise ValueError( + f"bess.inverter_type must be one of {', '.join(_BATTERY_INVERTER_TYPES)}, " + f"not {inverter_type!r}" + ) + if "pv_array" not in bess: + return + array = bess["pv_array"] + if inverter_type != "hybrid": + raise ValueError( + "bess.pv_array is the array a hybrid battery's own inverter takes; set " + "bess.inverter_type to hybrid, or remove it" + ) + if not isinstance(array, dict): + raise ValueError( + f"bess.pv_array must be a section naming nameplate_capacity_w, not {array!r}" + ) + nameplate = array.get("nameplate_capacity_w") + if ( + isinstance(nameplate, bool) + or not isinstance(nameplate, int | float) + or not math.isfinite(nameplate) + or nameplate < 0 + ): + raise ValueError( + "bess.pv_array.nameplate_capacity_w must be a finite number of watts, 0 or " + f"more, not {nameplate!r}" + ) + + def _listed(value: object) -> list[object]: return value if isinstance(value, list) else [] diff --git a/tests/_helpers.py b/tests/_helpers.py index e523276..29e9a5b 100644 --- a/tests/_helpers.py +++ b/tests/_helpers.py @@ -10,6 +10,8 @@ import asyncio import copy +import sqlite3 +import time from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Final @@ -29,11 +31,13 @@ recorded_panel, ) from panelbench.firmware import SPAN_RELEASE_202639, predates +from panelbench.recorder import RecorderDataSource from panelbench.reference_templates import ( template_capture_names, template_filename, write_reference_templates, ) +from panelbench.sqlite_history import SCHEMA_SQL, SqliteHistoryProvider from tests.fidelity.tree_diff import retained_topics if TYPE_CHECKING: @@ -328,3 +332,30 @@ def rehearsal_after(before: SimulationConfig, second: str) -> SimulationConfig: assert pv is not None pv["feed"] = REHEARSAL_ORIGINAL_INVERTER return config + + +async def recorder_history(tmp_path: Path, entity: str) -> RecorderDataSource: + """A recorder holding 25 hourly means of *entity*, the last a week ago, as a + panel's history database gives them.""" + db_path = tmp_path / "panel_history.db" + con = sqlite3.connect(str(db_path)) + con.executescript(SCHEMA_SQL) + con.execute( + "INSERT INTO statistics_meta (id, statistic_id, unit_of_measurement) VALUES (1, ?, 'W')", + (entity,), + ) + end = time.time() - 7 * 86400 + end -= end % 3600 + for hour in range(25): + ts = end - (24 - hour) * 3600 + mean = 100.0 + 5.0 * hour + con.execute( + "INSERT INTO statistics (metadata_id, created_ts, start_ts, mean, min, max) " + "VALUES (1, ?, ?, ?, ?, ?)", + (ts, ts, mean, mean * 0.9, mean * 1.1), + ) + con.commit() + con.close() + recorder = RecorderDataSource() + assert await recorder.load(SqliteHistoryProvider(db_path), [entity], lookback_days=365) == 1 + return recorder diff --git a/tests/fidelity/replay.py b/tests/fidelity/replay.py index e550d0f..fbc9528 100644 --- a/tests/fidelity/replay.py +++ b/tests/fidelity/replay.py @@ -83,4 +83,5 @@ def replayed( evse={drive_ids[i]: power for i, power in recorded.evse.items()}, envelope=envelope, bess_communication=links, + bess_pv={batteries[battery]: watts for battery, watts in recorded.bess_pv.items()}, ) diff --git a/tests/test_hybrid_battery.py b/tests/test_hybrid_battery.py new file mode 100644 index 0000000..01b7363 --- /dev/null +++ b/tests/test_hybrid_battery.py @@ -0,0 +1,208 @@ +"""A hybrid battery takes its own solar. + +``bess.inverter_type: hybrid`` says the battery's own inverter also takes PV, on its DC +side, and ``bess.pv_array.nameplate_capacity_w`` rates the array it takes. The engine +produces that array with the model PV circuits use, the panel's location and weather, +and hands it to the emitter as the battery's PV (``TickInputs.bess_pv``), which adds it +to ``power-flows/pv`` and to what the battery's dispatch sees. The battery is still +dispatched by the emitter. A clone reads the coupling as the emitter's capture reads it, +from what the tree publishes, and an import keeps its definition's. +""" + +from __future__ import annotations + +import copy +import random +from typing import TYPE_CHECKING, Final + +import pytest +import yaml +from ebus_panel_sim import load_reference_capture, reference_capture_names + +from panelbench.clone import translate_panel_tree +from panelbench.definition_import import config_from_definition +from panelbench.emitter_adapter import runtime as emitter_runtime +from panelbench.emitter_adapter.wire_capture import recorded_panel +from panelbench.engine import DynamicSimulationEngine +from panelbench.validation import validate_yaml_config +from tests._helpers import ( + discovered_from_tree, + panel_config, + published, + recorder_history, + write_config, +) + +if TYPE_CHECKING: + from pathlib import Path + + from panelbench.config_types import SimulationConfig + +_NOON: Final = "2026-06-15T12:00:00" +_MIDNIGHT: Final = "2026-06-15T00:00:00" +_ARRAY_W: Final = 7600.0 + +# The captures whose battery the emitter's capture writes hybrid: in each, the panel +# publishes power-flows/pv and nothing but its one battery could bring it solar. +_HYBRID_CAPTURES: Final = frozenset({"r202639-c", "r202639-f", "r202645-g"}) + + +def _hybrid(*, nameplate_w: float | None = _ARRAY_W) -> SimulationConfig: + """The working panel with its battery hybrid, its array rated *nameplate_w*.""" + config = panel_config() + bess = config["bess"] + bess["inverter_type"] = "hybrid" + if nameplate_w is not None: + bess["pv_array"] = {"nameplate_capacity_w": nameplate_w} + return config + + +async def _flows_at(tmp_path: Path, config: SimulationConfig, at: str) -> dict[str, float]: + """The panel's four power flows after one tick at simulated *at*.""" + timed = copy.deepcopy(config) + timed["simulation_params"]["use_simulation_time"] = True + timed["simulation_params"]["simulation_start_time"] = at + # The circuits' noise is drawn from `random`, and the array draws none, so two runs + # compared with each other draw the same. + random.seed(20261119) + runtime, recorder = await recorded_panel(write_config(tmp_path / "panel.yaml", timed)) + await emitter_runtime.publish_tick(runtime) + serial = config["panel_config"]["serial_number"] + return { + flow: float(published(recorder, serial, f"power-flows/{flow}")) + for flow in ("site", "grid", "pv", "battery") + } + + +@pytest.mark.asyncio +async def test_at_noon_a_hybrid_battery_s_array_joins_the_solar_flow(tmp_path: Path) -> None: + """``power-flows/pv`` is negative while producing, so the array makes it more so.""" + plain = await _flows_at(tmp_path, panel_config(), _NOON) + hybrid = await _flows_at(tmp_path, _hybrid(), _NOON) + + assert hybrid["pv"] < plain["pv"] + assert plain["pv"] - hybrid["pv"] <= _ARRAY_W + assert abs(sum(hybrid.values())) <= 1.5, hybrid + + +@pytest.mark.asyncio +async def test_at_midnight_the_array_produces_nothing(tmp_path: Path) -> None: + plain = await _flows_at(tmp_path, panel_config(), _MIDNIGHT) + hybrid = await _flows_at(tmp_path, _hybrid(), _MIDNIGHT) + + assert hybrid["pv"] == plain["pv"] + + +@pytest.mark.asyncio +async def test_a_hybrid_with_no_array_nameplate_produces_nothing(tmp_path: Path) -> None: + """As a clone writes one: a tree does not publish the array's rating.""" + plain = await _flows_at(tmp_path, panel_config(), _NOON) + hybrid = await _flows_at(tmp_path, _hybrid(nameplate_w=None), _NOON) + + assert hybrid["pv"] == plain["pv"] + + +def _raw(config: SimulationConfig) -> dict[str, object]: + """*config* as the YAML a user writes, which validation reads before any type.""" + loaded: dict[str, object] = yaml.safe_load(yaml.safe_dump(dict(config))) + return loaded + + +@pytest.mark.parametrize( + ("change", "message"), + [ + pytest.param({"inverter_type": "dc-coupled"}, r"bess\.inverter_type", id="unknown type"), + pytest.param( + {"inverter_type": "ac-coupled", "pv_array": {"nameplate_capacity_w": 5000}}, + r"bess\.pv_array", + id="an array on an ac-coupled battery", + ), + pytest.param( + {"pv_array": {"nameplate_capacity_w": 5000}}, + r"bess\.pv_array", + id="an array by default", + ), + pytest.param( + {"inverter_type": "hybrid", "pv_array": {"nameplate_capacity_w": -1}}, + r"bess\.pv_array\.nameplate_capacity_w", + id="a negative rating", + ), + pytest.param( + {"inverter_type": "hybrid", "pv_array": {"nameplate_capacity_w": "7.6 kW"}}, + r"bess\.pv_array\.nameplate_capacity_w", + id="a rating that is not a number", + ), + pytest.param( + {"inverter_type": "hybrid", "pv_array": {"nameplate_capacity_w": float("nan")}}, + r"bess\.pv_array\.nameplate_capacity_w", + id="a rating that is not finite", + ), + pytest.param( + {"inverter_type": "hybrid", "pv_array": 7600}, + r"bess\.pv_array", + id="an array that is not a section", + ), + ], +) +def test_a_battery_s_coupling_it_cannot_read_is_refused( + change: dict[str, object], message: str +) -> None: + raw = _raw(panel_config()) + bess = raw["bess"] + assert isinstance(bess, dict) + bess.update(change) + with pytest.raises(ValueError, match=message): + validate_yaml_config(raw) + + +@pytest.mark.parametrize("name", reference_capture_names()) +def test_a_clone_reads_a_battery_s_coupling_as_the_emitter_s_capture_does(name: str) -> None: + tree = load_reference_capture(name).tree + (panel,) = [i for i, d in tree.items() if d.type == "distribution-enclosure"] + config = translate_panel_tree(panel, discovered_from_tree(tree)) + bess = config.get("bess") + coupling = bess.get("inverter_type") if isinstance(bess, dict) else None + + assert (coupling == "hybrid") == (name in _HYBRID_CAPTURES), coupling + + +@pytest.mark.parametrize( + ("name", "coupling"), + [ + pytest.param("r202639-f", "hybrid", id="a definition writing it hybrid"), + pytest.param("r202639-c", None, id="a definition leaving it ac-coupled"), + ], +) +def test_an_import_keeps_its_definition_s_coupling(name: str, coupling: str | None) -> None: + """``r202639-c``'s recorded definition leaves its battery ac-coupled, though its tree + alone would be read hybrid: the definition says what the panel is.""" + config = config_from_definition(load_reference_capture(name).definition) + bess = config.get("bess") + assert isinstance(bess, dict) + assert bess.get("inverter_type") == coupling + + +@pytest.mark.asyncio +async def test_the_model_view_books_a_hybrid_battery_s_array_as_solar(tmp_path: Path) -> None: + """Its After pass gives the array to the solar trace by day, and nothing by night.""" + entity = "sensor.synthetic_circuit_power" + + async def after_pv(config: SimulationConfig, where: Path) -> list[float]: + config["circuits"][0]["recorder_entity"] = entity + engine = DynamicSimulationEngine( + config_data=config, recorder=await recorder_history(where, entity) + ) + await engine.initialize_async() + data = await engine.compute_modeling_data(24) + assert "error" not in data, data + trace: list[float] = data["pv_power_after"] + return trace + + (tmp_path / "plain").mkdir() + (tmp_path / "hybrid").mkdir() + plain = await after_pv(panel_config(), tmp_path / "plain") + hybrid = await after_pv(_hybrid(), tmp_path / "hybrid") + + assert all(h >= p for h, p in zip(hybrid, plain, strict=True)) + assert any(h > p for h, p in zip(hybrid, plain, strict=True)) + assert any(h == p for h, p in zip(hybrid, plain, strict=True)) diff --git a/tests/test_modeling_data.py b/tests/test_modeling_data.py index a8fcab3..c7c1693 100644 --- a/tests/test_modeling_data.py +++ b/tests/test_modeling_data.py @@ -9,16 +9,12 @@ from __future__ import annotations import random -import sqlite3 -import time from typing import TYPE_CHECKING, Final import pytest from panelbench.engine import DynamicSimulationEngine -from panelbench.recorder import RecorderDataSource -from panelbench.sqlite_history import SCHEMA_SQL, SqliteHistoryProvider -from tests._helpers import panel_config +from tests._helpers import panel_config, recorder_history if TYPE_CHECKING: from pathlib import Path @@ -26,40 +22,15 @@ _ENTITY: Final = "sensor.synthetic_circuit_power" -async def _history(tmp_path: Path) -> RecorderDataSource: - """A recorder holding 25 hourly means of ``_ENTITY``, the last a week ago, as a - panel's history database gives them.""" - db_path = tmp_path / "panel_history.db" - con = sqlite3.connect(str(db_path)) - con.executescript(SCHEMA_SQL) - con.execute( - "INSERT INTO statistics_meta (id, statistic_id, unit_of_measurement) VALUES (1, ?, 'W')", - (_ENTITY,), - ) - end = time.time() - 7 * 86400 - end -= end % 3600 - for hour in range(25): - ts = end - (24 - hour) * 3600 - mean = 100.0 + 5.0 * hour - con.execute( - "INSERT INTO statistics (metadata_id, created_ts, start_ts, mean, min, max) " - "VALUES (1, ?, ?, ?, ?, ?)", - (ts, ts, mean, mean * 0.9, mean * 1.1), - ) - con.commit() - con.close() - recorder = RecorderDataSource() - assert await recorder.load(SqliteHistoryProvider(db_path), [_ENTITY], lookback_days=365) == 1 - return recorder - - @pytest.mark.asyncio async def test_the_model_view_s_after_pass_is_each_circuit_s_model_and_repeats( tmp_path: Path, ) -> None: config = panel_config() config["circuits"][0]["recorder_entity"] = _ENTITY - engine = DynamicSimulationEngine(config_data=config, recorder=await _history(tmp_path)) + engine = DynamicSimulationEngine( + config_data=config, recorder=await recorder_history(tmp_path, _ENTITY) + ) await engine.initialize_async() circuits = [c["id"] for c in config["circuits"]] assert any("cycling_pattern" in engine.circuit_template(cid) for cid in circuits) From 68e6dec1211e7b556d35be95546f7a8cdfbb9fae Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:30:37 -0800 Subject: [PATCH 05/22] docs: PanelBench on ebus-panel-sim 0.11.0 The README, DEVELOPER and the add-on docs describe panel_config.feedthrough and a hybrid battery's inverter_type and pv_array, and which firmware each template reports; a config naming no firmware publishes release 202645's conventions. A MAIN 40's spaces now rest on a capture, r202645-c, whose 38 circuits sit on 9 to 48, in panel_models, the clone's comment and the changelog. Both changelogs record what 0.11.0 publishes differently, the battery's own solar and feedthrough. --- CHANGELOG.md | 16 ++++++-- DEVELOPER.md | 9 ++++- README.md | 40 +++++++++++++++++-- panelbench/CHANGELOG.md | 9 ++++- panelbench/DOCS.md | 6 +++ src/panelbench/clone.py | 4 +- .../emitter_adapter/spec_generator.py | 2 +- src/panelbench/panel_models.py | 8 ++-- 8 files changed, 78 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c86a080..531ebe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ - **Three templates of real panels**, generated from the emitter's reference captures: `ref_MAIN_32_CASCADE`, a MAIN 32 fed by another panel, with a battery; `ref_MAIN_16_BESS`, a MAIN 16 with a hybrid battery and an EVSE; and `ref_MLO_48_HYBRID`, an MLO 48 whose battery's inverter takes its solar. +- **A battery can take its own solar.** `bess.inverter_type: hybrid` (default `ac-coupled`) says the battery's own inverter also takes PV, on its DC side, and + `bess.pv_array.nameplate_capacity_w` rates the array; it produces by the panel's location and weather and joins `power-flows/pv` and the solar the battery's + dispatch sees, live and in the Model view. A clone writes a battery hybrid where the emitter's capture reads it so: the panel publishes `power-flows/pv` + and nothing but its one battery could bring it solar. An imported definition keeps its battery's coupling. +- **`panel_config.feedthrough`** (default `true`). With `false`, a hardware 3.0 panel on SPAN release 202645, or on a firmware naming none, publishes no + downstream lugs, as such a panel without a feedthrough module does; release 202639 and a MAIN 32 publish both. A clone of a panel publishing its upstream + lugs alone writes `false`, and a `lugs.downstream` section for lugs the panel does not publish is refused. ### Changed @@ -25,6 +32,10 @@ badge naming the serial. Delete the leftover `default_*` files, or clone the `ref_` equivalent. - **The README lists every template in one table**, and the conformance profile in `DEVELOPER.md` is the regenerated one: 452 match, 4 divergence, 69 extension and 1327 omission. +- **PanelBench runs on `ebus-panel-sim` 0.11.0**, which publishes some things differently, as its CHANGELOG records. The lugs' `meter/current-a` and + `meter/current-b` take each space's leg from its row and net each leg's current. On hardware 3.0 the circuits of one tandem or quad each publish the + breaker's one reading, and a relay or priority set on one over MQTT reaches them all. A battery's `info/nameplate-capacity` has one decimal place there (`27.0`). + A hardware 3.0 panel on release 202645 publishes each circuit's `connection/connection-point`. - **Four generated templates are their panels' later captures, on release 202645**: `ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48`, where they were the release 202639 captures of the same panels. `ref_MAIN_40` is that panel recommissioned, with 38 circuits and no battery, where it had 5 and a battery fed by a circuit, and `ref_UNKNOWN_16` adds an EVSE. @@ -53,9 +64,8 @@ - **`default_MAIN_16.yaml`, `default_MAIN_32.yaml` and `default_MAIN_40.yaml`**, which `ref_MAIN_16`, `ref_MAIN_32` and `ref_MAIN_40` cover. The SpanPanel integration's client, span-panel-api, places MAIN 16 at spaces 9 to 24 and MAIN 40 at 9 to 48, and `default_MAIN_16` and `default_MAIN_40` numbered their - spaces from 1, so the integration logged "Panel model ... has breaker positions ..., but its circuits occupy spaces ..." for both. The MAIN 16 range is the - one its reference capture shows, with circuits on spaces 9 to 24; the MAIN 40 range is the client's own choice, and its capture's circuits sit on spaces 9 - to 45. + spaces from 1, so the integration logged "Panel model ... has breaker positions ..., but its circuits occupy spaces ..." for both. Each range is the one a + reference capture of that model shows: a MAIN 16's circuits on spaces 9 to 24, and a MAIN 40's on 9 to 48. ## 2.8.0 — Tandem and quad breakers, and several panels on one broker diff --git a/DEVELOPER.md b/DEVELOPER.md index d991c75..95e485a 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -363,6 +363,9 @@ panel_config: ethernet_link: bool # status/ethernet wifi_ssid: str | null # status/wifi-ssid (default: sim-wifi while Wi-Fi is up); null publishes none unvalued: [str] # node/property paths the panel declares and leaves unvalued, as a clone reads them + # Whether the panel has a feedthrough module (default: true). false publishes no downstream lugs under hardware 3.0 + # from release 202645 (hardware.publishes_downstream_lugs); a clone of a panel publishing its upstream lugs alone writes it + feedthrough: bool registration_limit: # Absent, every registration succeeds per_minute: int # Registrations each client may make in a minute; past it, registration answers 429 retry_after: bool # Whether the refusal carries Retry-After (default: true) @@ -475,7 +478,7 @@ outside_meters: # A meter the panel reads that sits outside it, on no breaker sp unvalued: [str] lugs: # Each set of lugs as commissioned, published in its connection node - upstream: # downstream takes the same keys + upstream: # downstream takes the same keys, and is refused for lugs the panel does not publish (panel_config.feedthrough) feeds_role: str # What the lugs feed where it is not a device of its own service_rating_a: int # The utility service rating at a service entrance overcurrent_protection_a: int @@ -728,6 +731,10 @@ The Battery Storage Energy Equipment tracks real state-of-energy by integrating - **Discharging**: `SOE -= power * dt / discharge_efficiency` - **Backup reserve**: Normal discharge stops at `backup_reserve_pct` (default 20%); only grid-disconnect emergencies drain to the 5% hard floor - **Charge modes**: Custom (hour-based schedule), Solar Generation (tracks PV curve), Solar Excess (surplus after loads) +- **A hybrid battery's own array**: `bess.inverter_type: hybrid` (default `ac-coupled`), with `bess.pv_array.nameplate_capacity_w`, gives the battery's + inverter an array. The engine produces it with the PV circuits' solar model (`RealisticBehaviorEngine.solar_output_w`), and the runtime hands it to the + emitter as the battery's `TickInputs.bess_pv`, which the emitter adds to `power-flows/pv`, its dispatch's solar and the grid. The Model view books it the + same way. A clone takes the coupling from the emitter's own reading of the tree (`clone._hybrid_batteries`); an import keeps its definition's. ### Energy Accumulation diff --git a/README.md b/README.md index c4fc025..18a0b3e 100644 --- a/README.md +++ b/README.md @@ -433,9 +433,11 @@ leaves out. Each circuit still publishes its own reading, where a panel publishe `firmware_version` is the firmware string a panel reports over MQTT, its HTTP status endpoint and mDNS. It also decides which side of SPAN release 202639 the panel emulates: the battery's power sign, whether a SPAN Drive's user charge limit is published before a user sets one, one solar device per inverter, the -status endpoint's hardware version, and commissioned-system circuits. +status endpoint's hardware version, and commissioned-system circuits. From release 202645 a hardware 3.0 panel also publishes each circuit's +`connection/connection-point`, and one without a feedthrough publishes no downstream lugs ([A panel without a feedthrough](#a-panel-without-a-feedthrough)). -The shipped templates name `spanos3/r202639/03`, as a SPAN panel on that release publishes it, and so are panels after the upgrade to release 202639. +The two tracked templates name `spanos3/r202639/03`, as a SPAN panel on that release publishes it, and so are panels after the upgrade to release 202639; +each template of a real panel names the release it was captured on ([Templates](#templates)). `ref_MAIN_32_TANDEMS.yaml`'s solar circuit is the locked "Commissioned PV System" circuit, and it reports hardware version `1.2`. Read it with the `span-panel` integration v2.1.2 or later; v2.1.1 shows the battery's Meter Power with its sign flipped. `ref_MLO_48_TANDEMS.yaml` reports hardware version `3.0`, as the reference MLO 48 does, and has no solar circuit; read it with v2.2.0 or later, and with v2.3.0 or later for its tandem-quad to be drawn and judged correctly. @@ -447,8 +449,38 @@ remove `commissioned_system` from its solar template, which PanelBench refuses o firmware_version: spanos3/r202633/02 ``` -A config naming no firmware reports `sim/v`, which names no SPAN release, and publishes r202639's conventions. A clone keeps its source panel's -firmware. +A config naming no firmware reports `sim/v`, which names no SPAN release, and publishes the conventions of the latest release, 202645. A +clone keeps its source panel's firmware. + +### A panel without a feedthrough + +`panel_config.feedthrough` says whether the panel has a feedthrough module (default `true`). From SPAN release 202645 a hardware 3.0 panel without one +publishes its upstream lugs alone, so with `feedthrough: false` such a panel, on that release or on a firmware naming none, publishes no downstream lugs. On +release 202639 it publishes both, as panels on that release do, and a MAIN 32 publishes both whatever its feedthrough, since no capture shows one leaving them +out. A clone of a panel that publishes its upstream lugs alone writes `feedthrough: false`, and a `lugs.downstream` section for lugs the panel does not +publish is refused. + +```yaml +panel_config: + feedthrough: false +``` + +### A battery that takes its own solar + +A hybrid battery's own inverter also takes PV, on its DC side, as a Powerwall 3's does. Set `bess.inverter_type: hybrid` and rate its array with +`bess.pv_array.nameplate_capacity_w`. The array produces by the panel's location and weather, as a PV circuit does, and its production joins `power-flows/pv` +and the solar the battery's dispatch sees, live and in the Model view; the emitter still dispatches the battery. Without a rating the array produces nothing, +as a clone writes it, since a panel does not publish one. A clone writes `inverter_type: hybrid` where the emitter's capture reads the panel's battery as +hybrid: the panel publishes `power-flows/pv`, and nothing but its one battery could bring it solar. An imported definition keeps its own battery's coupling. +This `hybrid` is the battery's; a PV template's `inverter_type: hybrid` is a grid-forming inverter, which keeps producing off-grid. + +```yaml +bess: + enabled: true + inverter_type: hybrid + pv_array: + nameplate_capacity_w: 7600 +``` ## Environment Variables diff --git a/panelbench/CHANGELOG.md b/panelbench/CHANGELOG.md index 52c7b9b..fb57bc7 100644 --- a/panelbench/CHANGELOG.md +++ b/panelbench/CHANGELOG.md @@ -8,6 +8,10 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ - **`ref_MAIN_32_CASCADE`, `ref_MAIN_16_BESS` and `ref_MLO_48_HYBRID`**: a MAIN 32 fed by another panel, a MAIN 16 with a hybrid battery and an EVSE, and an MLO 48 whose battery's inverter takes its solar. +- **A battery can take its own solar**: set `bess.inverter_type: hybrid` and rate its array with `bess.pv_array.nameplate_capacity_w`, and it produces into the + panel's solar, live and in the Model view. A clone of a panel with such a battery writes it hybrid. +- **`panel_config.feedthrough: false`** for a panel without a feedthrough module: on SPAN release 202645 a hardware 3.0 one publishes no downstream lugs. A + clone writes it. ### Changed @@ -20,6 +24,8 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ integration's positions warning continues. A leftover `default_MAIN_32_TANDEMS.yaml` or `default_MLO_48_TANDEMS.yaml` keeps its `ref_` twin's serial (`sim-32t-tandems-001`, `sim-48t-tandems-001`), so running both starts one and the other shows an `error` badge naming the serial. Delete the leftover `default_*` files, or clone the `ref_` equivalent. +- **Runs on `ebus-panel-sim` 0.11.0**: the lugs' per-leg currents net each leg by the panel's rows; on hardware 3.0 a tandem's or quad's circuits each + publish the breaker's one reading and share its relay over MQTT, and a battery's nameplate capacity has one decimal place. - **`ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48` are their panels' later captures, on release 202645.** `ref_MAIN_40` now has 38 circuits and no battery, and `ref_UNKNOWN_16` an EVSE. - **A `pv` section listing `inverters` must set `enabled`, to `true` or `false`**: without it they published nothing, and a quoted `"false"` published them; @@ -35,7 +41,8 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ ### Removed - **`default_MAIN_16`, `default_MAIN_32` and `default_MAIN_40`**; use `ref_MAIN_16`, `ref_MAIN_32` and `ref_MAIN_40`. The first and last numbered their spaces - from 1, where the SpanPanel integration's client places those models at 9 to 24 and 9 to 48, so the integration warned about their breaker positions. + from 1, where the SpanPanel integration's client places those models at 9 to 24 and 9 to 48, as their reference captures show, so the integration warned + about their breaker positions. ## 2.8.0 — 2026-11-15 diff --git a/panelbench/DOCS.md b/panelbench/DOCS.md index 4c0b195..eebf4e4 100644 --- a/panelbench/DOCS.md +++ b/panelbench/DOCS.md @@ -170,6 +170,12 @@ size, circuit names, solar/battery presence, and load profiles. Or simply clone your real panel from the dashboard — no manual config needed. +A panel without a feedthrough module sets `panel_config.feedthrough: +false`, and on SPAN release 202645 a hardware 3.0 one then publishes no +downstream lugs. A battery whose own inverter takes solar, as a +Powerwall 3's does, sets `bess.inverter_type: hybrid` and rates its +array with `bess.pv_array.nameplate_capacity_w`. The README has both. + ## Full documentation Dashboard features, configuration reference, MQTT topics, and diff --git a/src/panelbench/clone.py b/src/panelbench/clone.py index 3a40d7a..fcca430 100644 --- a/src/panelbench/clone.py +++ b/src/panelbench/clone.py @@ -318,8 +318,8 @@ def translate_panel_tree( unmapped = [space for space in spaces if space not in used_tabs] outside = sorted(space for space in used_tabs if space not in spaces) if outside: - # The positions are the integration's client's, and the MAIN 40's an inference, - # so a real panel disagreeing with them is worth saying. + # The positions are the integration's client's, and only the MAIN 16's and MAIN + # 40's rest on a capture, so a real panel disagreeing with them is worth saying. _LOGGER.warning( "Panel %s reports model %s, whose spaces are %d to %d, but has circuits on %s", panel_device_id, diff --git a/src/panelbench/emitter_adapter/spec_generator.py b/src/panelbench/emitter_adapter/spec_generator.py index 7a0ed3e..4c5eceb 100644 --- a/src/panelbench/emitter_adapter/spec_generator.py +++ b/src/panelbench/emitter_adapter/spec_generator.py @@ -63,7 +63,7 @@ # What the emitter is given for a circuit whose template records that its panel # publishes no breaker rating (`breaker_rating: null`, which a clone writes). The -# emitter requires one (ebus-panel-sim 0.10.0, `manifest_physics` reads +# emitter requires one (ebus-panel-sim 0.11.0, `manifest_physics` reads # `breaker-rating-a` with `_req_float`), and the circuit lists `breaker/rating` as # unvalued, so it is never published. _UNPUBLISHED_BREAKER_RATING_A = 20.0 diff --git a/src/panelbench/panel_models.py b/src/panelbench/panel_models.py index 0763080..0ac0183 100644 --- a/src/panelbench/panel_models.py +++ b/src/panelbench/panel_models.py @@ -40,10 +40,10 @@ holds them (span-panel-api, schema-1 ``PANEL_POSITIONS_BY_MODEL``) and warns of a panel whose circuits sit outside them. -A panel publishes only which spaces are occupied, so the ranges are the client's. What -they rest on differs: MAIN_16's 9-24 is forced by its reference capture, whose 16 -circuits sit on 9 to 24; MAIN_40's 9-48 is a choice by analogy, since its capture's -circuits sit on 9 to 45, which a numbering from 6, 7, 8 or 9 all hold.""" +A panel publishes only which spaces are occupied, so the ranges are the client's. Two +rest on reference captures: MAIN_16's 9-24 on one whose 16 circuits sit on 9 to 24, +and MAIN_40's 9-48 on the release 202645 capture of a MAIN 40, whose 38 circuits sit +on 9 to 48.""" def panel_model(config: SimulationConfig) -> str: From eb247837fa18f7fe45c2eb88505d3e3def9f60c4 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:24:34 -0800 Subject: [PATCH 06/22] fix: what the emitter refuses is refused up front; a breaker switches as one; virtual devices stay unpublished Validation ends by asking the emitter: its manifest parse and, under a variant that publishes shared breakers, its rule that a breaker's circuits agree in priority, relay lock, never-backup, placement and energy seed (ebus_panel_sim.shared_hardware), on a normalised copy of the config, with each circuit named by its id. Under 0.11.0 the dashboard could otherwise save a tandem whose circuits differ, or a PV rating of 0, which then would not start. The dashboard applies a priority or relay-behaviour edit and a relay toggle on one circuit of a tandem or quad to every circuit on it, as the breaker has one relay. A circuit on no breaker space, as the dashboard adds a PV inverter or SPAN Drive, is a what-if device: the Model view models it, and it is left out of the manifest, the devices it would feed and each tick, since the emitter refuses a circuit with none and a panel with one did not start, on 0.10.0 too. A hybrid battery's PV goes only to a battery the emitter was started hybrid, and a live edit that makes a battery hybrid is not applied, so the dashboard restarts the panel instead of every tick being refused. A clone's hybrid battery, kept unrated as the Model view's Before battery, takes the live array rating there, so rating it shows no saving. The Model view tests now pin the array's amount, the energy balance and the battery's dispatch in both passes. A battery placed DOWNSTREAM of lugs the panel does not publish is refused. Off grid the array is not curtailed, as the PV circuits are not, which the emitter's dispatch is the place for; the README and changelogs say so. Stale 0.10.0 references in the fidelity provenance and round-trip reasons, the README's rehearsal text and the clone's warning are corrected. --- CHANGELOG.md | 17 +- README.md | 12 +- panelbench/CHANGELOG.md | 5 +- src/panelbench/app.py | 6 +- src/panelbench/circuit.py | 8 + src/panelbench/clone.py | 2 +- src/panelbench/dashboard/config_store.py | 24 ++- src/panelbench/dashboard/routes.py | 4 +- src/panelbench/emitter_adapter/runtime.py | 46 ++++-- .../emitter_adapter/spec_generator.py | 10 +- src/panelbench/engine.py | 31 +++- src/panelbench/panel.py | 7 +- src/panelbench/validation.py | 62 ++++++- src/panelbench/virtual_devices.py | 20 +++ tests/emitter_adapter/test_runtime.py | 6 +- .../fidelity/fixtures/upstream/PROVENANCE.md | 2 +- tests/fidelity/test_clone_round_trip.py | 12 +- tests/test_breaker_mates.py | 124 ++++++++++++++ tests/test_clone.py | 7 +- tests/test_feedthrough.py | 12 ++ tests/test_hybrid_battery.py | 156 +++++++++++++++--- tests/test_virtual_devices.py | 70 ++++++++ 22 files changed, 563 insertions(+), 80 deletions(-) create mode 100644 src/panelbench/virtual_devices.py create mode 100644 tests/test_breaker_mates.py create mode 100644 tests/test_virtual_devices.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 531ebe2..04b53d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,10 +11,12 @@ - **A battery can take its own solar.** `bess.inverter_type: hybrid` (default `ac-coupled`) says the battery's own inverter also takes PV, on its DC side, and `bess.pv_array.nameplate_capacity_w` rates the array; it produces by the panel's location and weather and joins `power-flows/pv` and the solar the battery's dispatch sees, live and in the Model view. A clone writes a battery hybrid where the emitter's capture reads it so: the panel publishes `power-flows/pv` - and nothing but its one battery could bring it solar. An imported definition keeps its battery's coupling. + and nothing but its one battery could bring it solar. An imported definition keeps its battery's coupling. A battery made hybrid while its panel runs + restarts the panel, since the emitter builds its battery at start. Off grid the array is not yet curtailed to what the load and battery can take, as the + PV circuits are not. - **`panel_config.feedthrough`** (default `true`). With `false`, a hardware 3.0 panel on SPAN release 202645, or on a firmware naming none, publishes no downstream lugs, as such a panel without a feedthrough module does; release 202639 and a MAIN 32 publish both. A clone of a panel publishing its upstream - lugs alone writes `false`, and a `lugs.downstream` section for lugs the panel does not publish is refused. + lugs alone writes `false`. A `lugs.downstream` section for lugs the panel does not publish is refused, and so is a battery placed `DOWNSTREAM` of them. ### Changed @@ -35,10 +37,15 @@ - **PanelBench runs on `ebus-panel-sim` 0.11.0**, which publishes some things differently, as its CHANGELOG records. The lugs' `meter/current-a` and `meter/current-b` take each space's leg from its row and net each leg's current. On hardware 3.0 the circuits of one tandem or quad each publish the breaker's one reading, and a relay or priority set on one over MQTT reaches them all. A battery's `info/nameplate-capacity` has one decimal place there (`27.0`). - A hardware 3.0 panel on release 202645 publishes each circuit's `connection/connection-point`. + A hardware 3.0 panel on release 202645, or on a firmware naming none, publishes each circuit's `connection/connection-point`. +- **A config the emitter would refuse is refused when PanelBench loads, edits or saves it**, with the emitter's reason and each circuit named by its `id`. + Under 0.11.0 that includes the circuits of one tandem or quad differing in priority, relay lock, never-backup or energy seed, and a PV rating that is not + above 0, both of which 0.10.0 started on. The dashboard applies a relay toggle, or a priority or relay-behaviour edit, on one circuit of a tandem or quad + to every circuit on it, since the breaker has one relay. - **Four generated templates are their panels' later captures, on release 202645**: `ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48`, where they were the release 202639 captures of the same panels. `ref_MAIN_40` is that panel recommissioned, with 38 circuits and no battery, where it had 5 and - a battery fed by a circuit, and `ref_UNKNOWN_16` adds an EVSE. + a battery fed by a circuit, and `ref_UNKNOWN_16` adds an EVSE. Their serials follow the captures: `sim-main32_r202645`, `sim-r202645-a`, `sim-r202645-c` and + `sim-r202645-e`, where they were `sim-main32_r202639`, `sim-r202639-a`, `sim-r202639-c` and `sim-r202639-e`. - **A `pv` section listing `inverters` must set `enabled`, and `pv.enabled` must be `true` or `false`.** The inverters no circuit feeds publish only while `pv.enabled` is `true`, and a config listing them without it loaded and published none of them; it is now refused, saying to set `enabled` to `true` to publish them or `false` to keep them off. An `enabled` that is empty or quoted, such as `"false"`, which published the opposite of what it says, is refused @@ -56,6 +63,8 @@ generated `ref_` templates, clones, history databases, and `configs/.secrets/` and `configs/rates/`, which hold credentials and API keys. `.dockerignore` now keeps all but the presets and the two tracked templates out, as a build from git has it, and leaves local state and caches out of the build context; images built by CI were not affected. +- **A PV inverter or SPAN Drive added in the dashboard no longer stops its panel starting.** It sits on no breaker space, and the emitter refuses a circuit + with none, so a panel with one would not start; it is now a what-if device, which the Model view models and the panel does not publish. - **A cycling load reads the same at a given simulated time on every run.** Its on and off phases follow the panel's clock, counted from the epoch, where they ran from the moment the panel started on the real clock. A panel set to a simulated time could read a cycling load on in one run and off in the next, and a panel no longer starts every cycling load at the start of its on phase. diff --git a/README.md b/README.md index 18a0b3e..f680401 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Each panel has a unique serial number, so there is no conflict between the auto- ## Rehearsing a SPAN firmware upgrade A SPAN panel reads its firmware once, when it starts, and an over-the-air upgrade takes it offline and brings it back reporting the new release. PanelBench -rehearses an upgrade the same way: two configs for one panel, run one after the other. The upgrade rehearsed here is to SPAN release 202639. The shipped +rehearses an upgrade the same way: two configs for one panel, run one after the other. The upgrade rehearsed here is to SPAN release 202639. The tracked templates name `spanos3/r202639/03` (see [Firmware Version](#firmware-version)) and so are panels after it, which is why the first config names an earlier release. @@ -292,6 +292,9 @@ The dashboard adds one PV circuit per panel, and a panel has one battery. A pane config's YAML, as [Rehearsing a SPAN firmware upgrade](#rehearsing-a-span-firmware-upgrade) shows. Recorder-sourced entities preserve their original panel settings (priority, relay behavior) as read-only. +A PV inverter or SPAN Drive the dashboard adds sits on no breaker space: it is a what-if device, which the Model view models and the panel does not publish, +since a panel publishes only the circuits on its spaces. Give it spaces in the config's YAML to publish it. + ### Relay Control and Load Shedding - Click status dots to toggle circuit relays @@ -416,6 +419,9 @@ two `_TANDEMS` templates show one each: 15-20" on space 32 past its 15 A to 24 A, well under the 35 A its two breakers carry. - **MAIN 16, MLO 24, MAIN 40 and MLO 48** publish one circuit per protected circuit, each with its own rating, and name each other in `meter/` and `switch/shared-with-device-ids`, which a circuit's `shared_with` sets. A single-pole circuit lists its own space and a two-pole circuit lists both. + The circuits of one breaker share its one reading and relay: each publishes the breaker's reading, and a relay or priority set on one over MQTT reaches them + all. In the dashboard a relay toggle, or an edit of the priority or relay behaviour, on one applies to every circuit on the breaker, and a config whose + circuits on one breaker differ in priority, relay lock, never-backup or energy seed is refused, as the emitter refuses it. `ref_MLO_48_TANDEMS.yaml` is the reference MLO 48 with synthetic names and loads. It keeps that panel's three tandems and adds a 15-20 tandem on space 37, a quad on 27 and 29, and a tandem-quad on 31 and 33. @@ -472,7 +478,9 @@ A hybrid battery's own inverter also takes PV, on its DC side, as a Powerwall 3' and the solar the battery's dispatch sees, live and in the Model view; the emitter still dispatches the battery. Without a rating the array produces nothing, as a clone writes it, since a panel does not publish one. A clone writes `inverter_type: hybrid` where the emitter's capture reads the panel's battery as hybrid: the panel publishes `power-flows/pv`, and nothing but its one battery could bring it solar. An imported definition keeps its own battery's coupling. -This `hybrid` is the battery's; a PV template's `inverter_type: hybrid` is a grid-forming inverter, which keeps producing off-grid. +This `hybrid` is the battery's; a PV template's `inverter_type: hybrid` is a grid-forming inverter, which keeps producing off-grid. Off grid the array is not +yet curtailed to what the panel's load and the battery can take, as PanelBench's PV circuits are not: the emitter's dispatch, which sees the load after +shedding, is where that belongs. ```yaml bess: diff --git a/panelbench/CHANGELOG.md b/panelbench/CHANGELOG.md index fb57bc7..b833ccc 100644 --- a/panelbench/CHANGELOG.md +++ b/panelbench/CHANGELOG.md @@ -9,7 +9,7 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ - **`ref_MAIN_32_CASCADE`, `ref_MAIN_16_BESS` and `ref_MLO_48_HYBRID`**: a MAIN 32 fed by another panel, a MAIN 16 with a hybrid battery and an EVSE, and an MLO 48 whose battery's inverter takes its solar. - **A battery can take its own solar**: set `bess.inverter_type: hybrid` and rate its array with `bess.pv_array.nameplate_capacity_w`, and it produces into the - panel's solar, live and in the Model view. A clone of a panel with such a battery writes it hybrid. + panel's solar, live and in the Model view. A clone of a panel with such a battery writes it hybrid. Making a battery hybrid restarts its panel. - **`panel_config.feedthrough: false`** for a panel without a feedthrough module: on SPAN release 202645 a hardware 3.0 one publishes no downstream lugs. A clone writes it. @@ -26,6 +26,8 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ `default_*` files, or clone the `ref_` equivalent. - **Runs on `ebus-panel-sim` 0.11.0**: the lugs' per-leg currents net each leg by the panel's rows; on hardware 3.0 a tandem's or quad's circuits each publish the breaker's one reading and share its relay over MQTT, and a battery's nameplate capacity has one decimal place. +- **The dashboard switches and edits a tandem or quad as one breaker**: a relay toggle, or a priority or relay-behaviour change, on one of its circuits + applies to all of them, and a config the emitter would refuse, such as a PV rating of 0, is refused with its reason when edited or loaded. - **`ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48` are their panels' later captures, on release 202645.** `ref_MAIN_40` now has 38 circuits and no battery, and `ref_UNKNOWN_16` an EVSE. - **A `pv` section listing `inverters` must set `enabled`, to `true` or `false`**: without it they published nothing, and a quoted `"false"` published them; @@ -37,6 +39,7 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ warned about its breaker positions. - **A cycling load, such as a pool pump or a dryer, reads the same at a given simulated time on every run**, where it could read on in one run and off in the next. +- **A PV inverter or SPAN Drive added in the dashboard no longer stops the panel starting**: it is modelled in the Model view and not published. ### Removed diff --git a/src/panelbench/app.py b/src/panelbench/app.py index 017ecfb..cc2b9aa 100644 --- a/src/panelbench/app.py +++ b/src/panelbench/app.py @@ -223,13 +223,13 @@ def apply_bess_config_live(self, filename: str, bess_yaml: BESSConfigYAML) -> bo """Apply a fresh BESS config to the running panel for ``filename`` without restarting it. SOC/SOE persists across the swap. Refreshes the cached config hash so the reload watcher doesn't see the on-disk YAML change as - a restart trigger. Returns True when applied, False when no panel matches.""" + a restart trigger. Returns True when applied, False when no panel matches + or the change needs a restart, which the caller then makes.""" for path, panel in self._panels.items(): if path.name != filename: continue - if panel.runtime is None: + if panel.runtime is None or not panel.update_bess_config(bess_yaml): return False - panel.update_bess_config(bess_yaml) # Refresh the cached hash so the reload watcher sees the file as # already-current. self._config_hashes[path] = _file_hash(path) diff --git a/src/panelbench/circuit.py b/src/panelbench/circuit.py index a1c9a13..ca8da38 100644 --- a/src/panelbench/circuit.py +++ b/src/panelbench/circuit.py @@ -11,6 +11,8 @@ from copy import deepcopy from typing import TYPE_CHECKING +from panelbench.virtual_devices import on_the_panel + if TYPE_CHECKING: from panelbench.config_types import ( CircuitDefinitionExtended, @@ -166,6 +168,12 @@ def consumed_energy_wh(self) -> float: def tabs(self) -> list[int]: return self._circuit_def.get("tabs", []) + @property + def on_the_panel(self) -> bool: + """Whether this circuit sits on a breaker space, and so is published; a virtual + device is modelled alone (``virtual_devices``).""" + return on_the_panel(self._circuit_def) + @property def template_name(self) -> str: return str(self._circuit_def["template"]) diff --git a/src/panelbench/clone.py b/src/panelbench/clone.py index fcca430..b74f658 100644 --- a/src/panelbench/clone.py +++ b/src/panelbench/clone.py @@ -1198,7 +1198,7 @@ def _emitter_reading( # unreadable to it as a malformed tree. _LOGGER.warning( "The emitter cannot read panel %s as a definition (%s); cloning it without " - "the properties it leaves unvalued", + "the properties it leaves unvalued, and its battery as ac-coupled", panel_device_id, exc, ) diff --git a/src/panelbench/dashboard/config_store.py b/src/panelbench/dashboard/config_store.py index da67483..fdaa500 100644 --- a/src/panelbench/dashboard/config_store.py +++ b/src/panelbench/dashboard/config_store.py @@ -423,6 +423,14 @@ def _find_circuit(self, entity_id: str) -> dict[str, Any] | None: return circ return None + def get_breaker_mates(self, entity_id: str) -> list[str]: + """The other circuits on *entity_id*'s breaker, by id: those it names in + ``shared_with``, which a tandem's or quad's circuits share one relay with.""" + circuit = self._find_circuit(entity_id) + if circuit is None: + raise KeyError(f"Entity not found: {entity_id}") + return [str(mate) for mate in circuit.get("shared_with") or []] + def _mark_user_modified(self, template_name: str) -> None: """Flag a template as user-modified so recorder replay is bypassed.""" template = self._templates().get(template_name) @@ -615,10 +623,18 @@ def update_entity(self, entity_id: str, data: dict[str, Any]) -> None: # following" was not expressible at all. if "inverter_type" in data: template["inverter_type"] = normalise_inverter_type(str(data["inverter_type"])) - if "priority" in data: - template["priority"] = data["priority"] - if "relay_behavior" in data: - template["relay_behavior"] = data["relay_behavior"] + # A breaker's circuits share one relay and one priority, so an edit to either + # is the breaker's: every circuit on it takes it, through its own template. + breaker_edits = {key: data[key] for key in ("priority", "relay_behavior") if key in data} + breaker_templates = [template_name] + [ + mate["template"] + for mate_id in self.get_breaker_mates(entity_id) + if (mate := self._find_circuit(mate_id)) is not None + ] + for name in dict.fromkeys(breaker_templates): + self._templates().get(name, {}).update(breaker_edits) + if breaker_edits and name != template_name and data.get("_dirty"): + self._mark_user_modified(name) overrides: dict[str, Any] = circuit.get("overrides", {}) ep = template.get("energy_profile", {}) diff --git a/src/panelbench/dashboard/routes.py b/src/panelbench/dashboard/routes.py index 0831f82..c64cf40 100644 --- a/src/panelbench/dashboard/routes.py +++ b/src/panelbench/dashboard/routes.py @@ -1458,7 +1458,9 @@ async def handle_set_relay(request: web.Request) -> web.Response: ) ) ctx = _ctx(request) - ctx.set_circuit_relay(entity_id, relay_state) + # A tandem's or quad's circuits sit behind one relay, so the breaker switches whole. + for circuit_id in [entity_id, *_store(request).get_breaker_mates(entity_id)]: + ctx.set_circuit_relay(circuit_id, relay_state) return web.json_response({"ok": True, "relay_state": relay_state}) diff --git a/src/panelbench/emitter_adapter/runtime.py b/src/panelbench/emitter_adapter/runtime.py index 3aca9d8..4508059 100644 --- a/src/panelbench/emitter_adapter/runtime.py +++ b/src/panelbench/emitter_adapter/runtime.py @@ -41,6 +41,7 @@ stable_circuit_uuid, ) from panelbench.emitter_adapter.transport import LoopBoundTransport +from panelbench.virtual_devices import on_the_panel if TYPE_CHECKING: from panelbench.config_types import ( @@ -87,18 +88,35 @@ def bess_config_from_engine(engine: DynamicSimulationEngine) -> BESSConfig | Non return bess_config(engine.serial_number, engine.config.get("bess") or {}) -def update_bess_config_live(runtime: CloneRuntime, bess_yaml: BESSConfigYAML) -> None: - """Apply a fresh BESS config to a running emitter without restart. +def update_bess_config_live(runtime: CloneRuntime, bess_yaml: BESSConfigYAML) -> bool: + """Apply a fresh BESS config to a running emitter without restart, or say it + cannot be. Mutates the engine's loaded config so subsequent reads see the new values, rebuilds the emitter-side ``BESSConfig`` from the YAML, and swaps it on the emitter (SOC/SOE state is preserved across the swap). + + Returns False, changing nothing, for a battery the change makes hybrid that the + emitter did not start hybrid: it builds its battery at start and refuses PV for + one it was not, so the panel must restart on the saved config instead. """ + makes_hybrid = bool(bess_yaml.get("enabled")) and bess_yaml.get("inverter_type") == "hybrid" + if makes_hybrid and not _hybrid_batteries(runtime.manifest): + return False runtime.engine.config["bess"] = bess_yaml new_cfg = bess_config_from_engine(runtime.engine) - if new_cfg is None: - return - runtime.emitter.update_bess_config(new_cfg) + if new_cfg is not None: + runtime.emitter.update_bess_config(new_cfg) + return True + + +def _hybrid_batteries(manifest: DeviceManifest) -> set[str]: + """The batteries the emitter was started with that it takes PV for.""" + return { + battery.instance_id + for battery in manifest.of_class("bess") + if battery.metadata.get("inverter-type") == "hybrid" + } def _resolve_broker( @@ -248,7 +266,7 @@ async def publish_tick(runtime: CloneRuntime) -> EbusPanelSnapshot: evse=_evse_tick_inputs(runtime.engine.config, raw.circuits), envelope=_panel_envelope(runtime.engine.config), bess_communication=_bess_communication(runtime.engine, raw.bess_link), - bess_pv=_bess_pv(runtime.engine, raw.bess_pv_w), + bess_pv=_bess_pv(runtime, raw.bess_pv_w), ) return runtime.emitter.publish_tick(tick) @@ -267,15 +285,15 @@ def _bess_communication( return {} if battery is None else {battery.instance_id: link} -def _bess_pv(engine: DynamicSimulationEngine, watts: float) -> dict[str, float]: +def _bess_pv(runtime: CloneRuntime, watts: float) -> dict[str, float]: """A hybrid battery's own array production, keyed by the battery the engine's - config enables now. Empty for any other battery, which the emitter refuses to - give PV, and with none.""" - bess = engine.config.get("bess") or {} - if bess.get("inverter_type") != "hybrid": + config enables now, where the emitter started that battery hybrid. Empty for any + other, which the emitter refuses to give PV, and with none. The engine produces + nothing for a battery its config does not make hybrid.""" + battery = bess_config_from_engine(runtime.engine) + if battery is None or battery.instance_id not in _hybrid_batteries(runtime.manifest): return {} - battery = bess_config_from_engine(engine) - return {} if battery is None else {battery.instance_id: watts} + return {battery.instance_id: watts} async def stop_clone(runtime: CloneRuntime, *, graceful: bool = True) -> None: @@ -367,7 +385,7 @@ def _feeds_for_device_type(config: SimulationConfig, device_type: str) -> list[s panel_id = config["panel_config"]["serial_number"] feeds: list[str] = [] for item in circuits: - if not isinstance(item, dict): + if not isinstance(item, dict) or not on_the_panel(item): continue template_name = item.get("template") if template_name is None or not isinstance(template_name, str): diff --git a/src/panelbench/emitter_adapter/spec_generator.py b/src/panelbench/emitter_adapter/spec_generator.py index 4c5eceb..3cdcba4 100644 --- a/src/panelbench/emitter_adapter/spec_generator.py +++ b/src/panelbench/emitter_adapter/spec_generator.py @@ -41,6 +41,7 @@ ) from panelbench.panel_models import DEFAULT_PANEL_SIZE, panel_model from panelbench.pv_section import UNFED_INVERTER_POSITION, bound_pv_circuit_id, unfed_inverters +from panelbench.virtual_devices import on_the_panel if TYPE_CHECKING: from collections.abc import Mapping @@ -204,7 +205,8 @@ def _circuit_instances(profile: SimulationConfig) -> list[DeviceInstance]: panel_id = profile["panel_config"]["serial_number"] named_by_id = not predates(panel_firmware_version(profile), SPAN_RELEASE_202639) instances: list[DeviceInstance] = [] - for idx, c in enumerate(profile.get("circuits") or [], start=1): + published = [c for c in profile.get("circuits") or [] if on_the_panel(c)] + for idx, c in enumerate(published, start=1): tabs = c.get("tabs") or [0] template_name = c.get("template", "") template: CircuitTemplateExtended | None = templates.get(template_name) @@ -845,7 +847,11 @@ def _circuits_for_device_type( circuits: list[CircuitDefinitionExtended] = [] for circuit in profile.get("circuits") or []: template = templates.get(circuit.get("template", "")) - if template is not None and template.get("device_type") == device_type: + if ( + template is not None + and template.get("device_type") == device_type + and on_the_panel(circuit) + ): circuits.append(circuit) return circuits diff --git a/src/panelbench/engine.py b/src/panelbench/engine.py index afbe1f2..daa7dd5 100644 --- a/src/panelbench/engine.py +++ b/src/panelbench/engine.py @@ -984,6 +984,10 @@ async def get_tick_inputs(self) -> EngineTick: panel_id = self.serial_number circuit_powers: dict[str, float] = {} for cid, circuit in self._circuits.items(): + # A virtual device is modelled but never published, so the emitter has no + # circuit to give its power to (`virtual_devices`). + if not circuit.on_the_panel: + continue mag = circuit.instant_power_w signed = -mag if circuit.energy_mode == "producer" else mag circuit_powers[stable_circuit_uuid(panel_id, cid)] = signed @@ -996,6 +1000,31 @@ async def get_tick_inputs(self) -> EngineTick: bess_pv_w=self._hybrid_array_w(self._config, current_time), ) + def _baseline_array_config( + self, baseline: Mapping[str, object] | None + ) -> Mapping[str, object] | None: + """The config the Before pass takes a hybrid battery's array from. + + The baseline's, or the live config's where there is none. A clone writes a + hybrid battery with no array rating, since a panel publishes none, so where + the baseline's hybrid battery has none and the live one is rated, rating it + filled in what the panel has: the Before pass takes the live rating too. + """ + if not baseline: + return self._config + bess = baseline.get("bess") + live = self._config.get("bess") if self._config else None + if ( + isinstance(bess, dict) + and bess.get("inverter_type") == "hybrid" + and "pv_array" not in bess + and isinstance(live, dict) + and live.get("inverter_type") == "hybrid" + and "pv_array" in live + ): + return {**baseline, "bess": {**bess, "pv_array": live["pv_array"]}} + return baseline + def _hybrid_array_w(self, config: Mapping[str, object] | None, ts: float) -> float: """What the hybrid battery *config* describes takes from its own array at *ts*, in watts, positive: 0 for a battery that is off, not hybrid, or has no rated @@ -1168,7 +1197,7 @@ async def compute_modeling_data(self, horizon_hours: int) -> dict[str, Any]: inputs_b = self._powers_to_energy_inputs(powers_b) # A hybrid battery's own array, booked as the emitter books its PV: in the # solar, in what the battery's dispatch sees, and off the grid. - array_b = self._hybrid_array_w(baseline_config or self._config, ts) + array_b = self._hybrid_array_w(self._baseline_array_config(baseline_config), ts) if before_energy_system is not None: state_b = before_energy_system.tick(ts, inputs_b) pre_grid_before = state_b.grid_power_w diff --git a/src/panelbench/panel.py b/src/panelbench/panel.py index 66d74b7..a68e948 100644 --- a/src/panelbench/panel.py +++ b/src/panelbench/panel.py @@ -212,14 +212,15 @@ def get_power_summary(self) -> dict[str, Any] | None: summary["consumption_w"] = round(snap.power_flows.site or 0.0, 1) return summary - def update_bess_config(self, bess_yaml: BESSConfigYAML) -> None: + def update_bess_config(self, bess_yaml: BESSConfigYAML) -> bool: """Apply a fresh BESS configuration mid-run (e.g. dashboard edit). The emitter's BESSDevice swaps configs; SOC/SOE state persists across the - swap, the change takes effect on the next published tick.""" + swap, the change takes effect on the next published tick. False when the + change needs a restart instead (``update_bess_config_live``).""" if self._runtime is None: msg = "Panel not initialised — call start() first" raise RuntimeError(msg) - emitter_runtime.update_bess_config_live(self._runtime, bess_yaml) + return emitter_runtime.update_bess_config_live(self._runtime, bess_yaml) async def start(self, *, running: Mapping[str, Path] | None = None) -> str: """Load the config, connect, publish the first tick and start ticking. diff --git a/src/panelbench/validation.py b/src/panelbench/validation.py index 29b6ded..d102196 100644 --- a/src/panelbench/validation.py +++ b/src/panelbench/validation.py @@ -6,11 +6,17 @@ from __future__ import annotations +import copy import logging import math -from typing import TYPE_CHECKING, Any, Final +from typing import TYPE_CHECKING, Any, Final, cast + +from ebus_panel_sim import EmitterError +from ebus_panel_sim.manifest_physics import ManifestPhysicsView +from ebus_panel_sim.shared_hardware import shared_breakers from panelbench.breakers import breaker_misfit, crowded_spaces, crowding +from panelbench.config_defaults import normalize_config from panelbench.config_types import PVInverterYAML from panelbench.const import SHED_PRIORITIES from panelbench.emitter_adapter.spec_generator import relay_locked @@ -34,6 +40,8 @@ from ebus_panel_sim import Variant + from panelbench.config_types import SimulationConfig + _LOGGER = logging.getLogger(__name__) @@ -70,6 +78,8 @@ def validate_yaml_config(config_data: Any) -> None: validate_unvalued_lists(config_data) validate_downstream_lugs(config_data) validate_battery_coupling(config_data) + # Every check above has established the shape a SimulationConfig has. + validate_emitter_accepts(cast("SimulationConfig", config_data)) if "panel_source" in config_data: validate_panel_source(config_data["panel_source"]) @@ -621,16 +631,25 @@ def section(where: str, value: object, *keys: str) -> None: def validate_downstream_lugs(config_data: dict[str, object]) -> None: - """Refuse commissioning for downstream lugs the panel does not publish. + """Refuse what hangs from downstream lugs the panel does not publish. A hardware 3.0 panel with ``feedthrough: false`` publishes none from release - 202645, so a ``lugs.downstream`` section would describe nothing; on an earlier - release it still describes the downstream lugs that release publishes. + 202645, so a ``lugs.downstream`` section would describe nothing, and a battery + placed ``DOWNSTREAM`` would hang from no lugs; on an earlier release both still + describe the downstream lugs that release publishes. """ - lugs = config_data.get("lugs") - if not isinstance(lugs, dict) or "downstream" not in lugs: + if publishes_downstream_lugs(config_data): return - if not publishes_downstream_lugs(config_data): + bess = config_data.get("bess") + if isinstance(bess, dict) and bess.get("relative_position") == "DOWNSTREAM": + raise ValueError( + "bess.relative_position DOWNSTREAM places the battery past downstream lugs this " + "panel does not publish: from SPAN release 202645 a hardware 3.0 panel with " + "panel_config.feedthrough false has none. Place it UPSTREAM or IN_PANEL, or set " + "feedthrough to true." + ) + lugs = config_data.get("lugs") + if isinstance(lugs, dict) and "downstream" in lugs: raise ValueError( "lugs.downstream commissions downstream lugs this panel does not publish: " "from SPAN release 202645 a hardware 3.0 panel with panel_config.feedthrough " @@ -677,6 +696,35 @@ def validate_battery_coupling(config_data: dict[str, object]) -> None: ) +def validate_emitter_accepts(config_data: SimulationConfig) -> None: + """Refuse a config whose definition the emitter refuses, with the emitter's reason. + + PanelBench's own rules say why in its terms. This asks the emitter's: its parse of + the manifest, and, under a variant that publishes shared breakers, its rule that a + breaker's circuits agree in priority, relay lock, never-backup, placement and + energy seed (``ebus_panel_sim.shared_hardware``). So a config PanelBench accepts + is one the panel starts on, and the dashboard refuses an edit the emitter would. + The definition is built from a normalised copy, as the engine builds it, and the + reason names each circuit by its config ``id``. + """ + from panelbench.emitter_adapter.definition import build_definition + from panelbench.emitter_adapter.instance_ids import stable_circuit_uuid + + config: SimulationConfig = copy.deepcopy(config_data) + normalize_config(config, source="validation") + definition = build_definition(config) + try: + view = ManifestPhysicsView(definition.manifest) + if publishes_shared_breakers(definition.variant): + shared_breakers(view.all_circuits()) + except EmitterError as exc: + reason = str(exc) + serial = config["panel_config"]["serial_number"] + for circuit in config.get("circuits") or []: + reason = reason.replace(stable_circuit_uuid(serial, circuit["id"]), circuit["id"]) + raise ValueError(f"The emitter refuses this panel: {reason}") from exc + + def _listed(value: object) -> list[object]: return value if isinstance(value, list) else [] diff --git a/src/panelbench/virtual_devices.py b/src/panelbench/virtual_devices.py new file mode 100644 index 0000000..403ae91 --- /dev/null +++ b/src/panelbench/virtual_devices.py @@ -0,0 +1,20 @@ +"""A circuit on no breaker space is a virtual device: modelled, never published. + +The dashboard adds a PV inverter or a SPAN Drive as a circuit with no spaces for a what-if +(validation allows one for a ``pv`` or ``evse`` template alone). The Model view models it, +but a panel publishes only the circuits on its spaces, and the emitter refuses a circuit +with none, so it is left out of all the emitter is handed: the manifest's circuits, the +devices they feed, and each tick's circuit powers and SPAN Drive readings. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping + + +def on_the_panel(circuit: Mapping[str, object]) -> bool: + """Whether *circuit* sits on a breaker space, and so is published.""" + return bool(circuit.get("tabs")) diff --git a/tests/emitter_adapter/test_runtime.py b/tests/emitter_adapter/test_runtime.py index 083f582..7a96b8f 100644 --- a/tests/emitter_adapter/test_runtime.py +++ b/tests/emitter_adapter/test_runtime.py @@ -99,9 +99,9 @@ def test_evse_tick_inputs_include_each_evse_feed() -> None: "lighting": {}, }, "circuits": [ - {"id": "span_drive_garage", "template": "span_drive"}, - {"id": "span_drive_driveway", "template": "span_drive"}, - {"id": "kitchen", "template": "lighting"}, + {"id": "span_drive_garage", "template": "span_drive", "tabs": [1, 3]}, + {"id": "span_drive_driveway", "template": "span_drive", "tabs": [5, 7]}, + {"id": "kitchen", "template": "lighting", "tabs": [2]}, ], } circuit_powers = { diff --git a/tests/fidelity/fixtures/upstream/PROVENANCE.md b/tests/fidelity/fixtures/upstream/PROVENANCE.md index 5e313ed..6490117 100644 --- a/tests/fidelity/fixtures/upstream/PROVENANCE.md +++ b/tests/fidelity/fixtures/upstream/PROVENANCE.md @@ -9,7 +9,7 @@ cell: a panel definition and the ticks that drive it. | `forty_tab_minimal.ticks.yaml` | `examples/forty_tab_minimal.ticks.yaml` | - **Repository:** `electrification-bus/distribution-enclosure-simulator` -- **Release:** `v0.10.0`, the version `pyproject.toml` pins (commit `33ae6456a005598b2d297fbafb943a1af231fa83`) +- **Release:** `v0.11.0`, the version `pyproject.toml` pins (commit `aef75165055ae9b6450a00acaf48a7d80d2926e9`) ## Why only these diff --git a/tests/fidelity/test_clone_round_trip.py b/tests/fidelity/test_clone_round_trip.py index 7c506ed..1336c7e 100644 --- a/tests/fidelity/test_clone_round_trip.py +++ b/tests/fidelity/test_clone_round_trip.py @@ -292,7 +292,7 @@ def _pcs_fixed(d: Difference) -> bool: UPSTREAM: dict[str, tuple[str, Callable[[Difference], bool]]] = { "one voltage for both legs": ( - "ebus-panel-sim 0.10.0 publishes one per-leg voltage on both legs, so a clone " + "ebus-panel-sim 0.11.0 publishes one per-leg voltage on both legs, so a clone " "carries the legs' mean, published to the panel's one decimal", lambda d: ( _is(d, _PANEL, "value meter/voltage-a", "121.8", "122.0") @@ -300,7 +300,7 @@ def _pcs_fixed(d: Difference) -> bool: ), ), "the shed policy is fixed": ( - "ebus-panel-sim 0.10.0 publishes a fixed soc-priority policy unless one is set over " + "ebus-panel-sim 0.11.0 publishes a fixed soc-priority policy unless one is set over " "MQTT; the manifest's shed threshold does not reach it, and LoadSheddingConfig has no " "field for the release threshold (51 here)", lambda d: ( @@ -308,19 +308,19 @@ def _pcs_fixed(d: Difference) -> bool: ), ), "the PCS settings are fixed": ( - "ebus-panel-sim 0.10.0 publishes its own value for these six PCS properties, whatever " + "ebus-panel-sim 0.11.0 publishes its own value for these six PCS properties, whatever " "the panel's", _pcs_fixed, ), "a commissioned circuit's relay requester": ( - "ebus-panel-sim 0.10.0 reports CONFIGURATION for a locked relay; SPAN reports PCS for " + "ebus-panel-sim 0.11.0 reports CONFIGURATION for a locked relay; SPAN reports PCS for " "the commissioned PV circuit (filed upstream as #66)", lambda d: _is( d, _COMMISSIONED_PV_CIRCUIT, "value switch/relay-requester", "PCS", "CONFIGURATION" ), ), "the MID's grid state is derived": ( - "ebus-panel-sim 0.10.0 derives the MID's grid-state from the tick (UP); the captured " + "ebus-panel-sim 0.11.0 derives the MID's grid-state from the tick (UP); the captured " "panel's MID publishes UNKNOWN", lambda d: ( d.role.startswith("mid of ") @@ -328,7 +328,7 @@ def _pcs_fixed(d: Difference) -> bool: ), ), "connection/count is not published": ( - "ebus-panel-sim 0.10.0's profiles do not declare connection/count", + "ebus-panel-sim 0.11.0's profiles do not declare connection/count", lambda d: ( (_on_a_circuit(d) or d.role.startswith("lugs ")) and d.where == "declaration connection/count" diff --git a/tests/test_breaker_mates.py b/tests/test_breaker_mates.py new file mode 100644 index 0000000..969fdf9 --- /dev/null +++ b/tests/test_breaker_mates.py @@ -0,0 +1,124 @@ +"""A breaker's circuits are one breaker: a config PanelBench accepts is one the panel runs. + +Under a variant that publishes shared breakers, a tandem's or quad's circuits sit behind +one meter, one relay and one position, so the emitter refuses circuits on one breaker +that differ in priority, relay lock, never-backup or energy seed, as it refuses a PV +rating that is not above 0. PanelBench validates a config by the emitter's own rules +before anything runs it, naming circuits by their config ids, and the dashboard edits +and toggles a breaker as one. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Final + +import pytest +import yaml +from aiohttp.test_utils import TestClient, TestServer + +from panelbench.dashboard import DashboardContext, create_dashboard_app +from panelbench.dashboard.config_store import ConfigStore +from panelbench.validation import validate_yaml_config +from tests._helpers import CONFIGS + +if TYPE_CHECKING: + from pathlib import Path + +_TANDEMS: Final = CONFIGS / "ref_MLO_48_TANDEMS.yaml" +_MATE: Final = "circuit_37" +_OTHER_MATE: Final = "circuit_37_2" + + +def _raw(path: Path) -> dict[str, object]: + loaded: dict[str, object] = yaml.safe_load(path.read_text(encoding="utf-8")) + return loaded + + +def _on_its_own_template(config: dict[str, object], circuit_id: str, **fields: object) -> None: + """Move *circuit_id* onto a copy of its template, with *fields* changed.""" + circuits = config["circuits"] + templates = config["circuit_templates"] + assert isinstance(circuits, list) + assert isinstance(templates, dict) + (circuit,) = [c for c in circuits if c["id"] == circuit_id] + own = dict(templates[circuit["template"]]) + own.update(fields) + templates[f"{circuit_id}_own"] = own + circuit["template"] = f"{circuit_id}_own" + + +@pytest.mark.parametrize( + ("fields", "what"), + [ + pytest.param({"priority": "OFF_GRID"}, "default-priority", id="priority"), + pytest.param({"relay_behavior": "non_controllable"}, "lock", id="relay lock"), + ], +) +def test_circuits_of_one_breaker_that_differ_are_refused_by_name( + fields: dict[str, object], what: str +) -> None: + config = _raw(_TANDEMS) + _on_its_own_template(config, _MATE, **fields) + + with pytest.raises(ValueError, match=what) as refused: + validate_yaml_config(config) + + assert _MATE in str(refused.value) + assert _OTHER_MATE in str(refused.value) + + +def test_a_pv_rating_that_is_not_above_zero_is_refused() -> None: + config = _raw(CONFIGS / "ref_MAIN_32_TANDEMS.yaml") + templates = config["circuit_templates"] + assert isinstance(templates, dict) + for template in templates.values(): + profile = template.get("energy_profile") or {} + if profile.get("mode") == "producer": + profile["nameplate_capacity_w"] = 0 + with pytest.raises(ValueError, match="nominal-power-w"): + validate_yaml_config(config) + + +@pytest.mark.parametrize( + ("field", "value", "seen"), + [ + pytest.param("priority", "OFF_GRID", "OFF_GRID", id="priority"), + pytest.param( + "relay_behavior", "non_controllable", "non-controllable", id="relay behaviour" + ), + ], +) +def test_editing_one_circuit_of_a_breaker_edits_the_breaker( + field: str, value: str, seen: str +) -> None: + store = ConfigStore() + store.load_from_file(_TANDEMS) + + store.update_entity(_MATE, {field: value, "_dirty": "1"}) + + for circuit_id in (_MATE, _OTHER_MATE): + entity = store.get_entity(circuit_id) + shown = entity.priority if field == "priority" else entity.relay_behavior_option + assert shown == seen, circuit_id + + +@pytest.mark.asyncio +async def test_the_dashboard_s_relay_toggle_switches_the_whole_breaker(tmp_path: Path) -> None: + """A breaker has one relay, so opening one of its circuits opens them all.""" + config_dir = tmp_path / "cfg" + config_dir.mkdir() + (config_dir / "panel.yaml").write_text(_TANDEMS.read_text(encoding="utf-8"), encoding="utf-8") + calls: list[tuple[str, str]] = [] + ctx = DashboardContext( + config_dir=config_dir, + config_filter="panel.yaml", + get_panel_configs=lambda: {}, + get_panel_ports=lambda: {}, + request_reload=lambda: None, + set_circuit_relay=lambda circuit_id, state: calls.append((circuit_id, state)), + ) + async with TestClient(TestServer(create_dashboard_app(ctx))) as client: + response = await client.post(f"/entities/{_MATE}/relay", json={"relay_state": "OPEN"}) + assert response.status == 200 + + assert sorted(calls) == [(_MATE, "OPEN"), (_OTHER_MATE, "OPEN")] diff --git a/tests/test_clone.py b/tests/test_clone.py index 0503dc4..02502a2 100644 --- a/tests/test_clone.py +++ b/tests/test_clone.py @@ -931,7 +931,12 @@ def test_a_list_published_one_way_is_cloned_both_ways(self) -> None: is on the breaker even where its own list is missing, and the clone loads.""" devices = self._devices() devices["fff777"] = _circuit( - "fff777", "Bedroom Outlets", "44", rating="20", priority="NEVER", active_power="0.0" + "fff777", + "Bedroom Outlets", + "44", + rating="20", + priority="NICE_TO_HAVE", + active_power="0.0", ) config = translate_scraped_panel(_make_scraped(devices)) diff --git a/tests/test_feedthrough.py b/tests/test_feedthrough.py index 0a4c2fd..043aef1 100644 --- a/tests/test_feedthrough.py +++ b/tests/test_feedthrough.py @@ -124,6 +124,18 @@ def test_downstream_lugs_commissioning_on_a_panel_that_publishes_none_is_refused validate_yaml_config(config) +def test_a_battery_downstream_of_lugs_the_panel_does_not_publish_is_refused() -> None: + """A battery placed downstream hangs from the downstream lugs, which a hardware 3.0 + panel without a feedthrough does not publish from release 202645.""" + config = _hardware_3(firmware=_R202645, feedthrough=False) + battery = copy.deepcopy(panel_config()["bess"]) + battery["relative_position"] = "DOWNSTREAM" + battery.pop("feed", None) + config["bess"] = battery + with pytest.raises(ValueError, match=r"DOWNSTREAM"): + validate_yaml_config(config) + + def test_on_release_202639_downstream_lugs_commissioning_stands_without_a_feedthrough() -> None: """That release publishes the downstream lugs whatever the panel has, so their commissioning still describes them.""" diff --git a/tests/test_hybrid_battery.py b/tests/test_hybrid_battery.py index 01b7363..35490cb 100644 --- a/tests/test_hybrid_battery.py +++ b/tests/test_hybrid_battery.py @@ -23,7 +23,7 @@ from panelbench.definition_import import config_from_definition from panelbench.emitter_adapter import runtime as emitter_runtime from panelbench.emitter_adapter.wire_capture import recorded_panel -from panelbench.engine import DynamicSimulationEngine +from panelbench.engine import DynamicSimulationEngine, RealisticBehaviorEngine from panelbench.validation import validate_yaml_config from tests._helpers import ( discovered_from_tree, @@ -57,7 +57,9 @@ def _hybrid(*, nameplate_w: float | None = _ARRAY_W) -> SimulationConfig: return config -async def _flows_at(tmp_path: Path, config: SimulationConfig, at: str) -> dict[str, float]: +async def _flows_at( + tmp_path: Path, config: SimulationConfig, at: str, *, grid_online: bool = True +) -> dict[str, float]: """The panel's four power flows after one tick at simulated *at*.""" timed = copy.deepcopy(config) timed["simulation_params"]["use_simulation_time"] = True @@ -65,7 +67,10 @@ async def _flows_at(tmp_path: Path, config: SimulationConfig, at: str) -> dict[s # The circuits' noise is drawn from `random`, and the array draws none, so two runs # compared with each other draw the same. random.seed(20261119) - runtime, recorder = await recorded_panel(write_config(tmp_path / "panel.yaml", timed)) + tmp_path.mkdir(parents=True, exist_ok=True) + runtime, recorder = await recorded_panel( + write_config(tmp_path / "panel.yaml", timed), grid_online=grid_online + ) await emitter_runtime.publish_tick(runtime) serial = config["panel_config"]["serial_number"] return { @@ -182,27 +187,126 @@ def test_an_import_keeps_its_definition_s_coupling(name: str, coupling: str | No assert bess.get("inverter_type") == coupling -@pytest.mark.asyncio -async def test_the_model_view_books_a_hybrid_battery_s_array_as_solar(tmp_path: Path) -> None: - """Its After pass gives the array to the solar trace by day, and nothing by night.""" - entity = "sensor.synthetic_circuit_power" - - async def after_pv(config: SimulationConfig, where: Path) -> list[float]: - config["circuits"][0]["recorder_entity"] = entity - engine = DynamicSimulationEngine( - config_data=config, recorder=await recorder_history(where, entity) +_ENTITY: Final = "sensor.synthetic_circuit_power" + + +async def _modeling(config: SimulationConfig, where: Path) -> dict[str, list[float]]: + """The Model view's series for *config* over a recorder history kept in *where*.""" + where.mkdir() + config["circuits"][0]["recorder_entity"] = _ENTITY + engine = DynamicSimulationEngine( + config_data=config, recorder=await recorder_history(where, _ENTITY) + ) + await engine.initialize_async() + data = await engine.compute_modeling_data(24) + assert "error" not in data, data + series: dict[str, list[float]] = { + key: [float(value) for value in data[key]] + for key in ( + "timestamps", + "site_power", + "grid_power", + "pv_power_before", + "pv_power_after", + "battery_power", + "battery_power_before", ) - await engine.initialize_async() - data = await engine.compute_modeling_data(24) - assert "error" not in data, data - trace: list[float] = data["pv_power_after"] - return trace - - (tmp_path / "plain").mkdir() - (tmp_path / "hybrid").mkdir() - plain = await after_pv(panel_config(), tmp_path / "plain") - hybrid = await after_pv(_hybrid(), tmp_path / "hybrid") - - assert all(h >= p for h, p in zip(hybrid, plain, strict=True)) - assert any(h > p for h, p in zip(hybrid, plain, strict=True)) - assert any(h == p for h, p in zip(hybrid, plain, strict=True)) + } + return series + + +@pytest.mark.asyncio +async def test_the_model_view_books_a_hybrid_battery_s_array_as_the_emitter_does( + tmp_path: Path, +) -> None: + """In both passes: the array's own production joins the solar, the battery's + dispatch sees it, and the grid, battery and solar still add up to the panel's load.""" + plain = await _modeling(panel_config(), tmp_path / "plain") + hybrid = await _modeling(_hybrid(), tmp_path / "hybrid") + sun = RealisticBehaviorEngine(_hybrid()) + array = [round(sun.solar_output_w(_ARRAY_W, ts), 1) for ts in hybrid["timestamps"]] + assert any(array) and not all(array) + + for before, after in (("pv_power_before", "pv_power_after"),): + assert [ + round(h - p, 1) for h, p in zip(hybrid[before], plain[before], strict=True) + ] == pytest.approx(array, abs=0.2) + assert [ + round(h - p, 1) for h, p in zip(hybrid[after], plain[after], strict=True) + ] == pytest.approx(array, abs=0.2) + for grid, battery, pv in ( + ("site_power", "battery_power_before", "pv_power_before"), + ("grid_power", "battery_power", "pv_power_after"), + ): + loads = [ + [g + b + s for g, b, s in zip(run[grid], run[battery], run[pv], strict=True)] + for run in (plain, hybrid) + ] + assert loads[1] == pytest.approx(loads[0], abs=0.5), grid + assert any(h < p for h, p in zip(hybrid["battery_power"], plain["battery_power"], strict=True)) + + +@pytest.mark.asyncio +async def test_a_disabled_hybrid_battery_s_array_produces_nothing(tmp_path: Path) -> None: + off = panel_config() + off["bess"]["enabled"] = False + off_hybrid = _hybrid() + off_hybrid["bess"]["enabled"] = False + + plain = await _modeling(off, tmp_path / "plain") + hybrid = await _modeling(off_hybrid, tmp_path / "hybrid") + + assert hybrid["pv_power_after"] == plain["pv_power_after"] + + +def _cloned(config: SimulationConfig, original_bess: object) -> SimulationConfig: + """*config* as a clone keeps it, its battery as cloned the Before pass's.""" + config["panel_source"] = { + "origin_serial": "nt-0000-panel", + "host": "192.0.2.10", + "original_bess": original_bess, + } + return config + + +@pytest.mark.asyncio +async def test_rating_a_cloned_hybrid_s_array_is_no_saving(tmp_path: Path) -> None: + """A clone writes a hybrid battery with no array rating, since a panel publishes + none, and keeps that battery as the Before pass's. Rating the array afterwards fills + in what the panel has, so the Before pass books the array as the After pass does.""" + plain = panel_config() + plain = _cloned(plain, copy.deepcopy(plain["bess"])) + rated = _hybrid() + unrated = copy.deepcopy(rated["bess"]) + del unrated["pv_array"] + rated = _cloned(rated, unrated) + + before_plain = (await _modeling(plain, tmp_path / "plain"))["pv_power_before"] + modeled = await _modeling(rated, tmp_path / "rated") + sun = RealisticBehaviorEngine(_hybrid()) + array = [round(sun.solar_output_w(_ARRAY_W, ts), 1) for ts in modeled["timestamps"]] + + added = [ + round(r - p, 1) for r, p in zip(modeled["pv_power_before"], before_plain, strict=True) + ] + assert added == pytest.approx(array, abs=0.2) + + +@pytest.mark.asyncio +async def test_a_battery_turned_hybrid_while_running_restarts_rather_than_changes( + tmp_path: Path, +) -> None: + """The emitter's battery is built at start, and the emitter refuses PV for a battery + it was not started hybrid. So a live change of coupling is not applied, the caller + restarts the panel on its saved config instead, and ticks go on as they were.""" + runtime, recorder = await recorded_panel(write_config(tmp_path / "panel.yaml", panel_config())) + del recorder + turned = copy.deepcopy(_hybrid()["bess"]) + + assert emitter_runtime.update_bess_config_live(runtime, turned) is False + assert runtime.engine.config["bess"].get("inverter_type") != "hybrid" + await emitter_runtime.publish_tick(runtime) + + kept = copy.deepcopy(runtime.engine.config["bess"]) + kept["backup_reserve_pct"] = 35.0 + assert emitter_runtime.update_bess_config_live(runtime, kept) is True diff --git a/tests/test_virtual_devices.py b/tests/test_virtual_devices.py new file mode 100644 index 0000000..899fc4c --- /dev/null +++ b/tests/test_virtual_devices.py @@ -0,0 +1,70 @@ +"""A circuit on no breaker space is a virtual device: modelled, never published. + +The dashboard adds a PV inverter or a SPAN Drive as a circuit with no spaces for a what-if. +The Model view models it, but a panel publishes only the circuits on its spaces, and the +emitter refuses a circuit with none, so it is left out of what the emitter is handed, and +the panel starts and publishes its real circuits alone. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest +import yaml + +from panelbench.dashboard.config_store import ConfigStore +from panelbench.emitter_adapter import runtime as emitter_runtime +from panelbench.emitter_adapter.instance_ids import stable_circuit_uuid +from panelbench.emitter_adapter.wire_capture import recorded_panel +from panelbench.engine import DynamicSimulationEngine +from panelbench.validation import validate_yaml_config +from tests._helpers import NOON, PANEL_CONFIG + +if TYPE_CHECKING: + from pathlib import Path + + +def _with_virtual(kind: str) -> tuple[dict[str, object], str]: + """The working panel with a *kind* added from the dashboard, and the added id.""" + store = ConfigStore() + store.load_from_file(PANEL_CONFIG) + added = store.add_entity(kind) + config: dict[str, object] = yaml.safe_load(store.export_yaml()) + return config, added.id + + +@pytest.mark.parametrize("kind", ["pv", "evse"]) +def test_a_virtual_device_loads(kind: str) -> None: + config, added = _with_virtual(kind) + circuits = config["circuits"] + assert isinstance(circuits, list) + (circuit,) = [c for c in circuits if c["id"] == added] + assert not circuit.get("tabs") + + validate_yaml_config(config) + + +@pytest.mark.parametrize("kind", ["pv", "evse"]) +@pytest.mark.asyncio +async def test_a_virtual_device_is_not_published(tmp_path: Path, kind: str) -> None: + config, added = _with_virtual(kind) + path = tmp_path / "panel.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + + runtime, recorder = await recorded_panel(path) + await emitter_runtime.publish_tick(runtime) + + panel_config = config["panel_config"] + assert isinstance(panel_config, dict) + uuid = stable_circuit_uuid(str(panel_config["serial_number"]), added) + assert not [topic for topic in recorder.retained if f"/{uuid}/" in topic] + + +@pytest.mark.asyncio +async def test_the_model_view_models_a_virtual_pv() -> None: + config, added = _with_virtual("pv") + engine = DynamicSimulationEngine(config_data=config) + await engine.initialize_async() + + assert engine.modelled_circuit_power(added, NOON) > 0 From 2f97df0e3139d7e090648b70701c3bc22472a12e Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:29:15 -0800 Subject: [PATCH 07/22] fix: validation builds the emitter as start does; a tandem's one register; virtual devices bind nothing Validation refuses what a panel cannot start on by building the emitter as start does, through one construct_emitter that start, an import's render and validation share, so every rule the emitter applies to a definition applies when PanelBench loads, edits or saves a config, with each circuit and outside meter named by its id. That replaces the partial check (the manifest parse and shared_hardware's breaker rule) and the import of a module outside the emitter's public API. Before it, shape checks refuse by name every section the definition reads that is not the mapping, list or number its type says (bess, pv, evse, lugs, broker, simulation_params, panel_config's serial, total_tabs, main_size and site, a template's energy_profile, nameplate and breaker_rating, a circuit's template and tabs, the battery's numbers and hours), which reached the panel's start as an AttributeError or TypeError naming nothing. A bess.feed naming no circuit is refused, and deleting the circuit it names drops it, as a pv.feed is dropped. A PV circuit on no breaker space binds no PV device: pv_circuit_ids counts the circuits on the panel, so a what-if PV no longer publishes a device fed by nothing, nor hides the panel's own inverter, and lends an upstream inverter no type; a pv.feed or bess.feed naming one is refused. A clone and a refresh from the source panel write a tandem's or quad's one register to each of its circuits, the largest any publishes, as the emitter's capture takes it: the circuits read one meter a moment apart, and 0.11.0 refuses seeds that differ. A mate leaves recorder replay only where its own value changes. A live battery change applies only when it keeps the battery the emitter started with, coupled as it was; enabling, disabling or replacing it, or changing its coupling, restarts the panel. Tests pin each fix; every weakening tried fails one. The README's off-grid sentence no longer says the emitter's dispatch sees the load after shedding. --- CHANGELOG.md | 24 ++- README.md | 8 +- panelbench/CHANGELOG.md | 7 +- src/panelbench/clone.py | 57 +++++- src/panelbench/dashboard/config_store.py | 16 +- src/panelbench/definition_import.py | 9 +- src/panelbench/emitter_adapter/definition.py | 17 ++ src/panelbench/emitter_adapter/runtime.py | 38 ++-- .../emitter_adapter/spec_generator.py | 9 +- src/panelbench/pv_section.py | 25 ++- src/panelbench/validation.py | 169 +++++++++++++++--- .../test_islanding_assertion.py | 15 +- tests/emitter_adapter/test_runtime.py | 16 ++ tests/test_app.py | 21 +++ tests/test_bess_link.py | 12 +- tests/test_breaker_mates.py | 50 +++++- tests/test_clone.py | 26 ++- tests/test_config_shapes.py | 153 ++++++++++++++++ tests/test_config_store.py | 24 +++ tests/test_hybrid_battery.py | 74 ++++++-- tests/test_virtual_devices.py | 129 +++++++++++-- 21 files changed, 770 insertions(+), 129 deletions(-) create mode 100644 tests/test_config_shapes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 04b53d8..46ac00e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,9 @@ - **A battery can take its own solar.** `bess.inverter_type: hybrid` (default `ac-coupled`) says the battery's own inverter also takes PV, on its DC side, and `bess.pv_array.nameplate_capacity_w` rates the array; it produces by the panel's location and weather and joins `power-flows/pv` and the solar the battery's dispatch sees, live and in the Model view. A clone writes a battery hybrid where the emitter's capture reads it so: the panel publishes `power-flows/pv` - and nothing but its one battery could bring it solar. An imported definition keeps its battery's coupling. A battery made hybrid while its panel runs - restarts the panel, since the emitter builds its battery at start. Off grid the array is not yet curtailed to what the load and battery can take, as the - PV circuits are not. + and nothing but its one battery could bring it solar. An imported definition keeps its battery's coupling. A battery change the running panel cannot + take, a coupling changed or the battery enabled, disabled or replaced, restarts the panel, since the emitter builds its battery at start. Off grid the + array is not yet curtailed to what the load and battery can take, as the PV circuits are not. - **`panel_config.feedthrough`** (default `true`). With `false`, a hardware 3.0 panel on SPAN release 202645, or on a firmware naming none, publishes no downstream lugs, as such a panel without a feedthrough module does; release 202639 and a MAIN 32 publish both. A clone of a panel publishing its upstream lugs alone writes `false`. A `lugs.downstream` section for lugs the panel does not publish is refused, and so is a battery placed `DOWNSTREAM` of them. @@ -38,10 +38,12 @@ `meter/current-b` take each space's leg from its row and net each leg's current. On hardware 3.0 the circuits of one tandem or quad each publish the breaker's one reading, and a relay or priority set on one over MQTT reaches them all. A battery's `info/nameplate-capacity` has one decimal place there (`27.0`). A hardware 3.0 panel on release 202645, or on a firmware naming none, publishes each circuit's `connection/connection-point`. -- **A config the emitter would refuse is refused when PanelBench loads, edits or saves it**, with the emitter's reason and each circuit named by its `id`. - Under 0.11.0 that includes the circuits of one tandem or quad differing in priority, relay lock, never-backup or energy seed, and a PV rating that is not - above 0, both of which 0.10.0 started on. The dashboard applies a relay toggle, or a priority or relay-behaviour edit, on one circuit of a tandem or quad - to every circuit on it, since the breaker has one relay. +- **0.11.0 refuses the circuits of one tandem or quad differing in priority, relay lock, never-backup or energy seed, and a PV rating that is not above 0**, + both of which 0.10.0 started on, and PanelBench refuses them when it loads, edits or saves a config, as it does all the emitter refuses (see Fixed). The + dashboard applies a relay toggle, or a priority or relay-behaviour edit, on one circuit of a tandem or quad to every circuit on it, since the breaker has + one relay; only a circuit whose own value changes leaves recorder replay. A clone, and a refresh of its energy from the source panel, writes a tandem's or + quad's one register to each of its circuits: the largest any of them publishes, as the emitter's capture takes it, since they read one meter a moment + apart. - **Four generated templates are their panels' later captures, on release 202645**: `ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48`, where they were the release 202639 captures of the same panels. `ref_MAIN_40` is that panel recommissioned, with 38 circuits and no battery, where it had 5 and a battery fed by a circuit, and `ref_UNKNOWN_16` adds an EVSE. Their serials follow the captures: `sim-main32_r202645`, `sim-r202645-a`, `sim-r202645-c` and @@ -64,7 +66,13 @@ keeps all but the presets and the two tracked templates out, as a build from git has it, and leaves local state and caches out of the build context; images built by CI were not affected. - **A PV inverter or SPAN Drive added in the dashboard no longer stops its panel starting.** It sits on no breaker space, and the emitter refuses a circuit - with none, so a panel with one would not start; it is now a what-if device, which the Model view models and the panel does not publish. + with none, so a panel with one would not start; it is now a what-if device, which the Model view models and the panel does not publish, nor anything it + would feed. A `pv.feed` or `bess.feed` naming one is refused. +- **A config the panel cannot start on is refused when PanelBench loads, edits or saves it, saying why**, where it loaded and saved and the panel then + failed to start. PanelBench builds the emitter as a panel's start does, so whatever the emitter refuses, such as an `unvalued` path the device's profile + declares none of, is refused with its reason, each circuit and meter named by its `id`. A section or setting of the wrong shape, such as `lugs: x` or + `bess.charge_hours: 5`, is refused by name, where the panel failed with an error naming nothing. A `bess.feed` naming no circuit, which published a + battery fed by nothing, is refused, and deleting the circuit it names in the dashboard drops it, as it drops a `pv.feed`. - **A cycling load reads the same at a given simulated time on every run.** Its on and off phases follow the panel's clock, counted from the epoch, where they ran from the moment the panel started on the real clock. A panel set to a simulated time could read a cycling load on in one run and off in the next, and a panel no longer starts every cycling load at the start of its on phase. diff --git a/README.md b/README.md index f680401..3d68c3e 100644 --- a/README.md +++ b/README.md @@ -421,7 +421,8 @@ two `_TANDEMS` templates show one each: `switch/shared-with-device-ids`, which a circuit's `shared_with` sets. A single-pole circuit lists its own space and a two-pole circuit lists both. The circuits of one breaker share its one reading and relay: each publishes the breaker's reading, and a relay or priority set on one over MQTT reaches them all. In the dashboard a relay toggle, or an edit of the priority or relay behaviour, on one applies to every circuit on the breaker, and a config whose - circuits on one breaker differ in priority, relay lock, never-backup or energy seed is refused, as the emitter refuses it. + circuits on one breaker differ in priority, relay lock, never-backup or energy seed is refused, as the emitter refuses it. A clone gives each circuit the + breaker's one energy register, the largest any of them publishes, since they read one meter a moment apart. `ref_MLO_48_TANDEMS.yaml` is the reference MLO 48 with synthetic names and loads. It keeps that panel's three tandems and adds a 15-20 tandem on space 37, a quad on 27 and 29, and a tandem-quad on 31 and 33. @@ -479,8 +480,9 @@ and the solar the battery's dispatch sees, live and in the Model view; the emitt as a clone writes it, since a panel does not publish one. A clone writes `inverter_type: hybrid` where the emitter's capture reads the panel's battery as hybrid: the panel publishes `power-flows/pv`, and nothing but its one battery could bring it solar. An imported definition keeps its own battery's coupling. This `hybrid` is the battery's; a PV template's `inverter_type: hybrid` is a grid-forming inverter, which keeps producing off-grid. Off grid the array is not -yet curtailed to what the panel's load and the battery can take, as PanelBench's PV circuits are not: the emitter's dispatch, which sees the load after -shedding, is where that belongs. +yet curtailed to what the panel's load and the battery can take, as PanelBench's PV circuits are not: only the emitter knows which circuits it sheds and +how much the battery can still charge, so its dispatch is where that belongs. A change to the battery that the running panel cannot take, making it hybrid +or ac-coupled, or enabling, disabling or replacing it, restarts the panel, since the emitter builds its battery at start. ```yaml bess: diff --git a/panelbench/CHANGELOG.md b/panelbench/CHANGELOG.md index b833ccc..0b85ef3 100644 --- a/panelbench/CHANGELOG.md +++ b/panelbench/CHANGELOG.md @@ -9,7 +9,8 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ - **`ref_MAIN_32_CASCADE`, `ref_MAIN_16_BESS` and `ref_MLO_48_HYBRID`**: a MAIN 32 fed by another panel, a MAIN 16 with a hybrid battery and an EVSE, and an MLO 48 whose battery's inverter takes its solar. - **A battery can take its own solar**: set `bess.inverter_type: hybrid` and rate its array with `bess.pv_array.nameplate_capacity_w`, and it produces into the - panel's solar, live and in the Model view. A clone of a panel with such a battery writes it hybrid. Making a battery hybrid restarts its panel. + panel's solar, live and in the Model view. A clone of a panel with such a battery writes it hybrid. Changing a running battery's coupling restarts its + panel. - **`panel_config.feedthrough: false`** for a panel without a feedthrough module: on SPAN release 202645 a hardware 3.0 one publishes no downstream lugs. A clone writes it. @@ -27,7 +28,8 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ - **Runs on `ebus-panel-sim` 0.11.0**: the lugs' per-leg currents net each leg by the panel's rows; on hardware 3.0 a tandem's or quad's circuits each publish the breaker's one reading and share its relay over MQTT, and a battery's nameplate capacity has one decimal place. - **The dashboard switches and edits a tandem or quad as one breaker**: a relay toggle, or a priority or relay-behaviour change, on one of its circuits - applies to all of them, and a config the emitter would refuse, such as a PV rating of 0, is refused with its reason when edited or loaded. + applies to all of them. A config 0.11.0 refuses, such as a PV rating of 0, is refused with its reason when edited or loaded, and a clone gives a tandem's + circuits its one energy register. - **`ref_MAIN_32`, `ref_UNKNOWN_16`, `ref_MAIN_40` and `ref_MLO_48` are their panels' later captures, on release 202645.** `ref_MAIN_40` now has 38 circuits and no battery, and `ref_UNKNOWN_16` an EVSE. - **A `pv` section listing `inverters` must set `enabled`, to `true` or `false`**: without it they published nothing, and a quoted `"false"` published them; @@ -40,6 +42,7 @@ The shipped templates are now all `ref_` templates, and the three `default_MAIN_ - **A cycling load, such as a pool pump or a dryer, reads the same at a given simulated time on every run**, where it could read on in one run and off in the next. - **A PV inverter or SPAN Drive added in the dashboard no longer stops the panel starting**: it is modelled in the Model view and not published. +- **A config the panel cannot start on is refused when loaded, edited or saved, saying why**, where it was saved and the panel then failed to start. ### Removed diff --git a/src/panelbench/clone.py b/src/panelbench/clone.py index b74f658..109d600 100644 --- a/src/panelbench/clone.py +++ b/src/panelbench/clone.py @@ -20,7 +20,7 @@ import logging import math import re -from collections.abc import Callable, Mapping +from collections.abc import Callable, Collection, Mapping from datetime import UTC, datetime from types import MappingProxyType from typing import TYPE_CHECKING, Final @@ -428,6 +428,7 @@ def update_config_from_scrape( circuit_nodes = _devices_of_type(scraped.devices, scraped.serial_number, TYPE_CIRCUIT) keys = _circuit_keys(scraped.devices, circuit_nodes) + shared = _shared_with_by_circuit(config) changed = False @@ -447,8 +448,10 @@ def update_config_from_scrape( # Update energy seeds. Enclosure frame: `exported-energy` is the # enclosure exporting to the circuit (consumption), `imported-energy` is # the circuit backfeeding the enclosure (production). See the seeding - # comment in `_translate_circuit`. - exported = _float_prop(scraped.devices, node_uuid, "meter", "exported-energy") + # comment in `_translate_circuit`. A breaker the config records takes its one + # register on each of its circuits. + breaker = _breaker_nodes(node_uuid, keys, shared.get(_circuit_id(keys[node_uuid]), ())) + exported = _breaker_register(scraped.devices, breaker, "exported-energy") if ( exported is not None and exported > 0 @@ -457,7 +460,7 @@ def update_config_from_scrape( ep["initial_consumed_energy_wh"] = exported changed = True - imported = _float_prop(scraped.devices, node_uuid, "meter", "imported-energy") + imported = _breaker_register(scraped.devices, breaker, "imported-energy") if ( imported is not None and imported > 0 @@ -1028,9 +1031,11 @@ def _translate_circuit( # (backfeed). The simulator's own accumulators are device-framed, so # consumption seeds from `exported-energy` and production from # `imported-energy`. Requires ebus-emitter >= 0.2.1, which publishes the - # enclosure frame on both power and energy. - imported_energy = _float_prop(devices, node_uuid, "meter", "imported-energy") - exported_energy = _float_prop(devices, node_uuid, "meter", "exported-energy") + # enclosure frame on both power and energy. A tandem's or quad's circuits each + # take the breaker's one register (`_breaker_register`). + breaker = _breaker_nodes(node_uuid, keys, siblings.get(node_uuid, ())) + imported_energy = _breaker_register(devices, breaker, "imported-energy") + exported_energy = _breaker_register(devices, breaker, "exported-energy") # Build template energy_profile: dict[str, object] = { @@ -1563,6 +1568,44 @@ def _breaker_siblings( return siblings +def _breaker_nodes( + node_uuid: str, keys: Mapping[str, str], shared_with: Collection[str] +) -> list[str]: + """The device ids of *node_uuid*'s breaker: the circuit, then the circuits + *shared_with* names by their ids in the clone (``_circuit_id``).""" + named = set(shared_with) + return [node_uuid, *(node for node, key in keys.items() if _circuit_id(key) in named)] + + +def _breaker_register( + devices: Mapping[str, DiscoveredDevice], breaker: Collection[str], register: str +) -> float | None: + """The energy *register* (``meter/`` property) the circuits of one *breaker*, by + their device ids, publish. + + A tandem's or quad's circuits publish its one meter's register, each read a moment + apart, so the breaker's is the largest any of them publishes, as the emitter's own + capture takes it; and the emitter refuses circuits on one breaker whose seeds + differ. A circuit on a breaker of its own publishes its own. + """ + values = [ + value + for node in breaker + if (value := _float_prop(devices, node, "meter", register)) is not None + ] + return max(values) if values else None + + +def _shared_with_by_circuit(config: Mapping[str, object]) -> dict[str, list[str]]: + """Each of *config*'s circuits' ``shared_with``, by the circuit's id.""" + circuits = config.get("circuits") + return { + str(circuit["id"]): [str(peer) for peer in circuit.get("shared_with") or ()] + for circuit in (circuits if isinstance(circuits, list) else []) + if isinstance(circuit, dict) and "id" in circuit + } + + def _enrich_pv_template( devices: Mapping[str, DiscoveredDevice], circuit_nodes: list[str], diff --git a/src/panelbench/dashboard/config_store.py b/src/panelbench/dashboard/config_store.py index fdaa500..902354d 100644 --- a/src/panelbench/dashboard/config_store.py +++ b/src/panelbench/dashboard/config_store.py @@ -632,8 +632,12 @@ def update_entity(self, entity_id: str, data: dict[str, Any]) -> None: if (mate := self._find_circuit(mate_id)) is not None ] for name in dict.fromkeys(breaker_templates): - self._templates().get(name, {}).update(breaker_edits) - if breaker_edits and name != template_name and data.get("_dirty"): + breaker_template = self._templates().get(name, {}) + # The form posts both whatever was touched, so a mate leaves recorder + # replay only where its own value changes. + changed = any(breaker_template.get(k) != v for k, v in breaker_edits.items()) + breaker_template.update(breaker_edits) + if changed and name != template_name: self._mark_user_modified(name) overrides: dict[str, Any] = circuit.get("overrides", {}) @@ -805,9 +809,11 @@ def delete_entity(self, entity_id: str) -> None: if index is None: raise KeyError(f"Entity not found: {entity_id}") circuit = circuits.pop(index) - pv = self._state.get("pv") - if isinstance(pv, dict) and str(pv.get("feed")) == str(entity_id): - pv.pop("feed") + # A feed naming the circuit would name nothing once it is gone. + for section in ("pv", "bess"): + fed = self._state.get(section) + if isinstance(fed, dict) and str(fed.get("feed")) == str(entity_id): + fed.pop("feed") template_name = circuit["template"] still_used = any(c.get("template") == template_name for c in circuits) if not still_used: diff --git a/src/panelbench/definition_import.py b/src/panelbench/definition_import.py index 594f4c0..0773637 100644 --- a/src/panelbench/definition_import.py +++ b/src/panelbench/definition_import.py @@ -16,7 +16,6 @@ import yaml from ebus_panel_sim import ( - Emitter, EmitterError, PanelDefinition, SetterRegistry, @@ -25,7 +24,11 @@ ) from panelbench.clone import translate_panel_tree -from panelbench.emitter_adapter.definition import bess_dispatch_yaml, load_shedding_yaml +from panelbench.emitter_adapter.definition import ( + bess_dispatch_yaml, + construct_emitter, + load_shedding_yaml, +) from panelbench.emitter_adapter.wire_capture import RecordingTransport, discovered_devices from panelbench.hardware import published_variant @@ -93,7 +96,7 @@ def config_from_definition(definition: PanelDefinition) -> dict[str, object]: def _render(definition: PanelDefinition) -> dict[str, bytes]: """The retained tree upstream's emitter publishes for *definition*.""" transport = RecordingTransport() - emitter = Emitter.from_definition(definition, SetterRegistry(), mqttc=transport) + emitter = construct_emitter(definition, SetterRegistry(), transport) emitter.start() emitter.publish_tick(TickInputs(current_time=0.0, grid_online=True, circuits={})) return transport.retained diff --git a/src/panelbench/emitter_adapter/definition.py b/src/panelbench/emitter_adapter/definition.py index 9cf5cdf..40676d4 100644 --- a/src/panelbench/emitter_adapter/definition.py +++ b/src/panelbench/emitter_adapter/definition.py @@ -15,6 +15,7 @@ BESSConfig, ChargeMode, DeviceManifest, + Emitter, LoadSheddingConfig, ManifestPhysicsView, PanelDefinition, @@ -25,6 +26,8 @@ from panelbench.hardware import panel_variant if TYPE_CHECKING: + from ebus_panel_sim import MqttDeviceTransport, SetterRegistry + from panelbench.config_types import BESSConfigYAML, PanelConfig, SimulationConfig _DEFAULT_SOC_SHED_THRESHOLD_PCT = 20.0 @@ -43,6 +46,20 @@ def build_definition(config: SimulationConfig) -> PanelDefinition: ) +def construct_emitter( + definition: PanelDefinition, setters: SetterRegistry, transport: MqttDeviceTransport +) -> Emitter: + """The emitter for *definition*, publishing through *transport*. + + The one place PanelBench builds one: a panel's start, an import's render and + validation all build it here, so a config validation accepts is one a panel + starts on. Construction applies every rule the emitter has for a definition and + publishes nothing until ``start``. The emitter registers its own default ``/set`` + handlers from an empty *setters*, so no producer-side wiring is needed. + """ + return Emitter.from_definition(definition, setters, mqttc=transport) + + def bess_config(serial_number: str, bess: BESSConfigYAML) -> BESSConfig | None: """The emitter's native battery for a YAML ``bess`` section, or ``None`` when disabled.""" if not bess.get("enabled"): diff --git a/src/panelbench/emitter_adapter/runtime.py b/src/panelbench/emitter_adapter/runtime.py index 4508059..33e5fea 100644 --- a/src/panelbench/emitter_adapter/runtime.py +++ b/src/panelbench/emitter_adapter/runtime.py @@ -35,7 +35,11 @@ from panelbench.const import DEFAULT_WIFI_SSID from panelbench.emitter_adapter.broker_link import BrokerLink -from panelbench.emitter_adapter.definition import bess_config, build_definition +from panelbench.emitter_adapter.definition import ( + bess_config, + build_definition, + construct_emitter, +) from panelbench.emitter_adapter.instance_ids import ( evse_device_id, stable_circuit_uuid, @@ -96,26 +100,28 @@ def update_bess_config_live(runtime: CloneRuntime, bess_yaml: BESSConfigYAML) -> values, rebuilds the emitter-side ``BESSConfig`` from the YAML, and swaps it on the emitter (SOC/SOE state is preserved across the swap). - Returns False, changing nothing, for a battery the change makes hybrid that the - emitter did not start hybrid: it builds its battery at start and refuses PV for - one it was not, so the panel must restart on the saved config instead. + Returns False, changing nothing, unless the change keeps the battery the emitter + was started with, coupled as it was. The emitter builds its batteries at start and + takes PV only for one it started hybrid, so a battery the change enables, + disables or renames, or makes hybrid or ac-coupled, needs the panel restarted on + the saved config instead. """ - makes_hybrid = bool(bess_yaml.get("enabled")) and bess_yaml.get("inverter_type") == "hybrid" - if makes_hybrid and not _hybrid_batteries(runtime.manifest): + battery = bess_config(runtime.engine.serial_number, bess_yaml) + hybrid = bess_yaml.get("inverter_type") == "hybrid" + started = _started_batteries(runtime.manifest) + if battery is None or started.get(battery.instance_id) is not hybrid: return False runtime.engine.config["bess"] = bess_yaml - new_cfg = bess_config_from_engine(runtime.engine) - if new_cfg is not None: - runtime.emitter.update_bess_config(new_cfg) + runtime.emitter.update_bess_config(battery) return True -def _hybrid_batteries(manifest: DeviceManifest) -> set[str]: - """The batteries the emitter was started with that it takes PV for.""" +def _started_batteries(manifest: DeviceManifest) -> dict[str, bool]: + """The batteries the emitter was started with, each mapped to whether it is + hybrid, which the emitter takes PV for.""" return { - battery.instance_id + battery.instance_id: battery.metadata.get("inverter-type") == "hybrid" for battery in manifest.of_class("bess") - if battery.metadata.get("inverter-type") == "hybrid" } @@ -181,8 +187,6 @@ async def start_clone( stable_circuit_uuid(panel_id, c["id"]): c["id"] for c in engine.config["circuits"] } - # The emitter registers internal default /set handlers from the empty - # SetterRegistry — no producer-side wiring required. setters = SetterRegistry() # The will rides the CONNECT packet, so it has to be registered on the client @@ -220,7 +224,7 @@ async def start_clone( transport = loop_bound try: - emitter = Emitter.from_definition(definition, setters, mqttc=transport) + emitter = construct_emitter(definition, setters, transport) # Synchronous, and returns immediately for an injected client rather than # polling is_connected for the connect timeout: the SDK never starts a client # it did not build, so nothing would change during the wait. @@ -291,7 +295,7 @@ def _bess_pv(runtime: CloneRuntime, watts: float) -> dict[str, float]: other, which the emitter refuses to give PV, and with none. The engine produces nothing for a battery its config does not make hybrid.""" battery = bess_config_from_engine(runtime.engine) - if battery is None or battery.instance_id not in _hybrid_batteries(runtime.manifest): + if battery is None or not _started_batteries(runtime.manifest).get(battery.instance_id): return {} return {battery.instance_id: watts} diff --git a/src/panelbench/emitter_adapter/spec_generator.py b/src/panelbench/emitter_adapter/spec_generator.py index 3cdcba4..9580ae8 100644 --- a/src/panelbench/emitter_adapter/spec_generator.py +++ b/src/panelbench/emitter_adapter/spec_generator.py @@ -207,7 +207,7 @@ def _circuit_instances(profile: SimulationConfig) -> list[DeviceInstance]: instances: list[DeviceInstance] = [] published = [c for c in profile.get("circuits") or [] if on_the_panel(c)] for idx, c in enumerate(published, start=1): - tabs = c.get("tabs") or [0] + tabs = c["tabs"] template_name = c.get("template", "") template: CircuitTemplateExtended | None = templates.get(template_name) commissioned_system: str | None @@ -246,7 +246,7 @@ def _circuit_instances(profile: SimulationConfig) -> list[DeviceInstance]: display_name=c.get("name", c["id"]), description_name=instance_id if named_by_id else None, metadata={ - "tab-numbers": ",".join(str(int(t)) for t in tabs if t), + "tab-numbers": ",".join(str(int(t)) for t in tabs), "breaker-rating-a": str(breaker_rating), "default-priority": priority, "relay-behavior": relay_behavior, @@ -816,9 +816,12 @@ def _islandable(profile: SimulationConfig) -> bool: def _first_producer_template(profile: SimulationConfig) -> CircuitTemplateExtended | None: - """The template of the first producer circuit, read for a PV device with no PV circuit.""" + """The template of the first producer circuit on the panel, read for a PV device with + no PV circuit.""" templates = profile.get("circuit_templates") or {} for circuit in profile.get("circuits") or []: + if not on_the_panel(circuit): + continue template = templates.get(circuit.get("template", "")) if template is None: continue diff --git a/src/panelbench/pv_section.py b/src/panelbench/pv_section.py index c597f49..626cb90 100644 --- a/src/panelbench/pv_section.py +++ b/src/panelbench/pv_section.py @@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Final, Literal from panelbench.firmware import SPAN_RELEASE_202639, panel_firmware_version, predates +from panelbench.virtual_devices import on_the_panel if TYPE_CHECKING: from collections.abc import Mapping @@ -24,10 +25,12 @@ def pv_circuit_ids(config: Mapping[str, object]) -> list[str]: - """The ids of *config*'s PV circuits, those whose template says ``device_type: pv``. + """The ids of *config*'s PV circuits on the panel, those on a breaker space whose + template says ``device_type: pv``. - In list order. Anything malformed is skipped rather than refused: validation - names it. + In list order. A PV circuit on no space is a what-if device (``virtual_devices``), + which feeds no inverter the panel publishes, so it is none of them. Anything + malformed is skipped rather than refused: validation names it. """ templates = config.get("circuit_templates") circuits = config.get("circuits") @@ -35,7 +38,7 @@ def pv_circuit_ids(config: Mapping[str, object]) -> list[str]: return [] ids: list[str] = [] for circuit in circuits: - if not isinstance(circuit, dict) or "id" not in circuit: + if not isinstance(circuit, dict) or "id" not in circuit or not on_the_panel(circuit): continue template_name = circuit.get("template") template = templates.get(template_name) if isinstance(template_name, str) else None @@ -82,14 +85,22 @@ def bound_pv_circuit_id(config: Mapping[str, object]) -> str | None: def _pv_circuit_named(config: Mapping[str, object], pv_ids: list[str], feed: str) -> str: """*feed*, once it is known to name a PV circuit by its config ``id``.""" circuits = config.get("circuits") - named = isinstance(circuits, list) and any( - isinstance(circuit, dict) and str(circuit.get("id")) == feed for circuit in circuits - ) + named = [ + circuit + for circuit in (circuits if isinstance(circuits, list) else []) + if isinstance(circuit, dict) and str(circuit.get("id")) == feed + ] if not named: raise ValueError( f"pv.feed {feed!r} names no circuit: set it to the id of the PV circuit feeding " "the inverter the pv section describes" ) + if not on_the_panel(named[0]): + raise ValueError( + f"pv.feed names circuit {feed!r}, which sits on no breaker space: a what-if " + "device, which the panel does not publish, so it feeds no inverter the panel " + "does. Give it spaces, or name the PV circuit feeding the inverter" + ) if feed not in pv_ids: raise ValueError( f"pv.feed names circuit {feed!r}, which is not a PV circuit: its template " diff --git a/src/panelbench/validation.py b/src/panelbench/validation.py index d102196..c0a6747 100644 --- a/src/panelbench/validation.py +++ b/src/panelbench/validation.py @@ -11,9 +11,7 @@ import math from typing import TYPE_CHECKING, Any, Final, cast -from ebus_panel_sim import EmitterError -from ebus_panel_sim.manifest_physics import ManifestPhysicsView -from ebus_panel_sim.shared_hardware import shared_breakers +from ebus_panel_sim import EmitterError, SetterRegistry from panelbench.breakers import breaker_misfit, crowded_spaces, crowding from panelbench.config_defaults import normalize_config @@ -34,6 +32,7 @@ from panelbench.pv_rating import rating_conflicts from panelbench.pv_section import bound_pv_circuit_id, pv_circuit_ids from panelbench.registration_limit import registration_limit +from panelbench.virtual_devices import on_the_panel if TYPE_CHECKING: from collections.abc import Mapping @@ -56,6 +55,8 @@ def validate_yaml_config(config_data: Any) -> None: raise ValueError(f"Missing required section: {section}") validate_panel_config(config_data["panel_config"]) + validate_section_shapes(config_data) + validate_battery_settings(config_data) # A declared variant must be one PanelBench publishes; panel_variant says which. panel_variant(config_data) validate_circuit_templates(config_data["circuit_templates"]) @@ -78,7 +79,8 @@ def validate_yaml_config(config_data: Any) -> None: validate_unvalued_lists(config_data) validate_downstream_lugs(config_data) validate_battery_coupling(config_data) - # Every check above has established the shape a SimulationConfig has. + # Every check above has established the shape a SimulationConfig has: each + # section the definition reads is the mapping, list or number its type says. validate_emitter_accepts(cast("SimulationConfig", config_data)) if "panel_source" in config_data: @@ -94,6 +96,23 @@ def validate_panel_config(panel_config: Any) -> None: for field in required_panel_fields: if field not in panel_config: raise ValueError(f"Missing required panel_config field: {field}") + serial = panel_config["serial_number"] + if isinstance(serial, bool) or not isinstance(serial, (str, int)) or not str(serial): + raise ValueError(f"panel_config.serial_number must be the panel's serial, not {serial!r}") + if not _is_int(panel_config["total_tabs"]): + raise ValueError( + f"panel_config.total_tabs must be a whole number of spaces, not " + f"{panel_config['total_tabs']!r}" + ) + main_size = panel_config["main_size"] + if main_size is not None and not _is_finite_number(main_size): + raise ValueError( + f"panel_config.main_size must be the main breaker's amps, or null for none, " + f"not {main_size!r}" + ) + site = panel_config.get("site") + if site is not None and not isinstance(site, dict): + raise ValueError(f"panel_config.site must be a mapping of its settings, not {site!r}") if "feedthrough" in panel_config and not isinstance(panel_config["feedthrough"], bool): raise ValueError( f"panel_config.feedthrough must be true or false, not {panel_config['feedthrough']!r}" @@ -128,6 +147,24 @@ def validate_single_template(template_name: str, template: Any) -> None: raise ValueError( f"Missing required field '{field}' in circuit template '{template_name}'" ) + energy_profile = template["energy_profile"] + if not isinstance(energy_profile, dict): + raise ValueError( + f"Circuit template '{template_name}' energy_profile must be a mapping of its " + f"settings, not {energy_profile!r}" + ) + nameplate = energy_profile.get("nameplate_capacity_w", 0.0) + if not _is_finite_number(nameplate): + raise ValueError( + f"Circuit template '{template_name}' energy_profile.nameplate_capacity_w must be " + f"a number of watts, not {nameplate!r}" + ) + rating = template.get("breaker_rating") + if rating is not None and not _is_finite_number(rating): + raise ValueError( + f"Circuit template '{template_name}' breaker_rating must be the breaker's amps, " + f"or null where the panel publishes none, not {rating!r}" + ) priority = str(template["priority"]).upper() if priority not in SHED_PRIORITIES: raise ValueError( @@ -282,14 +319,14 @@ def validate_single_circuit(index: int, circuit: Any, circuit_templates: dict[st raise ValueError(f"Missing required field '{field}' in circuit {index}") template_name = circuit["template"] - if template_name not in circuit_templates: + if not isinstance(template_name, str) or template_name not in circuit_templates: raise ValueError(f"Circuit {index} references unknown template '{template_name}'") template = circuit_templates.get(template_name, {}) tabs = circuit.get("tabs", []) - if not isinstance(tabs, list): - raise ValueError(f"Circuit {index} ('tabs') must be a list") + if not isinstance(tabs, list) or not all(_is_int(tab) for tab in tabs): + raise ValueError(f"Circuit {index} ('tabs') must be a list of space numbers, not {tabs!r}") # Infrastructure entities (PV, EVSE) may have empty tabs # when added as virtual devices for "what-if" modeling. @@ -696,32 +733,120 @@ def validate_battery_coupling(config_data: dict[str, object]) -> None: ) +# Sections a config may leave out or set null, each otherwise a mapping of settings. +_MAPPING_SECTIONS: Final = ("bess", "pv", "evse", "lugs", "broker", "simulation_params") + + +def validate_section_shapes(config_data: Mapping[str, object]) -> None: + """Refuse a section that is not the mapping of settings it must be. + + Each is read setting by setting when the panel's definition is built, so a scalar + or a list there would otherwise fail there, with an error naming nothing. + """ + for section in _MAPPING_SECTIONS: + value = config_data.get(section) + if value is not None and not isinstance(value, dict): + raise ValueError(f"{section} must be a mapping of its settings, not {value!r}") + lugs = config_data.get("lugs") + if isinstance(lugs, dict): + for direction in ("upstream", "downstream"): + value = lugs.get(direction) + if value is not None and not isinstance(value, dict): + raise ValueError( + f"lugs.{direction} must be a mapping of its commissioning, not {value!r}" + ) + + +_BATTERY_NUMBERS: Final = ( + "nameplate_capacity_kwh", + "max_charge_w", + "max_discharge_w", + "charge_efficiency", + "discharge_efficiency", + "backup_reserve_pct", + "initial_soe_kwh", +) +_BATTERY_HOURS: Final = ("charge_hours", "discharge_hours") + + +def validate_battery_settings(config_data: Mapping[str, object]) -> None: + """Refuse a ``bess`` setting that is not the number, or list of hours, it must be.""" + bess = config_data.get("bess") + if not isinstance(bess, dict): + return + for key in _BATTERY_NUMBERS: + if key in bess and not _is_finite_number(bess[key]): + raise ValueError(f"bess.{key} must be a finite number, not {bess[key]!r}") + for key in _BATTERY_HOURS: + hours = bess.get(key, []) + if not isinstance(hours, list) or not all(_is_int(hour) for hour in hours): + raise ValueError(f"bess.{key} must be a list of hours of the day, not {hours!r}") + if "feed" in bess: + _validate_battery_feed(str(bess["feed"]), config_data.get("circuits")) + + +def _validate_battery_feed(feed: str, circuits: object) -> None: + """Refuse a ``bess.feed`` naming no circuit the panel publishes. + + The emitter takes a feed naming nothing as it is, and a circuit on no breaker space + is a what-if device the panel does not publish, so no battery can hang from it. + """ + named = [ + circuit + for circuit in (circuits if isinstance(circuits, list) else []) + if isinstance(circuit, dict) and str(circuit.get("id")) == feed + ] + if not named: + raise ValueError( + f"bess.feed {feed!r} names no circuit: set it to the id of the circuit feeding " + "the battery, or remove it for a battery no circuit feeds" + ) + if not on_the_panel(named[0]): + raise ValueError( + f"bess.feed names circuit {feed!r}, which sits on no breaker space: a what-if " + "device, which the panel does not publish, so no battery hangs from it" + ) + + +def _is_int(value: object) -> bool: + """A YAML integer: never a bool, which YAML also reads as one.""" + return isinstance(value, int) and not isinstance(value, bool) + + +def _is_finite_number(value: object) -> bool: + """A finite YAML number, integer or float, never a bool.""" + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + def validate_emitter_accepts(config_data: SimulationConfig) -> None: - """Refuse a config whose definition the emitter refuses, with the emitter's reason. - - PanelBench's own rules say why in its terms. This asks the emitter's: its parse of - the manifest, and, under a variant that publishes shared breakers, its rule that a - breaker's circuits agree in priority, relay lock, never-backup, placement and - energy seed (``ebus_panel_sim.shared_hardware``). So a config PanelBench accepts - is one the panel starts on, and the dashboard refuses an edit the emitter would. - The definition is built from a normalised copy, as the engine builds it, and the - reason names each circuit by its config ``id``. + """Refuse a config the emitter refuses to start a panel on, with its reason. + + PanelBench's own rules say why in its terms. This asks the emitter by building + it, as a panel's start does (``construct_emitter``), on a transport that records + what it would publish: every rule the emitter applies to a definition then + applies here, such as a breaker's circuits agreeing in priority, relay lock, + never-backup, placement and energy seed, and a PV rating above 0. So a config + PanelBench accepts is one the panel starts on, and the dashboard refuses an edit + the emitter would. The definition is built from a normalised copy, as the engine + builds it, and the reason names each circuit by its config ``id``. """ - from panelbench.emitter_adapter.definition import build_definition + from panelbench.emitter_adapter.definition import build_definition, construct_emitter from panelbench.emitter_adapter.instance_ids import stable_circuit_uuid + from panelbench.emitter_adapter.wire_capture import RecordingTransport config: SimulationConfig = copy.deepcopy(config_data) normalize_config(config, source="validation") definition = build_definition(config) try: - view = ManifestPhysicsView(definition.manifest) - if publishes_shared_breakers(definition.variant): - shared_breakers(view.all_circuits()) + construct_emitter(definition, SetterRegistry(), RecordingTransport()) except EmitterError as exc: reason = str(exc) serial = config["panel_config"]["serial_number"] - for circuit in config.get("circuits") or []: - reason = reason.replace(stable_circuit_uuid(serial, circuit["id"]), circuit["id"]) + # A meter outside the panel takes its device id from its `id` as a circuit does. + named = [*(config.get("circuits") or []), *(config.get("outside_meters") or [])] + for device in named: + device_id = str(device["id"]) + reason = reason.replace(stable_circuit_uuid(serial, device_id), device_id) raise ValueError(f"The emitter refuses this panel: {reason}") from exc diff --git a/tests/emitter_adapter/test_islanding_assertion.py b/tests/emitter_adapter/test_islanding_assertion.py index de77ceb..09f2a2e 100644 --- a/tests/emitter_adapter/test_islanding_assertion.py +++ b/tests/emitter_adapter/test_islanding_assertion.py @@ -76,19 +76,16 @@ async def test_a_link_set_without_a_battery_is_not_sent(tmp_path: Path) -> None: assert not [topic for topic in recorder.retained if topic.endswith(f"/{_LINK}")] -async def test_a_battery_disabled_mid_run_stops_receiving_the_link() -> None: +async def test_a_battery_disabled_mid_run_keeps_its_link_until_the_restart() -> None: + """The emitter builds its battery at start, so disabling it live is not applied: + the panel goes on running the battery it started with, its link with it, until + the caller restarts it on the saved config.""" runtime, recorder = await recorded_panel(PANEL_CONFIG) battery = bess_config_from_engine(runtime.engine) assert battery is not None runtime.engine.set_bess_link("LOST") - await emitter_runtime.publish_tick(runtime) - assert published(recorder, battery.instance_id, _LINK) == "LOST" - update_bess_config_live(runtime, {"enabled": False}) + assert update_bess_config_live(runtime, {"enabled": False}) is False - # The link is keyed from the live config, so the disabled battery gets nothing. - # The emitter keeps the battery it was built with, and one left out of the tick - # reads as OK. - assert emitter_runtime._bess_communication(runtime.engine, "LOST") == {} await emitter_runtime.publish_tick(runtime) - assert published(recorder, battery.instance_id, _LINK) == "OK" + assert published(recorder, battery.instance_id, _LINK) == "LOST" diff --git a/tests/emitter_adapter/test_runtime.py b/tests/emitter_adapter/test_runtime.py index 7a96b8f..5d81eac 100644 --- a/tests/emitter_adapter/test_runtime.py +++ b/tests/emitter_adapter/test_runtime.py @@ -117,6 +117,22 @@ def test_evse_tick_inputs_include_each_evse_feed() -> None: } +def test_a_virtual_span_drive_takes_no_published_drive_s_reading() -> None: + """SPAN Drive ids follow the published drives' order, so a what-if drive on no + space listed first must not take the first id, and the real drive's reading.""" + config = { + "panel_config": {"serial_number": "abc"}, + "circuit_templates": {"span_drive": {"device_type": "evse"}}, + "circuits": [ + {"id": "span_drive_what_if", "template": "span_drive"}, + {"id": "span_drive_garage", "template": "span_drive", "tabs": [1, 3]}, + ], + } + circuit_powers = {stable_circuit_uuid("abc", "span_drive_garage"): 7200.0} + + assert _evse_tick_inputs(config, circuit_powers) == {"abc-sim-evse-abc": 7200.0} + + def test_panel_envelope_publishes_the_configured_ssid() -> None: config = {"panel_config": {"serial_number": "abc", "wifi_ssid": "example-net"}} diff --git a/tests/test_app.py b/tests/test_app.py index 546ae61..afe04ad 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -422,3 +422,24 @@ async def test_a_second_panel_with_a_running_serial_is_refused( for panel in list(app._panels.values()): with contextlib.suppress(Exception): await panel.stop() + + +class TestApplyBessConfigLive: + """A live battery change the panel cannot take is left to the reload watcher.""" + + @pytest.mark.parametrize("applied", [True, False], ids=["applied", "needs a restart"]) + def test_only_an_applied_change_marks_the_file_current( + self, tmp_path: Path, applied: bool + ) -> None: + path = tmp_path / "panel.yaml" + path.write_text("saved: true\n", encoding="utf-8") + panel = MagicMock(spec=PanelInstance) + panel.runtime = MagicMock() + panel.update_bess_config.return_value = applied + app = SimulatorApp(config_dir=tmp_path) + app._panels[path] = panel + app._config_hashes[path] = "before the save" + + assert app.apply_bess_config_live("panel.yaml", {"enabled": True}) is applied + + assert app._config_hashes[path] == (_file_hash(path) if applied else "before the save") diff --git a/tests/test_bess_link.py b/tests/test_bess_link.py index 1a61169..83b021f 100644 --- a/tests/test_bess_link.py +++ b/tests/test_bess_link.py @@ -63,8 +63,8 @@ def test_an_unknown_link_health_is_refused() -> None: async def test_the_summary_reports_the_published_link( tmp_path: Path, amqtt_broker: tuple[str, int] ) -> None: - """The dashboard shows what the wire carries, not what was asked for: a battery - disabled mid-run is still published, out of the tick, as ``OK``.""" + """The dashboard shows what the wire carries, not what was asked for: a link asked + for reads as the one last published until a tick publishes it.""" host, port = amqtt_broker config = panel_config() config["broker"] = {"host": host, "port": port} @@ -74,17 +74,15 @@ async def test_the_summary_reports_the_published_link( assert panel.engine is not None assert panel.runtime is not None panel.engine.set_bess_link("LOST") - await emitter_runtime.publish_tick(panel.runtime) summary = panel.get_power_summary() assert summary is not None - assert summary["bess_link"] == "LOST" + assert panel.engine.bess_link == "LOST" + assert summary["bess_link"] == "OK" - panel.update_bess_config({"enabled": False}) await emitter_runtime.publish_tick(panel.runtime) summary = panel.get_power_summary() assert summary is not None - assert panel.engine.bess_link == "LOST" - assert summary["bess_link"] == "OK" + assert summary["bess_link"] == "LOST" finally: await panel.stop() diff --git a/tests/test_breaker_mates.py b/tests/test_breaker_mates.py index 969fdf9..589bb3d 100644 --- a/tests/test_breaker_mates.py +++ b/tests/test_breaker_mates.py @@ -89,10 +89,10 @@ def test_a_pv_rating_that_is_not_above_zero_is_refused() -> None: ], ) def test_editing_one_circuit_of_a_breaker_edits_the_breaker( - field: str, value: str, seen: str + tmp_path: Path, field: str, value: str, seen: str ) -> None: store = ConfigStore() - store.load_from_file(_TANDEMS) + store.load_from_file(_replayed(tmp_path)) store.update_entity(_MATE, {field: value, "_dirty": "1"}) @@ -100,6 +100,52 @@ def test_editing_one_circuit_of_a_breaker_edits_the_breaker( entity = store.get_entity(circuit_id) shown = entity.priority if field == "priority" else entity.relay_behavior_option assert shown == seen, circuit_id + # Each circuit's own value changed, so each has left recorder replay. + assert entity.user_modified, circuit_id + + +def test_renaming_one_circuit_of_a_breaker_leaves_the_other_on_recorder_replay( + tmp_path: Path, +) -> None: + """The edit form posts the priority and relay behaviour with every save, so only a + mate whose own value changes leaves replay.""" + store = ConfigStore() + store.load_from_file(_replayed(tmp_path)) + template = _template_of(_raw(_TANDEMS), _MATE) + + store.update_entity( + _MATE, + { + "name": "Renamed", + "priority": template["priority"], + "relay_behavior": template["relay_behavior"], + "_dirty": "1", + }, + ) + + assert store.get_entity(_MATE).user_modified + assert not store.get_entity(_OTHER_MATE).user_modified + + +def _replayed(tmp_path: Path) -> Path: + """The tandems template with both circuits of one breaker replaying a recorder + entity, as a clone's circuits do until edited.""" + config = _raw(_TANDEMS) + for circuit_id in (_MATE, _OTHER_MATE): + _template_of(config, circuit_id)["recorder_entity"] = f"sensor.{circuit_id}_power" + path = tmp_path / "panel.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + return path + + +def _template_of(config: dict[str, object], circuit_id: str) -> dict[str, object]: + circuits = config["circuits"] + templates = config["circuit_templates"] + assert isinstance(circuits, list) + assert isinstance(templates, dict) + (circuit,) = [c for c in circuits if c["id"] == circuit_id] + template: dict[str, object] = templates[circuit["template"]] + return template @pytest.mark.asyncio diff --git a/tests/test_clone.py b/tests/test_clone.py index 02502a2..6278379 100644 --- a/tests/test_clone.py +++ b/tests/test_clone.py @@ -800,15 +800,35 @@ def test_each_keeps_its_own_id_and_names_the_other(self) -> None: assert outlets["shared_with"] == ["circuit_44"] validate_yaml_config(config) - def test_a_refresh_updates_each_ones_own_energy(self) -> None: + def _seeds(self, config: dict[str, object]) -> dict[str, object]: + templates = _templates(config) + return { + name: templates[name]["energy_profile"].get("initial_consumed_energy_wh") + for name in ("clone_44", "clone_44_2") + } + + def test_a_tandem_read_a_moment_apart_is_cloned_with_its_one_register(self) -> None: + """Its circuits publish its one meter's register, each read a moment apart, so + each takes the largest, as the emitter's capture does: the emitter refuses + circuits on one breaker whose seeds differ.""" + devices = self._devices() + devices["fff666"].update_property("meter", "exported-energy", "1000.5") + devices["fff777"].update_property("meter", "exported-energy", "1000.0") + + config = translate_scraped_panel(_make_scraped(devices)) + + assert self._seeds(config) == {"clone_44": 1000.5, "clone_44_2": 1000.5} + validate_yaml_config(config) + + def test_a_refresh_writes_the_breaker_s_one_register_to_each_circuit(self) -> None: devices = self._devices() config = translate_scraped_panel(_make_scraped(devices)) devices["fff777"].update_property("meter", "exported-energy", "777.0") assert update_config_from_scrape(config, _make_scraped(devices)) - energy = _templates(config)["clone_44_2"]["energy_profile"] - assert energy["initial_consumed_energy_wh"] == 777.0 + assert self._seeds(config) == {"clone_44": 777.0, "clone_44_2": 777.0} + validate_yaml_config(config) def test_sharing_with_no_other_circuit_is_refused(self) -> None: config = translate_scraped_panel(_make_scraped(self._devices())) diff --git a/tests/test_config_shapes.py b/tests/test_config_shapes.py new file mode 100644 index 0000000..2841ea9 --- /dev/null +++ b/tests/test_config_shapes.py @@ -0,0 +1,153 @@ +"""A config PanelBench accepts is one a panel starts on. + +Validation refuses, with a reason naming what is wrong, every section the panel's +definition reads that is not the shape its type says, and then builds the emitter as a +panel's start does, so every rule the emitter applies to a definition applies there too. +Nothing a config holds reaches the panel's start as an error naming nothing. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Final + +import pytest +import yaml + +from panelbench.validation import validate_yaml_config +from tests._helpers import CONFIGS, PANEL_CONFIG + +if TYPE_CHECKING: + from pathlib import Path + +_MLO_48: Final = CONFIGS / "ref_MLO_48_TANDEMS.yaml" +# Stands for the first circuit's template in a path through `circuit_templates`. +_TEMPLATE: Final = "