diff --git a/.changeset/charge-ends-at-restart.md b/.changeset/charge-ends-at-restart.md new file mode 100644 index 000000000..74ddb07cd --- /dev/null +++ b/.changeset/charge-ends-at-restart.md @@ -0,0 +1,8 @@ +--- +"ftw": patch +--- + +End manual battery Charge when FTW restarts. Return to automatic planning +with the saved battery export permission, or Idle when the planner is disabled. +Ignore old retained MQTT Charge commands so reconnecting cannot resume the +override. A new Charge command still works. diff --git a/go/cmd/ftw/charge_restart_test.go b/go/cmd/ftw/charge_restart_test.go new file mode 100644 index 000000000..c5feb3fb4 --- /dev/null +++ b/go/cmd/ftw/charge_restart_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "context" + "path/filepath" + "sync" + "testing" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/control" + "github.com/srcfl/ftw/go/internal/state" +) + +func TestRestartEndsManualCharge(t *testing.T) { + for _, tc := range []struct { + name string + planner *config.Planner + storedExport string + want control.Mode + }{ + {"planner enabled", &config.Planner{Enabled: true}, "", control.ModePlannerPassiveArbitrage}, + {"export allowed", &config.Planner{Enabled: true}, "allowed", control.ModePlannerArbitrage}, + {"export refused", &config.Planner{Enabled: true, BatteryExport: "allowed"}, "not_allowed", control.ModePlannerPassiveArbitrage}, + {"export unknown", &config.Planner{Enabled: true, BatteryExport: "allowed"}, "unknown", control.ModePlannerPassiveArbitrage}, + {"export from config", &config.Planner{Enabled: true, BatteryExport: "allowed"}, "", control.ModePlannerArbitrage}, + {"invalid stored permission", &config.Planner{Enabled: true, BatteryExport: "allowed"}, "invalid", control.ModePlannerArbitrage}, + {"no export permission", &config.Planner{Enabled: true, BatteryExport: "invalid"}, "invalid", control.ModePlannerPassiveArbitrage}, + {"planner disabled", &config.Planner{Enabled: false}, "allowed", control.ModeIdle}, + {"no planner", nil, "", control.ModeIdle}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := parseBatteryLimitConfig(t, "", " max_charge_w: 10000\n soc_max: 0.9\n") + cfg.Planner = tc.planner + path := filepath.Join(t.TempDir(), "state.db") + st, err := state.Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + if err := st.SaveConfig(config.StateKeyBatteryExport, tc.storedExport); err != nil { + t.Fatal(err) + } + // A new, explicit Charge still works during this process. + ctrl := newControlStateFromConfig(cfg) + modes := appModes{ctrl: ctrl, ctrlMu: &sync.Mutex{}, state: st} + if err := modes.SetMode(context.Background(), control.ModeCharge); err != nil { + t.Fatal(err) + } + if targets := control.ComputeDispatch(batteryLimitStore(1000), ctrl, map[string]float64{"battery": 15000}, 40000); len(targets) != 1 || targets[0].TargetW != 10000 { + t.Fatalf("explicit Charge: %+v, want 10000 W", targets) + } + for boot := 1; boot <= 2; boot++ { + if err := st.Close(); err != nil { + t.Fatal(err) + } + st, err = state.Open(path) + if err != nil { + t.Fatal(err) + } + ctrl = newControlStateFromConfig(cfg) + restoreStoredMode(ctrl, st, cfg) + if ctrl.Mode != tc.want { + t.Fatalf("boot %d: mode = %q, want %q", boot, ctrl.Mode, tc.want) + } + if saved, _ := st.LoadConfig("mode"); saved != string(tc.want) { + t.Fatalf("boot %d: stored mode = %q, want %q", boot, saved, tc.want) + } + if tc.name == "planner enabled" || tc.name == "export unknown" { + if export, _ := st.LoadConfig(config.StateKeyBatteryExport); export != "unknown" { + t.Fatalf("boot %d: unknown export permission became %q", boot, export) + } + } + // Before the fresh plan arrives, import without solar must + // not resume the earlier full-power charging order. + for _, target := range control.ComputeDispatch(batteryLimitStore(1000), ctrl, map[string]float64{"battery": 15000}, 40000) { + if target.TargetW > 0 { + t.Fatalf("boot %d: charging before a fresh plan: %+v", boot, target) + } + } + } + }) + } +} diff --git a/go/cmd/ftw/control_state.go b/go/cmd/ftw/control_state.go index ec87976b7..3b239b418 100644 --- a/go/cmd/ftw/control_state.go +++ b/go/cmd/ftw/control_state.go @@ -76,14 +76,39 @@ func energyDispatchEnabled(cfg *config.Config) bool { // and weighted split equally because nothing set its weights. var removedModes = map[string]bool{"priority": true, "weighted": true} -// restoreStoredMode applies the mode saved in state.db. A removed mode becomes -// manual self-consumption and is saved back, so the stored mode matches what -// the site runs. Any other unknown value keeps the default mode, as before. -func restoreStoredMode(ctrl *control.State, st *state.Store) { +// restoreStoredMode keeps durable modes, but never resumes forced Charge. +// Charge returns to the planner, or Idle if planning is disabled. Removed +// modes become self-consumption; unknown values keep the default mode. +func restoreStoredMode(ctrl *control.State, st *state.Store, cfg *config.Config) { v, ok := st.LoadConfig("mode") if !ok { return } + if control.Mode(v) == control.ModeCharge { + next := control.ModeIdle + values := map[string]string{} + if cfg != nil && cfg.Planner != nil && cfg.Planner.Enabled { + export := config.BatteryExportUnknown + if e, valid := config.ParseBatteryExport(cfg.Planner.BatteryExport); valid { + export = e + } + storedExport, _ := st.LoadConfig(config.StateKeyBatteryExport) + if e, valid := config.ParseBatteryExport(storedExport); valid { + export = e + } + next = control.Mode(export.PlannerModeKey()) + // Keep unknown as unknown. Otherwise the later preference + // migration would infer a refusal from the new passive mode. + values[config.StateKeyBatteryExport] = string(export) + } + ctrl.Mode = next + values["mode"] = string(next) + if err := st.SaveConfigValues(values); err != nil { + slog.Warn("could not save the mode after ending manual Charge at restart", "mode", next, "err", err) + } + slog.Info("manual Charge ended at restart", "previous_mode", v, "mode", next) + return + } if m := control.Mode(v); control.IsValidMode(m) { ctrl.Mode = m return diff --git a/go/cmd/ftw/control_state_test.go b/go/cmd/ftw/control_state_test.go index e0f650357..8c516be71 100644 --- a/go/cmd/ftw/control_state_test.go +++ b/go/cmd/ftw/control_state_test.go @@ -184,10 +184,15 @@ func TestRestoredGridTargetIgnoresNonFinite(t *testing.T) { // self-consumption and store it, not keep a mode no door accepts any more. func TestRestoreStoredModeMapsRemovedModesToSelfConsumption(t *testing.T) { for stored, want := range map[string]control.Mode{ - "priority": control.ModeSelfConsumption, - "weighted": control.ModeSelfConsumption, - "planner_arbitrage": control.ModePlannerArbitrage, - "peak_shaving": control.ModePeakShaving, + "priority": control.ModeSelfConsumption, + "weighted": control.ModeSelfConsumption, + "idle": control.ModeIdle, + "self_consumption": control.ModeSelfConsumption, + "peak_shaving": control.ModePeakShaving, + "planner_self": control.ModePlannerSelf, + "planner_cheap": control.ModePlannerCheap, + "planner_passive_arbitrage": control.ModePlannerPassiveArbitrage, + "planner_arbitrage": control.ModePlannerArbitrage, } { t.Run(stored, func(t *testing.T) { st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) @@ -201,7 +206,7 @@ func TestRestoreStoredModeMapsRemovedModesToSelfConsumption(t *testing.T) { ctrl := control.NewState(0, 50, "meter") ctrl.Mode = control.ModeIdle - restoreStoredMode(ctrl, st) + restoreStoredMode(ctrl, st, nil) if ctrl.Mode != want { t.Fatalf("mode = %q, want %q", ctrl.Mode, want) @@ -225,7 +230,7 @@ func TestRestoreStoredModeLeavesAnUnknownValueAlone(t *testing.T) { } ctrl := control.NewState(0, 50, "meter") - restoreStoredMode(ctrl, st) + restoreStoredMode(ctrl, st, nil) if ctrl.Mode != control.ModeSelfConsumption { t.Fatalf("mode = %q, want the default", ctrl.Mode) diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index de09caf3f..f044f4028 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -591,11 +591,9 @@ func main() { // ---- Control state ---- ctrl := newControlStateFromConfig(cfg) - // Restore persisted mode + target if present. The planner variants - // have to be listed too — without them the strategy the user picked in - // the UI (planner_self / planner_cheap / planner_arbitrage) is silently - // dropped on restart and the dashboard appears to forget the selection. - restoreStoredMode(ctrl, st) + // Restore durable modes and targets. Forced Charge ends at restart; + // the planner makes a fresh plan instead of resuming that override. + restoreStoredMode(ctrl, st, cfg) storedTrust, _ := st.LoadConfig(config.StateKeyForecastTrust) storedExport, _ := st.LoadConfig(config.StateKeyBatteryExport) storedSafetyK, _ := st.LoadConfig(config.StateKeySafetyK) diff --git a/go/internal/ha/bridge.go b/go/internal/ha/bridge.go index 9aae52446..39c4bfbe9 100644 --- a/go/internal/ha/bridge.go +++ b/go/internal/ha/bridge.go @@ -816,6 +816,12 @@ func metricUnitAndClass(name, explicitUnit string) (unit, devClass string) { func (b *Bridge) subscribeCommands() { b.client.Subscribe(b.cmdTopic("mode"), 0, func(_ paho.Client, m paho.Message) { mode := string(m.Payload()) + // A stored broker command is replayed on every reconnect. It + // must not undo the boot rule that ends manual Charge. + if mode == string(control.ModeCharge) && m.Retained() { + slog.Warn("HA: ignored a retained Charge command; send a new command to charge") + return + } if b.cb.SetMode != nil { if err := b.cb.SetMode(mode); err != nil { slog.Warn("HA set mode failed", "err", err) diff --git a/go/internal/ha/charge_restart_test.go b/go/internal/ha/charge_restart_test.go new file mode 100644 index 000000000..03fce2067 --- /dev/null +++ b/go/internal/ha/charge_restart_test.go @@ -0,0 +1,45 @@ +package ha + +import ( + "fmt" + "testing" + + paho "github.com/eclipse/paho.mqtt.golang" +) + +type retainedModeMessage struct { + commandMessage + retained bool +} + +func (m retainedModeMessage) Retained() bool { return m.retained } + +func TestRetainedChargeCannotRestartManualCharging(t *testing.T) { + for _, tc := range []struct { + mode string + retained bool + want bool + }{ + {"charge", true, false}, + {"charge", false, true}, + {"idle", true, true}, + {"planner_passive_arbitrage", true, true}, + } { + t.Run(fmt.Sprintf("%s/retained=%t", tc.mode, tc.retained), func(t *testing.T) { + cli := &commandClient{handlers: map[string]paho.MessageHandler{}} + var called bool + b := &Bridge{topicPrefix: "ftw", client: cli, cb: CommandCallbacks{SetMode: func(mode string) error { + called = true + if mode != tc.mode { + t.Errorf("mode = %q, want %q", mode, tc.mode) + } + return nil + }}} + b.subscribeCommands() + cli.handlers[b.cmdTopic("mode")](cli, retainedModeMessage{commandMessage: commandMessage{payload: []byte(tc.mode)}, retained: tc.retained}) + if called != tc.want { + t.Fatalf("SetMode called = %v, want %v", called, tc.want) + } + }) + } +} diff --git a/go/internal/mpc/startup_replan_test.go b/go/internal/mpc/startup_replan_test.go new file mode 100644 index 000000000..b92b1e0cf --- /dev/null +++ b/go/internal/mpc/startup_replan_test.go @@ -0,0 +1,63 @@ +package mpc + +import ( + "context" + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/state" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +func TestStartReplansAnArchivedPlanWithFreshSoC(t *testing.T) { + old := newCancellationTestService(t, nil) + if _, err := old.Store.ClearPrices(); err != nil { + t.Fatal(err) + } + start := time.Now().UTC().Truncate(15 * time.Minute) + var prices []state.PricePoint + for i := 0; i < 16; i++ { + prices = append(prices, state.PricePoint{ + Zone: "SE3", SlotTsMs: start.Add(time.Duration(i) * 15 * time.Minute).UnixMilli(), + SlotLenMin: 15, SpotOreKwh: 50, TotalOreKwh: 100, + Source: "test", FetchedAtMs: start.UnixMilli(), + }) + } + if err := old.Store.SavePrices(prices); err != nil { + t.Fatal(err) + } + if old.Replan(context.Background()) == nil { + t.Fatal("could not create the previous process's plan") + } + archived := old.Diagnose() + + tel := telemetry.NewStore() + soc := .4 + tel.Update("battery", telemetry.DerBattery, 0, &soc, nil) + tel.RecordDriverSuccess("battery") + svc := New(old.Store, tel, "SE3", old.Defaults) + svc.Horizon, svc.BaseLoad = old.Horizon, old.BaseLoad + svc.Interval = time.Hour + if !svc.RestoreDiagnostic(archived, time.Now(), "restored_diagnostic") { + t.Fatal("could not restore the archived plan") + } + saved := make(chan *Diagnostic, 1) + svc.SaveDiag = func(d *Diagnostic, _ string) error { + saved <- d + return nil + } + svc.Start(context.Background()) + t.Cleanup(svc.Stop) + select { + case d := <-saved: + if math.Abs(d.Params.InitialSoC-soc) > 1e-9 { + t.Fatalf("startup SoC = %v, want the fresh %v", d.Params.InitialSoC, soc) + } + if d.DecisionID == archived.DecisionID { + t.Fatal("startup reused the previous process's decision") + } + case <-time.After(5 * time.Second): + t.Fatal("startup waited for the scheduled interval instead of making a fresh plan") + } +}