From 7f819961643d94992bc3c7f2872133f79763a80e Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 14:05:28 +0100 Subject: [PATCH 1/6] fix(control): one SoC floor for the stale-plan fallback, fuse relief and the hourly import limit Control now gets PowerLimits.SoCMin, the higher of batteries..soc_min and the running planner's soc_min (10 % default). Core still stops at 5 %. - A planner mode with no plan no longer discharges below the floor. - Fuse relief and the hourly import limit stop at the floor. - The part of the relief that only the hourly import limit asks for keeps the battery-boost reserve; a real fuse overage may still pass it. Item A4 of the stable plan. Co-Authored-By: Claude Opus 5.5 --- .changeset/a4-one-soc-floor.md | 5 + go/cmd/ftw/battery_soc_max_test.go | 29 ++++++ go/cmd/ftw/main.go | 13 +++ go/internal/control/dispatch.go | 145 +++++++++++++++++--------- go/internal/control/soc_floor_test.go | 109 +++++++++++++++++++ 5 files changed, 253 insertions(+), 48 deletions(-) create mode 100644 .changeset/a4-one-soc-floor.md create mode 100644 go/internal/control/soc_floor_test.go diff --git a/.changeset/a4-one-soc-floor.md b/.changeset/a4-one-soc-floor.md new file mode 100644 index 000000000..3457ed4f7 --- /dev/null +++ b/.changeset/a4-one-soc-floor.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +Keep the battery above its minimum level when no plan exists, during fuse protection and under the hourly import limit. The floor is the highest of 5 %, the battery's `soc_min` and the planner's `soc_min` (10 % by default). Below it, the car is the lever for the fuse. The hourly import limit also no longer discharges below a battery-boost reserve. diff --git a/go/cmd/ftw/battery_soc_max_test.go b/go/cmd/ftw/battery_soc_max_test.go index 6f8f4dfce..26e0723f0 100644 --- a/go/cmd/ftw/battery_soc_max_test.go +++ b/go/cmd/ftw/battery_soc_max_test.go @@ -66,3 +66,32 @@ func TestSoCMaxConfigPrecedenceAndReload(t *testing.T) { ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner) check(.5, false) // An explicit zero is not an absent limit. } + +// Dispatch keeps the higher of the battery's and the running planner's +// soc_min. The planner's unset soc_min means its 10 % default. +func TestSoCMinReachesDispatch(t *testing.T) { + f := func(v float64) *float64 { return &v } + for _, tc := range []struct { + name string + battery *float64 + planner *config.Planner + want float64 + }{ + {"no planner, no battery floor", nil, nil, 0}, + {"planner off", nil, &config.Planner{SoCMin: 0.2}, 0}, + {"planner default", nil, &config.Planner{Enabled: true}, 0.10}, + {"planner set", nil, &config.Planner{Enabled: true, SoCMin: 0.15}, 0.15}, + {"battery higher", f(0.25), &config.Planner{Enabled: true, SoCMin: 0.15}, 0.25}, + {"planner higher", f(0.05), &config.Planner{Enabled: true, SoCMin: 0.15}, 0.15}, + {"battery only", f(0.2), nil, 0.2}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := parseBatteryLimitConfig(t, "", " max_charge_w: 5000\n") + cfg.Batteries = map[string]config.Battery{"battery": {SoCMin: tc.battery}} + got := driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, tc.planner)["battery"].SoCMin + if got != tc.want { + t.Fatalf("SoCMin = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index 4b23e1d63..08b8d7009 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -3665,11 +3665,20 @@ func driverCapacitiesFrom(drvList []config.Driver, loadpoints []config.Loadpoint // driverLimitsFrom gives dispatch the same per-driver power limits and charge // ceilings as the planner. Each battery's soc_max overrides the planner's. +// The SoC floor is the higher of the battery's and the running planner's +// soc_min, with the planner's 10 % default. func driverLimitsFrom(drivers []config.Driver, batteries map[string]config.Battery, planner *config.Planner) map[string]control.PowerLimits { ceiling := 1.0 if planner != nil && planner.SoCMax > 0 { ceiling = planner.SoCMax } + floor := 0.0 + if planner != nil && planner.Enabled { + floor = planner.SoCMin + if floor <= 0 { + floor = 0.10 + } + } out := map[string]control.PowerLimits{} for _, d := range drivers { if !d.ObserveOnly { @@ -3679,6 +3688,10 @@ func driverLimitsFrom(drivers []config.Driver, batteries map[string]config.Batte limits.SoCMax = *b.SoCMax limits.SoCMaxSet = true } + limits.SoCMin = floor + if b := batteries[d.Name]; b.SoCMin != nil && *b.SoCMin > floor { + limits.SoCMin = *b.SoCMin + } out[d.Name] = limits } } diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index af88953e9..2361cb2e8 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -234,6 +234,18 @@ type PowerLimits struct { // SoCMax is the battery's charge ceiling, 0..1. An unset limit uses 100%. SoCMax float64 SoCMaxSet bool + // SoCMin is the owner's discharge floor, 0..1: the higher of the + // battery's and the planner's soc_min. Core never goes below 5 %. + SoCMin float64 +} + +// socFloor is the lowest SoC that the stale-plan fallback, fuse relief and +// the hourly import limit may discharge to. +func (l PowerLimits) socFloor() float64 { + if l.SoCMin > dischargeFloorSoC && l.SoCMin <= 1 { + return l.SoCMin + } + return dischargeFloorSoC } func (l PowerLimits) socCeiling() float64 { @@ -1489,6 +1501,8 @@ func ComputeDispatch( } // ---- Gather online batteries ---- + // Without a plan, a planner mode keeps the owner's reserve. + staleFloor := !manualHoldActive && state.Mode.IsPlannerMode() && state.PlanStale batteries := make([]batteryInfo, 0, len(driverCapacities)) for name, cap := range driverCapacities { r := store.Get(name, telemetry.DerBattery) @@ -1510,7 +1524,8 @@ func ComputeDispatch( // A configured zero is a hard direction block, not the legacy // "use MaxCommandW" sentinel. Feed it into the allocator as well as // the clamps so capable siblings receive the blocked battery's share. - dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 + dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 || + staleFloor && soc < lim.socFloor() chargeBlocked = chargeBlocked || lim.chargeCap() == 0 || state.BatteryChargePaused(name) batteries = append(batteries, batteryInfo{ driver: name, @@ -2407,6 +2422,7 @@ func applyDispatchSafetyPipeline( // explicit reserve. Apply this immediately before forceFuseDischarge: // normal planning/operator intent is constrained, while the physical fuse // emergency remains superior and may still discharge to prevent a trip. + // The hour's import limit is not a fuse and keeps the reserve. targets = applyBatteryBoostReserve(targets, store, state, driverCapacities) // forceFuseDischarge runs after the normal policy rails. A fuse overflow can @@ -2556,31 +2572,36 @@ func applyBatteryBoostReserve(targets []DispatchTarget, store *telemetry.Store, continue } r := store.Get(out[i].Driver, telemetry.DerBattery) - capacityWh := driverCapacities[out[i].Driver] - if r == nil || r.SoC == nil || capacityWh <= 0 || *r.SoC <= state.BatteryBoostReserveSoC { - out[i].TargetW = 0 - out[i].Clamped = true - continue - } - // Bound the next control interval's discharge energy to the SoC - // headroom above reserve. A 0.9 discharge-efficiency factor is - // deliberately conservative: delivering 1 Wh to the AC bus costs - // more than 1 Wh inside the pack. This closes the between-ticks - // overshoot that a threshold-only clamp would permit. - dtS := float64(state.MinDispatchIntervalS) - if dtS <= 0 { - dtS = 5 - } - headroomWh := (*r.SoC - state.BatteryBoostReserveSoC) * capacityWh - maxDischargeW := headroomWh * 0.9 * 3600 / dtS - if -out[i].TargetW > maxDischargeW { - out[i].TargetW = -maxDischargeW + if lower := boostReserveLowerW(r, driverCapacities[out[i].Driver], state); out[i].TargetW < lower { + out[i].TargetW = lower out[i].Clamped = true } } return out } +// boostReserveLowerW is the lowest target that keeps a battery above the +// battery-boost reserve until the next tick. Without a reserve it is -Inf. +func boostReserveLowerW(r *telemetry.DerReading, capacityWh float64, state *State) float64 { + if state == nil || state.BatteryBoostReserveSoC <= 0 { + return math.Inf(-1) + } + if r == nil || r.SoC == nil || capacityWh <= 0 || *r.SoC <= state.BatteryBoostReserveSoC { + return 0 + } + // Bound the next control interval's discharge energy to the SoC + // headroom above reserve. A 0.9 discharge-efficiency factor is + // deliberately conservative: delivering 1 Wh to the AC bus costs + // more than 1 Wh inside the pack. This closes the between-ticks + // overshoot that a threshold-only clamp would permit. + dtS := float64(state.MinDispatchIntervalS) + if dtS <= 0 { + dtS = 5 + } + headroomWh := (*r.SoC - state.BatteryBoostReserveSoC) * capacityWh + return -headroomWh * 0.9 * 3600 / dtS +} + // protectiveCurtailLimitW caps PV at live load plus margin when SoC is // high and surplus exceeds that margin. (0, false) means leave PV alone. func protectiveCurtailLimitW(state *State, store *telemetry.Store) (float64, bool) { @@ -4176,7 +4197,7 @@ func fuseTargetBounds(r *telemetry.DerReading, lim PowerLimits) (lower, upper fl lower = -lim.dischargeCap() upper = lim.chargeCap() dischargeBlocked, chargeBlocked := batteryDirectionBlocks(r.Data) - if r.SoC == nil || *r.SoC < dischargeFloorSoC || dischargeBlocked { + if r.SoC == nil || *r.SoC < lim.socFloor() || dischargeBlocked { lower = 0 } if chargeBlocked || r.SoC != nil && *r.SoC >= lim.socCeiling() { @@ -4538,8 +4559,22 @@ func fuseReliefFromSnapshot( fuseMaxW float64, accountPhaseTargetDelta bool, ) float64 { + overage, _ := fuseReliefPartsFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW, accountPhaseTargetDelta) + return overage +} + +// fuseReliefPartsFromSnapshot also returns limitOnlyW, the part of the relief +// that only the hour's import limit asks for. +func fuseReliefPartsFromSnapshot( + targets []DispatchTarget, + batteryReadings map[string]*telemetry.DerReading, + meter *telemetry.DerReading, + state *State, + fuseMaxW float64, + accountPhaseTargetDelta bool, +) (overage, limitOnlyW float64) { if fuseMaxW <= 0 || len(targets) == 0 || state == nil { - return 0 + return 0, 0 } currentBat, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) @@ -4555,9 +4590,10 @@ func fuseReliefFromSnapshot( // Per-phase relief remains fuse-only and may act only while the matching // aggregate meter sample is on the import side. fuseW := math.Max(0, fuseMaxW-state.fuseSafetyMarginW()) - overage := predicted - fuseW + overage = predicted - fuseW + limitOverage := math.Inf(-1) if ceilingW := state.effectiveImportCeilingW(fuseMaxW); ceilingW < fuseW { - overage = math.Max(overage, predicted-ceilingW-state.pendingEVCutW()) + limitOverage = predicted - ceilingW - state.pendingEVCutW() } if currentGrid >= 0 { relief := perPhaseOverageReadingW(meter, state) * float64(state.SiteFusePhases) @@ -4574,7 +4610,11 @@ func fuseReliefFromSnapshot( overage = relief } } - return overage + if limitOverage > overage { + limitOnlyW = math.Max(0, limitOverage-math.Max(0, overage)) + overage = limitOverage + } + return overage, limitOnlyW } // predictedGridFromSnapshot holds non-targeted site power constant and replaces @@ -4644,7 +4684,7 @@ func forceFuseDischargeWithSnapshot( if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return targets } - overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW, accountPhaseTargetDelta) + overage, limitOnlyW := fuseReliefPartsFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW, accountPhaseTargetDelta) if overage <= 0 { return targets } @@ -4657,13 +4697,12 @@ func forceFuseDischargeWithSnapshot( overage = exportRoom } - type slot struct { - idx int - headroom float64 - } - slots := make([]slot, 0, len(targets)) - var totalHeadroom float64 + // The fuse may discharge down to the SoC floor. The hour's import limit + // is a bill, not a breaker: its extra part also keeps the boost reserve. + lowers := make([]float64, len(targets)) + limitLowers := make([]float64, len(targets)) for i, t := range targets { + lowers[i], limitLowers[i] = math.Inf(1), math.Inf(1) cap, ok := driverCapacities[t.Driver] if !ok || cap <= 0 { continue @@ -4672,35 +4711,45 @@ func forceFuseDischargeWithSnapshot( if r == nil { continue } - lower, _ := fuseTargetBounds(r, state.DriverLimits[t.Driver]) + lowers[i], _ = fuseTargetBounds(r, state.DriverLimits[t.Driver]) + limitLowers[i] = math.Max(lowers[i], boostReserveLowerW(r, cap, state)) + } + fusePartW := math.Max(0, overage-limitOnlyW) + out := allocateFuseRelief(targets, fusePartW, lowers) + return allocateFuseRelief(out, overage-fusePartW, limitLowers) +} + +// allocateFuseRelief subtracts reliefW from the targets in proportion to +// each one's room above its lower bound. +func allocateFuseRelief(targets []DispatchTarget, reliefW float64, lowers []float64) []DispatchTarget { + if reliefW <= 0 { + return targets + } + var totalHeadroom float64 + for i, t := range targets { // Relief subtracts from the current target. Its full safe travel is // the distance to the current lower command bound. A live positive // target contributes charge cancellation even when SoC or the driver // blocks discharge, but the target cannot cross below 0 W in that case. - room := t.TargetW - lower - if room <= 0 { - continue + if room := t.TargetW - lowers[i]; room > 0 { + totalHeadroom += room } - slots = append(slots, slot{idx: i, headroom: room}) - totalHeadroom += room } if totalHeadroom <= 0 { return targets } - - allocate := overage - if allocate > totalHeadroom { - allocate = totalHeadroom - } - + allocate := math.Min(reliefW, totalHeadroom) out := make([]DispatchTarget, len(targets)) copy(out, targets) - for _, s := range slots { - share := allocate * (s.headroom / totalHeadroom) + for i, t := range targets { + room := t.TargetW - lowers[i] + if room <= 0 { + continue + } // Subtract from the current target. Replacing a charge with -share // removed the charge twice and discharged more than the overage. - out[s.idx].TargetW -= share - out[s.idx].Clamped = true + out[i].TargetW -= allocate * (room / totalHeadroom) + out[i].Clamped = true } return out } diff --git a/go/internal/control/soc_floor_test.go b/go/internal/control/soc_floor_test.go new file mode 100644 index 000000000..0334c9e25 --- /dev/null +++ b/go/internal/control/soc_floor_test.go @@ -0,0 +1,109 @@ +package control + +import ( + "testing" + "time" +) + +// A planner mode with no plan falls back to self-consumption. It must keep +// the owner's reserve (planner soc_min 10 %), not discharge to Core's 5 %. +func TestPlannerFallbackKeepsHouseReserve(t *testing.T) { + for _, mode := range []Mode{ModePlannerSelf, ModePlannerCheap, ModePlannerPassiveArbitrage, ModePlannerArbitrage} { + t.Run(string(mode), func(t *testing.T) { + store := seedStore(2000, []struct { + name string + currentW, soc float64 + }{ + {"ferroamp", 0, 0.08}, + }) + st := NewState(0, 50, "ferroamp") + st.Mode = mode + st.UseEnergyDispatch = true + st.SlewRateW = 10000 + st.MinDispatchIntervalS = 0 + st.DriverLimits = map[string]PowerLimits{"ferroamp": {SoCMin: 0.10}} + st.SlotDirective = func(time.Time) (SlotDirective, bool) { return SlotDirective{}, false } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { return "", 0, "", false } + + targets := ComputeDispatch(store, st, caps(map[string]float64{"ferroamp": 15200}), 11040) + if !st.PlanStale { + t.Fatalf("expected stale-plan fallback") + } + for _, tg := range targets { + if tg.TargetW < 0 { + t.Errorf("%s: stale plan, SoC 8%% < 10%% house reserve, TargetW=%.0f W (discharges below reserve)", tg.Driver, tg.TargetW) + } + } + }) + } +} + +// The hourly import ceiling (a billing limit) runs through the fuse relief. +// 25 A site, every phase at 11.6 A (far from the fuse), meter 8 kW, +// ceiling 5 kW. Neither the SoC floor nor the boost reserve may be crossed. +func importCeilingSite(soc float64) (*State, func(targets []DispatchTarget) []DispatchTarget) { + store, st, caps := setupPerPhaseSite(3, 230, 8000, 11.6, 11.6, 11.6, soc, 10000) + st.SiteFuseAmps = 25 + st.PeakImportCeilingW = 5000 + lim := st.DriverLimits["bat"] + lim.SoCMin = 0.10 + st.DriverLimits["bat"] = lim + return st, func(targets []DispatchTarget) []DispatchTarget { + return applyDispatchSafetyPipeline(targets, store, st, caps, 25*230*3, dispatchSafetyOptions{}) + } +} + +func TestImportCeilingKeepsSoCFloor(t *testing.T) { + _, run := importCeilingSite(0.06) + if out := run([]DispatchTarget{{Driver: "bat"}}); out[0].TargetW < 0 { + t.Fatalf("import ceiling ordered %.0f W at SoC 6 %%, floor 10 %%", out[0].TargetW) + } + // Above the floor the ceiling still shaves the peak. + _, run = importCeilingSite(0.50) + if out := run([]DispatchTarget{{Driver: "bat"}}); out[0].TargetW > -2999 { + t.Fatalf("import ceiling at SoC 50 %%: got %.0f W, want -3000 W", out[0].TargetW) + } +} + +func TestImportCeilingKeepsBoostReserve(t *testing.T) { + st, run := importCeilingSite(0.20) + st.BatteryBoostReserveSoC = 0.30 + if out := run([]DispatchTarget{{Driver: "bat"}}); out[0].TargetW < 0 { + t.Fatalf("boost reserve 30 %%, SoC 20 %%, no fuse risk: ordered %.0f W", out[0].TargetW) + } +} + +func TestImportCeilingComputeDispatchKeepsBoostReserve(t *testing.T) { + store, st, caps := setupPerPhaseSite(3, 230, 8000, 11.6, 11.6, 11.6, 0.06, 10000) + st.SiteFuseAmps = 25 + st.PeakImportCeilingW = 5000 + st.BatteryBoostReserveSoC = 0.30 + st.SetGridTarget(0) + st.MinDispatchIntervalS = 0 + for _, tg := range ComputeDispatch(store, st, caps, 25*230*3) { + if tg.TargetW < 0 { + t.Fatalf("ComputeDispatch (mode %v) ordered %s %.0f W at SoC 6 %%, reserve 30 %%", st.Mode, tg.Driver, tg.TargetW) + } + } +} + +// A real fuse overage may still go past the boost reserve, but not past the +// SoC floor: below it the car is the lever. +func TestFuseReliefPassesBoostReserveButKeepsSoCFloor(t *testing.T) { + run := func(soc float64) float64 { + // 16 A fuse, 11040 W, meter 13 kW: about 2 kW over. + store, st, caps := setupPerPhaseSite(3, 230, 13000, 18.8, 18.8, 18.8, soc, 10000) + st.BatteryBoostReserveSoC = 0.30 + lim := st.DriverLimits["bat"] + lim.SoCMin = 0.10 + st.DriverLimits["bat"] = lim + out := applyDispatchSafetyPipeline([]DispatchTarget{{Driver: "bat"}}, store, st, caps, 11040, dispatchSafetyOptions{}) + return out[0].TargetW + } + if got := run(0.20); got >= 0 { + t.Fatalf("fuse overage at SoC 20 %%, reserve 30 %%: got %.0f W, want discharge", got) + } + if got := run(0.08); got < 0 { + t.Fatalf("fuse overage at SoC 8 %%, floor 10 %%: got %.0f W, want no discharge", got) + } +} From f87151ba2ad4317364d1a3c12958127030853742 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 15:32:13 +0100 Subject: [PATCH 2/6] fix(control): hold the stale-plan floor on a running discharge; give the limit part first A battery that drifts under the stale-plan floor while discharging kept going: the deadband exit returned no targets, so the driver held its last setpoint, and outside the deadband slew handed back part of the discharge. The deadband exit now falls through when such a battery is discharging, and the safety pipeline moves its negative target to 0 W after slew. Split relief gave the fuse part first across all batteries, which used up the room that only batteries above the boost reserve can give the hourly limit. Give the limit-only part first, then the fuse part down to the SoC floor. The fuse part is still covered whenever the fleet can cover it. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 66 +++++++++++++++- go/internal/control/soc_floor_test.go | 105 ++++++++++++++++++++++++++ 2 files changed, 167 insertions(+), 4 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 2361cb2e8..ce1e1e7a3 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1173,6 +1173,10 @@ type batteryInfo struct { dischargeBlocked bool chargeBlocked bool socMissing bool // no fresh SoC reading; soc is 0 + // belowStaleFloor: a planner mode without a plan, and SoC under the + // owner's floor. Unlike a driver's transient report, this must also + // stop a discharge already running, past the deadband and slew. + belowStaleFloor bool } // chargeCap returns the effective per-battery charge ceiling, falling @@ -1524,8 +1528,8 @@ func ComputeDispatch( // A configured zero is a hard direction block, not the legacy // "use MaxCommandW" sentinel. Feed it into the allocator as well as // the clamps so capable siblings receive the blocked battery's share. - dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 || - staleFloor && soc < lim.socFloor() + belowStaleFloor := staleFloor && soc < lim.socFloor() + dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 || belowStaleFloor chargeBlocked = chargeBlocked || lim.chargeCap() == 0 || state.BatteryChargePaused(name) batteries = append(batteries, batteryInfo{ driver: name, @@ -1541,6 +1545,7 @@ func ComputeDispatch( dischargeBlocked: dischargeBlocked, chargeBlocked: chargeBlocked, socMissing: socMissing, + belowStaleFloor: belowStaleFloor, }) } onlineBats := make([]batteryInfo, 0, len(batteries)) @@ -1797,6 +1802,7 @@ func ComputeDispatch( // and the held-meter exit both fall through to cut it. batteryBreaksLimit := (noSelfDischarge && anyBatteryDischarging(onlineBats)) || anyExplicitZeroDischargeViolation(onlineBats) || + anyBelowStaleFloorDischarging(onlineBats) || anyBlockedBatteryCharging(onlineBats, noSelfCharge) // The PI acts on the meter alone. A held sample carries no new @@ -2279,6 +2285,7 @@ func ComputeDispatch( noSelfDischarge: noSelfDischarge, noSelfCharge: noSelfCharge, chargeBlocked: chargeBlockedDrivers(onlineBats), + floorBlocked: belowStaleFloorDrivers(onlineBats), updatePrevTargets: true, recordDispatch: true, }) @@ -2373,11 +2380,57 @@ func chargeBlockedDrivers(bats []batteryInfo) map[string]bool { return out } +// belowStaleFloorDrivers is the set of online batteries under the stale-plan +// SoC floor. Slew anchors on measured power and would hand back part of a +// discharge the allocator already withdrew. +func belowStaleFloorDrivers(bats []batteryInfo) map[string]bool { + var out map[string]bool + for _, b := range bats { + if !b.belowStaleFloor { + continue + } + if out == nil { + out = make(map[string]bool, len(bats)) + } + out[b.driver] = true + } + return out +} + +// anyBelowStaleFloorDischarging reports a battery under the stale-plan floor +// that is measured discharging. The deadband exit returns no targets, and a +// driver keeps its last setpoint, so such a battery would drain on. +func anyBelowStaleFloorDischarging(bats []batteryInfo) bool { + for _, b := range bats { + if b.belowStaleFloor && b.currentW < -1 { + return true + } + } + return false +} + +// floorBelowStaleFloorDischarge moves a discharge target to 0 W for each +// battery under the stale-plan floor. Fuse relief runs later and stops at +// the same floor, so it cannot reopen the discharge. +func floorBelowStaleFloorDischarge(targets []DispatchTarget, blocked map[string]bool) []DispatchTarget { + if len(blocked) == 0 { + return targets + } + for i := range targets { + if targets[i].TargetW < 0 && blocked[targets[i].Driver] { + targets[i].TargetW = 0 + targets[i].Clamped = true + } + } + return targets +} + type dispatchSafetyOptions struct { manualHoldActive bool noSelfDischarge bool noSelfCharge bool chargeBlocked map[string]bool + floorBlocked map[string]bool updatePrevTargets bool recordDispatch bool } @@ -2417,6 +2470,7 @@ func applyDispatchSafetyPipeline( targets = floorNegativeTargets(targets) } targets = floorBlockedCharge(targets, opts.noSelfCharge, opts.chargeBlocked) + targets = floorBelowStaleFloorDischarge(targets, opts.floorBlocked) // A battery-boost lease may never draw the stationary fleet below its // explicit reserve. Apply this immediately before forceFuseDischarge: @@ -4714,9 +4768,13 @@ func forceFuseDischargeWithSnapshot( lowers[i], _ = fuseTargetBounds(r, state.DriverLimits[t.Driver]) limitLowers[i] = math.Max(lowers[i], boostReserveLowerW(r, cap, state)) } + // Give the limit-only part first to the batteries above the reserve. + // The fuse part then takes what is left down to the SoC floor, so a + // battery under the reserve still serves the fuse and the total is + // never less than in the other order. fusePartW := math.Max(0, overage-limitOnlyW) - out := allocateFuseRelief(targets, fusePartW, lowers) - return allocateFuseRelief(out, overage-fusePartW, limitLowers) + out := allocateFuseRelief(targets, overage-fusePartW, limitLowers) + return allocateFuseRelief(out, fusePartW, lowers) } // allocateFuseRelief subtracts reliefW from the targets in proportion to diff --git a/go/internal/control/soc_floor_test.go b/go/internal/control/soc_floor_test.go index 0334c9e25..e3d1bfb64 100644 --- a/go/internal/control/soc_floor_test.go +++ b/go/internal/control/soc_floor_test.go @@ -3,6 +3,8 @@ package control import ( "testing" "time" + + "github.com/srcfl/ftw/go/internal/telemetry" ) // A planner mode with no plan falls back to self-consumption. It must keep @@ -107,3 +109,106 @@ func TestFuseReliefPassesBoostReserveButKeepsSoCFloor(t *testing.T) { t.Fatalf("fuse overage at SoC 8 %%, floor 10 %%: got %.0f W, want no discharge", got) } } + +func staleFloorState(slew float64) *State { + st := NewState(0, 50, "ferroamp") + st.Mode = ModePlannerCheap + st.UseEnergyDispatch = true + st.SlewRateW = slew + st.MinDispatchIntervalS = 0 + st.DriverLimits = map[string]PowerLimits{"bat": {SoCMin: 0.10}, "bat2": {SoCMin: 0.10}} + st.SlotDirective = func(time.Time) (SlotDirective, bool) { return SlotDirective{}, false } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { return "", 0, "", false } + return st +} + +// SoC drifts under the floor while the battery already covers the house. +// Inside the deadband a tick with no targets leaves the driver on its last +// -2000 W setpoint, and outside it slew hands back -1500 W. Both must stop. +func TestStaleFloorStopsRunningDischarge(t *testing.T) { + cases := []struct { + name string + gridW, slewW float64 + }{ + {"inside deadband", 20, 10000}, + {"after slew", 2000, 500}, + } + for _, c := range cases { + for _, soc := range []float64{0.08, 0.04} { + store := seedStore(c.gridW, []struct { + name string + currentW, soc float64 + }{{"bat", -2000, soc}}) + st := staleFloorState(c.slewW) + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if len(targets) == 0 { + t.Errorf("%s, SoC %.2f: no target, the -2000 W setpoint stays", c.name, soc) + } + for _, tg := range targets { + if tg.TargetW < 0 { + t.Errorf("%s, SoC %.2f: %s %.0f W under the floor", c.name, soc, tg.Driver, tg.TargetW) + } + } + } + } +} + +// A battery under the floor hands its share to a sibling above it. +func TestStaleFloorSiblingTakesShare(t *testing.T) { + store := seedStore(2000, []struct { + name string + currentW, soc float64 + }{{"bat", 0, 0.08}, {"bat2", 0, 0.50}}) + st := staleFloorState(10000) + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200, "bat2": 15200}), 11040) + var sum float64 + for _, tg := range targets { + if tg.Driver == "bat" && tg.TargetW < 0 { + t.Errorf("bat under the floor discharged %.0f W", tg.TargetW) + } + sum += tg.TargetW + } + if sum > -1000 { + t.Errorf("sibling did not take the share: sum %.0f W", sum) + } +} + +// Plain self_consumption keeps Core's 5 % floor; soc_min is a planner rule. +func TestSelfConsumptionStillDischargesUnderSoCMin(t *testing.T) { + store := seedStore(2000, []struct { + name string + currentW, soc float64 + }{{"bat", 0, 0.08}}) + st := NewState(0, 50, "ferroamp") + st.Mode = ModeSelfConsumption + st.SlewRateW = 10000 + st.MinDispatchIntervalS = 0 + st.DriverLimits = map[string]PowerLimits{"bat": {SoCMin: 0.10}} + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if len(targets) == 0 || targets[0].TargetW >= 0 { + t.Errorf("self_consumption at SoC 8 %%: %+v", targets) + } +} + +// Two batteries, one under the boost reserve. 3 kW fuse overage plus 5 kW +// that only the hourly limit asks for. The battery above the reserve takes +// the limit part; the other still serves the fuse. +func TestSplitReliefUsesBothBatteries(t *testing.T) { + store, st, cp := setupPerPhaseSite(3, 230, 20250, 29.35, 29.35, 29.35, 0.20, 5000) + soc := 0.60 + store.Update("bat2", telemetry.DerBattery, 0, &soc, nil) + store.DriverHealthMut("bat2").RecordSuccess() + cp["bat2"] = 15200 + st.DriverLimits["bat2"] = PowerLimits{MaxChargeW: 10000, MaxDischargeW: 5000} + st.SiteFuseAmps = 25 + st.PeakImportCeilingW = 12250 + st.BatteryBoostReserveSoC = 0.30 + out := applyDispatchSafetyPipeline([]DispatchTarget{{Driver: "bat"}, {Driver: "bat2"}}, store, st, cp, 25*230*3, dispatchSafetyOptions{}) + got := map[string]float64{} + for _, o := range out { + got[o.Driver] = o.TargetW + } + if got["bat"] > -2999 || got["bat2"] > -4999 { + t.Errorf("want bat -3000 W, bat2 -5000 W; got bat %.0f W, bat2 %.0f W", got["bat"], got["bat2"]) + } +} From e053d2733dbb6b5e01daefdc3122851f8fac87ec Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 19:36:27 +0100 Subject: [PATCH 3/6] fix(control): no discharge order at exactly the SoC floor clampWithSoC, the stale-plan floor and fuseTargetBounds compared SoC with a strict <, so a battery at exactly 5 % (or exactly soc_min) still got discharge orders. Use <= in all three. Co-Authored-By: Claude Opus 5.5 --- .changeset/c7-soc-floor-inclusive.md | 5 ++ go/internal/control/dispatch.go | 8 +-- go/internal/control/soc_floor_test.go | 71 +++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 .changeset/c7-soc-floor-inclusive.md diff --git a/.changeset/c7-soc-floor-inclusive.md b/.changeset/c7-soc-floor-inclusive.md new file mode 100644 index 000000000..ad4a6f661 --- /dev/null +++ b/.changeset/c7-soc-floor-inclusive.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +A battery that sits exactly at its minimum level no longer gets a discharge order. Before, 5.0 % (or exactly the `soc_min` floor with no plan, during fuse protection and under the hourly import limit) still counted as above the floor. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index ce1e1e7a3..a7be54667 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1528,7 +1528,7 @@ func ComputeDispatch( // A configured zero is a hard direction block, not the legacy // "use MaxCommandW" sentinel. Feed it into the allocator as well as // the clamps so capable siblings receive the blocked battery's share. - belowStaleFloor := staleFloor && soc < lim.socFloor() + belowStaleFloor := staleFloor && soc <= lim.socFloor() dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 || belowStaleFloor chargeBlocked = chargeBlocked || lim.chargeCap() == 0 || state.BatteryChargePaused(name) batteries = append(batteries, batteryInfo{ @@ -3654,7 +3654,7 @@ func clampTargetsToPowerLimits(targets []DispatchTarget, limits map[string]Power const dischargeFloorSoC = 0.05 // clampWithSoC applies the hard safety clamps for one battery command: -// - don't discharge below SoC 5 % (site: don't make target < 0 when SoC < 0.05); +// - don't discharge at or below SoC 5 % (no target < 0 when SoC <= 0.05); // BMS handles fine-grained SoC but we never ask it to pull an empty pack. // - cap charge at the battery's MaxChargeW (falls back to MaxCommandW default). // - cap discharge at the battery's MaxDischargeW (same fallback). @@ -3666,7 +3666,7 @@ func clampWithSoC(target float64, b batteryInfo) (float64, bool) { clamped := target wasClamped := false // Block discharge when the battery is empty. - if b.soc < dischargeFloorSoC && target < 0 { + if b.soc <= dischargeFloorSoC && target < 0 { clamped = 0 wasClamped = true } @@ -4251,7 +4251,7 @@ func fuseTargetBounds(r *telemetry.DerReading, lim PowerLimits) (lower, upper fl lower = -lim.dischargeCap() upper = lim.chargeCap() dischargeBlocked, chargeBlocked := batteryDirectionBlocks(r.Data) - if r.SoC == nil || *r.SoC < lim.socFloor() || dischargeBlocked { + if r.SoC == nil || *r.SoC <= lim.socFloor() || dischargeBlocked { lower = 0 } if chargeBlocked || r.SoC != nil && *r.SoC >= lim.socCeiling() { diff --git a/go/internal/control/soc_floor_test.go b/go/internal/control/soc_floor_test.go index e3d1bfb64..bbc2588d0 100644 --- a/go/internal/control/soc_floor_test.go +++ b/go/internal/control/soc_floor_test.go @@ -212,3 +212,74 @@ func TestSplitReliefUsesBothBatteries(t *testing.T) { t.Errorf("want bat -3000 W, bat2 -5000 W; got bat %.0f W, bat2 %.0f W", got["bat"], got["bat2"]) } } + +// No discharge order goes out at exactly the floor (C7: rig seeds 207534 +// and 207536 ordered discharge at 5.0 %). +func TestClampWithSoCBlocksDischargeAtFloor(t *testing.T) { + if v, was := clampWithSoC(-1000, batteryInfo{soc: dischargeFloorSoC}); v != 0 || !was { + t.Fatalf("SoC exactly 5 %%: got %.0f W clamped=%v, want 0 W", v, was) + } + if v, was := clampWithSoC(-1000, batteryInfo{soc: 0.051}); v != -1000 || was { + t.Fatalf("SoC 5.1 %%: got %.0f W clamped=%v, want -1000 W", v, was) + } +} + +// A fresh plan that asks for discharge at exactly 5 % gets no discharge. +func TestFreshPlanNoDischargeAtFloor(t *testing.T) { + for _, energy := range []bool{false, true} { + store := seedStore(2000, []struct { + name string + currentW, soc float64 + }{{"bat", 0, 0.05}}) + st := NewState(0, 50, "ferroamp") + st.Mode = ModePlannerArbitrage + st.UseEnergyDispatch = energy + st.SlewRateW = 10000 + st.MinDispatchIntervalS = 0 + st.SlotDirective = func(now time.Time) (SlotDirective, bool) { + return SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), BatteryEnergyWh: -500, Strategy: "arbitrage"}, true + } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { return "discharge", -2000, "discharge", true } + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if st.PlanStale { + t.Fatalf("energy=%v: expected a fresh plan", energy) + } + for _, tg := range targets { + if tg.TargetW < 0 { + t.Errorf("energy=%v: SoC exactly 5 %%, %s ordered %.0f W", energy, tg.Driver, tg.TargetW) + } + } + } +} + +// Stale plan, soc_min 10 %: just under the floor (207531, 207532 at +// 5.5-5.8 %) and exactly at it, the battery gets 0 W. +func TestStaleFloorZeroAtAndUnderFloor(t *testing.T) { + for _, soc := range []float64{0.058, 0.10} { + store := seedStore(2000, []struct { + name string + currentW, soc float64 + }{{"bat", -1500, soc}}) + st := staleFloorState(10000) + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if !st.PlanStale { + t.Fatalf("SoC %.3f: expected stale-plan fallback", soc) + } + if len(targets) != 1 || targets[0].TargetW != 0 { + t.Errorf("SoC %.3f, floor 10 %%: got %+v, want bat 0 W", soc, targets) + } + } +} + +// Fuse relief and the hourly import limit stop at exactly the floor. +func TestFuseTargetBoundsAtFloor(t *testing.T) { + soc := 0.10 + r := &telemetry.DerReading{SoC: &soc} + if lower, _ := fuseTargetBounds(r, PowerLimits{SoCMin: 0.10}); lower != 0 { + t.Fatalf("SoC exactly at the 10 %% floor: lower bound %.0f W, want 0", lower) + } + soc = 0.101 + if lower, _ := fuseTargetBounds(r, PowerLimits{SoCMin: 0.10}); lower >= 0 { + t.Fatalf("SoC 10.1 %%, floor 10 %%: lower bound %.0f W, want discharge allowed", lower) + } +} From 635653e45acf5989c562f37f4dfa00c0f8e8ea8c Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 19:47:30 +0100 Subject: [PATCH 4/6] fix(control): a blocked-discharge stop keeps Core's 5 % floor in self-consumption #1876 decides whether the distributor parked a pack by reusing fuseTargetBounds. This branch makes that function honour the owner's soc_min, so plain self-consumption at 8 % with soc_min 10 % was stopped at 0 W. soc_min is a planner rule; the stale-plan floor applies it on its own. Give the stop its own check at Core's 5 % floor, as on master. TestSelfConsumptionStillDischargesUnderSoCMin fails without this. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 824f8642c..7806090ad 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3542,7 +3542,7 @@ func floorBlockedDischarge( if t.TargetW >= 0 || r == nil { continue } - if lower, _ := fuseTargetBounds(r, state.DriverLimits[t.Driver]); lower < 0 { + if !dischargeParked(r, state.DriverLimits[t.Driver]) { continue } if out == nil { @@ -3575,6 +3575,15 @@ func floorBlockedDischarge( return out } +// dischargeParked reports whether the distributor parks a pack's discharge +// at 0 W: no SoC, SoC under Core's 5 % floor, discharge_capable=false or a +// zero discharge limit. The owner's soc_min is a planner rule; the stale-plan +// floor applies it separately (floorBelowStaleFloorDischarge). +func dischargeParked(r *telemetry.DerReading, lim PowerLimits) bool { + dischargeBlocked, _ := batteryDirectionBlocks(r.Data) + return r.SoC == nil || *r.SoC < dischargeFloorSoC || dischargeBlocked || lim.dischargeCap() == 0 +} + // 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 From 09f0c73648160a08d7ef379c50f06e3a2ed81b61 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 20:09:51 +0100 Subject: [PATCH 5/6] fix(control): planner modes keep soc_min with a fresh plan; a running discharge stops at the floor Review of #1916 found three gaps after the merge of #1878 and master: - The owner floor max(5 %, soc_min) applied in planner modes only when the plan was stale. Most seed orders under it (207534, 207536) came on a fresh plan. Drop the PlanStale condition; manual holds and plain self_consumption keep Core's 5 % floor. - A discharge already running at or under 5 % inside the deadband got no target, so the driver kept its setpoint and drained on. The deadband exit now falls through when such a battery is measured discharging. - dischargeParked (#1876) used a strict < on 5 %, so slew handed back part of the discharge at exactly 5 %. Make it <=, as clampWithSoC. Rename belowStaleFloor to belowOwnerFloor to match. One golden record changes: seeded_siblings/034_soc_floor, where the sibling now takes the share of a pack under the floor in planner_arbitrage, as it already did with a stale plan. Co-Authored-By: Claude Opus 5.5 --- .changeset/c7-soc-floor-inclusive.md | 2 +- go/internal/control/dispatch.go | 75 ++++++---- go/internal/control/soc_floor_test.go | 132 ++++++++++++++++++ .../testdata/golden/seeded_siblings.json | 13 +- 4 files changed, 184 insertions(+), 38 deletions(-) diff --git a/.changeset/c7-soc-floor-inclusive.md b/.changeset/c7-soc-floor-inclusive.md index ad4a6f661..2bcff2dab 100644 --- a/.changeset/c7-soc-floor-inclusive.md +++ b/.changeset/c7-soc-floor-inclusive.md @@ -2,4 +2,4 @@ "ftw": patch --- -A battery that sits exactly at its minimum level no longer gets a discharge order. Before, 5.0 % (or exactly the `soc_min` floor with no plan, during fuse protection and under the hourly import limit) still counted as above the floor. +A battery at or under its minimum level no longer discharges. Before, a battery at exactly 5.0 % (or exactly at `soc_min`) still counted as above the floor. Planner modes now keep `soc_min` with a fresh plan too, not only when the plan is missing. A discharge already running stops at the floor even when the grid sits inside the deadband; before, the battery kept its last setpoint and drained on. Plain `self_consumption` and manual holds still use Core's 5 % floor. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index f7100a1ce..b9fa42992 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -239,8 +239,8 @@ type PowerLimits struct { SoCMin float64 } -// socFloor is the lowest SoC that the stale-plan fallback, fuse relief and -// the hourly import limit may discharge to. +// socFloor is the lowest SoC that planner modes, fuse relief and the hourly +// import limit may discharge to. func (l PowerLimits) socFloor() float64 { if l.SoCMin > dischargeFloorSoC && l.SoCMin <= 1 { return l.SoCMin @@ -1173,10 +1173,10 @@ type batteryInfo struct { dischargeBlocked bool chargeBlocked bool socMissing bool // no fresh SoC reading; soc is 0 - // belowStaleFloor: a planner mode without a plan, and SoC under the - // owner's floor. Unlike a driver's transient report, this must also - // stop a discharge already running, past the deadband and slew. - belowStaleFloor bool + // belowOwnerFloor: a planner mode, with or without a plan, and SoC at + // or under the owner's floor. Unlike a driver's transient report, this + // must also stop a discharge already running, past the deadband and slew. + belowOwnerFloor bool } // chargeCap returns the effective per-battery charge ceiling, falling @@ -1505,8 +1505,8 @@ func ComputeDispatch( } // ---- Gather online batteries ---- - // Without a plan, a planner mode keeps the owner's reserve. - staleFloor := !manualHoldActive && state.Mode.IsPlannerMode() && state.PlanStale + // A planner mode keeps the owner's reserve, with or without a plan. + ownerFloor := !manualHoldActive && state.Mode.IsPlannerMode() batteries := make([]batteryInfo, 0, len(driverCapacities)) for name, cap := range driverCapacities { r := store.Get(name, telemetry.DerBattery) @@ -1528,8 +1528,8 @@ func ComputeDispatch( // A configured zero is a hard direction block, not the legacy // "use MaxCommandW" sentinel. Feed it into the allocator as well as // the clamps so capable siblings receive the blocked battery's share. - belowStaleFloor := staleFloor && soc <= lim.socFloor() - dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 || belowStaleFloor + belowOwnerFloor := ownerFloor && soc <= lim.socFloor() + dischargeBlocked = dischargeBlocked || lim.dischargeCap() == 0 || belowOwnerFloor chargeBlocked = chargeBlocked || lim.chargeCap() == 0 || state.BatteryChargePaused(name) batteries = append(batteries, batteryInfo{ driver: name, @@ -1545,7 +1545,7 @@ func ComputeDispatch( dischargeBlocked: dischargeBlocked, chargeBlocked: chargeBlocked, socMissing: socMissing, - belowStaleFloor: belowStaleFloor, + belowOwnerFloor: belowOwnerFloor, }) } onlineBats := make([]batteryInfo, 0, len(batteries)) @@ -1802,7 +1802,8 @@ func ComputeDispatch( // and the held-meter exit both fall through to cut it. batteryBreaksLimit := (noSelfDischarge && anyBatteryDischarging(onlineBats)) || anyExplicitZeroDischargeViolation(onlineBats) || - anyBelowStaleFloorDischarging(onlineBats) || + anyBelowOwnerFloorDischarging(onlineBats) || + anyAtHardFloorDischarging(onlineBats) || anyBlockedBatteryCharging(onlineBats, noSelfCharge) // The PI acts on the meter alone. A held sample carries no new @@ -2285,7 +2286,7 @@ func ComputeDispatch( noSelfDischarge: noSelfDischarge, noSelfCharge: noSelfCharge, chargeBlocked: chargeBlockedDrivers(onlineBats), - floorBlocked: belowStaleFloorDrivers(onlineBats), + floorBlocked: belowOwnerFloorDrivers(onlineBats), updatePrevTargets: true, recordDispatch: true, }) @@ -2380,13 +2381,13 @@ func chargeBlockedDrivers(bats []batteryInfo) map[string]bool { return out } -// belowStaleFloorDrivers is the set of online batteries under the stale-plan -// SoC floor. Slew anchors on measured power and would hand back part of a -// discharge the allocator already withdrew. -func belowStaleFloorDrivers(bats []batteryInfo) map[string]bool { +// belowOwnerFloorDrivers is the set of online batteries at or under the +// owner SoC floor. Slew anchors on measured power and would hand back part +// of a discharge the allocator already withdrew. +func belowOwnerFloorDrivers(bats []batteryInfo) map[string]bool { var out map[string]bool for _, b := range bats { - if !b.belowStaleFloor { + if !b.belowOwnerFloor { continue } if out == nil { @@ -2397,22 +2398,34 @@ func belowStaleFloorDrivers(bats []batteryInfo) map[string]bool { return out } -// anyBelowStaleFloorDischarging reports a battery under the stale-plan floor -// that is measured discharging. The deadband exit returns no targets, and a -// driver keeps its last setpoint, so such a battery would drain on. -func anyBelowStaleFloorDischarging(bats []batteryInfo) bool { +// anyBelowOwnerFloorDischarging reports a battery at or under the owner +// floor that is measured discharging. The deadband exit returns no targets, +// and a driver keeps its last setpoint, so such a battery would drain on. +func anyBelowOwnerFloorDischarging(bats []batteryInfo) bool { for _, b := range bats { - if b.belowStaleFloor && b.currentW < -1 { + if b.belowOwnerFloor && b.currentW < -1 { return true } } return false } -// floorBelowStaleFloorDischarge moves a discharge target to 0 W for each -// battery under the stale-plan floor. Fuse relief runs later and stops at +// anyAtHardFloorDischarging reports a battery at or under Core's 5 % floor +// that is measured discharging, in any mode. The deadband exit would leave +// the driver on its last discharge setpoint. +func anyAtHardFloorDischarging(bats []batteryInfo) bool { + for _, b := range bats { + if !b.socMissing && b.soc <= dischargeFloorSoC && b.currentW < -1 { + return true + } + } + return false +} + +// floorBelowOwnerFloorDischarge moves a discharge target to 0 W for each +// battery at or under the owner floor. Fuse relief runs later and stops at // the same floor, so it cannot reopen the discharge. -func floorBelowStaleFloorDischarge(targets []DispatchTarget, blocked map[string]bool) []DispatchTarget { +func floorBelowOwnerFloorDischarge(targets []DispatchTarget, blocked map[string]bool) []DispatchTarget { if len(blocked) == 0 { return targets } @@ -2470,7 +2483,7 @@ func applyDispatchSafetyPipeline( targets = floorNegativeTargets(targets) } targets = floorBlockedCharge(targets, opts.noSelfCharge, opts.chargeBlocked) - targets = floorBelowStaleFloorDischarge(targets, opts.floorBlocked) + targets = floorBelowOwnerFloorDischarge(targets, opts.floorBlocked) targets = floorBlockedDischarge(targets, store, state, driverCapacities, fuseMaxW) // A battery-boost lease may never draw the stationary fleet below its @@ -3576,12 +3589,12 @@ func floorBlockedDischarge( } // dischargeParked reports whether the distributor parks a pack's discharge -// at 0 W: no SoC, SoC under Core's 5 % floor, discharge_capable=false or a -// zero discharge limit. The owner's soc_min is a planner rule; the stale-plan -// floor applies it separately (floorBelowStaleFloorDischarge). +// at 0 W: no SoC, SoC at or under Core's 5 % floor, discharge_capable=false +// or a zero discharge limit. The owner's soc_min is a planner rule; the +// owner floor applies it separately (floorBelowOwnerFloorDischarge). func dischargeParked(r *telemetry.DerReading, lim PowerLimits) bool { dischargeBlocked, _ := batteryDirectionBlocks(r.Data) - return r.SoC == nil || *r.SoC < dischargeFloorSoC || dischargeBlocked || lim.dischargeCap() == 0 + return r.SoC == nil || *r.SoC <= dischargeFloorSoC || dischargeBlocked || lim.dischargeCap() == 0 } // blockedDischargeKeepW is the discharge the blocked packs must keep after diff --git a/go/internal/control/soc_floor_test.go b/go/internal/control/soc_floor_test.go index bbc2588d0..6b45094ff 100644 --- a/go/internal/control/soc_floor_test.go +++ b/go/internal/control/soc_floor_test.go @@ -283,3 +283,135 @@ func TestFuseTargetBoundsAtFloor(t *testing.T) { t.Fatalf("SoC 10.1 %%, floor 10 %%: lower bound %.0f W, want discharge allowed", lower) } } + +// A planner mode keeps the owner's floor with a fresh plan too. In the rig +// the planner sets soc_min 10 %, and most discharge orders in seeds 207534 +// and 207536 came on a fresh plan. +func TestFreshPlanKeepsSoCMin(t *testing.T) { + run := func(energy bool, soc float64) []DispatchTarget { + store := seedStore(2000, []struct { + name string + currentW, soc float64 + }{{"bat", 0, soc}}) + st := NewState(0, 50, "ferroamp") + st.Mode = ModePlannerSelf + st.UseEnergyDispatch = energy + st.SlewRateW = 10000 + st.MinDispatchIntervalS = 0 + st.DriverLimits = map[string]PowerLimits{"bat": {SoCMin: 0.10}} + st.SlotDirective = func(now time.Time) (SlotDirective, bool) { + return SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), BatteryEnergyWh: -500, Strategy: "self_consumption"}, true + } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { return "self_consumption", 0, "self", true } + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if st.PlanStale { + t.Fatalf("energy=%v SoC %.2f: expected a fresh plan", energy, soc) + } + return targets + } + for _, energy := range []bool{false, true} { + for _, soc := range []float64{0.08, 0.10} { + for _, tg := range run(energy, soc) { + if tg.TargetW < 0 { + t.Errorf("energy=%v SoC %.2f, soc_min 10 %%: %s ordered %.0f W", energy, soc, tg.Driver, tg.TargetW) + } + } + } + if targets := run(energy, 0.12); len(targets) == 0 || targets[0].TargetW >= 0 { + t.Errorf("energy=%v SoC 12 %%, soc_min 10 %%: %+v, want discharge", energy, targets) + } + } +} + +// Core's 5 % floor stops a discharge already running, in every mode. +// Inside the deadband a tick with no targets leaves the driver on its last +// -2000 W setpoint; outside it slew hands back part of the discharge. +func TestHardFloorStopsRunningDischarge(t *testing.T) { + cases := []struct { + name string + gridW, slewW float64 + }{ + {"inside deadband", 20, 10000}, + {"after slew", 2000, 500}, + } + for _, mode := range []Mode{ModeSelfConsumption, ModePlannerSelf} { + for _, c := range cases { + for _, soc := range []float64{0.05, 0.04} { + store := seedStore(c.gridW, []struct { + name string + currentW, soc float64 + }{{"bat", -2000, soc}}) + st := NewState(0, 50, "ferroamp") + st.Mode = mode + st.SlewEnabled = true + st.SlewRateW = c.slewW + st.MinDispatchIntervalS = 0 + st.SlotDirective = func(now time.Time) (SlotDirective, bool) { + return SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), Strategy: "self_consumption"}, true + } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { return "self_consumption", 0, "self", true } + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if len(targets) == 0 { + t.Errorf("%s %s SoC %.2f: no target, the -2000 W setpoint stays", mode, c.name, soc) + } + for _, tg := range targets { + if tg.TargetW < 0 { + t.Errorf("%s %s SoC %.2f: %s %.0f W at or under 5 %%", mode, c.name, soc, tg.Driver, tg.TargetW) + } + } + } + } + } +} + +// Closed loop: the battery covers a 2 kW house at -2000 W and SoC walks +// down through 5 %. The driver keeps its last setpoint when no target +// comes. No tick at or under the floor may keep a discharge. +func TestHardFloorDeadbandClosedLoop(t *testing.T) { + st := NewState(0, 50, "ferroamp") + st.Mode = ModeSelfConsumption + st.SlewEnabled = true + st.SlewRateW = 3000 + st.MinDispatchIntervalS = 0 + setpoint := -2000.0 + soc := 0.0505 + bad := 0 + for tick := 0; tick < 60; tick++ { + store := seedStore(2000+setpoint, []struct { + name string + currentW, soc float64 + }{{"bat", setpoint, soc}}) + for _, tg := range ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) { + setpoint = tg.TargetW + } + if soc <= dischargeFloorSoC && setpoint < 0 { + bad++ + } + soc -= -setpoint / 10000 / 3600 * 2 // 10 kWh, 2 s tick + } + if bad > 0 { + t.Errorf("%d of 60 ticks kept a discharge at or under 5 %% (final SoC %.4f, setpoint %.0f W)", bad, soc, setpoint) + } +} + +// Fuse relief through the full safety pipeline, no soc_min: SoC exactly +// 5 % orders no discharge; 5.1 % may. +func TestFuseReliefPipelineAtHardFloor(t *testing.T) { + run := func(soc, curW float64) float64 { + store, st, cp := setupPerPhaseSite(3, 230, 13000, 19, 19, 19, soc, 5000) + if curW != 0 { + s := soc + store.Update("bat", telemetry.DerBattery, curW, &s, nil) + } + out := applyDispatchSafetyPipeline([]DispatchTarget{{Driver: "bat"}}, store, st, cp, 16*230*3, dispatchSafetyOptions{}) + return out[0].TargetW + } + for _, cur := range []float64{0, -5000} { + if got := run(0.05, cur); got < 0 { + t.Errorf("SoC exactly 5 %% (battery at %.0f W): ordered %.0f W", cur, got) + } + } + if got := run(0.051, 0); got >= 0 { + t.Errorf("SoC 5.1 %%: got %.0f W, want discharge", got) + } +} diff --git a/go/internal/control/testdata/golden/seeded_siblings.json b/go/internal/control/testdata/golden/seeded_siblings.json index e6339aa3a..1433c45b8 100644 --- a/go/internal/control/testdata/golden/seeded_siblings.json +++ b/go/internal/control/testdata/golden/seeded_siblings.json @@ -1,7 +1,7 @@ { "family": "seeded_siblings", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "b3af71859a912dcae3a512f6c1ca79a21c2bb631", + "ftw_commit": "c41dc64bb5a70b8c838e50225566995f3331fa70", "record_count": 60, "records": [ { @@ -3774,13 +3774,14 @@ }, { "driver": "sungrow", - "target_w": -3200, - "clamped": false + "target_w": -5000, + "clamped": true } ], "clamp_attributions": { "clamped_drivers": [ - "ferroamp" + "ferroamp", + "sungrow" ], "all_targets_zero_clamped": false, "plan_sign_intent": -1, @@ -3799,9 +3800,9 @@ }, "site_totals": { "battery_current_w": -1969, - "battery_target_sum_w": -3200, + "battery_target_sum_w": -5000, "raw_grid_w": 5401, - "projected_grid_w": 4170 + "projected_grid_w": 2370 } }, { From 2dd6bb9caa547f3cb1f6c9166737aee5a838f0a0 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:42:53 +0100 Subject: [PATCH 6/6] fix(control): standby draw at the SoC floor no longer breaks the deadband A pack parked at its floor reads tens of watts of standby draw. Any reading below -1 W made batteryBreaksLimit skip the deadband, so the PI chased meter noise and sent an order every tick. Now only a discharge past 50 W, or any discharge after FTW's own last order was a discharge, falls through. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 32 +++++++---- go/internal/control/soc_floor_test.go | 77 +++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 10 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index b9fa42992..799d1ddb3 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1802,8 +1802,8 @@ func ComputeDispatch( // and the held-meter exit both fall through to cut it. batteryBreaksLimit := (noSelfDischarge && anyBatteryDischarging(onlineBats)) || anyExplicitZeroDischargeViolation(onlineBats) || - anyBelowOwnerFloorDischarging(onlineBats) || - anyAtHardFloorDischarging(onlineBats) || + anyBelowOwnerFloorDischarging(onlineBats, state.PrevTargets) || + anyAtHardFloorDischarging(onlineBats, state.PrevTargets) || anyBlockedBatteryCharging(onlineBats, noSelfCharge) // The PI acts on the meter alone. A held sample carries no new @@ -2398,12 +2398,24 @@ func belowOwnerFloorDrivers(bats []batteryInfo) map[string]bool { return out } +// floorStandbyW is the largest draw a pack parked at its floor may read +// without counting as a discharge. Packs report tens of watts of standby +// draw there; treating that as a discharge sent an order every tick. +const floorStandbyW = 50.0 + +// dischargingAtFloor reports a real discharge on a pack at its floor: past +// standby draw, or any measured discharge after FTW's own last order to it +// was a discharge, which the driver would otherwise hold. +func dischargingAtFloor(b batteryInfo, prev map[string]float64) bool { + return b.currentW < -floorStandbyW || b.currentW < -1 && prev[b.driver] < 0 +} + // anyBelowOwnerFloorDischarging reports a battery at or under the owner -// floor that is measured discharging. The deadband exit returns no targets, -// and a driver keeps its last setpoint, so such a battery would drain on. -func anyBelowOwnerFloorDischarging(bats []batteryInfo) bool { +// floor that is discharging. The deadband exit returns no targets, and a +// driver keeps its last setpoint, so such a battery would drain on. +func anyBelowOwnerFloorDischarging(bats []batteryInfo, prev map[string]float64) bool { for _, b := range bats { - if b.belowOwnerFloor && b.currentW < -1 { + if b.belowOwnerFloor && dischargingAtFloor(b, prev) { return true } } @@ -2411,11 +2423,11 @@ func anyBelowOwnerFloorDischarging(bats []batteryInfo) bool { } // anyAtHardFloorDischarging reports a battery at or under Core's 5 % floor -// that is measured discharging, in any mode. The deadband exit would leave -// the driver on its last discharge setpoint. -func anyAtHardFloorDischarging(bats []batteryInfo) bool { +// that is discharging, in any mode. The deadband exit would leave the +// driver on its last discharge setpoint. +func anyAtHardFloorDischarging(bats []batteryInfo, prev map[string]float64) bool { for _, b := range bats { - if !b.socMissing && b.soc <= dischargeFloorSoC && b.currentW < -1 { + if !b.socMissing && b.soc <= dischargeFloorSoC && dischargingAtFloor(b, prev) { return true } } diff --git a/go/internal/control/soc_floor_test.go b/go/internal/control/soc_floor_test.go index 6b45094ff..a13c1ab87 100644 --- a/go/internal/control/soc_floor_test.go +++ b/go/internal/control/soc_floor_test.go @@ -1,6 +1,7 @@ package control import ( + "math" "testing" "time" @@ -415,3 +416,79 @@ func TestFuseReliefPipelineAtHardFloor(t *testing.T) { t.Errorf("SoC 5.1 %%: got %.0f W, want discharge", got) } } + +// floorStandbyWalk runs 300 ticks with a pack parked at its floor that +// reads a -15 W standby draw while the grid wanders inside the 50 W +// deadband. It returns how many ticks sent an order. +func floorStandbyWalk(st *State, soc float64) int { + sent := 0 + gridW := 0.0 + seed := uint32(7) + for tick := 0; tick < 300; tick++ { + seed = seed*1664525 + 1013904223 + gridW += float64(int(seed>>24)%21 - 10) + gridW = math.Max(-45, math.Min(45, gridW)) + store := seedStore(gridW, []struct { + name string + currentW, soc float64 + }{{"bat", -15, soc}}) + if len(ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040)) > 0 { + sent++ + } + } + return sent +} + +// A pack parked at Core's 5 % floor with standby draw is not discharging. +// The deadband holds, so the PI does not chase meter noise. +func TestHardFloorStandbyRandomWalk(t *testing.T) { + for _, soc := range []float64{0.05, 0.049} { + st := NewState(0, 50, "ferroamp") + st.Mode = ModeSelfConsumption + st.SlewEnabled = true + st.SlewRateW = 3000 + st.MinDispatchIntervalS = 0 + if sent := floorStandbyWalk(st, soc); sent != 0 { + t.Errorf("SoC %.3f, -15 W standby: %d of 300 ticks sent an order, want 0", soc, sent) + } + } +} + +// The same at the owner floor, in a planner mode with a fresh plan. +func TestOwnerFloorStandbyRandomWalk(t *testing.T) { + for _, energy := range []bool{false, true} { + st := NewState(0, 50, "ferroamp") + st.Mode = ModePlannerSelf + st.UseEnergyDispatch = energy + st.SlewEnabled = true + st.SlewRateW = 3000 + st.MinDispatchIntervalS = 0 + st.DriverLimits = map[string]PowerLimits{"bat": {SoCMin: 0.10}} + st.SlotDirective = func(now time.Time) (SlotDirective, bool) { + return SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), Strategy: "self_consumption"}, true + } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { return "self_consumption", 0, "self", true } + if sent := floorStandbyWalk(st, 0.10); sent != 0 { + t.Errorf("planner_self energy=%v, SoC 10 %%, -15 W standby: %d of 300 ticks sent an order, want 0", energy, sent) + } + } +} + +// A small discharge that FTW itself ordered still stops at the floor, +// though it reads under the standby threshold: the driver would hold it. +func TestHardFloorStopsOwnSmallDischarge(t *testing.T) { + st := NewState(0, 50, "ferroamp") + st.Mode = ModeSelfConsumption + st.SlewEnabled = true + st.SlewRateW = 3000 + st.MinDispatchIntervalS = 0 + st.PrevTargets["bat"] = -30 + store := seedStore(10, []struct { + name string + currentW, soc float64 + }{{"bat", -30, 0.05}}) + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat": 15200}), 11040) + if len(targets) == 0 || targets[0].TargetW < 0 { + t.Fatalf("own -30 W order at 5 %%: %+v, want a 0 W order", targets) + } +}