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
12 changes: 12 additions & 0 deletions .changeset/bundle-zaptec-0-3-0.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 13 additions & 0 deletions .changeset/slow-cloud-drivers-and-release.md
Original file line number Diff line number Diff line change
@@ -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`.
18 changes: 15 additions & 3 deletions docs/writing-a-driver.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion drivers/BUNDLED_SOURCE.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
24 changes: 24 additions & 0 deletions go/internal/drivers/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
51 changes: 50 additions & 1 deletion go/internal/drivers/lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import (
"errors"
"fmt"
"io"
"math"
net_http "net/http"
net_url "net/url"
"os"
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
107 changes: 87 additions & 20 deletions go/internal/drivers/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -301,13 +311,28 @@ 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
stop chan bool
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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading