From cf958fcdcc15160a60f904a4c8c9ac13a2463747 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 14:02:11 +0100 Subject: [PATCH 1/3] fix(control): slew no longer reopens discharge on a blocked battery The slew limiter anchors on measured power, so a pack the distributor parked at 0 W (SoC below 5 % or discharge_capable=false) was walked back toward its live discharge. Add floorBlockedDischarge, the twin of floorBlockedCharge, before forceFuseDischarge. It keeps the slewed ramp only when stopping at once would put the site over its fuse or import limit. Item A3 of the stable plan. Co-Authored-By: Claude Opus 5.5 --- .changeset/a3-no-discharge-after-slew.md | 5 +++ go/internal/control/dispatch.go | 40 ++++++++++++++++- go/internal/control/golden_dump_test.go | 5 ++- .../control/slew_discharge_floor_test.go | 44 +++++++++++++++++++ .../control/testdata/golden/slew_limiter.json | 6 +-- 5 files changed, 94 insertions(+), 6 deletions(-) create mode 100644 .changeset/a3-no-discharge-after-slew.md create mode 100644 go/internal/control/slew_discharge_floor_test.go diff --git a/.changeset/a3-no-discharge-after-slew.md b/.changeset/a3-no-discharge-after-slew.md new file mode 100644 index 000000000..84c7bddd5 --- /dev/null +++ b/.changeset/a3-no-discharge-after-slew.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +Stop asking a home battery to discharge when its charge is below 5 % or it reports that it cannot discharge. The slew limit used to ramp such a battery back toward the discharge it was already doing. If stopping it at once would push the site over its fuse or import limit, the battery ramps down toward 0 W instead. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 3e01f1eea..4be82bb84 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -2373,6 +2373,7 @@ func applyDispatchSafetyPipeline( targets = floorNegativeTargets(targets) } targets = floorBlockedCharge(targets, opts.noSelfCharge, opts.chargeBlocked) + targets = floorBlockedDischarge(targets, store, state, fuseMaxW) // A battery-boost lease may never draw the stationary fleet below its // explicit reserve. Apply this immediately before forceFuseDischarge: @@ -3394,7 +3395,7 @@ func floorNegativeTargets(targets []DispatchTarget) []DispatchTarget { // toward charge after noSelfCharge set 0. The snap-to-zero list inside // slew never grew the later charge gates, which is how an idle slot // commanded +1500 W. This only moves a target toward zero. Discharge -// stays out: the fuse saver may need it. +// has its own twin, floorBlockedDischarge, which yields to the fuse. func floorBlockedCharge(targets []DispatchTarget, noSelfCharge bool, chargeBlocked map[string]bool) []DispatchTarget { if !noSelfCharge && len(chargeBlocked) == 0 { return targets @@ -3411,6 +3412,43 @@ func floorBlockedCharge(targets []DispatchTarget, noSelfCharge bool, chargeBlock return targets } +// floorBlockedDischarge is the discharge twin of floorBlockedCharge. Slew +// anchors on measured watts, so a pack the distributor parked at 0 W (SoC +// below the floor, discharge_capable=false) is walked back toward its live +// discharge. Stop it at 0 W unless that stop alone would put the site over +// its fuse or import limit; then keep the slewed ramp, which only moves +// toward 0 W. Fuse relief never adds discharge to such a pack. +func floorBlockedDischarge(targets []DispatchTarget, store *telemetry.Store, state *State, fuseMaxW float64) []DispatchTarget { + if store == nil || state == nil { + return targets + } + var out []DispatchTarget + readings := make(map[string]*telemetry.DerReading, len(targets)) + for i, t := range targets { + r := store.Get(t.Driver, telemetry.DerBattery) + readings[t.Driver] = r + if t.TargetW >= 0 || r == nil { + continue + } + if lower, _ := fuseTargetBounds(r, state.DriverLimits[t.Driver]); lower < 0 { + continue + } + if out == nil { + out = append([]DispatchTarget(nil), targets...) + } + out[i].TargetW = 0 + out[i].Clamped = true + } + if out == nil { + return targets + } + meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) + if fuseReliefFromSnapshot(out, readings, meter, state, fuseMaxW, false) > 0 { + return targets + } + return out +} + // coverLoadChargeSlot reports whether the current plan slot is a charge-from- // PV-surplus slot: the DP meant to soak surplus (PlannedGridW below the // grid-charge import band), NOT buy from the grid. Such a slot carries no hard diff --git a/go/internal/control/golden_dump_test.go b/go/internal/control/golden_dump_test.go index ae96c9960..c9f3157c6 100644 --- a/go/internal/control/golden_dump_test.go +++ b/go/internal/control/golden_dump_test.go @@ -1316,8 +1316,9 @@ func slewScenarios() []goldenScenario { State: plan(ModePlannerSelf, 500), Slot: staleSlot(), })) - // A discharge-blocked battery is parked at 0 W by the distributor and - // then walked back toward its live discharge by the same mechanism. + // A discharge-blocked battery is parked at 0 W by the distributor. Slew + // used to walk it back toward its live discharge; floorBlockedDischarge + // now holds it at 0 W while the fuse does not need the ramp. blk := gb("ferroamp", 15200, -2000, 0.50) blk.DischargeBlocked = true out = append(out, mk("blocked_sibling_slew_reopens_parked_target", goldenInputs{ diff --git a/go/internal/control/slew_discharge_floor_test.go b/go/internal/control/slew_discharge_floor_test.go new file mode 100644 index 000000000..320679cf8 --- /dev/null +++ b/go/internal/control/slew_discharge_floor_test.go @@ -0,0 +1,44 @@ +package control + +import "testing" + +// Slew anchors on measured SmoothedW. It must not walk a pack back into the +// discharge the distributor closed (SoC below the 5 % floor, or +// discharge_capable=false). +func TestSlewDoesNotReopenBlockedDischarge(t *testing.T) { + cases := []struct { + name string + soc float64 + capability string + }{ + {"soc_below_floor", 0.04, ""}, + {"discharge_capable_false", 0.50, `{"discharge_capable":false}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + store := seedDeadbandSite(2000, []deadbandBattery{{"bat", -3000, tc.soc, tc.capability}}) + out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 0) + if got := targetsByDriver(out)["bat"].TargetW; got < -1 { + t.Errorf("commanded %.0f W discharge to a pack that must not discharge", got) + } + }) + } +} + +// When stopping the blocked pack at once would put the site over its fuse, +// keep the slewed ramp toward 0 W instead of adding the whole step as import. +// The ramp never adds discharge. +func TestBlockedDischargeKeepsRampWhenStopWouldTripFuse(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + store := seedDeadbandSite(10000, []deadbandBattery{{"bat", -3000, 0.04, ""}}) + out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 11040) + got := targetsByDriver(out)["bat"].TargetW + if got < -3000 || got > -1 { + t.Errorf("target %.0f W, want a ramp between -3000 W and 0 W", got) + } +} diff --git a/go/internal/control/testdata/golden/slew_limiter.json b/go/internal/control/testdata/golden/slew_limiter.json index 896d7f298..e807baf34 100644 --- a/go/internal/control/testdata/golden/slew_limiter.json +++ b/go/internal/control/testdata/golden/slew_limiter.json @@ -2174,7 +2174,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1500, + "target_w": 0, "clamped": true }, { @@ -2205,9 +2205,9 @@ }, "site_totals": { "battery_current_w": -2000, - "battery_target_sum_w": -2000, + "battery_target_sum_w": -500, "raw_grid_w": 2500, - "projected_grid_w": 2500 + "projected_grid_w": 4000 } }, { From 97fc2b701c5f96f91047c359935a6194eacb65f5 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 15:32:42 +0100 Subject: [PATCH 2/3] fix(control): blocked discharge keeps only the fuse need, per phase The stop on a blocked pack fell back to the whole slewed ramp whenever it would trip the fuse, and the gate checked the phases only as the meter shows them now. On an unbalanced site the stop could put one phase over the breaker. Now the blocked packs keep only the discharge that capable packs cannot cover, shared by their ramps and never more than the ramp. A projection of the stop onto each phase keeps the worst phase at its limit; the blocked packs cover that part alone, because forceFuseDischarge does not project phases until #1891 lands. Co-Authored-By: Claude Opus 5.5 --- .changeset/a3-no-discharge-after-slew.md | 2 +- go/internal/control/dispatch.go | 110 +++++++++++++++- .../control/slew_discharge_floor_test.go | 117 ++++++++++++++++-- 3 files changed, 215 insertions(+), 14 deletions(-) diff --git a/.changeset/a3-no-discharge-after-slew.md b/.changeset/a3-no-discharge-after-slew.md index 84c7bddd5..7f31b537d 100644 --- a/.changeset/a3-no-discharge-after-slew.md +++ b/.changeset/a3-no-discharge-after-slew.md @@ -2,4 +2,4 @@ "ftw": patch --- -Stop asking a home battery to discharge when its charge is below 5 % or it reports that it cannot discharge. The slew limit used to ramp such a battery back toward the discharge it was already doing. If stopping it at once would push the site over its fuse or import limit, the battery ramps down toward 0 W instead. +Stop asking a home battery to discharge when its charge is below 5 % or it reports that it cannot discharge. The slew limit used to ramp such a battery back toward the discharge it was already doing. If stopping it at once would put the site or one phase over the fuse or import limit, other batteries take that load first, and the blocked battery keeps only the discharge still needed. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 4be82bb84..92e7baa24 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -2373,7 +2373,7 @@ func applyDispatchSafetyPipeline( targets = floorNegativeTargets(targets) } targets = floorBlockedCharge(targets, opts.noSelfCharge, opts.chargeBlocked) - targets = floorBlockedDischarge(targets, store, state, fuseMaxW) + targets = floorBlockedDischarge(targets, store, state, driverCapacities, fuseMaxW) // A battery-boost lease may never draw the stationary fleet below its // explicit reserve. Apply this immediately before forceFuseDischarge: @@ -3415,14 +3415,23 @@ func floorBlockedCharge(targets []DispatchTarget, noSelfCharge bool, chargeBlock // floorBlockedDischarge is the discharge twin of floorBlockedCharge. Slew // anchors on measured watts, so a pack the distributor parked at 0 W (SoC // below the floor, discharge_capable=false) is walked back toward its live -// discharge. Stop it at 0 W unless that stop alone would put the site over -// its fuse or import limit; then keep the slewed ramp, which only moves -// toward 0 W. Fuse relief never adds discharge to such a pack. -func floorBlockedDischarge(targets []DispatchTarget, store *telemetry.Store, state *State, fuseMaxW float64) []DispatchTarget { +// discharge. Stop it at 0 W. If the stop would put the site or one phase +// over the fuse or import limit, the blocked packs keep only the discharge +// the capable packs cannot cover, and never more than their slewed ramp. +// forceFuseDischarge then takes the rest from the capable packs. +func floorBlockedDischarge( + targets []DispatchTarget, + store *telemetry.Store, + state *State, + driverCapacities map[string]float64, + fuseMaxW float64, +) []DispatchTarget { if store == nil || state == nil { return targets } var out []DispatchTarget + var rampW float64 // discharge the slewed ramp still asks of blocked packs + blocked := make([]bool, len(targets)) readings := make(map[string]*telemetry.DerReading, len(targets)) for i, t := range targets { r := store.Get(t.Driver, telemetry.DerBattery) @@ -3436,19 +3445,108 @@ func floorBlockedDischarge(targets []DispatchTarget, store *telemetry.Store, sta if out == nil { out = append([]DispatchTarget(nil), targets...) } + blocked[i] = true + rampW -= t.TargetW out[i].TargetW = 0 out[i].Clamped = true } if out == nil { return targets } + if fuseMaxW <= 0 { + return out + } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - if fuseReliefFromSnapshot(out, readings, meter, state, fuseMaxW, false) > 0 { + keepW := blockedDischargeKeepW(out, blocked, readings, meter, state, driverCapacities, fuseMaxW) + if keepW <= 0 { + return out + } + if keepW >= rampW { return targets } + for i, t := range targets { + if blocked[i] { + out[i].TargetW = t.TargetW * keepW / rampW + } + } return out } +// blockedDischargeKeepW is the discharge the blocked packs must keep after +// floorBlockedDischarge set them to 0 W. forceFuseDischarge covers the +// aggregate overage from capable packs, so only the part beyond their room +// stays with the blocked packs. forceFuseDischarge reads phase currents from +// the meter as they are, not as the stop leaves them, so a phase that only +// the stop puts over the fuse is covered by the blocked packs alone. +func blockedDischargeKeepW( + out []DispatchTarget, + blocked []bool, + readings map[string]*telemetry.DerReading, + meter *telemetry.DerReading, + state *State, + driverCapacities map[string]float64, + fuseMaxW float64, +) float64 { + reliefW := math.Max(0, fuseReliefFromSnapshot(out, readings, meter, state, fuseMaxW, false)) + if phaseW := stopPhaseReliefW(out, readings, meter, state); phaseW > reliefW { + return phaseW + } + var roomW float64 + for i, t := range out { + r := readings[t.Driver] + if blocked[i] || r == nil || driverCapacities[t.Driver] <= 0 { + continue + } + lower, _ := fuseTargetBounds(r, state.DriverLimits[t.Driver]) + roomW += math.Max(0, t.TargetW-lower) + } + _, _, predicted := predictedGridFromSnapshot(out, readings, meter) + roomW = math.Min(roomW, math.Max(0, predicted+state.effectiveExportCeilingW(fuseMaxW))) + return reliefW - roomW +} + +// stopPhaseReliefW is the aggregate import relief that keeps the worst phase +// inside the per-phase fuse once the targets replace the batteries' raw +// power. A battery spreads its move evenly over the site's phases. 0 without +// usable phase currents. +func stopPhaseReliefW( + targets []DispatchTarget, + readings map[string]*telemetry.DerReading, + meter *telemetry.DerReading, + state *State, +) float64 { + if meter == nil { + return 0 + } + amps, _, valid := phaseCurrentsA(meter, state, meter.RawW) + if !valid || len(amps) == 0 { + return 0 + } + moveW := 0.0 + seen := make(map[string]bool, len(targets)) + for _, t := range targets { + moveW += t.TargetW + if r := readings[t.Driver]; r != nil && !seen[t.Driver] { + moveW -= r.RawW + } + seen[t.Driver] = true + } + exports := meter.RawW < 0 + for _, a := range amps { + exports = exports && a >= 0 + } + perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) + hiA := math.Inf(-1) + for _, a := range amps { + if exports { + a = -a // unsigned phases take the total's direction + } + hiA = math.Max(hiA, a+moveW/perA) + } + limitA := math.Max(0, state.SiteFuseAmps-state.SiteFuseSafetyA) + return math.Max(0, hiA-limitA) * perA +} + // coverLoadChargeSlot reports whether the current plan slot is a charge-from- // PV-surplus slot: the DP meant to soak surplus (PlannedGridW below the // grid-charge import band), NOT buy from the grid. Such a slot carries no hard diff --git a/go/internal/control/slew_discharge_floor_test.go b/go/internal/control/slew_discharge_floor_test.go index 320679cf8..2495007df 100644 --- a/go/internal/control/slew_discharge_floor_test.go +++ b/go/internal/control/slew_discharge_floor_test.go @@ -1,6 +1,12 @@ package control -import "testing" +import ( + "encoding/json" + "math" + "testing" + + "github.com/srcfl/ftw/go/internal/telemetry" +) // Slew anchors on measured SmoothedW. It must not walk a pack back into the // discharge the distributor closed (SoC below the 5 % floor, or @@ -29,16 +35,113 @@ func TestSlewDoesNotReopenBlockedDischarge(t *testing.T) { } // When stopping the blocked pack at once would put the site over its fuse, -// keep the slewed ramp toward 0 W instead of adding the whole step as import. -// The ramp never adds discharge. -func TestBlockedDischargeKeepsRampWhenStopWouldTripFuse(t *testing.T) { +// the pack keeps only the discharge the fuse needs: 10000 + 3000 - 11040 W. +// That is less than the slewed ramp (-2500 W) and never more discharge. +func TestBlockedDischargeKeepsFuseOverage(t *testing.T) { st := NewState(0, 42, "meter") st.MinDispatchIntervalS = 0 st.SlewRateW = 500 store := seedDeadbandSite(10000, []deadbandBattery{{"bat", -3000, 0.04, ""}}) out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 11040) - got := targetsByDriver(out)["bat"].TargetW - if got < -3000 || got > -1 { - t.Errorf("target %.0f W, want a ramp between -3000 W and 0 W", got) + if got := targetsByDriver(out)["bat"].TargetW; math.Abs(got+1960) > 1 { + t.Errorf("target %.0f W, want -1960 W", got) + } +} + +// A stop 60 W over the fuse keeps 60 W of discharge, not the whole ramp. +func TestBlockedDischargeKeepsOnlyTheOverage(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + store := seedDeadbandSite(8100, []deadbandBattery{{"blk", -3000, 0.04, ""}}) + out := ComputeDispatch(store, st, caps(map[string]float64{"blk": 10000}), 11040) + if got := targetsByDriver(out)["blk"].TargetW; math.Abs(got+60) > 1 { + t.Errorf("target %.0f W, want -60 W", got) + } +} + +// A capable sibling takes the fuse relief, so the blocked pack stops. +func TestBlockedDischargeLeavesReliefToSibling(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + store := seedDeadbandSite(9000, []deadbandBattery{ + {"blk", -3000, 0.04, ""}, + {"ok", 0, 0.60, ""}, + }) + out := ComputeDispatch(store, st, caps(map[string]float64{"blk": 10000, "ok": 10000}), 11040) + m := targetsByDriver(out) + if m["blk"].TargetW < -1 { + t.Errorf("blocked pack at %.0f W while the sibling had room", m["blk"].TargetW) + } + // 9000 W meter + 3000 W stop + the sibling's target must fit 11040 W. + if grid := 12000 + m["ok"].TargetW; grid > 11041 { + t.Errorf("projected grid %.0f W over the 11040 W fuse (sibling %.0f W)", grid, m["ok"].TargetW) + } +} + +// Two blocked packs share the discharge the fuse needs. Together they keep +// 6000 + 6000 - 11040 = 960 W, not two ramps of 2500 W. +func TestBlockedDischargeSharesOverage(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + store := seedDeadbandSite(6000, []deadbandBattery{ + {"a", -3000, 0.04, ""}, + {"b", -3000, 0.50, `{"discharge_capable":false}`}, + }) + out := ComputeDispatch(store, st, caps(map[string]float64{"a": 10000, "b": 10000}), 11040) + m := targetsByDriver(out) + if sum := m["a"].TargetW + m["b"].TargetW; math.Abs(sum+960) > 1 { + t.Errorf("blocked packs keep %.0f W + %.0f W, want -960 W in total", m["a"].TargetW, m["b"].TargetW) + } +} + +// An unbalanced site: the total stays far under the fuse, but stopping a +// 3 kW discharge adds 4.35 A to each phase and L1 is at 15 A of 16 A. The +// pack keeps the discharge that holds L1 at 16 A. +func TestBlockedDischargeStopRespectsPhaseFuse(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + st.SiteFuseAmps = 16 + st.SiteFuseVoltage = 230 + st.SiteFusePhases = 3 + store := seedDeadbandSite(6000, []deadbandBattery{{"blk", -3000, 0.04, ""}}) + data, _ := json.Marshal(map[string]any{"l1_a": 15.0, "l2_a": 6.0, "l3_a": 5.1}) + store.Update("meter", telemetry.DerMeter, 6000, nil, data) + out := ComputeDispatch(store, st, caps(map[string]float64{"blk": 10000}), 11040) + got := targetsByDriver(out)["blk"].TargetW + if l1 := 15 + (got+3000)/(230*3); l1 > 16.01 { + t.Errorf("target %.0f W puts L1 at %.2f A on a 16 A fuse", got, l1) + } + if got < -2311 { + t.Errorf("target %.0f W keeps more discharge than L1 needs (-2310 W)", got) + } +} + +// The stop holds while the pack's measured discharge decays. +func TestBlockedDischargeStaysStopped(t *testing.T) { + st := NewState(0, 42, "meter") + st.MinDispatchIntervalS = 0 + st.SlewRateW = 500 + live := -3000.0 + for tick := 0; tick < 6; tick++ { + store := seedDeadbandSite(-1000-live, []deadbandBattery{{"bat", live, 0.04, ""}}) + out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 0) + if got := targetsByDriver(out)["bat"].TargetW; got < -1 { + t.Fatalf("tick %d: %.0f W", tick, got) + } + live /= 2 + } +} + +// A manual self-tune request goes through the same floor. +func TestSelfTuneDoesNotDischargeBlockedPack(t *testing.T) { + st := NewState(0, 42, "meter") + store := seedDeadbandSite(2000, []deadbandBattery{{"blk", -3000, 0.04, ""}}) + out := SelfTuneDispatch(store, st, caps(map[string]float64{"blk": 10000}), 11040, "blk", -2000) + if got := targetsByDriver(out)["blk"].TargetW; got < -1 { + t.Errorf("self-tune sent %.0f W", got) } } From 3e8c3f655bd4e88edb30d0e7f23639fc81a32d4b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 16:33:18 +0100 Subject: [PATCH 3/3] fix(control): blocked-discharge phase relief reads live raw power stopPhaseReliefW read RawW straight off cached meter and battery readings, which the telemetry-read ratchet rejects. It now takes the raw totals from Store.OnlineMeterW and a new Store.OnlineRawW, and gives no phase relief when either driver has gone offline or moved on to a newer reading than the rest of the decision used. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 25 +++++++---- .../control/slew_discharge_floor_test.go | 42 +++++++++++++++++++ go/internal/telemetry/store.go | 9 +++- go/internal/telemetry/telemetry_test.go | 18 ++++++++ 4 files changed, 86 insertions(+), 8 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 92e7baa24..e266c8dab 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3457,7 +3457,7 @@ func floorBlockedDischarge( return out } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - keepW := blockedDischargeKeepW(out, blocked, readings, meter, state, driverCapacities, fuseMaxW) + keepW := blockedDischargeKeepW(store, out, blocked, readings, meter, state, driverCapacities, fuseMaxW) if keepW <= 0 { return out } @@ -3479,6 +3479,7 @@ func floorBlockedDischarge( // the meter as they are, not as the stop leaves them, so a phase that only // the stop puts over the fuse is covered by the blocked packs alone. func blockedDischargeKeepW( + store *telemetry.Store, out []DispatchTarget, blocked []bool, readings map[string]*telemetry.DerReading, @@ -3488,7 +3489,7 @@ func blockedDischargeKeepW( fuseMaxW float64, ) float64 { reliefW := math.Max(0, fuseReliefFromSnapshot(out, readings, meter, state, fuseMaxW, false)) - if phaseW := stopPhaseReliefW(out, readings, meter, state); phaseW > reliefW { + if phaseW := stopPhaseReliefW(store, out, readings, meter, state); phaseW > reliefW { return phaseW } var roomW float64 @@ -3508,17 +3509,23 @@ func blockedDischargeKeepW( // stopPhaseReliefW is the aggregate import relief that keeps the worst phase // inside the per-phase fuse once the targets replace the batteries' raw // power. A battery spreads its move evenly over the site's phases. 0 without -// usable phase currents. +// usable phase currents, or when the meter or a battery has gone offline or +// moved on from the readings the rest of the decision used. func stopPhaseReliefW( + store *telemetry.Store, targets []DispatchTarget, readings map[string]*telemetry.DerReading, meter *telemetry.DerReading, state *State, ) float64 { - if meter == nil { + if store == nil || meter == nil { return 0 } - amps, _, valid := phaseCurrentsA(meter, state, meter.RawW) + totalW, at, ok := store.OnlineMeterW(state.SiteMeterDriver) + if !ok || !at.Equal(meter.UpdatedAt) { + return 0 + } + amps, _, valid := phaseCurrentsA(meter, state, totalW) if !valid || len(amps) == 0 { return 0 } @@ -3527,11 +3534,15 @@ func stopPhaseReliefW( for _, t := range targets { moveW += t.TargetW if r := readings[t.Driver]; r != nil && !seen[t.Driver] { - moveW -= r.RawW + rawW, at, ok := store.OnlineRawW(t.Driver, telemetry.DerBattery) + if !ok || !at.Equal(r.UpdatedAt) { + return 0 + } + moveW -= rawW } seen[t.Driver] = true } - exports := meter.RawW < 0 + exports := totalW < 0 for _, a := range amps { exports = exports && a >= 0 } diff --git a/go/internal/control/slew_discharge_floor_test.go b/go/internal/control/slew_discharge_floor_test.go index 2495007df..cdaef0bdf 100644 --- a/go/internal/control/slew_discharge_floor_test.go +++ b/go/internal/control/slew_discharge_floor_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "math" "testing" + "time" "github.com/srcfl/ftw/go/internal/telemetry" ) @@ -145,3 +146,44 @@ func TestSelfTuneDoesNotDischargeBlockedPack(t *testing.T) { t.Errorf("self-tune sent %.0f W", got) } } + +// The phase relief uses only live readings from the same sample as the rest +// of the decision. A battery or meter that went offline, or a meter that +// moved on to a newer reading, gives no phase relief. +func TestStopPhaseReliefNeedsLiveReadings(t *testing.T) { + st := NewState(0, 42, "meter") + st.SiteFuseAmps = 16 + st.SiteFuseVoltage = 230 + st.SiteFusePhases = 3 + data, _ := json.Marshal(map[string]any{"l1_a": 15.0, "l2_a": 6.0, "l3_a": 5.1}) + seed := func() (*telemetry.Store, map[string]*telemetry.DerReading, *telemetry.DerReading) { + store := seedDeadbandSite(6000, []deadbandBattery{{"blk", -3000, 0.04, ""}}) + store.Update("meter", telemetry.DerMeter, 6000, nil, data) + readings := map[string]*telemetry.DerReading{"blk": store.Get("blk", telemetry.DerBattery)} + return store, readings, store.Get("meter", telemetry.DerMeter) + } + stop := []DispatchTarget{{Driver: "blk", TargetW: 0}} + + store, readings, meter := seed() + // Stopping 3000 W puts L1 at 15 + 4.35 A; 3.35 A over 16 A is 2310 W. + if got := stopPhaseReliefW(store, stop, readings, meter, st); math.Abs(got-2310) > 1 { + t.Fatalf("live readings: relief %.0f W, want 2310 W", got) + } + store.DriverHealthMut("blk").SetOffline() + if got := stopPhaseReliefW(store, stop, readings, meter, st); got != 0 { + t.Errorf("offline battery: relief %.0f W, want 0", got) + } + + store, readings, meter = seed() + store.DriverHealthMut("meter").SetOffline() + if got := stopPhaseReliefW(store, stop, readings, meter, st); got != 0 { + t.Errorf("offline meter: relief %.0f W, want 0", got) + } + + store, readings, meter = seed() + time.Sleep(time.Millisecond) + store.Update("meter", telemetry.DerMeter, 6000, nil, data) + if got := stopPhaseReliefW(store, stop, readings, meter, st); got != 0 { + t.Errorf("newer meter reading: relief %.0f W, want 0", got) + } +} diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index d9dc84309..32e668501 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -692,9 +692,16 @@ func (s *Store) SumOnlineV2XW() float64 { // while its driver is still reporting. A watchdog-offline meter returns // false, so its last value never counts as a new reading. func (s *Store) OnlineMeterW(driver string) (w float64, at time.Time, ok bool) { + return s.OnlineRawW(driver, DerMeter) +} + +// OnlineRawW returns a driver's latest raw power of one type and when it +// arrived, while the driver is still reporting. A watchdog-offline driver +// returns false. +func (s *Store) OnlineRawW(driver string, t DerType) (w float64, at time.Time, ok bool) { s.mu.RLock() defer s.mu.RUnlock() - r, found := s.readings[key(driver, DerMeter)] + r, found := s.readings[key(driver, t)] if !found || math.IsNaN(r.RawW) || math.IsInf(r.RawW, 0) { return 0, time.Time{}, false } diff --git a/go/internal/telemetry/telemetry_test.go b/go/internal/telemetry/telemetry_test.go index 640d3d9f5..2ac3d4412 100644 --- a/go/internal/telemetry/telemetry_test.go +++ b/go/internal/telemetry/telemetry_test.go @@ -705,3 +705,21 @@ func TestOnlineMeterWSkipsOfflineMeter(t *testing.T) { t.Fatal("an offline meter's last reading was returned") } } + +// A battery's raw power, like the meter's, stops counting once its driver +// goes offline. +func TestOnlineRawWSkipsOfflineBattery(t *testing.T) { + s := NewStore() + s.Update("bat", DerBattery, -3000, nil, nil) + s.DriverHealthMut("bat").RecordSuccess() + if w, _, ok := s.OnlineRawW("bat", DerBattery); !ok || w != -3000 { + t.Fatalf("online battery: %v %v, want -3000 W", w, ok) + } + if _, _, ok := s.OnlineRawW("bat", DerMeter); ok { + t.Fatal("a battery driver reported a meter reading") + } + s.DriverHealthMut("bat").SetOffline() + if _, _, ok := s.OnlineRawW("bat", DerBattery); ok { + t.Fatal("an offline battery's last reading was returned") + } +}