Repository navigation
feat(ems): EV dispatch + Easee command wiring (Phase 4.1) - #101
Conversation
Wires the Phase 4 MPC output to the real charger. Every control tick
(5 s default) the main loop now:
1. Reads each loadpoint's driver telemetry (EV power + session Wh +
plug state).
2. Updates loadpoint.Manager with the observation; the manager
infers vehicle SoC from a session plug-in anchor plus delivered
energy (chargers like Easee don't expose the BMS). Anchor
defaults to 20 %, overridable per-loadpoint via the new
`plugin_soc_pct` config field.
3. Asks the MPC for the current slot's energy budget via
`SlotDirective.LoadpointEnergyWh[id]`.
4. Translates remaining Wh / remaining s to instantaneous W (same
energy-allocation contract as battery dispatch), snaps to the
charger's allowed steps, and sends
`{"action":"ev_set_current","power_w": W}` to the loadpoint's
driver.
The existing `easee_cloud.lua` handles that command — divides by
configured phases, clamps to 6-32 A, and sets dynamicChargerCurrent
via the Easee cloud API. 0 W cleanly pauses the charger session
rather than falling through to a below-6 A ignored state.
## New
- `control.SnapChargeW` — nearest-step snapping with clamp
- `control.EnergyBudgetToPowerW` — Wh over remaining s → W
- `loadpoint.Config.PluginSoCPct` — per-loadpoint SoC anchor
- `loadpoint.Manager` infers SoC internally; `Observe()` signature
simplified: no more external SoC param (driver can't tell us the
vehicle's actual BMS state)
## What's still outstanding (follow-up PRs)
- Per-loadpoint divergence check for reactive replan
- UI form for setting target SoC + target time
- 1-phase / 3-phase switching heuristic in easee_cloud.lua
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: 3f23267c5a
ℹ️ 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 !ok || d.LoadpointEnergyWh == nil { | ||
| continue |
There was a problem hiding this comment.
Send explicit 0 W command when EV slot budget is absent
When the current MPC slot has no EV allocation, SlotDirectiveAt can return LoadpointEnergyWh=nil (for example when planned LoadpointW is 0 in go/internal/mpc/service.go), and this branch skips dispatch entirely. For Easee, the last dynamicChargerCurrent setting is sticky, so if the previous slot was charging, the charger can keep drawing power through a supposed 0 W slot because no pause/0-current command is sent.
Useful? React with 👍 / 👎.
| if pluggedIn && !lp.pluggedIn { | ||
| // Plug-in transition: seed the session anchor. | ||
| anchor := lp.PluginSoCPct | ||
| if anchor <= 0 { |
There was a problem hiding this comment.
Preserve session SoC anchor across config reloads
This anchor is only initialized on a !pluggedIn -> pluggedIn transition, but Load() preserves pluggedIn while not preserving sessionPluginSoCPct. After a hot reload during an active charging session, the loadpoint remains marked plugged in, this branch does not run, and the next Observe computes SoC from a zero anchor, causing a sudden SoC drop and incorrect MPC input until unplug/replug.
Useful? React with 👍 / 👎.
| // Current SoC is then estimated as `PluginSoCPct + delivered / cap`. | ||
| // 0 defaults to 20 % (conservative). Operators who care can | ||
| // override per-loadpoint or pre-plug-in. | ||
| PluginSoCPct float64 `yaml:"plugin_soc_pct,omitempty" json:"plugin_soc_pct,omitempty"` |
There was a problem hiding this comment.
Wire
plugin_soc_pct through top-level config parsing
This field is introduced on the runtime loadpoint config, but it is never populated from user YAML because go/internal/config.Loadpoint lacks plugin_soc_pct and the bootstrap copy in main.go does not pass it through. In practice operator-specified anchors are silently ignored and the manager always falls back to the default 20% plug-in SoC.
Useful? React with 👍 / 👎.
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.1 follows #100 and wires the MPC output to the actual Easee charger. Targets
planner-overhaul/ev-in-dp— merge #100 first.Every control tick (5 s default) the main loop now:
loadpoint.Manager.Observe; the manager infers vehicle SoC asplugin_soc + session_wh / vehicle_capacity. Anchor defaults to 20 %, overridable via the newplugin_soc_pctconfig field.SlotDirective.LoadpointEnergyWh[id].{"action":"ev_set_current","power_w": W}to the loadpoint's driver.The existing
easee_cloud.luaalready understands that command — it divides by phases, clamps to 6–32 A, and writesdynamicChargerCurrentvia the Easee cloud API. 0 W pauses the session cleanly.New helpers
control.SnapChargeW(want, min, max, steps)— nearest-step snap with clampcontrol.EnergyBudgetToPowerW(remainingWh, remainingS)— the same formula battery dispatch usesLoadpoint changes
Config.PluginSoCPctadded (per-loadpoint anchor)Manager.Observesignature simplified — no more external SoC param (the charger can't tell us; manager derives it)Managerresets the session anchor on every plug-in transition so re-plugs don't leak stale delivered-Wh into the new sessionTest plan
control.TestSnapChargeWSnapsToNearest— step-snap is correct across edgescontrol.TestSnapChargeWNoStepsReturnsClamped— no-step fallback workscontrol.TestEnergyBudgetToPowerW— the Wh→W formula incl. edge casesloadpoint.TestObserveUnpluggedClearsSoCEstimate— no stale SoC after unplugloadpoint.TestObserveNewSessionAnchor— re-plug re-anchors correctlyObservesignature changego test ./...— full suite incl. e2e (27s) greenConfig example
After setting a target:
curl -XPOST localhost:8080/api/loadpoints/garage/target \ -d '{"soc_pct": 80, "target_time_ms": 1745030400000}'Roadmap
/api/mpc/diagnose(feat(mpc): /api/mpc/diagnose endpoint for per-slot audit #98)🤖 Generated with Claude Code