Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/battery-relief-fits-the-phase.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

A battery that has been relieving the fuse no longer lets go all at once when that would put a phase back over the limit. When a kettle came on while the car charged, the battery discharged to keep the busy phase under the fuse. As soon as the meter showed room, it stopped discharging in one step, and the phase went just over the limit again. Now the battery keeps the part of its discharge that the phase cannot take, counting the car's and its own changes that the meter may not show yet, and lets the rest go as the room shows.
60 changes: 60 additions & 0 deletions go/internal/control/battery_relief_release_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package control

import (
"math"
"testing"

"github.com/srcfl/ftw/go/internal/telemetry"
)

// batteryReading gives a battery the SoC its command bounds read.
func batteryReading(store *telemetry.Store, driver string, w, soc float64) {
store.Update(driver, telemetry.DerBattery, w, &soc, nil)
store.RecordDriverSuccess(driver)
}

// Field matrix, relief rows (srcfl/ftw#1763's site, 25 A): a kettle on L1,
// the battery relieving at -3,105 W and L1 reading 19.53 A. Ending that
// relief is our own raise of 4.5 A on every phase; with the car's unseen
// 1 A rise it took L1 to 24.03 A, over the 24 A working limit, for more
// than 3 s. The battery keeps the part of its relief the phase cannot take.
func TestEVBatteryEndingReliefKeepsWhatThePhaseCannotTake(t *testing.T) {
for _, tc := range []struct {
name string
l1A, carRiseA float64
soc float64
want float64
}{
{"the phase takes 3.47 A of the 4.5 A", 19.53, 1, .5, -(3105 - (24-19.53-1)*690)},
{"the phase takes it all and some charge", 15, 1, .5, (24-15-1)*690 - 3105},
{"a battery at its floor cannot keep it", 19.53, 1, 0.01, 0},
} {
t.Run(tc.name, func(t *testing.T) {
phases := []float64{tc.l1A, tc.l1A - 10, tc.l1A - 10}
store, state := evSplitFixture(t, (phases[0]+phases[1]+phases[2])*230, phases, 9660+tc.carRiseA*690, "3p")
sent(state, "ev", 9660, 9660+tc.carRiseA*690)
sent(state, "first", -3105)
batteryReading(store, "first", -3105, tc.soc)
out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "first", TargetW: 3430}}, store, state, 17250)
if got := targetW(out, "first"); math.Abs(got-tc.want) > .01 {
t.Fatalf("battery %.1f W, want %.1f W", got, tc.want)
}
})
}
}

// Before our first battery order, after every Core start, the charge cap
// counts the battery as possibly discharging at its cap. That is no order
// of ours: it must not become a discharge to keep. The battery keeps its
// target or less, never a discharge the plan did not ask for.
func TestEVBatteryWithNoOrderOfOursKeepsNoDischarge(t *testing.T) {
for _, planW := range []float64{0, 6000} {
phases := []float64{20.7, 10.7, 10.7}
store, state := evSplitFixture(t, (phases[0]+phases[1]+phases[2])*230, phases, 4140, "3p")
batteryReading(store, "first", 0, .5)
out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "first", TargetW: planW}}, store, state, 17250)
if got := targetW(out, "first"); got < 0 {
t.Fatalf("plan %.0f W with no order logged: battery %.0f W, want no discharge", planW, got)
}
}
}
59 changes: 50 additions & 9 deletions go/internal/control/ev_battery_headroom.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import (

// clampEVBatteryHeadroom keeps optional battery charge out of room an EV
// still needs. It reads only the site meter and our own commands; no charger
// or battery reading takes part. The EV still needs its demand less the
// reading takes part, and a battery's own reading only bounds how much of a
// discharge we ordered it may keep. The EV still needs its demand less the
// lowest offer of the last evSettle, which the meter surely shows.
func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, state *State, fuseMaxW float64) []DispatchTarget {
if store == nil || state == nil || len(targets) == 0 || fuseMaxW <= 0 {
Expand Down Expand Up @@ -37,6 +38,7 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st
return floorPositiveEVBatteryTargets(targets)
}
latest := make(map[string]float64, len(targets))
lowest := make(map[string]float64, len(targets))
targeted := make(map[string]bool, len(targets))
for _, target := range targets {
if targeted[target.Driver] {
Expand All @@ -45,22 +47,34 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st
targeted[target.Driver] = true
if _, _, last, sent := state.batteryCommands[target.Driver].span(now); sent {
latest[target.Driver] = last
// Only a discharge we ordered can be kept; a battery we have
// not ordered keeps nothing.
if r := store.Get(target.Driver, telemetry.DerBattery); r != nil {
lowest[target.Driver], _ = fuseTargetBounds(r, state.DriverLimits[target.Driver])
}
} else {
// Without a recent order it may be discharging and stop.
latest[target.Driver] = -state.DriverLimits[target.Driver].dischargeCap()
}
}
// Battery charge stays under the level the EV may rise to.
spare := state.importRiseCeilingW(fuseMaxW) - meter.RawW - needW
// Battery charge stays under the level the EV may rise to. Ending a
// discharge needs room past our own raises the meter may not show, the
// EV's included, not past what the car still wants.
riseW := math.Max(0, state.EVCommandedW-offeredW)
ceilingW := state.importRiseCeilingW(fuseMaxW) - meter.RawW
spare, releaseSpare := ceilingW-needW, ceilingW-riseW
// During measured export overflow, the existing fuse pipeline may
// require charge to reduce export. Magnitudes alone cannot label that
// worst phase as import; leave this direction to the existing guard.
if meter.RawW >= -state.effectiveExportCeilingW(fuseMaxW) && state.SiteFuseVoltage > 0 {
if phaseSpare, known := evBatteryPhaseSpareW(meter, state, needW/(state.SiteFuseVoltage*phases)); known {
spare = math.Min(spare, phaseSpare)
}
if phaseSpare, known := evBatteryPhaseSpareW(meter, state, riseW/(state.SiteFuseVoltage*phases)); known {
releaseSpare = math.Min(releaseSpare, phaseSpare)
}
}
out := capBatteryCharge(targets, latest, state.pendingBatteryCommandsW(now), spare)
out := capBatteryCharge(targets, latest, lowest, state.pendingBatteryCommandsW(now), spare, releaseSpare)
// Charge needed to bring measured export inside its hard ceiling is
// not optional. Preserve that part of the already validated offer;
// this stage never invents or increases an original battery command.
Expand All @@ -84,18 +98,21 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st
// capBatteryCharge keeps each battery's latest order: holding it is never an
// increase. A shortfall of measured room takes positive charge back; new
// charge needs room left after our increases the meter may not show yet. A
// reduction this tick funds nothing, as the meter does not show it, and only
// positive targets change.
func capBatteryCharge(targets []DispatchTarget, latest map[string]float64, pendingW, spare float64) []DispatchTarget {
// reduction this tick funds nothing, as the meter does not show it. Ending a
// discharge is our increase too: the part releaseSpare, less our unshown
// increases, cannot take stays as discharge, never below lowest, the lowest
// order each battery's bounds allow (0 W without a reading).
func capBatteryCharge(targets []DispatchTarget, latest, lowest map[string]float64, pendingW, spare, releaseSpare float64) []DispatchTarget {
if !finiteFuseValue(spare) || !finiteFuseValue(pendingW) {
return floorPositiveEVBatteryTargets(targets)
}
out := append([]DispatchTarget(nil), targets...)
holds := make([]float64, len(out))
var holdW, increaseW float64
var holdW, increaseW, lostW float64
for i, target := range out {
last := latest[target.Driver]
spare -= math.Max(0, math.Min(0, target.TargetW)-math.Min(0, last)) // Lost discharge.
lost := math.Max(0, math.Min(0, target.TargetW)-math.Min(0, last)) // Lost discharge.
spare, lostW = spare-lost, lostW+lost
if target.TargetW > 0 {
holds[i] = math.Min(target.TargetW, math.Max(0, last))
holdW += holds[i]
Expand All @@ -118,6 +135,30 @@ func capBatteryCharge(targets []DispatchTarget, latest map[string]float64, pendi
out[i].TargetW, out[i].Clamped = capped, true
}
}
return keepEndingDischarge(out, latest, lowest, lostW+pendingW-releaseSpare-holdW*(1-holdScale))
}

// keepEndingDischarge keeps shortW of the discharge this tick's targets end,
// shared by how much each battery can keep: down to its latest order, never
// below its lowest.
func keepEndingDischarge(out []DispatchTarget, latest, lowest map[string]float64, shortW float64) []DispatchTarget {
keep := make([]float64, len(out))
var keepW float64
for i, target := range out {
if last := latest[target.Driver]; last < 0 {
keep[i] = math.Max(0, math.Min(0, target.TargetW)-math.Max(last, lowest[target.Driver]))
Comment on lines +148 to +149

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore discharge only when a prior command actually exists

After startup, an idle battery with no command history can be commanded to discharge here: clampEVBatteryHeadroom substitutes the negative discharge cap for a missing command, and this loop treats that conservative reservation as discharge to preserve. For a 3×25 A site with an active EV, zero pending raises, a 5 kW battery discharge cap, measured export of 9 kW and a worst phase of 23 A, the new clamp changes a validated 0 W target to −4,310 W. An idle battery obeying that command raises export to 13,310 W, exceeding a configured 10 kW export ceiling; the export guard already ran earlier in applyDispatchSafetyPipeline. Keep the missing-history reservation for optional-charge budgeting, but require an actual prior discharge command before restoring negative power. This avoids issuing a clamp command without the quantified risk required by AGENTS.md.

AGENTS.md reference: AGENTS.md:L68-L68

Useful? React with 👍 / 👎.

keepW += keep[i]
}
}
if !(shortW > 0) || keepW <= 0 {
return out
}
share := math.Min(1, shortW/keepW)
for i := range out {
if keep[i] > 0 {
out[i].TargetW, out[i].Clamped = math.Min(0, out[i].TargetW)-keep[i]*share, true
}
}
return out
}

Expand Down
6 changes: 4 additions & 2 deletions go/internal/control/ev_battery_sequence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,9 @@ func TestCeilingOverageWaitsOnceWhenTheCarDrawsLessThanItsOffer(t *testing.T) {
// The fuse never waits for a car. A house step past the heat budget's
// instant limit (31 A on the 25 A fuse) cuts the car at once and gets
// battery relief on the first reading, which it keeps until the car's cut
// shows on the meter. Then the battery lets go, and nothing exports.
// shows on the meter. Then the battery lets go, and nothing exports. What it
// lets go is our own raise, counted as on its way for evSettle, so the last
// part goes once the first has had that time to show.
func TestFuseOverageGetsBatteryReliefUntilEVCutShows(t *testing.T) {
s := newIdleBatteryEVSite(t, 3000, 0)
s.run(5 * time.Minute)
Expand All @@ -498,7 +500,7 @@ func TestFuseOverageGetsBatteryReliefUntilEVCutShows(t *testing.T) {
}
stepAt := s.now
s.houseW += 8000 // 21,350 W, 31 A on each phase.
s.run(15 * time.Second)
s.run(time.Second + s.chargerDelay + evSettle + 5*time.Second)
cutShows := stepAt.Add(time.Second + s.chargerDelay)
t.Logf("first battery target %.0f W; offer %.0f W", since(s.targetW, stepAt.Add(time.Second))[0].w, s.offer())
for _, b := range since(s.targetW, stepAt.Add(time.Second)) {
Expand Down
9 changes: 0 additions & 9 deletions go/internal/control/testdata/sitesim_field_known.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,6 @@
# surplus never finds room to start.
# readback no fix yet: surplus raises again before the charger applied the
# last raise, then pauses when both land (surplus_reserve.go:128).
# relief srcfl/ftw#1789, draft: the battery ends its relief before the
# car's cut shows.
pr1763/25A/3p/3p-15A/cloud60s/car3p/6-2-2/chargenow+battery own-raise relief
pr1763/25A/3p/3p-15A/cloud60s/car3p/6-2-2/pause+battery own-raise relief
pr1763/25A/3p/3p-15A/easee120s/car3p/6-2-2/chargenow+battery own-raise relief
pr1763/25A/3p/3p-15A/easee120s/car3p/6-2-2/pause+battery own-raise relief
pr1763/25A/3p/3p-15A/easee40s/car3p/6-2-2/chargenow+battery own-raise relief
pr1763/25A/3p/3p-15A/easee40s/car3p/6-2-2/pause+battery own-raise relief
pr1763/25A/3p/3p-15A/fast2s/car3p/6-2-2/pause+battery own-raise relief
probe/25A/auto/mixed/easee40s/car3p/balanced/surplus+goal+export2500W idle readback
timing/16A/3p/3p/cloud60s/car3p/L1/surplus idle export
timing/16A/3p/3p/easee120s/car3p/L1/surplus idle export
Expand Down
Loading