Metadata-Version: 2.5
Name: ebus-panel-sim
Version: 0.11.0
Summary: Producer-side Homie publisher with embedded behaviour runtime for the eBus convention
Project-URL: Homepage, https://ebus.energy
Project-URL: Repository, https://github.com/electrification-bus/distribution-enclosure-simulator
Project-URL: Issues, https://github.com/electrification-bus/distribution-enclosure-simulator/issues
Author: Bill Flood, Clark Communications Corporation
License-Expression: MIT
License-File: LICENSE
Keywords: distribution-enclosure,ebus,energy,homie,homie5,iot,mqtt,simulator,span
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Home Automation
Classifier: Topic :: System :: Emulators
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: ebus-sdk<0.23,>=0.20.1
Requires-Dist: pyyaml>=6.0
Description-Content-Type: text/markdown

# ebus-panel-sim

[![PyPI](https://img.shields.io/pypi/v/ebus-panel-sim)](https://pypi.org/project/ebus-panel-sim/)
[![CI](https://github.com/electrification-bus/distribution-enclosure-simulator/actions/workflows/ci.yaml/badge.svg)](https://github.com/electrification-bus/distribution-enclosure-simulator/actions/workflows/ci.yaml)
[![Python versions](https://img.shields.io/pypi/pyversions/ebus-panel-sim.svg)](https://pypi.org/project/ebus-panel-sim/)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![eBus spec](https://img.shields.io/badge/eBus%20spec-6e582c9-green)](https://github.com/electrification-bus/specification/tree/6e582c994fff4c77853a79d8bab26ef9924e22c7)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A fully-loaded, spec-conformant **distribution-enclosure simulator** and producer-side Homie 5 publisher for the eBus convention. It publishes a complete eBus Homie device tree (the enclosure plus a device for every circuit, lugs pair, and integrated DER: BESS, PV, EVSE, and MID) so external developers can build and test their consumers against a realistic SPAN-like panel without beta firmware, a live panel, or the commissioned add-ons (SPAN Drive/EVSE, BESS, PV, MID) a real installation would have.

It serves two roles:

- **Simulator / test fixture.** Drive it from a small YAML definition and it publishes a spec-conformant, fully-commissioned enclosure to any MQTT broker. Consumers (Home Assistant integrations, dashboards, SDK code) validate against it before shipping to the field.
- **Producer library.** The canonical eBus Homie publisher. A producer (a simulator, a real panel gateway, an LLM-driven model) hands the emitter a small per-tick driving signal (signed power per circuit, current time, grid-online flag, and optionally the panel's link health to each battery, the PV a battery's own inverter takes and the production of PV inverters no circuit feeds) via `TickInputs`; the emitter derives all telemetry and publishes Homie-conformant retained MQTT with diff-only updates. The split is **identity = manifest (once at startup), telemetry = derived from TickInputs (per tick)**.

For the internals (the per-tick pipeline, the native BESS/load-shed devices, `/set` handling, the wire model) see [DESIGN.md](https://github.com/electrification-bus/distribution-enclosure-simulator/blob/main/DESIGN.md); for the dev setup see [DEVELOPER.md](https://github.com/electrification-bus/distribution-enclosure-simulator/blob/main/DEVELOPER.md).

## Requirements

- Python >= 3.11
- [uv](https://docs.astral.sh/uv/)
- An MQTT broker reachable at `localhost:1883` (plaintext). The companion [broker-quickstart](https://github.com/electrification-bus/broker-quickstart) bundle brings one up in one command; any `mosquitto` works too.

## Install

```bash
pip install ebus-panel-sim    # or: uv add ebus-panel-sim
```

The import package is `ebus_panel_sim`. During local development, pin a path instead:

```toml
ebus-panel-sim = { path = "../distribution-enclosure-simulator", editable = true }
```

It depends on `ebus-sdk`.

> Before 0.3.0 this package was named `panel-sim`, importing as `panel_sim`, and was
> installable only from git. Update both the dependency and your imports.

## Run

The repo ships a runnable example: it builds an emitter from a panel definition, publishes its three ticks (the last with the grid down) to an MQTT broker, then reads the retained tree back through an ebus-sdk `Controller` and prints it. It expects a plaintext broker on `localhost:1883`.

The quickest broker is the companion [broker-quickstart](https://github.com/electrification-bus/broker-quickstart) in its `open` profile (plaintext, anonymous, port 1883):

```bash
# in a broker-quickstart checkout — a plaintext :1883 broker (anon read + write)
python -m laptop.run --profile open
```

Then, in this repo, publish to it and print the retained tree:

```bash
uv sync --group dev
uv run python examples/run_forty_tab_minimal.py                        # print the retained tree
uv run python examples/run_forty_tab_minimal.py --broker 127.0.0.1:1883 > tree.txt
```

Any broker that accepts anonymous connections on `localhost:1883` works; `--broker host:port` points the example elsewhere.

The definition is `examples/forty_tab_minimal.yaml`, driven by `examples/forty_tab_minimal.ticks.yaml`: a fully-commissioned enclosure with circuits, upstream/downstream lugs, a BESS (plus its MID), PV, and SPAN Drive EVSEs. Each node is its own Homie device: the enclosure at `ebus/5/<enclosure-id>/…` and each circuit, lugs pair, and DER at its own topic root, for example `ebus/5/<circuit-id>/switch/relay`, `ebus/5/<lugs-id>/meter/current-a`, `ebus/5/<bess-id>-mid/grid/islanding-state`.

## Configure

The simulator is driven by a config that says which enclosure, which add-ons, and which circuits. There are two entry points.

### 1. Example definition

`examples/forty_tab_minimal.yaml` is the quickest path: a panel definition file (see "Panel definition file" below) listing each device with its metadata, plus the BESS dispatch settings. A DER sits on a circuit by naming it in its `feed` (the two PV inverters each sit on a `commissioned-system: pv` circuit), and the MID, the islanding authority of a grid-forming BESS in an islandable enclosure, is listed under the BESS as on a real SPAN panel. `examples/forty_tab_minimal.ticks.yaml` is the per-tick driving signal: signed watts per circuit, EVSE draw, and the grid-online flag. Copy and edit both, or generate them from a live panel with `panel-sim-capture`. `examples/span_alpha_test_b2_minimal.yaml` and its ticks do the same for a `span-alpha-test-b2` panel.

### 2. DeviceManifest (programmatic)

A producer can build `DeviceInstance`s directly instead of loading a definition file. Each device class's identity and static attributes live in the instance's `metadata`, validated once at startup by `ManifestPhysicsView` (missing required keys or malformed values raise `ManifestValidationError` naming the offending instance). The metadata keys per device class:

| entity_class | required keys | optional keys |
| --- | --- | --- |
| `panel` | `vendor-name`, `serial-number`, `firmware-version` (or `software-version`), `hardware-version`, `panel-size`, `panel-model`, `postal-code`, `time-zone` | `wifi-ssid` (reported unless a tick's envelope gives one), `off-grid-import-limit-enablement` (UNSPECIFIED, UNCONFIGURED, DISABLED or ENABLED; absent: no off-grid limit property is published), `off-grid-import-limit-a` (published only while ENABLED, and then required), `operator-import-limit-enablement` (UNCONFIGURED), `main-breaker-rating-a` (absent: no breaker capability), `service-voltage-v` (240), `line-voltage-v` (120), `islandable` (false), `schema-topology` (`flat` \| `parent-child`), `site-name`, `address-lines`, `locality`, `region`, `country-code`, `latitude`, `longitude`, `utility-meter-serial-number` |
| `lugs` | `direction` (`upstream` \| `downstream`) | `feeds-role`, `backed-up`, `service-rating-a`, `overcurrent-protection-a` |
| `circuit` | `tab-numbers` (CSV ints), `breaker-rating-a`, `default-priority`, `relay-behavior` (`controllable` \| `non-controllable` \| `always-on`), `placement` (`upstream-of-lugs` \| `downstream-of-lugs`) | `always-on`, `never-backup` (false), `commissioned-system` (`pv` \| `backup`), `dipole` (defaults to `len(tab-numbers) > 1`), `pcs-priority` (0), `initial-consumed-wh` (0), `initial-produced-wh` (0), `tags`, `locations`, `dedicated`, `nominal-voltage`, `protection-functions`, `shared-with-device-ids`, `feeds-role`, `backed-up` |
| `bess` | `vendor-name`, `nameplate-capacity-kwh` | `model`, `part-number`, `serial-number`, `firmware-version`/`software-version`, `relative-position` (`UPSTREAM`), `feed`, `initial-soe-kwh`, `inverter-type` (`ac-coupled`; `hybrid` when the battery's inverter also takes PV) |
| `pv` | `vendor-name`, `nominal-power-w` (a finite number greater than 0), `inverter-type` (`hybrid` \| `ac-coupled`) | `model`, `serial-number`, `firmware-version`/`software-version`, `relative-position` (`IN_PANEL`), `feed` |
| `evse` | `vendor-name`, `model`, `part-number`, `serial-number`, `firmware-version` (or `software-version`), `max-current-a` | `feed`, `user-max-charge-current-a` (the user limit it starts from, as if set) |
| `mid` | (none) | `vendor-name`, `serial-number`, `model`, `firmware-version`/`software-version`, `hardware-version` |

A circuit's `tab-numbers` are the panel spaces it occupies, numbered odd down the left column and even down the right, with the legs alternating by row: spaces 1 and 2 are on L1, 3 and 4 on L2, and so on. A tab's leg follows from its number alone, so on a panel whose spaces start at 9, 9 and 10 are on L1. A two-pole circuit takes two spaces one above the other in a column, such as `1,3`, which span both legs. A two-pole circuit on any other footprint is rejected: one space; two of one row, such as `1,2`, which share a leg; two of one column that are not adjacent, such as `1,5`, which share a leg, or `1,7`; two in different columns, such as `2,3` or `1,4`; or three or more. `panel-sim-capture` raises `CaptureError` for a tree that publishes one, or a circuit whose `breaker/poles` is not `1` or `2`. A panel numbered sequentially down one column, which the eBus specification also allows, puts its two-pole circuits on consecutive spaces, so its definition must be renumbered odd down the left and even down the right. The lugs' `meter/current-a` and `meter/current-b` are the magnitude of each leg's net current, so a circuit feeding back offsets the loads on its leg.

A circuit whose `relay-behavior` is `non-controllable` or `always-on` — or which carries
`always-on: true` — is **locked**: its relay refuses `/set`, is exempt from load-shed, reports
`switch/relay-requester` as `CONFIGURATION`, and declares no `$settable` on `switch/relay`.
The two spellings differ only in the operator's intent; the hardware this models carries one
flag, publishing `switch/relay-controllable` as its inverse. Locking reaches the relay only —
a locked circuit still declares `load-shed/priority` settable.

A circuit carrying `never-backup: true` is commissioned to receive no backup power: it is
permanently `OFF_GRID`, so its `default-priority` must be `OFF_GRID` (any other value is
rejected as contradictory), it declares no `$settable` on `load-shed/priority`, and a `/set`
on that priority is refused. It still sheds when the panel islands — that is what being
`OFF_GRID` means; what the lock removes is the consumer's ability to re-prioritise it. That
shed publishes `switch/relay-requester` as `LOAD_SHED`, like any other shed — the lock is not a
requester value — and at rest the circuit reports `NONE` like any other.
This is a **separate commissioning input from the priority value**: `default-priority: NEVER`
means "never shed" and stays fully settable, which is what real panels publish.

A circuit carrying `commissioned-system: pv` or `commissioned-system: backup` is the circuit a SPAN panel adds for a commissioned PV or battery system. It locks both: the relay as above, and `load-shed/priority`, which must be `NEVER` (any other `default-priority` is rejected).

A circuit carrying `shared-with-device-ids`, the comma-separated ids of the other circuits on its breaker, is one of the circuits a multi-load breaker (a tandem or quad) protects behind one CT and one relay. A variant whose circuit profile declares both `meter/shared-with-device-ids` and `switch/shared-with-device-ids` publishes such a breaker as one circuit device per protected circuit, as SPAN does wherever it publishes those lists (spanio/SPAN-API-Client-Docs#21): each circuit names the others in both, and every one publishes the breaker's one reading, which a consumer counts once. Its power is the sum of the circuits' loads, each of which a tick gives as that circuit's own; its energy accumulates once in one register, published on every circuit; and its current is the sum of the circuits' currents in one space or, across two, the larger leg, a single-pole circuit's current lying on its own space and a two-pole circuit's on both. Each circuit keeps its own `breaker/rating`, `breaker/poles` and `info/spaces`, a single-pole circuit listing its one space and a two-pole circuit both: a quad is two two-pole circuits each listing both spaces, a tandem-quad two single-pole circuits and a two-pole one. The breaker has one relay, which shedding acts on, so they share its state (`capabilities/switch.md`, "Shared switching hardware"): a `/set` of `switch/relay` or `load-shed/priority` on any of them, through the emitter's own handlers, applies to all of them, as does `emitter.relays.set_user_override`. Every circuit must name every other, they must agree on what one meter, relay and position fix (`initial-consumed-wh`, `initial-produced-wh`, the relay's lock however `relay-behavior`, `always-on` or `commissioned-system` sets it, `default-priority`, `never-backup` and `placement`), and they must sit where one breaker can, in one space or in the two spaces of a two-pole circuit on it, or the definition is rejected. This is the eBus shared-hardware declaration (`capabilities/meter.md`, "Shared metering hardware"); the specification also models such a breaker as a feed circuit above load circuits that carry only their breakers (`devices/circuit.md`, "Multi-load breakers"), which SPAN plans to move to and no variant publishes yet. The span variant models MAIN 32, which publishes one circuit per breaker space and no shared lists, and neither it nor the reference variant declares either list, so both publish each circuit's own load whatever the key says.

A `bess` carrying `inverter-type: hybrid` has an inverter that also takes PV on its DC side, as solar DC-coupled into a battery's inverter is. That PV never passes through a circuit, so the producer gives it per tick in `TickInputs.bess_pv`, which maps the id of a battery configured with a `BESSConfig` to the watts its PV input produces, positive while producing (a standby draw is negative). A battery left out produces none, and a tick naming a battery that is not `hybrid` or not configured, or giving a value that is not a finite number, raises `EmitterStateError`. In every variant `power-flows/pv` adds this PV to the solar the circuits carry, and the battery's dispatch sees it as solar. It leaves the battery's AC terminals together with the dispatch, so the grid is derived from the upstream lugs less both, while the lugs themselves carry only the circuits. Off grid the battery only discharges and the emitter curtails nothing, so there the four flows balance only while the solar is no more than the load and the battery covers the rest; curtailing any surplus is the producer's, as generating it is. The battery's own `meter/active-power` and `power-flows/battery` stay its charge and discharge. Capture `r202639-f` is such a panel: its battery is upstream of the lugs, and it reports its solar in `power-flows/pv` with no SOLAR circuit and no `pv` device.

A `pv` device that no circuit feeds (it has no `feed`) is taken to join the site upstream of the main lugs, whatever its `relative-position` or `inverter-type`, as AC-coupled solar behind a battery gateway does: that is the one place in this model that is neither a circuit nor the downstream lugs, which carry only downstream-of-lugs circuits. Its production never passes through a circuit, so the producer gives it per tick in `TickInputs.pv`, which maps the id of such a `pv` device to the watts it produces, positive while producing (a standby draw is negative). An inverter left out produces none, and a tick naming an id that is not a `pv` device, a `pv` device that a circuit feeds (that circuit's power already carries its production), or giving a value that is not a finite number, raises `EmitterStateError` before anything moves. In every variant that allows `pv` devices, `power-flows/pv` adds this production to the solar the circuits and any hybrid battery carry, and the battery's dispatch sees it as solar. The grid is derived from the upstream lugs less the battery's dispatch, any hybrid battery's PV and this production, while the lugs, the circuits and `site` are unchanged, and no relay gates it. Off grid the battery only discharges and the emitter curtails nothing, so there the four flows balance only while the solar is no more than the load and the battery covers the rest; curtailing any surplus is the producer's, as generating it is. A `pv` device still publishes only its `info`: its production is published nowhere on its own, only within the panel's flows.

A `remote-ct` instance (no metadata) is a meter on the service conductor, outside the panel. It is published only by `span-alpha-test-b2`, at most one per panel, as a `circuit` device with a `meter` and no `info`, and so no `info/spaces`; before release 202645 it has only the `meter`, and from that release also a `connection` node holding only `connection/connection-point` `MONITORED`, which is how a consumer tells it from a branch circuit. Its `active-power` is the utility-side grid power, positive on import, and `imported-energy` grows on import.

From SPAN release 202645 (the panel's `firmware-version`, or none named), `span-alpha-test-b2` declares `connection/connection-point` on every circuit: `BRANCH` on a branch circuit and `MONITORED` on the `remote-ct`, whose `connection` node carries only that property. Leave the downstream `lugs` row out for a panel without a feedthrough module, which that release publishes without downstream lugs. Identify devices by `$description.type` and their properties, never by their IDs.

Under `span-alpha-test-b2`, a locked relay also locks `load-shed/priority`, and `commissioned-system` is rejected: that variant publishes a PV or battery breaker as an ordinary circuit with a locked relay at `NEVER`. Its solar is a circuit with `feeds-role: SOLAR` or a hybrid battery's PV input, never a `pv` device (a `pv` instance is rejected). The flows follow r202639 firmware: `power-flows/pv` is the SOLAR circuits' powers summed with any hybrid battery's PV, negative while producing; `power-flows/battery` adds the powers of `STORAGE` circuits and a battery's own breaker to the battery's dispatch (so a BESS's `feed` circuit should read 0 in ticks, as captured ticks leave it); `power-flows/site` is the circuits with no role, `LOADS` or `UNUSED` (a surveyed, empty breaker), and a circuit feeding an EVSE whatever its role; with neither a SOLAR circuit nor a battery, `pv` and `battery` are unset. A circuit's power here is its own load as the tick gives it, which on a shared breaker is not the breaker's reading the circuit publishes; no capture shows which of the two the firmware books. A `STORAGE` circuit is metered only: no battery stands behind it, so off-grid the panel islands as one without a battery (no line voltage, no battery as the dominant source); give the battery as a `bess` device to model backup. A circuit with the `GENERATOR`, `SUBPANEL` or `MIXED` role is rejected, since no rule is known for how it is booked; `panel-sim-capture` still captures such a panel, keeps the role, and reports a note naming the circuit. A `remote-ct` meter would add the load it measures upstream of the panel to `site`, but this emitter's `remote-ct` reads the panel's own grid power. A third-party backup system that reports the site's flows from its own meter, as captures `r202639-c` and `r202639-f` show (their `grid` and `site` are not what the panel's lugs and circuits add up to), is modelled only as far as its battery and its inverter's PV: the emitter derives `grid` from its lugs and batteries and `site` from its circuits. No reference capture has a SOLAR-role circuit, so these tests carry the `spec_only` marker.

The keys from `site-name` on the `panel` row, from `tags` on the `circuit` row, and every optional `lugs` key are commissioning facts, checked against the datatype of the property they feed and published verbatim (a number keeps the digits it is written with), only by a variant whose profile declares that property (today `span-alpha-test-b2`). A key absent from the manifest leaves its property unpublished.

The span variant publishes the way the panel's `firmware-version` says its SPAN firmware did. The release build is the first `/`-separated segment that is exactly `r` plus six digits, so `spanos2/r202633/02` is release 202633. Before release 202639 the BESS's `meter/active-power` is the panel's reading of the battery, equal to `power-flows/battery` (positive while charging), and each EVSE's `config/user-max-charge-current` is published at its `max-current-a` until a user sets one. From release 202639, or for a string naming no release such as the examples' `example/v0.1.0`, the BESS meter is the battery's own frame (positive while discharging, the negative of `power-flows/battery`) and the user limit is unpublished until set. `span-alpha-test-b2` always publishes the latter, whatever its firmware. The reference variant always publishes the battery's own frame and declares no `config/user-max-charge-current` at all.

### 3. Panel definition file

A `PanelDefinition` holds everything that fixes a panel's makeup: the `DeviceManifest`, the variant, the native `BESSConfig`s and an optional `LoadSheddingConfig`. `dump_definition` and `load_definition` write and read it as YAML, and `Emitter.from_definition` builds an emitter from one:

```yaml
schema: panel-sim-definition/1
variant: span
devices:
  - class: panel
    id: abc-123
    name: Span Panel
    metadata: {vendor-name: Span, serial-number: abc-123, ...}
  - class: circuit
    id: kitchen
    name: Kitchen
    metadata: {tab-numbers: "1", breaker-rating-a: "20", ...}
bess:
  - {instance_id: abc-123-bess, nameplate_capacity_kwh: 13.5, max_charge_w: 3500.0, max_discharge_w: 3500.0}
load_shedding: {soc_threshold_pct: 20.0}
```

```python
from ebus_panel_sim import Emitter, SetterRegistry, load_definition

emitter = Emitter.from_definition(load_definition("panel.yaml"), SetterRegistry())
```

A device may also give a `description_name`, which it publishes as its `$description.name` in place of `name`; a circuit still publishes `name` as `info/name`. The MAIN 32 capture on release 202639 names each child device by its device ID there. Each device's `metadata` takes the keys in the table above, read exactly as written (`postal-code: 02134` stays `02134`), and any device also takes `unvalued`: a comma-separated list of the properties it declares in its `$description` and never values (`soc/soc,soc/soe` for a battery whose charge the panel does not report), each one its profile must declare. `bess` and `load_shedding` take the fields of `BESSConfig` and `LoadSheddingConfig`, converted to their types. An unknown key, a non-scalar metadata value, or a field of the wrong type is an error.

### 4. Capture a definition from a published panel

`panel-sim-capture` reads a distribution enclosure's published tree and writes a panel definition that reproduces it:

```bash
panel-sim-capture --host <broker> --username <user> --password <pw> --cafile <broker-ca>.crt -o panel.yaml
panel-sim-capture --from-snapshot snapshot.json -o panel.yaml   # a tree-v1 snapshot file
```

Live capture connects over TLS on port 8883 by default and needs either `--cafile` to verify the broker or `--insecure` to skip verification (`--no-tls` and `--port` otherwise). It returns once the tree is complete and has settled, or after `--timeout` seconds with a warning that it is incomplete. Only the distribution enclosure's own device tree is read; `--root` names it when the broker carries more than one. Serial numbers, device IDs, the postal code and the Wi-Fi SSID are masked unless `--no-mask` is given. Circuit names are kept as published; `--generic-names` replaces them with `Circuit 1`, `Circuit 2`, ... in tab order. A device the panel names by its own ID, rather than by its name, is written with that (masked) ID as its `description_name`. A property a device declares and leaves unvalued is written to its `unvalued` list only if the emitter would otherwise publish it: the capture republishes the definition once without the lists, driven by one tick sampled from the tree, and drops every path that stays unvalued anyway. A settable property is left out, since a consumer may set it later. The variant is `span-alpha-test-b2` for a panel whose hardware version string selects it, `span` for any other SPAN panel, and `reference` otherwise, unless `--variant` says. Under `span-alpha-test-b2` the commissioning keys are read back (masking replaces the site's name, address, coordinates and utility meter serial with placeholders, so they stay valued), and a circuit device with only a meter is captured as a `remote-ct`.

A published tree does not carry everything a definition holds. Each value the capture had to default is reported on stderr: BESS charge and discharge limits and charge mode, a PV inverter's or a battery's coupling, panel size where the model name does not give it, and tabs where `info/spaces` is not published (the reference variant). What a definition cannot express is reported and left out: upstream lugs fed by another enclosure, and a MID on a panel without exactly one battery. Captured circuits are placed `upstream-of-lugs`, inside the panel; a battery on a panel breaker stays on it (`relative-position: IN_PANEL`). The solar the panel's `power-flows/pv` reports beyond what its circuits carry, as the variant the panel's hardware version selects books them, is written where the tree's topology puts it. The decision comes from the tree's devices and connections and from whether its panel publishes a pv flow, never from a reading: a tree captured at zero, under a watt or at a standby draw decides as a sunny one does, and its figure is only quoted in the notes. Where the tree holds `pv` devices that no circuit feeds, it is their production, whether or not its panel publishes a pv flow: such an inverter is taken to join the site upstream of the main lugs, and each takes a share in proportion to its published `info/nominal-power`, with a note saying so, since the panel publishes only the total; the shares add back to that solar exactly. Inverters publishing the same figure split it equally, to within float rounding, as capture `main32_r202639-upstream-pv` shows, whose two inverters each publish 11680. A circuit-fed `pv` device or a producing circuit does not stand in the way, since its production is in the circuits already, and no battery is written hybrid. Whatever the tree reads, the solar is reported and left out where the upstream lugs are fed by another enclosure, since a chained panel's pv may report the chain's solar; where downstream lugs name a `pv` device in `connection/feeds-device-id`, which puts it on the feedthrough side; where lugs feed `SOLAR` or `MIXED`, which could bring it; or where one of those inverters publishes no `info/nominal-power`, or one that is not a finite number greater than 0, to divide it by. The definition gives any `pv` device publishing such a rating the default `nominal-power-w`, 5000, that it gives one publishing none, and notes the value it could not use. Where the tree holds no such inverter and its panel publishes a pv flow, whatever its value, a battery is written `inverter-type: hybrid` when nothing else in the tree could bring solar to the panel (no `pv` device, no circuit whose `connection/feeds-role` is `SOLAR`, under any variant, and no lugs feeding `SOLAR` or `MIXED`; a producing circuit does not stand in the way, since its production is in the circuits already), and the battery is the tree's only one: that solar reaches the panel through the battery, and the panel does not say whether it is DC-coupled to the battery's inverter or AC-coupled behind its gateway, which reach it alike. Such solar on any other panel that publishes a pv flow is reported and left out, and a `--variant` other than the one the hardware selects is noted, since the ticks' battery PV and inverters' production are still derived as the latter books circuits. The off-grid SOC shed threshold comes from the published `shed/policy`. `--record N --ticks-output ticks.yaml` also samples a live panel `N` times, `--interval` seconds apart, and writes the samples as replayable ticks (`schema: panel-sim-ticks/1`): each circuit's published power negated back to the producer's sign (circuits that share a meter, publishing its one reading, each given an equal share of it, as below), each EVSE drawing what the tick gives its feeding circuit (a circuit feeding a battery is left out, since the simulated battery's dispatch accounts for it), each battery's link from its `status/communication-state`, a hybrid battery's PV, or the production of the `pv` devices no circuit feeds split by the shares the tree gives them, from the solar the sample's `power-flows/pv` reports beyond what the tick's circuits carry (signed and at any size, so zero gives 0, a fraction of a watt that fraction and a standby draw a negative figure, whatever the tree read, and a sample that publishes no pv gives none), and the grid offline when the MID reports `OFF_GRID` (or, without a MID, the main relay is open). `load_ticks` reads them back:

```python
emitter = Emitter.from_definition(load_definition("panel.yaml"), SetterRegistry())
emitter.start()
for tick in load_ticks("ticks.yaml"):
    emitter.publish_tick(tick)
```

A tick entry's keys are `current_time` and `grid_online` (both required), `circuits` and `evse` (watts by id), and, written only where the tick gives them, `bess_communication` (a battery's link state by id), `bess_pv` (the watts a hybrid battery's PV input produces, by battery id) and `pv` (the watts a `pv` device that no circuit feeds produces, by the device's instance id, positive while producing and negative for a standby draw). A key outside these, or a value that is not a finite number (or, for a link, not a link state), is a `ManifestValidationError`.

Under a variant whose circuit profile declares both `shared-with-device-ids` lists, a panel publishes a shared breaker's one reading on each of its circuits and nothing of each circuit's own load, so the capture gives each an equal share, of their mean should the readings differ, read a moment apart. The shares add back to the reading, to within float rounding, so the breaker's meter republishes its power and energy, and its current in one space or across two where every circuit on it is two-pole. On a tandem or quad whose circuits book into the same flow, the flows and lugs, which the emitter takes from each circuit's own load, republish too, whichever way each circuit draws, since a leg's currents add with their signs. What depends on how the load divides cannot be reproduced:

- circuits whose roles book them into different flows, such as a SOLAR circuit sharing a breaker with a load: `power-flows/pv` and `power-flows/site` each take half the net reading, and the lugs and busbar follow them;
- a tandem-quad: its meter reads the mean of its two spaces instead of the larger, as little as half, and the lugs' legs move;
- an EVSE fed by a circuit on a shared breaker draws that circuit's share, not its own load;
- a battery's circuit on a shared breaker is left out, as every battery circuit is, so the others' shares carry the battery's flow, which its dispatch counts again.

Under `span` and `reference`, which publish each circuit's own load, each circuit keeps the reading it published; `ticks_from_samples` takes the definition's `variant` for this, and the command line passes it.

A circuit's `shared-with-device-ids` keeps only the other circuits in the tree, each entry read without the spaces around it, with a note counting any it drops. Under a variant declaring both lists, the circuits on one breaker are each seeded with the largest register any of them publishes, since it only rises, and circuits that do not all name each other are a capture error. Any other definition the emitter refuses is a `CaptureError`, except one with a circuit role `span-alpha-test-b2` cannot book, which is captured with a note.

`ebus_panel_sim.capture` exposes the same steps as functions (`capture_live`, `tree_from_snapshot`, `tree_from_retained`, `definition_from_tree`, `ticks_from_samples`).

### 5. Replay a reference capture

The package ships masked captures of real SPAN panels as package data: `r202639-a` to `r202639-e`, `main32_r202639` and `main32_r202639-upstream-pv` (a MAIN 32 with its PV inverters and battery upstream of the panel), each a panel on `spanos3/r202639/03`; `r202639-f`, a panel on `spanos3/r202639/04` whose solar is DC-coupled into its battery's inverter; `main32_r202633`, a MAIN 32 on `spanos3/r202633/02`; and six panels on `spanos3/r202645`: `main32_r202645` and `r202645-a`, `-c` and `-e`, the panels of `main32_r202639` and `r202639-a`, `-c` and `-e` on the later release (`r202645-a` with its remote CT) (`r202645-c` recommissioned with different circuits and no battery), and `main32_r202645-cascade` (a MAIN 32 fed by another panel) and `r202645-g` (a MAIN 16 with a battery and a SPAN Drive). A panel keeps its masked serial from one capture to the next, so a pair's trees can be compared device by device: on release 202645 a `span-alpha-test-b2` panel's circuit and lugs device IDs change, and it publishes one lugs device where it has no feedthrough, so align circuits by `info/spaces` and `info/name`, and lugs by `info/direction`. `reference_capture_names()` lists them, and `load_reference_capture(name)` reads one as a `ReferenceCapture`: the `tree` the panel published (a `Tree` of `Device`s, as `ebus_panel_sim.capture` reads one), and a `definition` (a `PanelDefinition`) and `ticks` that republish it. `derived_from_tree` says where those two come from. It is `False` when they were recorded with the capture. It is `True` for `main32_r202633` and `r202639-f`, each a tree alone: the definition is what `definition_from_tree(tree, mask=False)` writes (the tree is masked already) and the ticks are one tick sampled from the tree, the captured instant. Their `notes` (`CaptureNote`s) say what that definition had to default, leave out or read from the flows, as `panel-sim-capture` reports them, such as `main32_r202633`'s upstream lugs being fed by another enclosure and `r202639-f`'s battery being written `hybrid`; a recorded capture's `notes` are empty. Every call reads the files afresh, so the result is the caller's to change. Any other name raises `UnknownReferenceCaptureError`, a `LookupError`.

```python
from ebus_panel_sim import Emitter, SetterRegistry, load_reference_capture

capture = load_reference_capture("r202639-a")
emitter = Emitter.from_definition(capture.definition, SetterRegistry())
emitter.start()
for tick in capture.ticks:
    emitter.publish_tick(tick)
```

The emitter reproduces each capture's tree but for the differences `tests/test_reference_capture_fidelity.py` lists, each with its reason.

## Usage (as a producer library)

```python
import time

from ebus_panel_sim import (
    BESSConfig, DeviceInstance, DeviceManifest, Emitter,
    LoadSheddingConfig, SetterRegistry, TickInputs,
)


def main() -> None:
    manifest = DeviceManifest(instances=(
        DeviceInstance("panel", "abc-123", "Span Panel", metadata={
            "vendor-name": "Span", "serial-number": "abc-123",
            "firmware-version": "sim/v0.1.0", "hardware-version": "rev2",
            "panel-size": "40", "main-breaker-rating-a": "200",
            "panel-model": "MAIN_40", "postal-code": "94103",
            "time-zone": "America/Los_Angeles", "islandable": "true",
        }),
        DeviceInstance("lugs", "abc-123-lugs-up", "Upstream lugs", {"direction": "upstream"}),
        DeviceInstance("circuit", "kitchen", "Kitchen", metadata={
            "tab-numbers": "1", "breaker-rating-a": "20",
            "default-priority": "NICE_TO_HAVE", "relay-behavior": "controllable",
            "placement": "downstream-of-lugs",
        }),
        DeviceInstance("bess", "abc-123-bess", "Battery", metadata={
            "vendor-name": "Span", "nameplate-capacity-kwh": "13.5",
        }),
    ))
    bess_cfg = BESSConfig(instance_id="abc-123-bess", nameplate_capacity_kwh=13.5,
                          max_charge_w=3500.0, max_discharge_w=3500.0)

    # With mqtt_cfg the emitter owns the MQTT connection: ebus-sdk builds the
    # client and sets the enclosure's LWT. (Injecting your own client instead
    # moves both of those to you — see "Bring your own transport" below.)
    # Empty SetterRegistry -> the emitter installs internal default /set
    # handlers; register your own before construction to override them.
    emitter = Emitter(
        manifest, SetterRegistry(),
        mqtt_cfg={"host": "127.0.0.1", "port": 1883},
        bess_configs=(bess_cfg,),
        load_shedding_config=LoadSheddingConfig(soc_threshold_pct=20.0),
    )
    emitter.start()
    try:
        while True:
            emitter.publish_tick(TickInputs(
                current_time=time.time(),
                grid_online=True,
                circuits=collect_powers_from_your_model(),  # instance_id -> signed watts
            ))
            time.sleep(1.0)
    finally:
        emitter.stop()


main()
```

To model the panel losing its link to a battery, report it in the tick: `TickInputs(..., bess_communication={"abc-123-bess": "LOST"})`. The battery publishes it as `status/communication-state`, the connection status of the circuit or lugs connecting it follows, and while a battery link is not known to be healthy (before the first tick, or while any link is not `OK`) the emitter's own handler accepts an `asserted-islanding-state` write, clearing it once every link has been `OK` for 30 seconds (see [DESIGN.md](DESIGN.md#islanding-assertion)).

Read the most recently published state back through `emitter.last_snapshot`. `mqtt_cfg` is handed straight to ebus-sdk: beyond `host`/`port` it takes the ebus-mqtt-client TLS and authentication keys for secured brokers (e.g. broker-quickstart's mTLS `discovery`/`strict` profiles).

### Bring your own transport

A host that already owns an MQTT connection can publish through it instead of having a second one opened underneath: pass `Emitter(..., mqttc=client)` in place of `mqtt_cfg=`. The two are mutually exclusive. This mirrors ebus-sdk's own `Device(mqttc=...)`, and the case it exists for is a host like a Home Assistant add-on, whose MQTT integration is `single_config_entry` and which forbids background threads (`ebus-mqtt-client` 0.4.0's `asyncio_driver()` pumps paho's loop on yours).

**The emitter never starts or stops a client it did not build.** Two things it consequently cannot do for you — register the Last Will, and re-announce the tree on reconnect — are automatic on the `mqtt_cfg` path and yours here. They are steps 1 and 4 below, and the order is forced rather than stylistic:

```python
from ebus_panel_sim import Emitter, SetterRegistry
from ebus_mqtt_client import MqttClient

# 1. The Last Will must exist before the client connects — it rides the CONNECT
#    packet, so it cannot be attached afterwards. This is why it is a
#    staticmethod: there is no Emitter yet, and cannot be.
lwt = Emitter.lwt_settings(manifest)

# 2. Build your client with it, still unconnected.
client = MqttClient.from_config({"host": "127.0.0.1", "port": 1883}, client_id="my-host", lwt=lwt)

# 3. Now the emitter, publishing through it.
emitter = Emitter(manifest, SetterRegistry(), mqttc=client)

# 4. Re-announce the whole tree on every (re)connect. Assigned after construction
#    rather than passed to from_config, because the callback needs the emitter and
#    the emitter needs the client. Invoked with no arguments.
client.on_connect_callback = emitter.republish_tree

# 5. You connect, not the emitter — it never starts a client it did not build.
client.start()
emitter.start()           # returns immediately; it has no connection to wait for
```

To pump paho on your own event loop instead of its background thread — the case a
Home Assistant add-on needs — replace step 5's `client.start()` with the driver,
which is `async` and mutually exclusive with `start()`:

```python
driver = client.asyncio_driver()   # must be called from inside a running loop
await driver.start()
emitter.start()
```

What each buys, and one obligation that is about timing rather than wiring. All three are silent when they bite:

- **No will means no liveness signal.** Skip step 1 and the tree has no LWT at all: a host that dies leaves every consumer reading a stale retained `ready`, indefinitely. `stop(graceful=False)` publishes `$state=lost` itself, but that only covers an orderly teardown — the case where the process *didn't* die.
- **No re-announce means the tree does not come back.** Skip step 4 and a broker that loses its retained store never sees the tree again; what returns is whatever later ticks happen to republish. Measured after wiping a real broker's retained store: 5 topics of 56, every `$description` missing.
- **Let your loop turn before you close the client.** `stop(graceful=False)` *queues* the `lost` on your loop rather than flushing it — flushing would block the very thread that has to run `loop_write`. Closing the client in the same synchronous breath drops the message and leaves the retained tree on `ready`.

## Layout

- `src/ebus_panel_sim/` — the package (`emitter.py`, `manifest.py`, `wire/` profiles + publishing, `native_devices/`, `reference_captures/`); see [DESIGN.md](https://github.com/electrification-bus/distribution-enclosure-simulator/blob/main/DESIGN.md).
- `examples/` — the runnable example and its YAML definition.
- `tests/` — the pytest suite.

## Tests

```bash
uv run pytest
uv run mypy --strict src/ebus_panel_sim tests
uv run ruff check src tests
```

## Contributing

Contributions are welcome. See [CONTRIBUTING.md](https://github.com/electrification-bus/distribution-enclosure-simulator/blob/main/CONTRIBUTING.md) for how to file issues, start a [discussion](https://github.com/electrification-bus/distribution-enclosure-simulator/discussions), and open pull requests, plus the local quality gates (ruff, mypy `--strict`, pytest).

## Credits

A fork of, and building on, the original simulator created by **Bill Flood** ([@cayossarian](https://github.com/cayossarian)); since updated to track the latest eBus specification. See [AUTHORS](https://github.com/electrification-bus/distribution-enclosure-simulator/blob/main/AUTHORS).

## License

See [LICENSE](https://github.com/electrification-bus/distribution-enclosure-simulator/blob/main/LICENSE).
