Repository navigation
feat(mpc): unified battery + EV MPC (Phase 4 — ONE system) - #100
Conversation
The planner now co-optimizes the home battery and an EV loadpoint in
a single DP instead of leaving EV charging to an external scheduler.
Matches the user's goal: one system that sees the full site's energy
flow (battery + PV + EV + grid) and avoids the "two planners fighting"
problem that shows up when EVCC and MPC both try to own the same
surplus window.
## DP extension
- State: (t, battery_soc, ev_soc)
- Action: (battery_action, ev_action)
- EV action set is DISCRETE — the charger's allowed W levels — so the
1-phase ↔ 3-phase minimum-current gap gets handled naturally without
needing MILP (a classic LP pain-point). Taken from srcful-nova-ems-x
lessons but simpler by staying in Go.
Bilinear interpolation over both SoC dimensions preserves fractional
state progress — without this, a 15-min charge of 4.1 % on a 10 %
bucket resolution would round to "no progress" and the DP would
refuse to charge. Bucketing vs. interpolation is the quiet-but-sharp
edge case here.
Backwards-compatible: when no loadpoint probe is wired or no EV is
plugged in, the EV dimension collapses to size 1 — the DP runs
identically to the battery-only path. Regression test
`TestOptimizeNilLoadpointUnchanged` locks this in.
## Target + deadline (lexicographic-style)
User intent (target SoC by target time) maps to a horizon slot index.
Deadline slot gets a shortfall penalty of missed_kwh × mean_price × 4
— factor 4 tuned to dominate a single-slot charging cost so the DP
commits when feasible, with graceful degradation (max delivered
energy) when infeasible.
## Public surface
- `mpc.LoadpointSpec` — DP-side EV description
- `mpc.LoadpointProbe` — closure type wired from loadpoint.Manager
- `Service.Loadpoint` optional func field (avoids mpc → loadpoint
package import)
- `Action.LoadpointW` + `Action.LoadpointSoCPct`
- `SlotDirective.LoadpointEnergyWh[id]` + `LoadpointSoCTargetPct[id]`
- `POST /api/loadpoints/{id}/target {"soc_pct": 80, "target_time_ms": …}`
triggers a replan
## What's deferred to Phase 4.1
- `drivers.ChargerCap` interface + Lua bindings (needs real-hardware
verification; keep scope tight)
- EV dispatch path in control/dispatch.go (energy → W snap-to-steps)
- Per-loadpoint divergence check for reactive replan
- UI target-setting form
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: 9053bcf6c7
ℹ️ 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".
| if !st.TargetTime.IsZero() { | ||
| delta := time.Until(st.TargetTime) | ||
| if delta > 0 { | ||
| targetSlot = int(delta / (15 * time.Minute)) |
There was a problem hiding this comment.
Map EV target time to the correct MPC slot
The deadline index is computed as int(delta / (15 * time.Minute)), but TargetSlotIdx is consumed as the slot whose end must satisfy the target and slot duration is not guaranteed to be 15 minutes (buildSlots follows price row slot sizes). This makes deadlines late by at least one slot even on 15-minute plans (e.g., 1h ahead maps to slot 4 instead of 3) and much later on hourly plans, so the shortfall penalty is applied too late and the optimizer can miss the user’s requested target time.
Useful? React with 👍 / 👎.
| if a.LoadpointW > 0 && s.lastLoadpointID != "" { | ||
| lpEnergyWh := a.LoadpointW * float64(a.SlotLenMin) / 60.0 | ||
| d.LoadpointEnergyWh = map[string]float64{ | ||
| s.lastLoadpointID: lpEnergyWh, |
There was a problem hiding this comment.
Snapshot loadpoint ID under the same lock as plan
SlotDirectiveAt reads s.last under RLock but later reads s.lastLoadpointID without any lock, while replan updates both together under mu. If a replan happens between those reads, a directive can pair one plan with another loadpoint ID and route EV energy to the wrong charger; this is also a concurrent read/write race on lastLoadpointID in loadpoint-active systems.
Useful? React with 👍 / 👎.
…-in-dp # Conflicts: # docs/mpc-planner.md # go/internal/api/CLAUDE.md # go/internal/mpc/service.go
Bundles 8 issues Codex flagged across PRs #97-#101. Ordered by what blocks Erik's hardware testing most. ## P1 — charger kept running after slot ended (#101) When the current MPC slot had no EV allocation, the dispatch loop `continue`d without sending any command. Easee would keep drawing at its previous setpoint — including across a "stop charging" slot transition. Now we default cmdW=0 and always send the explicit ev_set_current command so the charger actively stands down. ## P1 — plugin_soc_pct never reached the runtime (#101) Added to loadpoint.Config in Phase 4.1 but never copied from YAML. Config knob was a no-op. Plumbed through config.Loadpoint and centralised the YAML→runtime mapping in a new buildLoadpointConfigs helper so boot-time init and hot-reload can't drift. ## P1 — TargetSlotIdx assumed 15-min slots (#100) Hard-coded `int(delta / (15 * time.Minute))` in main's LoadpointProbe, but Nordic day-ahead prices come as 60-min slots. A 2-hour deadline on hourly data mapped to slot 8, not slot 2 — DP thought it had 4× the time it actually did. LoadpointProbe now takes slotLenMin from the actual plan and mpc.Service passes it in from slots[0].LenMin. ## P1 — race on lastLoadpointID (#100) SlotDirectiveAt read s.last under RLock then s.lastLoadpointID outside. A concurrent replan could swap one without the other and produce a directive keyed under the wrong driver. Snapshot both under the same lock. ## P1 — infeasible DP states picked full-discharge fallback (#99) When mode + PowerLimits eliminated every action at a (slot, soc, ev) state, bestV stayed +Inf but bestPolicy defaulted to 0 — which encodes (ba=0, ea=0) = "full battery discharge, EV off", the WORST possible fallback. Now overrides bestPolicy to the closest-to-idle action index ((A-1)/2 * EA), so forward-sim produces a sane plan even in operator-induced infeasibility. ## P1 — persisted PV/load models misaligned after UTC switch (#97) pvmodel's β coefficients were fitted against local-zone hour-of-day harmonic features; loadmodel's buckets were indexed on local weekday+hour. After the Phase 1 UTC coercion in Features / HourOfWeek, restoring the old state silently misaligned both models against the new coordinate system. Bumped state keys (`pvmodel/state` → `pvmodel/state_utc`, `loadmodel/state` → `loadmodel/state_utc`) so old state is ignored on upgrade — model retrains from telemetry over a day or so. ## P2 — config hot-reload didn't touch loadpoints (#99) configreload callback skipped newCfg.Loadpoints entirely. Added a Load() call on the manager inside the callback — the manager preserves observed state across reloads, so adding / tuning loadpoints live no longer needs a process restart. ## P2 — session anchor lost on config reload (#101) loadpoint.Manager.Load preserved pluggedIn and delivered_wh_session but not sessionPluginSoCPct. A hot-reload mid-charge would reset the SoC inference baseline back to PluginSoCPct, making the estimate jump backward even though the car kept getting energy. Carry the anchor too. ## Tests - Added `TestOptimizeInfeasibleStatePicksNearIdle` covering the DP fallback. - All existing tests still pass incl. e2e (27s). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Phase 4 of 4 in the planner overhaul roadmap. Delivers on the user's explicit goal: ETT system that co-optimizes home battery + PV + EV in one DP instead of two planners negotiating.
This PR targets ''planner-overhaul/powerlimits-loadpoint'' (Phase 3) and assumes those types are present. Please merge #99 first.
DP extension
State:
(t, battery_soc, ev_soc).Action:
(battery_action, ev_action).EV action set is discrete (charger's allowed W levels). This elegantly handles the 1-phase ↔ 3-phase minimum-current gap that would otherwise require MILP — a key pain-point in CVXPY-style formulations (see srcful-nova-ems-x for the Python equivalent).
Bilinear interpolation over both SoC dimensions preserves fractional state progress. Without this, a 15-min charge that advances EV SoC by 4.1 % on a 10 % bucket resolution would round to "no progress" and the DP would refuse to charge. Caught this bucketing edge case via
TestSlotDirectiveCarriesLoadpointEnergyWh.Backwards-compatible: when no loadpoint probe is wired or no EV is plugged in, the EV dimension collapses to size 1 — the DP runs identically to the battery-only path.
TestOptimizeNilLoadpointUnchangedlocks this in.Target + deadline (lexicographic-style)
User intent (
POST /api/loadpoints/{id}/target) sets target SoC + target time. Maps to horizon slot index. Deadline slot getsmissed_kwh × mean_price × 4penalty — tuned so meeting target dominates any single-slot charging cost, with graceful degradation (max delivered energy) when infeasible.Public surface
mpc.LoadpointSpec— DP-side EV descriptionmpc.LoadpointProbe— closure type wired fromloadpoint.Manager(keeps mpc free of a loadpoint import)Service.Loadpointoptional func fieldAction.LoadpointW+Action.LoadpointSoCPctSlotDirective.LoadpointEnergyWh[id]+LoadpointSoCTargetPct[id]POST /api/loadpoints/{id}/targettriggers a replan so new intent lands in the next schedule within one tickDeferred to Phase 4.1 (follow-up PR)
drivers.ChargerCapinterface + Lua bindings (easee-cloud.lua + zap.lua needhost.set_charge_power_w— real-hardware verification scope)control/dispatch.go(energy → W snap-to-discrete-steps)Test plan
TestOptimizePrefersCheapSlotsForEV— DP schedules EV in cheap slots, skips expensive onesTestOptimizeNilLoadpointUnchanged— legacy path identical with nil or unplugged loadpointTestSlotDirectiveCarriesLoadpointEnergyWh— service routes DP's EV decision under loadpoint IDTestSlotDirectiveEmptyWhenNoLoadpoint— legacy path leaves LP fields nilTestNormalizedStepsDefaults+TestActiveGate— spec helpersgo test ./...— full suite incl. e2e (27s) greengo build ./...— main.go wiring compiles/api/mpc/planshowsloadpoint_wper slotRoadmap
/api/mpc/diagnose(feat(mpc): /api/mpc/diagnose endpoint for per-slot audit #98)🤖 Generated with Claude Code