diff --git a/.changeset/battery-device-soc-max.md b/.changeset/battery-device-soc-max.md new file mode 100644 index 000000000..6426949a3 --- /dev/null +++ b/.changeset/battery-device-soc-max.md @@ -0,0 +1,11 @@ +--- +"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. 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 new file mode 100644 index 000000000..972b9fc3e --- /dev/null +++ b/go/internal/control/battery_device_soc_max_test.go @@ -0,0 +1,168 @@ +package control + +import ( + "encoding/json" + "testing" + "testing/synctest" + "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 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) { + 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) + } +} + +// 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) + if !st.BatteryChargePaused("battery") { + t.Fatal("device ceiling did not pause charging") + } + // The owner raises the Pixii's limit; the next reading carries it. + 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) + } +} + +func TestDeviceSoCMaxClosesTheFuseChargeBound(t *testing.T) { + 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.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 f36dc75de..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" @@ -12,7 +13,38 @@ 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 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 := s.batteryDeviceSoCMax[driver].value; device > 0 && device < ceiling { + return device + } + return ceiling +} + +// 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 && 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 @@ -33,6 +65,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 +77,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 +85,44 @@ func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[s } } +// 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]deviceSoCMax{} + } + for name := range s.batteryDeviceSoCMax { + if _, ok := capacities[name]; !ok { + delete(s.batteryDeviceSoCMax, name) + } + } + now := s.now() + for name := range capacities { + 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 + } +} + 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..938d3d162 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 + // 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. @@ -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..8766074de --- /dev/null +++ b/go/internal/mpc/device_soc_ceiling.go @@ -0,0 +1,43 @@ +package mpc + +import ( + "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.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 %. 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] + 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 + } + 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..5258ded61 --- /dev/null +++ b/go/internal/mpc/device_soc_ceiling_test.go @@ -0,0 +1,169 @@ +package mpc + +import ( + "context" + "encoding/json" + "math" + "path/filepath" + "reflect" + "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 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 := .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") + } +} + +// 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..20859b254 --- /dev/null +++ b/go/internal/telemetry/battery_soc_ceiling.go @@ -0,0 +1,79 @@ +package telemetry + +import ( + "encoding/json" + "log/slog" + "time" +) + +// 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 + } + 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 +} + +// 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 new file mode 100644 index 000000000..673a4f583 --- /dev/null +++ b/go/internal/telemetry/battery_soc_ceiling_test.go @@ -0,0 +1,107 @@ +package telemetry + +import ( + "encoding/json" + "testing" + "testing/synctest" + "time" +) + +func TestParseSoCCeiling(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 := parseSoCCeiling(json.RawMessage(tc.data)) + if got != tc.want || ok != 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,