Skip to content

feat(loadpoint,api): manual_hold diagnostics endpoint - #206

Merged
erikarenhill merged 5 commits into
masterfrom
feat-loadpoint-manual-hold
Apr 27, 2026
Merged

erikarenhill merged 5 commits into
masterfrom
feat-loadpoint-manual-hold

Conversation

@erikarenhill

Copy link
Copy Markdown
Collaborator

Summary

Adds a per-loadpoint manual override so operators can pin a specific dispatch payload (power_w + phase preferences + site fuse params) on the charger for a bounded window, bypassing MPC. The control tick (every 5 s) would otherwise overwrite any externally-injected command — making controlled hardware tests impossible. With this endpoint:

POST /api/loadpoints/garage/manual_hold
{
  \"power_w\": 1380,
  \"phase_mode\": \"auto\",
  \"voltage\": 230,
  \"max_amps_per_phase\": 16,
  \"hold_s\": 60
}

→ controller pins this payload on every tick for the next 60 s, then resumes normal MPC-driven dispatch.

Endpoints

Method Path Purpose
POST /api/loadpoints/{id}/manual_hold Install hold
DELETE /api/loadpoints/{id}/manual_hold Cancel hold
GET /api/loadpoints/{id}/manual_hold Read current hold state

Validation: `hold_s` in (0, 1800], `power_w >= 0`, `phase_mode` ∈ {"", auto, 1p, 3p}. 503 when `LoadpointCtrl` isn't wired, 404 on unknown loadpoint id.

Implementation

Controller-side: `loadpoint.ManualHold` struct + sync.Mutex-protected `map[loadpoint_id]ManualHold` on the Controller. `tickOne` checks the hold first; if active and unexpired, sends the held payload verbatim, bypassing `computeCommand` entirely. Expired holds are lazily evicted on the next read. Per-loadpoint, isolated, no shared state with the MPC budget path.

API-side: handler lives in `api_loadpoint_manual.go` per the api/CLAUDE.md split convention. `Deps.LoadpointCtrl` is the new wired field; `main.go` passes `lpController`.

Why a separate primitive

