Skip to content

Add ESPHome DSMR meter driver + hot-reload site-meter swap - #248

Merged
frahlg merged 4 commits into
masterfrom
fix/site-meter-hotreload
Jul 11, 2026
Merged

frahlg merged 4 commits into
masterfrom
fix/site-meter-hotreload

Conversation

@erikarenhill

Copy link
Copy Markdown
Collaborator

Summary

Two related changes shipped together because the second was uncovered by testing the first:

  1. New ESPHome P1 / DSMR meter driver (drivers/esphome_dsmr.lua) — local-HTTP read of any device running ESPHome's dsmr component (e.g. Sourceful Zap on the open-source firmware). Hits /sensor/<id> + /text_sensor/<id> from the standard web_server: version: 3 REST surface, translates DSMR's split-direction reporting (power_consumed − power_produced) into site-convention W, emits per-phase V/A/W + lifetime kWh.

  2. Hot-reload of is_site_meter — flipping the flag in YAML used to require a process restart because ctrl.SiteMeterDriver, mpcSvc.SiteMeter, and loadSvc.SiteMeter were all captured at startup and never refreshed. Discovered the hard way when commissioning the new driver: moved the flag, saved the YAML, watched grid_w peg at 0.

Driver verification

Verified against a live LGF5E360 meter at 192.168.1.147 over multiple sample windows. Every active-power, voltage, and current channel matches the raw OBIS telegram bit-for-bit. Lifetime energy counters match within ~3 Wh of the stock Zap firmware (display rounding on a 22 MWh counter — well below DSMR class-1 accuracy).

Raw OBIS ESPHome Δ
Total W (site) (1.7.0 − 2.7.0)·1000 (power_consumed − power_produced)·1000 bit-equal
Per-phase W 22.7.0 / 42.7.0 / 62.7.0 power_*_lN diff·1000 bit-equal
V L1/L2/L3 32/52/72.7.0 voltage_lN bit-equal
Energy (Wh) 1.8.0 / 2.8.0 ·1000 energy_* ·1000 ±2-3 Wh

Driver robustness

  • Exponential backoff on consecutive poll failures (1 → 2 → 4 → 8 …, capped at 60 s) so a meter that drops off the LAN doesn't get hammered every poll cycle.
  • Reactive-power channels probed once on first poll. Firmwares without them skip the eight reactive HTTP requests forever (~80 ms saved per cycle on stripped-down DIY builds).
  • Serial discovery: tries DSMR equipment_id first, falls back to OBIS meter_identification (LGF5E360 etc.), falls through to MAC ARP / endpoint hash if both empty.
  • Read-only — driver_command rejects everything except init/deinit.

UI fix that came along

The setup wizard's HTTP branch defaulted unknown HTTP drivers to {email, password, serial} (cloud-creds shape) when the catalog had no connection_defaults.host. Local-HTTP meter / PV / battery drivers without a canned hostname (every ESPHome install picks its own mDNS name from the YAML name: field, so no universal default would be right) were mis-classified as cloud. Added a capability gate — meter / pv / battery caps default to {host: ""} regardless of connection_defaults.

Hot-reload fix details

configreload.Watcher.reload() now updates ctrl.SiteMeterDriver inside the same ctrlMu block that gates the other site-level mutations. main.go's applier closure propagates the new name to mpcSvc.SiteMeter and loadSvc.SiteMeter (both pre-declared earlier so the closure can capture them by reference; loadSvc gained the same forward-declaration treatment mpcSvc has used since #121).

Race story: the assignment happens at most once per YAML save (human cadence) and is read once per MPC replan / loadmodel-tick (~1 Hz). Aligned-string writes on amd64/arm64 don't tear in practice, and a one-tick stale value on these paths is harmless — the next tick observes the new name. Matches the pattern the existing applier already uses for ctrl.InverterGroups, ctrl.SupportsPVCurtail, ctrl.SiteFuse*, etc.

Test plan

  • go test ./internal/drivers -run ESPHomeDSMR -count=1 (9 cases — sign correctness, per-phase math, energy conversion, custom-make config, total-read failure, reactive emission, capability-probe gating, backoff sequence + recovery, catalog entry)
  • go test ./internal/configreload -count=1 (4 cases including new TestWatcherUpdatesSiteMeterDriverOnReload)
  • go test ./... -count=1 -short — whole module, 34 packages, all green including e2e
  • Live-fired against 192.168.1.147 from a make dev session — driver booted, discovered serial LGF5E360, started emitting; flipping is_site_meter from ferroamp (sim) to zap-p1 and saving the YAML moved grid_w to match meter_w from the next tick onward, no process restart needed.

🤖 Generated with Claude Code

@frahlg

frahlg commented May 26, 2026

Copy link
Copy Markdown
Member

