diff --git a/.changeset/declined-car-retry.md b/.changeset/declined-car-retry.md new file mode 100644 index 000000000..4b6a2e852 --- /dev/null +++ b/.changeset/declined-car-retry.md @@ -0,0 +1,14 @@ +--- +"ftw": minor +--- + +A car that stopped asking for charge is no longer left out for the rest of +the plug-in. While it stays plugged in with a goal to meet, FTW plans it +again an hour after it declined, or when the next ready time starts. A car +that is full or at its own limit declines once more and is left out again +after 90 seconds, so FTW offers it current at most once an hour. FTW does +not retry when the goal is met, when the car reports it is done or at its +limit, after a one-time ready time has passed, or on a charger it only +observes. Unplugging, a higher goal and Charge now still act at once, and +the plan now follows a refusal and its end right away instead of at the +next scheduled replan. diff --git a/docs/architecture.md b/docs/architecture.md index 93fe750e6..31d2c990f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,6 +57,9 @@ plug sessions. Completion requires a live report from the session car's own source, made after the observed connection, and no measured charging. A car the box has not named cannot finish the goal. A charger declining current is reported as a refusal, never as an invented battery level or proof that the target was reached. +A car that declined stays out of the plan for an hour, or until the next +goal window, while it stays plugged in with a goal to meet. Then the plan +takes it in once more; a car that declines again costs one short offer. ### Cars diff --git a/go/cmd/ftw/ev_stop_replan.go b/go/cmd/ftw/ev_stop_replan.go index ae9504ec4..1358b86d2 100644 --- a/go/cmd/ftw/ev_stop_replan.go +++ b/go/cmd/ftw/ev_stop_replan.go @@ -17,3 +17,20 @@ func evStopNeedsReplan(lp loadpoint.State, prevW float64) bool { } return !lp.CommandedKnown || lp.CommandedW >= evStopLow } + +// declineReplanReason names a replan when a plugged-in car's refusal latch +// moved since the last tick (prevDeclined): the plan leaves the car out once +// it declined, and takes it in again once the latch ends (a retry, Charge +// now, a higher goal, measured charging). A scheduled replan would leave the +// old plan offering a declining car, or holding back a car that may charge, +// for up to its whole interval. +func declineReplanReason(lp loadpoint.State, prevDeclined bool) string { + declined := lp.PluggedIn && lp.ChargingDeclined + switch { + case declined && !prevDeclined: + return "loadpoint_declined" + case prevDeclined && !declined && lp.PluggedIn: + return "loadpoint_decline_ended" + } + return "" +} diff --git a/go/cmd/ftw/ev_stop_replan_test.go b/go/cmd/ftw/ev_stop_replan_test.go index f920f2922..09c76ea9c 100644 --- a/go/cmd/ftw/ev_stop_replan_test.go +++ b/go/cmd/ftw/ev_stop_replan_test.go @@ -27,3 +27,27 @@ func TestEVStopReplanOnlyWhenTheCarStoppedItself(t *testing.T) { } } } + +// The plan follows the refusal latch at once: it leaves a car out as soon as +// the car has declined, and takes it in as soon as the latch ends while the +// car is still plugged in (srcfl/ftw#2080). An unplug replans on its own. +func TestDeclineEdgesReplan(t *testing.T) { + for _, tc := range []struct { + name string + prev, now, plugged bool + want string + }{ + {"car declined", false, true, true, "loadpoint_declined"}, + {"refusal ended", true, false, true, "loadpoint_decline_ended"}, + {"unplugged", true, false, false, ""}, + {"still declined", true, true, true, ""}, + {"never declined", false, false, true, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + lp := loadpoint.State{PluggedIn: tc.plugged, ChargingDeclined: tc.now} + if got := declineReplanReason(lp, tc.prev); got != tc.want { + t.Fatalf("got %q want %q", got, tc.want) + } + }) + } +} diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index eb6c4c2d4..750c5111f 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -2066,6 +2066,14 @@ func main() { health := tel.DriverHealth(name) return health != nil && health.IsOnline() }) + // An observe-only or read-only charger is never offered current + // again after a refusal; an approved OCPP charger may be. + lpController.SetChargerControlAllowed(func(name string) bool { + if ocppSrv != nil && ocppSrv.Handler().IsOnline(name) && ocppSrv.Handler().IsApproved(name) { + return true + } + return reg.CanControl(name) + }) // Wire the site fuse so the per-phase EV clamp and the // phase-split derivation can use the actual site voltage and // breaker rating instead of hard-coding 230 V × 16 A. @@ -2942,6 +2950,9 @@ func main() { // Cooldown shares the fuse-replan cooldown to keep per-second flap // from spamming the optimizer. evDrawPrev := map[string]float64{} + // declinedPrev is each plugged-in car's refusal latch on the last tick; + // declineReplanReason replans when it moves. + declinedPrev := map[string]bool{} var lastEVStopReplan time.Time const evStopReplanCooldown = 60 * time.Second var staleDefaults staleSiteDefaultTracker @@ -3406,6 +3417,10 @@ func main() { "power_unavailable", lp.PowerUnavailable) } evDrawPrev[lp.ID] = curr + if reason := declineReplanReason(lp, declinedPrev[lp.ID]); reason != "" { + mpcSvc.RequestReplan(reason) + } + declinedPrev[lp.ID] = lp.PluggedIn && lp.ChargingDeclined } } diff --git a/go/internal/loadpoint/controller.go b/go/internal/loadpoint/controller.go index 462e9f80d..0e674beca 100644 --- a/go/internal/loadpoint/controller.go +++ b/go/internal/loadpoint/controller.go @@ -128,6 +128,9 @@ type Controller struct { vehicleRefreshTarget func(loadpointID string) (string, error) vehicleChargeState func(loadpointID string) (VehicleChargeState, bool) vehicleControlAllowed func(driver string) bool + // chargerControlAllowed is the charger driver's write authority. nil + // allows, as in narrow tests. + chargerControlAllowed func(driver string) bool // peakRemainingSurplusW is the best PV-minus-load surplus left today. // Below the 3Φ minimum, surplus_only locks 1Φ for the day. nil keeps 3Φ. @@ -611,6 +614,40 @@ func (c *Controller) canControlVehicle(driver string) bool { return c.vehicleControlAllowed == nil || c.vehicleControlAllowed(driver) } +// SetChargerControlAllowed checks the charger driver's write authority. A +// charger Core only observes is never offered current again on its own. +func (c *Controller) SetChargerControlAllowed(f func(string) bool) { + if c != nil { + c.chargerControlAllowed = f + } +} + +// retryDeclinedCar lets a car that declined current into the plan again +// when Manager.retryDeclinedCharging says the refusal is due for another +// offer. Charge now already retries at once, and a charger Core may not +// command, or a car whose own fresh reading is Complete or at its limit, +// is left alone. The plan then decides when the offer comes. +func (c *Controller) retryDeclinedCar(cfg Config, now time.Time) { + if st, ok := c.manager.State(cfg.ID); !ok || !st.ChargingDeclined { + return + } + if _, held := c.GetManualHold(cfg.ID, now); held { + return + } + if c.chargerControlAllowed != nil && !c.chargerControlAllowed(cfg.DriverName) { + return + } + carDone := false + if c.vehicleChargeState != nil { + if car, fresh := c.vehicleChargeState(cfg.ID); fresh { + carDone = car.State == "Complete" || car.Limit > 0 && car.SoC >= car.Limit + } + } + if c.manager.retryDeclinedCharging(cfg.ID, now, carDone) { + slog.Info("loadpoint: planning a car again that declined current", "lp", cfg.ID, "retry_interval", DeclineRetryInterval) + } +} + // SetVehicleRefreshTarget selects an authorized telemetry recipient from // configuration. It must not require a fresh SoC or permit charging. func (c *Controller) SetVehicleRefreshTarget(f func(string) (string, error)) { @@ -1462,6 +1499,7 @@ func (c *Controller) tickOne(ctx context.Context, now time.Time, lpCfg Config, s // but do not advance completion timers or perform wake side effects. return } + c.retryDeclinedCar(lpCfg, now) // Wallbox just started delivering current: fire a wake at the // bound vehicle so the next vehicle-driver poll comes back with // fresh charging_state / charge_limit_pct / SoC. Gated by diff --git a/go/internal/loadpoint/controller_decline_retry_test.go b/go/internal/loadpoint/controller_decline_retry_test.go new file mode 100644 index 000000000..aae3c778f --- /dev/null +++ b/go/internal/loadpoint/controller_decline_retry_test.go @@ -0,0 +1,253 @@ +package loadpoint + +import ( + "context" + "testing" + "time" +) + +// declineRetryRig drives one charger through the field case of +// srcfl/ftw#2080. The plan offers the car current only while the loadpoint +// has not latched a refusal, as Core's planner does. The car declines every +// offer when refuses is set. Under Core's own 0 A the charger reports the car +// as asking, as an Easee does with reason 52. +type declineRetryRig struct { + t *testing.T + c *Controller + cfg Config + dir *Directive + samples map[string]EVSample + clock time.Time + refuses bool + offers []time.Time // when an offer began after Core held 0 A +} + +func newDeclineRetryRig(t *testing.T) *declineRetryRig { + t.Helper() + r := &declineRetryRig{ + t: t, + cfg: reasonLoadpoint(), + dir: &Directive{}, + clock: time.Date(2026, 11, 24, 21, 45, 0, 0, time.UTC), + } + r.samples = map[string]EVSample{r.cfg.DriverName: {Connected: true, PowerW: 11000, RequestActive: true}} + r.c = newTestController(t, []Config{r.cfg}, r.dir, r.samples, &fakeSender{}) + r.c.manager.SetNowFn(func() time.Time { return r.clock }) + r.c.manager.SetLocation(time.UTC) + r.c.manager.SetTarget(r.cfg.ID, 1, r.clock.Add(9*time.Hour)) + return r +} + +func (r *declineRetryRig) state() State { + r.t.Helper() + st, ok := r.c.manager.State(r.cfg.ID) + if !ok { + r.t.Fatal("loadpoint missing") + } + return st +} + +// step advances the clock and runs one control tick the way main does: +// roll schedules, plan, then the controller. +func (r *declineRetryRig) step(d time.Duration) { + r.t.Helper() + before := r.state() + r.clock = r.clock.Add(d) + offered := before.CommandedKnown && before.CommandedW >= DeliveringW + switch { + case !r.refuses: + r.samples[r.cfg.DriverName] = EVSample{Connected: true, PowerW: before.CommandedW, RequestActive: true} + case offered: + r.samples[r.cfg.DriverName] = EVSample{Connected: true, PowerW: 0, RequestActive: false} + default: + r.samples[r.cfg.DriverName] = EVSample{Connected: true, PowerW: 0, RequestActive: true} + } + r.c.manager.RollSchedules(r.clock) + slot := r.clock.Truncate(15 * time.Minute) + r.dir.SlotStart, r.dir.SlotEnd = slot, slot.Add(15*time.Minute) + r.dir.LoadpointEnergyWh = map[string]float64{} + if r.samples[r.cfg.DriverName].Connected && !r.state().ChargingDeclined { + r.dir.LoadpointEnergyWh[r.cfg.ID] = 2750 + } + r.c.Tick(context.Background(), r.clock) + if after := r.state(); !offered && after.CommandedW >= DeliveringW && before.CommandedKnown { + r.offers = append(r.offers, r.clock) + } +} + +func (r *declineRetryRig) run(d, every time.Duration) { + r.t.Helper() + for end := r.clock.Add(d); r.clock.Before(end); { + r.step(every) + } +} + +// decline makes the car refuse a live offer until the latch forms and the +// next plan leaves the car out, and returns when the latch formed. +func (r *declineRetryRig) decline() time.Time { + r.t.Helper() + r.step(5 * time.Second) + if st := r.state(); st.CommandedW < DeliveringW || st.CommandedReason != "plan" { + r.t.Fatalf("plan did not offer current: %+v", st) + } + r.refuses = true + for start := r.clock; r.clock.Sub(start) < 3*SessionCompletionTimeout; { + r.step(5 * time.Second) + if r.state().ChargingDeclined { + latched := r.clock + r.step(5 * time.Second) + r.wantLatched("once the plan leaves the car out") + return latched + } + } + r.t.Fatal("a lasting refusal under a live offer did not latch") + return time.Time{} +} + +func (r *declineRetryRig) wantLatched(why string) { + r.t.Helper() + if st := r.state(); !st.ChargingDeclined || st.CommandedW != 0 || st.CommandedReason != "vehicle_not_requesting" { + r.t.Fatalf("%s: want the refusal latched at 0 W (vehicle_not_requesting), got declined=%v %.0f W %q", + why, st.ChargingDeclined, st.CommandedW, st.CommandedReason) + } +} + +func (r *declineRetryRig) wantOffered(why string) { + r.t.Helper() + if st := r.state(); st.ChargingDeclined || st.CommandedW < DeliveringW || st.CommandedReason != "plan" { + r.t.Fatalf("%s: want the car planned and offered current, got declined=%v %.0f W %q", + why, st.ChargingDeclined, st.CommandedW, st.CommandedReason) + } +} + +// A car that declined is planned and offered current again once +// DeclineRetryInterval has passed, while it stays plugged in. +func TestDeclinedCarIsOfferedAgainAfterTheRetryInterval(t *testing.T) { + r := newDeclineRetryRig(t) + latched := r.decline() + r.run(DeclineRetryInterval-time.Minute-r.clock.Sub(latched), 30*time.Second) + r.wantLatched("before the retry interval") + + r.refuses = false + r.run(2*time.Minute, 30*time.Second) + r.wantOffered("after the retry interval") + if len(r.offers) != 1 { + t.Fatalf("want one new offer, got %v", r.offers) + } + if got := r.offers[0].Sub(latched); got < DeclineRetryInterval { + t.Fatalf("offered again %v after the refusal, before the %v interval", got, DeclineRetryInterval) + } +} + +// A new goal window, the next recurring deadline, also brings one more +// offer, even when the car declined less than an interval before. +func TestDeclinedCarIsOfferedAgainAtTheNextRecurringDeadline(t *testing.T) { + r := newDeclineRetryRig(t) + r.clock = time.Date(2026, 11, 25, 6, 30, 0, 0, time.UTC) + r.c.manager.SetSchedule(r.cfg.ID, Schedule{SoC: 1, TimeOfDayMinUTC: 7 * 60, Recurring: true}) + r.c.manager.RollSchedules(r.clock) + deadline := r.state().TargetTime + if !deadline.Equal(time.Date(2026, 11, 25, 7, 0, 0, 0, time.UTC)) { + t.Fatalf("recurring deadline: %v", deadline) + } + r.decline() + r.run(deadline.Sub(r.clock)-time.Minute, 30*time.Second) + r.wantLatched("before the deadline") + + r.refuses = false + r.run(2*time.Minute, 30*time.Second) + if next := r.state().TargetTime; !next.Equal(deadline.Add(24 * time.Hour)) { + t.Fatalf("deadline did not roll: %v", next) + } + r.wantOffered("at the next goal window") +} + +// A car that always declines is offered current at most once per +// DeclineRetryInterval, deadline rolls included. Each offer ends with the +// usual SessionCompletionTimeout, and the plan drops the car again. +func TestCarThatKeepsDecliningIsNotFlapped(t *testing.T) { + r := newDeclineRetryRig(t) + r.clock = time.Date(2026, 11, 25, 3, 15, 0, 0, time.UTC) + r.c.manager.SetSchedule(r.cfg.ID, Schedule{SoC: 1, TimeOfDayMinUTC: 7 * 60, Recurring: true}) + r.c.manager.RollSchedules(r.clock) + r.decline() + r.offers = nil + r.run(5*time.Hour, 15*time.Second) + + if len(r.offers) < 4 || len(r.offers) > 5 { + t.Fatalf("five hours of refusals: want an offer about once an hour, got %d: %v", len(r.offers), r.offers) + } + for i := 1; i < len(r.offers); i++ { + if gap := r.offers[i].Sub(r.offers[i-1]); gap < DeclineRetryInterval { + t.Fatalf("offers %v apart, under the %v interval: %v", gap, DeclineRetryInterval, r.offers) + } + } + r.wantLatched("between retries") +} + +// No retry once the goal is met, the car's own fresh reading says it is +// done, a one-shot deadline has passed, or Core may not command the charger. +func TestDeclinedCarRetryNeedsAGoalStillToMeet(t *testing.T) { + none := func(*declineRetryRig) {} + for _, tc := range []struct { + name string + before, after func(r *declineRetryRig) + retry bool + }{ + {"goal not met", none, none, true}, + {"goal lowered below the level", none, func(r *declineRetryRig) { + r.c.manager.SetTarget(r.cfg.ID, 0.1, r.state().TargetTime) + }, false}, + {"car at its own limit", none, func(r *declineRetryRig) { + r.c.SetVehicleChargeState(func(string) (VehicleChargeState, bool) { + return VehicleChargeState{SoC: .8, Limit: .8, State: "Stopped"}, true + }) + }, false}, + {"car reports complete", none, func(r *declineRetryRig) { + r.c.SetVehicleChargeState(func(string) (VehicleChargeState, bool) { + return VehicleChargeState{SoC: .6, State: "Complete"}, true + }) + }, false}, + {"one-shot deadline passed", func(r *declineRetryRig) { + r.c.manager.SetTarget(r.cfg.ID, 1, r.clock.Add(20*time.Minute)) + }, none, false}, + {"charger Core may not command", none, func(r *declineRetryRig) { + r.c.SetChargerControlAllowed(func(string) bool { return false }) + }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + r := newDeclineRetryRig(t) + tc.before(r) + r.decline() + tc.after(r) + r.refuses = false + r.run(DeclineRetryInterval+2*time.Minute, time.Minute) + if got := !r.state().ChargingDeclined; got != tc.retry { + t.Fatalf("retried=%v want %v: %+v", got, tc.retry, r.state()) + } + }) + } +} + +// The existing exits still end the refusal at once. +func TestDeclineExitsStillActAtOnce(t *testing.T) { + t.Run("charge now", func(t *testing.T) { + r := newDeclineRetryRig(t) + r.decline() + r.step(time.Minute) + r.c.SetManualHold(r.cfg.ID, ManualHold{PowerW: 11040, PhaseMode: "3p", Persistent: true}) + if r.state().ChargingDeclined { + t.Fatal("Charge now kept the refusal") + } + }) + t.Run("unplug", func(t *testing.T) { + r := newDeclineRetryRig(t) + r.decline() + r.step(time.Minute) + r.samples[r.cfg.DriverName] = EVSample{Connected: false} + r.c.manager.ObserveSample(r.cfg.ID, r.samples[r.cfg.DriverName]) + if r.state().ChargingDeclined { + t.Fatal("unplug kept the refusal") + } + }) +} diff --git a/go/internal/loadpoint/loadpoint.go b/go/internal/loadpoint/loadpoint.go index b6f137d57..4e398cf9a 100644 --- a/go/internal/loadpoint/loadpoint.go +++ b/go/internal/loadpoint/loadpoint.go @@ -369,6 +369,17 @@ type Manager struct { // A refusal is not evidence that the battery reached its target. const SessionCompletionTimeout = 90 * time.Second +// DeclineRetryInterval is how long a car that declined current stays out of +// the plan before Core offers it current again in the same plug-in. A car +// that is full or at its own limit declines again and the latch re-forms +// after SessionCompletionTimeout, so each retry costs one offer: 90 s, plus +// the charger's start delay (Easee: up to about 5 min) and a replan. An hour +// keeps that under a tenth of the time. It is longer than the Easee start +// delay and LoadBalancerRaiseWait, so one retry has ended before the next +// can begin, and short enough that a car that paused on its own (a timer in +// the car, a cold battery) loses at most an hour of a night's charging. +const DeclineRetryInterval = time.Hour + // VehicleDeclinesOffer reports a car that has refused Core's offered current // for SessionCompletionTimeout. A brief stop during the session handshake is // not enough. It says nothing about the battery level or a met goal. @@ -502,6 +513,13 @@ type loadpointRuntime struct { // It suspends planning while the vehicle refuses energy, without // changing the estimated battery level. Cleared on plug-out. chargingDeclined bool + // chargingDeclinedAt is when the latch last formed and + // declinedForTarget the deadline it formed under; declineRetriedAt is + // when Core last ended it to offer current again. They time the retry + // (retryDeclinedCharging) and reset with the plug-in. + chargingDeclinedAt time.Time + declinedForTarget time.Time + declineRetriedAt time.Time // socConfirmed is true only after a level from the user or a matched car. // A configured/default plug-in level remains a planning assumption. @@ -688,6 +706,9 @@ func (m *Manager) Load(cfgs []Config) { lp.lastRolledFor = existing.lastRolledFor lp.notRequestingSince = existing.notRequestingSince lp.chargingDeclined = existing.chargingDeclined + lp.chargingDeclinedAt = existing.chargingDeclinedAt + lp.declinedForTarget = existing.declinedForTarget + lp.declineRetriedAt = existing.declineRetriedAt lp.socConfirmed = existing.socConfirmed && existing.DriverName == c.DriverName if lp.socConfirmed { lp.socConfirmedAt = existing.socConfirmedAt @@ -869,12 +890,14 @@ func (m *Manager) observe(id string, pluggedIn bool, powerW, deliveredWh float64 lp.deliveredHistory = nil lp.notRequestingSince = time.Time{} lp.chargingDeclined = false + lp.declineRetriedAt = time.Time{} lp.carPhases = carPhases{} } if !pluggedIn { // Plug-out: drop any pending completion timer / latch. lp.notRequestingSince = time.Time{} lp.chargingDeclined = false + lp.declineRetriedAt = time.Time{} lp.carPhases = carPhases{} if lp.capacityFromCar { // The car that measured its own capacity left with its @@ -918,6 +941,8 @@ func (m *Manager) observe(id string, pluggedIn bool, powerW, deliveredWh float64 !lp.notRequestingSince.IsZero() && now.Sub(lp.notRequestingSince) >= SessionCompletionTimeout { lp.chargingDeclined = true + lp.chargingDeclinedAt = now + lp.declinedForTarget = lp.targetTime } } else if pluggedIn && requestActive { // Vehicle is back to requesting. Reset the timer, but keep @@ -1701,6 +1726,40 @@ func (m *Manager) RollSchedules(now time.Time) { } } +// retryDeclinedCharging ends a refusal latch so the plan takes the car in +// again and Core offers it current once more in this plug-in. It is due +// DeclineRetryInterval after the car declined, or when a new goal window +// starts (the recurring deadline rolled, or the owner set another), and Core +// ends a latch at most once per DeclineRetryInterval. It never retries a +// goal that is met, a goal whose deadline has passed (a vehicle-limit goal +// stays due), or a car whose own fresh reading says it is done (carDone). +// It changes no battery level or stored intent, and reports whether it +// ended the latch. +func (m *Manager) retryDeclinedCharging(id string, now time.Time, carDone bool) bool { + m.mu.Lock() + defer m.mu.Unlock() + lp := m.byID[id] + if lp == nil || !lp.pluggedIn || !lp.chargingDeclined || lp.chargingDeclinedAt.IsZero() || + carDone || lp.finishGoalCompleted { + return false + } + st := lp.snapshot() + if target := PlanningTarget(st, st.CarChargeLimit); target <= 0 || st.CurrentSoC >= target || + !lp.finishAtVehicleLimit && !lp.targetTime.After(now) { + return false + } + if !lp.declineRetriedAt.IsZero() && now.Sub(lp.declineRetriedAt) < DeclineRetryInterval { + return false + } + if now.Sub(lp.chargingDeclinedAt) < DeclineRetryInterval && lp.targetTime.Equal(lp.declinedForTarget) { + return false + } + lp.chargingDeclined = false + lp.notRequestingSince = time.Time{} + lp.declineRetriedAt = now + return true +} + // RetryCharging lets an explicit Start action retry a vehicle that previously // declined current. It changes no battery level or stored user intent. func (m *Manager) RetryCharging(id string) { diff --git a/go/internal/loadpoint/session_state.go b/go/internal/loadpoint/session_state.go index af65f6133..55de9599e 100644 --- a/go/internal/loadpoint/session_state.go +++ b/go/internal/loadpoint/session_state.go @@ -347,6 +347,7 @@ func (m *Manager) observeConnectionProof(id string, generation uint64, unknown b lp.steadyRunArmed = false lp.notRequestingSince = time.Time{} lp.chargingDeclined = false + lp.declineRetriedAt = time.Time{} lp.completionNotified = false m.mu.Unlock() if m.sessionStore != nil && previousDevice != "" {