Skip to content

feat(control): reactive fuse-saver — battery always discharges to protect fuse - #208

Merged
erikarenhill merged 3 commits into
masterfrom
feat-reactive-fuse-saver
Apr 27, 2026
Merged

erikarenhill merged 3 commits into
masterfrom
feat-reactive-fuse-saver

Conversation

@erikarenhill

Copy link
Copy Markdown
Collaborator

Summary

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

What incident this addresses

In PR #206's session, the manual_hold ramp test pinned the EV at ~5.5 kW while the home battery sat at 0 W per the planner's idle slot. gridW exceeded fuseSafeMaxW until the operator stopped the test by hand. The user's safety requirement: the battery should in ALL situations discharge to prevent fuse overload, react in real time for unplanned loads.

Why a new primitive (existing applyFuseGuard isn't enough)

applyFuseGuard only scales POSITIVE (charge) targets DOWN to 0 when import is over fuse. That helps when the planner asked for a charge — it prevents the EMS from making the overflow worse — but cannot help in the common "battery idle, surprise load" case because there's no charge to shrink. forceFuseDischarge closes that gap.

Behaviour

  1. Recompute predicted = currentGrid − currentBat + sumTarget after applyFuseGuard's scaling. currentGrid is the live meter and reflects ALL loads — planned, off-plan, manual_hold-injected, neighbour's pool pump on the same fuse.
  2. If predicted > fuseMaxW, allocate overage = predicted − fuseMaxW of additional discharge across online batteries proportionally to each battery's remaining headroom (MaxDischargeW − current target magnitude), gated on SoC ≥ 5 %.
  3. Mark every modified target Clamped = true so the dispatch trace shows the fuse-saver fired.

Coverage

  • Idle mode routes through fuseSaverFromZero — generates zero-W targets for every online battery and runs them through forceFuseDischarge. If no overflow is predicted, returns nil (same as today).
  • Holdoff window does the same — overflow can't wait 5 s for the next eligible tick.
  • Empty pack (SoC < 5 %) → fuse-saver returns targets unchanged. Hardware fuse becomes the next layer.
  • All batteries at MaxDischargeW → no-op (already doing all the EMS can).
  • fuseMaxW = 0 → disabled (matches applyFuseGuard's convention).

What this DOES NOT do

  • Sub-tick reactivity. The 5 s control-tick is the floor. Sub-tick spikes (an oven turning on between ticks) still rely on the hardware fuse. Going faster requires pushing the dispatch loop down to ~1 s — separate change.
  • Per-phase imbalance. This is the aggregate three-phase guard. Per-phase logic (e.g. a 16 A fuse where one phase is the EV and another the oven) would need driver-level data and is a follow-up.

Tests

9 new tests in go/internal/control/fuse_saver_test.go:

Test Verifies
TestFuseSaverForcesDischargeFromIdle Battery at 0 W + grid 14 kW + fuse 11.04 kW → battery commanded to −2960 W
TestFuseSaverFlipsChargeToDischargeWhenOverFuse Planner asks for +3 kW charge but grid already at fuse → battery flips to discharge
TestFuseSaverAddsToExistingDischarge Battery already discharging 1 kW, grid still over → tops up
TestFuseSaverRespectsEmptyBattery SoC = 2 % → no-op, hardware fuse takes over
TestFuseSaverRespectsMaxDischarge Massive overage but battery cap = 4 kW → discharge clamped at MaxDischargeW
TestFuseSaverNoOpWhenWithinFuse Healthy grid → leave dispatch alone
TestFuseSaverDistributesAcrossBatteries Two batteries with 6:4 headroom split → forced discharge weighted accordingly
TestFuseSaverDisabledWhenFuseMaxZero fuseMaxW = 0 → no-op
TestFuseSaverFiresInIdleMode End-to-end via ComputeDispatch — idle mode + grid spike yields non-empty dispatch

go test ./... all green incl. test/e2e. No regressions in existing fuse-guard tests.

Docs

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

🤖 Generated with Claude Code

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 reactive “fuse-saver” safety primary to the control loop so the battery can be commanded to discharge whenever predicted grid import exceeds the site fuse limit, including in paths that previously returned no dispatch (idle mode and holdoff window).

Changes:

  • Add forceFuseDischarge and fuseSaverFromZero to inject discharge when predicted import exceeds fuseMaxW, and call it after applyFuseGuard.
  • Run fuse-saver logic in ModeIdle and during the min-dispatch holdoff window instead of returning nil.
  • Add a new test file for fuse-saver behavior and document the new safety layer in docs/safety.md.

Reviewed changes

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

File Description
go/internal/control/dispatch.go Adds fuse-saver logic and integrates it into idle/holdoff paths and post-fuse-guard pipeline.
go/internal/control/fuse_saver_test.go Introduces unit tests (and one end-to-end via ComputeDispatch) for fuse-saver behavior.
docs/safety.md Documents the new reactive fuse-saver safety primary and its intended behavior/edge cases.

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

Comment thread go/internal/control/fuse_saver_test.go Resolved
Comment thread go/internal/control/dispatch.go Resolved
Comment thread go/internal/control/dispatch.go Resolved
Comment thread go/internal/control/dispatch.go Resolved
Comment thread go/internal/control/dispatch.go Resolved
Comment thread go/internal/control/dispatch.go Resolved
erikarenhill and others added 3 commits April 27, 2026 11:32
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]>
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]>
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]>
@erikarenhill
erikarenhill force-pushed the feat-reactive-fuse-saver branch from de90b6c to 6f68b35 Compare April 27, 2026 09:32
@erikarenhill

Copy link
Copy Markdown
Collaborator Author
image

@erikarenhill
erikarenhill merged commit f4a1903 into master Apr 27, 2026
1 check passed
@erikarenhill
erikarenhill deleted the feat-reactive-fuse-saver branch April 27, 2026 09:43
frahlg pushed a commit that referenced this pull request Nov 4, 2026
…te meter again (#1961)

Moves the pin to srcfl/device-drivers@d662c3eb (#208). Only the Zap driver
changes. A Zap on firmware 7.x serves its local API in data model v2, and
zap 3.1.1 read only the old names, so FTW lost its site meter.

The new tests use the payload a Zap-HAN on 7.0.3 sent, and they fail against
3.1.1. read_pv and read_battery on 7.x are not covered yet.

Signed-off-by: David Mozart <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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