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/a3-no-discharge-after-slew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

Stop asking a home battery to discharge when its charge is below 5 % or it reports that it cannot discharge. The slew limit used to ramp such a battery back toward the discharge it was already doing. If stopping it at once would put the site or one phase over the fuse or import limit, other batteries take that load first, and the blocked battery keeps only the discharge still needed.
149 changes: 148 additions & 1 deletion go/internal/control/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,7 @@ func applyDispatchSafetyPipeline(
targets = floorNegativeTargets(targets)
}
targets = floorBlockedCharge(targets, opts.noSelfCharge, opts.chargeBlocked)
targets = floorBlockedDischarge(targets, store, state, driverCapacities, fuseMaxW)

// A battery-boost lease may never draw the stationary fleet below its
// explicit reserve. Apply this immediately before forceFuseDischarge:
Expand Down Expand Up @@ -3394,7 +3395,7 @@ func floorNegativeTargets(targets []DispatchTarget) []DispatchTarget {
// toward charge after noSelfCharge set 0. The snap-to-zero list inside
// slew never grew the later charge gates, which is how an idle slot
// commanded +1500 W. This only moves a target toward zero. Discharge
// stays out: the fuse saver may need it.
// has its own twin, floorBlockedDischarge, which yields to the fuse.
func floorBlockedCharge(targets []DispatchTarget, noSelfCharge bool, chargeBlocked map[string]bool) []DispatchTarget {
if !noSelfCharge && len(chargeBlocked) == 0 {
return targets
Expand All @@ -3411,6 +3412,152 @@ func floorBlockedCharge(targets []DispatchTarget, noSelfCharge bool, chargeBlock
return targets
}

// floorBlockedDischarge is the discharge twin of floorBlockedCharge. Slew
// anchors on measured watts, so a pack the distributor parked at 0 W (SoC
// below the floor, discharge_capable=false) is walked back toward its live
// discharge. Stop it at 0 W. If the stop would put the site or one phase
// over the fuse or import limit, the blocked packs keep only the discharge
// the capable packs cannot cover, and never more than their slewed ramp.
// forceFuseDischarge then takes the rest from the capable packs.
func floorBlockedDischarge(
targets []DispatchTarget,
store *telemetry.Store,
state *State,
driverCapacities map[string]float64,
fuseMaxW float64,
) []DispatchTarget {
if store == nil || state == nil {
return targets
}
var out []DispatchTarget
var rampW float64 // discharge the slewed ramp still asks of blocked packs
blocked := make([]bool, len(targets))
readings := make(map[string]*telemetry.DerReading, len(targets))
for i, t := range targets {
r := store.Get(t.Driver, telemetry.DerBattery)
readings[t.Driver] = r
if t.TargetW >= 0 || r == nil {
continue
}
if lower, _ := fuseTargetBounds(r, state.DriverLimits[t.Driver]); lower < 0 {
continue
}
if out == nil {
out = append([]DispatchTarget(nil), targets...)
}
blocked[i] = true
rampW -= t.TargetW
out[i].TargetW = 0
out[i].Clamped = true
}
if out == nil {
return targets
}
if fuseMaxW <= 0 {
return out
}
meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter)
keepW := blockedDischargeKeepW(store, out, blocked, readings, meter, state, driverCapacities, fuseMaxW)
if keepW <= 0 {
return out
}
if keepW >= rampW {
return targets
}
Comment on lines +3459 to +3466

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 Check predicted phase headroom before stopping discharge

On an unbalanced three-phase site, this check can approve an immediate stop that overloads one phase. fuseReliefFromSnapshot checks projected aggregate import, but its phase check only detects an overage already present in the meter sample; it does not predict the phase-current increase from stopping discharge. For example, with a 16 A/230 V three-phase fuse, 6 kW aggregate import, L1 at 15 A, and a blocked battery discharging at 3 kW, stopping the battery leaves aggregate import at a seemingly safe 9 kW but raises L1 to approximately 19.35 A. The previous 500 W slew step would leave L1 at approximately 15.72 A. The subsequent forceFuseDischarge uses the same check and cannot correct this. Compare the floored targets against the phase-aware import ceiling, or explicitly project phase currents, before bypassing the ramp.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 97fc2b7. stopPhaseReliefW projects the stop onto each phase, and the blocked pack keeps the discharge that holds the worst phase at its limit. Your example (16 A, L1 at 15 A, 6 kW import, 3 kW blocked discharge) now gives -2310 W, so L1 lands at 16 A. Test: TestBlockedDischargeStopRespectsPhaseFuse.

for i, t := range targets {
if blocked[i] {
out[i].TargetW = t.TargetW * keepW / rampW
}
}
return out
}

// blockedDischargeKeepW is the discharge the blocked packs must keep after
// floorBlockedDischarge set them to 0 W. forceFuseDischarge covers the
// aggregate overage from capable packs, so only the part beyond their room
// stays with the blocked packs. forceFuseDischarge reads phase currents from
// the meter as they are, not as the stop leaves them, so a phase that only
// the stop puts over the fuse is covered by the blocked packs alone.
func blockedDischargeKeepW(
store *telemetry.Store,
out []DispatchTarget,
blocked []bool,
readings map[string]*telemetry.DerReading,
meter *telemetry.DerReading,
state *State,
driverCapacities map[string]float64,
fuseMaxW float64,
) float64 {
reliefW := math.Max(0, fuseReliefFromSnapshot(out, readings, meter, state, fuseMaxW, false))
if phaseW := stopPhaseReliefW(store, out, readings, meter, state); phaseW > reliefW {
return phaseW
}
var roomW float64
for i, t := range out {
r := readings[t.Driver]
if blocked[i] || r == nil || driverCapacities[t.Driver] <= 0 {
continue
}
lower, _ := fuseTargetBounds(r, state.DriverLimits[t.Driver])
roomW += math.Max(0, t.TargetW-lower)
}
_, _, predicted := predictedGridFromSnapshot(out, readings, meter)
roomW = math.Min(roomW, math.Max(0, predicted+state.effectiveExportCeilingW(fuseMaxW)))
return reliefW - roomW
}

// stopPhaseReliefW is the aggregate import relief that keeps the worst phase
// inside the per-phase fuse once the targets replace the batteries' raw
// power. A battery spreads its move evenly over the site's phases. 0 without
// usable phase currents, or when the meter or a battery has gone offline or
// moved on from the readings the rest of the decision used.
func stopPhaseReliefW(
store *telemetry.Store,
targets []DispatchTarget,
readings map[string]*telemetry.DerReading,
meter *telemetry.DerReading,
state *State,
) float64 {
if store == nil || meter == nil {
return 0
}
totalW, at, ok := store.OnlineMeterW(state.SiteMeterDriver)
if !ok || !at.Equal(meter.UpdatedAt) {
return 0
}
amps, _, valid := phaseCurrentsA(meter, state, totalW)
if !valid || len(amps) == 0 {
return 0
}
moveW := 0.0
seen := make(map[string]bool, len(targets))
for _, t := range targets {
moveW += t.TargetW
if r := readings[t.Driver]; r != nil && !seen[t.Driver] {
rawW, at, ok := store.OnlineRawW(t.Driver, telemetry.DerBattery)
if !ok || !at.Equal(r.UpdatedAt) {
return 0
}
moveW -= rawW
}
seen[t.Driver] = true
}
exports := totalW < 0
for _, a := range amps {
exports = exports && a >= 0
}
perA := state.SiteFuseVoltage * float64(state.SiteFusePhases)
hiA := math.Inf(-1)
for _, a := range amps {
if exports {
a = -a // unsigned phases take the total's direction
}
hiA = math.Max(hiA, a+moveW/perA)
}
limitA := math.Max(0, state.SiteFuseAmps-state.SiteFuseSafetyA)
return math.Max(0, hiA-limitA) * perA
}

// coverLoadChargeSlot reports whether the current plan slot is a charge-from-
// PV-surplus slot: the DP meant to soak surplus (PlannedGridW below the
// grid-charge import band), NOT buy from the grid. Such a slot carries no hard
Expand Down
5 changes: 3 additions & 2 deletions go/internal/control/golden_dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1316,8 +1316,9 @@ func slewScenarios() []goldenScenario {
State: plan(ModePlannerSelf, 500),
Slot: staleSlot(),
}))
// A discharge-blocked battery is parked at 0 W by the distributor and
// then walked back toward its live discharge by the same mechanism.
// A discharge-blocked battery is parked at 0 W by the distributor. Slew
// used to walk it back toward its live discharge; floorBlockedDischarge
// now holds it at 0 W while the fuse does not need the ramp.
blk := gb("ferroamp", 15200, -2000, 0.50)
blk.DischargeBlocked = true
out = append(out, mk("blocked_sibling_slew_reopens_parked_target", goldenInputs{
Expand Down
189 changes: 189 additions & 0 deletions go/internal/control/slew_discharge_floor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package control

import (
"encoding/json"
"math"
"testing"
"time"

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

// Slew anchors on measured SmoothedW. It must not walk a pack back into the
// discharge the distributor closed (SoC below the 5 % floor, or
// discharge_capable=false).
func TestSlewDoesNotReopenBlockedDischarge(t *testing.T) {
cases := []struct {
name string
soc float64
capability string
}{
{"soc_below_floor", 0.04, ""},
{"discharge_capable_false", 0.50, `{"discharge_capable":false}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
store := seedDeadbandSite(2000, []deadbandBattery{{"bat", -3000, tc.soc, tc.capability}})
out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 0)
if got := targetsByDriver(out)["bat"].TargetW; got < -1 {
t.Errorf("commanded %.0f W discharge to a pack that must not discharge", got)
}
})
}
}

// When stopping the blocked pack at once would put the site over its fuse,
// the pack keeps only the discharge the fuse needs: 10000 + 3000 - 11040 W.
// That is less than the slewed ramp (-2500 W) and never more discharge.
func TestBlockedDischargeKeepsFuseOverage(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
store := seedDeadbandSite(10000, []deadbandBattery{{"bat", -3000, 0.04, ""}})
out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 11040)
if got := targetsByDriver(out)["bat"].TargetW; math.Abs(got+1960) > 1 {
t.Errorf("target %.0f W, want -1960 W", got)
}
}

// A stop 60 W over the fuse keeps 60 W of discharge, not the whole ramp.
func TestBlockedDischargeKeepsOnlyTheOverage(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
store := seedDeadbandSite(8100, []deadbandBattery{{"blk", -3000, 0.04, ""}})
out := ComputeDispatch(store, st, caps(map[string]float64{"blk": 10000}), 11040)
if got := targetsByDriver(out)["blk"].TargetW; math.Abs(got+60) > 1 {
t.Errorf("target %.0f W, want -60 W", got)
}
}

// A capable sibling takes the fuse relief, so the blocked pack stops.
func TestBlockedDischargeLeavesReliefToSibling(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
store := seedDeadbandSite(9000, []deadbandBattery{
{"blk", -3000, 0.04, ""},
{"ok", 0, 0.60, ""},
})
out := ComputeDispatch(store, st, caps(map[string]float64{"blk": 10000, "ok": 10000}), 11040)
m := targetsByDriver(out)
if m["blk"].TargetW < -1 {
t.Errorf("blocked pack at %.0f W while the sibling had room", m["blk"].TargetW)
}
// 9000 W meter + 3000 W stop + the sibling's target must fit 11040 W.
if grid := 12000 + m["ok"].TargetW; grid > 11041 {
t.Errorf("projected grid %.0f W over the 11040 W fuse (sibling %.0f W)", grid, m["ok"].TargetW)
}
}

// Two blocked packs share the discharge the fuse needs. Together they keep
// 6000 + 6000 - 11040 = 960 W, not two ramps of 2500 W.
func TestBlockedDischargeSharesOverage(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
store := seedDeadbandSite(6000, []deadbandBattery{
{"a", -3000, 0.04, ""},
{"b", -3000, 0.50, `{"discharge_capable":false}`},
})
out := ComputeDispatch(store, st, caps(map[string]float64{"a": 10000, "b": 10000}), 11040)
m := targetsByDriver(out)
if sum := m["a"].TargetW + m["b"].TargetW; math.Abs(sum+960) > 1 {
t.Errorf("blocked packs keep %.0f W + %.0f W, want -960 W in total", m["a"].TargetW, m["b"].TargetW)
}
}

// An unbalanced site: the total stays far under the fuse, but stopping a
// 3 kW discharge adds 4.35 A to each phase and L1 is at 15 A of 16 A. The
// pack keeps the discharge that holds L1 at 16 A.
func TestBlockedDischargeStopRespectsPhaseFuse(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
st.SiteFuseAmps = 16
st.SiteFuseVoltage = 230
st.SiteFusePhases = 3
store := seedDeadbandSite(6000, []deadbandBattery{{"blk", -3000, 0.04, ""}})
data, _ := json.Marshal(map[string]any{"l1_a": 15.0, "l2_a": 6.0, "l3_a": 5.1})
store.Update("meter", telemetry.DerMeter, 6000, nil, data)
out := ComputeDispatch(store, st, caps(map[string]float64{"blk": 10000}), 11040)
got := targetsByDriver(out)["blk"].TargetW
if l1 := 15 + (got+3000)/(230*3); l1 > 16.01 {
t.Errorf("target %.0f W puts L1 at %.2f A on a 16 A fuse", got, l1)
}
if got < -2311 {
t.Errorf("target %.0f W keeps more discharge than L1 needs (-2310 W)", got)
}
}

// The stop holds while the pack's measured discharge decays.
func TestBlockedDischargeStaysStopped(t *testing.T) {
st := NewState(0, 42, "meter")
st.MinDispatchIntervalS = 0
st.SlewRateW = 500
live := -3000.0
for tick := 0; tick < 6; tick++ {
store := seedDeadbandSite(-1000-live, []deadbandBattery{{"bat", live, 0.04, ""}})
out := ComputeDispatch(store, st, caps(map[string]float64{"bat": 10000}), 0)
if got := targetsByDriver(out)["bat"].TargetW; got < -1 {
t.Fatalf("tick %d: %.0f W", tick, got)
}
live /= 2
}
}

// A manual self-tune request goes through the same floor.
func TestSelfTuneDoesNotDischargeBlockedPack(t *testing.T) {
st := NewState(0, 42, "meter")
store := seedDeadbandSite(2000, []deadbandBattery{{"blk", -3000, 0.04, ""}})
out := SelfTuneDispatch(store, st, caps(map[string]float64{"blk": 10000}), 11040, "blk", -2000)
if got := targetsByDriver(out)["blk"].TargetW; got < -1 {
t.Errorf("self-tune sent %.0f W", got)
}
}

// The phase relief uses only live readings from the same sample as the rest
// of the decision. A battery or meter that went offline, or a meter that
// moved on to a newer reading, gives no phase relief.
func TestStopPhaseReliefNeedsLiveReadings(t *testing.T) {
st := NewState(0, 42, "meter")
st.SiteFuseAmps = 16
st.SiteFuseVoltage = 230
st.SiteFusePhases = 3
data, _ := json.Marshal(map[string]any{"l1_a": 15.0, "l2_a": 6.0, "l3_a": 5.1})
seed := func() (*telemetry.Store, map[string]*telemetry.DerReading, *telemetry.DerReading) {
store := seedDeadbandSite(6000, []deadbandBattery{{"blk", -3000, 0.04, ""}})
store.Update("meter", telemetry.DerMeter, 6000, nil, data)
readings := map[string]*telemetry.DerReading{"blk": store.Get("blk", telemetry.DerBattery)}
return store, readings, store.Get("meter", telemetry.DerMeter)
}
stop := []DispatchTarget{{Driver: "blk", TargetW: 0}}

store, readings, meter := seed()
// Stopping 3000 W puts L1 at 15 + 4.35 A; 3.35 A over 16 A is 2310 W.
if got := stopPhaseReliefW(store, stop, readings, meter, st); math.Abs(got-2310) > 1 {
t.Fatalf("live readings: relief %.0f W, want 2310 W", got)
}
store.DriverHealthMut("blk").SetOffline()
if got := stopPhaseReliefW(store, stop, readings, meter, st); got != 0 {
t.Errorf("offline battery: relief %.0f W, want 0", got)
}

store, readings, meter = seed()
store.DriverHealthMut("meter").SetOffline()
if got := stopPhaseReliefW(store, stop, readings, meter, st); got != 0 {
t.Errorf("offline meter: relief %.0f W, want 0", got)
}

store, readings, meter = seed()
time.Sleep(time.Millisecond)
store.Update("meter", telemetry.DerMeter, 6000, nil, data)
if got := stopPhaseReliefW(store, stop, readings, meter, st); got != 0 {
t.Errorf("newer meter reading: relief %.0f W, want 0", got)
}
}
6 changes: 3 additions & 3 deletions go/internal/control/testdata/golden/slew_limiter.json
Original file line number Diff line number Diff line change
Expand Up @@ -2174,7 +2174,7 @@
"per_driver_targets": [
{
"driver": "ferroamp",
"target_w": -1500,
"target_w": 0,
"clamped": true
},
{
Expand Down Expand Up @@ -2205,9 +2205,9 @@
},
"site_totals": {
"battery_current_w": -2000,
"battery_target_sum_w": -2000,
"battery_target_sum_w": -500,
"raw_grid_w": 2500,
"projected_grid_w": 2500
"projected_grid_w": 4000
}
},
{
Expand Down
Loading
Loading