Skip to content
5 changes: 5 additions & 0 deletions .changeset/c9-ocpp-safe-boot-profile.md
Original file line number Diff line number Diff line change
@@ -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.
40 changes: 32 additions & 8 deletions go/cmd/ftw/ev_send.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
}
Expand Down
36 changes: 36 additions & 0 deletions go/cmd/ftw/ev_send_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions go/cmd/ftw/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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{
Expand Down
111 changes: 111 additions & 0 deletions go/cmd/sim-ocpp/ocppcp/boot_limit_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
144 changes: 144 additions & 0 deletions go/internal/ocpp/boot_limit.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading