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 e5e895879..4a32496aa 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -3663,11 +3663,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 { @@ -3677,6 +3686,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 f68f54885..7806090ad 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 { @@ -1161,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 @@ -1489,6 +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 batteries := make([]batteryInfo, 0, len(driverCapacities)) for name, cap := range driverCapacities { r := store.Get(name, telemetry.DerBattery) @@ -1510,7 +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 + 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, @@ -1526,6 +1545,7 @@ func ComputeDispatch( dischargeBlocked: dischargeBlocked, chargeBlocked: chargeBlocked, socMissing: socMissing, + belowStaleFloor: belowStaleFloor, }) } onlineBats := make([]batteryInfo, 0, len(batteries)) @@ -1782,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 @@ -2264,6 +2285,7 @@ func ComputeDispatch( noSelfDischarge: noSelfDischarge, noSelfCharge: noSelfCharge, chargeBlocked: chargeBlockedDrivers(onlineBats), + floorBlocked: belowStaleFloorDrivers(onlineBats), updatePrevTargets: true, recordDispatch: true, }) @@ -2358,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 } @@ -2402,12 +2470,14 @@ func applyDispatchSafetyPipeline( targets = floorNegativeTargets(targets) } targets = floorBlockedCharge(targets, opts.noSelfCharge, opts.chargeBlocked) + targets = floorBelowStaleFloorDischarge(targets, opts.floorBlocked) 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: // 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 @@ -2557,31 +2627,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) { @@ -3467,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 { @@ -3500,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 @@ -4323,7 +4407,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() { @@ -4685,8 +4769,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) @@ -4702,9 +4800,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) @@ -4721,7 +4820,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 @@ -4791,7 +4894,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 } @@ -4804,13 +4907,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 @@ -4819,35 +4921,49 @@ 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)) + } + // 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, overage-fusePartW, limitLowers) + return allocateFuseRelief(out, fusePartW, lowers) +} + +// 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..e3d1bfb64 --- /dev/null +++ b/go/internal/control/soc_floor_test.go @@ -0,0 +1,214 @@ +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 +// 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) + } +} + +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"]) + } +}