Skip to content

Commit 8539edc

Browse files
frahlgclaude
andcommitted
fix(loadpoint): Charge now keeps charging across a charger reconnect
A dropped charger socket, or a hardware identity that is missing for a while, is not an unplug. Charge now keeps its power, and the binding keeps the last proven charger. When the charger proves itself again, the same hardware keeps Charge now; another serial or session ID pauses it and asks for Start, as before. An observed unplug, Stop, a car that stops asking and a config change still end it. The site rig's s13 ("Charge now goes on after the charger returns") passes now, so its known line goes. Decision: #1788. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dca0656 commit 8539edc

8 files changed

Lines changed: 316 additions & 62 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"ftw": patch
3+
---
4+
5+
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.

‎go/cmd/ftw/ev_ocpp_blip_test.go‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"net"
8+
"testing"
9+
"time"
10+
11+
ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6"
12+
"github.com/lorenzodonini/ocpp-go/ocpp1.6/core"
13+
"github.com/srcfl/ftw/go/internal/events"
14+
"github.com/srcfl/ftw/go/internal/loadpoint"
15+
"github.com/srcfl/ftw/go/internal/ocpp"
16+
"github.com/srcfl/ftw/go/internal/ocpp/chargersocket"
17+
"github.com/srcfl/ftw/go/internal/telemetry"
18+
)
19+
20+
// A Wi-Fi blip drops the charger's socket while Charge now runs. The same
21+
// charger comes back still plugged in, and no unplug was seen.
22+
func TestChargeNowSurvivesOCPPSocketBlip(t *testing.T) {
23+
for _, tc := range []struct {
24+
name string
25+
serial string
26+
seeUnknown bool // a control tick runs while the socket is down
27+
unplugAfter bool // the charger reports Available after it returns
28+
wantW float64
29+
}{
30+
{name: "same charger", serial: "A", seeUnknown: true, wantW: 11040},
31+
{name: "same charger, blip between ticks", serial: "A", wantW: 11040},
32+
{name: "other charger", serial: "B", seeUnknown: true, wantW: 0},
33+
{name: "unplug reported after return", serial: "A", seeUnknown: true, unplugAfter: true, wantW: 0},
34+
} {
35+
t.Run(tc.name, func(t *testing.T) {
36+
listener, err := net.Listen("tcp", "127.0.0.1:0")
37+
if err != nil {
38+
t.Fatal(err)
39+
}
40+
port := listener.Addr().(*net.TCPAddr).Port
41+
listener.Close()
42+
tel := telemetry.NewStore()
43+
srv, err := ocpp.Start(context.Background(), &ocpp.Config{Enabled: true, Bind: "127.0.0.1", Port: port, ApprovedIDs: []string{"garage"}}, tel)
44+
if err != nil {
45+
t.Fatal(err)
46+
}
47+
defer srv.Stop()
48+
await := func(fn func() bool) {
49+
t.Helper()
50+
deadline := time.Now().Add(2 * time.Second)
51+
for !fn() {
52+
if time.Now().After(deadline) {
53+
t.Fatal("OCPP state did not settle")
54+
}
55+
time.Sleep(time.Millisecond)
56+
}
57+
}
58+
addr := fmt.Sprintf("127.0.0.1:%d", port)
59+
await(func() bool {
60+
c, e := net.DialTimeout("tcp", addr, 10*time.Millisecond)
61+
if e != nil {
62+
return false
63+
}
64+
c.Close()
65+
return true
66+
})
67+
connect := func(serial string) ocpp16.ChargePoint {
68+
t.Helper()
69+
cp := chargersocket.ChargePoint16("garage", nil)
70+
if e := cp.Start("ws://" + addr); e != nil {
71+
t.Fatal(e)
72+
}
73+
if _, e := cp.BootNotification("Home", "Easee", func(r *core.BootNotificationRequest) { r.ChargePointSerialNumber = serial }); e != nil {
74+
t.Fatal(e)
75+
}
76+
return cp
77+
}
78+
status := func(cp ocpp16.ChargePoint, s core.ChargePointStatus) {
79+
t.Helper()
80+
if _, e := cp.StatusNotification(1, core.NoError, s); e != nil {
81+
t.Fatal(e)
82+
}
83+
}
84+
cp := connect("A")
85+
status(cp, core.ChargePointStatusCharging)
86+
manager := loadpoint.NewManager()
87+
manager.Load([]loadpoint.Config{{ID: "garage", DriverName: "garage", MinChargeW: 1380, MaxChargeW: 11040, VehicleCapacityWh: 60000}})
88+
now := time.Now()
89+
manager.SetNowFn(func() time.Time { return now })
90+
bus := events.NewBus()
91+
manager.SetBus(bus)
92+
plugEdges := 0
93+
bus.Subscribe(events.KindChargingConnected, func(events.Event) { plugEdges++ })
94+
var commands []float64
95+
ctrl := loadpoint.NewController(manager, func(time.Time) (loadpoint.Directive, bool) { return loadpoint.Directive{}, false }, func(name string) (loadpoint.EVSample, bool) {
96+
return currentEVSample(tel.Get(name, telemetry.DerEV), tel.DriverHealth(name), time.Minute, time.Now(), srv.Handler().IsOnline(name), currentOCPPDeviceID(srv.Handler(), name))
97+
}, func(_ context.Context, _ string, p []byte) error {
98+
var d struct {
99+
Power float64 `json:"power_w"`
100+
Action string `json:"action"`
101+
}
102+
if e := json.Unmarshal(p, &d); e != nil {
103+
return e
104+
}
105+
if d.Action == "ev_set_current" {
106+
commands = append(commands, d.Power)
107+
}
108+
return nil
109+
})
110+
ctrl.SetSiteFuse(loadpoint.SiteFuse{MaxAmps: 25, Voltage: 230, PhaseCnt: 3})
111+
tick := func() { ctrl.Tick(context.Background(), now); now = now.Add(3 * time.Second) }
112+
tick()
113+
ctrl.SetManualHold("garage", loadpoint.ManualHold{Persistent: true, PowerW: 11040})
114+
tick()
115+
if len(commands) == 0 || commands[len(commands)-1] != 11040 {
116+
t.Fatalf("Charge now did not start: %v", commands)
117+
}
118+
sent := len(commands)
119+
120+
cp.Stop()
121+
await(func() bool { return !srv.Handler().IsOnline("garage") })
122+
if tc.seeUnknown {
123+
tick()
124+
}
125+
cp = connect(tc.serial)
126+
defer cp.Stop()
127+
status(cp, core.ChargePointStatusCharging)
128+
if tc.unplugAfter {
129+
tick()
130+
status(cp, core.ChargePointStatusAvailable)
131+
}
132+
tick()
133+
tick()
134+
135+
after := commands[sent:]
136+
hold, held := ctrl.GetManualHold("garage", now)
137+
st, _ := manager.State("garage")
138+
t.Logf("after the blip: commands=%v hold=%+v held=%v unconfirmed=%v plugged=%v", after, hold, held, st.ManualRestoreUnconfirmed, st.PluggedIn)
139+
if !tc.unplugAfter && (!st.PluggedIn || plugEdges != 0) {
140+
t.Fatalf("the blip looked like an unplug: plugged=%v plug edges=%d", st.PluggedIn, plugEdges)
141+
}
142+
if tc.wantW > 0 {
143+
if len(after) == 0 {
144+
t.Fatal("no command after the blip")
145+
}
146+
for _, w := range after {
147+
if w != tc.wantW {
148+
t.Fatalf("the blip changed Charge now: commands after it %v, want only %v", after, tc.wantW)
149+
}
150+
}
151+
if !held || hold.PowerW != tc.wantW || st.ManualRestoreUnconfirmed {
152+
t.Fatalf("Charge now did not survive: hold=%+v held=%v unconfirmed=%v", hold, held, st.ManualRestoreUnconfirmed)
153+
}
154+
return
155+
}
156+
if tc.unplugAfter {
157+
// An unplug ends Charge now; an empty charger gets no command.
158+
if held || st.PluggedIn {
159+
t.Fatalf("unplug did not end Charge now: hold=%+v held=%v plugged=%v", hold, held, st.PluggedIn)
160+
}
161+
return
162+
}
163+
if !held || hold.PowerW != 0 || !st.ManualRestoreUnconfirmed || len(after) == 0 || after[len(after)-1] != 0 {
164+
t.Fatalf("old Charge now followed %s: commands=%v hold=%+v unconfirmed=%v", tc.name, after, hold, st.ManualRestoreUnconfirmed)
165+
}
166+
})
167+
}
168+
}

‎go/cmd/ftw/ev_ocpp_reconnect_test.go‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ import (
2020
"github.com/srcfl/ftw/go/internal/telemetry"
2121
)
2222

23-
func TestOCPPReconnectDoesNotUnplugOrResumeOldStart(t *testing.T) {
23+
// A reconnect is not an unplug. The same charger keeps its Start; another
24+
// serial on the same charge point name pauses it and asks for Start.
25+
func TestOCPPReconnectIsNotAnUnplug(t *testing.T) {
2426
for _, power := range []float64{0, 4140} {
2527
for _, skipUnknown := range []bool{false, true} {
2628
t.Run(fmt.Sprintf("power=%v/fast=%v", power, skipUnknown), func(t *testing.T) {
@@ -131,8 +133,8 @@ func TestOCPPReconnectDoesNotUnplugOrResumeOldStart(t *testing.T) {
131133
tick()
132134
st, _ := manager.State("garage")
133135
hold, ok := ctrl.GetManualHold("garage", now)
134-
if !ok || hold.PowerW != 0 || !st.PluggedIn || st.ManualRestoreUnconfirmed != (power > 0) {
135-
t.Fatalf("unknown socket lost safety: hold=%+v state=%+v", hold, st)
136+
if !ok || hold.PowerW != power || !st.PluggedIn || st.ManualRestoreUnconfirmed {
137+
t.Fatalf("the outage changed the hold: hold=%+v state=%+v", hold, st)
136138
}
137139
if sendCount != commandCount {
138140
t.Fatal("unknown cable dispatched a command")
@@ -171,12 +173,16 @@ func TestOCPPReconnectDoesNotUnplugOrResumeOldStart(t *testing.T) {
171173
}
172174
status(cp, true)
173175
tick()
176+
want, unconfirmed := power, false
177+
if serial != "A" {
178+
want, unconfirmed = 0, power > 0
179+
}
174180
hold, ok := ctrl.GetManualHold("garage", now)
175-
if !ok || hold.PowerW != 0 || commands[len(commands)-1] != 0 {
176-
t.Fatalf("status revived an old Start: %+v %v", hold, commands)
181+
if !ok || hold.PowerW != want || commands[len(commands)-1] != want {
182+
t.Fatalf("serial %s after reconnect: hold=%+v commands=%v, want %v W", serial, hold, commands, want)
177183
}
178-
if st, _ := manager.State("garage"); st.ManualRestoreUnconfirmed != (power > 0) {
179-
t.Fatal("status changed required confirmation")
184+
if st, _ := manager.State("garage"); st.ManualRestoreUnconfirmed != unconfirmed {
185+
t.Fatalf("serial %s after reconnect: unconfirmed=%v, want %v", serial, st.ManualRestoreUnconfirmed, unconfirmed)
180186
}
181187
if connectedEvents != 0 {
182188
t.Fatalf("socket reconnect invented %d plug notifications", connectedEvents)

‎go/internal/loadpoint/controller_hold_restore.go‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,21 @@ type manualSessionBinding struct {
55
generation uint64
66
configuration uint64
77
connectionGeneration uint64
8+
// proofLost keeps the last proven hardware while the charger cannot
9+
// prove it, so the next proof is compared with it, not with nothing.
10+
proofLost bool
11+
}
12+
13+
func otherSession(previous, current manualSessionBinding) bool {
14+
return previous.sessionID != "" && current.sessionID != "" && previous.sessionID != current.sessionID
815
}
916

1017
func (m *Manager) manualSessionBinding(id string) manualSessionBinding {
1118
m.mu.RLock()
1219
defer m.mu.RUnlock()
1320
if lp := m.byID[id]; lp != nil {
14-
return manualSessionBinding{lp.sessionDeviceID, lp.sessionID, lp.sessionGeneration, lp.configGeneration, lp.connectionGeneration}
21+
return manualSessionBinding{deviceID: lp.sessionDeviceID, sessionID: lp.sessionID, generation: lp.sessionGeneration,
22+
configuration: lp.configGeneration, connectionGeneration: lp.connectionGeneration}
1523
}
1624
return manualSessionBinding{}
1725
}
@@ -50,14 +58,33 @@ func (c *Controller) restoreManualHoldForSession(id string) {
5058
c.manualBindings = map[string]manualSessionBinding{}
5159
}
5260
previous, bound := c.manualBindings[id]
53-
changed := bound && (previous.configuration != current.configuration ||
54-
(previous.connectionGeneration != 0 && current.connectionGeneration != 0 && previous.connectionGeneration != current.connectionGeneration))
61+
changed := bound && previous.configuration != current.configuration
62+
// A dropped socket or a lost hardware proof is not an unplug. Keep the
63+
// last proof until the charger proves itself again: the same charger
64+
// keeps Charge now, other hardware or another session does not.
65+
reconnected := bound && (previous.proofLost || (previous.connectionGeneration != 0 &&
66+
current.connectionGeneration != 0 && previous.connectionGeneration != current.connectionGeneration))
5567
if bound && previous.deviceID != "" {
56-
changed = changed || previous.deviceID != current.deviceID
57-
// ObserveSession preserves the generation for a valid first proof.
58-
// A changed generation therefore means a new connection or a counter
59-
// reset, even when the earlier session ID was still unknown.
60-
changed = changed || previous.generation != current.generation
68+
switch {
69+
case current.deviceID == "":
70+
if !changed {
71+
current = previous
72+
current.proofLost = true
73+
}
74+
case reconnected:
75+
changed = changed || previous.deviceID != current.deviceID || otherSession(previous, current)
76+
if !changed && current.sessionID == "" {
77+
// A driver can report the session after the hardware. Check
78+
// the next session against the last proven one.
79+
current.sessionID = previous.sessionID
80+
}
81+
default:
82+
changed = changed || previous.deviceID != current.deviceID || otherSession(previous, current)
83+
// ObserveSession preserves the generation for a valid first proof.
84+
// A changed generation therefore means a counter reset or a new
85+
// session, even when the earlier session ID was still unknown.
86+
changed = changed || previous.generation != current.generation
87+
}
6188
}
6289
// A Start before the first hardware reading binds here. Once bound, a
6390
// different hardware/session/config generation must not inherit its power.

0 commit comments

Comments
 (0)