Repository navigation
fix(mpc): exclude EV chargers from MPC battery-pool capacity (investigation PR 3/4) - #121
Conversation
## Problem (Fredrik, live on homelab-rpi)
Config:
drivers:
- name: ferroamp battery_capacity_wh: 15200
- name: sungrow battery_capacity_wh: 9600
- name: easee battery_capacity_wh: 75000 # EV vehicle!
loadpoints:
- id: garage driver_name: easee
`driverCapacitiesFrom` summed ALL drivers with battery_capacity_wh > 0,
so MPC saw 99.8 kWh aggregate battery when the real pool is 24.8 kWh.
Everything downstream (SoC percentages, TerminalSoCPrice credit,
discharge-headroom arithmetic) operated against the inflated pool.
Confirmed from live `/api/mpc/diagnose/at`:
params.capacity_wh: 99800 <- should be 24800
## Fix
`driverCapacitiesFrom(drivers, loadpoints)` now filters out any
driver referenced by a loadpoint. That driver is an EV charger, its
capacity is the VEHICLE battery (not site battery), and it belongs to
the loadpoint's own vehicle_capacity_wh field — not the MPC pool.
- Boot + hot-reload call sites updated to pass cfg.Loadpoints.
- `warnIfEVHasBatteryCapacity` logs at WARN when operator has left
battery_capacity_wh on an EV driver entry, pointing them to
loadpoints[].vehicle_capacity_wh as the right home.
## Tests
- `TestDriverCapacitiesFromExcludesEV` — Fredrik's exact config:
ferroamp + sungrow counted, easee filtered out.
- `TestDriverCapacitiesFromNoLoadpointsBehavesAsBefore` — no-
loadpoint configs behave identically.
- `TestDriverCapacitiesFromMultipleLoadpoints` — two EV chargers
filtered out.
`go test ./...` incl. e2e green.
After deploy Fredrik's next replan should show params.capacity_wh =
24800, terminal_soc_price recomputed against the real pool, and
slot-level discharge decisions unblocked. PR 4 (strict
self_consumption) follows.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d17e9e9112
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for k, v := range driverCapacitiesFrom(newCfg.Drivers, newCfg.Loadpoints) { | ||
| capacities[k] = v | ||
| } |
There was a problem hiding this comment.
Recompute MPC params when capacities change on reload
This reload path only mutates the shared capacities map, but the planner was already constructed earlier with a snapshot (buildMPC sums capacity/max charge into mpc.Params once at startup). After a hot-reload that adds/removes a loadpoint-based EV exclusion, control dispatch sees new capacities while MPC keeps the old capacity_wh, so plans stay wrong until restart even though the callback claims hot-reload support.
Useful? React with 👍 / 👎.
| for _, lp := range loadpoints { | ||
| if lp.DriverName != "" { | ||
| evDrivers[lp.DriverName] = struct{}{} |
There was a problem hiding this comment.
Require valid loadpoints before marking drivers as EV
driverCapacitiesFrom treats any non-empty loadpoints[].driver_name as an EV driver, but loadpoint runtime loading ignores malformed entries (for example empty id), so an invalid/stale loadpoint row can still remove a real battery from MPC/control capacity accounting. This creates a silent capacity drop from config noise instead of only from active/valid loadpoints.
Useful? React with 👍 / 👎.
PR #121 filtered EV drivers from the MPC battery-pool aggregation by matching against `loadpoints[].driver_name`. That works when the operator has migrated to a `loadpoints:` config block, but Fredrik's production Pi has no loadpoints section — so the easee driver's `battery_capacity_wh: 75000` (vehicle capacity) still inflates the MPC pool from ~24.8 kWh to ~99.8 kWh, which is the root cause of the "morning grid import at 50% SoC" incident the strict self_consumption bias (PR #122) was supposed to address. Add a narrow filename-prefix allowlist (easee, ocpp, ctek, chargestorm) as a fallback so the filter fires even without a loadpoints block. Applies the same check to `warnIfEVHasBatteryCapacity` with a slightly different WARN wording so operators know whether the detection came from config reference or filename heuristic. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
) PR #121 filtered EV drivers from the MPC battery-pool aggregation by matching against `loadpoints[].driver_name`. That works when the operator has migrated to a `loadpoints:` config block, but Fredrik's production Pi has no loadpoints section — so the easee driver's `battery_capacity_wh: 75000` (vehicle capacity) still inflates the MPC pool from ~24.8 kWh to ~99.8 kWh, which is the root cause of the "morning grid import at 50% SoC" incident the strict self_consumption bias (PR #122) was supposed to address. Add a narrow filename-prefix allowlist (easee, ocpp, ctek, chargestorm) as a fallback so the filter fires even without a loadpoints block. Applies the same check to `warnIfEVHasBatteryCapacity` with a slightly different WARN wording so operators know whether the detection came from config reference or filename heuristic. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Five issues surfaced by the chatgpt-codex-connector bot across the batch of planner-overhaul PRs shipped earlier today. None catastrophic on Fredrik's current Pi, but all real bugs we'd hit as soon as a second deployment wanted to behave differently. PR #119 P2 — reasonFor() "absorb PV surplus" branch Condition was `!gridExports` which missed both edges: - partial PV absorption (battery charges, grid still exports residual) got labelled generic "charge" - over-charging (battery pulls more than PV provides, grid actually imports) got labelled "absorb PV surplus" Flipped to `!gridImports`. Added two test cases tracing both scenarios (reason_test.go). PR #121 P1 — hot-reload doesn't propagate capacity to MPC `buildMPC` computed totalCap/maxCharge/maxDischarge inline and stored them in `Service.Defaults`. Adding or removing an EV loadpoint via config-reload updated the dispatch-side capacity map but the planner kept optimising against the startup snapshot; SoC% and terminal credit went stale until process restart. - Hoisted the aggregation into `aggregateBatteryLimits()` in main.go so the reload closure can reuse it. - Added `mpc.Service.UpdateCapacity()` which takes the service mutex and swaps Defaults.CapacityWh / Max{Charge,Discharge}W. - Reload closure now calls it after the capacities map is rewritten. PR #121 P2 — invalid loadpoints still exclude drivers `driverCapacitiesFrom` treated any non-empty `driver_name` as an EV reference, but `loadpoint.Manager.Load` rejects rows with empty `id`. Means a malformed config row could silently drop a real battery from the MPC pool. Now requires `lp.ID != ""` before using the driver_name. Same guard applied to `warnIfEVHasBatteryCapacity`. Added regression test. PR #122 P1 — strict SC bias breaks EV deadline priority The 3× multiplier on self_consumption import cost applied to the TOTAL gridKWh (house + EV). Deadline shortfall is penalised at 4× meanPrice. At slot price > 4/3 × meanPrice the DP preferred missing the deadline over charging the EV at peak-hour prices. Rewrote the bias as a +2× effPrice additive penalty on the HOUSE portion of grid import only (load + PV + battery). EV import keeps its plain cost so deadline math stays honest. New test reproduces a 3-slot peak-deadline scenario that starves under the old bias and succeeds under the new one. PR #124 P1 — removed use_energy_dispatch without back-compat Renamed the opt-in field to an opt-out (`legacy_dispatch`) but dropped the old key entirely. Non-strict yaml.Unmarshal silently ignores unknown fields → an operator who explicitly set `use_energy_dispatch: false` (picked legacy on purpose) would silently flip to the energy path on upgrade. Added the field back as `*bool` so main.go can distinguish "unset" (nil) from "explicitly false" and honor prior intent, with a deprecation WARN on startup. Full `go test ./...` incl. e2e stays green. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Five issues surfaced by the chatgpt-codex-connector bot across the batch of planner-overhaul PRs shipped earlier today. None catastrophic on Fredrik's current Pi, but all real bugs we'd hit as soon as a second deployment wanted to behave differently. PR #119 P2 — reasonFor() "absorb PV surplus" branch Condition was `!gridExports` which missed both edges: - partial PV absorption (battery charges, grid still exports residual) got labelled generic "charge" - over-charging (battery pulls more than PV provides, grid actually imports) got labelled "absorb PV surplus" Flipped to `!gridImports`. Added two test cases tracing both scenarios (reason_test.go). PR #121 P1 — hot-reload doesn't propagate capacity to MPC `buildMPC` computed totalCap/maxCharge/maxDischarge inline and stored them in `Service.Defaults`. Adding or removing an EV loadpoint via config-reload updated the dispatch-side capacity map but the planner kept optimising against the startup snapshot; SoC% and terminal credit went stale until process restart. - Hoisted the aggregation into `aggregateBatteryLimits()` in main.go so the reload closure can reuse it. - Added `mpc.Service.UpdateCapacity()` which takes the service mutex and swaps Defaults.CapacityWh / Max{Charge,Discharge}W. - Reload closure now calls it after the capacities map is rewritten. PR #121 P2 — invalid loadpoints still exclude drivers `driverCapacitiesFrom` treated any non-empty `driver_name` as an EV reference, but `loadpoint.Manager.Load` rejects rows with empty `id`. Means a malformed config row could silently drop a real battery from the MPC pool. Now requires `lp.ID != ""` before using the driver_name. Same guard applied to `warnIfEVHasBatteryCapacity`. Added regression test. PR #122 P1 — strict SC bias breaks EV deadline priority The 3× multiplier on self_consumption import cost applied to the TOTAL gridKWh (house + EV). Deadline shortfall is penalised at 4× meanPrice. At slot price > 4/3 × meanPrice the DP preferred missing the deadline over charging the EV at peak-hour prices. Rewrote the bias as a +2× effPrice additive penalty on the HOUSE portion of grid import only (load + PV + battery). EV import keeps its plain cost so deadline math stays honest. New test reproduces a 3-slot peak-deadline scenario that starves under the old bias and succeeds under the new one. PR #124 P1 — removed use_energy_dispatch without back-compat Renamed the opt-in field to an opt-out (`legacy_dispatch`) but dropped the old key entirely. Non-strict yaml.Unmarshal silently ignores unknown fields → an operator who explicitly set `use_energy_dispatch: false` (picked legacy on purpose) would silently flip to the energy path on upgrade. Added the field back as `*bool` so main.go can distinguish "unset" (nil) from "explicitly false" and honor prior intent, with a deprecation WARN on startup. Full `go test ./...` incl. e2e stays green. 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]>
* feat(drivers): add ESPHome P1 / DSMR meter driver
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]>
* fix(configreload): hot-reload site-meter swap
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]>
* fix(esphome): preserve identity and optional meter safety
---------
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Fredrik Ahlgren <[email protected]>
Summary
Part 3 of 4 in the planner-logic investigation round. Fixes the single biggest arithmetic error upstream of Fredrik's Incident B.
The bug, live
driverCapacitiesFromsums every driver withbattery_capacity_wh > 0. Easee's 75 kWh — the car's battery — got counted as site-battery capacity. MPC saw 99.8 kWh of battery pool instead of 24.8 kWh.Confirmed from
/api/mpc/diagnose/aton Fredrik's Pi:Should be 24800. Everything downstream (SoC %, terminal-value credit, DP discharge-headroom) runs against the inflated pool.
Fix
driverCapacitiesFrom(drivers, loadpoints)filters out drivers referenced by anyloadpoints[].driver_name. Simple heuristic, no config schema migration needed.warnIfEVHasBatteryCapacitylogs at WARN when the operator has leftbattery_capacity_whon an EV driver entry, pointing them atloadpoints[].vehicle_capacity_whas the proper field.Boot + hot-reload call sites both updated.
Tests
TestDriverCapacitiesFromExcludesEV— Fredrik's exact config; easee filtered, ferroamp + sungrow kept.TestDriverCapacitiesFromNoLoadpointsBehavesAsBefore— backward compatibility.TestDriverCapacitiesFromMultipleLoadpoints— two EV chargers both filtered.go test ./...incl. e2e — green.What this unblocks
Post-deploy, Fredrik's
params.capacity_whdrops to 24 800.terminal_soc_pricerecomputes. The DP's discharge-vs-idle arithmetic now operates on the real pool, which should already help Incident B. PR 4 (strict self_consumption) closes the remaining gap by making discharge preference explicit rather than emergent.🤖 Generated with Claude Code