Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/pixii-calibration-status.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion 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_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` |
Expand Down
24 changes: 18 additions & 6 deletions go/internal/api/api_battery_manual.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 20 additions & 0 deletions go/internal/api/api_battery_manual_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
15 changes: 10 additions & 5 deletions go/internal/api/api_control_feedback.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,9 +348,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 {
Expand Down Expand Up @@ -451,7 +456,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"
Expand Down Expand Up @@ -489,7 +494,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" {
Expand Down
22 changes: 22 additions & 0 deletions go/internal/api/api_control_feedback_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,28 @@ 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)
}
}

func TestControlFeedbackUsesCurrentChargerReason(t *testing.T) {
now := time.Now()
for _, tc := range []struct {
Expand Down
7 changes: 7 additions & 0 deletions go/internal/drivers/lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 15 additions & 1 deletion go/internal/telemetry/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
33 changes: 30 additions & 3 deletions web/components/ftw-battery-control.js
Original file line number Diff line number Diff line change
Expand Up @@ -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" };
}

Expand Down Expand Up @@ -296,6 +298,7 @@ class FtwBatteryControl extends FtwElement {
</div>

<div class="error hidden" data-error></div>
<p class="hidden" data-calibration role="status"></p>
<button type="button" class="install-btn" data-install>Install hold</button>
</details>
</ftw-modal>
Expand Down Expand Up @@ -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 : ''}}));
}
Expand Down Expand Up @@ -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 */ });
}

Expand All @@ -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]");
Expand All @@ -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" },
Expand All @@ -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() {
Expand Down
2 changes: 2 additions & 0 deletions web/control-feedback.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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)
Expand Down
24 changes: 11 additions & 13 deletions web/energy-history-integration.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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: {},
Expand All @@ -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',
}));
Expand All @@ -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 },
Expand Down
Loading