From 6890ec2c8d8a840c05af209627a7afc772fba196 Mon Sep 17 00:00:00 2001 From: Segran Date: Sun, 15 Nov 2026 01:37:07 +0100 Subject: [PATCH 1/4] Treat battery calibration as a normal control state --- .changeset/pixii-calibration-status.md | 5 +++ docs/writing-a-driver.md | 2 +- go/internal/api/api_battery_manual.go | 24 ++++++++++---- go/internal/api/api_battery_manual_test.go | 20 ++++++++++++ go/internal/api/api_control_feedback.go | 15 ++++++--- go/internal/api/api_control_feedback_test.go | 22 +++++++++++++ go/internal/drivers/lua.go | 7 +++++ go/internal/telemetry/store.go | 16 +++++++++- web/components/ftw-battery-control.js | 33 ++++++++++++++++++-- web/control-feedback.js | 2 ++ 10 files changed, 130 insertions(+), 16 deletions(-) create mode 100644 .changeset/pixii-calibration-status.md diff --git a/.changeset/pixii-calibration-status.md b/.changeset/pixii-calibration-status.md new file mode 100644 index 000000000..b9a116f6f --- /dev/null +++ b/.changeset/pixii-calibration-status.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +Show battery calibration as a normal operating state and suspend control and scoped manual overrides while calibration is active. diff --git a/docs/writing-a-driver.md b/docs/writing-a-driver.md index a91d6e0e2..a35717407 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_device_fault`, `set_calibrating` | | 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` | diff --git a/go/internal/api/api_battery_manual.go b/go/internal/api/api_battery_manual.go index 07bf888dc..95fcd6e64 100644 --- a/go/internal/api/api_battery_manual.go +++ b/go/internal/api/api_battery_manual.go @@ -31,11 +31,12 @@ type batteryManualHoldRequest struct { // batteryManualHoldResponse mirrors the active hold so the operator // can confirm what's installed. type batteryManualHoldResponse struct { - Active bool `json:"active"` - Direction string `json:"direction,omitempty"` - PowerW float64 `json:"power_w,omitempty"` - Driver string `json:"driver,omitempty"` - ExpiresAtMs int64 `json:"expires_at_ms,omitempty"` + Active bool `json:"active"` + Direction string `json:"direction,omitempty"` + PowerW float64 `json:"power_w,omitempty"` + Driver string `json:"driver,omitempty"` + ExpiresAtMs int64 `json:"expires_at_ms,omitempty"` + CalibratingDrivers []string `json:"calibrating_drivers,omitempty"` } // maxBatteryManualHoldS bounds the hold duration. 30 minutes matches @@ -117,6 +118,9 @@ func (s *Server) resolveBatteryManualHoldTarget(driver string) (string, int, err return "", http.StatusServiceUnavailable, apiError("battery control state not available") } health := s.deps.Tel.DriverHealth(driver) + if health != nil && health.Calibrating { + return "", http.StatusConflict, apiError("Manual override is unavailable while this battery is calibrating.") + } reading := s.deps.Tel.Get(driver, telemetry.DerBattery) if health == nil || !health.IsOnline() || reading == nil || reading.SoC == nil { return "", http.StatusConflict, apiError("battery driver is not ready for a scoped hold") @@ -148,7 +152,15 @@ func (s *Server) handleBatteryManualHoldGet(w http.ResponseWriter, r *http.Reque s.deps.CtrlMu.Lock() h, active := s.deps.Ctrl.GetBatteryManualHold(time.Now()) s.deps.CtrlMu.Unlock() - writeJSON(w, 200, batteryManualHoldResponseFrom(h, active)) + resp := batteryManualHoldResponseFrom(h, active) + if s.deps.Tel != nil { + for name, health := range s.deps.Tel.AllHealth() { + if health.Calibrating { + resp.CalibratingDrivers = append(resp.CalibratingDrivers, name) + } + } + } + writeJSON(w, 200, resp) } // signedPowerForDirection converts the wire format (direction + magnitude) diff --git a/go/internal/api/api_battery_manual_test.go b/go/internal/api/api_battery_manual_test.go index 942434215..d5104a663 100644 --- a/go/internal/api/api_battery_manual_test.go +++ b/go/internal/api/api_battery_manual_test.go @@ -244,3 +244,23 @@ func TestBatteryHoldDriverScopeFailsClosed(t *testing.T) { }) } } + +func TestBatteryHoldRejectsScopedCalibration(t *testing.T) { + srv, st := newScopedBatteryHoldServer(t) + srv.deps.Tel.SetDriverCalibrating("bat_a", true) + post := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/battery/manual_hold", strings.NewReader(`{"driver":"bat_a","direction":"idle","hold_s":60}`)) + srv.handleBatteryManualHold(post, req) + if post.Code != http.StatusConflict || !strings.Contains(post.Body.String(), "calibrating") { + t.Fatalf("got %d %s, want calibration conflict", post.Code, post.Body) + } + if _, active := st.GetBatteryManualHold(time.Now()); active { + t.Fatal("calibrating battery acquired a hold") + } + get := httptest.NewRecorder() + srv.handleBatteryManualHoldGet(get, httptest.NewRequest(http.MethodGet, "/api/battery/manual_hold", nil)) + var resp batteryManualHoldResponse + if err := json.Unmarshal(get.Body.Bytes(), &resp); err != nil || len(resp.CalibratingDrivers) != 1 || resp.CalibratingDrivers[0] != "bat_a" { + t.Fatalf("calibration status missing: %s, err=%v", get.Body, err) + } +} diff --git a/go/internal/api/api_control_feedback.go b/go/internal/api/api_control_feedback.go index 288cd4fea..599ebec7a 100644 --- a/go/internal/api/api_control_feedback.go +++ b/go/internal/api/api_control_feedback.go @@ -324,9 +324,14 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { if lp, ok := lps[rd.Driver]; ok && kind == telemetry.DerEV && f.Reason == "telemetry_stale" && evAwayIdle(lp, f.RequestedW) { f.State, f.Reason, f.Severity = "waiting", "not_connected", "info" } - if h := s.deps.Tel.DriverHealth(rd.Driver); h != nil && h.DeviceFault { - f.State, f.Reason, f.Severity = "blocked", "device_fault", "warning" - f.DeviceReason = h.DeviceFaultReason + if h := s.deps.Tel.DriverHealth(rd.Driver); h != nil { + switch { + case h.DeviceFault: + f.State, f.Reason, f.Severity = "blocked", "device_fault", "warning" + f.DeviceReason = h.DeviceFaultReason + case h.Calibrating && kind == telemetry.DerBattery: + f.State, f.Reason, f.Severity = "waiting", "battery_calibrating", "info" + } } if s.deps.Registry != nil { if cs, ok := s.deps.Registry.ControlStatus(rd.Driver); ok && cs.Blocked { @@ -427,7 +432,7 @@ func setControlStatus(f *ControlFeedback) { status, severity = "no_contact", "warning" case "readings_lost", "default_failed": status, severity = "no_contact", "alarm" - case "observe_only", "disabled", "device_control": + case "observe_only", "disabled", "device_control", "battery_calibrating": status = "not_controlled" case "site_meter_stale", "site_phase_currents_stale": status, severity = "not_controlled", "warning" @@ -465,7 +470,7 @@ func controlVerificationLost(f ControlFeedback, cmd telemetry.CommandEvidence, n return false } switch f.Reason { - case "observe_only", "disabled", "device_control", "not_connected", "idle", "no_command": + case "observe_only", "disabled", "device_control", "battery_calibrating", "not_connected", "idle", "no_command": return false } if f.Reason == "telemetry_stale" { diff --git a/go/internal/api/api_control_feedback_test.go b/go/internal/api/api_control_feedback_test.go index 1bd271b82..aaedfd4fc 100644 --- a/go/internal/api/api_control_feedback_test.go +++ b/go/internal/api/api_control_feedback_test.go @@ -310,3 +310,25 @@ func TestFullBatteryFeedbackKeepsEvidenceAndFaultsSeparate(t *testing.T) { }) } } + +func TestCalibrationKeepsBatteryTelemetryAndSuspendsControl(t *testing.T) { + tel := telemetry.NewStore() + tel.Update("battery", telemetry.DerBattery, 3000, watts(0.25), nil) + tel.RecordDriverSuccess("battery") + cfg := &config.Config{Drivers: []config.Driver{{Name: "battery", BatteryCapacityWh: 10000}}} + srv := New(&Deps{Tel: tel, Cfg: cfg, CfgMu: &sync.RWMutex{}}) + tel.SetDriverCalibrating("battery", true) + got := srv.controlFeedback(time.Now()) + if len(got) != 1 || got[0].Reason != "battery_calibrating" || got[0].Status != "not_controlled" || got[0].Severity != "info" || !got[0].ReadingsFresh { + t.Fatalf("unexpected calibration feedback: %+v", got) + } + health := tel.DriverHealth("battery") + if health.IsOnline() || health.DeviceFault || !health.TelemetryLive() { + t.Fatalf("calibration must suspend control only: %+v", health) + } + tel.SetDriverCalibrating("battery", false) + got = srv.controlFeedback(time.Now()) + if len(got) != 1 || got[0].Reason != "no_command" || !tel.DriverHealth("battery").IsOnline() { + t.Fatalf("control did not become available after calibration: %+v", got) + } +} diff --git a/go/internal/drivers/lua.go b/go/internal/drivers/lua.go index c629d8ad0..b1616275a 100644 --- a/go/internal/drivers/lua.go +++ b/go/internal/drivers/lua.go @@ -757,6 +757,13 @@ func registerHost(L *lua.LState, env *HostEnv) { return 0 })) + host.RawSetString("set_calibrating", L.NewFunction(func(L *lua.LState) int { + if env.Telemetry != nil { + env.Telemetry.SetDriverCalibrating(env.DriverName, L.CheckBool(1)) + } + return 0 + })) + host.RawSetString("set_sn", L.NewFunction(func(L *lua.LState) int { env.setSN(L.CheckString(1)) return 0 diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index 6bc61d1f7..995bdf453 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -153,6 +153,7 @@ type DriverHealth struct { // Read it; do not assign it. It is derived from the two sources below // so that both reach every consumer — /api/health, the driver // inventory, the support report — through one field. + Calibrating bool DeviceFault bool DeviceFaultReason string @@ -264,7 +265,7 @@ func (h *DriverHealth) SetCommandFault(faulted bool, reason string) { // IsOnline reports whether the driver is usable for control. A stale-flagged // driver (Status offline) OR one that cannot actuate is not. func (h *DriverHealth) IsOnline() bool { - return h.Status != StatusOffline && !h.DeviceFault + return h.Status != StatusOffline && !h.DeviceFault && !h.Calibrating } // TelemetryLive reports whether this driver's last reading is still a @@ -1014,6 +1015,19 @@ func (s *Store) SetDriverDeviceFault(name string, faulted bool, reason string) { } } +// SetDriverCalibrating records a device-managed calibration. Measurements +// remain live while the dispatcher and planner wait for control to resume. +func (s *Store) SetDriverCalibrating(name string, calibrating bool) { + s.mu.Lock() + defer s.mu.Unlock() + h, ok := s.health[name] + if !ok { + h = &DriverHealth{Name: name, StartedAt: time.Now()} + s.health[name] = h + } + h.Calibrating = calibrating +} + // SetDriverCommandFault records that core could not get its commands into // this device (or that it can again). Unlike SetDriverDeviceFault this does // NOT create a health record: only a driver that has been running can have diff --git a/web/components/ftw-battery-control.js b/web/components/ftw-battery-control.js index 9a897f6f3..d443c6ad7 100644 --- a/web/components/ftw-battery-control.js +++ b/web/components/ftw-battery-control.js @@ -211,6 +211,8 @@ class FtwBatteryControl extends FtwElement { constructor() { super(); this._refreshTimer = null; + this._calibratingDrivers = []; + this._installing = false; this._formState = { direction: "charge", holdS: 900, scopeDriver: "", scopeMode: "pool" }; } @@ -296,6 +298,7 @@ class FtwBatteryControl extends FtwElement { + @@ -351,6 +354,7 @@ class FtwBatteryControl extends FtwElement { button.classList.toggle("active", on); button.setAttribute("aria-checked", on ? "true" : "false"); }); + this._renderInstallAvailability(); this.dispatchEvent(new CustomEvent('ftw-battery-scope', {bubbles:true, composed:true, detail:{driver:mode === 'driver' ? this._formState.scopeDriver : ''}})); } @@ -422,10 +426,28 @@ class FtwBatteryControl extends FtwElement { stopBtn.disabled = false; } + _renderInstallAvailability() { + const driver = this._formState.scopeMode === "driver" ? this._formState.scopeDriver : ""; + const blocked = !!driver && this._calibratingDrivers.includes(driver); + const message = blocked + ? "Manual override is unavailable while this battery is calibrating." + : !driver && this._calibratingDrivers.length + ? "This override skips batteries that are calibrating." + : ""; + const notice = this.shadowRoot.querySelector("[data-calibration]"); + notice.textContent = message; + notice.classList.toggle("hidden", !message); + this.shadowRoot.querySelector("[data-install]").disabled = blocked || this._installing; + } + _refresh() { apiFetch("/api/battery/manual_hold") .then((r) => r.json()) - .then((d) => this._renderActive(d)) + .then((d) => { + this._calibratingDrivers = d.calibrating_drivers || []; + this._renderInstallAvailability(); + this._renderActive(d); + }) .catch(() => { /* network blip — leave previous state */ }); } @@ -434,6 +456,7 @@ class FtwBatteryControl extends FtwElement { const dir = this._formState.direction; const holdS = this._formState.holdS; const installBtn = this.shadowRoot.querySelector("[data-install]"); + if (installBtn.disabled) return; let powerW = 0; if (dir !== "idle") { const input = this.shadowRoot.querySelector("[data-power-input]"); @@ -447,7 +470,8 @@ class FtwBatteryControl extends FtwElement { if (this._formState.scopeMode === "driver" && this._formState.scopeDriver) { body.driver = this._formState.scopeDriver; } - installBtn.disabled = true; + this._installing = true; + this._renderInstallAvailability(); apiFetch("/api/battery/manual_hold", { method: "POST", headers: { "Content-Type": "application/json" }, @@ -463,7 +487,10 @@ class FtwBatteryControl extends FtwElement { }) .then((d) => this._renderActive(d)) .catch((err) => this._showError(err.message || "Failed to install hold")) - .finally(() => { installBtn.disabled = false; }); + .finally(() => { + this._installing = false; + this._renderInstallAvailability(); + }); } _stop() { diff --git a/web/control-feedback.js b/web/control-feedback.js index ce356726b..ccd26f4f5 100644 --- a/web/control-feedback.js +++ b/web/control-feedback.js @@ -71,6 +71,7 @@ const REASON_TITLES = { charger_limit: 'Limited by FTW’s charger setting', device_limit: 'Charger limit', offered_current_lower: 'Charger offers less current', load_balancer_limit: 'Limited by the charger’s load balancing', charger_pilot_limit: 'Limited by the charger', one_phase: 'Charging on one phase', + battery_calibrating: 'Calibrating', device_fault: 'Device fault', telemetry_stale: 'No fresh readings', readings_lost: 'Lost control', command_failed: 'Commands failing', command_unconfirmed: 'Command not confirmed', default_failed: 'Cannot hand back control', response_unknown: 'No power reading', observe_only: 'Monitoring only', disabled: 'Disabled', device_control: 'Own control', @@ -116,6 +117,7 @@ function sentence(row) { case 'no_power_response': return evPowerWarning(row) || `Asked for ${target(row)}, but it delivers no power.`; case 'power_while_idle': return `Asked to stay idle, but it is ${doing(row, actual)} ${controlPower(actual)}.`; case 'setpoint_changed': return `The ${name} reports a target of ${controlFlow(row, row.readback_w)}, not the ${target(row)} FTW sent.`; + case 'battery_calibrating': return 'The battery is calibrating its charge level. FTW waits for calibration to finish before controlling it.'; case 'device_fault': return row.device_reason ? `The ${name} reports a fault: ${row.device_reason}.` : `The ${name} reports a fault that stops control.`; case 'telemetry_stale': return `FTW has no fresh readings from the ${name}.`; case 'readings_lost': return clock(row.observed_at_ms) From 10cbddcf21304be9deb8dd45e087ed15dd4a910e Mon Sep 17 00:00:00 2001 From: Segran Date: Sun, 15 Nov 2026 01:48:02 +0100 Subject: [PATCH 2/4] Fix EV history test across midnight --- web/energy-history-integration.test.mjs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/web/energy-history-integration.test.mjs b/web/energy-history-integration.test.mjs index 25310464a..5a111e557 100644 --- a/web/energy-history-integration.test.mjs +++ b/web/energy-history-integration.test.mjs @@ -151,10 +151,18 @@ test('raw energy rows load only when opened, flag rejected data and page locally let expectedChargeWh = 0; let expectedChargeOre = 0; let omitSecondPrice = false; + // Both mock charging buckets must be in the past, including on CI runs + // shortly after midnight. + const now = new Date(2026, 6, 24, 12).getTime(); + const midnight = new Date(2026, 6, 24).getTime(); + class FixtureDate extends Date { + constructor(...args) { super(...(args.length ? args : [now])); } + static now() { return now; } + } const window = { addEventListener() {}, devicePixelRatio: 1 }; vm.runInNewContext(source, { - Array, Date, Intl, Map, Math, Number, Object, Promise, Set, String, URLSearchParams, + Array, Date: FixtureDate, Intl, Map, Math, Number, Object, Promise, Set, String, URLSearchParams, document: { createElement() { return element({ id: 'option' }); }, documentElement: {}, @@ -173,13 +181,8 @@ test('raw energy rows load only when opened, flag rejected data and page locally const params = new URLSearchParams(path.split('?')[1]); if (params.get('bucket') === '30m') { evHistoryRequests += 1; - const since = Number(params.get('since')); const bucket = 1800000; - const today = new Date(); - today.setHours(0, 0, 0, 0); - const first = Math.floor(today.getTime() / bucket) * bucket; - const second = first + bucket; - const chargePoints = [first, second].map((start) => ({ + const chargePoints = [midnight, midnight + bucket].map((start) => ({ bucket_start_ms: start, bucket_len_ms: bucket, flow: 'vehicle_charge', energy_wh: 1500, quality: 'measured', source: 'hardware_counter', provenance: 'counter', })); @@ -192,12 +195,7 @@ test('raw energy rows load only when opened, flag rejected data and page locally } if (path.startsWith('/api/prices?')) { priceRequests += 1; - const params = new URLSearchParams(path.split('?')[1]); - // The cost assertion is supplied with slots matching the two readings - // by using their query-window relationship (both ranges are whole days). - const today = new Date(); - today.setHours(0, 0, 0, 0); - const first = Math.floor(today.getTime() / 1800000) * 1800000; + const first = midnight; return { ok: true, json: async () => ({ enabled: true, currency: 'SEK', items: [ { slot_ts_ms: first, slot_len_min: 15, total_ore_kwh: 100 }, From e71f2a46830340a20ef2a0c6afcc482de5448fc8 Mon Sep 17 00:00:00 2001 From: Segran Date: Sat, 21 Nov 2026 15:09:36 +0100 Subject: [PATCH 3/4] Keep calibrating batteries online while suspending control Driver inventory and status, support reports, app-link snapshots and Home Assistant availability read IsOnline. Non-battery health gates also use it for site-meter, EV, V2X, PV and vehicle telemetry. Use CanControl for battery dispatch, planner eligibility, scoped holds, self-tune and EV battery boost. Reject queued battery commands that reach the driver after calibration started. Calibration has no independent expiry. The telemetry watchdog still marks a silent battery offline. Fresh telemetry restores online status and explicit completion from the driver restores control eligibility. --- go/cmd/ftw/main.go | 4 ++-- go/internal/api/api_battery_manual.go | 6 +++--- go/internal/api/api_control_feedback.go | 2 +- go/internal/api/api_control_feedback_test.go | 20 ++++++++++++++++++-- go/internal/control/battery_full.go | 4 ++-- go/internal/control/control_test.go | 19 +++++++++++++++++++ go/internal/control/dispatch.go | 18 +++++++++--------- go/internal/control/ev_battery_priority.go | 2 +- go/internal/drivers/registry.go | 7 +++++++ go/internal/mpc/service.go | 4 ++-- go/internal/telemetry/store.go | 12 +++++++++--- 11 files changed, 73 insertions(+), 25 deletions(-) diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index e5bef56c7..a4977b1e8 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -838,7 +838,7 @@ func main() { } health := tel.DriverHealth(name) reading := tel.Get(name, telemetry.DerBattery) - return health != nil && health.IsOnline() && reading != nil && reading.SoC != nil + return health != nil && health.CanControl() && reading != nil && reading.SoC != nil } // ---- Identity bootstrap ---- @@ -2156,7 +2156,7 @@ func main() { continue } r := tel.Get(name, telemetry.DerBattery) - if !h.IsOnline() || r == nil || r.SoC == nil || tel.IsStale(name, telemetry.DerBattery, watchdog) { + if !h.CanControl() || r == nil || r.SoC == nil || tel.IsStale(name, telemetry.DerBattery, watchdog) { return loadpoint.BatteryBoostStoppedBatteryUnavailable } usable++ diff --git a/go/internal/api/api_battery_manual.go b/go/internal/api/api_battery_manual.go index 95fcd6e64..c289c70ff 100644 --- a/go/internal/api/api_battery_manual.go +++ b/go/internal/api/api_battery_manual.go @@ -118,11 +118,11 @@ func (s *Server) resolveBatteryManualHoldTarget(driver string) (string, int, err return "", http.StatusServiceUnavailable, apiError("battery control state not available") } health := s.deps.Tel.DriverHealth(driver) - if health != nil && health.Calibrating { + if health != nil && health.IsOnline() && health.Calibrating { return "", http.StatusConflict, apiError("Manual override is unavailable while this battery is calibrating.") } reading := s.deps.Tel.Get(driver, telemetry.DerBattery) - if health == nil || !health.IsOnline() || reading == nil || reading.SoC == nil { + if health == nil || !health.CanControl() || reading == nil || reading.SoC == nil { return "", http.StatusConflict, apiError("battery driver is not ready for a scoped hold") } deviceID, ok := s.deps.BatteryIdentity(driver) @@ -155,7 +155,7 @@ func (s *Server) handleBatteryManualHoldGet(w http.ResponseWriter, r *http.Reque resp := batteryManualHoldResponseFrom(h, active) if s.deps.Tel != nil { for name, health := range s.deps.Tel.AllHealth() { - if health.Calibrating { + if health.IsOnline() && health.Calibrating { resp.CalibratingDrivers = append(resp.CalibratingDrivers, name) } } diff --git a/go/internal/api/api_control_feedback.go b/go/internal/api/api_control_feedback.go index 3ac9a9c32..ecec2837d 100644 --- a/go/internal/api/api_control_feedback.go +++ b/go/internal/api/api_control_feedback.go @@ -353,7 +353,7 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { case h.DeviceFault: f.State, f.Reason, f.Severity = "blocked", "device_fault", "warning" f.DeviceReason = h.DeviceFaultReason - case h.Calibrating && kind == telemetry.DerBattery: + case fresh && h.IsOnline() && h.Calibrating && kind == telemetry.DerBattery: f.State, f.Reason, f.Severity = "waiting", "battery_calibrating", "info" } } diff --git a/go/internal/api/api_control_feedback_test.go b/go/internal/api/api_control_feedback_test.go index 238db5f11..e9d4306f9 100644 --- a/go/internal/api/api_control_feedback_test.go +++ b/go/internal/api/api_control_feedback_test.go @@ -323,12 +323,28 @@ func TestCalibrationKeepsBatteryTelemetryAndSuspendsControl(t *testing.T) { t.Fatalf("unexpected calibration feedback: %+v", got) } health := tel.DriverHealth("battery") - if health.IsOnline() || health.DeviceFault || !health.TelemetryLive() { + if !health.IsOnline() || health.CanControl() || health.DeviceFault || !health.TelemetryLive() { t.Fatalf("calibration must suspend control only: %+v", health) } + // A silent device becomes offline via the normal watchdog. Fresh + // telemetry alone does not end the owner's autonomous calibration. + tel.WatchdogScan(-time.Second) + health = tel.DriverHealth("battery") + if health.IsOnline() || health.CanControl() { + t.Fatalf("watchdog did not mark the calibrating battery offline: %+v", health) + } + got = srv.controlFeedback(time.Now()) + if len(got) != 1 || got[0].Reason != "telemetry_stale" { + t.Fatalf("calibration masked stale feedback: %+v", got) + } + tel.RecordDriverSuccess("battery") + health = tel.DriverHealth("battery") + if !health.IsOnline() || health.CanControl() { + t.Fatalf("telemetry recovery re-enabled control during calibration: %+v", health) + } tel.SetDriverCalibrating("battery", false) got = srv.controlFeedback(time.Now()) - if len(got) != 1 || got[0].Reason != "no_command" || !tel.DriverHealth("battery").IsOnline() { + if len(got) != 1 || got[0].Reason != "no_command" || !tel.DriverHealth("battery").CanControl() { t.Fatalf("control did not become available after calibration: %+v", got) } } diff --git a/go/internal/control/battery_full.go b/go/internal/control/battery_full.go index f36dc75de..fbfe7af8c 100644 --- a/go/internal/control/battery_full.go +++ b/go/internal/control/battery_full.go @@ -36,7 +36,7 @@ func (s *State) updateBatteryChargeFull(store *telemetry.Store, capacities map[s for name := range capacities { r := store.Get(name, telemetry.DerBattery) h := store.DriverHealth(name) - if r == nil || r.SoC == nil || h == nil || !h.IsOnline() { + if r == nil || r.SoC == nil || h == nil || !h.CanControl() { continue } age := s.now().Sub(r.SoCUpdatedAt) @@ -77,7 +77,7 @@ func (s *State) stopFullBatteries(targets []DispatchTarget, store *telemetry.Sto continue } r, h := store.Get(name, telemetry.DerBattery), store.DriverHealth(name) - if r == nil || h == nil || !h.IsOnline() || s.PrevTargets[name] <= 0 && r.RawW <= 100 { + if r == nil || h == nil || !h.CanControl() || s.PrevTargets[name] <= 0 && r.RawW <= 100 { continue } targets = append(targets, DispatchTarget{Driver: name, TargetW: 0, Clamped: true}) diff --git a/go/internal/control/control_test.go b/go/internal/control/control_test.go index 70bf04a0c..6983b44f5 100644 --- a/go/internal/control/control_test.go +++ b/go/internal/control/control_test.go @@ -4685,6 +4685,25 @@ func TestBatteryManualHoldChargesAtSetpoint(t *testing.T) { } } +func TestBatteryPoolSkipsCalibratingBattery(t *testing.T) { + store := seedStore(500, []struct { + name string + currentW, soc float64 + }{ + {"bat_a", 0, 0.5}, + {"bat_b", 0, 0.5}, + }) + st := NewState(0, 50, "ferroamp") + st.Mode = ModeSelfConsumption + st.SlewRateW = 100000 + st.SetBatteryManualHold(BatteryManualHold{PowerW: 3000, ExpiresAt: time.Now().Add(time.Minute)}) + store.SetDriverCalibrating("bat_a", true) + targets := ComputeDispatch(store, st, caps(map[string]float64{"bat_a": 10000, "bat_b": 10000}), 100000) + if len(targets) != 1 || targets[0].Driver != "bat_b" || math.Abs(targets[0].TargetW-3000) > 1 { + t.Fatalf("hold should only command bat_b: %+v", targets) + } +} + func TestBatteryManualHoldDischargesAtSetpoint(t *testing.T) { // grid = -2000 (exporting). Without hold, self-consumption would // command +2000 charge. Hold installs -2500 → expect discharge. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 88843fda2..b020a62fa 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1309,7 +1309,7 @@ func ComputeDispatch( for name := range driverCapacities { if r := store.Get(name, telemetry.DerBattery); r != nil { h := store.DriverHealth(name) - if h != nil && h.IsOnline() { + if h != nil && h.CanControl() { liveBatTotal += r.SmoothedW } } @@ -1607,7 +1607,7 @@ func ComputeDispatch( capacityWh: cap, currentW: r.SmoothedW, soc: soc, - online: h.IsOnline(), + online: h.CanControl(), group: state.InverterGroups[name], maxChargeW: lim.MaxChargeW, maxDischargeW: lim.MaxDischargeW, @@ -2852,7 +2852,7 @@ func protectiveCurtailLimitW(state *State, store *telemetry.Store) (float64, boo var sumSoCWh, totalCap float64 for _, r := range store.ReadingsByType(telemetry.DerBattery) { h := store.DriverHealth(r.Driver) - if h == nil || !h.IsOnline() || r.SoC == nil { + if h == nil || !h.CanControl() || r.SoC == nil { continue } // Capacity must come from the per-driver map passed into @@ -3235,7 +3235,7 @@ func liveCurtailLimitW(state *State, store *telemetry.Store) (float64, bool) { var batW float64 for _, r := range store.ReadingsByType(telemetry.DerBattery) { h := store.DriverHealth(r.Driver) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } batW += r.RawW @@ -3257,7 +3257,7 @@ func liveCurtailLimitW(state *State, store *telemetry.Store) (float64, bool) { var batHeadroomW float64 for _, r := range store.ReadingsByType(telemetry.DerBattery) { h := store.DriverHealth(r.Driver) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } if r.SoC == nil || *r.SoC >= pvCurtailBatterySoCMax { @@ -3895,7 +3895,7 @@ func chargeAll(store *telemetry.Store, capacities map[string]float64, limits map out := make([]DispatchTarget, 0) for name := range capacities { h := store.DriverHealth(name) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } target := limits[name].chargeCap() @@ -4837,7 +4837,7 @@ func holdFleetAtZero(store *telemetry.Store, capacities map[string]float64) []Di out := make([]DispatchTarget, 0, len(capacities)) for name := range capacities { h := store.DriverHealth(name) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } if r := store.Get(name, telemetry.DerBattery); r == nil { @@ -4884,7 +4884,7 @@ func fleetAtLivePower( readings = make(map[string]*telemetry.DerReading, len(capacities)) for name := range capacities { h := store.DriverHealth(name) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } r := store.Get(name, telemetry.DerBattery) @@ -5126,7 +5126,7 @@ func fuseSnapshotStillCurrent( for driver, captured := range batteryReadings { r := store.Get(driver, telemetry.DerBattery) h := store.DriverHealth(driver) - if captured == nil || r == nil || h == nil || !h.IsOnline() || !r.UpdatedAt.Equal(captured.UpdatedAt) { + if captured == nil || r == nil || h == nil || !h.CanControl() || !r.UpdatedAt.Equal(captured.UpdatedAt) { return false } fresh[driver] = r diff --git a/go/internal/control/ev_battery_priority.go b/go/internal/control/ev_battery_priority.go index c585c92e4..452ab7fbd 100644 --- a/go/internal/control/ev_battery_priority.go +++ b/go/internal/control/ev_battery_priority.go @@ -48,7 +48,7 @@ func (s *State) yieldBatteryBeforeEVCut(store *telemetry.Store, meter *telemetry var available, commanded float64 for driver, log := range s.batteryCommands { h := store.DriverHealth(driver) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } _, high, latest, ok := log.span(s.now()) diff --git a/go/internal/drivers/registry.go b/go/internal/drivers/registry.go index 8fb6dc8e1..3cfad8577 100644 --- a/go/internal/drivers/registry.go +++ b/go/internal/drivers/registry.go @@ -1095,6 +1095,13 @@ func (r *Registry) runLoop(rd *runningDriver) { err = cancelErr break } + if action == "battery" && r.tel != nil { + if health := r.tel.DriverHealth(rd.cfg.Name); health != nil && health.Calibrating { + err = ErrCommandIneligible + reportOutcome = false + break + } + } if cmd.checkEVHealth && isPhysicalEVCommand(action) && r.tel != nil { health := r.tel.DriverHealth(rd.cfg.Name) if health == nil || !health.IsOnline() { diff --git a/go/internal/mpc/service.go b/go/internal/mpc/service.go index b11a9ab8b..20ec797d4 100644 --- a/go/internal/mpc/service.go +++ b/go/internal/mpc/service.go @@ -2809,7 +2809,7 @@ func currentSoC(t *telemetry.Store, fallback float64) (float64, bool) { var n int for _, b := range bats { h := t.DriverHealth(b.Driver) - if (h == nil || h.IsOnline()) && freshBatterySoC(b) { + if (h == nil || h.CanControl()) && freshBatterySoC(b) { sum += *b.SoC n++ } @@ -2841,7 +2841,7 @@ func (s *Service) onlineFleetParams(p Params, fleet []BatteryFleetMember, fuseMa continue } h := s.Tele.DriverHealth(b.Driver) - if h == nil || !h.IsOnline() { + if h == nil || !h.CanControl() { continue } r := s.Tele.Get(b.Driver, telemetry.DerBattery) diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index 995bdf453..10e0a3730 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -262,10 +262,14 @@ func (h *DriverHealth) SetCommandFault(faulted bool, reason string) { h.refreshDeviceFault() } -// IsOnline reports whether the driver is usable for control. A stale-flagged -// driver (Status offline) OR one that cannot actuate is not. +// IsOnline reports the driver's health for inventories and diagnostics. func (h *DriverHealth) IsOnline() bool { - return h.Status != StatusOffline && !h.DeviceFault && !h.Calibrating + return h.Status != StatusOffline && !h.DeviceFault +} + +// CanControl also requires the device to be outside autonomous calibration. +func (h *DriverHealth) CanControl() bool { + return h.IsOnline() && !h.Calibrating } // TelemetryLive reports whether this driver's last reading is still a @@ -1017,6 +1021,8 @@ func (s *Store) SetDriverDeviceFault(name string, faulted bool, reason string) { // SetDriverCalibrating records a device-managed calibration. Measurements // remain live while the dispatcher and planner wait for control to resume. +// The watchdog still marks a silent driver offline. Only a driver report +// can end calibration; elapsed time alone is not permission to send commands. func (s *Store) SetDriverCalibrating(name string, calibrating bool) { s.mu.Lock() defer s.mu.Unlock() From 117709758efe96ab4c4e24295e3d6dbd02133cba Mon Sep 17 00:00:00 2001 From: Segran Date: Sun, 22 Nov 2026 13:19:27 +0100 Subject: [PATCH 4/4] fix(battery): preserve calibration across driver replacement Signed-off-by: Segran --- go/internal/drivers/registry.go | 28 ++-- .../registry_calibration_restart_test.go | 125 ++++++++++++++++++ go/internal/drivers/registry_spawn_retry.go | 2 +- go/internal/telemetry/store.go | 18 ++- 4 files changed, 162 insertions(+), 11 deletions(-) create mode 100644 go/internal/drivers/registry_calibration_restart_test.go diff --git a/go/internal/drivers/registry.go b/go/internal/drivers/registry.go index 3cfad8577..accc62be5 100644 --- a/go/internal/drivers/registry.go +++ b/go/internal/drivers/registry.go @@ -1280,19 +1280,25 @@ func (r *Registry) clearRecoveryRequired(name string, rd *runningDriver) { func (r *Registry) remove(name string, skipDefault bool) { release := r.acquireLifecycle(name) defer release() - r.removeLocked(name, skipDefault) + r.removeLocked(name, skipDefault, 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. -func (r *Registry) removeLocked(name string, skipDefault bool) { +func (r *Registry) removeLocked(name string, skipDefault, replacing bool) { + r.mu.Lock() + _, pending := r.spawnRetries[name] + r.mu.Unlock() r.takeSpawnRetry(name) skipDefault = skipDefault || r.controlBlocked() r.mu.Lock() rd, ok := r.rec[name] if !ok { r.mu.Unlock() + if pending && !replacing && r.tel != nil { + r.tel.Remove(name) + } return } // Another party owns an observe_only device's actuation (a retailer VPP, @@ -1336,7 +1342,11 @@ func (r *Registry) removeLocked(name string, skipDefault bool) { } } if r.tel != nil { - r.tel.Remove(name) + if replacing { + r.tel.RemoveForReplacement(name) + } else { + r.tel.Remove(name) + } } slog.Info("driver removed", "name", name) } @@ -1558,7 +1568,7 @@ func (r *Registry) Reload(ctx context.Context, newDrivers []config.Driver, troub for _, n := range r.pendingSpawnRetries() { if _, ok := findDriver(active, n); !ok { release := r.acquireLifecycle(n) - r.removeLocked(n, false) + r.removeLocked(n, false, false) release() } } @@ -1579,7 +1589,7 @@ func (r *Registry) Reload(ctx context.Context, newDrivers []config.Driver, troub requiresRestart := stillThere && (troubleshootingChanged || !sameDriverConfig(old, newCfg)) if !stillThere { release := r.acquireLifecycle(n) - r.removeLocked(n, false) + r.removeLocked(n, false, false) release() } else if requiresRestart { if troubleshootingChanged { @@ -1588,7 +1598,7 @@ func (r *Registry) Reload(ctx context.Context, newDrivers []config.Driver, troub slog.Info("driver config changed, restarting", "name", n) } release := r.acquireLifecycle(n) - r.removeLocked(n, false) + r.removeLocked(n, false, true) if err := r.add(ctx, newCfg, true); err != nil { slog.Warn("reload driver failed", "name", n, "err", err) } @@ -1610,7 +1620,7 @@ func (r *Registry) Reload(ctx context.Context, newDrivers []config.Driver, troub continue } if exists { - r.removeLocked(d.Name, false) + r.removeLocked(d.Name, false, true) } if err := r.add(ctx, d, true); err != nil { slog.Warn("add driver failed", "name", d.Name, "err", err) @@ -1625,7 +1635,7 @@ func (r *Registry) Reload(ctx context.Context, newDrivers []config.Driver, troub func (r *Registry) Restart(ctx context.Context, cfg config.Driver) error { release := r.acquireLifecycle(cfg.Name) defer release() - r.removeLocked(cfg.Name, false) + r.removeLocked(cfg.Name, false, !cfg.Disabled) if cfg.Disabled { return nil } @@ -1645,7 +1655,7 @@ func (r *Registry) RestartByName(ctx context.Context, name string) error { return fmt.Errorf("driver %q not running", name) } cfg := rd.cfg - r.removeLocked(name, false) + r.removeLocked(name, false, !cfg.Disabled) if cfg.Disabled { return nil } diff --git a/go/internal/drivers/registry_calibration_restart_test.go b/go/internal/drivers/registry_calibration_restart_test.go new file mode 100644 index 000000000..5b52222f9 --- /dev/null +++ b/go/internal/drivers/registry_calibration_restart_test.go @@ -0,0 +1,125 @@ +package drivers + +import ( + "context" + "errors" + "os" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +func TestBatteryCalibrationAcrossDriverRestart(t *testing.T) { + t.Run("restart by name", func(t *testing.T) { + testBatteryCalibrationAcrossReplacement(t, func(ctx context.Context, registry *Registry, cfg config.Driver) error { + return registry.RestartByName(ctx, cfg.Name) + }) + }) + t.Run("configuration reload", func(t *testing.T) { + testBatteryCalibrationAcrossReplacement(t, func(ctx context.Context, registry *Registry, cfg config.Driver) error { + cfg.Config = map[string]any{"changed": true} + registry.Reload(ctx, []config.Driver{cfg}, false) + return nil + }) + }) +} + +func testBatteryCalibrationAcrossReplacement(t *testing.T, replace func(context.Context, *Registry, config.Driver) error) { + t.Helper() + const driver = ` +function driver_init(config) + host.set_poll_interval(20) +end + +function driver_poll() + host.emit_metric("calibration_test_poll", 1) + return 20 +end + +function driver_command(action, w, cmd) + if action == "calibration_active" then host.set_calibrating(true) end + if action == "calibration_complete" then host.set_calibrating(false) end + if action == "battery" then host.emit_metric("battery_command_called", 1) end + return true +end + +function driver_default_mode() end +` + tel := telemetry.NewStore() + registry := NewRegistry(tel) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + path := writeTestDriver(t, driver) + cfg := config.Driver{Name: "battery", Lua: path} + if err := registry.Add(ctx, cfg); err != nil { + t.Fatal(err) + } + t.Cleanup(registry.ShutdownAll) + + waitForPoll := func(want float64) { + t.Helper() + ticker := time.NewTicker(5 * time.Millisecond) + defer ticker.Stop() + for { + value, _, ok := tel.LatestMetric(cfg.Name, "calibration_test_poll") + health := tel.DriverHealth(cfg.Name) + if ok && value == want && health != nil && health.IsOnline() && health.LastSuccess != nil { + return + } + select { + case <-ticker.C: + case <-ctx.Done(): + t.Fatalf("waiting for generation %.0f to poll: %v", want, ctx.Err()) + } + } + } + send := func(action string) error { + return registry.Send(ctx, cfg.Name, []byte(`{"action":"`+action+`","power_w":1000}`)) + } + report := func(action string) { + t.Helper() + if err := send(action); err != nil { + t.Fatalf("driver report %s: %v", action, err) + } + } + checkBlocked := func(stage string) { + t.Helper() + if err := send("battery"); !errors.Is(err, ErrCommandIneligible) { + _, _, called := tel.LatestMetric(cfg.Name, "battery_command_called") + t.Errorf("%s: battery command returned %v, Lua received command: %t; want ErrCommandIneligible", stage, err, called) + } + } + + waitForPoll(1) + report("calibration_active") + checkBlocked("before restart") + + if err := os.WriteFile(path, []byte(driver+` +function driver_poll() + host.emit_metric("calibration_test_poll", 2) + return 20 +end +`), 0o600); err != nil { + t.Fatal(err) + } + if err := replace(ctx, registry, cfg); err != nil { + t.Fatal(err) + } + waitForPoll(2) + checkBlocked("new driver is polling but has not reported calibration status") + + report("calibration_active") + checkBlocked("new driver confirms calibration") + report("calibration_complete") + if err := send("battery"); err != nil { + t.Fatalf("after calibration completes: %v", err) + } + report("calibration_active") + registry.Remove(cfg.Name) + if health := tel.DriverHealth(cfg.Name); health != nil { + t.Fatalf("removal retained driver health: %+v", health) + } +} diff --git a/go/internal/drivers/registry_spawn_retry.go b/go/internal/drivers/registry_spawn_retry.go index 3bb3574be..43efcfd54 100644 --- a/go/internal/drivers/registry_spawn_retry.go +++ b/go/internal/drivers/registry_spawn_retry.go @@ -91,7 +91,7 @@ func (r *Registry) retrySpawn(name string, e *spawnRetry) { } if closed { // Shutdown began while this attempt ran and may have missed it. - r.removeLocked(name, false) + r.removeLocked(name, false, false) return } slog.Info("driver started on retry", "name", name) diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index 10e0a3730..4ef7f4f88 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -908,13 +908,29 @@ func (s *Store) PollsLastDay(now time.Time) (polls, errors uint64, covered time. // A battery's outstanding order bound survives until raw power confirms its // replacement. Historical TS-DB samples stay queryable. func (s *Store) Remove(driver string) { + s.remove(driver, false) +} + +// RemoveForReplacement drops the old driver's readings and health counters +// but keeps a known calibration until the replacement reports its state. +func (s *Store) RemoveForReplacement(driver string) { + s.remove(driver, true) +} + +func (s *Store) remove(driver string, replacing bool) { s.mu.Lock() for _, t := range allDerTypes { k := key(driver, t) delete(s.readings, k) delete(s.filters, k) } - delete(s.health, driver) + if old := s.health[driver]; replacing && old != nil && old.Calibrating { + s.health[driver] = &DriverHealth{ + Name: driver, StartedAt: time.Now(), Status: StatusOffline, Calibrating: true, + } + } else { + delete(s.health, driver) + } for _, kind := range allDerTypes { delete(s.controlObservations, key(driver, kind)) }