diff --git a/.changeset/car-before-battery-charge.md b/.changeset/car-before-battery-charge.md new file mode 100644 index 000000000..d7f2f0f0f --- /dev/null +++ b/.changeset/car-before-battery-charge.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +Give the car priority over home battery charging at the main fuse. Reduce battery charging before cutting an existing car offer, with a fixed response timeout and the rated fuse limit still enforced. Restart the car when its minimum fits the measured room, and let it reach its requested power while the battery uses the space left over. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 6745ff96a..3e01f1eea 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -2392,6 +2392,7 @@ func applyDispatchSafetyPipeline( } targets = floorMissingSoCDischarge(targets, store) targets = clampEVBatteryHeadroom(targets, store, state, fuseMaxW) + targets = state.applyEVBatteryYield(targets) targets = state.floorFullBatteryCharge(targets) republishFuseEVCapAfterFuseDischarge(targets, store, state, fuseMaxW) recordDispatchTargets(targets, state, opts.updatePrevTargets, opts.recordDispatch) diff --git a/go/internal/control/ev_battery_priority.go b/go/internal/control/ev_battery_priority.go new file mode 100644 index 000000000..29bee0621 --- /dev/null +++ b/go/internal/control/ev_battery_priority.go @@ -0,0 +1,100 @@ +package control + +import ( + "log/slog" + "math" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// evBatteryYield lets an existing car offer wait for a battery charge cut. +// It never grants a car rise, never runs outside the measured fuse rating, +// and cannot renew while the site remains over its working limit. +type evBatteryYield struct { + tried bool + until time.Time + active bool + maxChargeW float64 +} + +func (s *State) hasBatteryCharge() bool { + for _, log := range s.batteryCommands { + if _, _, latest, ok := log.span(s.now()); ok && latest > 0 { + return true + } + } + return false +} + +func (s *State) yieldBatteryBeforeEVCut(store *telemetry.Store, meter *telemetry.DerReading, r evMeterRoom, pool evPool, requiredW, gridW, pendingBatteryW float64, rise pendingLoad, fresh bool) bool { + y := &s.evLimit.batteryYield + if !fresh || !r.perPhase || pool.offerW <= 0 || requiredW <= 0 || s.SiteFuseVoltage <= 0 || s.SiteFusePhases <= 0 { + return false + } + // This hold uses only the installation's existing current allowance. + // Include offers still on their way; a cut never funds a car increase. + amps, present, valid := phaseCurrentsA(meter, s, gridW) + if !present || !valid || gridW+rise.w+pendingBatteryW > s.SiteFuseAmps*s.SiteFuseVoltage*float64(s.SiteFusePhases) { + return false + } + pendingA := pendingBatteryW / (s.SiteFuseVoltage * float64(s.SiteFusePhases)) + for i, a := range amps { + if math.Max(a, math.Sqrt(s.fuseHeat.sq[i]))+rise.phaseA[i]+pendingA > s.SiteFuseAmps { + return false + } + } + var available, commanded float64 + for driver, log := range s.batteryCommands { + h := store.DriverHealth(driver) + if h == nil || !h.IsOnline() { + continue + } + _, high, latest, ok := log.span(s.now()) + if ok && finiteFuseValue(high) && finiteFuseValue(latest) { + available += math.Max(0, high) + commanded += math.Max(0, latest) + } + } + if available+1e-6 < requiredW { + return false + } + // Removing balanced charge must not overload an exporting phase. + cutA := requiredW / (s.SiteFuseVoltage * float64(s.SiteFusePhases)) + for _, a := range amps { + if a-cutA < -s.SiteFuseAmps { + return false + } + } + if !y.tried { + y.tried, y.until = true, s.now().Add(evSettle) + slog.Info("EV priority: battery charging yields before the car", + "battery_reduction_w", requiredW, "car_offer_w", pool.offerW, "until", y.until) + } + if !s.now().Before(y.until) { + return false + } + y.active, y.maxChargeW = true, math.Max(0, commanded-requiredW) + return true +} + +func (s *State) applyEVBatteryYield(targets []DispatchTarget) []DispatchTarget { + if !s.evLimit.batteryYield.active || !s.now().Before(s.evLimit.batteryYield.until) { + return targets + } + var chargeW float64 + for _, target := range targets { + chargeW += math.Max(0, target.TargetW) + } + capW := s.evLimit.batteryYield.maxChargeW + if chargeW <= capW || chargeW <= 0 { + return targets + } + for i := range targets { + if targets[i].TargetW > 0 { + targets[i].TargetW *= capW / chargeW + targets[i].Clamped = true + } + } + return targets +} diff --git a/go/internal/control/ev_battery_priority_test.go b/go/internal/control/ev_battery_priority_test.go new file mode 100644 index 000000000..f84b0d96c --- /dev/null +++ b/go/internal/control/ev_battery_priority_test.go @@ -0,0 +1,128 @@ +package control + +import ( + "fmt" + "testing" + "testing/synctest" + "time" + + "github.com/srcfl/ftw/go/internal/loadpoint" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// #1868: 16 A, 6 A on all three car phases, and a 0.1 A working-limit +// overage. The 4 kW battery is the continuous load that can yield first. +func issue1868Site(t *testing.T) (*telemetry.Store, *State, []loadpoint.State, []loadpoint.Config) { + t.Helper() + tel, st := evSplitFixture(t, 9084, []float64{15.1, 12.5, 11.9}, 4140, "3p") + st.SiteFuseAmps, st.SiteFuseSafetyA = 16, .5 + st.Mode = ModeCharge + st.DriverLimits = map[string]PowerLimits{"battery": {MaxChargeW: 6000, MaxDischargeW: 6000}} + soc := .4 + tel.Update("battery", telemetry.DerBattery, 4000, &soc, nil) + tel.RecordDriverSuccess("battery") + sent(st, "ev", 4140) + sent(st, "battery", 4000) + points := []loadpoint.State{{ID: "rav4", DriverName: "car", PluggedIn: true, CommandedKnown: true, CommandedW: 4140, CommandedPhases: 3}} + configs := []loadpoint.Config{{ID: "rav4", DriverName: "car", PhaseMode: "3p", MinChargeW: 4140, MaxChargeW: 4140, AllowedStepsW: []float64{0, 4140}}} + return tel, st, points, configs +} + +func TestIssue1868BatteryChargeYieldsBeforeTheCar(t *testing.T) { + for _, mode := range AllModes() { + t.Run(string(mode), func(t *testing.T) { + tel, st, points, configs := issue1868Site(t) + cap, known := EVFuseBudget(tel, st, points, configs, 11040) + if !known || cap != 4140 { + t.Fatalf("71 W relief shed the 4140 W car: cap=%v known=%v", cap, known) + } + st.SetEVCommanded(points) + st.Mode = mode + st.SetEVFuseDemands([]loadpoint.FuseDemand{{DriverName: "car", PowerW: 4140, PhaseMode: "3p"}}) + targets := ComputeDispatch(tel, st, map[string]float64{"battery": 12200}, 11040) + if len(targets) != 1 { + t.Fatalf("missing battery command: %+v", targets) + } + for _, target := range targets { + if target.TargetW > 3931.001 { + t.Fatalf("%s left the car's relief in the battery: %+v", mode, target) + } + if mode == ModeCharge && target.TargetW < 3800 { + t.Fatalf("small overage needlessly stopped battery charging: %+v", target) + } + } + for _, target := range SelfTuneDispatch(tel, st, map[string]float64{"battery": 12200}, 11040, "battery", 6000) { + if target.TargetW > 3931.001 { + t.Fatalf("self-tune took the car's relief: %+v", target) + } + } + }) + } +} + +func TestEVPriorityCannotSpendUnmeasuredBatteryRelief(t *testing.T) { + tel, st, points, configs := issue1868Site(t) + st.SetEVFuseDemands([]loadpoint.FuseDemand{{DriverName: "car", PowerW: 10350, PhaseMode: "3p"}}) + cap, _ := EVFuseBudget(tel, st, points, configs, 11040) + if cap > points[0].CommandedW { + t.Fatalf("battery cut became an unmeasured car rise: %v W", cap) + } +} + +func TestEVPriorityFallsBackWhenTheBatteryCannotYield(t *testing.T) { + for _, tc := range []struct { + name string + set func(*telemetry.Store, *State) + }{ + {"no command", func(_ *telemetry.Store, st *State) { st.batteryCommands = nil }}, + {"not charging", func(_ *telemetry.Store, st *State) { sent(st, "battery", 0) }}, + {"insufficient charge", func(_ *telemetry.Store, st *State) { sent(st, "battery", 10) }}, + {"offline", func(tel *telemetry.Store, _ *State) { tel.Remove("battery") }}, + {"stale meter", func(tel *telemetry.Store, _ *State) { + tel.Get("meter", telemetry.DerMeter).UpdatedAt = time.Now().Add(-time.Minute) + }}, + {"past fuse rating", func(tel *telemetry.Store, _ *State) { + tel.Update("meter", telemetry.DerMeter, 10000, nil, []byte(`{"l1_a":16.1,"l2_a":12.5,"l3_a":11.9}`)) + }}, + {"unseen battery rise", func(_ *telemetry.Store, st *State) { sent(st, "battery", 0, 4000) }}, + } { + t.Run(tc.name, func(t *testing.T) { + tel, st, points, configs := issue1868Site(t) + tc.set(tel, st) + cap, _ := EVFuseBudget(tel, st, points, configs, 11040) + if cap >= 4140 || st.evLimit.batteryYield.active { + t.Fatalf("unsafe battery priority: cap=%v yield=%+v", cap, st.evLimit.batteryYield) + } + }) + } +} + +func TestEVPriorityWaitForBatteryHasAFixedDeadline(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + tel, st, points, configs := issue1868Site(t) + var deadline time.Time + for tick := 0; tick <= 6; tick++ { + // The battery accepts lower commands, but the site meter never + // shows the reduction. Repeated commands cannot renew the wait. + cap, _ := EVFuseBudget(tel, st, points, configs, 11040) + if tick == 0 { + deadline = st.evLimit.batteryYield.until + } + st.SetEVCommanded(points) + if tick < 4 && cap != 4140 { + t.Fatalf("tick %d: car cut before the response wait: %v", tick, cap) + } + if tick >= 4 && cap >= 4140 { + t.Fatalf("tick %d: ignored battery cut holds the car forever: %v", tick, cap) + } + if st.evLimit.batteryYield.until != deadline { + t.Fatalf("tick %d renewed the deadline", tick) + } + _ = ComputeDispatch(tel, st, map[string]float64{"battery": 12200}, 11040) + time.Sleep(5 * time.Second) + tel.Update("meter", telemetry.DerMeter, 9084, nil, []byte(`{"l1_a":15.1,"l2_a":12.5,"l3_a":11.9}`)) + tel.RecordDriverSuccess("meter") + } + t.Logf("car protected while battery responded; fallback deadline %s", fmt.Sprint(evSettle)) + }) +} diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index 3d3379b58..aa46d4acc 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -3,6 +3,7 @@ package control import ( "context" "encoding/json" + "fmt" "math" "math/rand" "testing" @@ -13,94 +14,98 @@ import ( ) func TestJoinedEVWaitsForMeasuredBatteryBackoffThenResumes(t *testing.T) { - now := time.Now().Truncate(time.Second) - const houseW, desiredEVW = 5000.0, 10350.0 - actualBattery, actualEV := 8000.0, 0.0 - config := loadpoint.Config{ID: "garage", DriverName: "charger", MinChargeW: 4140, MaxChargeW: desiredEVW, - PhaseMode: "3p", AllowedStepsW: []float64{0, 4140, 4830, 5520, 6210, 6900, 7590, 8280, 8970, 9660, 10350}} - mgr := loadpoint.NewManager() - mgr.Load([]loadpoint.Config{config}) - store := telemetry.NewStore() - dir := SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), BatteryEnergyWh: 2500, Strategy: "arbitrage"} - st := newStateWithEnergyDispatch(dir, "meter") - st.clock = func() time.Time { return now } - st.SiteFuseAmps, st.SiteFuseVoltage, st.SiteFusePhases, st.SiteFuseSafetyA = 25, 230, 3, 1 - st.SlewEnabled = false - st.DriverLimits = map[string]PowerLimits{"pixii": {MaxChargeW: 10000, MaxDischargeW: 10000}} - var sampledPhaseA float64 - controller := loadpoint.NewController(mgr, - func(time.Time) (loadpoint.Directive, bool) { return loadpoint.Directive{}, false }, - func(string) (loadpoint.EVSample, bool) { - return loadpoint.EVSample{Connected: true, RequestActive: true, PowerW: actualEV, PowerAt: now, SessionWhUnavailable: true}, true - }, - func(_ context.Context, _ string, payload []byte) error { - var cmd struct { - Action string `json:"action"` - PowerW float64 `json:"power_w"` - } - if err := json.Unmarshal(payload, &cmd); err != nil { - return err + for _, desiredEVW := range []float64{4140, 10350} { + t.Run(fmt.Sprintf("%.0fW", desiredEVW), func(t *testing.T) { + now := time.Now().Truncate(time.Second) + const houseW = 5000.0 + actualBattery, actualEV := 8000.0, 0.0 + config := loadpoint.Config{ID: "garage", DriverName: "charger", MinChargeW: 4140, MaxChargeW: desiredEVW, + PhaseMode: "3p", AllowedStepsW: []float64{0, 4140, 4830, 5520, 6210, 6900, 7590, 8280, 8970, 9660, 10350}} + mgr := loadpoint.NewManager() + mgr.Load([]loadpoint.Config{config}) + store := telemetry.NewStore() + dir := SlotDirective{SlotStart: now, SlotEnd: now.Add(15 * time.Minute), BatteryEnergyWh: 2500, Strategy: "arbitrage"} + st := newStateWithEnergyDispatch(dir, "meter") + st.clock = func() time.Time { return now } + st.SiteFuseAmps, st.SiteFuseVoltage, st.SiteFusePhases, st.SiteFuseSafetyA = 25, 230, 3, 1 + st.SlewEnabled = false + st.DriverLimits = map[string]PowerLimits{"pixii": {MaxChargeW: 10000, MaxDischargeW: 10000}} + var sampledPhaseA float64 + controller := loadpoint.NewController(mgr, + func(time.Time) (loadpoint.Directive, bool) { return loadpoint.Directive{}, false }, + func(string) (loadpoint.EVSample, bool) { + return loadpoint.EVSample{Connected: true, RequestActive: true, PowerW: actualEV, PowerAt: now, SessionWhUnavailable: true}, true + }, + func(_ context.Context, _ string, payload []byte) error { + var cmd struct { + Action string `json:"action"` + PowerW float64 `json:"power_w"` + } + if err := json.Unmarshal(payload, &cmd); err != nil { + return err + } + if cmd.Action == "ev_set_current" { + actualEV = cmd.PowerW + // The physical battery may ignore a reduction. Check this at + // the EV send, before a later battery command can conceal it. + if phase := (houseW + actualBattery + actualEV) / 690; phase > 24.001 { + t.Fatalf("EV spent unmeasured battery relief: %.1f A", phase) + } + } + return nil + }) + controller.SetSiteFuse(loadpoint.SiteFuse{MaxAmps: 25, Voltage: 230, PhaseCnt: 3}) + controller.SetManualHold(config.ID, loadpoint.ManualHold{PowerW: desiredEVW, PhaseMode: "3p", Persistent: true}) + controller.SetFuseEVMax(func() (float64, bool) { return EVFuseBudget(store, st, mgr.States(), controller.FuseConfigs(), 17250) }) + controller.SetFusePhaseRoomA(func() (float64, bool) { return EVFusePhaseRoomA(st) }) + emit := func(driver string, kind telemetry.DerType, watts float64) { + d := map[string]any{"control_power_available": true, "control_power_observed_at": now.Format(time.RFC3339Nano)} + if kind == telemetry.DerMeter { + d["l1_a"], d["l2_a"], d["l3_a"] = sampledPhaseA, sampledPhaseA, sampledPhaseA + } + if kind == telemetry.DerEV { + d["power_max_age_s"] = 5 // A local charger that answers within seconds. + } + data, _ := json.Marshal(d) + soc := .5 + store.Update(driver, kind, watts, &soc, data) + store.Get(driver, kind).UpdatedAt = now + store.RecordDriverSuccess(driver) } - if cmd.Action == "ev_set_current" { - actualEV = cmd.PowerW - // The physical battery may ignore a reduction. Check this at - // the EV send, before a later battery command can conceal it. - if phase := (houseW + actualBattery + actualEV) / 690; phase > 24.001 { - t.Fatalf("EV spent unmeasured battery relief: %.1f A", phase) + var obeyedAt, resumedAt time.Time + for tick := 0; tick < 30; tick++ { + now = now.Add(5 * time.Second) + if tick == 3 { + actualBattery, obeyedAt = 0, now // Only now does the battery obey. + } + sampledPhaseA = (houseW + actualBattery + actualEV) / 690 + emit("pixii", telemetry.DerBattery, actualBattery) + emit(config.DriverName, telemetry.DerEV, actualEV) + emit("meter", telemetry.DerMeter, houseW+actualBattery+actualEV) + controller.TickWithDispatch(context.Background(), now, true) + st.SetEVCommanded(mgr.States()) + st.SetEVFuseDemands(controller.FuseDemands()) + targets := ComputeDispatch(store, st, caps(map[string]float64{"pixii": 15000}), 17250) + if len(targets) != 1 || targets[0].TargetW > 16560-houseW-desiredEVW+.001 { + t.Fatalf("tick %d: battery did not yield to the EV: %+v", tick, targets) + } + if actualEV > 0 && resumedAt.IsZero() { + resumedAt = now + } + if !obeyedAt.IsZero() { + actualBattery = math.Max(0, targets[0].TargetW) + } + if (houseW+actualBattery+actualEV)/690 > 24.001 { + t.Fatalf("tick %d: battery took the EV's headroom: EV %.0f battery %.0f W", tick, actualEV, actualBattery) } } - return nil + if resumedAt.IsZero() || resumedAt.Sub(obeyedAt) < evRestartDwell { + t.Fatalf("EV resumed at %v, battery obeyed at %v: want a %v dwell on measured room", resumedAt, obeyedAt, evRestartDwell) + } + if actualEV < desiredEVW { + t.Fatalf("EV stuck at %.0f W after recovery", actualEV) + } }) - controller.SetSiteFuse(loadpoint.SiteFuse{MaxAmps: 25, Voltage: 230, PhaseCnt: 3}) - controller.SetManualHold(config.ID, loadpoint.ManualHold{PowerW: desiredEVW, PhaseMode: "3p", Persistent: true}) - controller.SetFuseEVMax(func() (float64, bool) { return EVFuseBudget(store, st, mgr.States(), controller.FuseConfigs(), 17250) }) - controller.SetFusePhaseRoomA(func() (float64, bool) { return EVFusePhaseRoomA(st) }) - emit := func(driver string, kind telemetry.DerType, watts float64) { - d := map[string]any{"control_power_available": true, "control_power_observed_at": now.Format(time.RFC3339Nano)} - if kind == telemetry.DerMeter { - d["l1_a"], d["l2_a"], d["l3_a"] = sampledPhaseA, sampledPhaseA, sampledPhaseA - } - if kind == telemetry.DerEV { - d["power_max_age_s"] = 5 // A local charger that answers within seconds. - } - data, _ := json.Marshal(d) - soc := .5 - store.Update(driver, kind, watts, &soc, data) - store.Get(driver, kind).UpdatedAt = now - store.RecordDriverSuccess(driver) - } - var obeyedAt, resumedAt time.Time - for tick := 0; tick < 30; tick++ { - now = now.Add(5 * time.Second) - if tick == 3 { - actualBattery, obeyedAt = 0, now // Only now does the battery obey. - } - sampledPhaseA = (houseW + actualBattery + actualEV) / 690 - emit("pixii", telemetry.DerBattery, actualBattery) - emit(config.DriverName, telemetry.DerEV, actualEV) - emit("meter", telemetry.DerMeter, houseW+actualBattery+actualEV) - controller.TickWithDispatch(context.Background(), now, true) - st.SetEVCommanded(mgr.States()) - st.SetEVFuseDemands(controller.FuseDemands()) - targets := ComputeDispatch(store, st, caps(map[string]float64{"pixii": 15000}), 17250) - if len(targets) != 1 || targets[0].TargetW > 1210.001 { - t.Fatalf("tick %d: battery did not yield to the EV: %+v", tick, targets) - } - if actualEV > 0 && resumedAt.IsZero() { - resumedAt = now - } - if !obeyedAt.IsZero() { - actualBattery = math.Max(0, targets[0].TargetW) - } - if (houseW+actualBattery+actualEV)/690 > 24.001 { - t.Fatalf("tick %d: battery took the EV's headroom: EV %.0f battery %.0f W", tick, actualEV, actualBattery) - } - } - if resumedAt.IsZero() || resumedAt.Sub(obeyedAt) < evRestartDwell { - t.Fatalf("EV resumed at %v, battery obeyed at %v: want a %v dwell on measured room", resumedAt, obeyedAt, evRestartDwell) - } - if actualEV < 9660 { - t.Fatalf("EV stuck at %.0f W after recovery", actualEV) } } diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 51e492c4f..e07c63e25 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -323,6 +323,7 @@ type evMeterLimit struct { overOffers map[string]float64 // each charger's offer when that run began idleWh float64 // import since roomSince, for the ceiling's start test byImport bool // the hour's import limit, not the fuse, left less room at readingAt + batteryYield evBatteryYield } type evPool struct { @@ -346,7 +347,7 @@ type evPool struct { // stay at or below fuseHourFactor (unshownOrders). // EVFusePhaseRoomA gives the same room per phase to the split between cars. // An idle pool starts only after the meter has kept showing -// room for its minimum plus a step. Each reading acts once, so a silent +// room for its minimum below the working limit. Each reading acts once, so a silent // meter can never raise or restart a charge. func EVFuseBudget(store *telemetry.Store, state *State, points []loadpoint.State, configs []loadpoint.Config, fuseMaxW float64) (float64, bool) { if store == nil || state == nil || !finiteFuseValue(fuseMaxW) || fuseMaxW <= 0 { @@ -372,12 +373,12 @@ func EVFuseBudget(store *telemetry.Store, state *State, points []loadpoint.State } state.recordEVOffers(store, points) if !lim.set || meter.UpdatedAt.After(lim.readingAt) { - state.stepEVMeterLimit(meter, gridW, pool, fuseMaxW) + state.stepEVMeterLimit(store, meter, gridW, pool, fuseMaxW) } return lim.capW, true } -func (s *State) stepEVMeterLimit(meter *telemetry.DerReading, gridW float64, pool evPool, fuseMaxW float64) { +func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerReading, gridW float64, pool evPool, fuseMaxW float64) { lim, now, at := &s.evLimit, s.now(), meter.UpdatedAt first, prevAt := !lim.set, lim.readingAt gap := first || at.Sub(prevAt) > evSettle @@ -397,6 +398,10 @@ func (s *State) stepEVMeterLimit(meter *telemetry.DerReading, gridW float64, poo r := s.evMeterRoom(meter, gridW, pool.phases, fuseMaxW, s.withBatteryOrders(s.pendingLoad(at), pending)) _, fresh := qualifiedFuseObservation(meter, now) fresh = fresh && r.measured + lim.batteryYield.active = false + if fresh && !r.overLimit && r.limitW >= 0 { + lim.batteryYield = evBatteryYield{} + } lim.phaseRoomA, lim.phaseRoomKnown = 0, r.phaseRoomKnown if fresh { lim.phaseRoomA = r.phaseRoomA @@ -457,6 +462,13 @@ func (s *State) stepEVMeterLimit(meter *telemetry.DerReading, gridW float64, poo } } if over { + requiredW := math.Max(0, latestW-capW) + if !byImport && pool.phases > 0 { + requiredW *= float64(s.SiteFusePhases) / pool.phases + } + if s.yieldBatteryBeforeEVCut(store, meter, r, pool, requiredW, gridW, pending, rise, fresh) { + capW = latestW // Keep the existing car order while the battery yields. + } lim.byImport = byImport lim.capW, lim.roomSince = math.Min(prev, math.Max(0, capW)), time.Time{} if lim.capW < prev { @@ -490,11 +502,17 @@ func (s *State) stepEVMeterLimit(meter *telemetry.DerReading, gridW float64, poo // One step at most, and a step of room stays free. lim.capW = math.Max(lim.capW, math.Min(lim.capW+step, peakW+room-step)) } + // The battery leaves room for the car's demand, not a further unused + // step. Let the last step use that measured room below the working + // limit, or concurrent battery charge can keep the car short forever. + if remaining := pool.wantW - peakW; s.hasBatteryCharge() && remaining > 0 && remaining <= step && room+1e-6 >= remaining && now.Sub(lim.cutAt) >= evSettle { + lim.capW = math.Max(lim.capW, pool.wantW) + } } // stepEVIdleStart starts an idle pool once the meter has kept showing room -// for evRestartDwell: room on every reading for its minimum plus a step -// below the fuse. Under a measured hour, the ceiling's part is judged on the +// for evRestartDwell: room on every reading for its minimum below the +// fuse's working limit. Under a measured hour, the ceiling's part is judged on the // dwell's mean import, the house's load rather than one reading of it, and // the minimum needs no step of margin there: a short overage waits. func (s *State) stepEVIdleStart(r evMeterRoom, gridW float64, pool evPool, first, gap, fresh bool, at, prevAt time.Time, pending, step float64) { @@ -513,7 +531,11 @@ func (s *State) stepEVIdleStart(r evMeterRoom, gridW float64, pool evPool, first if fresh { room = math.Max(0, perReadingW) // r holds our battery orders. } - if room < pool.minW+step { + minimumRoom := pool.minW + if !r.hourly && r.riseW < r.startW { + minimumRoom += step // Keep the hour's separate rise margin. + } + if room+1e-6 < minimumRoom { lim.roomSince = time.Time{} return } @@ -530,7 +552,7 @@ func (s *State) stepEVIdleStart(r evMeterRoom, gridW float64, pool evPool, first if dwell < evRestartDwell { return } - lim.capW = room - step + lim.capW = math.Max(pool.minW, room-step) if !r.hourly { return } diff --git a/go/internal/control/ev_fuse_budget_test.go b/go/internal/control/ev_fuse_budget_test.go index add26c76a..0f1fa537d 100644 --- a/go/internal/control/ev_fuse_budget_test.go +++ b/go/internal/control/ev_fuse_budget_test.go @@ -727,7 +727,7 @@ func TestEVHardLimitStopsOnlyWhenOverageExceedsOfferLessMinimum(t *testing.T) { } } -// An idle car starts with a step of margin under the measured room, and a +// An idle car's minimum must fit below the working limit, and a // single-phase or auto car may land its whole offer on the worst phase. func TestEVHardLimitIdleStartNeedsRoomOnDeclaredPhases(t *testing.T) { for _, tc := range []struct { @@ -739,7 +739,8 @@ func TestEVHardLimitIdleStartNeedsRoomOnDeclaredPhases(t *testing.T) { {"legacy_default", "", 5, (24 - 5 - 1) * 690}, {"1p_room", "1p", 5, (24 - 5 - 1) * 230}, {"auto_room", "auto", 5, (24 - 5 - 1) * 230}, - {"3p_below_minimum", "3p", 21.5, 0}, // 1,725 W < 1,380 + 690 W + {"3p_minimum_fits", "3p", 21.5, 1380}, + {"3p_below_minimum", "3p", 22.5, 0}, // 1,035 W < 1,380 W } { t.Run(tc.name, func(t *testing.T) { store, state, points, configs := evMeterBudgetFixture(t, tc.worstA*690, []float64{tc.worstA, tc.worstA, tc.worstA}, 0, tc.phase) diff --git a/go/internal/control/ev_priority_sitesim_test.go b/go/internal/control/ev_priority_sitesim_test.go new file mode 100644 index 000000000..a93519da8 --- /dev/null +++ b/go/internal/control/ev_priority_sitesim_test.go @@ -0,0 +1,84 @@ +package control + +import ( + "fmt" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/loadpoint" + "github.com/srcfl/ftw/go/internal/sitesim" +) + +// Exercise the whole loop, including delayed physical responses and fuse +// heating. A small house step must take battery charge first; a house +// that cannot fit the car must stop it, then let it restart without input. +func TestIssue1868ClosedLoopPriorityAndRecovery(t *testing.T) { + for _, planned := range []bool{false, true} { + for _, phases := range []int{1, 3} { + for _, delay := range []time.Duration{5 * time.Second, 40 * time.Second, 120 * time.Second} { + t.Run(fmt.Sprintf("plan=%v/phases=%d/charger=%s", planned, phases, delay), func(t *testing.T) { + minimum := 6 * 230 * float64(phases) + sc := simScenario{name: "issue1868", run: 20 * time.Minute, + plant: func(p *sitesim.Plant) { + p.Fuse.RatingA, p.HouseW = 16, houseA(3, 2, 2) + p.EVSE.Phases, p.EVSE.Delay = phases, delay + p.Car.Phases, p.Car.MaxW = phases, minimum + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 6000, MaxDischargeW: 6000, CapacityWh: 12200, SoC: .3, Latency: 2 * time.Second} + p.Events = []sitesim.Event{ + {At: 5 * time.Minute, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.HouseW = houseA(3.1, 2, 2) }}, + {At: 10 * time.Minute, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.HouseW = houseA(16, 16, 16) }}, + {At: 14 * time.Minute, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.HouseW = houseA(3, 2, 2) }}, + } + }, + lp: func(c *loadpoint.Config) { + c.MinChargeW, c.MaxChargeW = minimum, minimum + c.PhaseMode = fmt.Sprintf("%dp", phases) + c.AllowedStepsW = []float64{0, minimum} + }, + setup: planBatteryCharge(6000), + } + if planned { + sc.plan = planEV(minimum) + } + sc.expect = []simExpect{ + + {9 * time.Minute, func(s *simSite) error { + if s.p.EVSE.DrawW < minimum-.1 { + return fmt.Errorf("car yielded to battery: car %.0f, battery %.0f W", s.p.EVSE.DrawW, s.batteryW()) + } + for _, cmd := range s.commands { + if cmd.device == "evse" && cmd.at.After(simStart.Add(5*time.Minute)) && cmd.w < minimum-.1 { + return fmt.Errorf("small step cut the car: %v", cmd) + } + } + return nil + }}, + {14*time.Minute - time.Second, func(s *simSite) error { + if s.p.EVSE.DrawW > 0 { + return fmt.Errorf("car did not stop when house used the fuse: %.0f W", s.p.EVSE.DrawW) + } + return nil + }}, + {20*time.Minute - time.Second, func(s *simSite) error { + if s.p.EVSE.DrawW < minimum-.1 { + return fmt.Errorf("car failed to restart: %.0f W; battery %.0f W", s.p.EVSE.DrawW, s.batteryW()) + } + return nil + }}, + } + s := runSimScenario(sc, simStart) + + if s.p.Fuse.Blown != [3]bool{} { + t.Fatalf("fuse opened: %+v", s.p.Fuse) + } + // Outside house steps may exceed the working margin during device + // response. The fixture checks unsafe raises and sustained overages. + if s.failure != "" { + t.Fatal(s.failure) + } + t.Logf("car %.0f W, residual battery %.0f W, peak phase %.2f A", s.p.EVSE.DrawW, s.batteryW(), s.peakA) + }) + } + } + } +} diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 6167d172d..6022cd157 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -361,7 +361,9 @@ func (s *simSite) check() { s.fail("over Core's limit for more than %v (heat %.1f A, limit %.0f A)", allow, math.Sqrt(max(s.heat[0], s.heat[1], s.heat[2])), limitA) } // (b) With the meter on schedule, room for the car's minimum and a car - // that asks, the car draws within a minute plus the charger's delay. + // that asks, the car draws within a minute plus the charger's delay + // and the battery-command settling window. A battery raise may still + // occupy that window even after the physical meter shows it. if !s.wantsCharge() { s.needSince = time.Time{} } else if s.needSince.IsZero() { @@ -369,7 +371,7 @@ func (s *simSite) check() { } if !s.needSince.IsZero() && p.EVSE.DrawW <= 0 { s.idleWithRoom += sitesim.Step - if wait := time.Minute + p.EVSE.Delay; now.Sub(s.needSince) > wait { + if wait := time.Minute + p.EVSE.Delay + evSettle; now.Sub(s.needSince) > wait { s.fail("the car is idle after %v with room for it", wait) } } @@ -388,6 +390,11 @@ func (s *simSite) wantsCharge() bool { if p.Car == nil || !p.Car.Plugged || p.Offline("evse") || !s.downUntil.IsZero() || p.Now.Sub(s.meterAt) > max(p.Meter.Every, sitesim.Step)+sitesim.Step { return false } + // After a real overload, an idle car must wait for the fuse to cool. + // Its recovery deadline starts when that heat no longer blocks a start. + if e.DrawW <= 0 && max(s.heat[0], s.heat[1], s.heat[2]) > math.Pow(p.Fuse.RatingA-evPhaseMarginA, 2) { + return false + } phases := min(e.Phases, p.Car.Phases) var baseW float64 for i, houseW := range p.HouseW { diff --git a/go/test/site/catalog_test.go b/go/test/site/catalog_test.go index b33feacea..87108f722 100644 --- a/go/test/site/catalog_test.go +++ b/go/test/site/catalog_test.go @@ -20,6 +20,7 @@ var provenance = map[string]struct { catalog []string sources []string }{ + "s18-16": {nil, []string{"https://github.com/srcfl/ftw/issues/1868"}}, "s0-25": {[]string{"home-070", "ocpp-011", "ocpp-013", "ui-052"}, []string{"https://github.com/srcfl/ftw/pull/1779", "https://github.com/srcfl/ftw/pull/1790"}}, "s0b-25": {[]string{"home-070", "ocpp-011", "ocpp-013", "ui-052"}, []string{"https://github.com/srcfl/ftw/pull/1790"}}, "s1-16": {nil, []string{"simulator test before beta 0.155.0, 21 Oct 2026"}}, diff --git a/go/test/site/ev_battery_priority_test.go b/go/test/site/ev_battery_priority_test.go new file mode 100644 index 000000000..ab11ca8af --- /dev/null +++ b/go/test/site/ev_battery_priority_test.go @@ -0,0 +1,63 @@ +//go:build unix + +package site + +// #1868: the car has only [0, 4140] W, while the battery can charge at +// 6000 W. The actual devices run over Modbus and OCPP; marks and the +// physical meter record let the judge see which device yielded. +func s18(c *runCtx) (map[string]any, error) { + err := with(c, stackSpec{fuseA: 16, loadsW: houseA(3), socPct: 40, + lpExtra: map[string]any{"min_charge_w": 4140, "max_charge_w": 4140, "phase_mode": "3p", "allowed_steps_w": []float64{0, 4140}}}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + if err := st.post("/api/battery/manual_hold", map[string]any{"direction": "charge", "power_w": 6000, "hold_s": 1800}, nil); err != nil { + return err + } + st.mark("charge_now") + if err := st.chargeNow("garage", 6, "3p", 4140); err != nil { + return err + } + sleepS(120) + st.mark("small_step") + if err := st.setLoadsA(3.1); err != nil { + return err + } + sleepS(90) + st.mark("no_room") + if err := st.setLoadsA(16); err != nil { + return err + } + sleepS(90) + st.mark("room_returns") + if err := st.setLoadsA(3); err != nil { + return err + } + sleepS(150) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "s18", "fuse": 16, "battery_hold_w": 6000, "car_w": 4140}, err +} + +func judgeS18(d *runData) (metrics, []criterion) { + t0, small, none, back, end := d.marks["charge_now"], d.marks["small_step"], d.marks["no_room"], d.marks["room_returns"], d.marks["end"] + pre := d.window(small-20, small) + minor := d.window(small+10, none) + paused := d.window(back-20, back) + recovered := d.window(end-30, end) + carMin := func(w []*sample) float64 { return minOf(w, func(r *sample) float64 { return carW(r, 0) }) } + restart := d.firstT(back, func(r *sample) bool { return carW(r, 0) >= 4100 }) + batteryBefore, batteryAfter := meanOf(pre, batSigned), meanOf(d.window(none-20, none), batSigned) + m := metrics{"battery_before_w": batteryBefore, "battery_after_w": batteryAfter, "restart_s": restart, + "car_before_w": carMin(pre), "car_small_step_w": carMin(minor), "car_recovered_w": carMin(recovered), + "fuse_blown": anyBlown(d.samples), "max_i_before_house_overload": maxOf(d.window(t0, none), maxAbsI)} + return m, []criterion{ + crit("setup: car and battery charge together", len(pre) > 0 && carMin(pre) >= 4100 && batteryBefore > 1000), + crit("battery yields before the minimum-step car", len(minor) > 0 && carMin(minor) >= 4100 && batteryAfter < batteryBefore-40), + crit("car stops when house leaves no room", len(paused) > 0 && maxOf(paused, func(r *sample) float64 { return carW(r, 0) }) < 100), + crit("car restarts automatically within 150 s", le(restart, 150) && len(recovered) > 0 && carMin(recovered) >= 4100), + crit("own commands stay inside the rated fuse", maxOf(d.window(t0, none), maxAbsI) <= 16.01), + crit("fuse holds", !anyBlown(d.samples)), + } +} diff --git a/go/test/site/scenarios_test.go b/go/test/site/scenarios_test.go index 0e3258df4..8f987969d 100644 --- a/go/test/site/scenarios_test.go +++ b/go/test/site/scenarios_test.go @@ -30,6 +30,8 @@ type scenario struct { } var scenarios = []scenario{ + {name: "s18-16", dir: "s18-car-first-battery-charge-16A", minutes: 8, short: true, + run: s18, judge: judgeS18}, {name: "s0-25", dir: "s0-idle-charger-25A", minutes: 5.1, short: true, run: func(c *runCtx) (map[string]any, error) { return s0(c, 25, 60) }, judge: judgeS0}, {name: "s0b-25", dir: "s0b-idle-charger-default-hb-25A", minutes: 5.1,