diff --git a/.changeset/ems-battery-soc-max.md b/.changeset/ems-battery-soc-max.md new file mode 100644 index 000000000..fcb4bc7c9 --- /dev/null +++ b/.changeset/ems-battery-soc-max.md @@ -0,0 +1,8 @@ +--- +"ftw": patch +--- + +Stop battery charging at the configured maximum charge level in every EMS mode, +including manual holds and self-tuning. Use each battery's soc_max, or the +planner's limit when the battery has none. Charging resumes one percentage +point below that limit; discharge remains available. diff --git a/go/cmd/ftw/battery_soc_max_test.go b/go/cmd/ftw/battery_soc_max_test.go new file mode 100644 index 000000000..6f8f4dfce --- /dev/null +++ b/go/cmd/ftw/battery_soc_max_test.go @@ -0,0 +1,68 @@ +package main + +import ( + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/control" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The planner's earlier charge budget cannot override the owner's SoC limit. +// No solar or export is needed to reproduce the 10 kW order at 90%. +func TestConfiguredSoCMaxStopsDispatch(t *testing.T) { + for _, mode := range []control.Mode{control.ModeCharge, control.ModePlannerArbitrage} { + t.Run(string(mode), func(t *testing.T) { + cfg := parseBatteryLimitConfig(t, "", " soc_max: 0.9\n max_charge_w: 10000\n") + ctrl := newControlStateFromConfig(cfg) + ctrl.Mode = mode + ctrl.SlewEnabled = false + ctrl.UseEnergyDispatch = true + ctrl.SlotDirective = func(now time.Time) (control.SlotDirective, bool) { + return control.SlotDirective{ + SlotStart: now, SlotEnd: now.Add(15 * time.Minute), + BatteryEnergyWh: 2500, PlannedGridW: 11000, HasPlannedGridW: true, + }, true + } + tel := batteryLimitStore(1000) + soc := 0.9 + tel.Update("battery", telemetry.DerBattery, 0, &soc, nil) + got := control.ComputeDispatch(tel, ctrl, map[string]float64{"battery": 15000}, 40000) + if len(got) != 1 || got[0].TargetW != 0 { + t.Fatalf("soc_max=0.9 at 90%% sent %+v, want one 0 W target", got) + } + }) + } +} + +func TestSoCMaxConfigPrecedenceAndReload(t *testing.T) { + cfg := parseBatteryLimitConfig(t, "", " soc_max: 0.9\n") + cfg.Planner = &config.Planner{SoCMax: .8} + ctrl := newControlStateFromConfig(cfg) + ctrl.Mode, ctrl.SlewEnabled = control.ModeCharge, false + tel := batteryLimitStore(1000) + capacities := map[string]float64{"battery": 10000} + check := func(soc float64, charging bool) { + t.Helper() + tel.Update("battery", telemetry.DerBattery, 0, &soc, nil) + got := control.ComputeDispatch(tel, ctrl, capacities, 40000) + if len(got) != 1 || (got[0].TargetW > 0) != charging { + t.Fatalf("SoC %.2f: got %+v, want charging=%v", soc, got, charging) + } + } + check(.85, true) // The battery's 90% overrides the planner's 80%. + check(.9, false) + // The config watcher replaces the limits through this same function. + cfg.Batteries = nil + ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner) + check(.85, false) // With no battery override, the planner's 80% applies. + cfg.Planner = nil + ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner) + check(.99, true) // No configured ceiling keeps the 100% default. + check(1, false) + zero := 0.0 + cfg.Batteries = map[string]config.Battery{"battery": {SoCMax: &zero}} + ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner) + check(.5, false) // An explicit zero is not an absent limit. +} diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index eb18815df..de09caf3f 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -3616,20 +3616,29 @@ func driverCapacitiesFrom(drvList []config.Driver, loadpoints []config.Loadpoint } // driverLimitsFrom gives dispatch the same per-driver limits as the planner, -// with each battery's floor: its soc_min, else the planner's (default 10 %). +// with each battery's SoC bounds, falling back to the planner's. func driverLimitsFrom(drivers []config.Driver, batteries map[string]config.Battery, planner *config.Planner) map[string]control.PowerLimits { floor := 0.10 + ceiling := 1.0 if planner != nil && planner.SoCMin > 0 { floor = planner.SoCMin } + if planner != nil && planner.SoCMax > 0 { + ceiling = planner.SoCMax + } out := map[string]control.PowerLimits{} for _, d := range drivers { if !d.ObserveOnly { limits := batteryPowerLimits(d, batteries[d.Name]) limits.SoCMin = floor + limits.SoCMax = ceiling if b := batteries[d.Name]; b.SoCMin != nil { limits.SoCMin = *b.SoCMin } + if b := batteries[d.Name]; b.SoCMax != nil { + limits.SoCMax = *b.SoCMax + limits.SoCMaxSet = true + } out[d.Name] = limits } } diff --git a/go/internal/api/api_battery_soc_max_test.go b/go/internal/api/api_battery_soc_max_test.go new file mode 100644 index 000000000..e0a8038e9 --- /dev/null +++ b/go/internal/api/api_battery_soc_max_test.go @@ -0,0 +1,42 @@ +package api + +import ( + "encoding/json" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/srcfl/ftw/go/internal/control" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +func TestSoCMaxFeedbackUsesTheDispatchResumeLevel(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tel := telemetry.NewStore() + soc := .9 + tel.Update("battery", telemetry.DerBattery, 0, &soc, nil) + tel.RecordDriverSuccess("battery") + tel.Update("meter", telemetry.DerMeter, 1000, nil, nil) + tel.RecordDriverSuccess("meter") + st := control.NewState(0, 50, "meter") + st.Mode = control.ModeCharge + st.DriverLimits = map[string]control.PowerLimits{"battery": {SoCMax: .9}} + got := control.ComputeDispatch(tel, st, map[string]float64{"battery": 15000}, 13800) + if len(got) != 1 || got[0].TargetW != 0 { + t.Fatalf("charge not stopped: %+v", got) + } + request, _ := json.Marshal(map[string]any{"action": "battery", "power_w": 0}) + cmd := tel.BeginCommand("battery", request, time.Now()) + tel.CompleteCommand(cmd, "accepted") + for range 16 { + tel.Update("battery", telemetry.DerBattery, 0, &soc, []byte(`{"setpoint_w":0}`)) + time.Sleep(3 * time.Second) + } + srv := New(&Deps{Tel: tel, Ctrl: st, CtrlMu: &sync.Mutex{}}) + f := srv.controlFeedback(time.Now())[0] + if f.Status != "limited" || f.Reason != "battery_full" || f.Severity != "info" || f.ChargeResumeSoC == nil || *f.ChargeResumeSoC != .89 { + t.Fatalf("wrong explanation of the 90%% stop: %+v", f) + } + }) +} diff --git a/go/internal/api/api_control_feedback.go b/go/internal/api/api_control_feedback.go index ca84538ed..68c905afa 100644 --- a/go/internal/api/api_control_feedback.go +++ b/go/internal/api/api_control_feedback.go @@ -84,7 +84,7 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { } mode, meter := "", "" clamped := map[string]bool{} - full := map[string]bool{} + full := map[string]float64{} targeted := map[string]bool{} var hold control.BatteryManualHold var held bool @@ -94,7 +94,9 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { meter = s.deps.Ctrl.SiteMeterDriver for _, t := range s.deps.Ctrl.LastTargets { clamped[t.Driver] = t.Clamped - full[t.Driver] = s.deps.Ctrl.BatteryChargePaused(t.Driver) + if s.deps.Ctrl.BatteryChargePaused(t.Driver) { + full[t.Driver] = s.deps.Ctrl.BatteryChargeResumeSoC(t.Driver) + } targeted[t.Driver] = true } hold, held = s.deps.Ctrl.GetBatteryManualHold(now) @@ -178,9 +180,9 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { if clamped[rd.Driver] && kind == telemetry.DerBattery { coreReason = "core_limit" } - if full[rd.Driver] && kind == telemetry.DerBattery && f.BatterySoC != nil { + if resume, paused := full[rd.Driver]; paused && kind == telemetry.DerBattery && f.BatterySoC != nil { coreReason = "battery_full" - f.ChargeResumeSoC = watts(control.BatteryChargeResumeSoC) + f.ChargeResumeSoC = watts(resume) } if held && kind == telemetry.DerBattery && (hold.Driver == "" || hold.Driver == rd.Driver) { f.Mode = "manual" diff --git a/go/internal/control/battery_full.go b/go/internal/control/battery_full.go index b7c358404..f36dc75de 100644 --- a/go/internal/control/battery_full.go +++ b/go/internal/control/battery_full.go @@ -6,9 +6,14 @@ import ( "github.com/srcfl/ftw/go/internal/telemetry" ) -// A one percentage point gap prevents repeated starts at a rounded 100%. -// This limits charging only; the plan can discharge a full battery at once. -const BatteryChargeResumeSoC = 0.99 +// A one percentage point gap prevents repeated starts at the charge ceiling. +const batteryChargeHysteresisSoC = 0.01 + +// BatteryChargeResumeSoC uses the same ceiling as dispatch. Callers hold the +// control lock, as they do for BatteryChargePaused. +func (s *State) BatteryChargeResumeSoC(driver string) float64 { + return math.Max(0, s.DriverLimits[driver].socCeiling()-batteryChargeHysteresisSoC) +} // BatteryChargePaused reports the dispatcher's full-battery stop. Callers use // the same lock as ComputeDispatch; this state is local to the running device. @@ -17,6 +22,9 @@ func (s *State) BatteryChargePaused(driver string) bool { } func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[string]float64) { + if s == nil || store == nil { + return + } if s.batteryChargeFull == nil { s.batteryChargeFull = map[string]bool{} } @@ -36,9 +44,9 @@ func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[s if age < 0 || age > telemetry.BatterySoCMaxAge || math.IsNaN(soc) || math.IsInf(soc, 0) || soc < 0 || soc > 1 { continue } - if soc == 1 { + if soc >= s.DriverLimits[name].socCeiling() { s.batteryChargeFull[name] = true - } else if soc <= BatteryChargeResumeSoC { + } else if soc <= s.BatteryChargeResumeSoC(name) { delete(s.batteryChargeFull, name) } } diff --git a/go/internal/control/battery_soc_max_test.go b/go/internal/control/battery_soc_max_test.go new file mode 100644 index 000000000..4d201a9bb --- /dev/null +++ b/go/internal/control/battery_soc_max_test.go @@ -0,0 +1,154 @@ +package control + +import ( + "testing" + "testing/synctest" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +func cappedBatterySite(soc, power float64) (*telemetry.Store, *State, map[string]float64) { + tel, st, capacities := fullBatterySite(soc, power) + st.DriverLimits = map[string]PowerLimits{"battery": {SoCMax: .9, MaxChargeW: 10000}} + return tel, st, capacities +} + +func TestSoCMaxStopsChargingInEveryMode(t *testing.T) { + for _, mode := range AllModes() { + for _, energy := range []bool{false, true} { + t.Run(string(mode)+"/energy="+map[bool]string{false: "off", true: "on"}[energy], func(t *testing.T) { + tel, st, capacities := cappedBatterySite(.9, 2000) + st.Mode, st.UseEnergyDispatch = mode, energy + st.SlewEnabled, st.SlewRateW = true, 10 + st.SlotDirective = func(now time.Time) (SlotDirective, bool) { + return SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), BatteryEnergyWh: 500}, true + } + st.PlanTarget = func(time.Time) (string, float64, string, bool) { + return string(ModeCharge), 2000, "charge", true + } + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW > 0 || !st.BatteryChargePaused("battery") { + t.Fatalf("90%% ceiling did not stop charging: %+v", got) + } + }) + } + } +} + +func TestSoCMaxManualHoldAndSibling(t *testing.T) { + tel, st, capacities := cappedBatterySite(.9, 0) + tel.Update("other", telemetry.DerBattery, 0, ptrF64(.8), nil) + tel.RecordDriverSuccess("other") + capacities["other"] = 9600 + st.DriverLimits["other"] = PowerLimits{SoCMax: .95} + st.SlewEnabled = false + st.SetBatteryManualHold(BatteryManualHold{PowerW: 3000, ExpiresAt: time.Now().Add(time.Hour)}) + got := ComputeDispatch(tel, st, capacities, 13800) + if targetFor(t, got, "battery").TargetW != 0 || targetFor(t, got, "other").TargetW < 2900 { + t.Fatalf("charge must go to the battery below its own ceiling: %+v", got) + } + st.SetBatteryManualHold(BatteryManualHold{PowerW: -2000, ExpiresAt: time.Now().Add(time.Hour)}) + got = ComputeDispatch(tel, st, capacities, 13800) + if targetFor(t, got, "battery").TargetW >= 0 { + t.Fatalf("charge ceiling blocked discharge: %+v", got) + } + st.BatteryHoldTargetValid = func(driver, id string) bool { return driver == "battery" && id == "hardware" } + st.SetBatteryManualHold(BatteryManualHold{Driver: "battery", DeviceID: "hardware", PowerW: 3000, ExpiresAt: time.Now().Add(time.Hour)}) + got = ComputeDispatch(tel, st, capacities, 13800) + if targetFor(t, got, "battery").TargetW != 0 || targetFor(t, got, "other").TargetW != 0 { + t.Fatalf("scoped hold bypassed its ceiling or charged another battery: %+v", got) + } +} + +func TestSoCMaxStopsSelfTuneWithoutPriorControlTick(t *testing.T) { + tel, st, capacities := cappedBatterySite(.9, 1000) + got := SelfTuneDispatch(tel, st, capacities, 13800, "battery", 3000) + if len(got) != 1 || got[0].TargetW != 0 || !got[0].Clamped { + t.Fatalf("self-tune crossed the charge ceiling: %+v", got) + } +} + +func TestSoCMaxStopsPreviousOrderDuringQuietOrHeldTick(t *testing.T) { + for _, holdoff := range []bool{false, true} { + tel, st, capacities := cappedBatterySite(.9, 0) + st.Mode = ModeSelfConsumption + tel.Update("ferroamp", telemetry.DerMeter, 0, nil, nil) + st.PrevTargets["battery"] = 10000 + st.LastTargets = []DispatchTarget{{Driver: "battery", TargetW: 10000}} + if holdoff { + now := time.Now() + st.LastDispatch, st.MinDispatchIntervalS = &now, 60 + } + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW != 0 || st.LastTargets[0].TargetW != 0 || st.PrevTargets["battery"] != 0 { + t.Fatalf("holdoff=%v left the prior charge active: %+v", holdoff, got) + } + } +} + +func TestSoCMaxHysteresisAndMissingLevel(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tel, st, capacities := cappedBatterySite(.899, 0) + check := func(paused bool) { + t.Helper() + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || st.BatteryChargePaused("battery") != paused || (got[0].TargetW == 0) != paused { + t.Fatalf("paused=%v targets=%+v, want paused=%v", st.BatteryChargePaused("battery"), got, paused) + } + } + check(false) + for _, level := range []float64{.9, .92, .899, .891} { + tel.Update("battery", telemetry.DerBattery, 0, &level, nil) + check(true) + } + time.Sleep(6 * time.Minute) + tel.Update("battery", telemetry.DerBattery, 0, nil, nil) + tel.RecordDriverSuccess("battery") + check(true) + tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.89), nil) + check(false) + }) +} + +func TestSoCMaxReloadTakesEffectOnNextTick(t *testing.T) { + tel, st, capacities := cappedBatterySite(.9, 0) + ComputeDispatch(tel, st, capacities, 13800) + st.DriverLimits["battery"] = PowerLimits{SoCMax: .95} + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW <= 0 { + t.Fatalf("raising the ceiling did not release the stop: %+v", got) + } + st.DriverLimits["battery"] = PowerLimits{SoCMax: .85} + got = ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW != 0 { + t.Fatalf("lowering the ceiling did not stop charging: %+v", got) + } +} + +func TestSoCMaxStillAllowsFuseRelief(t *testing.T) { + tel, st, capacities := cappedBatterySite(.9, 0) + tel.Update("ferroamp", telemetry.DerMeter, 16000, nil, nil) + st.Mode = ModeIdle + describeFuse(st, 13800) + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW >= 0 { + t.Fatalf("charge ceiling blocked fuse relief: %+v", got) + } +} + +func TestSoCMaxExportGuardCannotRestorePausedCharge(t *testing.T) { + tel, st, capacities := cappedBatterySite(.9, 2000) + st.Mode = ModeIdle + describeFuse(st, 13800) + st.batteryCommands = map[string]commandLog{"battery": commandLog{}.add(st.now(), 2000)} + st.updateBatteryChargeFull(tel, capacities) + // The stop remains active below the ceiling until the resume level. Even + // an export overage must not restore the charge that the stop removed. + tel.Update("battery", telemetry.DerBattery, 2000, ptrF64(.895), nil) + tel.Update("ferroamp", telemetry.DerMeter, -20000, nil, nil) + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW != 0 { + t.Fatalf("export guard restored paused charging: %+v", got) + } +} diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index a21f90dd6..bfb2a1fb2 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -230,11 +230,21 @@ type PowerLimits struct { // SoCMin is the battery's floor, 0..1: its soc_min, else the planner's. // Fuse relief discharges no further. Zero leaves the 5 % empty guard. SoCMin float64 + // SoCMax is the battery's charge ceiling, 0..1. An unset limit uses 100%. + SoCMax float64 + SoCMaxSet bool } // socFloor is the SoC fuse relief stops discharging at. func (l PowerLimits) socFloor() float64 { return math.Max(0.05, l.SoCMin) } +func (l PowerLimits) socCeiling() float64 { + if (l.SoCMaxSet || l.SoCMax > 0) && l.SoCMax >= 0 && l.SoCMax <= 1 { + return l.SoCMax + } + return 1 +} + func effectivePowerLimit(value float64, set bool) float64 { if set && value >= 0 { return value @@ -2280,6 +2290,7 @@ func applyDispatchSafetyPipeline( // ---- The hour's import limit and the export limit (#145) ---- if state != nil { state.FuseSaturated, state.FuseSaturatedByImport = false, false + state.updateBatteryChargeFull(store, driverCapacities) } targets = applySiteLimits(targets, store, state) @@ -2322,8 +2333,8 @@ func applyDispatchSafetyPipeline( targets = clampTargetsToPowerLimits(targets, state.DriverLimits) } targets = floorMissingSoCDischarge(targets, store) - targets = state.floorFullBatteryCharge(targets) targets = fitBatteryRisesToFuse(targets, store, state) + targets = state.floorFullBatteryCharge(targets) recordDispatchTargets(targets, state, opts.updatePrevTargets, opts.recordDispatch) return targets } @@ -3745,7 +3756,7 @@ func fuseTargetBounds(r *telemetry.DerReading, lim PowerLimits) (lower, upper fl if r.SoC == nil || *r.SoC <= lim.socFloor() || dischargeBlocked { lower = 0 } - if chargeBlocked { + if chargeBlocked || r.SoC != nil && *r.SoC >= lim.socCeiling() { upper = 0 } return lower, upper