Approve — driver looks clean. Sign conversion at the boundary ((power_consumed - power_produced) * 1000) matches the site convention, host.set_make + host.set_sn anchor device_id properly, exponential backoff on poll failures, and the hot-reload site-meter swap is correctly serialized under ctrlMu.

Could you rebase onto master before I merge? Looks like there may be conflicts after #309 / recent main changes.

@frahlg

frahlg commented May 27, 2026

Copy link
Copy Markdown
Member

Friendly bump @erikarenhill — last green CI was 2026-05-09 and master has moved meaningfully since (configreload idempotency fix in #337 / #344, several main.go touches). The hot-reload site-meter swap should rebase cleanly against the new Watcher shape, but a rebase + force-push is needed to re-trigger CI. Let me know if you want me to take the rebase off your plate.

erikarenhill and others added 3 commits July 11, 2026 15:19
Local-HTTP meter driver for any ESPHome device running the `dsmr`
component (e.g. Sourceful Zap on the open-source firmware at
github.com/erikarenhill/sourceful-zap-esphome). Reads the standard
`web_server: version: 3` REST surface — `/sensor/<id>` and
`/text_sensor/<id>` — translates DSMR's split-direction reporting
(`power_consumed` − `power_produced`) into site-convention W, and
emits per-phase V/A/W plus lifetime kWh.

Verified against a live LGF5E360 meter at 192.168.1.147: every
active-power, voltage, and current channel matches the raw OBIS
telegram bit-for-bit; lifetime energy counters match within
~3 Wh of the stock Zap firmware (display rounding on a 22 MWh
counter — well below DSMR class-1 accuracy).

Robustness:
  - Exponential backoff on consecutive failures (1 → 2 → 4 → 8 …
    capped at 60 s) so a meter that drops off the LAN doesn't get
    hammered every poll_ms.
  - Reactive-power channels probed once on first poll. Firmwares
    without them skip the eight reactive HTTP requests forever
    (~80 ms saved per cycle on stripped-down DIY builds).
  - Serial discovery: tries DSMR equipment_id first, falls back to
    OBIS meter_identification (LGF5E360 etc.), falls through to
    MAC ARP / endpoint hash if both empty.

UI fix: the new-device wizard's HTTP branch defaulted unknown HTTP
drivers to `{email, password, serial}` (cloud-creds shape) when the
catalog had no `connection_defaults.host`. Local-HTTP meter / PV /
battery drivers without a canned hostname (every ESPHome install
picks its own mDNS name from the YAML `name:` field) were
mis-classified. Added a capability gate — meter / pv / battery
caps default to `{host: ""}` regardless of connection_defaults.

Tests cover sign correctness (importing + exporting), per-phase
math, kWh→Wh conversion, custom-make config override, total-read
failure, reactive emission, capability-probe gating, backoff
sequence, recovery reset, and catalog metadata.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The is_site_meter flag is captured at three places during startup:
ctrl.SiteMeterDriver (control.NewState at main.go:164), mpcSvc.SiteMeter
(line ~634), and loadSvc.SiteMeter (line ~619). The configreload
watcher previously refreshed grid_target / tolerance / slew rate /
dispatch interval but ignored the site-meter pointer, so an operator
moving `is_site_meter: true` between drivers via YAML edit + UI save
ended up with grid_w pegged at 0 once the old driver stopped emitting
— the dispatcher kept calling `tel.Get(<old driver>, DerMeter)`. The
only workaround was a process restart, which surprised me when the
ESPHome driver landed and is_site_meter was flipped onto it live.

The watcher now updates ctrl.SiteMeterDriver inside the same ctrlMu
block that already gates the other site-level mutations, and main.go's
applier closure propagates the new name to mpcSvc.SiteMeter and
loadSvc.SiteMeter (both pre-declared earlier so the closure can
capture them by reference; loadSvc gained the same forward-declaration
treatment mpcSvc has used since #121).

Race story for the field writes on the two services: the assignment
happens at most once per YAML save (~human cadence) and is read
once per MPC replan / loadmodel-tick (~1 Hz). Aligned-string writes
on amd64/arm64 don't tear in practice, and a one-tick stale value
on these paths is harmless — the next tick observes the new name.
This matches the pattern the existing applier already uses for
ctrl.InverterGroups, ctrl.SupportsPVCurtail, etc.

Test exercises a YAML rewrite that moves is_site_meter from
ferroamp to zap-p1, asserts ctrl.SiteMeterDriver flips to "zap-p1"
without a process restart.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@frahlg
frahlg force-pushed the fix/site-meter-hotreload branch from 93fb955 to 48e8fa7 Compare July 11, 2026 13:23
@frahlg
frahlg merged commit 07a5ae5 into master Jul 11, 2026
2 checks passed
@frahlg
frahlg deleted the fix/site-meter-hotreload branch July 11, 2026 16:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants