Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/battery-device-soc-max.md
Original file line number Diff line number Diff line change
@@ -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.
168 changes: 168 additions & 0 deletions go/internal/control/battery_device_soc_max_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
75 changes: 73 additions & 2 deletions go/internal/control/battery_full.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package control

import (
"log/slog"
"math"

"github.com/srcfl/ftw/go/internal/telemetry"
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -44,14 +77,52 @@ 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)
}
}
}

// 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) {
Expand Down
5 changes: 4 additions & 1 deletion go/internal/control/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions go/internal/mpc/device_soc_ceiling.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading