From f3193dcc6dd3abfebb462b672717ea1aecc1b0db Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 25 Nov 2026 07:02:31 +0100 Subject: [PATCH 1/2] fix(drivers): give slow cloud drivers time, hand devices back on removal A Zaptec Cloud command that took longer than 5 s failed, and the safe default then paused the charger at 0 A. A driver can now ask for up to 30 s per call with host.set_command_timeout_s; the control tick still waits only its short deadline and the call finishes in the driver's queue. Removing or disabling a driver calls its optional driver_release instead of driver_default_mode, so a charger goes back to the owner's own current rather than staying at FTW's 0 A. Restarts, shutdown and stale readings keep the safe default. Co-Authored-By: Claude Opus 5.5 --- .changeset/slow-cloud-drivers-and-release.md | 13 + docs/writing-a-driver.md | 18 +- go/internal/drivers/host.go | 24 ++ go/internal/drivers/lua.go | 51 +++- go/internal/drivers/registry.go | 107 ++++++-- go/internal/drivers/registry_release_test.go | 249 +++++++++++++++++++ 6 files changed, 438 insertions(+), 24 deletions(-) create mode 100644 .changeset/slow-cloud-drivers-and-release.md create mode 100644 go/internal/drivers/registry_release_test.go diff --git a/.changeset/slow-cloud-drivers-and-release.md b/.changeset/slow-cloud-drivers-and-release.md new file mode 100644 index 000000000..61144045f --- /dev/null +++ b/.changeset/slow-cloud-drivers-and-release.md @@ -0,0 +1,13 @@ +--- +"ftw": patch +--- + +Slow cloud chargers no longer get paused for being slow. A driver can ask for +up to 30 s per call with `host.set_command_timeout_s`; the control tick still +waits only its short deadline, and the call finishes in the driver's own +queue. Before, a Zaptec command that took longer than 5 s failed, and the safe +default then paused the charger at 0 A. + +Removing or disabling a driver now calls its optional `driver_release`, so a +charger goes back to the owner's own current instead of staying at FTW's 0 A. +A restart, a shutdown or a stale reading still uses `driver_default_mode`. diff --git a/docs/writing-a-driver.md b/docs/writing-a-driver.md index 9d58c3de7..dfef90ffc 100644 --- a/docs/writing-a-driver.md +++ b/docs/writing-a-driver.md @@ -36,7 +36,7 @@ current host API and the source of truth for it. Today it registers: |---|---| | Telemetry | `emit`, `emit_metric` | | Identity and nameplate | `set_make`, `set_sn`, `set_model`, `set_rated_w` | -| Driver control | `set_poll_interval`, `set_warmup_s`, `set_watchdog_timeout_s`, `set_device_fault` | +| Driver control | `set_poll_interval`, `set_warmup_s`, `set_watchdog_timeout_s`, `set_command_timeout_s`, `set_device_fault` | | Helpers | `log`, `sleep`, `millis`, `now_ms`, `unix_ms`, `json_encode`, `json_decode`, `persist_secret` | | Vehicle | `reserve_vehicle_wake`, `site_location` | | Decoding | `decode_string`, `decode_i16`, `decode_i32_be`, `decode_i32_le`, `decode_u32_be`, `decode_u32_le` | @@ -138,9 +138,21 @@ Sign conversion happens only here. Read driver is a bug. A controllable device needs a real `driver_default_mode`. The host calls it for -stale telemetry, relevant reloads, removal and shutdown, so it is the path that +stale telemetry, relevant reloads, restarts and shutdown, so it is the path that returns hardware to safe autonomous operation when FTW stops being able to -steer it. Polling must not keep re-emitting an indefinitely cached value as +steer it. + +When the owner removes or disables a driver, FTW is done with the device, and +the host calls the optional `driver_release()` instead. A driver whose safe +stop is stored on the device, such as a charger held at 0 A, gives the owner's +own setting back there. Without `driver_release` the host uses +`driver_default_mode`, as before. Return `false` when the device refuses. + +Each command, default, release and cleanup call gets 5 s. A driver whose vendor +cloud answers slowly calls `host.set_command_timeout_s(seconds)` in +`driver_init` for up to 30 s. The control tick does not wait longer: the call +finishes in the driver's own queue, and only a call that runs out of that time +counts as failed. Polling must not keep re-emitting an indefinitely cached value as fresh telemetry: age vendor data and stop emitting when it is stale, or core's watchdog cannot see the fault. diff --git a/go/internal/drivers/host.go b/go/internal/drivers/host.go index 6c20e3601..251fe4cdc 100644 --- a/go/internal/drivers/host.go +++ b/go/internal/drivers/host.go @@ -189,6 +189,10 @@ type HostEnv struct { // their registers carry meaningful values. Set via host.set_warmup_s // in driver_init; read once by the registry's run loop. WarmupS float64 + // CommandTimeoutS is how long one driver call may run before the host + // gives up on it, for drivers whose vendor cloud answers slowly. Set via + // host.set_command_timeout_s in driver_init. Zero keeps the host default. + CommandTimeoutS float64 // PersistSecret, when non-nil, lets a driver write a secret (e.g. a // rotated OAuth refresh_token) into its own persisted KV namespace. @@ -802,6 +806,26 @@ func (h *HostEnv) setWarmupS(s float64) { h.mu.Unlock() } +// setCommandTimeoutS records how long one driver call may run, in seconds. +func (h *HostEnv) setCommandTimeoutS(s float64) { + h.mu.Lock() + h.CommandTimeoutS = s + h.mu.Unlock() +} + +// CommandTimeout returns the call time the driver asked for, or 0. +func (h *HostEnv) CommandTimeout() time.Duration { + if h == nil { + return 0 + } + h.mu.Lock() + defer h.mu.Unlock() + if h.CommandTimeoutS <= 0 { + return 0 + } + return time.Duration(h.CommandTimeoutS * float64(time.Second)) +} + // DeviceModel returns the model name the driver reported, or "" if it // reported none. Named DeviceModel because the field is Model. func (h *HostEnv) DeviceModel() string { diff --git a/go/internal/drivers/lua.go b/go/internal/drivers/lua.go index 4c8c84426..173c7c848 100644 --- a/go/internal/drivers/lua.go +++ b/go/internal/drivers/lua.go @@ -44,6 +44,7 @@ import ( "errors" "fmt" "io" + "math" net_http "net/http" net_url "net/url" "os" @@ -60,6 +61,9 @@ import ( // per-driver staleness window. Tesla's 5-minute BLE proxy fits; a year does not. const maxDriverWatchdogTimeout = 15 * time.Minute +// maxDriverCommandTimeout caps host.set_command_timeout_s. +const maxDriverCommandTimeout = 30 * time.Second + // driverInitTimeout bounds driver_init. An init that runs past it fails like // any other init error, so a looping or hung init cannot block boot, a reload // or a settings save. @@ -475,6 +479,21 @@ func (d *LuaDriver) DefaultModeContext(ctx context.Context) error { return d.call(ctx, "driver_default_mode") } +// ErrNoRelease means the driver defines no driver_release. The registry then +// stops it with driver_default_mode, as before release existed. +var ErrNoRelease = errors.New("driver defines no driver_release") + +// ReleaseContext calls driver_release() when the owner removes or disables +// the driver: FTW stops managing the device for good, so the driver gives +// back the owner's own settings instead of holding FTW's safe stop. A +// restart, a shutdown or a stale reading still uses driver_default_mode. +func (d *LuaDriver) ReleaseContext(ctx context.Context) error { + if !d.hasEntrypoint("driver_release") { + return ErrNoRelease + } + return d.call(ctx, "driver_release") +} + // hasEntrypoint reports whether the loaded driver defines a callable global. // Missing lifecycle hooks remain optional for reporting-only drivers, so the // registry uses this only when it has already established that an operator @@ -494,7 +513,7 @@ func (d *LuaDriver) call(ctx context.Context, name string) error { if fn == lua.LNil { return nil } - cleanup := d.setLuaCallContext(ctx, 5*time.Second) + cleanup := d.setLuaCallContext(ctx, d.lifecycleCallTimeout()) defer cleanup() if err := d.L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}); err != nil { return err @@ -504,6 +523,16 @@ func (d *LuaDriver) call(ctx context.Context, name string) error { return luaReturnError(name, ret) } +// lifecycleCallTimeout bounds one lifecycle call: 5 s, or longer when the +// driver asked for it with host.set_command_timeout_s. +func (d *LuaDriver) lifecycleCallTimeout() time.Duration { + timeout := 5 * time.Second + if t := d.Env.CommandTimeout(); t > timeout { + timeout = t + } + return timeout +} + func luaReturnError(name string, ret lua.LValue) error { switch v := ret.(type) { case lua.LBool: @@ -806,6 +835,26 @@ func registerHost(L *lua.LState, env *HostEnv) { return 0 })) + // host.set_command_timeout_s(seconds) — call from driver_init. A + // driver whose vendor cloud answers slowly gets this long for each + // command, default mode, release and cleanup call, instead of 5 s. The + // control tick still waits only its own short deadline; the command + // finishes in the driver's actor and its result is recorded there. + // 0 restores the default. Values above 30 s are capped so a hung + // cloud cannot hold the driver's safety default for long. + host.RawSetString("set_command_timeout_s", L.NewFunction(func(L *lua.LState) int { + secs := float64(L.CheckNumber(1)) + if secs < 0 || math.IsNaN(secs) || math.IsInf(secs, 0) { + L.Push(lua.LString("set_command_timeout_s: timeout must be >= 0")) + return 1 + } + if limit := maxDriverCommandTimeout.Seconds(); secs > limit { + secs = limit + } + env.setCommandTimeoutS(secs) + return 0 + })) + // host.persist_secret(key, value) -> ok, err // Writes a secret into the driver's own persisted KV namespace. // Managed read-only OAuth drivers need a signed config_secrets entry. diff --git a/go/internal/drivers/registry.go b/go/internal/drivers/registry.go index 5d7f4ecff..7eeb81c7c 100644 --- a/go/internal/drivers/registry.go +++ b/go/internal/drivers/registry.go @@ -248,6 +248,16 @@ func (l *luaRuntime) Cleanup(ctx context.Context) error { l.LuaDriver.CleanupContext(ctx) return nil } +func (l *luaRuntime) Release(ctx context.Context) error { + return l.LuaDriver.ReleaseContext(ctx) +} + +// releaser is a runtime that can hand its device back to the owner when the +// driver is removed for good. Returning ErrNoRelease means it cannot, and the +// registry stops it with driver_default_mode instead. +type releaser interface { + Release(ctx context.Context) error +} func (l *luaRuntime) Env() *HostEnv { return l.LuaDriver.Env } func driverInitConfigJSON(cfg config.Driver, troubleshootingMode bool) []byte { @@ -301,6 +311,9 @@ type runningDriver struct { // defaultRetryMax. Tests set them. retryInitial time.Duration retryMax time.Duration + // releaseOnStop is set before stop is sent when the owner removed or + // disabled the driver. The send on stop orders it before the read. + releaseOnStop bool // Poll loop coordination cmdCh chan driverCmd defaultCh chan driverCmd @@ -308,6 +321,18 @@ type runningDriver struct { done chan struct{} } +// runTimeout is the least time one driver call gets: commandRunTimeout, or +// longer when a slow cloud driver asked for it in driver_init. +func (rd *runningDriver) runTimeout() time.Duration { + timeout := commandRunTimeout + if rd != nil && rd.env != nil { + if t := rd.env.CommandTimeout(); t > timeout { + timeout = t + } + } + return timeout +} + func (rd *runningDriver) controlStatus() DriverControlStatus { rd.statusMu.RLock() defer rd.statusMu.RUnlock() @@ -369,15 +394,40 @@ func (rd *runningDriver) markDefaultRecoveryPending() { rd.statusMu.Unlock() } -// commandRunContext gives a started command at least commandRunTimeout. A -// caller deadline shorter than that ends only the caller's wait; an explicit -// cancel still stops the command. -func commandRunContext(caller context.Context) (context.Context, func()) { +// stopDevice is the last write before a driver stops. A driver the owner +// removed or disabled hands its device back with driver_release when it has +// one; every other stop, and a driver without release, uses +// driver_default_mode. +func stopDevice(ctx context.Context, rd *runningDriver) error { + if rd.releaseOnStop { + if rel, ok := rd.driver.(releaser); ok { + err := rel.Release(ctx) + if !errors.Is(err, ErrNoRelease) { + if err != nil { + slog.Error("driver failed to hand its device back on removal", "name", rd.cfg.Name, "err", err) + } else { + slog.Info("driver handed its device back on removal", "name", rd.cfg.Name) + } + return err + } + } + } + err := rd.driver.DefaultMode(ctx) + if err != nil { + slog.Error("driver failed to enter default mode during shutdown", "name", rd.cfg.Name, "err", err) + } + return err +} + +// commandRunContext gives a started command at least least. A caller deadline +// shorter than that ends only the caller's wait; an explicit cancel still +// stops the command. +func commandRunContext(caller context.Context, least time.Duration) (context.Context, func()) { deadline, ok := caller.Deadline() - if !ok || time.Until(deadline) >= commandRunTimeout { + if !ok || time.Until(deadline) >= least { return caller, func() {} } - run, cancel := context.WithTimeout(context.WithoutCancel(caller), commandRunTimeout) + run, cancel := context.WithTimeout(context.WithoutCancel(caller), least) stop := context.AfterFunc(caller, func() { if errors.Is(caller.Err(), context.Canceled) { cancel() @@ -817,7 +867,11 @@ func (r *Registry) add(ctx context.Context, cfg config.Driver, startupDefault bo } var startupDefaultErr error if startupDefault && !cfg.ObserveOnly && !r.controlBlocked() { - defaultCtx, cancel := context.WithTimeout(ctx, defaultRecoveryTimeout) + startupTimeout := defaultRecoveryTimeout + if t := drv.Env().CommandTimeout(); t > startupTimeout { + startupTimeout = t + } + defaultCtx, cancel := context.WithTimeout(ctx, startupTimeout) startupDefaultErr = drv.DefaultMode(defaultCtx) cancel() if startupDefaultErr != nil { @@ -958,7 +1012,7 @@ func (r *Registry) runLoop(rd *runningDriver) { // continuation before the default call starts, regardless of whether // the device later confirms it. invalidateCommandSequence() - defaultCtx, cancel := context.WithTimeout(context.Background(), defaultRecoveryTimeout) + defaultCtx, cancel := context.WithTimeout(context.Background(), rd.runTimeout()) defaultErr := rd.driver.DefaultMode(defaultCtx) if r.tel != nil { r.tel.EndCommandControl(rd.cfg.Name, defaultErr != nil) @@ -994,11 +1048,13 @@ func (r *Registry) runLoop(rd *runningDriver) { cmdCtx = ctx } // Once accepted, a safety default must survive its caller timing out - // behind an older command. A fresh bounded attempt keeps that request - // durable without letting the actor block forever. + // behind an older command, and a slow cloud driver gets the time it + // asked for even when its caller waits less. A fresh bounded attempt + // keeps that request durable without letting the actor block forever. var cancel context.CancelFunc - if cmdCtx.Err() != nil { - cmdCtx, cancel = context.WithTimeout(context.Background(), defaultRecoveryTimeout) + least := rd.runTimeout() + if deadline, ok := cmdCtx.Deadline(); cmdCtx.Err() != nil || ok && time.Until(deadline) < least { + cmdCtx, cancel = context.WithTimeout(context.Background(), least) } err := rd.driver.DefaultMode(cmdCtx) if r.tel != nil { @@ -1035,17 +1091,14 @@ func (r *Registry) runLoop(rd *runningDriver) { rd.driver.Discard() } else { invalidateCommandSequence() - shutdownCtx, cancel := context.WithTimeout(context.Background(), defaultRecoveryTimeout) - defaultErr := rd.driver.DefaultMode(shutdownCtx) + shutdownCtx, cancel := context.WithTimeout(context.Background(), rd.runTimeout()) + defaultErr := stopDevice(shutdownCtx, rd) rd.setShutdownDefaultError(defaultErr) - if defaultErr != nil { - slog.Error("driver failed to enter default mode during shutdown", "name", rd.cfg.Name, "err", defaultErr) - } cancel() // The lifecycle context is already canceled. driver_cleanup // gets its own bound so the hand-back it performs (releasing // a PV curtailment, for one) still runs. - cleanupCtx, cancelCleanup := context.WithTimeout(context.Background(), defaultRecoveryTimeout) + cleanupCtx, cancelCleanup := context.WithTimeout(context.Background(), rd.runTimeout()) _ = rd.driver.Cleanup(cleanupCtx) cancelCleanup() } @@ -1130,7 +1183,7 @@ func (r *Registry) runLoop(rd *runningDriver) { // late must fail and restore the default, not latch as pending. runCtx, finishRun := cmdCtx, func() {} if cmd.cycleID == 0 { - runCtx, finishRun = commandRunContext(cmdCtx) + runCtx, finishRun = commandRunContext(cmdCtx, rd.runTimeout()) } commandCtx, finishCommand := rd.beginCommand(runCtx) // SendDefault may close the control window after the earlier queue @@ -1276,6 +1329,19 @@ func (r *Registry) remove(name string, skipDefault bool) { r.removeLocked(name, skipDefault) } +// removeReleasingLocked stops a driver the owner removed or disabled. Its +// last write is driver_release, so the device goes back to the owner's own +// settings rather than staying in FTW's safe stop. The caller holds the +// per-name lifecycle gate, so the instance cannot change in between. +func (r *Registry) removeReleasingLocked(name string) { + r.mu.Lock() + if rd, ok := r.rec[name]; ok { + rd.releaseOnStop = true + } + r.mu.Unlock() + r.removeLocked(name, false) +} + // removeLocked stops a driver while its per-name lifecycle gate is held. This // lets Restart and Reload keep the old generation and its replacement in one // serialized transition instead of opening an Add/Remove gap. @@ -1585,8 +1651,9 @@ func (r *Registry) Reload(ctx context.Context, newDrivers []config.Driver, troub newCfg, stillThere := findDriver(active, n) requiresRestart := stillThere && (troubleshootingChanged || !sameDriverConfig(old, newCfg)) if !stillThere { + // The owner removed or disabled it: hand the device back. release := r.acquireLifecycle(n) - r.removeLocked(n, false) + r.removeReleasingLocked(n) release() } else if requiresRestart { if troubleshootingChanged { diff --git a/go/internal/drivers/registry_release_test.go b/go/internal/drivers/registry_release_test.go new file mode 100644 index 000000000..76d46bfa1 --- /dev/null +++ b/go/internal/drivers/registry_release_test.go @@ -0,0 +1,249 @@ +package drivers + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// releaseHookDriver records which stop hook ran, as metrics. +const releaseHookDriver = ` +function driver_init(config) + host.set_poll_interval(1000) +end +function driver_poll() return 1000 end +function driver_command(action, w, cmd) return true end +function driver_default_mode() + host.emit_metric("default_called", 1) +end +function driver_release() + host.emit_metric("release_called", 1) + return true +end +function driver_cleanup() + host.emit_metric("cleanup_called", 1) +end +` + +func addAndForgetStartup(t *testing.T, r *Registry, tel *telemetry.Store, cfg config.Driver) { + t.Helper() + if err := r.Add(context.Background(), cfg); err != nil { + t.Fatal(err) + } + // Add runs driver_default_mode once at startup; only the stop counts. + tel.FlushSamples() +} + +func TestOwnerRemovalReleasesTheDevice(t *testing.T) { + path := writeTestDriver(t, releaseHookDriver) + for _, tc := range []struct { + name string + next func(config.Driver) []config.Driver + }{ + {"removed from config", func(config.Driver) []config.Driver { return nil }}, + {"disabled", func(cfg config.Driver) []config.Driver { + cfg.Disabled = true + return []config.Driver{cfg} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + tel := telemetry.NewStore() + r := NewRegistry(tel) + t.Cleanup(r.ShutdownAll) + cfg := config.Driver{Name: "charger", Lua: path} + addAndForgetStartup(t, r, tel, cfg) + r.Reload(context.Background(), tc.next(cfg), false) + emitted := emittedHooks(tel) + if !emitted["charger:release_called"] { + t.Fatal("removing the driver did not hand the device back") + } + if emitted["charger:default_called"] { + t.Fatal("removing the driver also ran driver_default_mode, which would undo the hand-back") + } + if !emitted["charger:cleanup_called"] { + t.Fatal("driver_cleanup did not run after release") + } + r.mu.Lock() + blocked := r.recoveryRequired["charger"] + r.mu.Unlock() + if blocked { + t.Fatal("a successful release left the name's recovery gate closed") + } + }) + } +} + +func TestOtherStopsKeepTheSafeDefault(t *testing.T) { + path := writeTestDriver(t, releaseHookDriver) + for _, tc := range []struct { + name string + stop func(*Registry, config.Driver) error + }{ + {"shutdown", func(r *Registry, cfg config.Driver) error { r.ShutdownAll(); return nil }}, + {"restart", func(r *Registry, cfg config.Driver) error { return r.Restart(context.Background(), cfg) }}, + {"config change", func(r *Registry, cfg config.Driver) error { + cfg.Config = map[string]any{"changed": true} + r.Reload(context.Background(), []config.Driver{cfg}, false) + return nil + }}, + } { + t.Run(tc.name, func(t *testing.T) { + tel := telemetry.NewStore() + r := NewRegistry(tel) + t.Cleanup(r.ShutdownAll) + cfg := config.Driver{Name: "charger", Lua: path} + addAndForgetStartup(t, r, tel, cfg) + if err := tc.stop(r, cfg); err != nil { + t.Fatal(err) + } + emitted := emittedHooks(tel) + if emitted["charger:release_called"] { + t.Fatal("a stop that FTW comes back from handed the device to its owner") + } + if !emitted["charger:default_called"] { + t.Fatal("the stop did not run driver_default_mode") + } + }) + } +} + +func TestRemovalWithoutReleaseUsesDefault(t *testing.T) { + tel := telemetry.NewStore() + r := NewRegistry(tel) + t.Cleanup(r.ShutdownAll) + addAndForgetStartup(t, r, tel, config.Driver{Name: "d1", Lua: writeTestDriver(t, lifecycleHookDriver)}) + r.Reload(context.Background(), nil, false) + if !emittedHooks(tel)["d1:default_called"] { + t.Fatal("a driver without driver_release was removed without its safe default") + } +} + +func TestRefusedReleaseBlocksTheName(t *testing.T) { + tel := telemetry.NewStore() + r := NewRegistry(tel) + t.Cleanup(r.ShutdownAll) + addAndForgetStartup(t, r, tel, config.Driver{Name: "charger", Lua: writeTestDriver(t, ` +function driver_init(config) host.set_poll_interval(1000) end +function driver_poll() return 1000 end +function driver_command(action, w, cmd) return true end +function driver_default_mode() return true end +function driver_release() return false end +`)}) + r.Reload(context.Background(), nil, false) + r.mu.Lock() + blocked := r.recoveryRequired["charger"] + r.mu.Unlock() + if !blocked { + t.Fatal("a refused release cleared the name's recovery gate") + } +} + +func TestSetCommandTimeoutBounds(t *testing.T) { + for _, tc := range []struct { + name string + call string + want time.Duration + }{ + {"default", "", commandRunTimeout}, + {"longer", "host.set_command_timeout_s(12)", 12 * time.Second}, + {"capped", "host.set_command_timeout_s(600)", maxDriverCommandTimeout}, + {"shorter keeps the floor", "host.set_command_timeout_s(1)", commandRunTimeout}, + {"negative refused", `local err = host.set_command_timeout_s(-1) + if err == nil then error("negative timeout accepted") end`, commandRunTimeout}, + } { + t.Run(tc.name, func(t *testing.T) { + tel := telemetry.NewStore() + r := NewRegistry(tel) + t.Cleanup(r.ShutdownAll) + src := ` +function driver_init(config) + host.set_poll_interval(1000) + ` + tc.call + ` +end +function driver_poll() return 1000 end +function driver_command(action, w, cmd) return true end +function driver_default_mode() return true end +` + if err := r.Add(context.Background(), config.Driver{Name: "d1", Lua: writeTestDriver(t, src)}); err != nil { + t.Fatal(err) + } + r.mu.Lock() + rd := r.rec["d1"] + r.mu.Unlock() + if got := rd.runTimeout(); got != tc.want { + t.Fatalf("runTimeout = %s, want %s", got, tc.want) + } + }) + } +} + +// A slow cloud command that finishes after the caller stopped waiting is not +// a failure: it must complete, and must not trip the safe default (for a +// charger, a pause at 0 A). +func TestSlowCommandFinishesWithinDeclaredTime(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + declare string + wantDone bool + wantDefault bool + }{ + {"declared", "host.set_command_timeout_s(15)", true, false}, + {"undeclared", "", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tel := telemetry.NewStore() + r := NewRegistry(tel) + t.Cleanup(r.ShutdownAll) + src := ` +function driver_init(config) + host.set_poll_interval(60000) + ` + tc.declare + ` +end +function driver_poll() return 60000 end +function driver_command(action, w, cmd) + host.sleep(6500) + host.emit_metric("command_done", 1) + return true +end +function driver_default_mode() + host.emit_metric("default_called", 1) + return true +end +` + addAndForgetStartup(t, r, tel, config.Driver{Name: "cloud", Lua: writeTestDriver(t, src)}) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + err := r.Send(ctx, "cloud", []byte(`{"action":"ev_set_current","w":1380}`)) + cancel() + if !errors.Is(err, ErrCommandMayHaveRun) { + t.Fatalf("Send = %v, want ErrCommandMayHaveRun while the command runs on", err) + } + seen := map[string]bool{} + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + for k, v := range emittedHooks(tel) { + seen[k] = seen[k] || v + } + if seen["cloud:command_done"] || seen["cloud:default_called"] { + break + } + time.Sleep(100 * time.Millisecond) + } + time.Sleep(300 * time.Millisecond) + for k, v := range emittedHooks(tel) { + seen[k] = seen[k] || v + } + if seen["cloud:command_done"] != tc.wantDone { + t.Fatalf("command finished = %v, want %v", seen["cloud:command_done"], tc.wantDone) + } + if seen["cloud:default_called"] != tc.wantDefault { + t.Fatalf("safe default ran = %v, want %v", seen["cloud:default_called"], tc.wantDefault) + } + }) + } +} From d40836704dd6cdd7a29eed13ba06fe628c76d687 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 25 Nov 2026 07:09:37 +0100 Subject: [PATCH 2/2] fix(drivers): bundle zaptec_cloud 0.3.0 and easee_cloud 1.5.0 Move the pin to srcfl/device-drivers@28c771fd (#279). zaptec_cloud 0.3.0 uses host.set_command_timeout_s and driver_release from this PR. The pin also carries the easee_cloud fixes merged since e7b94b11 (#183, #227, #194, #236, #200), whose Core side (#2050, #2062) is already on master. Tell the stopped instance's default apart from a replacement's startup default in TestOtherStopsKeepTheSafeDefault (review finding). Co-Authored-By: Claude Opus 5.5 --- .changeset/bundle-zaptec-0-3-0.md | 12 ++++++++++++ drivers/BUNDLED_SOURCE.json | 2 +- go/internal/drivers/registry_release_test.go | 15 +++++++++++---- 3 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 .changeset/bundle-zaptec-0-3-0.md diff --git a/.changeset/bundle-zaptec-0-3-0.md b/.changeset/bundle-zaptec-0-3-0.md new file mode 100644 index 000000000..9686cbc78 --- /dev/null +++ b/.changeset/bundle-zaptec-0-3-0.md @@ -0,0 +1,12 @@ +--- +"ftw": patch +--- + +Bundle zaptec_cloud 0.3.0 and easee_cloud 1.5.0. Zaptec: a one-phase car on +an idle three-phase charger now starts at the charger's minimum instead of +getting 0 A, no positive current goes below the charger's own minimum, +removing the charger gives back the owner's maximum and resumes it, and slow +Zaptec Cloud calls get 20 s and one retry. Easee: re-sends the current limit +as a command, rejects out-of-order power readings, reports when Easee's load +balancing holds the car below FTW's order or holds a start, and exposes a +confirmed pilot current. Neither is confirmed on hardware yet. diff --git a/drivers/BUNDLED_SOURCE.json b/drivers/BUNDLED_SOURCE.json index 92cb4d6b8..7755a3d0b 100644 --- a/drivers/BUNDLED_SOURCE.json +++ b/drivers/BUNDLED_SOURCE.json @@ -16,7 +16,7 @@ "from the signed channel. Run scripts/sync-bundled-drivers.sh to update." ], "repository": "srcfl/device-drivers", - "commit": "e7b94b11ca6b0c41c1ed275af2a698917e05e767", + "commit": "28c771fd64694f375d1ebc5b6d57b3cf2032d34e", "source_dir": "drivers/lua", "drivers": [ "ambibox_v2x", "ctek", "ctek_hybrid", "ctek_v2", "deye", "easee_cloud", diff --git a/go/internal/drivers/registry_release_test.go b/go/internal/drivers/registry_release_test.go index 76d46bfa1..1e90b4283 100644 --- a/go/internal/drivers/registry_release_test.go +++ b/go/internal/drivers/registry_release_test.go @@ -10,15 +10,19 @@ import ( "github.com/srcfl/ftw/go/internal/telemetry" ) -// releaseHookDriver records which stop hook ran, as metrics. +// releaseHookDriver records which stop hook ran, as metrics. A default that +// runs after a command emits stop_default as well, so a stop's own default can +// be told apart from the startup default of a replacement instance. const releaseHookDriver = ` +local commanded = false function driver_init(config) host.set_poll_interval(1000) end function driver_poll() return 1000 end -function driver_command(action, w, cmd) return true end +function driver_command(action, w, cmd) commanded = true; return true end function driver_default_mode() host.emit_metric("default_called", 1) + if commanded then host.emit_metric("stop_default", 1) end end function driver_release() host.emit_metric("release_called", 1) @@ -97,6 +101,9 @@ func TestOtherStopsKeepTheSafeDefault(t *testing.T) { t.Cleanup(r.ShutdownAll) cfg := config.Driver{Name: "charger", Lua: path} addAndForgetStartup(t, r, tel, cfg) + if err := r.Send(context.Background(), "charger", []byte(`{"action":"ev_set_current","w":1380}`)); err != nil { + t.Fatal(err) + } if err := tc.stop(r, cfg); err != nil { t.Fatal(err) } @@ -104,8 +111,8 @@ func TestOtherStopsKeepTheSafeDefault(t *testing.T) { if emitted["charger:release_called"] { t.Fatal("a stop that FTW comes back from handed the device to its owner") } - if !emitted["charger:default_called"] { - t.Fatal("the stop did not run driver_default_mode") + if !emitted["charger:stop_default"] { + t.Fatal("the stopped instance did not run driver_default_mode") } }) }