This is not the operational interface. The 30-minute upper bound on `hold_s` ensures a forgotten override can't permanently shadow MPC dispatch. It exists for:

  1. Hardware bring-up tests of driver-level phase decisions (the immediate use case after PR feat(loadpoint,easee): 1Φ/3Φ auto-switching with per-phase fuse clamp #203 landed phase switching).
  2. Operator diagnostics when a charger is misbehaving and you want to isolate the driver from the controller's behaviour.
  3. Future: a UI "manual mode" toggle if we ever want one.

Tests

  • 6 controller tests (`controller_manual_hold_test.go`): install / read / clear / expiry / payload propagation / unknown-loadpoint safety.
  • 5 API tests (`api_loadpoint_manual_test.go`): 503 without controller, 404 on bad id, validation matrix, full install→GET→DELETE lifecycle.
  • `go test ./...` green incl. `test/e2e`.

🤖 Generated with Claude Code

erikarenhill and others added 3 commits April 26, 2026 19:07
Adds a per-loadpoint dispatch override so an operator can pin a
specific power_w + phase configuration on the charger long enough
to observe driver behaviour without fighting the 5-second control
tick. Used to test driver-level phase decisions on real hardware.

Controller side:

  * loadpoint.ManualHold — plain struct: power, phase prefs, site
    fuse params, expires_at.
  * Controller.SetManualHold / ClearManualHold / GetManualHold —
    sync.Mutex-protected map[loadpoint_id]ManualHold.
  * tickOne checks the hold first; if active and unexpired it sends
    the held payload verbatim, bypassing computeCommand entirely.
  * Expired holds are lazily evicted on the next read.
  * 6 tests in controller_manual_hold_test.go covering install,
    expiry, clear, payload propagation, unknown loadpoint.

API side:

  * POST /api/loadpoints/{id}/manual_hold — install hold
  * DELETE /api/loadpoints/{id}/manual_hold — cancel
  * GET /api/loadpoints/{id}/manual_hold — read state
  * Validation: hold_s in (0, 1800], power_w >= 0, phase_mode in
    {"", auto, 1p, 3p}.
  * 503 when LoadpointCtrl isn't wired (e.g. no MPC), 404 on
    unknown loadpoint id, 400 on validation, 200 on success.
  * 5 tests in api_loadpoint_manual_test.go.

Wiring:

  * Deps.LoadpointCtrl added; main.go passes lpController.
  * Routes registered in api.go's routes() table.
  * Handler lives in api_loadpoint_manual.go per the
    api/CLAUDE.md split convention.

Out-of-scope: this endpoint is a diagnostics primitive — not
intended for routine operation. The 30-minute upper bound on hold_s
ensures a forgotten override can't permanently override MPC.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous driver implementation picked 1Φ vs 3Φ from a split-W
threshold and wrote phaseMode=1 or =3 explicitly. That fights with
Easee's own firmware-side automatic phase switching when the
operator has it enabled, AND adds a 5 s controller-tick + cloud
round-trip to every flip — Easee's firmware handles the same
decision sub-second.

Now:

  * phase_mode = "auto" → phaseMode = 2 (let Easee firmware decide)
  * phase_mode = "1p"   → phaseMode = 1 (lock single-phase)
  * phase_mode = "3p"   → phaseMode = 3 (lock three-phase)
  * phase_mode = ""     → phaseMode = 3 (legacy default)

Removes pick_phases() + the per-driver hysteresis state machine —
Easee owns those concerns when in auto. The driver still owns
amperage clamping (per-phase fuse, Easee 0/6/32 A band) and the
phaseMode-fail-safe early-return on phase transition.

Trade-off: when phase_mode=auto, the driver no longer KNOWS which
phase Easee picked; it computes amps assuming 3Φ. If Easee
firmware-auto falls back to 1Φ, the EV gets 1/3 the requested power
this tick. That's acceptable because (a) the controller re-sends
every 5 s and (b) Easee firmware-auto's 1Φ fall-back is rare on
typical EVs (it only triggers when 3Φ would be below the EV's 6 A
minimum). Operators who need explicit 1Φ low-W charging should set
phase_mode = "1p" instead of relying on auto.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds a diagnostics “manual hold” mechanism for EV loadpoints so operators can temporarily pin a fixed ev_set_current dispatch payload (power + phase preferences + fuse params) that bypasses the normal MPC-driven dispatch until expiry.

Changes:

  • Add ManualHold state to the loadpoint controller and make tickOne prefer an active hold over the MPC plan path.
  • Add /api/loadpoints/{id}/manual_hold POST/GET/DELETE endpoints to install, read, and clear holds (wired via Deps.LoadpointCtrl).
  • Add controller + API test coverage for lifecycle, validation, and expiry behavior.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
go/internal/loadpoint/controller.go Introduces ManualHold registry and dispatch override behavior in tickOne.
go/internal/loadpoint/controller_manual_hold_test.go Adds unit tests for controller manual-hold semantics (override, expiry, clear, safety).
go/internal/api/api_loadpoint_manual.go Implements the manual-hold API endpoints and validation.
go/internal/api/api_loadpoint_manual_test.go Adds API tests for validation, wiring, and basic lifecycle.
go/internal/api/api.go Adds Deps.LoadpointCtrl and registers the new routes.
go/cmd/forty-two-watts/main.go Wires lpController into the API deps as LoadpointCtrl.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread go/internal/loadpoint/controller.go Outdated
Comment on lines +222 to +242
// Manual override active — use the hold's payload verbatim.
// Skips MPC translation AND the loadpoint's own phase
// preferences; everything comes from the operator's hold.
cmd["power_w"] = hold.PowerW
if hold.PhaseMode != "" {
cmd["phase_mode"] = hold.PhaseMode
}
if hold.PhaseSplitW > 0 {
cmd["phase_split_w"] = hold.PhaseSplitW
}
if hold.MinPhaseHoldS > 0 {
cmd["min_phase_hold_s"] = hold.MinPhaseHoldS
}
if hold.Voltage > 0 {
cmd["voltage"] = hold.Voltage
}
if hold.MaxAmpsPerPhase > 0 {
cmd["max_amps_per_phase"] = hold.MaxAmpsPerPhase
}
if hold.SitePhases > 0 {
cmd["site_phases"] = hold.SitePhases

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

In the manual-hold path, the controller only emits fuse/phase fields if they’re explicitly present in the hold; it does not fall back to lpCfg or c.site. This means a minimal hold (e.g. only power_w/expiry) will drop max_amps_per_phase/voltage/site_phases and phase preferences that are normally sent, which can remove the driver-side per-phase fuse clamp (see drivers/easee_cloud.lua clamping logic) and change behavior vs normal dispatch. Consider defaulting missing hold fields to the loadpoint config + site fuse (or explicitly requiring these fields in the API) to keep holds safe and consistent.

Suggested change
// Manual override active — use the hold's payload verbatim.
// Skips MPC translation AND the loadpoint's own phase
// preferences; everything comes from the operator's hold.
cmd["power_w"] = hold.PowerW
if hold.PhaseMode != "" {
cmd["phase_mode"] = hold.PhaseMode
}
if hold.PhaseSplitW > 0 {
cmd["phase_split_w"] = hold.PhaseSplitW
}
if hold.MinPhaseHoldS > 0 {
cmd["min_phase_hold_s"] = hold.MinPhaseHoldS
}
if hold.Voltage > 0 {
cmd["voltage"] = hold.Voltage
}
if hold.MaxAmpsPerPhase > 0 {
cmd["max_amps_per_phase"] = hold.MaxAmpsPerPhase
}
if hold.SitePhases > 0 {
cmd["site_phases"] = hold.SitePhases
// Manual override active — skip MPC translation, but preserve the
// loadpoint/site defaults for phase and fuse related fields unless
// the operator explicitly overrides them in the hold.
cmd["power_w"] = hold.PowerW
if hold.PhaseMode != "" {
cmd["phase_mode"] = hold.PhaseMode
} else if lpCfg.PhaseMode != "" {
cmd["phase_mode"] = lpCfg.PhaseMode
}
if hold.PhaseSplitW > 0 {
cmd["phase_split_w"] = hold.PhaseSplitW
} else if lpCfg.PhaseSplitW > 0 {
cmd["phase_split_w"] = lpCfg.PhaseSplitW
}
if hold.MinPhaseHoldS > 0 {
cmd["min_phase_hold_s"] = hold.MinPhaseHoldS
} else if lpCfg.MinPhaseHoldS > 0 {
cmd["min_phase_hold_s"] = lpCfg.MinPhaseHoldS
}
if hold.Voltage > 0 {
cmd["voltage"] = hold.Voltage
} else if v := c.site.Voltage; v > 0 {
cmd["voltage"] = v
}
if hold.MaxAmpsPerPhase > 0 {
cmd["max_amps_per_phase"] = hold.MaxAmpsPerPhase
} else if c.site.MaxAmps > 0 {
cmd["max_amps_per_phase"] = c.site.MaxAmps
}
if hold.SitePhases > 0 {
cmd["site_phases"] = hold.SitePhases
} else if c.site.MaxAmps > 0 {
cmd["site_phases"] = c.site.Phases()

Copilot uses AI. Check for mistakes.
Comment thread go/internal/api/api_loadpoint_manual.go Outdated
Comment on lines +22 to +24
// optional except hold_s; defaults match the loadpoint's configured
// values + the wired site fuse, so a minimal {hold_s: 30, power_w: X}
// works for the common case.

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

The request type comment says omitted fields default to the loadpoint’s configured values + the wired site fuse, but the handler currently forwards zero-values into loadpoint.ManualHold without applying any defaults. Either implement the described defaulting (so minimal bodies behave as documented) or adjust the comment to match the actual behavior (omitted fields are omitted from the cmd, so the driver falls back to its own defaults).

Suggested change
// optional except hold_s; defaults match the loadpoint's configured
// values + the wired site fuse, so a minimal {hold_s: 30, power_w: X}
// works for the common case.
// optional except hold_s. Omitted fields are omitted from the manual
// hold command as well, allowing downstream loadpoint/driver logic to
// apply any defaults it supports.

Copilot uses AI. Check for mistakes.
Comment thread go/internal/api/api_loadpoint_manual.go Outdated
Comment on lines +67 to +72
if s.deps.Loadpoints != nil {
if _, ok := s.deps.Loadpoints.State(id); !ok {
writeJSON(w, 404, map[string]string{"error": "loadpoint not found"})
return
}
}

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

POST currently only checks Loadpoints.State(id) when s.deps.Loadpoints != nil; if loadpoints aren’t configured, this will allow installing a hold for an arbitrary id (contrary to the other per-loadpoint endpoints which return 404 loadpoints not configured). Consider returning 404 when Loadpoints is nil and always validating that the id exists before installing a hold, to match the endpoint contract (“404 on unknown loadpoint id”).

Suggested change
if s.deps.Loadpoints != nil {
if _, ok := s.deps.Loadpoints.State(id); !ok {
writeJSON(w, 404, map[string]string{"error": "loadpoint not found"})
return
}
}
if s.deps.Loadpoints == nil {
writeJSON(w, 404, map[string]string{"error": "loadpoints not configured"})
return
}
if _, ok := s.deps.Loadpoints.State(id); !ok {
writeJSON(w, 404, map[string]string{"error": "loadpoint not found"})
return
}

Copilot uses AI. Check for mistakes.
Comment thread go/internal/api/api_loadpoint_manual.go Outdated
case "", "auto", "1p", "3p":
default:
writeJSON(w, 400, map[string]string{
"error": "phase_mode must be one of: auto, 1p, 3p",

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

The handler accepts phase_mode == "" (treated as “unspecified”), but the error message omits that option. Update the error message to include the empty/omitted case (or reject empty strings explicitly and require the client to omit the field).

Suggested change
"error": "phase_mode must be one of: auto, 1p, 3p",
"error": "phase_mode must be omitted/empty or one of: auto, 1p, 3p",

Copilot uses AI. Check for mistakes.
Comment on lines +118 to +130
func (s *Server) handleLoadpointManualHoldClear(w http.ResponseWriter, r *http.Request) {
if s.deps.LoadpointCtrl == nil {
writeJSON(w, 503, map[string]string{"error": "loadpoint controller not available"})
return
}
id := r.PathValue("id")
if id == "" {
writeJSON(w, 400, map[string]string{"error": "id required"})
return
}
s.deps.LoadpointCtrl.ClearManualHold(id)
writeJSON(w, 200, manualHoldResponse{Active: false})
}

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

DELETE clears holds for any id without checking whether the loadpoint exists. The PR description says unknown ids should return 404, and other per-loadpoint endpoints validate existence via Loadpoints.State/SetTarget. Consider returning 404 when Loadpoints is nil (“loadpoints not configured”) and 404 when id isn’t a configured loadpoint.

Copilot uses AI. Check for mistakes.
Comment on lines +135 to +147
func (s *Server) handleLoadpointManualHoldGet(w http.ResponseWriter, r *http.Request) {
if s.deps.LoadpointCtrl == nil {
writeJSON(w, 503, map[string]string{"error": "loadpoint controller not available"})
return
}
id := r.PathValue("id")
if id == "" {
writeJSON(w, 400, map[string]string{"error": "id required"})
return
}
h, active := s.deps.LoadpointCtrl.GetManualHold(id, time.Now())
writeJSON(w, 200, manualHoldResponseFrom(h, active))
}

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

GET returns {active:false} with 200 for unknown loadpoint ids. If the endpoint contract is “404 on unknown loadpoint id” (as described in the PR), this should validate the id against deps.Loadpoints similarly to the POST handler / other loadpoint endpoints, and return 404 when not configured or unknown.

Copilot uses AI. Check for mistakes.
Comment thread go/internal/loadpoint/controller.go Outdated
// `POST /api/loadpoints/{id}/manual_hold` so an operator can pin
// a specific amperage / phase configuration on the charger for
// long enough to observe driver behaviour, without fighting the
// 5-second control loop. nil entries (or expired ones) fall

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

The struct comment says “nil entries … fall through”, but holds is a map[string]ManualHold (value type), so entries can’t be nil. This is misleading—consider rewording to “missing entries” / “no active hold” (expired holds are deleted in GetManualHold).

Suggested change
// 5-second control loop. nil entries (or expired ones) fall
// 5-second control loop. Missing entries (or expired holds) fall

Copilot uses AI. Check for mistakes.
Seven findings, all valid:

  * controller.go:242 — manual hold dropped voltage / max_amps_per_phase
    / phase prefs when not explicitly set, removing the driver-side
    per-phase fuse clamp on minimal `{power_w, hold_s}` holds. Fall
    through to lpCfg + c.site for missing fields; explicit values
    still override. Safety regression fix.
  * controller.go:50 — struct comment said "nil entries"; map values
    are not nil. Reworded to "missing entries (or expired holds)".
  * api_loadpoint_manual.go:24 — request-doc comment now matches the
    actual fall-through semantics.
  * api_loadpoint_manual.go:72 — POST: 404 when Loadpoints is nil
    (was: silently allowed install on arbitrary id).
  * api_loadpoint_manual.go:96 — phase_mode error message now mentions
    the omitted/empty case.
  * api_loadpoint_manual.go:130 — DELETE validates id (404 on missing
    or unknown loadpoint).
  * api_loadpoint_manual.go:147 — GET validates id (same).

Tests:

  * 3 new controller tests:
    - TestManualHoldFallsThroughToLoadpointAndSiteDefaults
    - TestManualHoldFallsThroughToNonStandardSiteFuse
    - TestManualHoldExplicitFieldsOverrideDefaults
  * 2 new API tests:
    - TestManualHold404WhenLoadpointsNil (POST/DELETE/GET matrix)
    - TestManualHoldDeleteAndGet404OnUnknownLoadpoint

Full suite green incl. e2e.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@erikarenhill
erikarenhill merged commit cb7c00c into master Apr 27, 2026
1 check passed
@erikarenhill
erikarenhill deleted the feat-loadpoint-manual-hold branch April 27, 2026 06:20
erikarenhill added a commit that referenced this pull request Apr 27, 2026
* feat(easee): driver-side improvements derived from hardware test

Five field-tested improvements to the Easee driver, all driver-only —
no Go side changes. Derived from the 1Φ↔3Φ ramp test we ran on a
real charger:

  * **Default MinPhaseHoldS 60 → 90 s.** Field-measured: a phaseMode
    flip + EV ramp to steady state takes 60–90 s. A 60 s hold could
    let a flap-prone wantW trigger another transition mid-ramp; 90 s
    gives one full ramp cycle before another flip.

  * **Optional `max_charger_current` config.** When set, driver
    writes it to the charger's static maxChargerCurrent at init.
    After every phaseMode change Easee resets dynamicChargerCurrent
    to maxChargerCurrent — clamping that ceiling bounds the
    post-transition window. Defaults unset (no-op) for backward
    compat; sites with maxChargerCurrent oversized vs the per-phase
    fuse should set this.

  * **Firmware-settings probe at init.** Driver fetches the charger's
    own settings (phaseMode, maxChargerCurrent) and logs them. We
    spent 30 minutes debugging silently-rejected phaseMode=1 writes
    in the field because the box was firmware-locked to phaseMode=3
    and Easee's API just returns 200 OK with no effect. Logging the
    firmware-side phaseMode at init makes that case immediately
    obvious.

  * **Forced `dynamicChargerCurrent` re-assert on next poll.** After a
    successful phaseMode change, schedules one re-write of
    last_amps_set ~5 s later (next driver_poll). Defends against
    Easee's post-transition reset of dynamicChargerCurrent → 16 A
    without waiting for the controller's 5 s tick. Idempotent if the
    controller's tick beats us to it.

  * **Emit `actual_amps_per_phase`.** Derived from totalPower and
    per-phase voltage in the ev telemetry. Operators wanting "is the
    EV actually drawing what we asked for?" can now compare
    actual_amps_per_phase against max_a (which only echoes our last
    write and lags ~5–10 s on the Easee cloud).

No tests added — the project has no Lua test harness yet, and these
are observability + post-transition timing tweaks best verified
against real hardware. Validated via gopher-lua syntax check + the
ramp test described in PR #206's session log.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(easee): read firmware settings from /config (GET), not /settings (POST-only)

Easee's API isn't symmetric — /settings only accepts POST writes,
GET there returns 405 Method Not Allowed. The static config (phaseMode,
maxChargerCurrent, …) is exposed at /config for reads.

Caught at init the first time the driver-improvements PR ran on
hardware: 'Easee: could not read firmware settings: HTTP 405'.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* review: address Copilot comments on PR #207

Six findings, all valid:

  * easee_cloud.lua:315 — read_settings doc claimed "detect a
    firmware lock" but the implementation only logs settings. Active
    detection (compare requested phaseMode after a write / periodic
    re-read) is a follow-up; reword the comment to match what the
    driver actually does (diagnostic logging at init).
  * easee_cloud.lua:319 — host.json_decode failure was treated as
    "no error", silently skipping the settings log. Now returns
    `nil, "decode failed (non-JSON response)"` so init logs a clear
    warning distinct from HTTP errors.
  * easee_cloud.lua:457 — actual_amps_per_phase used the global
    `phases` which can be 2 when config.phases=2 is misconfigured,
    or before the first successful phaseMode write. Dividing by 2
    yields a non-physical "per-phase" value. Now emitted only when
    phases ∈ {1, 3}; otherwise nil so the field is omitted from the
    payload rather than misleading.
  * easee_cloud.lua:493 — pending_amp_resend was cleared
    unconditionally even on POST failure, so a transient network
    error left the charger pinned at maxChargerCurrent. Now cleared
    only on successful re-write; failures retain the flag and
    retry on the next poll.
  * easee_cloud.lua:574 — driver_command's two raw http_post calls
    to /settings now route through the existing write_setting()
    helper for consistent encoding/auth/error handling.
  * api.go:383 — actual_amps_per_phase from the ev emit is now
    surfaced through /api/status as ev_actual_amps_per_phase. PR
    description said this would appear without Go changes; that
    was wrong. Added the field to the EV-status decode struct so
    the operator can compare requested vs actual amps directly.

Build green; gopher-lua syntax check OK; full test suite green
incl. test/e2e.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
erikarenhill added a commit that referenced this pull request Apr 27, 2026
Adds forceFuseDischarge — a dispatch-level safety primary that
unconditionally drains the home battery whenever predicted grid
import exceeds fuseMaxW. Runs in every mode (idle, self_consumption,
planner_*, holdoff window) and overrides every operator intent
(BatteryCoversEV toggle, planner allocation, manual_hold injection).

Surfaced by the manual_hold ramp test in PR #206's session: the EV
was pinned at ~5.5 kW while the home battery sat at 0 W per the
planner's idle slot, and gridW exceeded fuseSafeMaxW until the
operator stopped the test by hand.

Why this exists separately from applyFuseGuard:

  applyFuseGuard scales POSITIVE (charge) targets DOWN to 0 when
  import is over fuse — prevents the EMS from making the overflow
  worse. But it doesn't help in the "battery idle, surprise load"
  case because there's no charge to shrink. forceFuseDischarge
  closes that gap by FORCING the battery to discharge.

Behaviour:

  1. Recompute predicted gridW after applyFuseGuard's scaling.
     Uses the LIVE meter reading so all loads — planned, off-plan,
     manual_hold-injected, oven-on-the-fuse — flow into the math.
  2. If predicted > fuseMaxW, allocate overage = predicted - fuseMaxW
     of additional discharge across online batteries, weighted by
     remaining headroom (MaxDischargeW - current target magnitude),
     gated on SoC ≥ 5 %.
  3. Mark every modified target Clamped so the dispatch trace shows
     the fuse-saver fired.

Coverage:

  * Idle mode and holdoff window now route through fuseSaverFromZero,
    which generates zero-W targets for every online battery and runs
    them through forceFuseDischarge. If no overflow is predicted,
    the result is nil (caller sees the same empty-dispatch behaviour
    as before).
  * Empty pack (SoC < 5 %) → fuse-saver returns unchanged, hardware
    breaker becomes the next layer.
  * MaxDischargeW caps the redistribution.

Out of scope: sub-tick reactivity. The 5 s control-tick is the floor
here; going faster requires pushing the dispatch loop down to ~1 s.
Hardware fuse trips remain the only protection for sub-tick spikes.

Tests: 9 in fuse_saver_test.go covering forced-discharge from idle,
charge → discharge override, top-up of existing discharge, empty
pack, MaxDischargeW cap, no-op cases, multi-battery distribution,
fuseMaxW=0 disable, and end-to-end via ComputeDispatch in idle mode.

Docs: docs/safety.md gets section 3a documenting the new primary
alongside the existing applyFuseGuard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
erikarenhill added a commit that referenced this pull request Apr 27, 2026
…tect fuse (#208)

* feat(control): reactive fuse-saver primary

Adds forceFuseDischarge — a dispatch-level safety primary that
unconditionally drains the home battery whenever predicted grid
import exceeds fuseMaxW. Runs in every mode (idle, self_consumption,
planner_*, holdoff window) and overrides every operator intent
(BatteryCoversEV toggle, planner allocation, manual_hold injection).

Surfaced by the manual_hold ramp test in PR #206's session: the EV
was pinned at ~5.5 kW while the home battery sat at 0 W per the
planner's idle slot, and gridW exceeded fuseSafeMaxW until the
operator stopped the test by hand.

Why this exists separately from applyFuseGuard:

  applyFuseGuard scales POSITIVE (charge) targets DOWN to 0 when
  import is over fuse — prevents the EMS from making the overflow
  worse. But it doesn't help in the "battery idle, surprise load"
  case because there's no charge to shrink. forceFuseDischarge
  closes that gap by FORCING the battery to discharge.

Behaviour:

  1. Recompute predicted gridW after applyFuseGuard's scaling.
     Uses the LIVE meter reading so all loads — planned, off-plan,
     manual_hold-injected, oven-on-the-fuse — flow into the math.
  2. If predicted > fuseMaxW, allocate overage = predicted - fuseMaxW
     of additional discharge across online batteries, weighted by
     remaining headroom (MaxDischargeW - current target magnitude),
     gated on SoC ≥ 5 %.
  3. Mark every modified target Clamped so the dispatch trace shows
     the fuse-saver fired.

Coverage:

  * Idle mode and holdoff window now route through fuseSaverFromZero,
    which generates zero-W targets for every online battery and runs
    them through forceFuseDischarge. If no overflow is predicted,
    the result is nil (caller sees the same empty-dispatch behaviour
    as before).
  * Empty pack (SoC < 5 %) → fuse-saver returns unchanged, hardware
    breaker becomes the next layer.
  * MaxDischargeW caps the redistribution.

Out of scope: sub-tick reactivity. The 5 s control-tick is the floor
here; going faster requires pushing the dispatch loop down to ~1 s.
Hardware fuse trips remain the only protection for sub-tick spikes.

Tests: 9 in fuse_saver_test.go covering forced-discharge from idle,
charge → discharge override, top-up of existing discharge, empty
pack, MaxDischargeW cap, no-op cases, multi-battery distribution,
fuseMaxW=0 disable, and end-to-end via ComputeDispatch in idle mode.

Docs: docs/safety.md gets section 3a documenting the new primary
alongside the existing applyFuseGuard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* review: address Copilot comments + slew-bypass guarantee on PR #208

Six Copilot findings, all valid:

  * dispatch.go:1119 — TargetW=-share over-corrected when starting
    target was a positive charge (net change > overage). Replaced
    with `TargetW -= share` for one consistent rule across all
    starting signs. The discharge magnitude now matches `allocate`
    exactly so predicted gridW lands at fuseMaxW.
  * dispatch.go:1048 — currentBat was summed across ALL DerBattery
    readings (including offline / uncontrolled). Now sums only
    batteries we're actually commanding, which keeps the
    predicted-grid math symmetric with the "remove current
    contribution, add target" model.
  * dispatch.go:985 — fuseSaverFromZero now filters to batteries
    that are BOTH online (per DriverHealth) AND have a current
    DerBattery reading. Matches ComputeDispatch's main path; no
    longer routes commands to offline batteries via the back door.
  * dispatch.go:371 — ModeIdle: state.LastTargets now reflects what
    we actually issued (the fuse-saver targets when it fires, nil
    otherwise). LastDispatch is also updated. /api/status, history
    snapshots, and the RLS learner all depend on this.
  * dispatch.go:391 — Holdoff branch: same bookkeeping fix.
  * fuse_saver_test.go:73 — the standalone "flip charge to
    discharge" test asserted behaviour that doesn't occur in
    production (applyFuseGuard runs first and scales charge → 0).
    Rewritten to call applyFuseGuard then forceFuseDischarge and
    assert the chain's combined behaviour.

User-requested addition: explicit slew-bypass guarantee. The fuse
is non-negotiable; a sudden 0 W → −3 kW response in one tick must
not be slew-limited to ~500 W/cycle for ten cycles while the fuse
is being violated. The current ordering (slew at line 625, then
applyFuseGuard, then forceFuseDischarge) already provides this —
but it was implicit. Added:

  * Comment block at the forceFuseDischarge call site documenting
    the ordering invariant.
  * TestFuseSaverBypassesSlew — end-to-end via ComputeDispatch with
    a tight 500 W/cycle slew rate, a 14 kW grid spike, and a
    battery at rest. Asserts target ≈ −2960 W (full overage), NOT
    −500 W (slew clamp). Locks in the bypass as a regression guard.

Full suite green incl. test/e2e.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(control): per-phase fuse clamp in fuse-saver

Both applyFuseGuard and forceFuseDischarge now consult per-phase
amperage from the meter driver (l1_a / l2_a / l3_a — Pixii,
Ferroamp, Sungrow all emit these in DerReading.Data). When ANY
single phase exceeds the per-phase fuse rating, the dispatch
treats `worst_phase_overage_w × 3` as additional aggregate
overage and routes it through the existing scaling and
forced-discharge logic.

Surfaced by the PR #208 hardware ramp test: aggregate gridW stayed
under the 11.04 kW fuse on every step, but a single-phase Pixii
charging at 4.4 kW on L1 was pushing that one phase past 16 A
while the EV was already drawing ~3.6 kW per phase. Operator
correctly identified the gap.

Implementation:

  * State gets `SiteFuseAmps` + `SiteFuseVoltage`. main.go wires
    them from `cfg.Fuse.MaxAmps` + `cfg.Fuse.Voltage`. Zero
    SiteFuseAmps disables the per-phase clamp (back-compat).
  * `perPhaseImportOverageW(store, state)` reads l1_a / l2_a /
    l3_a from the site meter's DerReading.Data, returns the worst
    phase's wattage over `SiteFuseAmps`. 0 when safe, missing,
    or disabled.
  * applyFuseGuard signature changed: now takes `*State` instead
    of just `siteMeter`. The aggregate-vs-per-phase decision picks
    `max(aggregate_overage, per_phase × 3)`.
  * forceFuseDischarge applies the same max() rule. Still respects
    SoC / MaxDischargeW caps.

The `× 3` factor assumes a balanced 3Φ battery. Conservative for
single-phase batteries on the overloaded phase (over-corrects by
3×, which is safer — less import on that phase) and limited for
single-phase batteries on a different phase (cannot help that
phase). Per-battery `phase` configuration is a follow-up.

Tests:

  * 5 new in fuse_saver_test.go:
    - TestPerPhaseClampScalesChargingOnImbalance
    - TestPerPhaseClampFiresFuseSaverFromIdle
    - TestPerPhaseClampNoOpWhenAllPhasesSafe
    - TestPerPhaseClampDisabledWhenSiteFuseAmpsZero
    - TestPerPhaseClampDominatesAggregateWhenLarger
  * 4 existing applyFuseGuard tests updated to new signature.

Docs: docs/safety.md gets section 3b documenting the per-phase
clamp alongside 3a (the reactive fuse-saver).

Full suite green incl. test/e2e.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

2 participants