diff --git a/.changeset/pending-battery-relief.md b/.changeset/pending-battery-relief.md new file mode 100644 index 000000000..f2ab816f8 --- /dev/null +++ b/.changeset/pending-battery-relief.md @@ -0,0 +1,7 @@ +--- +"ftw": patch +--- + +Keep pending battery import and export increases reserved when ending existing fuse relief, so successive commands cannot spend the same phase headroom before the meter observes their effect. + +Distribute retained relief only across available, previously commanded battery supply. A battery at its SoC floor or blocked in the required direction no longer consumes a share that another eligible battery can provide. Apply the same bounded allocation to import and export. diff --git a/go/internal/control/battery_pending_relief_test.go b/go/internal/control/battery_pending_relief_test.go new file mode 100644 index 000000000..fe670a617 --- /dev/null +++ b/go/internal/control/battery_pending_relief_test.go @@ -0,0 +1,88 @@ +package control + +import ( + "encoding/json" + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// Ending discharge raises import; ending charge raises export. A prior rise +// still absent from the meter must consume room before either can rise again. +func TestPendingBatteryReliefDoesNotSpendPhaseRoomTwice(t *testing.T) { + for _, direction := range []float64{1, -1} { + for _, layer := range []string{"allocation", "manual", "idle"} { + name := "import" + if direction < 0 { + name = "export" + } + t.Run(name+"/"+layer, func(t *testing.T) { + now := time.Now().UTC() + store := telemetry.NewStore() + data, _ := json.Marshal(map[string]float64{ + "l1_a": 22.3 * direction, "l2_a": 12.3 * direction, "l3_a": 12.3 * direction, + "l1_w": 22.3 * 230 * direction, "l2_w": 12.3 * 230 * direction, "l3_w": 12.3 * 230 * direction, + }) + store.Update("meter", telemetry.DerMeter, 10787*direction, nil, data) + store.RecordDriverSuccess("meter") + soc := .5 + actual := -2000 * direction + store.Update("battery", telemetry.DerBattery, actual, &soc, nil) + store.RecordDriverSuccess("battery") + store.Get("meter", telemetry.DerMeter).UpdatedAt = now + store.Get("battery", telemetry.DerBattery).UpdatedAt = now + st := phaseState(25, 1) + st.clock = func() time.Time { return now } + st.DriverLimits = map[string]PowerLimits{"battery": {MaxChargeW: 10000, MaxDischargeW: 5000}} + st.batteryCommands = map[string]commandLog{"battery": commandLog{}.add(now.Add(-time.Hour), actual).add(now.Add(-2*time.Second), -1000*direction)} + var out []DispatchTarget + if layer == "allocation" { + out = fitBatteryRisesToFuse([]DispatchTarget{{Driver: "battery", TargetW: 0}}, store, st) + } else { + st.SlewEnabled = false + st.MinDispatchIntervalS = 0 + if layer == "manual" { + st.SetBatteryManualHold(BatteryManualHold{PowerW: 0, ExpiresAt: now.Add(time.Minute)}) + } else { + st.Mode = ModeIdle + } + out = ComputeDispatch(store, st, map[string]float64{"battery": 20000}, 17250) + } + if len(out) != 1 { + t.Fatalf("missing battery target: %+v", out) + } + projected := 22.3 + direction*(out[0].TargetW-actual)/690 + if !finiteFuseValue(out[0].TargetW) || projected > 24.01 { + t.Fatalf("pending rise spent twice: target %.1f W projects %.3f A", out[0].TargetW, projected) + } + if math.Abs(out[0].TargetW+827*direction) > 1e-6 { + t.Fatalf("target %.3f W, want %.3f W", out[0].TargetW, -827*direction) + } + }) + } + } +} + +func TestPendingBatteryReliefRespectsAvailableRoomAndBounds(t *testing.T) { + cases := []struct { + name string + pending, room, last, keep, want float64 + }{ + {"pending", 1000, 1173, -1000, 1000, -827}, + {"settled", 0, 1173, -1000, 1000, 0}, + {"room_for_both", 1000, 2500, -1000, 1000, 0}, + {"direction_blocked", 1000, 1173, -1000, 0, 0}, + {"battery_floor_bounds_relief", 1000, 1173, -1000, 500, -500}, + {"no_existing_relief", 2000, 1173, 0, 1000, 0}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + out := capBatteryCharge([]DispatchTarget{{Driver: "battery", TargetW: 0}}, map[string]float64{"battery": c.last}, c.pending, c.room, map[string]float64{"battery": c.keep}) + if got := out[0].TargetW; math.Abs(got-c.want) > 1e-6 { + t.Fatalf("target %.3f want %.3f", got, c.want) + } + }) + } +} diff --git a/go/internal/control/battery_relief_distribution_test.go b/go/internal/control/battery_relief_distribution_test.go new file mode 100644 index 000000000..9670ebeed --- /dev/null +++ b/go/internal/control/battery_relief_distribution_test.go @@ -0,0 +1,143 @@ +package control + +import ( + "encoding/json" + "github.com/srcfl/ftw/go/internal/telemetry" + "math" + "testing" + "time" +) + +func TestBatteryReliefRedistributesOnlyAvailableSupply(t *testing.T) { + for _, tc := range []struct { + name string + lastA, keepA, keepB, pending, wantA, wantB float64 + }{ + {"blocked", -1000, 0, 5000, 0, 0, -1827}, + {"partial", -1000, 300, 5000, 0, 0, -1827}, + {"insufficient", -1000, 100, 700, 0, -100, -700}, + {"no_prior_supply", 0, 5000, 5000, 0, 0, -827}, + {"pending_exceeds_supply", -1000, 0, 5000, 1000, 0, -2000}, + } { + for _, reverse := range []bool{false, true} { + t.Run(tc.name+map[bool]string{false: "/forward", true: "/reverse"}[reverse], func(t *testing.T) { + targets := []DispatchTarget{{Driver: "a", TargetW: 0}, {Driver: "b", TargetW: 0}} + if reverse { + targets[0], targets[1] = targets[1], targets[0] + } + out := capBatteryCharge(targets, map[string]float64{"a": tc.lastA, "b": -2000}, tc.pending, 1173, map[string]float64{"a": tc.keepA, "b": tc.keepB}) + if tc.name == "partial" { + total := 0.0 + for _, v := range out { + total += v.TargetW + if v.TargetW > 0 || v.Driver == "a" && v.TargetW < -300 || v.Driver == "b" && v.TargetW < -2000 { + t.Fatalf("relief crossed available supply: %+v", out) + } + } + if math.Abs(total+1827) > 1e-6 { + t.Fatalf("retained %.6f W, want -1827 W", total) + } + return + } + wants := map[string]float64{"a": tc.wantA, "b": tc.wantB} + for _, v := range out { + if math.Abs(v.TargetW-wants[v.Driver]) > 1e-6 { + t.Fatalf("%s target %.6f, want %.6f", v.Driver, v.TargetW, wants[v.Driver]) + } + } + }) + } + } +} + +func TestBatteryReliefDistributionAcrossDirectionsAndDispatch(t *testing.T) { + for _, direction := range []float64{1, -1} { + for _, bound := range []string{"blocked", "partial"} { + for _, layer := range []string{"allocation", "manual", "idle"} { + for _, reverse := range []bool{false, true} { + name := map[float64]string{1: "import", -1: "export"}[direction] + "/" + bound + "/" + layer + map[bool]string{false: "/forward", true: "/reverse"}[reverse] + t.Run(name, func(t *testing.T) { + now := time.Now().UTC() + store := telemetry.NewStore() + data, _ := json.Marshal(map[string]float64{"l1_a": 22.3 * direction, "l2_a": 12.3 * direction, "l3_a": 12.3 * direction, "l1_w": 22.3 * 230 * direction, "l2_w": 12.3 * 230 * direction, "l3_w": 12.3 * 230 * direction}) + store.Update("meter", telemetry.DerMeter, 10787*direction, nil, data) + store.RecordDriverSuccess("meter") + soc := .6 + low := .04 + var blocked json.RawMessage + aSoc := &soc + if bound == "blocked" { + if direction > 0 { + aSoc = &low + } else { + blocked = json.RawMessage(`{"charge_capable":false}`) + } + } + store.Update("a", telemetry.DerBattery, -1000*direction, aSoc, blocked) + store.RecordDriverSuccess("a") + store.Update("b", telemetry.DerBattery, -2000*direction, &soc, nil) + store.RecordDriverSuccess("b") + for _, d := range []string{"meter", "a", "b"} { + kind := telemetry.DerBattery + if d == "meter" { + kind = telemetry.DerMeter + } + store.Get(d, kind).UpdatedAt = now + } + st := phaseState(25, 1) + st.clock = func() time.Time { return now } + st.Mode = ModeIdle + st.SlewEnabled = false + st.MinDispatchIntervalS = 0 + limits := PowerLimits{MaxChargeW: 5000, MaxDischargeW: 5000} + if bound == "partial" { + if direction > 0 { + limits.MaxDischargeW = 300 + } else { + limits.MaxChargeW = 300 + } + } + st.DriverLimits = map[string]PowerLimits{"a": limits, "b": {MaxChargeW: 5000, MaxDischargeW: 5000}} + st.batteryCommands = map[string]commandLog{"a": commandLog{}.add(now.Add(-time.Hour), -1000*direction), "b": commandLog{}.add(now.Add(-time.Hour), -2000*direction)} + targets := []DispatchTarget{{Driver: "a", TargetW: 0}, {Driver: "b", TargetW: 0}} + if reverse { + targets[0], targets[1] = targets[1], targets[0] + } + var out []DispatchTarget + if layer == "allocation" { + out = fitBatteryRisesToFuse(targets, store, st) + } else { + if layer == "manual" { + st.SetBatteryManualHold(BatteryManualHold{PowerW: 0, ExpiresAt: now.Add(time.Minute)}) + } + out = ComputeDispatch(store, st, map[string]float64{"a": 10000, "b": 10000}, 17250) + } + if len(out) != 2 { + t.Fatalf("missing targets %+v", out) + } + total := 0.0 + for _, v := range out { + total += v.TargetW + if v.Driver == "a" { + cap := 0.0 + if bound == "partial" { + cap = 300 + } + if math.Abs(v.TargetW) > cap+1e-6 { + t.Fatalf("blocked/bounded supply used: %+v", out) + } + } + if v.TargetW*direction > 1e-6 || math.Abs(v.TargetW) > map[string]float64{"a": 1000, "b": 2000}[v.Driver]+1e-6 { + t.Fatalf("new or reversed supply %+v", out) + } + } + projected := 22.3 + (3000+direction*total)/690 + if math.Abs(projected-24) > 1e-6 { + t.Fatalf("target %.6f projects %.6f A, want 24 A", total, projected) + } + }) + } + } + } + } +} diff --git a/go/internal/control/fuse_phase.go b/go/internal/control/fuse_phase.go index 2adf893af..095acd5e1 100644 --- a/go/internal/control/fuse_phase.go +++ b/go/internal/control/fuse_phase.go @@ -306,11 +306,11 @@ func capBatteryCharge(targets []DispatchTarget, latest map[string]float64, pendi } out := append([]DispatchTarget(nil), targets...) holds, lost := make([]float64, len(out)), make([]float64, len(out)) - var holdW, increaseW, lostW float64 + var holdW, increaseW float64 for i, target := range out { last := latest[target.Driver] lost[i] = math.Max(0, math.Min(0, target.TargetW)-math.Min(0, last)) - lostW, spare = lostW+lost[i], spare-lost[i] + spare -= lost[i] if target.TargetW > 0 { holds[i] = math.Min(target.TargetW, math.Max(0, last)) holdW += holds[i] @@ -333,10 +333,21 @@ func capBatteryCharge(targets []DispatchTarget, latest map[string]float64, pendi out[i].TargetW, out[i].Clamped = capped, true } } - if short := -spare - holdW; short > 0 && lostW > 0 { - k := math.Min(1, short/lostW) + // Pending rises consume room when ending relief too, not only when + // adding positive charge. Otherwise two successive reductions of + // discharge (or charge on the export pass) can spend the same room. + // Divide the shortfall over supply that can actually remain. A share + // assigned to a blocked or floor-bounded battery cannot protect the fuse. + // Never retain more than the previous order would otherwise release. + var availableW float64 + for i := range out { + lost[i] = math.Min(lost[i], math.Max(0, keepW[out[i].Driver])) + availableW += lost[i] + } + if short := pendingW - spare - holdW; short > 0 && availableW > 0 { + k := math.Min(1, short/availableW) for i := range out { - if keep := math.Min(lost[i]*k, keepW[out[i].Driver]); keep > 0 { + if keep := lost[i] * k; keep > 0 { out[i].TargetW, out[i].Clamped = math.Min(0, out[i].TargetW)-keep, true } }