diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f5d24ae..ead0255 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -40,7 +40,7 @@ repos: # released versions from PyPI rather than a git ref: `ebus-panel-sim` used to # track the fork's moving `spanpanel/main` branch, so this hook could resolve a # different build on two consecutive runs with nothing in the repo changing. - - ebus-panel-sim==0.10.0b2 + - ebus-panel-sim==0.11.0 - ebus-sdk==0.22.0 - aiomqtt>=2.5.1,<2.6 - paho-mqtt>=2.1,<2.2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 74d1cfa..c58266e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,33 @@ # Changelog -## Unreleased +## 2.9.0 — SPAN release 202645, and the device ids real panels publish -**The shipped templates are all `ref_` templates: the two tandem templates are renamed, and the three `default_MAIN_` templates are removed.** +**PanelBench runs on `ebus-panel-sim` 0.11.0. Its generated templates are each panel's latest capture, on SPAN release 202645 where the emitter has one, +and a hardware 3.0 panel publishes the device ids a real one does.** The shipped templates are all `ref_` templates: the two tandem templates are renamed, +and the three `default_MAIN_` templates are removed. The `span-panel` integration carries a hardware 3.0 panel's entities across the change of ids at +release 202645 from v2.3.3 (in pre-release as v2.3.3b1). + +### Added + +- **PanelBench publishes the device ids a real panel does.** A hardware 3.0 panel names its circuits, its remote CT and its lugs by SPAN's numbers for them, + which it keeps while the ids around them change at release 202645: `circuit-` and `remote-ct-` before it, `{serial}-{hex16}-1-16-`, + `-1-42-` and `-1-21-2` from it. A circuit records its number as `circuit_number`, and the panel its segment as `panel_config.device_id_hex`, so the ids + follow `firmware_version` across the release. A template of a hardware 3.0 capture that keeps its panel's ids and a clone of such a panel record them as + the panel publishes them, and a circuit added in the dashboard takes the lowest number its panel's circuits leave. A MAIN 32, whose ids no release + changes, and a config that records no numbers publish as before. Since nothing scopes those ids to the panel before release 202645, a panel whose + device ids another running panel already publishes is refused at start, as one with a running serial is. The `span-panel` integration carries a panel's + entities across the change from v2.3.3 (in pre-release as v2.3.3b1). +- **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. 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. ### Changed @@ -20,6 +45,23 @@ 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, or on a firmware naming none, publishes each circuit's `connection/connection-point`. +- **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. Each keeps its serial (`sim-main32_r202639`, `sim-r202639-a`, `sim-r202639-c` and + `sim-r202639-e`), as a panel keeps its serial through a firmware upgrade, so Home Assistant keeps a panel run from one of them across the upgrade of + PanelBench. `ref_MAIN_32` keeps its devices' ids too. The hardware 3.0 templates (`ref_UNKNOWN_16`, `ref_MAIN_16`, `ref_MAIN_40`, `ref_MLO_24` and + `ref_MLO_48`) now publish their panels' own ids for their circuits and remote CT, and on release 202645 for their lugs, where they published hashed and + serial-scoped ones, so Home Assistant sees those devices as new. - **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,20 +79,33 @@ 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, nor anything it + would feed. A `pv.feed` or `bess.feed` naming one is refused. +- **A breaker rating edited in the dashboard is published.** The edit writes the circuit's own rating, which the dashboard showed while the panel went on + publishing its template's. The engine, the panel's definition, validation and the dashboard's view of a circuit now all read it by its template with + the circuit's overrides and own rating over it, so what is checked is what is modelled, published and shown. A hand-written override outside the + energy profile, such as `relay_behavior`, which only the engine applied, is published too, and a rating must be above 0. +- **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`, + `bess.charge_hours: 5` or a template's `power_range: {min: 50, max: 150}`, is refused by name, a circuit's `overrides` as they leave its template, where + the panel failed to start or tick with an error naming nothing; a number may still be quoted where it is read as one. + A `total_tabs` that is no SPAN panel's size, or a latitude or longitude off the globe, which the dashboard's form allowed, and a battery of 0 kWh or a + discharge efficiency of 0, which failed on its first tick, are refused. A template no circuit uses is read by nothing, so it is checked for its shape + alone. 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. ### Removed - **`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. -### 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/DEVELOPER.md b/DEVELOPER.md index d991c75..a30108a 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -363,6 +363,12 @@ 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 + # The 16 hex digits a hardware 3.0 panel's numbered devices publish under from release 202645, {serial}-{hex16}-1-16- + # (instance_ids); absent, one is derived from the serial + device_id_hex: str 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) @@ -447,6 +453,9 @@ circuits: name: str # Human-readable name template: str # References a circuit_templates key tabs: [int] # Tab positions ([1] = 120V, [1, 3] = 240V) + # SPAN's number for the circuit on hardware 3.0, kept across releases: published as circuit-, then + # {serial}-{hex16}-1-16- from release 202645; absent, the circuit keeps its hashed id + circuit_number: int breaker_rating: int # Per-circuit override (optional) pcs_priority: int | null # Published as pcs/priority (default: the circuit's position). null records a panel that @@ -473,9 +482,10 @@ unmapped_tabs: [int] # Tab numbers with no circuit assigned outside_meters: # A meter the panel reads that sits outside it, on no breaker space; one at most - id: str # Scopes its device id, as a circuit's id does unvalued: [str] + circuit_number: int # SPAN's number for it as a remote CT: remote-ct-, then {serial}-{hex16}-1-42- 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 @@ -611,7 +621,10 @@ ebus/5/{serial}/{node}/{property} | `power-flows` | Aggregated: PV, battery, grid, site power | `{circuit-uuid}` is a UUID v5 over `{panel-serial}/{circuit-id}`. It is scoped to the panel because the shipped configs reuse circuit ids such as -`solar_inverter` across panel sizes, and two panels in one add-on publish to one broker. +`solar_inverter` across panel sizes, and two panels in one add-on publish to one broker. A hardware 3.0 panel whose config numbers its circuits +(`circuit_number`) names them instead as such a panel does: `circuit-` before release 202645 and `{panel-serial}-{hex16}-1-16-` from it (see the +README's Device ids). Before 202645 nothing scopes those ids to the panel, as a real panel's own broker needs nothing to, so PanelBench refuses to start a +panel whose device ids another running panel already publishes. ### Settable Properties @@ -728,6 +741,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 205d036..f54325c 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Click a simulator configuration to view it. Templates are read-only. A running s ## Home Assistant App PanelBench installs as a Home Assistant app from this repository. Images are published for `amd64` and `aarch64`, and the app is not distributed through HACS. -It requires the `span-panel` integration **v2.1.2 or later**, which reads the SPAN firmware release 202639 the shipped templates publish. The +It requires the `span-panel` integration **v2.1.2 or later**, which reads the SPAN firmware release 202639 the two tracked templates publish. The [reference panels](#templates), and `ref_MLO_48_TANDEMS.yaml`, which is built from one, need **v2.2.0 or later**; its tandem-quad is drawn and judged correctly from **v2.3.0**. @@ -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 @@ -390,15 +393,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 @@ -411,6 +419,10 @@ 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. 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. @@ -428,9 +440,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. @@ -442,8 +456,68 @@ 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 +``` + +### Device ids + +A hardware 3.0 panel names each circuit by SPAN's number for it, ``, which it keeps across releases while the id around it changes at release 202645, and +PanelBench publishes the same ids: + +| Device | before release 202645 | from release 202645 | +|---|---|---| +| circuit | `circuit-` | `{serial}-{hex16}-1-16-` | +| remote CT (`outside_meters`) | `remote-ct-` | `{serial}-{hex16}-1-42-` | +| lugs | `{serial}-lugs-up`, `{serial}-lugs-dn` | `{serial}-{hex16}-1-21-2` upstream | + +A circuit records its number as `circuit_number`, a remote CT its own, and the panel its 16-hex segment as `panel_config.device_id_hex`; the ids follow +`firmware_version`, a firmware naming no release taking the later shape. A template of a hardware 3.0 capture that keeps its panel's ids, and a clone of +such a panel, record them as the panel publishes them, and a circuit added in the dashboard takes the lowest number its panel's circuits leave. A MAIN 32 keeps its ids on every release, +and a config that records no numbers publishes the ids it always has. No capture shows a hardware 3.0 panel's downstream lugs from release 202645, so +`{serial}-{hex16}-1-21-1` is a guess. Before release 202645 nothing scopes these ids to the panel, as a real panel's own broker needs nothing to, so +PanelBench refuses to start a panel whose device ids another panel it runs already publishes. The `span-panel` integration carries a panel's entities across +the change of ids from **v2.3.3** (in pre-release as v2.3.3b1). + +```yaml +panel_config: + device_id_hex: d3c25547dc2d6690 +circuits: + - id: circuit_1 + circuit_number: 1 +``` + +### 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. 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: 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: + enabled: true + inverter_type: hybrid + pv_array: + nameplate_capacity_w: 7600 +``` ## Environment Variables diff --git a/panelbench/CHANGELOG.md b/panelbench/CHANGELOG.md index cb8ae00..52205ff 100644 --- a/panelbench/CHANGELOG.md +++ b/panelbench/CHANGELOG.md @@ -1,8 +1,23 @@ # Changelog -## Unreleased +## 2.9.0 — 2026-11-20 -The shipped templates are now all `ref_` templates, and the three `default_MAIN_` templates are removed. +Runs on `ebus-panel-sim` 0.11.0: the generated templates are each panel's latest capture, on SPAN release 202645 where there is one, and hardware 3.0 +panels publish the device ids real ones do. The shipped templates are now all `ref_` templates, and the three `default_MAIN_` templates are removed. + +### Added + +- **Hardware 3.0 panels publish the device ids a real panel does**, by SPAN's number for each circuit, changing shape at release 202645 as the panel's do. + Configs that record no numbers publish as before. The circuits of `ref_UNKNOWN_16`, `ref_MAIN_16`, `ref_MAIN_40`, `ref_MLO_24` and `ref_MLO_48` come back + to Home Assistant as new devices, since they now publish their panels' own ids; the SpanPanel/span integration carries a panel's entities across the + change of ids at release 202645 from v2.3.3 (in pre-release as v2.3.3b1). A panel whose device ids another running panel publishes is refused at start. +- **`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. 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. ### Changed @@ -15,6 +30,13 @@ 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. +- **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. 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. Each keeps its serial, so Home Assistant keeps the panel. - **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 +44,18 @@ 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. +- **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 breaker rating edited in the dashboard is published**, where the panel went on publishing the template's. +- **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 - **`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. -### 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..83a98f6 100644 --- a/panelbench/DOCS.md +++ b/panelbench/DOCS.md @@ -140,15 +140,21 @@ 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 integration **v2.1.2 or later**. `ref_MLO_48_TANDEMS` reports hardware version `3.0`, as the reference MLO 48 it is built from does; read it, and the `ref_` templates, with **v2.2.0 or later**. Its tandem-quad is drawn and -judged correctly from **v2.3.0**. +judged correctly from **v2.3.0**. A hardware 3.0 panel publishes the +device ids a real one does, which change at SPAN release 202645; the +integration carries its entities across that change from **v2.3.3** (in +pre-release as v2.3.3b1). To emulate a panel before the upgrade to release 202639, clone a config from the dashboard, then in the clone's YAML name a 202633 @@ -167,6 +173,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/panelbench/Dockerfile b/panelbench/Dockerfile index d21a1cc..c8a8af8 100644 --- a/panelbench/Dockerfile +++ b/panelbench/Dockerfile @@ -32,7 +32,7 @@ EXPOSE 18883 8081 18080 LABEL io.hass.name="SPAN PanelBench" \ io.hass.description="Simulates a SPAN electrical panel for testing and upgrade modeling" \ io.hass.type="addon" \ - io.hass.version="2.8.0" \ + io.hass.version="2.9.0" \ io.hass.arch="aarch64|amd64" CMD ["/run.sh"] diff --git a/panelbench/README.md b/panelbench/README.md index 0af89f3..b3b9b0e 100644 --- a/panelbench/README.md +++ b/panelbench/README.md @@ -17,10 +17,13 @@ This App emulates SPAN firmware `r202633+`, the first to publish the parent/child device tree (`data-model-version` `1.x`). Requires the SpanPanel/span integration **v2.1.2 or later**, which -reads the SPAN firmware release 202639 the shipped templates publish. +reads the SPAN firmware release 202639 the two tracked templates publish. The `ref_` templates of real SPAN panels, and `ref_MLO_48_TANDEMS` built from one, need **v2.2.0 or later**. Its tandem-quad is drawn and judged correctly from **v2.3.0**. +A hardware 3.0 panel's entities are carried across the change of its +device ids at SPAN release 202645 from **v2.3.3** (in pre-release as +v2.3.3b1). Visit [SPAN PanelBench](https://github.com/SpanPanel/panelbench) page for more details. diff --git a/panelbench/config.yaml b/panelbench/config.yaml index 6db4cc2..6809c4f 100644 --- a/panelbench/config.yaml +++ b/panelbench/config.yaml @@ -1,6 +1,6 @@ name: "SPAN PanelBench" description: "Simulates a SPAN electrical panel for testing and upgrade modeling" -version: "2.8.0" +version: "2.9.0" slug: "panelbench" url: "https://github.com/SpanPanel/panelbench" image: "ghcr.io/spanpanel/panelbench/{arch}" diff --git a/pyproject.toml b/pyproject.toml index 0b62888..cd021c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "panelbench" -version = "2.8.0" +version = "2.9.0" description = "Standalone eBus simulator for SPAN panels" requires-python = ">=3.14" dependencies = [ @@ -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/__init__.py b/src/panelbench/__init__.py index fadc8af..28d9d74 100644 --- a/src/panelbench/__init__.py +++ b/src/panelbench/__init__.py @@ -1,3 +1,3 @@ """Standalone eBus simulator for SPAN panels.""" -__version__ = "2.8.0" +__version__ = "2.9.0" diff --git a/src/panelbench/app.py b/src/panelbench/app.py index 017ecfb..c25886b 100644 --- a/src/panelbench/app.py +++ b/src/panelbench/app.py @@ -35,7 +35,6 @@ from panelbench.discovery import PanelAdvertiser, PanelBrowser from panelbench.emitter_adapter.runtime import BrokerConnection from panelbench.panel import PanelInstance -from panelbench.panel_models import PANEL_SIZE_TO_MODEL from panelbench.panel_secrets import SECRETS_FILENAME, PanelSecretsStore from panelbench.recorder import RecorderDataSource from panelbench.schema import HomieSchemaRegistry, load_schema, render_for_panel @@ -223,13 +222,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) @@ -319,17 +318,19 @@ async def _start_panel(self, config_path: Path) -> PanelInstance: broker=broker, ) serial = await panel.start( - running={s: p.config_path for s, p in self._serial_to_panel.items()} + running={ + device_id: p.config_path + for p in self._serial_to_panel.values() + for device_id in p.device_ids + } ) - # Validate panel size and render schema before registering. If the - # panel's total_tabs is not a SPAN model size, stop the started panel - # cleanly so we don't leave a zombie tick task and MQTT publisher - # without a bootstrap HTTP server to match. + # Render the schema before registering, the panel's size having passed + # validation as it loaded. If anything here fails, stop the started panel + # cleanly so we don't leave a zombie tick task and MQTT publisher without a + # bootstrap HTTP server to match. try: total_tabs = panel.total_tabs - if total_tabs not in PANEL_SIZE_TO_MODEL: - raise KeyError(f"total_tabs {total_tabs} is not a SPAN panel size") # The model MQTT publishes, so mDNS cannot advertise another. panel_model = panel.model firmware = panel.firmware_version diff --git a/src/panelbench/circuit.py b/src/panelbench/circuit.py index a1c9a13..a96b43f 100644 --- a/src/panelbench/circuit.py +++ b/src/panelbench/circuit.py @@ -9,9 +9,19 @@ from __future__ import annotations from copy import deepcopy -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Final, cast + +from panelbench.virtual_devices import on_the_panel + +# The circuit overrides that land in its template's energy profile; any other lands in +# the template itself. +OVERRIDDEN_PROFILE_KEYS: Final = frozenset( + {"mode", "power_range", "typical_power", "power_variation", "efficiency"} +) if TYPE_CHECKING: + from collections.abc import Mapping + from panelbench.config_types import ( CircuitDefinitionExtended, CircuitTemplateExtended, @@ -19,6 +29,45 @@ from panelbench.engine import RealisticBehaviorEngine +def effective_template( + template: CircuitTemplateExtended, circuit: CircuitDefinitionExtended +) -> CircuitTemplateExtended: + """*circuit*'s template as the panel models and publishes it + (``effective_settings``), for code reading a validated config.""" + # The template's keys, set from the circuit's settings under the same keys, which + # validation checks on this result as it checks a template's own. + return cast("CircuitTemplateExtended", effective_settings(template, circuit)) + + +def effective_settings( + template: Mapping[str, object], circuit: Mapping[str, object] +) -> dict[str, object]: + """*circuit*'s template as the panel models and publishes it. + + A copy of *template* with the circuit's own ``recorder_entity``, its ``overrides`` + (``OVERRIDDEN_PROFILE_KEYS`` into the energy profile, any other into the template), + and its own ``breaker_rating``, which replaces the template's under either key, as + the dashboard's rating edit writes it. The engine, the definition and validation + all read a circuit through this, so what is checked is what is modelled, and what + is modelled is what is published. + """ + merged: dict[str, object] = deepcopy(dict(template)) + recorder_entity = circuit.get("recorder_entity") + if recorder_entity is not None: + merged["recorder_entity"] = recorder_entity + profile = merged.get("energy_profile") + overrides = circuit.get("overrides") + for key, value in overrides.items() if isinstance(overrides, dict) else (): + if key in OVERRIDDEN_PROFILE_KEYS and isinstance(profile, dict): + profile[key] = value + else: + merged[key] = value + if "breaker_rating" in circuit: + merged["breaker_rating"] = circuit["breaker_rating"] + merged.pop("breaker_rating_a", None) + return merged + + class SimulatedCircuit: """Encapsulates the state and logic for a single simulated circuit.""" @@ -29,35 +78,10 @@ def __init__( behavior_engine: RealisticBehaviorEngine, ) -> None: self._circuit_def = circuit_def - self._template = deepcopy(template) + # The circuit's recorder link, overrides and own rating, over its template. + self._template = effective_template(template, circuit_def) self._behavior_engine = behavior_engine - # Per-circuit recorder link lives on the circuit definition in YAML; - # merge it so behaviour engine / modeling see ``recorder_entity``. - rec_entity = circuit_def.get("recorder_entity") - if rec_entity is not None: - self._template["recorder_entity"] = rec_entity - - # Apply circuit-level overrides to the template, routing - # energy-profile keys into the nested ``energy_profile`` dict. - if "overrides" in circuit_def: - _ENERGY_PROFILE_KEYS = { - "mode", - "power_range", - "typical_power", - "power_variation", - "efficiency", - } - for key, value in circuit_def["overrides"].items(): - if key in _ENERGY_PROFILE_KEYS: - self._template["energy_profile"][key] = value # type: ignore[literal-required] - else: - self._template[key] = value # type: ignore[literal-required] - - # Circuit-level breaker_rating overrides template - if "breaker_rating" in circuit_def: - self._template["breaker_rating"] = circuit_def["breaker_rating"] - # Derived from template (stable across ticks) self._energy_mode: str = self._template["energy_profile"]["mode"] self._device_type_str: str = self._derive_device_type() @@ -166,6 +190,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 244d12f..72bbc30 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 @@ -31,6 +31,7 @@ from ebus_sdk import DiscoveredDevice from panelbench.breakers import breaker_misfit +from panelbench.device_numbers import hex_of, number_of from panelbench.emitter_adapter import commissioning from panelbench.hardware import publishes_shared_breakers, relay_locks_priority, variant_for from panelbench.panel_models import model_positions, panel_spaces, reported_model @@ -213,7 +214,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 @@ -278,7 +280,9 @@ def translate_panel_tree( for node_uuid in sorted(circuit_nodes): if _meters_outside_the_panel(devices, node_uuid): outside_meters.append( - _outside_meter(len(outside_meters) + 1, unvalued.get(node_uuid, [])) + _outside_meter( + len(outside_meters) + 1, unvalued.get(node_uuid, []), number_of(node_uuid) + ) ) continue result = _translate_circuit( @@ -317,8 +321,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, @@ -347,6 +351,14 @@ 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 segment a hardware 3.0 panel's numbered devices publish under from release + # 202645, where its ids carry one. + if (segment := hex_of(panel_device_id, devices)) is not None: + panel_config["device_id_hex"] = segment # 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 @@ -369,6 +381,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: @@ -421,6 +435,8 @@ 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) + template_of = _template_by_circuit(config) changed = False @@ -428,36 +444,25 @@ def update_config_from_scrape( if node_uuid not in keys: continue - template_name = _template_name(keys[node_uuid]) - template = templates.get(template_name) - if not isinstance(template, dict): - continue - - ep = template.get("energy_profile") - if not isinstance(ep, dict): - continue - # 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") - if ( - exported is not None - and exported > 0 - and ep.get("initial_consumed_energy_wh") != exported + # comment in `_translate_circuit`. A breaker the config records takes its one + # register on each of its circuits, a circuit the scrape left out included. + mates = shared.get(_circuit_id(keys[node_uuid]), []) + breaker = _breaker_nodes(node_uuid, keys, mates) + exported = _breaker_register(scraped.devices, breaker, "exported-energy") + imported = _breaker_register(scraped.devices, breaker, "imported-energy") + own = _template_name(keys[node_uuid]) + for template_name in dict.fromkeys( + [own, *(template_of[m] for m in mates if m in template_of)] ): - ep["initial_consumed_energy_wh"] = exported - changed = True - - imported = _float_prop(scraped.devices, node_uuid, "meter", "imported-energy") - if ( - imported is not None - and imported > 0 - and ep.get("initial_produced_energy_wh") != imported - ): - ep["initial_produced_energy_wh"] = imported - changed = True + template = templates.get(template_name) + ep = template.get("energy_profile") if isinstance(template, dict) else None + if not isinstance(ep, dict): + continue + changed = _seed(ep, "initial_consumed_energy_wh", exported) or changed + changed = _seed(ep, "initial_produced_energy_wh", imported) or changed # Update last_synced timestamp panel_source = config.get("panel_source") @@ -1021,9 +1026,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] = { @@ -1076,6 +1083,10 @@ def _translate_circuit( "pcs_priority": _int_prop(devices, node_uuid, "pcs", "priority"), **commissioning.config_values(commissioning.CIRCUIT, _published_by(devices, node_uuid)), } + # SPAN's number for the circuit, which its id carries on hardware 3.0 and which it + # keeps across releases: the clone publishes its ids as the panel does. + if (number := number_of(node_uuid)) is not None: + circuit_def["circuit_number"] = number shared = siblings.get(node_uuid) if shared: circuit_def["shared_with"] = shared @@ -1106,18 +1117,29 @@ def _meters_outside_the_panel(devices: Mapping[str, DiscoveredDevice], node_uuid return "spaces" not in device.get_node_properties("info") -def _outside_meter(ordinal: int, unvalued: list[str]) -> dict[str, object]: +def _outside_meter(ordinal: int, unvalued: list[str], number: int | None) -> dict[str, object]: """A meter outside the panel, as ``outside_meters`` holds it. Its id is its place among the panel's such meters, as a circuit's is its first - space: the panel publishes nothing else to tell them apart. + space: the panel publishes nothing else to tell them apart. *number* is SPAN's + for it as a remote CT, where its id carries one. """ meter: dict[str, object] = {"id": f"outside_meter_{ordinal}"} + if number is not None: + meter["circuit_number"] = number if unvalued: meter["unvalued"] = unvalued 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, @@ -1183,7 +1205,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, ) @@ -1210,6 +1232,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: @@ -1531,6 +1570,62 @@ 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 _seed(energy_profile: dict[str, object], key: str, register: float | None) -> bool: + """Seed *key* with a register read above 0, and say whether that changed it.""" + if register is None or register <= 0 or energy_profile.get(key) == register: + return False + energy_profile[key] = register + return True + + +def _template_by_circuit(config: Mapping[str, object]) -> dict[str, str]: + """Each of *config*'s circuits' template, by the circuit's id.""" + circuits = config.get("circuits") + return { + str(circuit["id"]): str(circuit["template"]) + for circuit in (circuits if isinstance(circuits, list) else []) + if isinstance(circuit, dict) and "id" in circuit and "template" in circuit + } + + +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/config_types.py b/src/panelbench/config_types.py index 2bbe1b2..a1c21b0 100644 --- a/src/panelbench/config_types.py +++ b/src/panelbench/config_types.py @@ -69,6 +69,13 @@ 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] + # The 16 hex digits a hardware 3.0 panel's numbered devices are published under + # from release 202645, `{serial}-{hex16}-1-16-` (`device_numbers`). + device_id_hex: NotRequired[str] 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: @@ -155,6 +162,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.""" @@ -180,6 +193,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 @@ -271,6 +288,9 @@ class OutsideMeterYAML(TypedDict): id: str unvalued: NotRequired[list[str]] + # SPAN's number for the meter, as a remote CT: `remote-ct-`, or `…-1-42-` + # from release 202645 (`device_numbers`). + circuit_number: NotRequired[int] class BrokerConfigYAML(TypedDict, total=False): @@ -334,6 +354,9 @@ class CircuitDefinitionExtended(CircuitDefinition, total=False): overrides: dict[str, Any] breaker_rating: int # Per-circuit breaker rating in Amps (overrides template) recorder_entity: str # HA entity for recorder replay (also merged onto resolved template) + # SPAN's number for the circuit, kept across releases while the id around it + # changes: `circuit-`, then `{serial}-{hex16}-1-16-` (`device_numbers`). + circuit_number: int # The identity of the device this circuit feeds: a DER's identity belongs to the # circuit, not to its position in a list (see `instance_ids.evse_circuit_serial`). # Read for a PV circuit's inverter, where the top-level `pv` section is the diff --git a/src/panelbench/dashboard/config_store.py b/src/panelbench/dashboard/config_store.py index da67483..cc6d330 100644 --- a/src/panelbench/dashboard/config_store.py +++ b/src/panelbench/dashboard/config_store.py @@ -20,6 +20,8 @@ import yaml +from panelbench.circuit import effective_settings +from panelbench.device_numbers import next_number from panelbench.inverter import AC_COUPLED, normalise_inverter_type, template_inverter_type from panelbench.pv_section import UNFED_INVERTER_POSITION, unfed_inverter_entries @@ -423,6 +425,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) @@ -527,17 +537,16 @@ def toggle_user_modified(self, entity_id: str) -> bool: return not current def _merge_entity(self, circuit: dict[str, Any]) -> EntityView: - """Build an EntityView by merging template + circuit overrides.""" + """An EntityView of *circuit* as the panel has it: its template with the + circuit's overrides and own rating over it (``circuit.effective_settings``), + which the engine models and the panel publishes, so the dashboard shows, and + its lock guards judge, the same.""" template_name = circuit["template"] - template = deepcopy(self._templates().get(template_name, {})) - + template: dict[str, Any] = effective_settings( + self._templates().get(template_name, {}), circuit + ) overrides = circuit.get("overrides", {}) energy_profile = dict(template.get("energy_profile", {})) - for k, v in overrides.items(): - if k == "power_range": - energy_profile["power_range"] = v - elif k in energy_profile: - energy_profile[k] = v return EntityView( id=circuit["id"], @@ -553,7 +562,8 @@ def _merge_entity(self, circuit: dict[str, Any]) -> EntityView: time_of_day_profile=template.get("time_of_day_profile"), smart_behavior=template.get("smart_behavior"), hvac_type=template.get("hvac_type"), - breaker_rating=circuit.get("breaker_rating") or template.get("breaker_rating"), + # As the definition reads it: the legacy key first. + breaker_rating=template.get("breaker_rating_a") or template.get("breaker_rating"), overrides=dict(overrides), recorder_entity=template.get("recorder_entity"), user_modified=bool(template.get("user_modified")), @@ -615,10 +625,22 @@ 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): + 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", {}) ep = template.get("energy_profile", {}) @@ -703,6 +725,9 @@ def add_entity(self, entity_type: str) -> EntityView: circuit_dict["id"] = entity_id counter += 1 + # A panel that numbers its circuits numbers this one too, as SPAN would. + if (number := next_number(self._state)) is not None: + circuit_dict["circuit_number"] = number self._templates()[template_name] = template_dict self._circuits().append(circuit_dict) self._dirty = True @@ -765,6 +790,9 @@ def add_entity_from_tabs(self, tabs: list[int]) -> EntityView: circuit_dict["id"] = entity_id counter += 1 + # A panel that numbers its circuits numbers this one too, as SPAN would. + if (number := next_number(self._state)) is not None: + circuit_dict["circuit_number"] = number self._templates()[template_name] = template_dict self._circuits().append(circuit_dict) self._dirty = True @@ -789,9 +817,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/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/definition_import.py b/src/panelbench/definition_import.py index 92fafbc..924e88e 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 @@ -86,14 +89,32 @@ def config_from_definition(definition: PanelDefinition) -> dict[str, object]: config = translate_panel_tree( panels[0].instance_id, discovered_devices(_render(definition)), variant=variant ) + _drop_device_numbers(config) _overlay_emitter_options(config, definition) return config +def _drop_device_numbers(config: dict[str, object]) -> None: + """Forget the device numbers the translation read from the rendered tree. + + A definition's ids are its own, masked and renumbered in space order where it + was captured from a panel, so the numbers they carry are no panel's: an import + publishes the hashed ids a config with none does. + """ + for section in ("circuits", "outside_meters"): + entries = config.get(section) + for entry in entries if isinstance(entries, list) else []: + if isinstance(entry, dict): + entry.pop("circuit_number", None) + panel = config.get("panel_config") + if isinstance(panel, dict): + panel.pop("device_id_hex", None) + + 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 @@ -108,6 +129,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/device_numbers.py b/src/panelbench/device_numbers.py new file mode 100644 index 0000000..ba880e4 --- /dev/null +++ b/src/panelbench/device_numbers.py @@ -0,0 +1,73 @@ +"""SPAN's number for each of a panel's circuits, and the id segment they publish under. + +A hardware 3.0 panel numbers its circuits, and the meters outside it, and keeps each +number across releases while the id around it changes: ``circuit-`` and +``remote-ct-`` before release 202645, ``{serial}-{hex16}-1-16-`` and +``{serial}-{hex16}-1-42-`` from it, every id of one panel sharing one 16-hex +segment. A config records the number of each (``circuit_number``) and the segment +(``panel_config.device_id_hex``), read here from the ids a panel publishes, so the +ids PanelBench publishes follow the release as the panel's do +(``emitter_adapter.instance_ids``). +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Final + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +# A circuit's or remote CT's id, either release's, with its number in one group. +_NUMBERED: Final = re.compile(r"(?:circuit|remote-ct)-(\d+)|.+-1-(?:16|42)-(\d+)") + + +def number_of(device_id: str) -> int | None: + """SPAN's number for the circuit or remote CT *device_id* names, or None for an + id that carries none: a MAIN 32's, the lugs', or PanelBench's own hashed one.""" + match = _NUMBERED.fullmatch(device_id) + if match is None: + return None + return int(match.group(1) or match.group(2)) + + +def is_remote_ct(device_id: str) -> bool: + """Whether *device_id* names a meter outside the panel: ``remote-ct-``, or + ``…-1-42-`` from release 202645.""" + return re.fullmatch(r"remote-ct-\d+|.+-1-42-\d+", device_id) is not None + + +def hex_of(root_id: str, device_ids: Iterable[str]) -> str | None: + """The 16-hex segment the panel *root_id* publishes its numbered devices under, as + the first of *device_ids* shaped ``{root_id}-{hex16}-1--`` has it; None + where none is, as before release 202645.""" + shaped = re.compile(rf"{re.escape(root_id)}-([0-9a-f]{{16}})-1-\d+-\d+") + for device_id in device_ids: + if (match := shaped.fullmatch(device_id)) is not None: + return match.group(1) + return None + + +def next_number(config: Mapping[str, object]) -> int | None: + """The lowest number above 0 none of *config*'s circuits uses, for a circuit added + to it; None on a panel that numbers none of its devices. A remote CT's number is + no circuit's: SPAN numbers the two apart.""" + used = { + number + for entry in _listed(config.get("circuits")) + if isinstance(number := entry.get("circuit_number"), int) + } + numbered = used or any( + isinstance(entry.get("circuit_number"), int) + for entry in _listed(config.get("outside_meters")) + ) + if not numbered: + return None + number = 1 + while number in used: + number += 1 + return number + + +def _listed(value: object) -> list[Mapping[str, object]]: + return [entry for entry in value if isinstance(entry, dict)] if isinstance(value, list) else [] diff --git a/src/panelbench/emitter_adapter/definition.py b/src/panelbench/emitter_adapter/definition.py index 9cf5cdf..d028fe5 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,21 @@ 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 + already hands *transport* the device tree it describes; ``start`` begins the + panel's life on it. 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/instance_ids.py b/src/panelbench/emitter_adapter/instance_ids.py index a0d2b97..d5b5c5c 100644 --- a/src/panelbench/emitter_adapter/instance_ids.py +++ b/src/panelbench/emitter_adapter/instance_ids.py @@ -20,6 +20,14 @@ PV, several -- MID -mid +except on a hardware 3.0 panel whose config numbers its circuits +(``circuit_number``), which names them as such a panel does: by SPAN's number +for each, ````, under the shape its release gives it (``circuit_device_id``). + + Circuit circuit-, then --1-16- from 202645 + Remote CT remote-ct-, then --1-42- + Lugs --1-21-2 upstream from 202645 + `devices/distribution-enclosure.md` Example 1 shows the proxied form concretely: `xy-0001-aaaaa-lugs-up`, `xy-0001-aaaaa-TG000000000001` (panel + the BESS's own serial), `xy-0001-aaaaa-pv-1`, `xy-0001-aaaaa-TG000000000001-mid`. @@ -34,9 +42,13 @@ from __future__ import annotations +import hashlib import re import uuid -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Final + +from panelbench.firmware import SPAN_RELEASE_202645, panel_firmware_version, predates +from panelbench.hardware import panel_variant if TYPE_CHECKING: from collections.abc import Mapping @@ -71,9 +83,112 @@ def stable_circuit_uuid(panel_id: str, circuit_id: str) -> str: return str(uuid.uuid5(_CIRCUIT_NAMESPACE, f"{panel_id}/{circuit_id}")).replace("-", "") -def lugs_device_ids(panel_id: str) -> tuple[str, str]: - """Upstream and downstream lugs device ids, in that order.""" - return f"{panel_id}-lugs-up", f"{panel_id}-lugs-dn" +# The SPAN traits a hardware 3.0 panel numbers its devices by from release 202645, +# `{serial}-{hex16}-1--`, as every r202645 capture publishes them. +_CIRCUIT_TRAIT: Final = 16 +_REMOTE_CT_TRAIT: Final = 42 +_LUGS_TRAIT: Final = 21 +# Before release 202645 a numbered device is `-`, under no root. +_BEFORE_202645: Final = {_CIRCUIT_TRAIT: "circuit", _REMOTE_CT_TRAIT: "remote-ct"} +# The variant whose panels number their devices: hardware 3.0's. +_NUMBERING_VARIANT: Final = "span-alpha-test-b2" + + +def circuit_device_id(config: Mapping[str, object], circuit: Mapping[str, object]) -> str: + """The device id the panel *config* describes publishes *circuit* under. + + A hardware 3.0 panel names a circuit by SPAN's number for it, ````, which it + keeps while the id around it changes at release 202645: ``circuit-`` + before it, ``{serial}-{hex16}-1-16-`` from it, as its captures show. A + firmware naming no release is current. Anything else keeps the hashed id + (``stable_circuit_uuid``): a MAIN 32, whose ids no release changes, and a + circuit, or a whole panel, a config records no number for, so a config written + before numbers publishes as it did. + """ + number = _number(circuit) + if number is None or not _names_by_number(config): + return stable_circuit_uuid(_serial(config), str(circuit["id"])) + return _numbered_id(config, _CIRCUIT_TRAIT, number) + + +def outside_meter_device_id(config: Mapping[str, object], meter: Mapping[str, object]) -> str: + """The device id a meter outside the panel publishes under: a remote CT's, + ``remote-ct-`` and then ``{serial}-{hex16}-1-42-``, as + ``circuit_device_id`` names a circuit, and hashed from its ``id`` otherwise.""" + number = _number(meter) + if number is None or not _names_by_number(config): + return stable_circuit_uuid(_serial(config), str(meter["id"])) + return _numbered_id(config, _REMOTE_CT_TRAIT, number) + + +def lugs_device_ids(config: Mapping[str, object]) -> tuple[str, str]: + """Upstream and downstream lugs device ids, in that order. + + ``{serial}-lugs-up`` and ``-dn``, except on a numbered hardware 3.0 panel from + release 202645, whose lugs are numbered devices too: its upstream lugs are + ``{serial}-{hex16}-1-21-2`` in every r202645 capture. No capture shows such a + panel's downstream lugs, every one of them having no feedthrough, so + ``-1-21-1`` is a guess. + """ + serial = _serial(config) + if _names_by_number(config) and not predates( + panel_firmware_version(config), SPAN_RELEASE_202645 + ): + segment = device_id_hex(config) + return ( + f"{serial}-{segment}-1-{_LUGS_TRAIT}-2", + f"{serial}-{segment}-1-{_LUGS_TRAIT}-1", # a guess: see above + ) + return f"{serial}-lugs-up", f"{serial}-lugs-dn" + + +def device_id_hex(config: Mapping[str, object]) -> str: + """The 16-hex segment the panel's numbered devices publish under from release + 202645: the one ``panel_config.device_id_hex`` records, or else one of the + panel's own, derived from its serial so it holds from one start to the next.""" + panel = config.get("panel_config") + recorded = panel.get("device_id_hex") if isinstance(panel, dict) else None + if isinstance(recorded, str): + return recorded + return hashlib.sha256(_serial(config).encode()).hexdigest()[:16] + + +def _names_by_number(config: Mapping[str, object]) -> bool: + """Whether *config*'s panel names its devices by number: hardware 3.0's variant, + with a number recorded for any of its circuits or meters outside it.""" + if panel_variant(config) != _NUMBERING_VARIANT: + return False + return any( + isinstance(entry, dict) and _number(entry) is not None + for section in ("circuits", "outside_meters") + for entry in _entries(config.get(section)) + ) + + +def _numbered_id(config: Mapping[str, object], trait: int, number: int) -> str: + if predates(panel_firmware_version(config), SPAN_RELEASE_202645): + return f"{_BEFORE_202645[trait]}-{number}" + return f"{_serial(config)}-{device_id_hex(config)}-1-{trait}-{number}" + + +def _number(entry: Mapping[str, object]) -> int | None: + """An entry's ``circuit_number``, which validation has made a whole number.""" + number = entry.get("circuit_number") + if isinstance(number, bool) or not isinstance(number, (int, float)): + return None + return int(number) + + +def _entries(value: object) -> list[object]: + return value if isinstance(value, list) else [] + + +def _serial(config: Mapping[str, object]) -> str: + """The serial the panel publishes as its root id.""" + panel = config.get("panel_config") + if not isinstance(panel, dict): + raise ValueError("a panel's devices are named under its panel_config.serial_number") + return str(panel["serial_number"]) def bess_device_id(panel_id: str, bess: Mapping[str, object] | None) -> str: diff --git a/src/panelbench/emitter_adapter/runtime.py b/src/panelbench/emitter_adapter/runtime.py index 2013fcf..1a25091 100644 --- a/src/panelbench/emitter_adapter/runtime.py +++ b/src/panelbench/emitter_adapter/runtime.py @@ -35,11 +35,16 @@ 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 ( + circuit_device_id, evse_device_id, - stable_circuit_uuid, ) +from panelbench.emitter_adapter.spec_generator import circuits_for_device_type from panelbench.emitter_adapter.transport import LoopBoundTransport if TYPE_CHECKING: @@ -81,24 +86,49 @@ class CloneRuntime: lifecycle, which is the same rule the SDK follows for an injected client.""" +def published_device_ids(engine: DynamicSimulationEngine) -> frozenset[str]: + """Every device id the panel *engine* runs would publish, its own serial first + among them: what another panel on the same broker must not publish too.""" + return frozenset(d.instance_id for d in build_definition(engine.config).manifest.instances) + + def bess_config_from_engine(engine: DynamicSimulationEngine) -> BESSConfig | None: """Build the emitter-side BESSConfig from the engine's loaded clone profile. Returns None when the profile has no BESS enabled.""" 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, 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. """ + 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 None: - return - runtime.emitter.update_bess_config(new_cfg) + runtime.emitter.update_bess_config(battery) + return True + + +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.metadata.get("inverter-type") == "hybrid" + for battery in manifest.of_class("bess") + } def _resolve_broker( @@ -158,13 +188,10 @@ async def start_clone( definition = build_definition(engine.config) manifest = definition.manifest - panel_id = engine.config["panel_config"]["serial_number"] uuid_to_circuit_id = { - stable_circuit_uuid(panel_id, c["id"]): c["id"] for c in engine.config["circuits"] + circuit_device_id(engine.config, c): 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 @@ -202,7 +229,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. @@ -248,6 +275,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, raw.bess_pv_w), ) return runtime.emitter.publish_tick(tick) @@ -266,6 +294,17 @@ def _bess_communication( return {} if battery is None else {battery.instance_id: link} +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, 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 not _started_batteries(runtime.manifest).get(battery.instance_id): + return {} + return {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. @@ -345,24 +384,12 @@ def _first_feed_for_device_type(config: SimulationConfig, device_type: str) -> s def _feeds_for_device_type(config: SimulationConfig, device_type: str) -> list[str]: - templates = config.get("circuit_templates") - circuits = config.get("circuits") - if not isinstance(templates, dict) or not isinstance(circuits, list): - return [] + """The device ids of the circuits feeding *device_type* devices, from the one list + the manifest builds them from (``spec_generator.circuits_for_device_type``).""" # Read from the config being walked, not from a serial handed in beside it: a # feed id must be the id the *owner* of these circuits publishes, and taking # both from one mapping is what makes that true by construction. - panel_id = config["panel_config"]["serial_number"] - feeds: list[str] = [] - for item in circuits: - if not isinstance(item, dict): - continue - template_name = item.get("template") - if template_name is None or not isinstance(template_name, str): - continue - template = templates.get(template_name) - if isinstance(template, dict) and template.get("device_type") == device_type: - circuit_id = item.get("id") - if circuit_id is not None: - feeds.append(stable_circuit_uuid(panel_id, str(circuit_id))) - return feeds + return [ + circuit_device_id(config, circuit) + for circuit in circuits_for_device_type(config, device_type) + ] diff --git a/src/panelbench/emitter_adapter/spec_generator.py b/src/panelbench/emitter_adapter/spec_generator.py index 0b2abda..e521abe 100644 --- a/src/panelbench/emitter_adapter/spec_generator.py +++ b/src/panelbench/emitter_adapter/spec_generator.py @@ -16,26 +16,34 @@ from ebus_panel_sim import DeviceInstance, DeviceManifest +from panelbench.circuit import effective_template from panelbench.emitter_adapter import commissioning from panelbench.emitter_adapter.instance_ids import ( bess_device_id, + circuit_device_id, evse_circuit_serial, evse_device_id, evse_serial_number, lugs_device_ids, mid_device_id, + outside_meter_device_id, pv_device_id, pv_inverter_device_id, - 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, ) 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 @@ -58,7 +66,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 @@ -148,7 +156,7 @@ def _main_breaker(main_size: int | None) -> dict[str, str]: def _lugs_instances(profile: SimulationConfig) -> list[DeviceInstance]: - upstream_id, downstream_id = lugs_device_ids(profile["panel_config"]["serial_number"]) + upstream_id, downstream_id = lugs_device_ids(profile) lugs = profile.get("lugs") or {} # Named after their ids, as SPAN release 202639 names every device it proxies or # synthesizes: the captured MAIN 32 publishes its lugs, battery and MID that way. @@ -169,6 +177,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) ] @@ -178,10 +187,9 @@ def _outside_meter_instances(profile: SimulationConfig) -> list[DeviceInstance]: Named after its device id, which scopes its config ``id`` to the panel as a circuit's is scoped, because the panel publishes no other name for it. """ - panel_id = profile["panel_config"]["serial_number"] instances: list[DeviceInstance] = [] for meter in profile.get("outside_meters") or []: - instance_id = stable_circuit_uuid(panel_id, meter["id"]) + instance_id = outside_meter_device_id(profile, meter) instances.append( DeviceInstance( entity_class="remote-ct", @@ -194,14 +202,12 @@ def _outside_meter_instances(profile: SimulationConfig) -> list[DeviceInstance]: def _circuit_instances(profile: SimulationConfig) -> list[DeviceInstance]: - templates = profile.get("circuit_templates") or {} - 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): - tabs = c.get("tabs") or [0] - template_name = c.get("template", "") - template: CircuitTemplateExtended | None = templates.get(template_name) + published = [c for c in profile.get("circuits") or [] if on_the_panel(c)] + for idx, c in enumerate(published, start=1): + tabs = c["tabs"] + template = _template_of(profile, c) commissioned_system: str | None # What the circuit records as unpublished by a null rather than in `unvalued`. unpublished: list[str] = [] @@ -227,7 +233,7 @@ def _circuit_instances(profile: SimulationConfig) -> list[DeviceInstance]: if rating is None: unpublished.append("breaker/rating") relay_behavior = normalise_relay_behavior(relay_behavior_raw) - instance_id = stable_circuit_uuid(panel_id, c["id"]) + instance_id = circuit_device_id(profile, c) instances.append( DeviceInstance( entity_class="circuit", @@ -238,7 +244,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, @@ -282,7 +288,7 @@ def _circuit_instances(profile: SimulationConfig) -> list[DeviceInstance]: ), **_solar_role(profile, template), **commissioning.metadata(commissioning.CIRCUIT, c), - **_shared_with(panel_id, c), + **_shared_with(profile, c), **commissioning.unvalued_metadata(c.get("unvalued"), unpublished), }, ), @@ -306,12 +312,19 @@ def _solar_role( return {"feeds-role": "SOLAR"} # eBus connection/feeds-role SOLAR -def _shared_with(panel_id: str, circuit: CircuitDefinitionExtended) -> dict[str, str]: +def _shared_with(profile: SimulationConfig, circuit: CircuitDefinitionExtended) -> dict[str, str]: """The circuits sharing *circuit*'s meter and relay, by device id, where it names any.""" peers = circuit.get("shared_with") or [] if not peers: return {} - return {"shared-with-device-ids": ",".join(stable_circuit_uuid(panel_id, p) for p in peers)} + return {"shared-with-device-ids": ",".join(_named_device_id(profile, p) for p in peers)} + + +def _named_device_id(profile: SimulationConfig, circuit_id: str) -> str: + """The device id of the circuit whose config ``id`` is *circuit_id*, as a tandem's + lists and a battery's feed name it; validation has made sure there is one.""" + circuit = next(c for c in profile.get("circuits") or [] if str(c["id"]) == circuit_id) + return circuit_device_id(profile, circuit) def _energy_seeds(template: CircuitTemplateExtended | None) -> dict[str, str]: @@ -341,6 +354,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) @@ -351,9 +366,7 @@ def _bess_instance(profile: SimulationConfig) -> DeviceInstance | None: if "firmware_version" in bess_cfg: bess_meta["firmware-version"] = str(bess_cfg["firmware_version"]) if "feed" in bess_cfg: - bess_meta["feed"] = stable_circuit_uuid( - profile["panel_config"]["serial_number"], str(bess_cfg["feed"]) - ) + bess_meta["feed"] = _named_device_id(profile, str(bess_cfg["feed"])) if "initial_soe_kwh" in bess_cfg: bess_meta["initial-soe-kwh"] = str(bess_cfg["initial_soe_kwh"]) bess_meta.update(commissioning.unvalued_metadata(bess_cfg.get("unvalued"))) @@ -457,12 +470,11 @@ def _pv_instance(profile: SimulationConfig) -> DeviceInstance | None: relative_position = pv_cfg.get("relative_position") if relative_position is None: relative_position = "IN_PANEL" if circuit is not None else UNFED_INVERTER_POSITION - templates = profile.get("circuit_templates") or {} # With no PV circuit -- an inverter upstream of the panel, or a config written # before templates carried `device_type` -- the first producer's template is the # only one there is to read the inverter's type from. inverter_template = ( - templates.get(circuit["template"]) + _template_of(profile, circuit) if circuit is not None else _first_producer_template(profile) ) @@ -586,7 +598,7 @@ def _pv_instances(profile: SimulationConfig) -> list[DeviceInstance]: The inverters no circuit feeds that the section's ``inverters`` lists follow, each its own device (``_unfed_pv_instances``). """ - circuits = _circuits_for_device_type(profile, "pv") + circuits = circuits_for_device_type(profile, "pv") if len(circuits) < 2 or predates(panel_firmware_version(profile), SPAN_RELEASE_202639): single = _pv_instance(profile) fed = [] if single is None else [single] @@ -602,18 +614,17 @@ def _fed_pv_instances( panel_id = profile["panel_config"]["serial_number"] pv_cfg = profile.get("pv") or {} section_circuit = pv_section_circuit(profile) - templates = profile.get("circuit_templates") or {} instances: list[DeviceInstance] = [] for circuit in circuits: # The `pv` section describes one inverter, as it did when a panel had one. defaults: PVConfigYAML = pv_cfg if circuit is section_circuit else {} - circuit_id = stable_circuit_uuid(panel_id, circuit["id"]) + circuit_id = circuit_device_id(profile, circuit) metadata = _pv_metadata( profile, circuit, defaults, feed=circuit_id, - inverter_template=templates.get(circuit["template"]) or {}, + inverter_template=_template_of(profile, circuit) or {}, relative_position=str(defaults.get("relative_position", "IN_PANEL")), firmware=_circuit_firmware(circuit, pv_cfg), ) @@ -675,12 +686,12 @@ def _unfed_pv_instances(profile: SimulationConfig, *, numbered_after: int) -> li def _evse_instances(profile: SimulationConfig) -> list[DeviceInstance]: evse_cfg = profile.get("evse") or {} panel_id = profile["panel_config"]["serial_number"] - feed_circuits = _circuits_for_device_type(profile, "evse") + feed_circuits = circuits_for_device_type(profile, "evse") explicit_feed = str(evse_cfg["feed"]) if "feed" in evse_cfg else None if explicit_feed: feeds = [explicit_feed] else: - feeds = [stable_circuit_uuid(panel_id, circuit["id"]) for circuit in feed_circuits] + feeds = [circuit_device_id(profile, circuit) for circuit in feed_circuits] if not feeds and evse_cfg.get("enabled"): feeds = [""] if not feeds: @@ -806,10 +817,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.""" - templates = profile.get("circuit_templates") or {} + """The template of the first producer circuit on the panel, read for a PV device with + no PV circuit.""" for circuit in profile.get("circuits") or []: - template = templates.get(circuit.get("template", "")) + if not on_the_panel(circuit): + continue + template = _template_of(profile, circuit) if template is None: continue energy_profile = template.get("energy_profile") @@ -826,18 +839,23 @@ def _circuit_device_id( """The device id *circuit* publishes, which a DER it feeds names as its ``feed``.""" if circuit is None: return None - return stable_circuit_uuid(profile["panel_config"]["serial_number"], circuit["id"]) + return circuit_device_id(profile, circuit) -def _circuits_for_device_type( +def circuits_for_device_type( profile: SimulationConfig, device_type: str, ) -> list[CircuitDefinitionExtended]: - templates = profile.get("circuit_templates") or {} + """The circuits on the panel whose template, as each has it, feeds a *device_type* + device, in list order: the one list the manifest and each tick's readings take.""" 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: + template = _template_of(profile, circuit) + if ( + template is not None + and template.get("device_type") == device_type + and on_the_panel(circuit) + ): circuits.append(circuit) return circuits @@ -848,13 +866,22 @@ def _evse_display_name(feed_circuits: list[CircuitDefinitionExtended], idx: int) return "EV Charger" +def _template_of( + profile: SimulationConfig, circuit: CircuitDefinitionExtended +) -> CircuitTemplateExtended | None: + """*circuit*'s template as the panel models it (``circuit.effective_template``), + or None where it names none.""" + template = (profile.get("circuit_templates") or {}).get(circuit.get("template", "")) + return None if template is None else effective_template(template, circuit) + + def _circuit_nameplate_w( profile: SimulationConfig, circuit: CircuitDefinitionExtended | None, default: float ) -> float: """The nameplate rating of the device *circuit* feeds, from its template.""" if circuit is None: return default - template = (profile.get("circuit_templates") or {}).get(circuit.get("template", "")) + template = _template_of(profile, circuit) if template is None: return default energy_profile = template.get("energy_profile", {}) diff --git a/src/panelbench/engine.py b/src/panelbench/engine.py index 11459d1..89c2790 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) @@ -589,6 +598,9 @@ def __init__( self._clock = SimulationClock() self._behavior_engine: RealisticBehaviorEngine | None = None self._circuits: dict[str, SimulatedCircuit] = {} + # Each circuit's published device id, by its config id: named once the serial + # is final, as the panel names it (`instance_ids.circuit_device_id`). + self._device_ids: dict[str, str] = {} self._energy_system: EnergySystem | None = None # Dynamic overrides (dispatched to circuits) @@ -705,13 +717,17 @@ def _build_circuits(self) -> None: if not self._config or not self._behavior_engine: raise SimulationConfigurationError("Configuration and behavior engine required") + from panelbench.emitter_adapter.instance_ids import circuit_device_id + self._circuits = {} + self._device_ids = {} for circuit_def in self._config["circuits"]: template_name = circuit_def["template"] template = self._config["circuit_templates"][template_name] self._circuits[circuit_def["id"]] = SimulatedCircuit( circuit_def, template, self._behavior_engine ) + self._device_ids[circuit_def["id"]] = circuit_device_id(self._config, circuit_def) # ------------------------------------------------------------------ # Clock delegation (preserves public API) @@ -959,8 +975,6 @@ async def get_tick_inputs(self) -> EngineTick: if not self._config: raise SimulationConfigurationError("Configuration not loaded") - from panelbench.emitter_adapter.instance_ids import stable_circuit_uuid - current_time = self._clock.current_time for _cid, circuit in self._circuits.items(): # Tab-sync grouping currently has no override path — the @@ -972,19 +986,67 @@ async def get_tick_inputs(self) -> EngineTick: # Apply the v0.3.0 sign convention: producers (PV) report negative # power; consumers report positive. SimulatedCircuit stores magnitudes # only; the energy_mode tells direction. - 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 + circuit_powers[self._device_ids[cid]] = signed return EngineTick( current_time=current_time, 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 _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 + 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 +1199,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(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 @@ -1149,9 +1214,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 +1229,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/firmware.py b/src/panelbench/firmware.py index fb2b53d..91f96e1 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 @@ -34,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/panel.py b/src/panelbench/panel.py index 66d74b7..6c19136 100644 --- a/src/panelbench/panel.py +++ b/src/panelbench/panel.py @@ -40,6 +40,15 @@ class DuplicateSerialError(ValueError): """ +class SharedDeviceError(ValueError): + """A panel's devices are already published by another running panel. + + A real panel has a broker of its own, so nothing scopes a hardware 3.0 panel's + circuits before release 202645 to it: they are ``circuit-``. Two such panels + on PanelBench's one broker would claim each other's circuits' topics. + """ + + class PanelInstance: """A single simulated panel: engine + emitter, with its own tick loop.""" @@ -133,6 +142,14 @@ def engine(self) -> DynamicSimulationEngine | None: def runtime(self) -> CloneRuntime | None: return self._runtime + @property + def device_ids(self) -> frozenset[str]: + """Every device id the running panel publishes, its serial among them; none + before it starts.""" + if self._runtime is None: + return frozenset() + return frozenset(d.instance_id for d in self._runtime.manifest.instances) + # ------------------------------------------------------------------ # Battery state accessors — read-through to the emitter's last snapshot. # The simulator no longer models BESS state; the emitter's BESSDevice owns @@ -212,37 +229,51 @@ 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. - *running* maps the serials already running to their configs; a config - naming one of them is refused before anything connects. + *running* maps each device id the panels already running publish, their + serials among them, to its panel's config; a config publishing one of them is + refused before anything connects. Raises: DuplicateSerialError: the config's serial is already running. + SharedDeviceError: another of its devices' ids is already published. """ engine = DynamicSimulationEngine( config_path=self._config_path, recorder=self._recorder, ) await engine.initialize_async() - other = (running or {}).get(engine.serial_number) + running = running or {} + other = running.get(engine.serial_number) if other is not None: msg = ( f"{self._config_path.name} was not started: serial {engine.serial_number} " f"is already running from {other.name}; give it its own " - "panel_config.serial_number" + "panel_config.serial_number, or stop that panel first" ) raise DuplicateSerialError(msg) + shared = sorted(emitter_runtime.published_device_ids(engine) & running.keys()) + if shared: + owners = ", ".join(sorted({running[device_id].name for device_id in shared})) + named = ", ".join(shared[:4]) + (", …" if len(shared) > 4 else "") + msg = ( + f"{self._config_path.name} was not started: {owners} already publishes " + f"its devices {named} on this broker, as hardware 3.0 panels before " + "release 202645 name their circuits under no serial; stop that panel first" + ) + raise SharedDeviceError(msg) self._engine = engine self._runtime = await emitter_runtime.start_clone( 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: diff --git a/src/panelbench/pv_section.py b/src/panelbench/pv_section.py index c597f49..33bd051 100644 --- a/src/panelbench/pv_section.py +++ b/src/panelbench/pv_section.py @@ -13,7 +13,9 @@ from typing import TYPE_CHECKING, Final, Literal +from panelbench.circuit import effective_settings 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 +26,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,11 +39,14 @@ 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 - if isinstance(template, dict) and template.get("device_type") == "pv": + if ( + isinstance(template, dict) + and effective_settings(template, circuit).get("device_type") == "pv" + ): ids.append(str(circuit["id"])) return ids @@ -82,14 +89,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/reference_templates.py b/src/panelbench/reference_templates.py index dbc03ef..0abc2e2 100644 --- a/src/panelbench/reference_templates.py +++ b/src/panelbench/reference_templates.py @@ -13,7 +13,8 @@ into the config directory where it is missing or stale, as ``run.sh`` refreshes the shipped templates. So no copy of a capture lives in this repository, and a new emitter release brings its captures' templates with it. Each takes a serial of its own, so -several can run on one broker. +several can run on one broker, and a later capture of a panel takes its earlier one's +(``_SUCCEEDS``), as a panel keeps its serial through a firmware upgrade. A template is named for the panel it is, not for its capture's handle, so the dashboard's list reads as hardware (``_TEMPLATE_NAMES``). A capture the release has @@ -27,14 +28,18 @@ import tempfile from collections.abc import Mapping from pathlib import Path -from typing import Final +from typing import TYPE_CHECKING, Final import yaml from ebus_panel_sim import EmitterError, load_reference_capture, reference_capture_names from panelbench.definition_import import config_from_definition +from panelbench.device_numbers import hex_of, is_remote_ct, number_of from panelbench.validation import validate_yaml_config +if TYPE_CHECKING: + from ebus_panel_sim.capture import Tree + _LOGGER = logging.getLogger(__name__) @@ -45,13 +50,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 +68,25 @@ 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.""" +_SUCCEEDS: Final[Mapping[str, str]] = { + "main32_r202645": "main32_r202639", + "r202645-a": "r202639-a", + "r202645-c": "r202639-c", + "r202645-e": "r202639-e", +} +"""Each later capture of a panel, with the earlier capture of it whose template name +and serial it takes. A panel keeps its serial through a firmware upgrade, so a config +running the earlier capture, from a PanelBench release that had it, and one running +the later are one panel upgraded, as Home Assistant sees it.""" + +_RETIRED_CAPTURES: Final = frozenset({"main32_r202633", *_SUCCEEDS.values()}) +"""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 +109,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: @@ -111,15 +135,60 @@ def clone_name(filename: str) -> str: def reference_template(name: str) -> dict[str, object]: """The config for the reference capture *name*, one of ``reference_capture_names()``.""" - config = config_from_definition(load_reference_capture(name).definition) + capture = load_reference_capture(name) + config = config_from_definition(capture.definition) panel = config["panel_config"] if not isinstance(panel, dict): raise ValueError(f"reference capture {name!r} imported with no panel_config") - panel["serial_number"] = f"sim-{name}" + panel["serial_number"] = f"sim-{_SUCCEEDS.get(name, name)}" + _take_device_numbers(name, config, panel, capture.tree) validate_yaml_config(config) return config +def _take_device_numbers( + name: str, config: dict[str, object], panel: dict[str, object], tree: Tree +) -> None: + """Number the template's circuits, its remote CT and its panel as the panel the + capture *name* records names them, so the template publishes the ids it did. + + A definition's ids are masked and renumbered in space order, so the numbers come + from the capture's tree: each circuit is matched by its spaces, and by its name + where several share them, as a tandem's do; a remote CT, on no space, is the + template's one meter outside the panel. A capture whose ids carry no numbers, a + MAIN 32's or one masked whole, numbers nothing. + + Raises: + ValueError: a numbered device of the tree matches no one entry of the config. + """ + circuits = [c for c in _entries(config.get("circuits"))] + meters = [m for m in _entries(config.get("outside_meters"))] + for device_id, device in tree.items(): + number = number_of(device_id) + if device.type != "circuit" or number is None: + continue + if is_remote_ct(device_id): + matches = meters + else: + spaces = [int(s) for s in str(device.value("info/spaces") or "").split(",") if s] + matches = [c for c in circuits if c.get("tabs") == spaces] + if len(matches) > 1: + matches = [c for c in matches if c.get("name") == device.value("info/name")] + if len(matches) != 1: + raise ValueError( + f"reference capture {name!r} publishes {device_id}, which matches " + f"{len(matches)} of its template's entries, not one" + ) + matches[0]["circuit_number"] = number + root = next(i for i, d in tree.items() if d.type == "distribution-enclosure") + if (segment := hex_of(root, tree)) is not None: + panel["device_id_hex"] = segment + + +def _entries(value: object) -> list[dict[str, object]]: + return [e for e in value if isinstance(e, dict)] if isinstance(value, list) else [] + + def write_reference_templates(config_dir: Path) -> list[Path]: """Lay each reference capture's template into *config_dir*; return those written. diff --git a/src/panelbench/validation.py b/src/panelbench/validation.py index 58f7f3c..6cbd3ed 100644 --- a/src/panelbench/validation.py +++ b/src/panelbench/validation.py @@ -6,10 +6,19 @@ from __future__ import annotations +import contextvars +import copy import logging -from typing import TYPE_CHECKING, Any, Final +import math +import re +from collections.abc import Hashable +from typing import TYPE_CHECKING, Any, Final, cast + +from ebus_panel_sim import EmitterError, SetterRegistry from panelbench.breakers import breaker_misfit, crowded_spaces, crowding +from panelbench.circuit import effective_settings +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 @@ -17,21 +26,26 @@ from panelbench.hardware import ( declares_variant, panel_variant, + publishes_downstream_lugs, publishes_outside_meters, publishes_pv_devices, publishes_shared_breakers, relay_locks_priority, variant_selection, ) +from panelbench.panel_models import PANEL_SIZE_TO_MODEL 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 from ebus_panel_sim import Variant + from panelbench.config_types import SimulationConfig + _LOGGER = logging.getLogger(__name__) @@ -46,6 +60,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"]) @@ -64,8 +80,14 @@ def validate_yaml_config(config_data: Any) -> None: validate_unfed_inverters(config_data) validate_ratings(config_data) validate_outside_meters(config_data) + validate_device_numbers(config_data) validate_shared_circuits(config_data) 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: 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: validate_panel_source(config_data["panel_source"]) @@ -80,6 +102,45 @@ 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 not isinstance(serial, str) or not serial: + raise ValueError( + f"panel_config.serial_number must be the panel's serial, a string, not {serial!r}" + ) + # The time-zone lookup refuses a place off the globe, as a swapped pair often is. + for key, bound in (("latitude", 90), ("longitude", 180)): + if key in panel_config: + degrees = panel_config[key] + if not _is_real(degrees) or not -bound <= degrees <= bound: + raise ValueError( + f"panel_config.{key} must be degrees from -{bound} to {bound}, not {degrees!r}" + ) + if "soc_shed_threshold" in panel_config and ( + _as_number(panel_config["soc_shed_threshold"]) is None + ): + raise ValueError( + "panel_config.soc_shed_threshold must be a percentage, not " + f"{panel_config['soc_shed_threshold']!r}" + ) + if _as_whole_number(panel_config["total_tabs"]) not in PANEL_SIZE_TO_MODEL: + sizes = ", ".join(str(size) for size in PANEL_SIZE_TO_MODEL) + raise ValueError( + f"panel_config.total_tabs must be the spaces of a SPAN panel, one of {sizes}, " + f"not {panel_config['total_tabs']!r}" + ) + main_size = panel_config["main_size"] + if main_size is not None and _as_whole_number(main_size) is None: + 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}" + ) registration_limit(panel_config) @@ -110,6 +171,12 @@ 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}" + ) priority = str(template["priority"]).upper() if priority not in SHED_PRIORITIES: raise ValueError( @@ -119,6 +186,156 @@ def validate_single_template(template_name: str, template: Any) -> None: _validate_commissioned_system(template_name, template) +def _validate_as_modelled( + index: int, circuit: Mapping[str, object], template_name: str, template: Mapping[str, object] +) -> None: + """Refuse a circuit whose template, as it is read for this circuit, cannot be. + + The engine models it, and the definition publishes it, by its template with the + circuit's ``overrides`` and own ``breaker_rating`` over it + (``circuit.effective_template``), so that is what is checked. A template no + circuit uses is read by nothing, so it is checked for its shape alone. + """ + overrides = circuit.get("overrides", {}) + if not isinstance(overrides, dict): + raise ValueError(f"Circuit {index} overrides must be a mapping, not {overrides!r}") + if not isinstance(template.get("energy_profile"), dict): + return + where = f"Circuit template '{template_name}'" + if overrides or "breaker_rating" in circuit: + where = f"{where}, as circuit {index} has it," + effective = effective_settings(template, circuit) + profile = effective["energy_profile"] + if not isinstance(profile, dict): + # An override named energy_profile replaces the template's whole profile. + raise ValueError( + f"{where} energy_profile must be a mapping of its settings, not {profile!r}" + ) + _validate_behaviour(where, effective, profile) + _validate_profile_numbers(where, effective, profile) + + +def _validate_behaviour( + where: str, template: Mapping[str, object], energy_profile: Mapping[str, object] +) -> None: + """Refuse a template whose behaviour the engine cannot model: each setting the + engine reads, taken as it reads it, so a value it converts may be quoted. + + It indexes the profile's ``mode``, ``power_range`` and ``typical_power``, and does + arithmetic on those numbers, the variation and a cycling load's durations; it + converts a duty cycle and the time-of-day and monthly factors with ``float()``. + """ + for key in ("mode", "power_range", "typical_power"): + if key not in energy_profile: + raise ValueError(f"{where} energy_profile has no {key}") + power_range = energy_profile["power_range"] + if not ( + isinstance(power_range, list) + and len(power_range) == 2 + and all(_is_real(bound) for bound in power_range) + ): + raise ValueError( + f"{where} energy_profile.power_range must be [minimum, maximum] in watts, not " + f"{power_range!r}" + ) + for key in ("typical_power", "power_variation"): + if key in energy_profile and not _is_real(energy_profile[key]): + raise ValueError( + f"{where} energy_profile.{key} must be a number, not {energy_profile[key]!r}" + ) + if "cycling_pattern" in template: + cycling = template["cycling_pattern"] + if not isinstance(cycling, dict): + raise ValueError(f"{where} cycling_pattern must be a mapping, not {cycling!r}") + for key in ("on_duration", "off_duration"): + if key in cycling and not _is_real(cycling[key]): + raise ValueError( + f"{where} cycling_pattern.{key} must be a number of seconds, not " + f"{cycling[key]!r}" + ) + duty = cycling.get("duty_cycle") + if duty is not None and _as_number(duty) is None: + raise ValueError( + f"{where} cycling_pattern.duty_cycle must be a fraction, not {duty!r}" + ) + smart = template.get("smart_behavior", {}) + if not isinstance(smart, dict): + raise ValueError(f"{where} smart_behavior must be a mapping, not {smart!r}") + if "max_power_reduction" in smart and not _is_real(smart["max_power_reduction"]): + raise ValueError( + f"{where} smart_behavior.max_power_reduction must be a fraction, not " + f"{smart['max_power_reduction']!r}" + ) + profile = template.get("time_of_day_profile", {}) + if not isinstance(profile, dict): + raise ValueError(f"{where} time_of_day_profile must be a mapping, not {profile!r}") + for key in ("hourly_multipliers", "hour_factors"): + factors = profile.get(key) + if factors and not _maps_to_factors(factors): + raise ValueError( + f"{where} time_of_day_profile.{key} must map each hour to a factor, not " + f"{factors!r}" + ) + days = profile.get("active_days") + if days and (not isinstance(days, list) or not all(_is_whole(day) for day in days)): + raise ValueError( + f"{where} time_of_day_profile.active_days must list the days it runs, 0 for " + f"Monday, not {days!r}" + ) + monthly = template.get("monthly_factors") + if monthly and not _maps_to_factors(monthly): + raise ValueError( + f"{where} monthly_factors must map each month to a factor, not {monthly!r}" + ) + hvac = template.get("hvac_type") + if hvac and not isinstance(hvac, Hashable): + raise ValueError(f"{where} hvac_type must name an HVAC type, not {hvac!r}") + + +def _maps_to_factors(factors: object) -> bool: + """A mapping whose every factor ``float()`` reads.""" + return isinstance(factors, dict) and all(_as_number(f) is not None for f in factors.values()) + + +def _validate_profile_numbers( + where: str, template: Mapping[str, object], energy_profile: Mapping[str, object] +) -> None: + """Refuse a rating or energy seed the definition or the engine cannot read. + + The definition converts each with ``float()``, so it may be quoted, but the engine + takes ``abs()`` of a producer's nameplate. Left empty, a nameplate states none, + which only a PV circuit's template cannot do without: its inverter's device + publishes the rating. + """ + nameplate = energy_profile.get("nameplate_capacity_w") + producer = energy_profile.get("mode") == "producer" + if nameplate is None: + unrated_pv = ( + "nameplate_capacity_w" in energy_profile and template.get("device_type") == "pv" + ) + else: + unrated_pv = not (_is_real(nameplate) if producer else _as_number(nameplate) is not None) + if unrated_pv: + raise ValueError( + f"{where} energy_profile.nameplate_capacity_w must be a number of watts, not " + f"{nameplate!r}" + ) + for key in ("initial_consumed_energy_wh", "initial_produced_energy_wh"): + seed = energy_profile.get(key) + if seed and _as_number(seed) is None: + raise ValueError( + f"{where} energy_profile.{key} must be a number of watt-hours, not {seed!r}" + ) + for key in ("breaker_rating_a", "breaker_rating"): + rating = template.get(key) + amps = _as_number(rating) + if rating is not None and (amps is None or amps <= 0): + raise ValueError( + f"{where} {key} must be the breaker's amps, above 0, or null where the panel " + f"publishes none, not {rating!r}" + ) + + _COMMISSIONED_SYSTEMS = ("pv", "backup") @@ -262,16 +479,20 @@ def validate_single_circuit(index: int, circuit: Any, circuit_templates: dict[st for field in required_circuit_fields: if field not in circuit: raise ValueError(f"Missing required field '{field}' in circuit {index}") + circuit_id = circuit["id"] + if isinstance(circuit_id, bool) or not isinstance(circuit_id, (str, int, float)): + raise ValueError(f"Circuit {index} id must be a name or a number, not {circuit_id!r}") 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, {}) + _validate_as_modelled(index, circuit, template_name, template) 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_whole(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. @@ -467,6 +688,46 @@ def validate_outside_meters(config_data: Mapping[str, object]) -> None: ) +def validate_device_numbers(config_data: Mapping[str, object]) -> None: + """SPAN's number for each circuit and meter outside the panel, and the panel's id + segment, as ``device_numbers`` reads them: a whole number above 0, used once among + the panel's circuits and once among its remote CTs, which SPAN numbers apart, and + 16 lowercase hex digits.""" + for kind, section in (("circuit", "circuits"), ("outside meter", "outside_meters")): + taken: dict[int, str] = {} + for entry in _listed(config_data.get(section)): + if not isinstance(entry, dict) or "circuit_number" not in entry: + continue + where = f"{kind} {entry.get('id')!r}" + number = _positive_whole(entry["circuit_number"]) + if number is None: + raise ValueError( + f"{where} circuit_number must be SPAN's number for the circuit, a whole " + f"number above 0, not {entry['circuit_number']!r}" + ) + if number in taken: + raise ValueError( + f"{where} circuit_number {number} is taken by {taken[number]}: SPAN " + f"numbers each {kind} of a panel once" + ) + taken[number] = where + panel = config_data.get("panel_config") + segment = panel.get("device_id_hex") if isinstance(panel, dict) else None + if segment is not None and not ( + isinstance(segment, str) and re.fullmatch(r"[0-9a-f]{16}", segment) + ): + raise ValueError( + f"panel_config.device_id_hex must be 16 lowercase hex digits, not {segment!r}" + ) + + +def _positive_whole(value: object) -> int | None: + """*value* as a whole YAML number above 0, never a bool; None where it is not one.""" + if _is_whole(value) and isinstance(value, (int, float)) and value > 0: + return int(value) + return None + + def validate_shared_circuits(config_data: Mapping[str, object]) -> None: """Circuits list one breaker space only as the circuits of one multi-load breaker. @@ -612,6 +873,288 @@ 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 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, and a battery + placed ``DOWNSTREAM`` would hang from no lugs; on an earlier release both still + describe the downstream lugs that release publishes. + """ + if publishes_downstream_lugs(config_data): + return + 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 " + "false publishes none. Remove lugs.downstream, or set feedthrough to true." + ) + + +_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}" + ) + + +# Sections a config may leave out or set null, each otherwise a mapping of settings. +_MAPPING_SECTIONS: Final = ("bess", "pv", "evse", "lugs", "broker") + + +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}") + # Read as a mapping wherever the key is present, so null is no way to leave it out. + params = config_data.get("simulation_params", {}) + if not isinstance(params, dict): + raise ValueError(f"simulation_params must be a mapping of its settings, not {params!r}") + for key in ("noise_factor", "time_acceleration"): + if key in params and not _is_real(params[key]): + raise ValueError(f"simulation_params.{key} must be a number, not {params[key]!r}") + syncs = config_data.get("tab_synchronizations", []) + if not isinstance(syncs, list) or not all( + isinstance(sync, dict) + and "behavior" in sync + and isinstance(sync.get("tabs"), list) + and all(isinstance(tab, (str, int, float)) for tab in sync["tabs"]) + for sync in syncs + ): + raise ValueError( + "tab_synchronizations must list groups, each a mapping with its behavior and " + f"the tabs it syncs, not {syncs!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 _as_number(bess[key]) is None: + raise ValueError(f"bess.{key} must be a finite number, not {bess[key]!r}") + capacity = _as_number(bess.get("nameplate_capacity_kwh", 13.5)) + if capacity is not None and capacity <= 0: + raise ValueError( + "bess.nameplate_capacity_kwh must be above 0, not " + f"{bess['nameplate_capacity_kwh']!r}: a battery's charge is its energy over it" + ) + discharge = _as_number(bess.get("discharge_efficiency", 0.95)) + if discharge is not None and discharge <= 0: + raise ValueError( + "bess.discharge_efficiency must be above 0, not " + f"{bess['discharge_efficiency']!r}: a battery's discharge is divided by it" + ) + for key in _BATTERY_HOURS: + hours = bess.get(key, []) + if not isinstance(hours, list) or not all(_is_whole(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" + ) + + +# These take a setting as the code reading it does, so a config that ran before keeps +# running: a number may be quoted where its reader converts it. + + +def _as_number(value: object) -> float | None: + """*value* as ``float()`` reads a number: a YAML number, or a string of one. None + where it reads none, or none that is finite.""" + if not isinstance(value, (int, float, str)): + return None + try: + number = float(value) + except ValueError: + return None + return number if math.isfinite(number) else None + + +def _as_whole_number(value: object) -> int | None: + """*value* as ``int()`` reads a whole number: a YAML number, or a string of a whole + one. None where it reads none.""" + if not isinstance(value, (int, float, str)): + return None + try: + return int(value) + except (ValueError, OverflowError): + return None + + +def _is_real(value: object) -> bool: + """A finite YAML number, for a reader that does arithmetic on it rather than + converting it: never a string, nor a bool.""" + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def _is_whole(value: object) -> bool: + """A space or hour as its readers compare it: a whole YAML number, ``1`` or ``1.0``, + never a bool or a string, which equals no space or hour.""" + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and float(value).is_integer() + ) + + +# Set while validation builds an emitter it then discards. +_VALIDATING: Final = contextvars.ContextVar("panelbench_validating", default=False) + + +class _QuietWhileValidating(logging.Filter): + """Drops the SDK's records below WARNING while validation builds its emitter. + + They describe a device tree no one will see, about 19,000 records on 48 circuits + at DEBUG, for every edit. A context variable marks the build, so a running + panel's own records, in its own task or thread, still pass; a warning always does. + """ + + def filter(self, record: logging.LogRecord) -> bool: + return record.levelno >= logging.WARNING or not _VALIDATING.get() + + +logging.getLogger("homie").addFilter(_QuietWhileValidating()) + + +def validate_emitter_accepts(config_data: SimulationConfig) -> None: + """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 and is then dropped: 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, construct_emitter + from panelbench.emitter_adapter.instance_ids import ( + circuit_device_id, + outside_meter_device_id, + ) + from panelbench.emitter_adapter.wire_capture import RecordingTransport + + config: SimulationConfig = copy.deepcopy(config_data) + normalize_config(config, source="validation") + definition = build_definition(config) + validating = _VALIDATING.set(True) + try: + construct_emitter(definition, SetterRegistry(), RecordingTransport()) + except EmitterError as exc: + reason = str(exc) + published = [ + *((circuit_device_id(config, c), c["id"]) for c in config.get("circuits") or []), + *( + (outside_meter_device_id(config, m), m["id"]) + for m in config.get("outside_meters") or [] + ), + ] + # One pass over whole ids, longest first: `circuit-1` begins `circuit-12`, as + # `…-1-16-1` begins `…-1-16-12`, so replacing one id at a time would misname. + names = {device_id: str(config_id) for device_id, config_id in published} + if names: + ids = "|".join(re.escape(i) for i in sorted(names, key=len, reverse=True)) + whole = re.compile(rf"(? 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/_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/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 083f582..5d81eac 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 = { @@ -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/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/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/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/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_app.py b/tests/test_app.py index 546ae61..ccd8706 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +import yaml from aiohttp.test_utils import TestClient, TestServer from panelbench.app import SimulatorApp, _discover_configs, _file_hash @@ -15,6 +16,7 @@ from panelbench.emitter_adapter.runtime import start_clone as _real_start_clone from panelbench.emitter_adapter.spec_generator import build_manifest from panelbench.panel import PanelInstance +from panelbench.reference_templates import reference_template from panelbench.schema import load_schema from tests._helpers import CURRENT_FIRMWARE, EARLIER_FIRMWARE @@ -141,15 +143,16 @@ def test_hash_stable_for_same_content(self, tmp_path: Path) -> None: class TestUnsupportedPanelSize: - """Configs with total_tabs outside _PANEL_SIZE_TO_MODEL fail loudly at panel-add.""" + """Configs with total_tabs outside PANEL_SIZE_TO_MODEL fail loudly at panel-add.""" @pytest.mark.asyncio - async def test_unsupported_total_tabs_raises_key_error( + async def test_unsupported_total_tabs_is_refused( self, tmp_path: Path, amqtt_broker: tuple[str, int], ) -> None: - """total_tabs=20 has no SPAN model — _start_panel must raise AND not register.""" + """total_tabs=20 has no SPAN model — _start_panel must refuse it, as validation + does when the panel loads, AND not register.""" host, port = amqtt_broker config = tmp_path / "bad_size.yaml" config.write_text(_BAD_SIZE_CONFIG.format(broker_host=host, broker_port=port)) @@ -163,7 +166,7 @@ async def test_unsupported_total_tabs_raises_key_error( ca_cert_path=None, ) - with pytest.raises(KeyError): + with pytest.raises(ValueError, match=r"total_tabs must be the spaces of a SPAN panel"): await app._start_panel(config) assert config not in app._panels @@ -422,3 +425,83 @@ 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() + + +async def _reloaded( + tmp_path: Path, broker: tuple[str, int], captures: tuple[str, ...] +) -> tuple[SimulatorApp, dict[str, list[str]]]: + """An app reloaded over *captures*' templates, each on the test broker.""" + host, port = broker + for capture in captures: + config = reference_template(capture) + config["broker"] = {"host": host, "port": port} + (tmp_path / f"{capture}.yaml").write_text(yaml.safe_dump(config, sort_keys=False)) + app = SimulatorApp(config_dir=tmp_path) + app._schema = load_schema(_BUNDLED_SCHEMA) + app._certs = MagicMock( + ca_cert_pem=b"-----BEGIN CERTIFICATE-----\nX\n-----END CERTIFICATE-----\n", + ca_cert_path=None, + ) + mock_server = MagicMock() + mock_server.start = AsyncMock() + mock_server.stop = AsyncMock() + with patch("panelbench.app.BootstrapHttpServer", return_value=mock_server): + result = await app.reload() + return app, result + + +@pytest.mark.asyncio +async def test_a_panel_whose_devices_another_running_panel_publishes_is_refused( + tmp_path: Path, amqtt_broker: tuple[str, int] +) -> None: + """A hardware 3.0 panel before release 202645 names its circuits ``circuit-`` + under no serial, as its own broker lets a real one; on one shared broker, two such + panels would claim each other's circuits' topics.""" + app, result = await _reloaded(tmp_path, amqtt_broker, ("r202639-a", "r202639-e")) + + try: + assert len(result["started"]) == 1 + [(refused, error)] = app._get_panel_start_errors().items() + assert refused in ("r202639-a.yaml", "r202639-e.yaml") + assert "circuit-3" in error + assert "already publishes" in error + finally: + for panel in list(app._panels.values()): + with contextlib.suppress(Exception): + await panel.stop() + + +@pytest.mark.asyncio +async def test_panels_that_scope_their_devices_by_serial_run_together( + tmp_path: Path, amqtt_broker: tuple[str, int] +) -> None: + app, result = await _reloaded(tmp_path, amqtt_broker, ("r202645-a", "r202645-e")) + + try: + assert sorted(result["started"]) == ["sim-r202639-a", "sim-r202639-e"] + assert not app._get_panel_start_errors() + finally: + 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 new file mode 100644 index 0000000..589bb3d --- /dev/null +++ b/tests/test_breaker_mates.py @@ -0,0 +1,170 @@ +"""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( + tmp_path: Path, field: str, value: str, seen: str +) -> None: + store = ConfigStore() + store.load_from_file(_replayed(tmp_path)) + + 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 + # 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 +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..f0eb43f 100644 --- a/tests/test_clone.py +++ b/tests/test_clone.py @@ -4,7 +4,7 @@ import json import logging -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Final import pytest import yaml @@ -777,6 +777,13 @@ def _sharing(device_id: str, name: str, peer: str) -> DiscoveredDevice: return circuit +# Each meter register a circuit publishes, and the seed a clone writes it to. +_REGISTERS: Final = [ + pytest.param("exported-energy", "initial_consumed_energy_wh", id="consumed"), + pytest.param("imported-energy", "initial_produced_energy_wh", id="produced"), +] + + class TestCircuitsSharingASpace: """Two circuits on one space, as circuits sharing a meter are, stay two circuits.""" @@ -800,15 +807,59 @@ 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], seed: str) -> dict[str, object]: + templates = _templates(config) + return { + name: templates[name]["energy_profile"].get(seed) + for name in ("clone_44", "clone_44_2") + } + + @pytest.mark.parametrize(("register", "seed"), _REGISTERS) + def test_a_tandem_read_a_moment_apart_is_cloned_with_its_one_register( + self, register: str, seed: str + ) -> 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", register, "1000.5") + devices["fff777"].update_property("meter", register, "1000.0") + + config = translate_scraped_panel(_make_scraped(devices)) + + assert self._seeds(config, seed) == {"clone_44": 1000.5, "clone_44_2": 1000.5} + validate_yaml_config(config) + + @pytest.mark.parametrize(("register", "seed"), _REGISTERS) + def test_a_refresh_writes_the_breaker_s_one_register_to_each_circuit( + self, register: str, seed: str + ) -> None: devices = self._devices() config = translate_scraped_panel(_make_scraped(devices)) - devices["fff777"].update_property("meter", "exported-energy", "777.0") + devices["fff777"].update_property("meter", register, "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, seed) == {"clone_44": 777.0, "clone_44_2": 777.0} + validate_yaml_config(config) + + def test_a_refresh_missing_one_circuit_of_a_tandem_still_gives_both_its_register( + self, + ) -> None: + """A partial scrape reads the breaker's one meter through the circuit it has, + which is the other's register too.""" + devices = self._devices() + config = translate_scraped_panel(_make_scraped(devices)) + del devices["fff777"] + devices["fff666"].update_property("meter", "exported-energy", "900.0") + + assert update_config_from_scrape(config, _make_scraped(devices)) + + assert self._seeds(config, "initial_consumed_energy_wh") == { + "clone_44": 900.0, + "clone_44_2": 900.0, + } + validate_yaml_config(config) def test_sharing_with_no_other_circuit_is_refused(self) -> None: config = translate_scraped_panel(_make_scraped(self._devices())) @@ -931,7 +982,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_config_shapes.py b/tests/test_config_shapes.py new file mode 100644 index 0000000..7e56f6b --- /dev/null +++ b/tests/test_config_shapes.py @@ -0,0 +1,375 @@ +"""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 + +import logging +from typing import TYPE_CHECKING, Final + +import pytest +import yaml + +from panelbench import validation +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 = "