From 6890ec2c8d8a840c05af209627a7afc772fba196 Mon Sep 17 00:00:00 2001 From: Segran Date: Sun, 15 Nov 2026 01:37:07 +0100 Subject: [PATCH 1/2] 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/2] 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 },