From 3e4629968ce188ae9bb7af0639f3d086139f206b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:01:31 +0100 Subject: [PATCH 1/6] fix(ocpp): a managed charger starts at 0 A on boot Until FTW's first order lands, an OCPP charger runs at its own default, usually its rating. In random rig seed 207534 the charger booted at 5.0 s, a car plugged in at 7.3 s and drew 11040 W from 10 s until FTW's first 0 A took effect at 13.5 s, with 18.9 A on a 16 A fuse. On BootNotification (1.6 and 2.0.1) from a charger a loadpoint names, send the same 0 A TxDefaultProfile FTW sends to pause: profile id 1, stack level 0, connector or EVSE 0, with the usual connector-1 retry. FTW's first order has the same id, purpose and stack level, so it replaces the boot profile. Skip chargers listed only under ocpp.chargers (FTW never orders them), pending chargers, a boot that answers FTW's own identity probe, and a boot on a socket that already reported a car. A refusal is logged once and not retried until the next boot. Co-Authored-By: Claude Opus 5.5 --- .changeset/c9-ocpp-safe-boot-profile.md | 5 + go/cmd/ftw/ev_send.go | 29 +++- go/cmd/ftw/ev_send_test.go | 16 ++ go/cmd/ftw/main.go | 2 + go/cmd/sim-ocpp/ocppcp/boot_limit_test.go | 107 ++++++++++++ go/internal/ocpp/boot_limit.go | 63 +++++++ go/internal/ocpp/boot_limit_test.go | 192 ++++++++++++++++++++++ go/internal/ocpp/config.go | 5 + go/internal/ocpp/handlers.go | 8 + go/internal/ocpp/handlers_v201.go | 1 + go/internal/ocpp/server.go | 2 + 11 files changed, 422 insertions(+), 8 deletions(-) create mode 100644 .changeset/c9-ocpp-safe-boot-profile.md create mode 100644 go/cmd/sim-ocpp/ocppcp/boot_limit_test.go create mode 100644 go/internal/ocpp/boot_limit.go create mode 100644 go/internal/ocpp/boot_limit_test.go diff --git a/.changeset/c9-ocpp-safe-boot-profile.md b/.changeset/c9-ocpp-safe-boot-profile.md new file mode 100644 index 000000000..3af64977d --- /dev/null +++ b/.changeset/c9-ocpp-safe-boot-profile.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +An OCPP charger that a loadpoint names now starts at 0 A when it boots. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. diff --git a/go/cmd/ftw/ev_send.go b/go/cmd/ftw/ev_send.go index 959a46f8b..be76caa5a 100644 --- a/go/cmd/ftw/ev_send.go +++ b/go/cmd/ftw/ev_send.go @@ -16,12 +16,6 @@ func ocppApprovedIDs(cfg *config.Config) []string { if cfg == nil { return nil } - lua := make(map[string]struct{}, len(cfg.Drivers)) - for _, d := range cfg.Drivers { - if d.Name != "" { - lua[d.Name] = struct{}{} - } - } seen := make(map[string]struct{}) var out []string add := func(id string) { @@ -39,11 +33,30 @@ func ocppApprovedIDs(cfg *config.Config) []string { add(c.ID) } } + for _, id := range ocppManagedIDs(cfg) { + add(id) + } + return out +} + +// ocppManagedIDs is the OCPP chargers a loadpoint names: the ones FTW orders. +// An id listed only under ocpp.chargers is approved but never ordered. +func ocppManagedIDs(cfg *config.Config) []string { + if cfg == nil { + return nil + } + lua := make(map[string]struct{}, len(cfg.Drivers)) + for _, d := range cfg.Drivers { + if d.Name != "" { + lua[d.Name] = struct{}{} + } + } + var out []string for _, lp := range cfg.Loadpoints { - if _, isLua := lua[lp.DriverName]; isLua { + if _, isLua := lua[lp.DriverName]; isLua || lp.DriverName == "" { continue } - add(lp.DriverName) + out = append(out, lp.DriverName) } return out } diff --git a/go/cmd/ftw/ev_send_test.go b/go/cmd/ftw/ev_send_test.go index 0503e2b71..c1d66d901 100644 --- a/go/cmd/ftw/ev_send_test.go +++ b/go/cmd/ftw/ev_send_test.go @@ -46,6 +46,22 @@ func TestOCPPApprovedIDsSkipLuaLoadpointNames(t *testing.T) { } } +// Only a loadpoint's charger gets FTW's orders, so only it may start at 0 A. +func TestOCPPManagedIDsAreLoadpointChargersOnly(t *testing.T) { + cfg := &config.Config{ + Drivers: []config.Driver{{Name: "easee", Lua: "drivers/easee.lua"}}, + Loadpoints: []config.Loadpoint{ + {ID: "cloud", DriverName: "easee"}, + {ID: "garage", DriverName: "garage"}, + }, + OCPP: &config.OCPP{Enabled: true, Chargers: []config.OCPPCharger{{ID: "wallbox", Password: "own"}}}, + } + got := ocppManagedIDs(cfg) + if len(got) != 1 || got[0] != "garage" { + t.Fatalf("managed %v, want garage only", got) + } +} + func containsID(ids []string, want string) bool { for _, id := range ids { if id == want { diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index 4b23e1d63..36834b8c5 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -1305,6 +1305,7 @@ func main() { // and one whose entry was removed goes back to pending. if ocppSrv != nil { ocppSrv.Handler().SetApprovedIDs(ocppApprovedIDs(newCfg)) + ocppSrv.Handler().SetManagedIDs(ocppManagedIDs(newCfg)) // A charger adopted by this save booted long ago and will not // boot again just because we changed our mind, so its device // row has to be written here rather than waiting for one. @@ -1475,6 +1476,7 @@ func main() { HeartbeatIntervalS: cfg.OCPP.HeartbeatIntervalS, ChargerSecrets: cfg.OCPP.ChargerSecrets(), ApprovedIDs: approved, + ManagedIDs: ocppManagedIDs(cfg), } if t := cfg.OCPP.TLS; t != nil { ocppCfg.TLS = &ocpp.TLSConfig{ diff --git a/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go b/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go new file mode 100644 index 000000000..7cb830fe1 --- /dev/null +++ b/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go @@ -0,0 +1,107 @@ +package ocppcp + +import ( + "context" + "encoding/json" + "fmt" + "net" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/ocpp" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +func freePort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + return l.Addr().(*net.TCPAddr).Port +} + +// startFTW runs FTW's Central System with id named by a loadpoint. +func startFTW(t *testing.T, id string) (*ocpp.Server, DialOpts) { + t.Helper() + for attempt := 1; ; attempt++ { + cfg := &ocpp.Config{ + Enabled: true, Bind: "127.0.0.1", HeartbeatIntervalS: 60, + Port: freePort(t), PortV201: freePort(t), + ApprovedIDs: []string{id}, ManagedIDs: []string{id}, + } + srv, err := ocpp.Start(context.Background(), cfg, telemetry.NewStore()) + if err != nil && attempt < 5 { + continue // another test took the port + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(srv.Stop) + return srv, DialOpts{ + URL16: fmt.Sprintf("ws://127.0.0.1:%d", cfg.Port), + URL201: fmt.Sprintf("ws://127.0.0.1:%d", cfg.PortV201), + } + } +} + +func waitFor(t *testing.T, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// Seed 207534: the charger booted at 5.0 s, a car plugged in at 7.3 s and +// drew the charger's 16 A rating from 10 s until FTW's first 0 A landed at +// 13.5 s, with 18.9 A on a 16 A fuse. With the start limit, the charger holds +// 0 A from boot, and FTW's order still sets the rate afterwards. +func TestChargerHoldsZeroAmpsFromBootUntilFTWOrder(t *testing.T) { + for _, modelID := range []string{"easee-charge-up", "charge-amps-aura", "defa-power"} { + t.Run(modelID, func(t *testing.T) { + m, ok := Lookup(modelID) + if !ok { + t.Fatalf("no model %s", modelID) + } + sim := New(m) + srv, opts := startFTW(t, sim.DialID()) + waitFor(t, "the charger to connect", func() bool { return sim.Dial(opts) == nil }) + t.Cleanup(sim.Close) + if got := sim.LimitA(); got != m.MaxAmps() { + t.Fatalf("unsteered limit %v A, want the rating %v A", got, m.MaxAmps()) + } + + if err := sim.Boot(); err != nil { + t.Fatal(err) + } + waitFor(t, "the 0 A start limit", func() bool { return sim.LimitA() == 0 }) + + if err := sim.Plug(); err != nil { + t.Fatal(err) + } + sim.Tick(time.Second) + if w := sim.PowerW(); w != 0 { + t.Fatalf("car drew %v W before FTW's first order, want 0", w) + } + + order, _ := json.Marshal(map[string]any{ + "action": "ev_set_current", "power_w": 6900.0, "voltage": 230.0, "site_phases": 3, + }) + if err := srv.Command(context.Background(), sim.DialID(), order); err != nil { + t.Fatalf("order: %v", err) + } + sim.Tick(time.Second) + if got := sim.LimitA(); got != 10 { + t.Fatalf("effective limit %v A after FTW's order, want 10 A", got) + } + if w := sim.PowerW(); w != 6900 { + t.Fatalf("car draws %v W after FTW's order, want 6900", w) + } + }) + } +} diff --git a/go/internal/ocpp/boot_limit.go b/go/internal/ocpp/boot_limit.go new file mode 100644 index 000000000..7f415b6af --- /dev/null +++ b/go/internal/ocpp/boot_limit.go @@ -0,0 +1,63 @@ +package ocpp + +// A charger FTW steers starts at 0 A. +// +// Until a charging profile lands, a charger runs at its own default, which is +// usually its rating. FTW orders a plugged-in car every control tick, but the +// first order still takes a tick plus the charger's own response time. A car +// plugged in during that gap draws the full rating on a fuse FTW has not yet +// shared out. So on each BootNotification from a charger a loadpoint names, +// FTW sends the same profile it sends to pause: TxDefaultProfile, id 1, stack +// level 0, 0 A for the whole charger. Its first real order has the same id, +// purpose and stack level, so it replaces this one (OCPP 1.6 §3.13.2, 2.0.1 +// K01.FR.05). + +import ( + "context" + "log/slog" +) + +// SetManagedIDs declares which approved chargers FTW orders: those a loadpoint +// names. An id listed only under ocpp.chargers is approved and metered but +// never ordered, so a 0 A start would hold it at 0 A for good. Replaces the +// previous set; a change applies at the charger's next boot. +func (h *Handler) SetManagedIDs(ids []string) { + m := make(map[string]bool, len(ids)) + for _, id := range ids { + if id != "" { + m[id] = true + } + } + h.mu.Lock() + h.managed = m + h.mu.Unlock() +} + +// maybeSendBootLimit sends the 0 A start limit after a BootNotification. +// +// It skips a boot that answers FTW's own identity probe: that charger did not +// restart, and may be charging under FTW's last order. It also skips a boot on +// a socket that already reported a car: FTW orders that car every tick. +// The send runs on its own goroutine, as the capability probe does, and goes +// through the same one-at-a-time slot as every other order. A refusal is +// logged once; the next boot tries again. +func (h *Handler) maybeSendBootLimit(id string) { + h.mu.Lock() + s := h.chargersLocked(id) + send := h.bootLimit + if !h.approved[id] || !h.managed[id] || s.identityProbeAttempts > 0 || (s.connectedKnown && s.connected) { + send = nil + } + h.mu.Unlock() + if send != nil { + go send(id) + } +} + +// sendBootLimit is the Server side of maybeSendBootLimit. +func (s *Server) sendBootLimit(id string) { + if err := s.setLimit(context.Background(), id, 0, nil); err != nil { + slog.Warn("ocpp: charger did not take the 0 A start limit; it runs at its own default until FTW's first order", + "charger", id, "err", err) + } +} diff --git a/go/internal/ocpp/boot_limit_test.go b/go/internal/ocpp/boot_limit_test.go new file mode 100644 index 000000000..bc5efb6fc --- /dev/null +++ b/go/internal/ocpp/boot_limit_test.go @@ -0,0 +1,192 @@ +package ocpp + +import ( + "context" + "testing" + "time" + + ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6" + "github.com/lorenzodonini/ocpp-go/ocpp1.6/core" + "github.com/lorenzodonini/ocpp-go/ocpp1.6/smartcharging" + "github.com/lorenzodonini/ocpp-go/ocpp1.6/types" + types201 "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/types" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// startManagedServer runs a 1.6 listener (and 2.0.1 when v201) where +// "garage" is named by a loadpoint and "metered" is listed only under +// ocpp.chargers. +func startManagedServer(t *testing.T, v201 bool) *Server { + t.Helper() + return startOCPP(t, Config{ + Enabled: true, Bind: "127.0.0.1", HeartbeatIntervalS: 60, + ApprovedIDs: []string{"garage", "metered"}, + ManagedIDs: []string{"garage"}, + }, telemetry.NewStore(), v201) +} + +func awaitProfiles(t *testing.T, count func() int, want int) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for count() < want { + if time.Now().After(deadline) { + t.Fatalf("got %d charging profiles, want %d", count(), want) + } + time.Sleep(5 * time.Millisecond) + } +} + +// settle gives a profile that should not come time to arrive. +func settle() { time.Sleep(300 * time.Millisecond) } + +// A managed charger gets a 0 A TxDefaultProfile at boot, before any car, and +// FTW's first order uses the same id, purpose and stack level, so it replaces +// that profile instead of stacking under it. +func TestManagedChargerStartsAtZeroAmpsOnBoot(t *testing.T) { + srv := startManagedServer(t, false) + _, fake, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + awaitProfiles(t, fake.count, 1) + + fake.mu.Lock() + boot := fake.profiles[0] + fake.mu.Unlock() + p := boot.ChargingProfile + if boot.ConnectorId != allConnectors || p.ChargingProfilePurpose != types.ChargingProfilePurposeTxDefaultProfile || + p.ChargingProfileId != ftwProfileID || p.StackLevel != ftwStackLevel { + t.Fatalf("boot profile: connector %d purpose %s id %d stack %d, want 0 TxDefaultProfile %d %d", + boot.ConnectorId, p.ChargingProfilePurpose, p.ChargingProfileId, p.StackLevel, ftwProfileID, ftwStackLevel) + } + if got := fake.lastLimit(t); got != 0 { + t.Fatalf("boot limit %v A, want 0 A", got) + } + + if err := srv.Command(context.Background(), "garage", setCurrent11kW(t)); err != nil { + t.Fatalf("order: %v", err) + } + fake.mu.Lock() + order := fake.profiles[len(fake.profiles)-1] + fake.mu.Unlock() + o := order.ChargingProfile + if order.ConnectorId != boot.ConnectorId || o.ChargingProfilePurpose != p.ChargingProfilePurpose || + o.ChargingProfileId != p.ChargingProfileId || o.StackLevel != p.StackLevel { + t.Fatalf("FTW's order does not replace the boot profile: connector %d purpose %s id %d stack %d", + order.ConnectorId, o.ChargingProfilePurpose, o.ChargingProfileId, o.StackLevel) + } + if got := fake.lastLimit(t); got != 16 { + t.Fatalf("order limit %v A, want 16 A", got) + } +} + +// FTW never orders a charger no loadpoint names, so a 0 A start would hold +// it at 0 A for good. A pending charger is not FTW's to steer at all. +func TestUnmanagedChargersGetNoBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + _, managed, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + _, metered, _ := connectCharger(t, srv, srv.cfg.Port, "metered") + _, pending, _ := connectCharger(t, srv, srv.cfg.Port, "stranger") + awaitProfiles(t, managed.count, 1) + settle() + if n := metered.count(); n != 0 { + t.Errorf("charger listed only under ocpp.chargers got %d profiles, want 0", n) + } + if n := pending.count(); n != 0 { + t.Errorf("pending charger got %d profiles, want 0", n) + } +} + +// A charger that refuses the start limit gets the connector-1 retry every +// order gets, and then nothing more until it boots again. +func TestRefusedBootLimitIsNotRetried(t *testing.T) { + srv := startManagedServer(t, false) + fake := newFakeCharger() + fake.setStatus(smartcharging.ChargingProfileStatusRejected) + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { + t.Fatal(err) + } + awaitProfiles(t, fake.count, 2) + settle() + if n := fake.count(); n != 2 { + t.Fatalf("refused start limit sent %d times, want 2 (connector 0, then 1)", n) + } +} + +// A boot on a socket that already reported a car is not a fresh start: FTW +// orders that car every tick, and 0 A would only pause it. +func TestBootWithCarAlreadyReportedGetsNoBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + fake := newFakeCharger() + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cp.StatusNotification(1, core.NoError, core.ChargePointStatusCharging); err != nil { + t.Fatal(err) + } + if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { + t.Fatal(err) + } + settle() + if n := fake.count(); n != 0 { + t.Fatalf("boot with a car on the socket got %d profiles, want 0", n) + } +} + +// After a Core restart the charger reconnects without booting, and FTW asks +// it for a BootNotification. That boot is FTW's own request, not a charger +// restart; the car may be charging on FTW's last order. +func TestBootAnsweringIdentityProbeGetsNoBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + fake := newFakeCharger() + requests := make(chan string, 10) + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { + cp.SetSmartChargingHandler(fake) + cp.SetRemoteTriggerHandler(bootTrigger16{requested: requests}) + }) + if err != nil { + t.Fatal(err) + } + select { + case <-requests: + case <-time.After(3 * time.Second): + t.Fatal("FTW never asked for a BootNotification") + } + if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { + t.Fatal(err) + } + settle() + if n := fake.count(); n != 0 { + t.Fatalf("boot answering FTW's probe got %d profiles, want 0", n) + } +} + +// 2.0.1: the same 0 A TxDefaultProfile on EVSE 0, replaced by FTW's order. +func TestV201ManagedStationStartsAtZeroAmpsOnBoot(t *testing.T) { + srv := startManagedServer(t, true) + fake, _ := connectStationV201(t, srv, srv.cfg.PortV201, "garage") + count := func() int { fake.mu.Lock(); defer fake.mu.Unlock(); return len(fake.profiles) } + awaitProfiles(t, count, 1) + + fake.mu.Lock() + boot := fake.profiles[0] + fake.mu.Unlock() + p := boot.ChargingProfile + if boot.EvseID != allEVSEs || p.ChargingProfilePurpose != types201.ChargingProfilePurposeTxDefaultProfile || + p.ID != ftwProfileID || p.StackLevel != ftwStackLevel { + t.Fatalf("boot profile: evse %d purpose %s id %d stack %d, want 0 TxDefaultProfile %d %d", + boot.EvseID, p.ChargingProfilePurpose, p.ID, p.StackLevel, ftwProfileID, ftwStackLevel) + } + if got := fake.lastLimit(t); got != 0 { + t.Fatalf("boot limit %v A, want 0 A", got) + } + if err := srv.Command(context.Background(), "garage", setCurrent11kW(t)); err != nil { + t.Fatalf("order: %v", err) + } + if got := fake.lastLimit(t); got != 16 { + t.Fatalf("order limit %v A, want 16 A", got) + } +} diff --git a/go/internal/ocpp/config.go b/go/internal/ocpp/config.go index c8f581ab0..ba5d6302e 100644 --- a/go/internal/ocpp/config.go +++ b/go/internal/ocpp/config.go @@ -55,6 +55,11 @@ type Config struct { // UI so an operator can adopt it, withheld from telemetry so it cannot // influence dispatch. Empty means every charger is pending. ApprovedIDs []string `yaml:"-"` + + // ManagedIDs is the part of ApprovedIDs a loadpoint names: the chargers + // FTW orders. Each starts at 0 A on boot (see boot_limit.go). Derived by + // the caller, never read from YAML. + ManagedIDs []string `yaml:"-"` } // TLSConfig points at the certificate this server presents, and optionally at diff --git a/go/internal/ocpp/handlers.go b/go/internal/ocpp/handlers.go index 451459c14..4d1b34205 100644 --- a/go/internal/ocpp/handlers.go +++ b/go/internal/ocpp/handlers.go @@ -30,6 +30,13 @@ type Handler struct { // no driver health, no metrics — so it cannot influence dispatch. See // SetApprovedIDs. approved map[string]bool + + // managed is the approved chargers a loadpoint names, which FTW orders. + // bootLimit, set by the Server, holds each at 0 A from its boot until + // FTW's first order. See boot_limit.go. + managed map[string]bool + bootLimit func(id string) + nextTxID int // vehicleIdentified, when set, fires once per new vehicle identity seen @@ -487,6 +494,7 @@ func (h *Handler) OnBootNotification(id string, req *core.BootNotificationReques h.noteIdentity(id) h.telHealth(id) h.maybeProbeCapability(id) + h.maybeSendBootLimit(id) return core.NewBootNotificationConfirmation( types.NewDateTime(time.Now()), h.heartbeatIntervalS, diff --git a/go/internal/ocpp/handlers_v201.go b/go/internal/ocpp/handlers_v201.go index b89cbfa17..e88571692 100644 --- a/go/internal/ocpp/handlers_v201.go +++ b/go/internal/ocpp/handlers_v201.go @@ -67,6 +67,7 @@ func (h *handlerV201) OnBootNotification(id string, req *provisioning.BootNotifi h.setVersion(id, Version201) h.noteIdentity(id) h.telHealth(id) + h.maybeSendBootLimit(id) return provisioning.NewBootNotificationResponse( types201.NewDateTime(time.Now()), diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index e3e3d39ce..2d0af142b 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -137,6 +137,8 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, e s := &Server{cfg: cfg, cs: cs, handler: h, sockets: sockets, done: make(chan struct{})} h.identityProbe = s.requestBootNotification h.later = sockets.later + h.SetManagedIDs(cfg.ManagedIDs) + h.bootLimit = s.sendBootLimit // OCPP 2.0.1 on its own port, when configured. Same handler and therefore // the same charger state and telemetry — only the message encoding differs. From 964643e9591af6d3a7802bf7acd1ccbb7de08e27 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:17:40 +0100 Subject: [PATCH 2/6] fix(ocpp): no start limit in measurement mode or mid-session reconnect Setup measurement mode blocks every charger write, standdowns included. The boot limit went straight to setLimit, so a charger named by a loadpoint saved during setup got 0 A and kept it until restart. Both the start and the hot-reload paths now pass no managed chargers while Core runs in the mode it booted in. Much firmware sends its own BootNotification on every reconnect. The car guard read only the new socket, so a Wi-Fi drop mid-session paused the car. The guard now reads the last status FTW holds, which survives the reconnect, and any open transaction. Co-Authored-By: Claude Opus 5.5 --- go/cmd/ftw/ev_send.go | 11 +++++ go/cmd/ftw/ev_send_test.go | 20 ++++++++++ go/cmd/ftw/main.go | 4 +- go/internal/ocpp/boot_limit.go | 9 +++-- go/internal/ocpp/boot_limit_test.go | 62 +++++++++++++++++++++++++++++ go/internal/ocpp/config.go | 3 +- 6 files changed, 103 insertions(+), 6 deletions(-) diff --git a/go/cmd/ftw/ev_send.go b/go/cmd/ftw/ev_send.go index be76caa5a..29535394a 100644 --- a/go/cmd/ftw/ev_send.go +++ b/go/cmd/ftw/ev_send.go @@ -39,6 +39,17 @@ func ocppApprovedIDs(cfg *config.Config) []string { return out } +// ocppStartLimitIDs is the chargers that get the 0 A start limit on boot. +// Setup measurement mode blocks every charger write, standdowns included, so +// none does then. measurementAtBoot is the mode Core started in: leaving it +// takes a restart, so a reload that clears it must not lift the block early. +func ocppStartLimitIDs(cfg *config.Config, measurementAtBoot bool) []string { + if measurementAtBoot { + return nil + } + return ocppManagedIDs(cfg) +} + // ocppManagedIDs is the OCPP chargers a loadpoint names: the ones FTW orders. // An id listed only under ocpp.chargers is approved but never ordered. func ocppManagedIDs(cfg *config.Config) []string { diff --git a/go/cmd/ftw/ev_send_test.go b/go/cmd/ftw/ev_send_test.go index c1d66d901..4165d242e 100644 --- a/go/cmd/ftw/ev_send_test.go +++ b/go/cmd/ftw/ev_send_test.go @@ -62,6 +62,26 @@ func TestOCPPManagedIDsAreLoadpointChargersOnly(t *testing.T) { } } +// Setup measurement mode blocks every charger write, standdowns included, so +// no charger may start at 0 A while Core runs in it. Start passes the config +// Core booted with; a hot reload passes the saved config, which may already +// have left the mode while the block holds until restart. Both must give none. +func TestOCPPStartLimitIDsFollowMeasurementModeAtBoot(t *testing.T) { + loadpoints := []config.Loadpoint{{ID: "garage", DriverName: "garage"}} + measuring := &config.Config{Setup: &config.Setup{MeasurementOnly: true}, Loadpoints: loadpoints} + left := &config.Config{Loadpoints: loadpoints} + + if got := ocppStartLimitIDs(measuring, measuring.MeasurementOnly()); len(got) != 0 { + t.Fatalf("start in measurement mode: start limit for %v, want none", got) + } + if got := ocppStartLimitIDs(left, true); len(got) != 0 { + t.Fatalf("reload that left measurement mode before restart: start limit for %v, want none", got) + } + if got := ocppStartLimitIDs(left, false); len(got) != 1 || got[0] != "garage" { + t.Fatalf("normal operation: start limit for %v, want garage", got) + } +} + func containsID(ids []string, want string) bool { for _, id := range ids { if id == want { diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index 36834b8c5..0f10db14d 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -1305,7 +1305,7 @@ func main() { // and one whose entry was removed goes back to pending. if ocppSrv != nil { ocppSrv.Handler().SetApprovedIDs(ocppApprovedIDs(newCfg)) - ocppSrv.Handler().SetManagedIDs(ocppManagedIDs(newCfg)) + ocppSrv.Handler().SetManagedIDs(ocppStartLimitIDs(newCfg, setupMeasurementAtBoot)) // A charger adopted by this save booted long ago and will not // boot again just because we changed our mind, so its device // row has to be written here rather than waiting for one. @@ -1476,7 +1476,7 @@ func main() { HeartbeatIntervalS: cfg.OCPP.HeartbeatIntervalS, ChargerSecrets: cfg.OCPP.ChargerSecrets(), ApprovedIDs: approved, - ManagedIDs: ocppManagedIDs(cfg), + ManagedIDs: ocppStartLimitIDs(cfg, setupMeasurementAtBoot), } if t := cfg.OCPP.TLS; t != nil { ocppCfg.TLS = &ocpp.TLSConfig{ diff --git a/go/internal/ocpp/boot_limit.go b/go/internal/ocpp/boot_limit.go index 7f415b6af..b2cb74edf 100644 --- a/go/internal/ocpp/boot_limit.go +++ b/go/internal/ocpp/boot_limit.go @@ -36,8 +36,11 @@ func (h *Handler) SetManagedIDs(ids []string) { // maybeSendBootLimit sends the 0 A start limit after a BootNotification. // // It skips a boot that answers FTW's own identity probe: that charger did not -// restart, and may be charging under FTW's last order. It also skips a boot on -// a socket that already reported a car: FTW orders that car every tick. +// restart, and may be charging under FTW's last order. It also skips a boot +// when the last status FTW holds shows a car or an open transaction, on this +// socket or the one before: FTW orders that car every tick. Much firmware +// sends its own BootNotification on every reconnect, before any status, so +// after a Wi-Fi drop the new socket alone says nothing about the car. // The send runs on its own goroutine, as the capability probe does, and goes // through the same one-at-a-time slot as every other order. A refusal is // logged once; the next boot tries again. @@ -45,7 +48,7 @@ func (h *Handler) maybeSendBootLimit(id string) { h.mu.Lock() s := h.chargersLocked(id) send := h.bootLimit - if !h.approved[id] || !h.managed[id] || s.identityProbeAttempts > 0 || (s.connectedKnown && s.connected) { + if !h.approved[id] || !h.managed[id] || s.identityProbeAttempts > 0 || s.connected || s.transactionID >= 0 { send = nil } h.mu.Unlock() diff --git a/go/internal/ocpp/boot_limit_test.go b/go/internal/ocpp/boot_limit_test.go index bc5efb6fc..ff05ec5c8 100644 --- a/go/internal/ocpp/boot_limit_test.go +++ b/go/internal/ocpp/boot_limit_test.go @@ -136,6 +136,68 @@ func TestBootWithCarAlreadyReportedGetsNoBootLimit(t *testing.T) { } } +// reconnectAndBoot drops the charger's socket, waits for FTW to see it go, +// then dials again and sends a BootNotification before any status, as much +// firmware does after a Wi-Fi drop. It returns the new socket's charger. +func reconnectAndBoot(t *testing.T, srv *Server, stop func()) *fakeCharger { + t.Helper() + stop() + deadline := time.Now().Add(2 * time.Second) + for srv.Handler().IsOnline("garage") { + if time.Now().After(deadline) { + t.Fatal("FTW never saw the socket drop") + } + time.Sleep(10 * time.Millisecond) + } + fake := newFakeCharger() + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { + t.Fatal(err) + } + return fake +} + +// A Wi-Fi drop mid-session: the charger had reported Charging and taken +// FTW's 16 A. It reconnects and boots before any status. The car is most +// likely still charging, so FTW keeps its live order rather than pausing it. +func TestReconnectBootMidSessionKeepsFTWOrder(t *testing.T) { + srv := startManagedServer(t, false) + cp, fake, stop := connectCharger(t, srv, srv.cfg.Port, "garage") + awaitProfiles(t, fake.count, 1) // the real boot's 0 A + if _, err := cp.StatusNotification(1, core.NoError, core.ChargePointStatusCharging); err != nil { + t.Fatal(err) + } + if err := srv.Command(context.Background(), "garage", setCurrent11kW(t)); err != nil { + t.Fatal(err) + } + + after := reconnectAndBoot(t, srv, stop) + settle() + if n := after.count(); n != 0 { + t.Fatalf("reconnect boot mid-session got %d profile(s), last %v A; want FTW's live 16 A kept", n, after.lastLimit(t)) + } +} + +// The same reconnect after the car left: no car to pause, so the charger +// gets its start limit again. +func TestReconnectBootWithNoCarGetsBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + cp, fake, stop := connectCharger(t, srv, srv.cfg.Port, "garage") + awaitProfiles(t, fake.count, 1) + if _, err := cp.StatusNotification(1, core.NoError, core.ChargePointStatusAvailable); err != nil { + t.Fatal(err) + } + + after := reconnectAndBoot(t, srv, stop) + awaitProfiles(t, after.count, 1) + if got := after.lastLimit(t); got != 0 { + t.Fatalf("reconnect boot with no car: limit %v A, want 0 A", got) + } +} + // After a Core restart the charger reconnects without booting, and FTW asks // it for a BootNotification. That boot is FTW's own request, not a charger // restart; the car may be charging on FTW's last order. diff --git a/go/internal/ocpp/config.go b/go/internal/ocpp/config.go index ba5d6302e..242c2e1f9 100644 --- a/go/internal/ocpp/config.go +++ b/go/internal/ocpp/config.go @@ -58,7 +58,8 @@ type Config struct { // ManagedIDs is the part of ApprovedIDs a loadpoint names: the chargers // FTW orders. Each starts at 0 A on boot (see boot_limit.go). Derived by - // the caller, never read from YAML. + // the caller, never read from YAML, and empty while Core blocks every + // charger write (setup measurement mode). ManagedIDs []string `yaml:"-"` } From 92104f5a612693d8564f1d03739977d4d48721f6 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:45:35 +0100 Subject: [PATCH 3/6] fix(ocpp): wait for a status before the 0 A start limit Rig s7s-restart-short-25A failed twice on 964643e9: after a Core restart the charger sent its own BootNotification at once, the new process held no status or transaction, and FTW sent the 0 A start limit mid Charge now. The car went to SuspendedEVSE for a second. A boot now only marks the charger. The first connector status after it decides: no car and no transaction sends the 0 A limit; a car sends nothing. Connector 0 Available on 1.6 does not decide. Co-Authored-By: Claude Opus 5.5 --- .changeset/c9-ocpp-safe-boot-profile.md | 2 +- go/cmd/sim-ocpp/ocppcp/boot_limit_test.go | 4 + go/internal/ocpp/boot_limit.go | 46 ++++++--- go/internal/ocpp/boot_limit_test.go | 114 +++++++++++++++++++--- go/internal/ocpp/handlers.go | 6 ++ go/internal/ocpp/handlers_v201.go | 1 + 6 files changed, 144 insertions(+), 29 deletions(-) diff --git a/.changeset/c9-ocpp-safe-boot-profile.md b/.changeset/c9-ocpp-safe-boot-profile.md index 3af64977d..73b1877b3 100644 --- a/.changeset/c9-ocpp-safe-boot-profile.md +++ b/.changeset/c9-ocpp-safe-boot-profile.md @@ -2,4 +2,4 @@ "ftw": patch --- -An OCPP charger that a loadpoint names now starts at 0 A when it boots. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. +An OCPP charger that a loadpoint names now starts at 0 A when it boots and reports no car. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW waits for the charger's first connector status after the boot, so a charger that reconnects to a restarted Core with a car charging is not paused. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. diff --git a/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go b/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go index 7cb830fe1..811e8ece3 100644 --- a/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go +++ b/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go @@ -79,6 +79,10 @@ func TestChargerHoldsZeroAmpsFromBootUntilFTWOrder(t *testing.T) { if err := sim.Boot(); err != nil { t.Fatal(err) } + // After an accepted boot a charger reports its connectors. + if err := sim.statusPlugged(false); err != nil { + t.Fatal(err) + } waitFor(t, "the 0 A start limit", func() bool { return sim.LimitA() == 0 }) if err := sim.Plug(); err != nil { diff --git a/go/internal/ocpp/boot_limit.go b/go/internal/ocpp/boot_limit.go index b2cb74edf..39fe33cfe 100644 --- a/go/internal/ocpp/boot_limit.go +++ b/go/internal/ocpp/boot_limit.go @@ -6,11 +6,11 @@ package ocpp // usually its rating. FTW orders a plugged-in car every control tick, but the // first order still takes a tick plus the charger's own response time. A car // plugged in during that gap draws the full rating on a fuse FTW has not yet -// shared out. So on each BootNotification from a charger a loadpoint names, -// FTW sends the same profile it sends to pause: TxDefaultProfile, id 1, stack -// level 0, 0 A for the whole charger. Its first real order has the same id, -// purpose and stack level, so it replaces this one (OCPP 1.6 §3.13.2, 2.0.1 -// K01.FR.05). +// shared out. So when a charger a loadpoint names boots and then reports no +// car, FTW sends the same profile it sends to pause: TxDefaultProfile, id 1, +// stack level 0, 0 A for the whole charger. Its first real order has the same +// id, purpose and stack level, so it replaces this one (OCPP 1.6 §3.13.2, +// 2.0.1 K01.FR.05). import ( "context" @@ -33,24 +33,44 @@ func (h *Handler) SetManagedIDs(ids []string) { h.mu.Unlock() } -// maybeSendBootLimit sends the 0 A start limit after a BootNotification. +// maybeSendBootLimit marks a BootNotification for the 0 A start limit. The +// limit goes out on the first connector status after it, and only when that +// status shows no car (resolveBootLimit). +// +// A boot alone does not show a fresh start. After a Core restart the new +// process holds no status and no transaction, and much firmware sends its own +// BootNotification on reconnect, before FTW's identity probe, while the car +// goes on charging. A 1.6 charger reports every connector's status after an +// accepted boot (§4.9), and 2.0.1 stations send StatusNotification there too, +// so FTW waits for it. A charger that never reports one gets no start limit, +// as before this file existed. // // It skips a boot that answers FTW's own identity probe: that charger did not // restart, and may be charging under FTW's last order. It also skips a boot // when the last status FTW holds shows a car or an open transaction, on this -// socket or the one before: FTW orders that car every tick. Much firmware -// sends its own BootNotification on every reconnect, before any status, so -// after a Wi-Fi drop the new socket alone says nothing about the car. -// The send runs on its own goroutine, as the capability probe does, and goes -// through the same one-at-a-time slot as every other order. A refusal is -// logged once; the next boot tries again. +// socket or the one before: FTW orders that car every tick. func (h *Handler) maybeSendBootLimit(id string) { + h.mu.Lock() + defer h.mu.Unlock() + s := h.chargersLocked(id) + s.bootLimitPending = h.bootLimit != nil && h.approved[id] && h.managed[id] && + s.identityProbeAttempts == 0 && !s.connected && s.transactionID < 0 +} + +// resolveBootLimit runs after each connector status. The first one after a +// marked boot decides: no car and no transaction sends the start limit; a car +// sends nothing, since FTW orders that car every tick. The send runs on its +// own goroutine, as the capability probe does, and goes through the same +// one-at-a-time slot as every other order. A refusal is logged once; the next +// boot tries again. +func (h *Handler) resolveBootLimit(id string) { h.mu.Lock() s := h.chargersLocked(id) send := h.bootLimit - if !h.approved[id] || !h.managed[id] || s.identityProbeAttempts > 0 || s.connected || s.transactionID >= 0 { + if !s.bootLimitPending || !h.approved[id] || !h.managed[id] || s.connected || s.transactionID >= 0 { send = nil } + s.bootLimitPending = false h.mu.Unlock() if send != nil { go send(id) diff --git a/go/internal/ocpp/boot_limit_test.go b/go/internal/ocpp/boot_limit_test.go index ff05ec5c8..0c27f388c 100644 --- a/go/internal/ocpp/boot_limit_test.go +++ b/go/internal/ocpp/boot_limit_test.go @@ -9,6 +9,9 @@ import ( "github.com/lorenzodonini/ocpp-go/ocpp1.6/core" "github.com/lorenzodonini/ocpp-go/ocpp1.6/smartcharging" "github.com/lorenzodonini/ocpp-go/ocpp1.6/types" + ocpp201 "github.com/lorenzodonini/ocpp-go/ocpp2.0.1" + "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/availability" + "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/provisioning" types201 "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/types" "github.com/srcfl/ftw/go/internal/telemetry" @@ -40,12 +43,28 @@ func awaitProfiles(t *testing.T, count func() int, want int) { // settle gives a profile that should not come time to arrive. func settle() { time.Sleep(300 * time.Millisecond) } -// A managed charger gets a 0 A TxDefaultProfile at boot, before any car, and -// FTW's first order uses the same id, purpose and stack level, so it replaces -// that profile instead of stacking under it. +// reportStatus16 sends what a 1.6 charger sends after an accepted boot: the +// status of connector 0 and of its connector (OCPP 1.6 §4.9). +func reportStatus16(t *testing.T, cp ocpp16.ChargePoint, status core.ChargePointStatus) { + t.Helper() + for connector, st := range []core.ChargePointStatus{core.ChargePointStatusAvailable, status} { + if _, err := cp.StatusNotification(connector, core.NoError, st); err != nil { + t.Fatal(err) + } + } +} + +// A managed charger that boots and reports no car gets a 0 A +// TxDefaultProfile, and FTW's first order uses the same id, purpose and stack +// level, so it replaces that profile instead of stacking under it. func TestManagedChargerStartsAtZeroAmpsOnBoot(t *testing.T) { srv := startManagedServer(t, false) - _, fake, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + cp, fake, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + settle() + if n := fake.count(); n != 0 { + t.Fatalf("boot alone sent %d profiles; want none before the charger reports its connector", n) + } + reportStatus16(t, cp, core.ChargePointStatusAvailable) awaitProfiles(t, fake.count, 1) fake.mu.Lock() @@ -82,9 +101,12 @@ func TestManagedChargerStartsAtZeroAmpsOnBoot(t *testing.T) { // it at 0 A for good. A pending charger is not FTW's to steer at all. func TestUnmanagedChargersGetNoBootLimit(t *testing.T) { srv := startManagedServer(t, false) - _, managed, _ := connectCharger(t, srv, srv.cfg.Port, "garage") - _, metered, _ := connectCharger(t, srv, srv.cfg.Port, "metered") - _, pending, _ := connectCharger(t, srv, srv.cfg.Port, "stranger") + cpManaged, managed, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + cpMetered, metered, _ := connectCharger(t, srv, srv.cfg.Port, "metered") + cpPending, pending, _ := connectCharger(t, srv, srv.cfg.Port, "stranger") + for _, cp := range []ocpp16.ChargePoint{cpManaged, cpMetered, cpPending} { + reportStatus16(t, cp, core.ChargePointStatusAvailable) + } awaitProfiles(t, managed.count, 1) settle() if n := metered.count(); n != 0 { @@ -108,6 +130,7 @@ func TestRefusedBootLimitIsNotRetried(t *testing.T) { if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { t.Fatal(err) } + reportStatus16(t, cp, core.ChargePointStatusAvailable) awaitProfiles(t, fake.count, 2) settle() if n := fake.count(); n != 2 { @@ -139,7 +162,7 @@ func TestBootWithCarAlreadyReportedGetsNoBootLimit(t *testing.T) { // reconnectAndBoot drops the charger's socket, waits for FTW to see it go, // then dials again and sends a BootNotification before any status, as much // firmware does after a Wi-Fi drop. It returns the new socket's charger. -func reconnectAndBoot(t *testing.T, srv *Server, stop func()) *fakeCharger { +func reconnectAndBoot(t *testing.T, srv *Server, stop func()) (ocpp16.ChargePoint, *fakeCharger) { t.Helper() stop() deadline := time.Now().Add(2 * time.Second) @@ -157,7 +180,7 @@ func reconnectAndBoot(t *testing.T, srv *Server, stop func()) *fakeCharger { if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { t.Fatal(err) } - return fake + return cp, fake } // A Wi-Fi drop mid-session: the charger had reported Charging and taken @@ -166,6 +189,7 @@ func reconnectAndBoot(t *testing.T, srv *Server, stop func()) *fakeCharger { func TestReconnectBootMidSessionKeepsFTWOrder(t *testing.T) { srv := startManagedServer(t, false) cp, fake, stop := connectCharger(t, srv, srv.cfg.Port, "garage") + reportStatus16(t, cp, core.ChargePointStatusAvailable) awaitProfiles(t, fake.count, 1) // the real boot's 0 A if _, err := cp.StatusNotification(1, core.NoError, core.ChargePointStatusCharging); err != nil { t.Fatal(err) @@ -174,7 +198,8 @@ func TestReconnectBootMidSessionKeepsFTWOrder(t *testing.T) { t.Fatal(err) } - after := reconnectAndBoot(t, srv, stop) + cpAfter, after := reconnectAndBoot(t, srv, stop) + reportStatus16(t, cpAfter, core.ChargePointStatusCharging) settle() if n := after.count(); n != 0 { t.Fatalf("reconnect boot mid-session got %d profile(s), last %v A; want FTW's live 16 A kept", n, after.lastLimit(t)) @@ -186,12 +211,11 @@ func TestReconnectBootMidSessionKeepsFTWOrder(t *testing.T) { func TestReconnectBootWithNoCarGetsBootLimit(t *testing.T) { srv := startManagedServer(t, false) cp, fake, stop := connectCharger(t, srv, srv.cfg.Port, "garage") + reportStatus16(t, cp, core.ChargePointStatusAvailable) awaitProfiles(t, fake.count, 1) - if _, err := cp.StatusNotification(1, core.NoError, core.ChargePointStatusAvailable); err != nil { - t.Fatal(err) - } - after := reconnectAndBoot(t, srv, stop) + cpAfter, after := reconnectAndBoot(t, srv, stop) + reportStatus16(t, cpAfter, core.ChargePointStatusAvailable) awaitProfiles(t, after.count, 1) if got := after.lastLimit(t); got != 0 { t.Fatalf("reconnect boot with no car: limit %v A, want 0 A", got) @@ -220,6 +244,7 @@ func TestBootAnsweringIdentityProbeGetsNoBootLimit(t *testing.T) { if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { t.Fatal(err) } + reportStatus16(t, cp, core.ChargePointStatusAvailable) settle() if n := fake.count(); n != 0 { t.Fatalf("boot answering FTW's probe got %d profiles, want 0", n) @@ -229,8 +254,11 @@ func TestBootAnsweringIdentityProbeGetsNoBootLimit(t *testing.T) { // 2.0.1: the same 0 A TxDefaultProfile on EVSE 0, replaced by FTW's order. func TestV201ManagedStationStartsAtZeroAmpsOnBoot(t *testing.T) { srv := startManagedServer(t, true) - fake, _ := connectStationV201(t, srv, srv.cfg.PortV201, "garage") + cs, fake := bootStationV201(t, srv) count := func() int { fake.mu.Lock(); defer fake.mu.Unlock(); return len(fake.profiles) } + if _, err := cs.StatusNotification(types201.NewDateTime(time.Now()), availability.ConnectorStatusAvailable, 1, 1); err != nil { + t.Fatal(err) + } awaitProfiles(t, count, 1) fake.mu.Lock() @@ -252,3 +280,59 @@ func TestV201ManagedStationStartsAtZeroAmpsOnBoot(t *testing.T) { t.Fatalf("order limit %v A, want 16 A", got) } } + +// Rig s7s-restart-short-25A on 964643e9: Core restarts during Charge now. The +// charger reconnects to the new process and sends its own BootNotification at +// once, before FTW's identity probe, then reports connector 0 Available and +// connector 1 Charging. The new process holds no status and no transaction, so +// the boot alone looks like a fresh start. FTW sent 0 A, the car went to +// SuspendedEVSE for a second, and "Charge now never stops" failed. The status +// after the boot shows the car, so no start limit goes out. +func TestCoreRestartBootMidSessionGetsNoBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + fake := newFakeCharger() + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cp.BootNotification("Rig11", "RigCo"); err != nil { + t.Fatal(err) + } + reportStatus16(t, cp, core.ChargePointStatusCharging) + settle() + if n := fake.count(); n != 0 { + t.Fatalf("boot after a Core restart with the car charging got %d profile(s), last %v A; want none", + n, fake.lastLimit(t)) + } +} + +// bootStationV201 dials "garage" on 2.0.1 and sends a BootNotification. +func bootStationV201(t *testing.T, srv *Server) (ocpp201.ChargingStation, *fakeStationV201) { + t.Helper() + fake := newFakeStationV201() + cs, _, err := dialChargingStation201(t, wsURL(srv.cfg.PortV201), "garage", func(cs ocpp201.ChargingStation) { cs.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cs.BootNotification(provisioning.BootReasonPowerUp, "Dawn", "Charge Amps"); err != nil { + t.Fatal(err) + } + return cs, fake +} + +// The s7s shape on 2.0.1: after a Core restart the station boots on its own +// and reports its connector Occupied. No start limit. +func TestV201CoreRestartBootWithCarGetsNoBootLimit(t *testing.T) { + srv := startManagedServer(t, true) + cs, fake := bootStationV201(t, srv) + if _, err := cs.StatusNotification(types201.NewDateTime(time.Now()), availability.ConnectorStatusOccupied, 1, 1); err != nil { + t.Fatal(err) + } + settle() + fake.mu.Lock() + n := len(fake.profiles) + fake.mu.Unlock() + if n != 0 { + t.Fatalf("boot after a Core restart with a car got %d profile(s); want none", n) + } +} diff --git a/go/internal/ocpp/handlers.go b/go/internal/ocpp/handlers.go index 4d1b34205..bc2869c83 100644 --- a/go/internal/ocpp/handlers.go +++ b/go/internal/ocpp/handlers.go @@ -125,6 +125,9 @@ type chargerState struct { identityProbeEpoch uint64 identityProbeAttempts int identityProbeAfter time.Time + // bootLimitPending marks a boot that may get the 0 A start limit once + // the next connector status shows no car. See boot_limit.go. + bootLimitPending bool // vehicleID is the identity presented when the current/last transaction // started: the RFID idTag on 1.6, or a 2.0.1 idToken — where the token // type MacAddress (autocharge) or eMAID (ISO 15118) names the actual @@ -434,6 +437,7 @@ func (h *Handler) OnConnect(id string) { s.charging = false s.clearMeasuredPower() s.identityCurrent = false + s.bootLimitPending = false s.featureProfiles = "" s.steerable = nil h.cancelIdentityProbeLocked(s) @@ -455,6 +459,7 @@ func (h *Handler) OnDisconnect(id string) { delete(h.probing, id) s.online = false s.identityCurrent = false + s.bootLimitPending = false h.cancelIdentityProbeLocked(s) s.connectedKnown = false s.charging = false @@ -587,6 +592,7 @@ func (h *Handler) OnStatusNotification(id string, req *core.StatusNotificationRe h.pushReading(id, s) h.telSuccess(id) + h.resolveBootLimit(id) return core.NewStatusNotificationConfirmation(), nil } diff --git a/go/internal/ocpp/handlers_v201.go b/go/internal/ocpp/handlers_v201.go index e88571692..fac40fb5c 100644 --- a/go/internal/ocpp/handlers_v201.go +++ b/go/internal/ocpp/handlers_v201.go @@ -139,6 +139,7 @@ func (h *handlerV201) OnStatusNotification(id string, req *availability.StatusNo h.telSuccess(id) } h.pushReading(id, s) + h.resolveBootLimit(id) return availability.NewStatusNotificationResponse(), nil } From e6fc34b1a2bae0658945de7f0645ce5d294e7056 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:10:21 +0100 Subject: [PATCH 4/6] fix(ocpp): start limit waits for every socket's status The 0 A start limit goes to connector or EVSE 0, the whole charger. It went out on the first connector status after a boot that showed no car. On a two-socket 1.6 charger or a two-EVSE 2.0.1 station, a Core restart while a car charged on socket 2 sent 0 A as soon as socket 1 reported Available, and paused that car. FTW now waits until the statuses after the boot have been quiet for one second. Any status that shows a car or a transaction cancels the limit as it arrives, since the last status wins in FTW's one state per charger. An order from FTW during the wait also cancels it, so the 0 A cannot land after that order. Co-Authored-By: Claude Opus 5.5 --- .changeset/c9-ocpp-safe-boot-profile.md | 2 +- go/internal/ocpp/boot_limit.go | 65 +++++++++++++--- go/internal/ocpp/boot_limit_test.go | 99 ++++++++++++++++++++++++- go/internal/ocpp/control.go | 5 ++ go/internal/ocpp/handlers.go | 13 +++- 5 files changed, 168 insertions(+), 16 deletions(-) diff --git a/.changeset/c9-ocpp-safe-boot-profile.md b/.changeset/c9-ocpp-safe-boot-profile.md index 73b1877b3..19bb7f326 100644 --- a/.changeset/c9-ocpp-safe-boot-profile.md +++ b/.changeset/c9-ocpp-safe-boot-profile.md @@ -2,4 +2,4 @@ "ftw": patch --- -An OCPP charger that a loadpoint names now starts at 0 A when it boots and reports no car. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW waits for the charger's first connector status after the boot, so a charger that reconnects to a restarted Core with a car charging is not paused. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. +An OCPP charger that a loadpoint names now starts at 0 A when it boots and reports no car. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW waits until the connector statuses after the boot have been quiet for one second, and any socket that reports a car cancels the limit, so a charger that reconnects to a restarted Core with a car charging on any socket is not paused. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. diff --git a/go/internal/ocpp/boot_limit.go b/go/internal/ocpp/boot_limit.go index 39fe33cfe..2167e94f8 100644 --- a/go/internal/ocpp/boot_limit.go +++ b/go/internal/ocpp/boot_limit.go @@ -15,8 +15,18 @@ package ocpp import ( "context" "log/slog" + "time" ) +// defaultBootLimitSettle is how long the connector statuses after a boot must +// stay quiet before the start limit goes out. The limit covers the whole +// charger, so one socket's Available proves nothing while another socket may +// still report a car. A charger sends its statuses one after another, each +// after FTW's reply, so on a local network the burst ends within tens of +// milliseconds. One second leaves room for a slow link and still sends the +// limit seconds before FTW's first order would take hold. +const defaultBootLimitSettle = time.Second + // SetManagedIDs declares which approved chargers FTW orders: those a loadpoint // names. An id listed only under ocpp.chargers is approved and metered but // never ordered, so a 0 A start would hold it at 0 A for good. Replaces the @@ -34,8 +44,8 @@ func (h *Handler) SetManagedIDs(ids []string) { } // maybeSendBootLimit marks a BootNotification for the 0 A start limit. The -// limit goes out on the first connector status after it, and only when that -// status shows no car (resolveBootLimit). +// limit goes out once the connector statuses after it settle, and only when +// none of them showed a car (resolveBootLimit). // // A boot alone does not show a fresh start. After a Core restart the new // process holds no status and no transaction, and much firmware sends its own @@ -53,19 +63,56 @@ func (h *Handler) maybeSendBootLimit(id string) { h.mu.Lock() defer h.mu.Unlock() s := h.chargersLocked(id) + s.bootLimitEpoch++ s.bootLimitPending = h.bootLimit != nil && h.approved[id] && h.managed[id] && s.identityProbeAttempts == 0 && !s.connected && s.transactionID < 0 } -// resolveBootLimit runs after each connector status. The first one after a -// marked boot decides: no car and no transaction sends the start limit; a car -// sends nothing, since FTW orders that car every tick. The send runs on its -// own goroutine, as the capability probe does, and goes through the same -// one-at-a-time slot as every other order. A refusal is logged once; the next -// boot tries again. +// resolveBootLimit runs after each connector status. A status that shows a car +// or an open transaction on any socket cancels the start limit: FTW orders +// that car every tick, and 0 A for the whole charger would pause it. A status +// with no car starts the settle timer again, so the limit goes out only after +// the statuses have been quiet for bootLimitSettle. FTW keeps one connection +// state per charger and the last status wins, so the cancel happens here, as +// each status arrives, not when the timer fires. func (h *Handler) resolveBootLimit(id string) { + h.mu.Lock() + defer h.mu.Unlock() + s := h.chargersLocked(id) + if !s.bootLimitPending { + return + } + if s.connected || s.transactionID >= 0 { + s.bootLimitPending = false + return + } + s.bootLimitEpoch++ + epoch := s.bootLimitEpoch + time.AfterFunc(h.bootLimitSettle, func() { h.fireBootLimit(id, epoch) }) +} + +// cancelBootLimit drops a pending start limit when FTW orders the charger +// during the settle wait. That order is newer, and a 0 A landing after it +// would undo it. +func (h *Handler) cancelBootLimit(id string) { + h.mu.Lock() + defer h.mu.Unlock() + if s := h.chargers[id]; s != nil { + s.bootLimitPending = false + } +} + +// fireBootLimit sends the start limit when no status, boot or socket change +// came after the timer that calls it, and still no car or transaction shows. +// The send goes through the same one-at-a-time slot as every other order. A +// refusal is logged once; the next boot tries again. +func (h *Handler) fireBootLimit(id string, epoch uint64) { h.mu.Lock() s := h.chargersLocked(id) + if s.bootLimitEpoch != epoch { + h.mu.Unlock() + return + } send := h.bootLimit if !s.bootLimitPending || !h.approved[id] || !h.managed[id] || s.connected || s.transactionID >= 0 { send = nil @@ -73,7 +120,7 @@ func (h *Handler) resolveBootLimit(id string) { s.bootLimitPending = false h.mu.Unlock() if send != nil { - go send(id) + send(id) } } diff --git a/go/internal/ocpp/boot_limit_test.go b/go/internal/ocpp/boot_limit_test.go index 0c27f388c..6284567d8 100644 --- a/go/internal/ocpp/boot_limit_test.go +++ b/go/internal/ocpp/boot_limit_test.go @@ -19,16 +19,23 @@ import ( // startManagedServer runs a 1.6 listener (and 2.0.1 when v201) where // "garage" is named by a loadpoint and "metered" is listed only under -// ocpp.chargers. +// ocpp.chargers. The status burst after a boot settles in testBootLimitSettle, +// well inside settle(), so a start limit that should not come has time to. func startManagedServer(t *testing.T, v201 bool) *Server { t.Helper() - return startOCPP(t, Config{ + srv := startOCPP(t, Config{ Enabled: true, Bind: "127.0.0.1", HeartbeatIntervalS: 60, ApprovedIDs: []string{"garage", "metered"}, ManagedIDs: []string{"garage"}, }, telemetry.NewStore(), v201) + srv.handler.mu.Lock() + srv.handler.bootLimitSettle = testBootLimitSettle + srv.handler.mu.Unlock() + return srv } +const testBootLimitSettle = 50 * time.Millisecond + func awaitProfiles(t *testing.T, count func() int, want int) { t.Helper() deadline := time.Now().Add(3 * time.Second) @@ -336,3 +343,91 @@ func TestV201CoreRestartBootWithCarGetsNoBootLimit(t *testing.T) { t.Fatalf("boot after a Core restart with a car got %d profile(s); want none", n) } } + +// A Core restart while a car charges on socket 2 of a two-socket 1.6 +// charger. The charger boots on its own and reports socket 1 Available +// before socket 2 Charging. The start limit goes to connector 0, the whole +// charger, so sending it on socket 1's status would pause the car on socket +// 2. FTW waits for the status burst to settle; the car on socket 2 cancels it. +func TestDualSocketCoreRestartCarOnSocket2GetsNoBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + fake := newFakeCharger() + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cp.BootNotification("Twin", "RigCo"); err != nil { + t.Fatal(err) + } + for connector, st := range []core.ChargePointStatus{core.ChargePointStatusAvailable, core.ChargePointStatusAvailable, core.ChargePointStatusCharging} { + if _, err := cp.StatusNotification(connector, core.NoError, st); err != nil { + t.Fatal(err) + } + } + settle() + if n := fake.count(); n != 0 { + t.Fatalf("two-socket restart with a car on socket 2 got %d profile(s), last %v A; want none", n, fake.lastLimit(t)) + } +} + +// The same charger reporting socket 2 first. FTW keeps one connection state +// per charger and the last status wins, so socket 1's later Available must +// not undo the car socket 2 showed during the burst. +func TestDualSocketCarReportedFirstStillCancelsBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + fake := newFakeCharger() + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { + t.Fatal(err) + } + if _, err := cp.BootNotification("Twin", "RigCo"); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + connector int + status core.ChargePointStatus + }{{0, core.ChargePointStatusAvailable}, {2, core.ChargePointStatusCharging}, {1, core.ChargePointStatusAvailable}} { + if _, err := cp.StatusNotification(c.connector, core.NoError, c.status); err != nil { + t.Fatal(err) + } + } + settle() + if n := fake.count(); n != 0 { + t.Fatalf("two-socket restart with a car on socket 2 reported first got %d profile(s); want none", n) + } +} + +// FTW orders the charger while the start limit waits for the statuses to +// settle. The order is newer, so the 0 A must not land after it. +func TestOrderDuringSettleWaitCancelsBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + cp, fake, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + reportStatus16(t, cp, core.ChargePointStatusAvailable) + if err := srv.Command(context.Background(), "garage", setCurrent11kW(t)); err != nil { + t.Fatal(err) + } + settle() + if n, got := fake.count(), fake.lastLimit(t); n != 1 || got != 16 { + t.Fatalf("order during the settle wait: %d profile(s), last %v A; want FTW's 16 A alone", n, got) + } +} + +// 2.0.1 with two EVSEs: EVSE 1 Available, then EVSE 2 Occupied. The start +// limit goes to EVSE 0, the whole station, so it must not go out. +func TestV201TwoEVSECoreRestartCarOnEVSE2GetsNoBootLimit(t *testing.T) { + srv := startManagedServer(t, true) + cs, fake := bootStationV201(t, srv) + if _, err := cs.StatusNotification(types201.NewDateTime(time.Now()), availability.ConnectorStatusAvailable, 1, 1); err != nil { + t.Fatal(err) + } + if _, err := cs.StatusNotification(types201.NewDateTime(time.Now()), availability.ConnectorStatusOccupied, 2, 1); err != nil { + t.Fatal(err) + } + settle() + fake.mu.Lock() + n := len(fake.profiles) + fake.mu.Unlock() + if n != 0 { + t.Fatalf("two-EVSE restart with a car on EVSE 2 got %d profile(s); want none", n) + } +} diff --git a/go/internal/ocpp/control.go b/go/internal/ocpp/control.go index 5d24a3986..0f853e52e 100644 --- a/go/internal/ocpp/control.go +++ b/go/internal/ocpp/control.go @@ -141,6 +141,11 @@ func (s *Server) Command(ctx context.Context, id string, payload []byte) (result return fmt.Errorf("ocpp: bad command payload for %s: %w", id, err) } + switch c.Action { + case "ev_set_current", "ev_pause", "ev_start", "ev_resume": + s.handler.cancelBootLimit(id) + } + switch c.Action { case "init", "deinit": // Lifecycle hooks that only mean something to a Lua VM. diff --git a/go/internal/ocpp/handlers.go b/go/internal/ocpp/handlers.go index bc2869c83..62438fb53 100644 --- a/go/internal/ocpp/handlers.go +++ b/go/internal/ocpp/handlers.go @@ -33,9 +33,11 @@ type Handler struct { // managed is the approved chargers a loadpoint names, which FTW orders. // bootLimit, set by the Server, holds each at 0 A from its boot until - // FTW's first order. See boot_limit.go. - managed map[string]bool - bootLimit func(id string) + // FTW's first order, once the connector statuses after the boot have + // been quiet for bootLimitSettle. See boot_limit.go. + managed map[string]bool + bootLimit func(id string) + bootLimitSettle time.Duration nextTxID int @@ -126,8 +128,10 @@ type chargerState struct { identityProbeAttempts int identityProbeAfter time.Time // bootLimitPending marks a boot that may get the 0 A start limit once - // the next connector status shows no car. See boot_limit.go. + // the status burst after it settles with no car. bootLimitEpoch names + // the latest settle timer. See boot_limit.go. bootLimitPending bool + bootLimitEpoch uint64 // vehicleID is the identity presented when the current/last transaction // started: the RFID idTag on 1.6, or a 2.0.1 idToken — where the token // type MacAddress (autocharge) or eMAID (ISO 15118) names the actual @@ -159,6 +163,7 @@ func NewHandler(tel *telemetry.Store, heartbeatIntervalS int) *Handler { approved: map[string]bool{}, probing: map[string]bool{}, identityProbeTiming: defaultIdentityProbeTiming, + bootLimitSettle: defaultBootLimitSettle, nextTxID: 1, } } From a814fb44920e18135f4bab2eb7ba3c7d4f39d09f Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:14:41 +0100 Subject: [PATCH 5/6] refactor(ocpp): set the boot-limit wait beside the boot-limit sender Start sets the settle wait next to bootLimit instead of in NewHandler, which keeps this branch from touching the line #1787 changes there. Co-Authored-By: Claude Opus 5.5 --- go/internal/ocpp/handlers.go | 1 - go/internal/ocpp/server.go | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/go/internal/ocpp/handlers.go b/go/internal/ocpp/handlers.go index 62438fb53..b7cccb1c9 100644 --- a/go/internal/ocpp/handlers.go +++ b/go/internal/ocpp/handlers.go @@ -163,7 +163,6 @@ func NewHandler(tel *telemetry.Store, heartbeatIntervalS int) *Handler { approved: map[string]bool{}, probing: map[string]bool{}, identityProbeTiming: defaultIdentityProbeTiming, - bootLimitSettle: defaultBootLimitSettle, nextTxID: 1, } } diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index 2d0af142b..7f214d901 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -139,6 +139,7 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, e h.later = sockets.later h.SetManagedIDs(cfg.ManagedIDs) h.bootLimit = s.sendBootLimit + h.bootLimitSettle = defaultBootLimitSettle // OCPP 2.0.1 on its own port, when configured. Same handler and therefore // the same charger state and telemetry — only the message encoding differs. From 797f806cfa0ed2027b5252ea8dbc4ac6e54fcc13 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:36:09 +0100 Subject: [PATCH 6/6] fix(ocpp): meter values showing a car cancel the start limit After a Core restart a two-socket 1.6 charger may report socket 1 Available and then send socket 2's meter values for its running transaction before socket 2's status. Without #1787 FTW holds no transaction id then, so the 0 A start limit went to the whole charger and paused that car. A 1.6 meter value that names a transaction or measures power above zero now cancels the pending limit, as a status with a car does. Co-Authored-By: Claude Opus 5.5 --- .changeset/c9-ocpp-safe-boot-profile.md | 2 +- go/internal/ocpp/boot_limit.go | 11 +++++ go/internal/ocpp/boot_limit_test.go | 59 +++++++++++++++++++++++++ go/internal/ocpp/handlers.go | 2 + 4 files changed, 73 insertions(+), 1 deletion(-) diff --git a/.changeset/c9-ocpp-safe-boot-profile.md b/.changeset/c9-ocpp-safe-boot-profile.md index 19bb7f326..95b041429 100644 --- a/.changeset/c9-ocpp-safe-boot-profile.md +++ b/.changeset/c9-ocpp-safe-boot-profile.md @@ -2,4 +2,4 @@ "ftw": patch --- -An OCPP charger that a loadpoint names now starts at 0 A when it boots and reports no car. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW waits until the connector statuses after the boot have been quiet for one second, and any socket that reports a car cancels the limit, so a charger that reconnects to a restarted Core with a car charging on any socket is not paused. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. +An OCPP charger that a loadpoint names now starts at 0 A when it boots and reports no car. Until now it ran at its own default, usually its full rating, until FTW's first order landed, so a car plugged in during that gap could draw 16 A per phase on a fuse FTW had not yet shared out. FTW waits until the connector statuses after the boot have been quiet for one second, and any socket that reports a car, or meter values that name a transaction or show power, cancels the limit, so a charger that reconnects to a restarted Core with a car charging on any socket is not paused. FTW's first order replaces the 0 A limit. A charger that refuses it is logged and not asked again until its next boot. A charger listed only under `ocpp.chargers`, which FTW meters but never orders, is left alone. diff --git a/go/internal/ocpp/boot_limit.go b/go/internal/ocpp/boot_limit.go index 2167e94f8..6c16b9752 100644 --- a/go/internal/ocpp/boot_limit.go +++ b/go/internal/ocpp/boot_limit.go @@ -91,6 +91,17 @@ func (h *Handler) resolveBootLimit(id string) { time.AfterFunc(h.bootLimitSettle, func() { h.fireBootLimit(id, epoch) }) } +// meterCancelsBootLimitLocked drops a pending start limit when a 1.6 meter +// value shows a car: it names a transaction, or it measures power above zero. +// After a Core restart a two-socket charger may send the running socket's +// meter values before that socket's status, and 0 A for the whole charger +// would pause its car. The caller holds h.mu. +func (s *chargerState) meterCancelsBootLimitLocked(txID *int, w float64) { + if txID != nil || w > 0 { + s.bootLimitPending = false + } +} + // cancelBootLimit drops a pending start limit when FTW orders the charger // during the settle wait. That order is newer, and a 0 A landing after it // would undo it. diff --git a/go/internal/ocpp/boot_limit_test.go b/go/internal/ocpp/boot_limit_test.go index 6284567d8..869d1f43e 100644 --- a/go/internal/ocpp/boot_limit_test.go +++ b/go/internal/ocpp/boot_limit_test.go @@ -431,3 +431,62 @@ func TestV201TwoEVSECoreRestartCarOnEVSE2GetsNoBootLimit(t *testing.T) { t.Fatalf("two-EVSE restart with a car on EVSE 2 got %d profile(s); want none", n) } } + +// A Core restart while a car charges on socket 2 of a two-socket 1.6 +// charger, where socket 2's status comes only after the wait. Socket 1 +// reports Available, then meter values for socket 2's car arrive inside the +// wait. They show the car, so the start limit must not go out to the whole +// charger. The meter values may name the transaction, or carry only power. +func TestMeterValuesShowingACarDuringWaitCancelBootLimit(t *testing.T) { + tx := 7 + for _, c := range []struct { + name string + txID *int + power string + }{ + {"transaction and 7 kW", &tx, "7000"}, + {"transaction at 0 W", &tx, "0"}, + {"7 kW without transaction", nil, "7000"}, + } { + t.Run(c.name, func(t *testing.T) { + srv := startManagedServer(t, false) + srv.handler.mu.Lock() + srv.handler.bootLimitSettle = 200 * time.Millisecond + srv.handler.mu.Unlock() + cp, fake, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + reportStatus16(t, cp, core.ChargePointStatusAvailable) + if _, err := cp.MeterValues(2, meterValues16(c.power), func(r *core.MeterValuesRequest) { r.TransactionId = c.txID }); err != nil { + t.Fatal(err) + } + time.Sleep(400 * time.Millisecond) + if n := fake.count(); n != 0 { + t.Fatalf("car on socket 2 shown by meter values got %d profile(s), last %v A; want none", n, fake.lastLimit(t)) + } + }) + } +} + +// Meter values with no transaction and 0 W show no car: the start limit +// still goes out. +func TestIdleMeterValuesDuringWaitKeepBootLimit(t *testing.T) { + srv := startManagedServer(t, false) + cp, fake, _ := connectCharger(t, srv, srv.cfg.Port, "garage") + reportStatus16(t, cp, core.ChargePointStatusAvailable) + if _, err := cp.MeterValues(1, meterValues16("0")); err != nil { + t.Fatal(err) + } + awaitProfiles(t, fake.count, 1) + if got := fake.lastLimit(t); got != 0 { + t.Fatalf("start limit after idle meter values = %v A; want 0", got) + } +} + +func meterValues16(powerW string) []types.MeterValue { + return []types.MeterValue{{ + Timestamp: types.NewDateTime(time.Now()), + SampledValue: []types.SampledValue{ + {Value: powerW, Measurand: types.MeasurandPowerActiveImport, Unit: types.UnitOfMeasureW}, + {Value: "12345", Measurand: types.MeasurandEnergyActiveImportRegister, Unit: types.UnitOfMeasureWh}, + }, + }} +} diff --git a/go/internal/ocpp/handlers.go b/go/internal/ocpp/handlers.go index b7cccb1c9..78dc142aa 100644 --- a/go/internal/ocpp/handlers.go +++ b/go/internal/ocpp/handlers.go @@ -640,8 +640,10 @@ func (h *Handler) OnMeterValues(id string, req *core.MeterValuesRequest) (*core. } if w, ok := meterPowerW(samples); ok { s.recordPower(w, measured, received) + s.meterCancelsBootLimitLocked(nil, w) } } + s.meterCancelsBootLimitLocked(req.TransactionId, 0) h.mu.Unlock() h.pushReading(id, s)