Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/charge-now-survives-reconnect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

Charge now keeps charging when a charger's connection drops and the same charger comes back without an unplug, for example after a Wi-Fi drop. Before, FTW paused it until someone pressed Start again. Another charger or session on the same loadpoint still pauses it and asks for Start.
168 changes: 168 additions & 0 deletions go/cmd/ftw/ev_ocpp_blip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
package main

import (
"context"
"encoding/json"
"fmt"
"net"
"testing"
"time"

ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6"
"github.com/lorenzodonini/ocpp-go/ocpp1.6/core"
"github.com/srcfl/ftw/go/internal/events"
"github.com/srcfl/ftw/go/internal/loadpoint"
"github.com/srcfl/ftw/go/internal/ocpp"
"github.com/srcfl/ftw/go/internal/ocpp/chargersocket"
"github.com/srcfl/ftw/go/internal/telemetry"
)

// A Wi-Fi blip drops the charger's socket while Charge now runs. The same
// charger comes back still plugged in, and no unplug was seen.
func TestChargeNowSurvivesOCPPSocketBlip(t *testing.T) {
for _, tc := range []struct {
name string
serial string
seeUnknown bool // a control tick runs while the socket is down
unplugAfter bool // the charger reports Available after it returns
wantW float64
}{
{name: "same charger", serial: "A", seeUnknown: true, wantW: 11040},
{name: "same charger, blip between ticks", serial: "A", wantW: 11040},
{name: "other charger", serial: "B", seeUnknown: true, wantW: 0},
{name: "unplug reported after return", serial: "A", seeUnknown: true, unplugAfter: true, wantW: 0},
} {
t.Run(tc.name, func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
tel := telemetry.NewStore()
srv, err := ocpp.Start(context.Background(), &ocpp.Config{Enabled: true, Bind: "127.0.0.1", Port: port, ApprovedIDs: []string{"garage"}}, tel)
if err != nil {
t.Fatal(err)
}
defer srv.Stop()
await := func(fn func() bool) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for !fn() {
if time.Now().After(deadline) {
t.Fatal("OCPP state did not settle")
}
time.Sleep(time.Millisecond)
}
}
addr := fmt.Sprintf("127.0.0.1:%d", port)
await(func() bool {
c, e := net.DialTimeout("tcp", addr, 10*time.Millisecond)
if e != nil {
return false
}
c.Close()
return true
})
connect := func(serial string) ocpp16.ChargePoint {
t.Helper()
cp := chargersocket.ChargePoint16("garage", nil)
if e := cp.Start("ws://" + addr); e != nil {
t.Fatal(e)
}
if _, e := cp.BootNotification("Home", "Easee", func(r *core.BootNotificationRequest) { r.ChargePointSerialNumber = serial }); e != nil {
t.Fatal(e)
}
return cp
}
status := func(cp ocpp16.ChargePoint, s core.ChargePointStatus) {
t.Helper()
if _, e := cp.StatusNotification(1, core.NoError, s); e != nil {
t.Fatal(e)
}
}
cp := connect("A")
status(cp, core.ChargePointStatusCharging)
manager := loadpoint.NewManager()
manager.Load([]loadpoint.Config{{ID: "garage", DriverName: "garage", MinChargeW: 1380, MaxChargeW: 11040, VehicleCapacityWh: 60000}})
now := time.Now()
manager.SetNowFn(func() time.Time { return now })
bus := events.NewBus()
manager.SetBus(bus)
plugEdges := 0
bus.Subscribe(events.KindChargingConnected, func(events.Event) { plugEdges++ })
var commands []float64
ctrl := loadpoint.NewController(manager, func(time.Time) (loadpoint.Directive, bool) { return loadpoint.Directive{}, false }, func(name string) (loadpoint.EVSample, bool) {
return currentEVSample(tel.Get(name, telemetry.DerEV), tel.DriverHealth(name), time.Minute, time.Now(), srv.Handler().IsOnline(name), currentOCPPDeviceID(srv.Handler(), name))
}, func(_ context.Context, _ string, p []byte) error {
var d struct {
Power float64 `json:"power_w"`
Action string `json:"action"`
}
if e := json.Unmarshal(p, &d); e != nil {
return e
}
if d.Action == "ev_set_current" {
commands = append(commands, d.Power)
}
return nil
})
ctrl.SetSiteFuse(loadpoint.SiteFuse{MaxAmps: 25, Voltage: 230, PhaseCnt: 3})
tick := func() { ctrl.Tick(context.Background(), now); now = now.Add(3 * time.Second) }
tick()
ctrl.SetManualHold("garage", loadpoint.ManualHold{Persistent: true, PowerW: 11040})
tick()
if len(commands) == 0 || commands[len(commands)-1] != 11040 {
t.Fatalf("Charge now did not start: %v", commands)
}
sent := len(commands)

cp.Stop()
await(func() bool { return !srv.Handler().IsOnline("garage") })
if tc.seeUnknown {
tick()
}
cp = connect(tc.serial)
defer cp.Stop()
status(cp, core.ChargePointStatusCharging)
if tc.unplugAfter {
tick()
status(cp, core.ChargePointStatusAvailable)
}
tick()
tick()

after := commands[sent:]
hold, held := ctrl.GetManualHold("garage", now)
st, _ := manager.State("garage")
t.Logf("after the blip: commands=%v hold=%+v held=%v unconfirmed=%v plugged=%v", after, hold, held, st.ManualRestoreUnconfirmed, st.PluggedIn)
if !tc.unplugAfter && (!st.PluggedIn || plugEdges != 0) {
t.Fatalf("the blip looked like an unplug: plugged=%v plug edges=%d", st.PluggedIn, plugEdges)
}
if tc.wantW > 0 {
if len(after) == 0 {
t.Fatal("no command after the blip")
}
for _, w := range after {
if w != tc.wantW {
t.Fatalf("the blip changed Charge now: commands after it %v, want only %v", after, tc.wantW)
}
}
if !held || hold.PowerW != tc.wantW || st.ManualRestoreUnconfirmed {
t.Fatalf("Charge now did not survive: hold=%+v held=%v unconfirmed=%v", hold, held, st.ManualRestoreUnconfirmed)
}
return
}
if tc.unplugAfter {
// An unplug ends Charge now; an empty charger gets no command.
if held || st.PluggedIn {
t.Fatalf("unplug did not end Charge now: hold=%+v held=%v plugged=%v", hold, held, st.PluggedIn)
}
return
}
if !held || hold.PowerW != 0 || !st.ManualRestoreUnconfirmed || len(after) == 0 || after[len(after)-1] != 0 {
t.Fatalf("old Charge now followed %s: commands=%v hold=%+v unconfirmed=%v", tc.name, after, hold, st.ManualRestoreUnconfirmed)
}
})
}
}
20 changes: 13 additions & 7 deletions go/cmd/ftw/ev_ocpp_reconnect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import (
"github.com/srcfl/ftw/go/internal/telemetry"
)

func TestOCPPReconnectDoesNotUnplugOrResumeOldStart(t *testing.T) {
// A reconnect is not an unplug. The same charger keeps its Start; another
// serial on the same charge point name pauses it and asks for Start.
func TestOCPPReconnectIsNotAnUnplug(t *testing.T) {
for _, power := range []float64{0, 4140} {
for _, skipUnknown := range []bool{false, true} {
t.Run(fmt.Sprintf("power=%v/fast=%v", power, skipUnknown), func(t *testing.T) {
Expand Down Expand Up @@ -131,8 +133,8 @@ func TestOCPPReconnectDoesNotUnplugOrResumeOldStart(t *testing.T) {
tick()
st, _ := manager.State("garage")
hold, ok := ctrl.GetManualHold("garage", now)
if !ok || hold.PowerW != 0 || !st.PluggedIn || st.ManualRestoreUnconfirmed != (power > 0) {
t.Fatalf("unknown socket lost safety: hold=%+v state=%+v", hold, st)
if !ok || hold.PowerW != power || !st.PluggedIn || st.ManualRestoreUnconfirmed {
t.Fatalf("the outage changed the hold: hold=%+v state=%+v", hold, st)
}
if sendCount != commandCount {
t.Fatal("unknown cable dispatched a command")
Expand Down Expand Up @@ -171,12 +173,16 @@ func TestOCPPReconnectDoesNotUnplugOrResumeOldStart(t *testing.T) {
}
status(cp, true)
tick()
want, unconfirmed := power, false
if serial != "A" {
want, unconfirmed = 0, power > 0
}
hold, ok := ctrl.GetManualHold("garage", now)
if !ok || hold.PowerW != 0 || commands[len(commands)-1] != 0 {
t.Fatalf("status revived an old Start: %+v %v", hold, commands)
if !ok || hold.PowerW != want || commands[len(commands)-1] != want {
t.Fatalf("serial %s after reconnect: hold=%+v commands=%v, want %v W", serial, hold, commands, want)
}
if st, _ := manager.State("garage"); st.ManualRestoreUnconfirmed != (power > 0) {
t.Fatal("status changed required confirmation")
if st, _ := manager.State("garage"); st.ManualRestoreUnconfirmed != unconfirmed {
t.Fatalf("serial %s after reconnect: unconfirmed=%v, want %v", serial, st.ManualRestoreUnconfirmed, unconfirmed)
}
if connectedEvents != 0 {
t.Fatalf("socket reconnect invented %d plug notifications", connectedEvents)
Expand Down
43 changes: 35 additions & 8 deletions go/internal/loadpoint/controller_hold_restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,21 @@ type manualSessionBinding struct {
generation uint64
configuration uint64
connectionGeneration uint64
// proofLost keeps the last proven hardware while the charger cannot
// prove it, so the next proof is compared with it, not with nothing.
proofLost bool
}

func otherSession(previous, current manualSessionBinding) bool {
return previous.sessionID != "" && current.sessionID != "" && previous.sessionID != current.sessionID
}

func (m *Manager) manualSessionBinding(id string) manualSessionBinding {
m.mu.RLock()
defer m.mu.RUnlock()
if lp := m.byID[id]; lp != nil {
return manualSessionBinding{lp.sessionDeviceID, lp.sessionID, lp.sessionGeneration, lp.configGeneration, lp.connectionGeneration}
return manualSessionBinding{deviceID: lp.sessionDeviceID, sessionID: lp.sessionID, generation: lp.sessionGeneration,
configuration: lp.configGeneration, connectionGeneration: lp.connectionGeneration}
}
return manualSessionBinding{}
}
Expand Down Expand Up @@ -50,14 +58,33 @@ func (c *Controller) restoreManualHoldForSession(id string) {
c.manualBindings = map[string]manualSessionBinding{}
}
previous, bound := c.manualBindings[id]
changed := bound && (previous.configuration != current.configuration ||
(previous.connectionGeneration != 0 && current.connectionGeneration != 0 && previous.connectionGeneration != current.connectionGeneration))
changed := bound && previous.configuration != current.configuration
// A dropped socket or a lost hardware proof is not an unplug. Keep the
// last proof until the charger proves itself again: the same charger
// keeps Charge now, other hardware or another session does not.
reconnected := bound && (previous.proofLost || (previous.connectionGeneration != 0 &&
current.connectionGeneration != 0 && previous.connectionGeneration != current.connectionGeneration))
if bound && previous.deviceID != "" {
changed = changed || previous.deviceID != current.deviceID
// ObserveSession preserves the generation for a valid first proof.
// A changed generation therefore means a new connection or a counter
// reset, even when the earlier session ID was still unknown.
changed = changed || previous.generation != current.generation
switch {
case current.deviceID == "":
if !changed {
current = previous
current.proofLost = true
}
case reconnected:
changed = changed || previous.deviceID != current.deviceID || otherSession(previous, current)
if !changed && current.sessionID == "" {
// A driver can report the session after the hardware. Check
// the next session against the last proven one.
current.sessionID = previous.sessionID
Comment on lines +76 to +79

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain the previous session until a non-empty proof arrives

If the hardware identity returns before the session ID and remains session-less for two controller ticks, the previous session is forgotten. The first tick copies previous.sessionID here, but clears proofLost and adopts the current connection generation; the second tick therefore takes the default branch and overwrites the binding with an empty session ID. When a different session subsequently arrives, otherSession cannot detect it, and ObserveSample treats it as a first session proof without changing the generation, so the new session inherits the old Charge now power instead of requiring confirmation. Preserve the last proven session across every session-less tick; adding a second consecutive tick("easee:A", "", 4140, false) to TestLostProofCannotHandStartToALateNewSession exercises this gap.

Useful? React with 👍 / 👎.

}
default:
changed = changed || previous.deviceID != current.deviceID || otherSession(previous, current)
// ObserveSession preserves the generation for a valid first proof.
// A changed generation therefore means a counter reset or a new
// session, even when the earlier session ID was still unknown.
changed = changed || previous.generation != current.generation
}
}
// A Start before the first hardware reading binds here. Once bound, a
// different hardware/session/config generation must not inherit its power.
Expand Down
Loading
Loading