diff --git a/.changeset/c9-ocpp-safe-boot-profile.md b/.changeset/c9-ocpp-safe-boot-profile.md new file mode 100644 index 000000000..95b041429 --- /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 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/cmd/ftw/ev_send.go b/go/cmd/ftw/ev_send.go index 959a46f8b..29535394a 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,41 @@ func ocppApprovedIDs(cfg *config.Config) []string { add(c.ID) } } + for _, id := range ocppManagedIDs(cfg) { + add(id) + } + 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 { + 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..4165d242e 100644 --- a/go/cmd/ftw/ev_send_test.go +++ b/go/cmd/ftw/ev_send_test.go @@ -46,6 +46,42 @@ 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) + } +} + +// 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 e5e895879..47256346a 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -1303,6 +1303,7 @@ func main() { // and one whose entry was removed goes back to pending. if ocppSrv != nil { ocppSrv.Handler().SetApprovedIDs(ocppApprovedIDs(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. @@ -1473,6 +1474,7 @@ func main() { HeartbeatIntervalS: cfg.OCPP.HeartbeatIntervalS, ChargerSecrets: cfg.OCPP.ChargerSecrets(), ApprovedIDs: approved, + ManagedIDs: ocppStartLimitIDs(cfg, setupMeasurementAtBoot), } 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..811e8ece3 --- /dev/null +++ b/go/cmd/sim-ocpp/ocppcp/boot_limit_test.go @@ -0,0 +1,111 @@ +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) + } + // 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 { + 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..6c16b9752 --- /dev/null +++ b/go/internal/ocpp/boot_limit.go @@ -0,0 +1,144 @@ +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 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" + "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 +// 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 marks a BootNotification for the 0 A start limit. The +// 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 +// 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. +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. 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) }) +} + +// 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. +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 + } + s.bootLimitPending = false + h.mu.Unlock() + if send != nil { + 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..869d1f43e --- /dev/null +++ b/go/internal/ocpp/boot_limit_test.go @@ -0,0 +1,492 @@ +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" + 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" +) + +// 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. 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() + 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) + 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) } + +// 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) + 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() + 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) + 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 { + 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) + } + reportStatus16(t, cp, core.ChargePointStatusAvailable) + 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) + } +} + +// 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()) (ocpp16.ChargePoint, *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 cp, 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") + 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) + } + if err := srv.Command(context.Background(), "garage", setCurrent11kW(t)); err != nil { + t.Fatal(err) + } + + 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)) + } +} + +// 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") + reportStatus16(t, cp, core.ChargePointStatusAvailable) + awaitProfiles(t, fake.count, 1) + + 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) + } +} + +// 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) + } + 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) + } +} + +// 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) + 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() + 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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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/config.go b/go/internal/ocpp/config.go index c8f581ab0..242c2e1f9 100644 --- a/go/internal/ocpp/config.go +++ b/go/internal/ocpp/config.go @@ -55,6 +55,12 @@ 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, and empty while Core blocks every + // charger write (setup measurement mode). + ManagedIDs []string `yaml:"-"` } // TLSConfig points at the certificate this server presents, and optionally at 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 bf728a3bd..6eb327d0e 100644 --- a/go/internal/ocpp/handlers.go +++ b/go/internal/ocpp/handlers.go @@ -30,6 +30,15 @@ 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, 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 // vehicleIdentified, when set, fires once per new vehicle identity seen @@ -121,6 +130,11 @@ type chargerState struct { identityProbeEpoch uint64 identityProbeAttempts int identityProbeAfter time.Time + // bootLimitPending marks a boot that may get the 0 A start limit once + // 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 @@ -442,6 +456,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) @@ -463,6 +478,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 @@ -502,6 +518,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, @@ -594,6 +611,7 @@ func (h *Handler) OnStatusNotification(id string, req *core.StatusNotificationRe h.pushReading(id, s) h.telSuccess(id) + h.resolveBootLimit(id) return core.NewStatusNotificationConfirmation(), nil } @@ -642,8 +660,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) diff --git a/go/internal/ocpp/handlers_v201.go b/go/internal/ocpp/handlers_v201.go index b89cbfa17..fac40fb5c 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()), @@ -138,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 } diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index e3e3d39ce..7f214d901 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -137,6 +137,9 @@ 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 + 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.