Repository navigation
feat: plan allocates energy, EMS converts to power (opt-in) - #79
Conversation
Captures the three-principle redesign of the dispatch layer: 1. Planner allocates energy per slot (Wh), not instantaneous power (W) 2. EMS converts energy to power in real time via delivered-vs-target bookkeeping — battery setpoint is derived per tick 3. Grid flow is the residual; no PI loop tracking grid target from the plan-driven path Motivated by the 2026-04-17 incident where the plan's grid target caused the battery to absorb a 4.1 kW PV surprise instead of letting it export during a high-price window. Also proposes a cleaner two-axis mode taxonomy: - planner strategy: self_consumption | arbitrage | cheap_charge - EMS state: follow_plan | manual | idle | auto_fallback Peak shaving, SoC floor/ceiling, backup reserve, and multi-battery split rules move out of the mode enum into always-on constraints or parameters where they belong. Not yet implemented — this is a proposal for team reaction before code. Migration notes, wire contract, and open questions included. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Non-breaking addition alongside existing SlotAt. SlotDirective is the per-slot energy-allocation instruction from planner → EMS under the new dispatch contract (docs/plan-ems-contract.md): - BatteryEnergyWh: total energy for the slot (site-signed) - SlotStart / SlotEnd: window for EMS bookkeeping - SoCTargetPct: plan's expected SoC at slot end — feeds divergence detector - Strategy: planner mode echoed for logging / API SlotAt stays for the legacy grid-target path until that's retired. The control loop will switch to SlotDirectiveAt in a follow-up commit; this one only adds the API surface so tests and the dispatch refactor can start assuming it exists. Tests cover the 200-Wh charge slot, discharge slot (negative energy), stale-plan fallback, out-of-window, and nil-service safety. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ispatch)
Adds the new plan→EMS contract as a second code path in ComputeDispatch,
gated on State.UseEnergyDispatch. Legacy PI-on-grid-target remains the
default and is untouched for anyone not flipping the flag.
When UseEnergyDispatch=true AND the operator is in a planner mode:
- SlotDirective callback returns (battery_energy_wh, slot window, SoC
target, strategy). Directive per slot, not per tick.
- Each tick integrates live battery power × dt into slotDelivered (Wh).
- Target total battery power = (remaining_wh × 3600) / remaining_s.
- Distributed across online batteries by the existing proportional
rule. Slew, SoC clamp, fuse guard — all unchanged.
- No PI on grid. Grid flow is the residual; PV surprises naturally
leak to grid without battery "absorbing" them.
Falls back to the legacy path when SlotDirective returns ok=false.
This preserves today's behavior for a stale plan and means the flag
can be flipped in production without a separate stale-plan handler.
Tests:
- Wh → W conversion (200 Wh, 15 min → 800 W).
- Xorath scenario: 4.8 kW actual PV vs 700 W forecast, plan allocates
200 Wh charge → battery stays at ~800 W instead of ~3.9 kW
absorption. This is the fix.
- Slot rollover resets delivered accumulator.
- Stale-directive fallback routes through the legacy plan-stale branch.
Not yet wired in main.go; UseEnergyDispatch defaults to false. Next
commit adds the wiring + config toggle.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
main.go now wires both plan→EMS callbacks:
- PlanTarget → mpcSvc.SlotAt (legacy grid-target path)
- SlotDirective → mpcSvc.SlotDirectiveAt (energy-allocation path)
The control loop picks which one is actually used based on
State.UseEnergyDispatch, which is loaded from
config.Planner.UseEnergyDispatch. Default off — no behavior change for
existing deploys. Operators enabling it opt in with:
planner:
use_energy_dispatch: true
Once the new path is validated in production the legacy path can be
removed and this flag retired.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
6193066 to
17b9c12
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6193066093
ℹ️ 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".
| state.GridTargetW = 0 | ||
| state.PI.Reset() |
There was a problem hiding this comment.
Keep PI setpoint in sync on energy-dispatch cycles
The energy-dispatch branch zeroes GridTargetW with a direct assignment and resets only the PI integral, but it never updates PI.Setpoint. If the controller later leaves planner mode (for example via /api/mode), the legacy PI path will compute output from a stale setpoint while deadband/error checks use GridTargetW=0, which can produce incorrect corrections (including no correction when export should be absorbed). This is a behavioral regression introduced by bypassing SetGridTarget here.
Useful? React with 👍 / 👎.
The energy-dispatch branch in ComputeDispatch was setting GridTargetW=0 via direct assignment and calling PI.Reset() (which only zeros the integral, not the setpoint). Result: if the operator later left a planner mode — e.g. via POST /api/mode — the legacy PI path would compute error against a stale PI.Setpoint while deadband/error checks used GridTargetW=0. Under those conditions the controller could issue no correction when one was needed (or the wrong correction). Use SetGridTarget(0) so both fields move in lockstep. This mirrors every other caller in the package. Regression test pre-poisons PI.Setpoint + GridTargetW to 3000, runs one energy-dispatch cycle, and asserts both are 0 afterward. Caught by Codex on PR #79. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#84) The energy-dispatch branch in ComputeDispatch was setting GridTargetW=0 via direct assignment and calling PI.Reset() (which only zeros the integral, not the setpoint). Result: if the operator later left a planner mode — e.g. via POST /api/mode — the legacy PI path would compute error against a stale PI.Setpoint while deadband/error checks used GridTargetW=0. Under those conditions the controller could issue no correction when one was needed (or the wrong correction). Use SetGridTarget(0) so both fields move in lockstep. This mirrors every other caller in the package. Regression test pre-poisons PI.Setpoint + GridTargetW to 3000, runs one energy-dispatch cycle, and asserts both are 0 afterward. Caught by Codex on PR #79. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Implements the three-principle dispatch rework described in
docs/plan-ems-contract.md:Opt-in via
planner.use_energy_dispatch: truein config. Default off — zero behavior change for anyone not flipping the flag. Legacy PI-on-grid path untouched.Why
Operator report (2026-04-17): plan said
grid_target_w = −51, actual grid was−18, battery charging ~3.9 kW during a high-price window. Forecast PV = 700 W; reality = 4.8 kW. Instead of exporting the 4 kW surplus at peak price, the PI drove the battery to absorb it — because the plan's intent reached the EMS as "drive grid to −51 W", not as "charge ~800 W from the available PV".Under the new path: plan emits
BatteryEnergyWh = 200for the slot. EMS computesbattery_w = (200 − delivered_wh) × 3600 / remaining_s ≈ 800 W. Grid absorbs the 4 kW surplus naturally. Plan's intent respected. No PI fighting reality.What changes
mpc.SlotDirectiveAt(now) (SlotDirective, bool)— non-breaking addition alongsideSlotAt. Returns{SlotStart, SlotEnd, BatteryEnergyWh, SoCTargetPct, Strategy}.control.State:SlotDirective,UseEnergyDispatch, internalcurrentDirective,slotDelivered,lastTickTs.ComputeDispatchgains a second code path gated onUseEnergyDispatch + SlotDirective set. Falls back to legacy when the directive is unavailable.config.Planner.UseEnergyDispatch(YAML:use_energy_dispatch).main.gowiresmpcSvc.SlotDirectiveAtinto control via a thin adapter.Tests
Four new tests in
control_test.go:TestEnergyDispatchConvertsWhToW— core formula: 200 Wh, 15 min → 800 W.TestEnergyDispatchDoesNotAbsorbPVSurprise— the motivating scenario: 4.8 kW actual PV vs 700 W forecast, plan allocates 200 Wh charge → battery stays at ~800 W instead of ~3.9 kW absorption.TestEnergyDispatchResetsOnSlotRollover— delivered accumulator resets at slot boundary.TestEnergyDispatchFallsBackToLegacyWhenDirectiveUnavailable— stale plan routes through the existing plan-stale branch.Plus five new
SlotDirectiveAttests inmpc/service_test.go(happy path, discharge, stale plan, out-of-window, nil service).Rollout
planner.use_energy_dispatch: trueon a single site (homelab-rpi) and observe for a day or two.Design note
Full rationale + mode taxonomy + migration notes + open questions in
docs/plan-ems-contract.md(223 lines). Read that first if you want the thinking behind the change.Not addressed here (follow-ups)
/api/mpc/diagnosefor ops introspection — separate PR.🤖 Generated with Claude Code