Skip to content

feat(mpc): PowerLimits per slot + Loadpoint observable skeleton - #99

Merged
frahlg merged 2 commits into
masterfrom
planner-overhaul/powerlimits-loadpoint
Apr 18, 2026
Merged

frahlg merged 2 commits into
masterfrom
planner-overhaul/powerlimits-loadpoint

Conversation

@frahlg

@frahlg frahlg commented Apr 18, 2026

Copy link
Copy Markdown
Member

Summary

Phase 3 of 4 in the planner overhaul roadmap. Introduces structural pieces for unified battery + EV optimization (Phase 4), without yet activating EV-side control.

PowerLimits — per-slot grid flow caps

New mpc.PowerLimits value type on Slot. Zero-value = unlimited (backwards compatible — no existing call sites need changes).

Use cases inspired by srcful-nova-ems-x:

  • Dynamic-capacity tariffs: ''between 17-20 local, max 5 kW import'' (avoid a peak-kW charge from the DSO)
  • DSO curtailment signals: ''zero export during congestion event''
  • Service-entrance fuse: cap total import even when prices would make aggressive grid-charging attractive

DP respects them after the mode-feasibility check, before the SoC transition. Infeasible actions are skipped.

Loadpoint — EV charge point skeleton

New go/internal/loadpoint package modeling one EV charge point:

  • Config (YAML-facing): id, driver_name, min_charge_w, max_charge_w, allowed_steps_w, vehicle_capacity_wh
  • State (observable): plug status, current SoC %, current power W, delivered Wh this session, user intent (target SoC + target time)
  • Manager: thread-safe registry + reload-preserves-observed-state semantics

Read-only in Phase 3:

  • Configured via new loadpoints: top-level in config.yaml
  • Exposed at GET /api/loadpoints for the UI
  • No driver wiring yet — Observe() exists but isn't called

Deliberately lightweight (~300 LOC vs EVCC's ~20 kLOC). We skip EVCC's hysteresis/enable-delay because the energy-budget dispatch contract is continuous by construction; phase-switching is a driver-local concern.

What Phase 4 will add

  • Extend DP with EV-SoC dimension (11 steps per loadpoint)
  • SlotDirective.LoadpointEnergyWh for per-LP energy budgets
  • EV dispatch mirroring battery dispatch
  • ChargerCap capability + easee-cloud.lua / zap.lua driver support
  • Divergence check per loadpoint
  • POST /api/loadpoints/:id/target for UI target setting

Test plan

  • go test ./internal/mpc/... — 4 new tests covering unlimited default, import/export caps, end-to-end DP respect (passes)
  • go test ./internal/loadpoint/... — 7 tests covering load/reload, state preservation, drop-removed-IDs, target clamping, States() ordering
  • go test ./... — full suite including e2e (27s) green
  • go build ./... — main.go wiring compiles
  • Deploy to Pi, add a test loadpoints: block, curl localhost:8080/api/loadpoints

Roadmap

🤖 Generated with Claude Code

Phase 3 of the planner overhaul. Introduces the structural pieces for
the unified battery + EV optimization coming in Phase 4, without yet
activating EV-side control.

**PowerLimits** — per-slot cap on grid flow (import/export). Zero-value
is unlimited (backwards compatible). Use cases:

- Dynamic-capacity tariffs with peak-charging windows
- DSO curtailment signals during grid congestion events
- Service-entrance current limits that require capping total draw

DP respects them after the mode-feasibility check, before the SoC
transition — infeasible actions are simply skipped. End-to-end tests
verify capped slots stay under limit and uncapped slots still
optimize freely.

**Loadpoint** — new package modeling one EV charge point with driver
association, electrical constraints (min/max/allowed steps), and
observable state (plug, SoC, power, session Wh delivered) + user
intent (target SoC by target time).

Read-only in Phase 3: configured via YAML (`loadpoints:` top-level),
surfaced through `GET /api/loadpoints`, no driver wiring yet. The
Manager preserves observed state across config reloads so hot-edits
don't drop session data.

Deliberately lightweight — ~300 LOC versus EVCC's ~20 kLOC of
loadpoint machinery. We don't need EVCC's hysteresis/enable-delay
because the energy-budget dispatch contract is continuous by
construction; phase-switching is a driver-local concern.

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: b7a8a1081d

ℹ️ 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 thread go/internal/mpc/mpc.go
Comment on lines +273 to +274
if !slot.Limits.allowsImport(gridW) || !slot.Limits.allowsExport(gridW) {
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 Handle no-feasible-action states after applying limits

The new PowerLimits gate can eliminate every candidate action for a (slot, SoC) state, but the DP currently just continues and leaves bestA at its default index 0. In this solver, index 0 is actionAt(0) == -MaxDischargeW (not idle), so the forward pass can emit a synthetic full-discharge command even when no action is feasible under the cap/SoC constraints (for example, tight MaxImportW while already at SoCMinPct). This yields plans that violate the intended hard-limit behavior instead of explicitly handling infeasibility.

Useful? React with 👍 / 👎.

Comment on lines +474 to +475
lpMgr := loadpoint.NewManager()
if len(cfg.Loadpoints) > 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 Reload loadpoint config when applying hot config updates

Loadpoints are initialized from cfg.Loadpoints only in startup, but the config watcher callback does not repopulate lpMgr from newCfg.Loadpoints. As a result, after editing config.yaml at runtime, GET /api/loadpoints can keep returning stale IDs/limits until restart, which is inconsistent with the rest of the hot-reload flow. The loadpoint manager should be refreshed inside the existing reload applier path.

Useful? React with 👍 / 👎.

…werlimits-loadpoint

# Conflicts:
#	go/internal/api/CLAUDE.md
@frahlg
frahlg merged commit 48a5ea0 into master Apr 18, 2026
1 check passed
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/powerlimits-loadpoint 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