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
4 changes: 2 additions & 2 deletions go/cmd/ftw/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 ----
Expand Down Expand Up @@ -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++
Expand Down
26 changes: 19 additions & 7 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,8 +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.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)
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.IsOnline() && 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 fresh && h.IsOnline() && 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
38 changes: 38 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,44 @@ 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.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").CanControl() {
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
4 changes: 2 additions & 2 deletions go/internal/control/battery_full.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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})
Expand Down
19 changes: 19 additions & 0 deletions go/internal/control/control_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 9 additions & 9 deletions go/internal/control/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion go/internal/control/ev_battery_priority.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
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
Loading
Loading