Repository navigation
feat(control): reactive fuse-saver — battery always discharges to protect fuse - #208
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
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
forceFuseDischargeandfuseSaverFromZeroto inject discharge when predicted import exceedsfuseMaxW, and call it afterapplyFuseGuard. - Run fuse-saver logic in
ModeIdleand during the min-dispatch holdoff window instead of returningnil. - 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.
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
force-pushed
the
feat-reactive-fuse-saver
branch
from
April 27, 2026 09:32
de90b6c to
6f68b35
Compare
Collaborator
Author
4 tasks
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

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.
gridWexceededfuseSafeMaxWuntil 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
applyFuseGuardisn't enough)applyFuseGuardonly 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.forceFuseDischargecloses that gap.Behaviour
predicted = currentGrid − currentBat + sumTargetafterapplyFuseGuard's scaling.currentGridis the live meter and reflects ALL loads — planned, off-plan, manual_hold-injected, neighbour's pool pump on the same fuse.predicted > fuseMaxW, allocateoverage = predicted − fuseMaxWof additional discharge across online batteries proportionally to each battery's remaining headroom (MaxDischargeW − current target magnitude), gated onSoC ≥ 5 %.Clamped = trueso the dispatch trace shows the fuse-saver fired.Coverage
fuseSaverFromZero— generates zero-W targets for every online battery and runs them throughforceFuseDischarge. If no overflow is predicted, returns nil (same as today).fuseMaxW = 0→ disabled (matchesapplyFuseGuard's convention).What this DOES NOT do
Tests
9 new tests in
go/internal/control/fuse_saver_test.go:TestFuseSaverForcesDischargeFromIdleTestFuseSaverFlipsChargeToDischargeWhenOverFuseTestFuseSaverAddsToExistingDischargeTestFuseSaverRespectsEmptyBatteryTestFuseSaverRespectsMaxDischargeTestFuseSaverNoOpWhenWithinFuseTestFuseSaverDistributesAcrossBatteriesTestFuseSaverDisabledWhenFuseMaxZerofuseMaxW = 0→ no-opTestFuseSaverFiresInIdleModeComputeDispatch— idle mode + grid spike yields non-empty dispatchgo test ./...all green incl.test/e2e. No regressions in existing fuse-guard tests.Docs
docs/safety.mdgets section 3a documenting the new primary alongside the existingapplyFuseGuard.🤖 Generated with Claude Code