From 280420c95fed366114f8d978c77922186f744bee Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 25 Nov 2026 08:36:40 +0100 Subject: [PATCH 1/2] fix(battery): plan and charge no higher than the battery's own ceiling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Pixii can stop charging at 90 % while the planner's ceiling is 95 %. The plan booked "90 → 95 %, 1.0 kWh" and dispatch ordered charge the battery never took (srcfl/device-drivers#175). Drivers now report the device's own ceiling as max_soc_fract on the battery reading, the `@srcful/data-models` name. Core takes the lower of it and the configured ceiling: - dispatch marks the battery full there, stops charge orders and resumes one point below, and the fuse bounds close the charge side; - the planner caps each battery's MaxEnergyWh at it and sets the fleet's SoCMax to the capacity-weighted result, so the Go DP and Energyplan plan to the same limit. A device ceiling at or below the SoC floor is ignored. A missing, zero or out-of-range value changes nothing. Refs srcfl/device-drivers#175 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --- .changeset/battery-device-soc-max.md | 9 ++ .../control/battery_device_soc_max_test.go | 89 ++++++++++++ go/internal/control/battery_full.go | 54 ++++++- go/internal/control/dispatch.go | 5 +- go/internal/mpc/device_soc_ceiling.go | 46 ++++++ go/internal/mpc/device_soc_ceiling_test.go | 134 ++++++++++++++++++ go/internal/mpc/service.go | 2 +- go/internal/telemetry/battery_soc_ceiling.go | 26 ++++ .../telemetry/battery_soc_ceiling_test.go | 29 ++++ 9 files changed, 390 insertions(+), 4 deletions(-) create mode 100644 .changeset/battery-device-soc-max.md create mode 100644 go/internal/control/battery_device_soc_max_test.go create mode 100644 go/internal/mpc/device_soc_ceiling.go create mode 100644 go/internal/mpc/device_soc_ceiling_test.go create mode 100644 go/internal/telemetry/battery_soc_ceiling.go create mode 100644 go/internal/telemetry/battery_soc_ceiling_test.go diff --git a/.changeset/battery-device-soc-max.md b/.changeset/battery-device-soc-max.md new file mode 100644 index 000000000..fd701fa49 --- /dev/null +++ b/.changeset/battery-device-soc-max.md @@ -0,0 +1,9 @@ +--- +"ftw": patch +--- + +Plan and charge a battery no higher than the charge level its own device +reports it will accept. A Pixii can stop at 90 % while the plan booked energy +up to 95 %, so dispatch ordered charge the battery never took. Drivers report +the limit as `max_soc_fract` (Pixii from driver 2.2.0). Core uses the lower of +it and the configured ceiling; a configured ceiling below it still applies. diff --git a/go/internal/control/battery_device_soc_max_test.go b/go/internal/control/battery_device_soc_max_test.go new file mode 100644 index 000000000..066e5784b --- /dev/null +++ b/go/internal/control/battery_device_soc_max_test.go @@ -0,0 +1,89 @@ +package control + +import ( + "encoding/json" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// A Pixii stops charging at its own ceiling, 90 % on the site in +// srcfl/device-drivers#175, while Core had no soc_max configured. The driver +// reports that ceiling as max_soc_fract; dispatch stops charge there too. +func deviceCappedBatterySite(soc float64, data string) (*telemetry.Store, *State, map[string]float64) { + tel, st, capacities := fullBatterySite(soc, 0) + tel.Update("battery", telemetry.DerBattery, 0, &soc, json.RawMessage(data)) + st.PlanTarget = func(time.Time) (string, float64, string, bool) { + return string(ModeCharge), 2000, "charge", true + } + return tel, st, capacities +} + +func TestDeviceSoCMaxStopsChargingWithoutConfiguredCeiling(t *testing.T) { + for _, mode := range AllModes() { + t.Run(string(mode), func(t *testing.T) { + tel, st, capacities := deviceCappedBatterySite(.9, `{"max_soc_fract":0.9}`) + st.Mode = mode + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW > 0 || !st.BatteryChargePaused("battery") { + t.Fatalf("device ceiling of 90%% did not stop charging: %+v", got) + } + if resume := st.BatteryChargeResumeSoC("battery"); resume < .889 || resume > .891 { + t.Fatalf("resume level = %v, want 0.89 under the device ceiling", resume) + } + }) + } +} + +func TestDeviceSoCMaxAbsentOrHigherKeepsConfiguredCeiling(t *testing.T) { + for _, data := range []string{`{}`, `{"max_soc_fract":0}`, `{"max_soc_fract":90}`, `{"max_soc_fract":1}`} { + tel, st, capacities := deviceCappedBatterySite(.9, data) + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW <= 0 || st.BatteryChargePaused("battery") { + t.Fatalf("%s stopped charging at 90%% with no ceiling below it: %+v", data, got) + } + } + // The configured ceiling still applies when it is the lower one. + tel, st, capacities := deviceCappedBatterySite(.86, `{"max_soc_fract":0.95}`) + st.DriverLimits = map[string]PowerLimits{"battery": {SoCMax: .85}} + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW > 0 || !st.BatteryChargePaused("battery") { + t.Fatalf("a higher device ceiling lifted the configured 85%%: %+v", got) + } +} + +func TestDeviceSoCMaxFollowsTheLatestReading(t *testing.T) { + tel, st, capacities := deviceCappedBatterySite(.9, `{"max_soc_fract":0.9}`) + ComputeDispatch(tel, st, capacities, 13800) + if !st.BatteryChargePaused("battery") { + t.Fatal("device ceiling did not pause charging") + } + // The owner raises the Pixii's limit; the next reading carries it. + tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.9), json.RawMessage(`{"max_soc_fract":0.95}`)) + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW <= 0 || st.BatteryChargePaused("battery") { + t.Fatalf("raising the device ceiling did not release the stop: %+v", got) + } + // A driver that stops reporting the ceiling falls back to the configured one. + tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.95), json.RawMessage(`{"max_soc_fract":0.95}`)) + ComputeDispatch(tel, st, capacities, 13800) + tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.95), json.RawMessage(`{}`)) + got = ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW <= 0 { + t.Fatalf("a ceiling the driver no longer reports still stops charging: %+v", got) + } +} + +func TestDeviceSoCMaxClosesTheFuseChargeBound(t *testing.T) { + soc := .9 + r := &telemetry.DerReading{SoC: &soc, Data: json.RawMessage(`{"max_soc_fract":0.9}`)} + lim := PowerLimits{MaxChargeW: 5000, MaxDischargeW: 5000} + if lower, upper := fuseTargetBounds(r, lim); upper != 0 || lower != -5000 { + t.Fatalf("bounds at the device ceiling = %v..%v, want -5000..0", lower, upper) + } + r.Data = json.RawMessage(`{}`) + if _, upper := fuseTargetBounds(r, lim); upper != 5000 { + t.Fatalf("charge bound without a device ceiling = %v, want 5000", upper) + } +} diff --git a/go/internal/control/battery_full.go b/go/internal/control/battery_full.go index f36dc75de..d193da355 100644 --- a/go/internal/control/battery_full.go +++ b/go/internal/control/battery_full.go @@ -12,7 +12,30 @@ 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) + return math.Max(0, s.chargeCeiling(driver)-batteryChargeHysteresisSoC) +} + +// chargeCeiling is the lower of the configured ceiling and the one the +// battery's own device last reported (telemetry.BatterySoCCeiling). A Pixii +// stops charging at its own limit, so an order above it goes undelivered. +func (s *State) chargeCeiling(driver string) float64 { + ceiling := s.DriverLimits[driver].socCeiling() + if device, ok := s.batteryDeviceSoCMax[driver]; ok && device < ceiling { + return device + } + return ceiling +} + +// readingChargeCeiling is chargeCeiling for a caller that holds the reading. +func readingChargeCeiling(r *telemetry.DerReading, lim PowerLimits) float64 { + ceiling := lim.socCeiling() + if r == nil { + return ceiling + } + if device, ok := telemetry.BatterySoCCeiling(r.Data); ok && device < ceiling { + return device + } + return ceiling } // BatteryChargePaused reports the dispatcher's full-battery stop. Callers use @@ -33,6 +56,7 @@ func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[s delete(s.batteryChargeFull, name) } } + s.updateBatteryDeviceSoCMax(store, capacities) for name := range capacities { r := store.Get(name, telemetry.DerBattery) h := store.DriverHealth(name) @@ -44,7 +68,7 @@ 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 >= s.DriverLimits[name].socCeiling() { + if soc >= s.chargeCeiling(name) { s.batteryChargeFull[name] = true } else if soc <= s.BatteryChargeResumeSoC(name) { delete(s.batteryChargeFull, name) @@ -52,6 +76,32 @@ func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[s } } +// updateBatteryDeviceSoCMax keeps the charge ceiling each battery's device +// reports in its latest reading. A reading without one clears it, so a driver +// that stops reporting falls back to the configured ceiling. +func (s *State) updateBatteryDeviceSoCMax(store *telemetry.Store, capacities map[string]float64) { + if s.batteryDeviceSoCMax == nil { + s.batteryDeviceSoCMax = map[string]float64{} + } + for name := range s.batteryDeviceSoCMax { + if _, ok := capacities[name]; !ok { + delete(s.batteryDeviceSoCMax, name) + } + } + for name := range capacities { + r := store.Get(name, telemetry.DerBattery) + if r == nil { + delete(s.batteryDeviceSoCMax, name) + continue + } + if device, ok := telemetry.BatterySoCCeiling(r.Data); ok { + s.batteryDeviceSoCMax[name] = device + } else { + delete(s.batteryDeviceSoCMax, name) + } + } +} + func (s *State) floorFullBatteryCharge(targets []DispatchTarget) []DispatchTarget { for i := range targets { if targets[i].TargetW > 0 && s.BatteryChargePaused(targets[i].Driver) { diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 83a2412e0..7347d5b1b 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -466,6 +466,9 @@ type State struct { LastDispatch *time.Time PrevTargets map[string]float64 batteryChargeFull map[string]bool + // batteryDeviceSoCMax is the charge ceiling each battery's device last + // reported (max_soc_fract). See chargeCeiling. + batteryDeviceSoCMax map[string]float64 // clock is nil in production. Tests may set it to keep a dispatch // scenario on one instant even when the test runner is delayed. @@ -4863,7 +4866,7 @@ func fuseTargetBounds(r *telemetry.DerReading, lim PowerLimits) (lower, upper fl if r.SoC == nil || *r.SoC <= lim.socFloor() || dischargeBlocked { lower = 0 } - if chargeBlocked || r.SoC != nil && *r.SoC >= lim.socCeiling() { + if chargeBlocked || r.SoC != nil && *r.SoC >= readingChargeCeiling(r, lim) { upper = 0 } return lower, upper diff --git a/go/internal/mpc/device_soc_ceiling.go b/go/internal/mpc/device_soc_ceiling.go new file mode 100644 index 000000000..3a5599dd2 --- /dev/null +++ b/go/internal/mpc/device_soc_ceiling.go @@ -0,0 +1,46 @@ +package mpc + +import ( + "log/slog" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// withDeviceSoCCeilings plans each battery no higher than the charge level +// its own device reports it will accept (telemetry.BatterySoCCeiling). A +// Pixii stops charging at its own limit, 90 % on the site in +// srcfl/device-drivers#175, while the plan booked energy up to the planner's +// 95 %. The fleet's SoCMax becomes the capacity-weighted ceiling, so the Go +// DP and Energyplan plan to the same limit and the storage totals still +// match. A device ceiling at or below the planner's SoC floor cannot be +// planned with and is ignored; dispatch still stops charge at it. +func withDeviceSoCCeilings(p Params, tele *telemetry.Store) Params { + if tele == nil || len(p.Storages) == 0 || p.CapacityWh <= 0 { + return p + } + storages := append([]StorageAssetSpec(nil), p.Storages...) + lowered := false + var maxWh float64 + for i := range storages { + storage := &storages[i] + if r := tele.Get(storage.ID, telemetry.DerBattery); r != nil { + if ceiling, ok := telemetry.BatterySoCCeiling(r.Data); ok { + switch wh := storage.CapacityWh * ceiling; { + case ceiling <= p.SoCMin: + slog.Warn("mpc: ignoring a battery's own charge ceiling at or below the planner's SoC floor", + "battery", storage.ID, "device_soc_max", ceiling, "soc_min", p.SoCMin) + case wh < storage.MaxEnergyWh: + storage.MaxEnergyWh = wh + lowered = true + } + } + } + maxWh += storage.MaxEnergyWh + } + if !lowered { + return p + } + p.Storages = storages + p.SoCMax = maxWh / p.CapacityWh + return p +} diff --git a/go/internal/mpc/device_soc_ceiling_test.go b/go/internal/mpc/device_soc_ceiling_test.go new file mode 100644 index 000000000..09eac8ee6 --- /dev/null +++ b/go/internal/mpc/device_soc_ceiling_test.go @@ -0,0 +1,134 @@ +package mpc + +import ( + "context" + "encoding/json" + "math" + "path/filepath" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/state" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// A Pixii Home 20 kWh stops charging at 90 % while the planner's ceiling is +// 95 %. The plan said "90 → 95 %, 1.0 kWh" and dispatch ordered charge the +// battery never took (srcfl/device-drivers#175). The driver now reports the +// device's ceiling as max_soc_fract. + +func TestOnlineFleetParamsPlansEachBatteryToItsDeviceCeiling(t *testing.T) { + tel := telemetry.NewStore() + socPixii, socOther := .9, .5 + tel.Update("pixii", telemetry.DerBattery, 0, &socPixii, json.RawMessage(`{"max_soc_fract":0.9}`)) + tel.DriverHealthMut("pixii").RecordSuccess() + tel.Update("other", telemetry.DerBattery, 0, &socOther, json.RawMessage(`{"max_soc_fract":0.98}`)) + tel.DriverHealthMut("other").RecordSuccess() + + s := &Service{Tele: tel} + p, ok := s.onlineFleetParams(Params{InitialSoC: .5, SoCMin: .1, SoCMax: .95, ChargeEfficiency: .95, DischargeEfficiency: .95}, []BatteryFleetMember{ + {Driver: "pixii", CapacityWh: 20000, MaxChargeW: 5000, MaxDischargeW: 5000}, + {Driver: "other", CapacityWh: 10000, MaxChargeW: 5000, MaxDischargeW: 5000}, + }, 0) + if !ok { + t.Fatal("onlineFleetParams returned ok=false") + } + if got := p.Storages[0].MaxEnergyWh; math.Abs(got-18000) > 1e-6 { + t.Fatalf("pixii MaxEnergyWh = %.1f, want 18000 at its own 90%%", got) + } + if got := p.Storages[1].MaxEnergyWh; math.Abs(got-9500) > 1e-6 { + t.Fatalf("other MaxEnergyWh = %.1f, want the planner's 95%%: a higher device ceiling never lifts it", got) + } + // (18 + 9.5) / 30 kWh. + if want := 27500.0 / 30000; math.Abs(p.SoCMax-want) > 1e-9 { + t.Fatalf("fleet SoCMax = %.6f, want %.6f", p.SoCMax, want) + } + if err := validateStorageSpecs(p, map[string]string{}); err != nil { + t.Fatalf("storages no longer add up to the fleet: %v", err) + } +} + +func TestOnlineFleetParamsIgnoresDeviceCeilingAtTheFloor(t *testing.T) { + tel := telemetry.NewStore() + soc := .1 + tel.Update("pixii", telemetry.DerBattery, 0, &soc, json.RawMessage(`{"max_soc_fract":0.1}`)) + tel.DriverHealthMut("pixii").RecordSuccess() + s := &Service{Tele: tel} + p, ok := s.onlineFleetParams(Params{SoCMin: .1, SoCMax: .95}, []BatteryFleetMember{ + {Driver: "pixii", CapacityWh: 20000, MaxChargeW: 5000, MaxDischargeW: 5000}, + }, 0) + if !ok || p.SoCMax != .95 || p.Storages[0].MaxEnergyWh != 19000 { + t.Fatalf("a device ceiling at the SoC floor changed the plan's window: ok=%v SoCMax=%v storage=%+v", + ok, p.SoCMax, p.Storages[0]) + } +} + +// deviceCeilingPlan replans the field case: a 20 kWh battery at 90 % with +// cheap hours first and dear hours after, the prices that made the plan book +// a top-up to 95 %. +func deviceCeilingPlan(t *testing.T, data string) Plan { + t.Helper() + start := time.Date(2026, 11, 24, 1, 0, 0, 0, stockholm(t)) + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + prices := make([]state.PricePoint, 32) + for i := range prices { + spot := 10.0 + if i >= 8 { + spot = 300 + } + prices[i] = state.PricePoint{ + Zone: "SE3", SlotTsMs: start.Add(time.Duration(i) * 15 * time.Minute).UnixMilli(), SlotLenMin: 15, + SpotOreKwh: spot, TotalOreKwh: spot + 60, Source: "test", FetchedAtMs: start.UnixMilli(), + } + } + if err := st.SavePrices(prices); err != nil { + t.Fatal(err) + } + svc := New(st, nil, "SE3", Params{ + Mode: ModeArbitrage, SoCLevels: 101, ActionLevels: 21, + CapacityWh: 20000, InitialSoC: .9, SoCMin: .1, SoCMax: .95, + MaxChargeW: 5000, MaxDischargeW: 5000, ChargeEfficiency: .95, DischargeEfficiency: .95, + }) + svc.Horizon = 8 * time.Hour + svc.BaseLoad = 500 + svc.now = func() time.Time { return start.Add(30 * time.Second) } + tel := telemetry.NewStore() + soc := .9 + tel.Update("pixii", telemetry.DerBattery, 0, &soc, json.RawMessage(data)) + tel.DriverHealthMut("pixii").RecordSuccess() + svc.Tele = tel + svc.UpdateBatteryFleet([]BatteryFleetMember{{Driver: "pixii", CapacityWh: 20000, MaxChargeW: 5000, MaxDischargeW: 5000}}, 20000, 5000, 5000) + svc.UpdateSiteEconomics(SiteEconomics{FuseMaxW: 13800, Timezone: "Europe/Stockholm"}) + if svc.Replan(context.Background()) == nil { + t.Fatalf("no plan published: %+v", svc.PlanSnapshot()) + } + return *svc.PlanSnapshot().Plan +} + +func TestPlanNeverTargetsAboveTheDeviceCeiling(t *testing.T) { + highest := func(plan Plan) float64 { + top := 0.0 + for _, a := range plan.Actions { + top = math.Max(top, a.SoC) + } + return top + } + // Without the device's ceiling the plan tops the battery up to 95 %, + // which is the field finding. + if top := highest(deviceCeilingPlan(t, `{}`)); top < .93 { + t.Fatalf("control case peaks at %.3f; the prices no longer make the plan charge", top) + } + plan := deviceCeilingPlan(t, `{"max_soc_fract":0.9}`) + if top := highest(plan); top > .9+1e-9 { + t.Fatalf("plan targets %.3f above the device's 90%% ceiling", top) + } + for _, a := range plan.Actions { + if a.SoC >= .9-1e-9 && a.BatteryW > IdleGateThresholdW { + t.Fatalf("plan charges %.0f W at the device ceiling: %+v", a.BatteryW, a) + } + } +} diff --git a/go/internal/mpc/service.go b/go/internal/mpc/service.go index abef59fba..93f89c897 100644 --- a/go/internal/mpc/service.go +++ b/go/internal/mpc/service.go @@ -2905,5 +2905,5 @@ func (s *Service) onlineFleetParams(p Params, fleet []BatteryFleetMember, fuseMa storages[i].MaxDischargeW *= dischargeScale } p.Storages = storages - return p, true + return withDeviceSoCCeilings(p, s.Tele), true } diff --git a/go/internal/telemetry/battery_soc_ceiling.go b/go/internal/telemetry/battery_soc_ceiling.go new file mode 100644 index 000000000..2a8fc9a57 --- /dev/null +++ b/go/internal/telemetry/battery_soc_ceiling.go @@ -0,0 +1,26 @@ +package telemetry + +import "encoding/json" + +// BatterySoCCeiling is the highest state of charge, 0..1, that a battery's +// own device reports it will charge to. Drivers send it as max_soc_fract on +// the battery reading, the name @srcful/data-models gives a battery's own +// maximum SoC. A Pixii can stop at 90 % while Core plans to 95 % +// (srcfl/device-drivers#175). A missing, non-finite, zero or out-of-range +// value reports false. +func BatterySoCCeiling(data json.RawMessage) (float64, bool) { + if len(data) == 0 { + return 0, false + } + var d struct { + MaxSoCFract *float64 `json:"max_soc_fract"` + } + if json.Unmarshal(data, &d) != nil || d.MaxSoCFract == nil { + return 0, false + } + v := *d.MaxSoCFract + if !finite(v) || v <= 0 || v > 1 { + return 0, false + } + return v, true +} diff --git a/go/internal/telemetry/battery_soc_ceiling_test.go b/go/internal/telemetry/battery_soc_ceiling_test.go new file mode 100644 index 000000000..70d046a1a --- /dev/null +++ b/go/internal/telemetry/battery_soc_ceiling_test.go @@ -0,0 +1,29 @@ +package telemetry + +import ( + "encoding/json" + "testing" +) + +func TestBatterySoCCeiling(t *testing.T) { + for _, tc := range []struct { + data string + want float64 + ok bool + }{ + {`{"max_soc_fract":0.9}`, 0.9, true}, + {`{"max_soc_fract":1}`, 1, true}, + {`{"max_soc_fract":0}`, 0, false}, + {`{"max_soc_fract":-0.1}`, 0, false}, + {`{"max_soc_fract":90}`, 0, false}, + {`{"max_soc_fract":null}`, 0, false}, + {`{"soc":0.9}`, 0, false}, + {`not json`, 0, false}, + {``, 0, false}, + } { + got, ok := BatterySoCCeiling(json.RawMessage(tc.data)) + if got != tc.want || ok != tc.ok { + t.Errorf("BatterySoCCeiling(%s) = %v, %v; want %v, %v", tc.data, got, ok, tc.want, tc.ok) + } + } +} From d76b4c2da3512402e10802adc94b8fb18c7e7543 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 25 Nov 2026 08:52:26 +0100 Subject: [PATCH 2/2] fix(battery): guard and hold the battery's own charge ceiling Review findings on the device ceiling: - Dispatch used any reported ceiling, so max_soc_fract 0.05 with a floor of 0.10 marked a half-empty battery full. Dispatch now ignores a ceiling at or below the battery's SoC floor, as the planner does, and logs it once. - Telemetry ignores a ceiling below 50 % and logs it once: real ceilings sit around 80-100 %, and a misread register must not stop charging. - One reading without the ceiling, from a failed limit read, released a full battery for a poll. The store now carries the ceiling on the reading, like SoC, for up to ten minutes (the Pixii driver retries a missed register after five) and drops it with a stale reading or a removed driver. - A test pins that the planner changes only MaxEnergyWh on a storage, so per-battery limits added beside it pass through. Refs srcfl/device-drivers#175 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --- .changeset/battery-device-soc-max.md | 4 +- .../control/battery_device_soc_max_test.go | 103 ++++++++++++++++-- go/internal/control/battery_full.go | 65 +++++++---- go/internal/control/dispatch.go | 6 +- go/internal/mpc/device_soc_ceiling.go | 33 +++--- go/internal/mpc/device_soc_ceiling_test.go | 57 ++++++++-- go/internal/telemetry/battery_soc_ceiling.go | 69 ++++++++++-- .../telemetry/battery_soc_ceiling_test.go | 84 +++++++++++++- go/internal/telemetry/store.go | 14 +++ 9 files changed, 357 insertions(+), 78 deletions(-) diff --git a/.changeset/battery-device-soc-max.md b/.changeset/battery-device-soc-max.md index fd701fa49..6426949a3 100644 --- a/.changeset/battery-device-soc-max.md +++ b/.changeset/battery-device-soc-max.md @@ -6,4 +6,6 @@ Plan and charge a battery no higher than the charge level its own device reports it will accept. A Pixii can stop at 90 % while the plan booked energy up to 95 %, so dispatch ordered charge the battery never took. Drivers report the limit as `max_soc_fract` (Pixii from driver 2.2.0). Core uses the lower of -it and the configured ceiling; a configured ceiling below it still applies. +it and the configured ceiling. It ignores a device limit below 50 % or at or +below the battery's SoC floor, and keeps the last one for up to ten minutes +when a reading leaves it out. diff --git a/go/internal/control/battery_device_soc_max_test.go b/go/internal/control/battery_device_soc_max_test.go index 066e5784b..972b9fc3e 100644 --- a/go/internal/control/battery_device_soc_max_test.go +++ b/go/internal/control/battery_device_soc_max_test.go @@ -3,6 +3,7 @@ package control import ( "encoding/json" "testing" + "testing/synctest" "time" "github.com/srcfl/ftw/go/internal/telemetry" @@ -20,6 +21,13 @@ func deviceCappedBatterySite(soc float64, data string) (*telemetry.Store, *State return tel, st, capacities } +func updateDeviceBattery(tel *telemetry.Store, soc float64, data string) { + tel.Update("battery", telemetry.DerBattery, 0, &soc, json.RawMessage(data)) + tel.RecordDriverSuccess("battery") + tel.Update("ferroamp", telemetry.DerMeter, -1000, nil, nil) + tel.RecordDriverSuccess("ferroamp") +} + func TestDeviceSoCMaxStopsChargingWithoutConfiguredCeiling(t *testing.T) { for _, mode := range AllModes() { t.Run(string(mode), func(t *testing.T) { @@ -53,6 +61,85 @@ func TestDeviceSoCMaxAbsentOrHigherKeepsConfiguredCeiling(t *testing.T) { } } +// A ceiling at or below the SoC floor, or below the trusted minimum, must +// not mark a half-empty battery full. +func TestDeviceSoCMaxAtOrBelowTheFloorIsNotUsed(t *testing.T) { + for _, tc := range []struct { + name string + soc float64 + data string + floor float64 + }{ + {"below the trusted minimum", .5, `{"max_soc_fract":0.05}`, .10}, + {"at or below the battery's floor", .58, `{"max_soc_fract":0.55}`, .60}, + } { + t.Run(tc.name, func(t *testing.T) { + tel, st, capacities := deviceCappedBatterySite(tc.soc, tc.data) + st.DriverLimits = map[string]PowerLimits{"battery": {SoCMin: tc.floor, MaxChargeW: 5000}} + for range 2 { + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW <= 0 || st.BatteryChargePaused("battery") { + t.Fatalf("an unusable device ceiling stopped charging at %.0f%%: %+v", tc.soc*100, got) + } + } + if c := st.chargeCeiling("battery"); c != 1 { + t.Fatalf("charge ceiling = %v, want the configured 1", c) + } + r := tel.Get("battery", telemetry.DerBattery) + if _, upper := fuseTargetBounds(r, st.DriverLimits["battery"]); upper != 5000 { + t.Fatalf("fuse charge bound = %v, want 5000", upper) + } + }) + } + // The floor case is logged once per value, not on every tick. + tel, st, capacities := deviceCappedBatterySite(.58, `{"max_soc_fract":0.55}`) + st.DriverLimits = map[string]PowerLimits{"battery": {SoCMin: .60}} + ComputeDispatch(tel, st, capacities, 13800) + if got := st.batteryDeviceSoCMax["battery"].belowFloor; got != .55 { + t.Fatalf("below-floor ceiling recorded for its one log = %v, want 0.55", got) + } +} + +// One reading without the ceiling, from a limit read that failed, must not +// release a full battery. The ceiling holds for a bounded time. +func TestDeviceSoCMaxHoldsAcrossAMissedLimitRead(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tel, st, capacities := deviceCappedBatterySite(.9, `{"max_soc_fract":0.9}`) + ComputeDispatch(tel, st, capacities, 13800) + if !st.BatteryChargePaused("battery") { + t.Fatal("device ceiling did not pause charging") + } + updateDeviceBattery(tel, .9, `{}`) + got := ComputeDispatch(tel, st, capacities, 13800) + if len(got) != 1 || got[0].TargetW > 0 || !st.BatteryChargePaused("battery") { + t.Fatalf("one reading without the ceiling released the stop: %+v", got) + } + for range 11 { + time.Sleep(time.Minute) + updateDeviceBattery(tel, .9, `{}`) + } + ComputeDispatch(tel, st, capacities, 13800) + if st.BatteryChargePaused("battery") || st.chargeCeiling("battery") != 1 { + t.Fatalf("a ceiling unreported for 11 minutes still applies: %v", st.chargeCeiling("battery")) + } + }) +} + +func TestDeviceSoCMaxDropsWithAStaleReading(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tel, st, capacities := deviceCappedBatterySite(.9, `{"max_soc_fract":0.9}`) + st.updateBatteryChargeFull(tel, capacities) + if st.chargeCeiling("battery") != .9 { + t.Fatalf("charge ceiling = %v, want 0.9", st.chargeCeiling("battery")) + } + time.Sleep(telemetry.BatterySoCMaxAge + time.Second) + st.updateBatteryChargeFull(tel, capacities) + if c := st.chargeCeiling("battery"); c != 1 { + t.Fatalf("a stale reading kept the device ceiling: %v", c) + } + }) +} + func TestDeviceSoCMaxFollowsTheLatestReading(t *testing.T) { tel, st, capacities := deviceCappedBatterySite(.9, `{"max_soc_fract":0.9}`) ComputeDispatch(tel, st, capacities, 13800) @@ -60,29 +147,21 @@ func TestDeviceSoCMaxFollowsTheLatestReading(t *testing.T) { t.Fatal("device ceiling did not pause charging") } // The owner raises the Pixii's limit; the next reading carries it. - tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.9), json.RawMessage(`{"max_soc_fract":0.95}`)) + updateDeviceBattery(tel, .9, `{"max_soc_fract":0.95}`) got := ComputeDispatch(tel, st, capacities, 13800) if len(got) != 1 || got[0].TargetW <= 0 || st.BatteryChargePaused("battery") { t.Fatalf("raising the device ceiling did not release the stop: %+v", got) } - // A driver that stops reporting the ceiling falls back to the configured one. - tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.95), json.RawMessage(`{"max_soc_fract":0.95}`)) - ComputeDispatch(tel, st, capacities, 13800) - tel.Update("battery", telemetry.DerBattery, 0, ptrF64(.95), json.RawMessage(`{}`)) - got = ComputeDispatch(tel, st, capacities, 13800) - if len(got) != 1 || got[0].TargetW <= 0 { - t.Fatalf("a ceiling the driver no longer reports still stops charging: %+v", got) - } } func TestDeviceSoCMaxClosesTheFuseChargeBound(t *testing.T) { - soc := .9 - r := &telemetry.DerReading{SoC: &soc, Data: json.RawMessage(`{"max_soc_fract":0.9}`)} + soc, ceiling := .9, .9 + r := &telemetry.DerReading{SoC: &soc, SoCCeiling: &ceiling} lim := PowerLimits{MaxChargeW: 5000, MaxDischargeW: 5000} if lower, upper := fuseTargetBounds(r, lim); upper != 0 || lower != -5000 { t.Fatalf("bounds at the device ceiling = %v..%v, want -5000..0", lower, upper) } - r.Data = json.RawMessage(`{}`) + r.SoCCeiling = nil if _, upper := fuseTargetBounds(r, lim); upper != 5000 { t.Fatalf("charge bound without a device ceiling = %v, want 5000", upper) } diff --git a/go/internal/control/battery_full.go b/go/internal/control/battery_full.go index d193da355..927478584 100644 --- a/go/internal/control/battery_full.go +++ b/go/internal/control/battery_full.go @@ -1,6 +1,7 @@ package control import ( + "log/slog" "math" "github.com/srcfl/ftw/go/internal/telemetry" @@ -16,28 +17,36 @@ func (s *State) BatteryChargeResumeSoC(driver string) float64 { } // chargeCeiling is the lower of the configured ceiling and the one the -// battery's own device last reported (telemetry.BatterySoCCeiling). A Pixii -// stops charging at its own limit, so an order above it goes undelivered. +// battery's own device reports (telemetry.DerReading.SoCCeilingNow), as the +// last control tick saw it. A Pixii stops charging at its own limit, so an +// order above it goes undelivered. func (s *State) chargeCeiling(driver string) float64 { ceiling := s.DriverLimits[driver].socCeiling() - if device, ok := s.batteryDeviceSoCMax[driver]; ok && device < ceiling { + if device := s.batteryDeviceSoCMax[driver].value; device > 0 && device < ceiling { return device } return ceiling } -// readingChargeCeiling is chargeCeiling for a caller that holds the reading. +// readingChargeCeiling is chargeCeiling for a caller that holds an online +// battery's reading. func readingChargeCeiling(r *telemetry.DerReading, lim PowerLimits) float64 { ceiling := lim.socCeiling() - if r == nil { - return ceiling - } - if device, ok := telemetry.BatterySoCCeiling(r.Data); ok && device < ceiling { - return device + if r != nil && r.SoCCeiling != nil { + if device := *r.SoCCeiling; usableDeviceCeiling(device, lim) && device < ceiling { + return device + } } return ceiling } +// usableDeviceCeiling: a device ceiling at or below the battery's SoC floor +// leaves no band to charge or discharge in, so it is not used. Telemetry has +// already dropped one below telemetry.MinBatterySoCCeiling. +func usableDeviceCeiling(device float64, lim PowerLimits) bool { + return device > lim.socFloor() +} + // BatteryChargePaused reports the dispatcher's full-battery stop. Callers use // the same lock as ComputeDispatch; this state is local to the running device. func (s *State) BatteryChargePaused(driver string) bool { @@ -76,29 +85,41 @@ func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[s } } -// updateBatteryDeviceSoCMax keeps the charge ceiling each battery's device -// reports in its latest reading. A reading without one clears it, so a driver -// that stops reporting falls back to the configured ceiling. +// deviceSoCMax is the device ceiling a control tick saw for one battery. +type deviceSoCMax struct { + value float64 // 0 when none applies + belowFloor float64 // last ceiling logged as at or below the SoC floor +} + +// updateBatteryDeviceSoCMax takes each battery's own charge ceiling from its +// reading. Telemetry holds a ceiling across a few readings without it and +// drops it with a stale reading; here it must also sit above the battery's +// SoC floor, or it is logged once and not used. func (s *State) updateBatteryDeviceSoCMax(store *telemetry.Store, capacities map[string]float64) { if s.batteryDeviceSoCMax == nil { - s.batteryDeviceSoCMax = map[string]float64{} + s.batteryDeviceSoCMax = map[string]deviceSoCMax{} } for name := range s.batteryDeviceSoCMax { if _, ok := capacities[name]; !ok { delete(s.batteryDeviceSoCMax, name) } } + now := s.now() for name := range capacities { - r := store.Get(name, telemetry.DerBattery) - if r == nil { - delete(s.batteryDeviceSoCMax, name) - continue - } - if device, ok := telemetry.BatterySoCCeiling(r.Data); ok { - s.batteryDeviceSoCMax[name] = device - } else { - delete(s.batteryDeviceSoCMax, name) + seen := s.batteryDeviceSoCMax[name] + seen.value = 0 + if device, ok := store.Get(name, telemetry.DerBattery).SoCCeilingNow(now); ok { + lim := s.DriverLimits[name] + switch { + case usableDeviceCeiling(device, lim): + seen.value, seen.belowFloor = device, 0 + case seen.belowFloor != device: + slog.Warn("control: ignoring a battery's own charge ceiling at or below its SoC floor", + "driver", name, "max_soc_fract", device, "soc_floor", lim.socFloor()) + seen.belowFloor = device + } } + s.batteryDeviceSoCMax[name] = seen } } diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 7347d5b1b..938d3d162 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -466,9 +466,9 @@ type State struct { LastDispatch *time.Time PrevTargets map[string]float64 batteryChargeFull map[string]bool - // batteryDeviceSoCMax is the charge ceiling each battery's device last - // reported (max_soc_fract). See chargeCeiling. - batteryDeviceSoCMax map[string]float64 + // batteryDeviceSoCMax is the charge ceiling each battery's device + // reports (max_soc_fract), as the last tick saw it. See chargeCeiling. + batteryDeviceSoCMax map[string]deviceSoCMax // clock is nil in production. Tests may set it to keep a dispatch // scenario on one instant even when the test runner is delayed. diff --git a/go/internal/mpc/device_soc_ceiling.go b/go/internal/mpc/device_soc_ceiling.go index 3a5599dd2..8766074de 100644 --- a/go/internal/mpc/device_soc_ceiling.go +++ b/go/internal/mpc/device_soc_ceiling.go @@ -1,39 +1,36 @@ package mpc import ( - "log/slog" + "time" "github.com/srcfl/ftw/go/internal/telemetry" ) // withDeviceSoCCeilings plans each battery no higher than the charge level -// its own device reports it will accept (telemetry.BatterySoCCeiling). A -// Pixii stops charging at its own limit, 90 % on the site in +// its own device reports it will accept (telemetry.DerReading.SoCCeilingNow). +// A Pixii stops charging at its own limit, 90 % on the site in // srcfl/device-drivers#175, while the plan booked energy up to the planner's -// 95 %. The fleet's SoCMax becomes the capacity-weighted ceiling, so the Go -// DP and Energyplan plan to the same limit and the storage totals still -// match. A device ceiling at or below the planner's SoC floor cannot be -// planned with and is ignored; dispatch still stops charge at it. +// 95 %. Only MaxEnergyWh changes; the fleet's SoCMax becomes the +// capacity-weighted ceiling, so the Go DP and Energyplan plan to the same +// limit and the storage totals still match. +// +// Telemetry drops a ceiling below telemetry.MinBatterySoCCeiling. One at or +// below the planner's SoC floor leaves nothing to plan in and is not used; +// dispatch logs that case. func withDeviceSoCCeilings(p Params, tele *telemetry.Store) Params { if tele == nil || len(p.Storages) == 0 || p.CapacityWh <= 0 { return p } + now := time.Now() storages := append([]StorageAssetSpec(nil), p.Storages...) lowered := false var maxWh float64 for i := range storages { storage := &storages[i] - if r := tele.Get(storage.ID, telemetry.DerBattery); r != nil { - if ceiling, ok := telemetry.BatterySoCCeiling(r.Data); ok { - switch wh := storage.CapacityWh * ceiling; { - case ceiling <= p.SoCMin: - slog.Warn("mpc: ignoring a battery's own charge ceiling at or below the planner's SoC floor", - "battery", storage.ID, "device_soc_max", ceiling, "soc_min", p.SoCMin) - case wh < storage.MaxEnergyWh: - storage.MaxEnergyWh = wh - lowered = true - } - } + ceiling, ok := tele.Get(storage.ID, telemetry.DerBattery).SoCCeilingNow(now) + if wh := storage.CapacityWh * ceiling; ok && ceiling > p.SoCMin && wh < storage.MaxEnergyWh { + storage.MaxEnergyWh = wh + lowered = true } maxWh += storage.MaxEnergyWh } diff --git a/go/internal/mpc/device_soc_ceiling_test.go b/go/internal/mpc/device_soc_ceiling_test.go index 09eac8ee6..5258ded61 100644 --- a/go/internal/mpc/device_soc_ceiling_test.go +++ b/go/internal/mpc/device_soc_ceiling_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "math" "path/filepath" + "reflect" "testing" "time" @@ -48,18 +49,52 @@ func TestOnlineFleetParamsPlansEachBatteryToItsDeviceCeiling(t *testing.T) { } } -func TestOnlineFleetParamsIgnoresDeviceCeilingAtTheFloor(t *testing.T) { +func TestOnlineFleetParamsIgnoresUnusableDeviceCeilings(t *testing.T) { + for _, tc := range []struct { + name, data string + soc float64 + }{ + // Telemetry does not trust a ceiling below 50 %. + {"below the trusted minimum", `{"max_soc_fract":0.3}`, .7}, + // A ceiling at or below the floor leaves nothing to plan in. + {"at or below the SoC floor", `{"max_soc_fract":0.55}`, .7}, + } { + t.Run(tc.name, func(t *testing.T) { + tel := telemetry.NewStore() + tel.Update("pixii", telemetry.DerBattery, 0, &tc.soc, json.RawMessage(tc.data)) + tel.DriverHealthMut("pixii").RecordSuccess() + s := &Service{Tele: tel} + p, ok := s.onlineFleetParams(Params{SoCMin: .6, SoCMax: .95}, []BatteryFleetMember{ + {Driver: "pixii", CapacityWh: 20000, MaxChargeW: 5000, MaxDischargeW: 5000}, + }, 0) + if !ok || p.SoCMax != .95 || p.Storages[0].MaxEnergyWh != 19000 { + t.Fatalf("an unusable device ceiling changed the plan's window: ok=%v SoCMax=%v storage=%+v", + ok, p.SoCMax, p.Storages[0]) + } + }) + } +} + +// withDeviceSoCCeilings changes MaxEnergyWh and nothing else on a storage, so +// any per-battery limit added beside it (for example the per-slot limits in +// srcfl/ftw#2072) passes through unchanged. +func TestDeviceSoCCeilingsChangeOnlyMaxEnergy(t *testing.T) { tel := telemetry.NewStore() - soc := .1 - tel.Update("pixii", telemetry.DerBattery, 0, &soc, json.RawMessage(`{"max_soc_fract":0.1}`)) - tel.DriverHealthMut("pixii").RecordSuccess() - s := &Service{Tele: tel} - p, ok := s.onlineFleetParams(Params{SoCMin: .1, SoCMax: .95}, []BatteryFleetMember{ - {Driver: "pixii", CapacityWh: 20000, MaxChargeW: 5000, MaxDischargeW: 5000}, - }, 0) - if !ok || p.SoCMax != .95 || p.Storages[0].MaxEnergyWh != 19000 { - t.Fatalf("a device ceiling at the SoC floor changed the plan's window: ok=%v SoCMax=%v storage=%+v", - ok, p.SoCMax, p.Storages[0]) + soc := .5 + tel.Update("pixii", telemetry.DerBattery, 0, &soc, json.RawMessage(`{"max_soc_fract":0.9}`)) + storage := StorageAssetSpec{ + ID: "pixii", CapacityWh: 20000, InitialEnergyWh: 10000, MinEnergyWh: 2000, MaxEnergyWh: 19000, + MaxChargeW: 5000, MaxDischargeW: 4000, ChargeEfficiency: .95, DischargeEfficiency: .94, + } + p := Params{CapacityWh: 20000, InitialSoC: .5, SoCMin: .1, SoCMax: .95, Storages: []StorageAssetSpec{storage}} + got := withDeviceSoCCeilings(p, tel) + want := storage + want.MaxEnergyWh = 18000 + if !reflect.DeepEqual(got.Storages, []StorageAssetSpec{want}) { + t.Fatalf("storages = %+v, want only MaxEnergyWh lowered to %+v", got.Storages, want) + } + if p.Storages[0].MaxEnergyWh != 19000 { + t.Fatal("withDeviceSoCCeilings wrote through to the caller's storages") } } diff --git a/go/internal/telemetry/battery_soc_ceiling.go b/go/internal/telemetry/battery_soc_ceiling.go index 2a8fc9a57..20859b254 100644 --- a/go/internal/telemetry/battery_soc_ceiling.go +++ b/go/internal/telemetry/battery_soc_ceiling.go @@ -1,14 +1,42 @@ package telemetry -import "encoding/json" +import ( + "encoding/json" + "log/slog" + "time" +) -// BatterySoCCeiling is the highest state of charge, 0..1, that a battery's -// own device reports it will charge to. Drivers send it as max_soc_fract on -// the battery reading, the name @srcful/data-models gives a battery's own -// maximum SoC. A Pixii can stop at 90 % while Core plans to 95 % -// (srcfl/device-drivers#175). A missing, non-finite, zero or out-of-range -// value reports false. -func BatterySoCCeiling(data json.RawMessage) (float64, bool) { +// A battery's own charge ceiling is the highest state of charge its device +// reports it will charge to. Drivers send it as max_soc_fract on the battery +// reading, the name @srcful/data-models gives a battery's own maximum SoC. A +// Pixii can stop at 90 % while Core plans to 95 % (srcfl/device-drivers#175). + +// MinBatterySoCCeiling is the lowest device ceiling Core trusts. Real +// ceilings sit around 80-100 %; a misread register that says 30 % would +// otherwise stop all charging above 30 %. +const MinBatterySoCCeiling = 0.5 + +// BatterySoCCeilingHold is how long a ceiling outlives readings that no +// longer carry it. A limit register that fails a read leaves the ceiling out +// of that reading, and the Pixii driver retries a register that missed three +// polls only after five minutes. Dropping the ceiling at once would release +// a full battery for that time. +const BatterySoCCeilingHold = 10 * time.Minute + +// SoCCeilingNow is the battery's own charge ceiling, 0..1, while the reading +// is current (BatterySoCMaxAge) and the ceiling was reported within +// BatterySoCCeilingHold. +func (r *DerReading) SoCCeilingNow(now time.Time) (float64, bool) { + if r == nil || r.SoCCeiling == nil || + now.Sub(r.UpdatedAt) > BatterySoCMaxAge || now.Sub(r.SoCCeilingAt) > BatterySoCCeilingHold { + return 0, false + } + return *r.SoCCeiling, true +} + +// parseSoCCeiling reads max_soc_fract. A missing, non-finite, zero or +// out-of-range value reports false. +func parseSoCCeiling(data json.RawMessage) (float64, bool) { if len(data) == 0 { return 0, false } @@ -24,3 +52,28 @@ func BatterySoCCeiling(data json.RawMessage) (float64, bool) { } return v, true } + +// socCeilingFor is the ceiling a new battery reading carries: the one in its +// data, else the previous reading's while within BatterySoCCeilingHold. A +// value below MinBatterySoCCeiling is logged once and ignored. Caller holds +// s.mu. +func (s *Store) socCeilingFor(driver string, data json.RawMessage, prev *DerReading, now time.Time) (*float64, time.Time) { + if v, ok := parseSoCCeiling(data); ok { + if v >= MinBatterySoCCeiling { + delete(s.lowSoCCeilings, driver) + return &v, now + } + if logged, seen := s.lowSoCCeilings[driver]; !seen || logged != v { + if s.lowSoCCeilings == nil { + s.lowSoCCeilings = map[string]float64{} + } + s.lowSoCCeilings[driver] = v + slog.Warn("telemetry: ignoring a battery charge ceiling below the trusted minimum", + "driver", driver, "max_soc_fract", v, "min", MinBatterySoCCeiling) + } + } + if prev != nil && prev.SoCCeiling != nil && now.Sub(prev.SoCCeilingAt) <= BatterySoCCeilingHold { + return prev.SoCCeiling, prev.SoCCeilingAt + } + return nil, time.Time{} +} diff --git a/go/internal/telemetry/battery_soc_ceiling_test.go b/go/internal/telemetry/battery_soc_ceiling_test.go index 70d046a1a..673a4f583 100644 --- a/go/internal/telemetry/battery_soc_ceiling_test.go +++ b/go/internal/telemetry/battery_soc_ceiling_test.go @@ -3,9 +3,11 @@ package telemetry import ( "encoding/json" "testing" + "testing/synctest" + "time" ) -func TestBatterySoCCeiling(t *testing.T) { +func TestParseSoCCeiling(t *testing.T) { for _, tc := range []struct { data string want float64 @@ -21,9 +23,85 @@ func TestBatterySoCCeiling(t *testing.T) { {`not json`, 0, false}, {``, 0, false}, } { - got, ok := BatterySoCCeiling(json.RawMessage(tc.data)) + got, ok := parseSoCCeiling(json.RawMessage(tc.data)) if got != tc.want || ok != tc.ok { - t.Errorf("BatterySoCCeiling(%s) = %v, %v; want %v, %v", tc.data, got, ok, tc.want, tc.ok) + t.Errorf("parseSoCCeiling(%s) = %v, %v; want %v, %v", tc.data, got, ok, tc.want, tc.ok) } } } + +func batteryCeiling(s *Store) (float64, bool) { + return s.Get("pixii", DerBattery).SoCCeilingNow(time.Now()) +} + +func updateBattery(s *Store, data string) { + soc := .9 + s.Update("pixii", DerBattery, 0, &soc, json.RawMessage(data)) +} + +// One reading without the ceiling, from a limit register that missed a read, +// must not release a full battery. The ceiling holds for a bounded time. +func TestSoCCeilingHoldsAcrossReadingsWithoutIt(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := NewStore() + updateBattery(s, `{"max_soc_fract":0.9}`) + if c, ok := batteryCeiling(s); !ok || c != .9 { + t.Fatalf("ceiling = %v, %v; want 0.9", c, ok) + } + time.Sleep(BatterySoCCeilingHold - time.Second) + updateBattery(s, `{}`) + if c, ok := batteryCeiling(s); !ok || c != .9 { + t.Fatalf("ceiling after a reading without it = %v, %v; want the held 0.9", c, ok) + } + time.Sleep(2 * time.Second) + updateBattery(s, `{}`) + if c, ok := batteryCeiling(s); ok { + t.Fatalf("ceiling %v outlived its hold", c) + } + updateBattery(s, `{"max_soc_fract":0.95}`) + if c, ok := batteryCeiling(s); !ok || c != .95 { + t.Fatalf("a new ceiling = %v, %v; want 0.95", c, ok) + } + }) +} + +func TestSoCCeilingDropsWithAStaleReading(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := NewStore() + updateBattery(s, `{"max_soc_fract":0.9}`) + time.Sleep(BatterySoCMaxAge + time.Second) + if c, ok := batteryCeiling(s); ok { + t.Fatalf("a stale reading kept its ceiling %v", c) + } + }) +} + +func TestSoCCeilingBelowTrustedMinimumIsIgnored(t *testing.T) { + s := NewStore() + updateBattery(s, `{"max_soc_fract":0.05}`) + if c, ok := batteryCeiling(s); ok { + t.Fatalf("a ceiling of 5%% was trusted: %v", c) + } + updateBattery(s, `{"max_soc_fract":0.9}`) + updateBattery(s, `{"max_soc_fract":0.3}`) + if c, ok := batteryCeiling(s); !ok || c != .9 { + t.Fatalf("an implausible read replaced the held ceiling: %v, %v", c, ok) + } + if got := s.lowSoCCeilings["pixii"]; got != .3 { + t.Fatalf("logged low ceiling = %v, want 0.3", got) + } + updateBattery(s, `{"max_soc_fract":0.9}`) + if _, logged := s.lowSoCCeilings["pixii"]; logged { + t.Fatal("a trusted ceiling did not clear the low-ceiling log state") + } +} + +func TestSoCCeilingDoesNotSurviveRemove(t *testing.T) { + s := NewStore() + updateBattery(s, `{"max_soc_fract":0.9}`) + s.Remove("pixii") + updateBattery(s, `{}`) + if c, ok := batteryCeiling(s); ok { + t.Fatalf("a replacement driver inherited ceiling %v", c) + } +} diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index d9bfe20e8..6ebf66314 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -92,6 +92,10 @@ type DerReading struct { SmoothedW float64 SoC *float64 // optional; 0..1 fraction for every DER including vehicles SoCUpdatedAt time.Time // last SoC source observation (receipt time for legacy drivers) + // SoCCeiling is a battery's own charge ceiling, 0..1, and SoCCeilingAt + // when its driver last reported it. Read it through SoCCeilingNow. + SoCCeiling *float64 + SoCCeilingAt time.Time Data json.RawMessage UpdatedAt time.Time // Poll is the driver poll the reading came from, as the driver host @@ -312,6 +316,9 @@ type Store struct { // inverters holds each driver's latest inverter stream reading, apart // from readings so no site sum can include it (inverter.go). inverters map[string]InverterReading + // lowSoCCeilings is the last battery ceiling per driver logged as too low + // to trust (battery_soc_ceiling.go). + lowSoCCeilings map[string]float64 processNoise float64 measurementNoise float64 @@ -496,6 +503,11 @@ func (s *Store) UpdateFromPoll(driver string, t DerType, rawW float64, soc *floa socUpdatedAt = prev.SoCUpdatedAt } } + var socCeiling *float64 + var socCeilingAt time.Time + if t == DerBattery { + socCeiling, socCeilingAt = s.socCeilingFor(driver, data, s.readings[k], now) + } s.readings[k] = &DerReading{ Driver: driver, DerType: t, @@ -503,6 +515,8 @@ func (s *Store) UpdateFromPoll(driver string, t DerType, rawW float64, soc *floa SmoothedW: smoothed, SoC: soc, SoCUpdatedAt: socUpdatedAt, + SoCCeiling: socCeiling, + SoCCeilingAt: socCeilingAt, Data: data, UpdatedAt: now, Poll: poll,