Skip to content

feat(ems): EV dispatch + Easee command wiring (Phase 4.1) - #101

Merged
frahlg merged 2 commits into
masterfrom
planner-overhaul/ev-dispatch
Apr 18, 2026
Merged

frahlg merged 2 commits into
masterfrom
planner-overhaul/ev-dispatch

Conversation

@frahlg

@frahlg frahlg commented Apr 18, 2026

Copy link
Copy Markdown
Member

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:

  1. Reads each loadpoint's driver telemetry — EV power + session Wh + plug state.
  2. Calls loadpoint.Manager.Observe; the manager infers vehicle SoC as plugin_soc + session_wh / vehicle_capacity. Anchor defaults to 20 %, overridable 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 → 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 already understands that command — it divides by phases, clamps to 6–32 A, and writes dynamicChargerCurrent via the Easee cloud API. 0 W pauses the session cleanly.

New helpers

  • control.SnapChargeW(want, min, max, steps) — nearest-step snap with clamp
  • control.EnergyBudgetToPowerW(remainingWh, remainingS) — the same formula battery dispatch uses

Loadpoint changes

  • Config.PluginSoCPct added (per-loadpoint anchor)
  • Manager.Observe signature simplified — no more external SoC param (the charger can't tell us; manager derives it)
  • Manager resets the session anchor on every plug-in transition so re-plugs don't leak stale delivered-Wh into the new session

Test plan

  • control.TestSnapChargeWSnapsToNearest — step-snap is correct across edges
  • control.TestSnapChargeWNoStepsReturnsClamped — no-step fallback works
  • control.TestEnergyBudgetToPowerW — the Wh→W formula incl. edge cases
  • loadpoint.TestObserveUnpluggedClearsSoCEstimate — no stale SoC after unplug
  • loadpoint.TestObserveNewSessionAnchor — re-plug re-anchors correctly
  • All existing tests pass after Observe signature change
  • go test ./... — full suite incl. e2e (27s) green
  • Erik deploys to Pi, configures a loadpoint for his Easee, verifies MPC schedules EV charging through cheap hours and the charger actually responds.

Config example

loadpoints:
  - id: garage
    driver_name: easee-cloud            # existing Easee driver
    min_charge_w: 1400                  # 1-phase 6 A (~230 V)
    max_charge_w: 11000                 # 3-phase 16 A
    allowed_steps_w: [0, 1400, 4100, 7400, 11000]
    vehicle_capacity_wh: 75000          # 75 kWh
    plugin_soc_pct: 25                  # conservative anchor

After setting a target:

curl -XPOST localhost:8080/api/loadpoints/garage/target \
  -d '{"soc_pct": 80, "target_time_ms": 1745030400000}'

Roadmap

🤖 Generated with Claude Code

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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +787 to +788
if !ok || d.LoadpointEnergyWh == nil {
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +190 to +193
if pluggedIn && !lp.pluggedIn {
// Plug-in transition: seed the session anchor.
anchor := lp.PluginSoCPct
if anchor <= 0 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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"`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@frahlg
frahlg changed the base branch from planner-overhaul/ev-in-dp to master April 18, 2026 05:54
@frahlg
frahlg merged commit cf0170c into master Apr 18, 2026
frahlg added a commit that referenced this pull request Apr 18, 2026
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]>
@frahlg
frahlg deleted the planner-overhaul/ev-dispatch branch August 7, 2026 08:18
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.

1 participant