Skip to content
Draft
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
8 changes: 8 additions & 0 deletions .changeset/charge-ends-at-restart.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 8 additions & 0 deletions .changeset/ems-battery-soc-max.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"ftw": patch
---

Stop battery charging at the configured maximum charge level in every EMS mode,
including manual holds and self-tuning. Use each battery's soc_max, or the
planner's limit when the battery has none. Charging resumes one percentage
point below that limit; discharge remains available.
5 changes: 5 additions & 0 deletions .changeset/fuse-one-function.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

Fuse protection now reads the main fuse the same way for the car and the home battery: the site meter's current on each phase, with its direction, under one margin (your safety margin, at least 1 A). A battery's charge or a car may rise only into the room the phases show. When a phase goes over, the car is cut and the battery gives back only what the car's cut does not cover, so the two never answer the same overage twice. The meter's total no longer counts against the fuse when the meter reports phase currents, which a Pixii total that disagrees with its phases used to trip. A car now starts when its minimum fits, a second car plugging in no longer stops the first, and fuse relief no longer discharges a battery below its soc_min (or the planner's, 10 % by default).
5 changes: 5 additions & 0 deletions .changeset/fuse-phase-direction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

A car can now start and rise while the house exports. Fuse protection read each phase's current as a magnitude, so 20 A of solar export counted as 20 A of import and the car never started. A phase now takes its direction from the same phase's power in the meter reading, and new load on an exporting phase has more room, not less. When a meter reports no phase power, its current still counts as import.
5 changes: 5 additions & 0 deletions .changeset/import-limit-reason.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

When the hourly import limit holds a car back, FTW now says so instead of blaming the main fuse. The charger's reason is `import_limit` ("Limited by the hourly import limit") whenever this hour's import budget leaves less room than the fuse, and a battery boost stopped by that budget says "Hourly import limit stopped boost". `fuse_limit` now means the main fuse alone, and the web page says "Limited by the main fuse".
68 changes: 68 additions & 0 deletions go/cmd/ftw/battery_soc_max_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"testing"
"time"

"github.com/srcfl/ftw/go/internal/config"
"github.com/srcfl/ftw/go/internal/control"
"github.com/srcfl/ftw/go/internal/telemetry"
)

// The planner's earlier charge budget cannot override the owner's SoC limit.
// No solar or export is needed to reproduce the 10 kW order at 90%.
func TestConfiguredSoCMaxStopsDispatch(t *testing.T) {
for _, mode := range []control.Mode{control.ModeCharge, control.ModePlannerArbitrage} {
t.Run(string(mode), func(t *testing.T) {
cfg := parseBatteryLimitConfig(t, "", " soc_max: 0.9\n max_charge_w: 10000\n")
ctrl := newControlStateFromConfig(cfg)
ctrl.Mode = mode
ctrl.SlewEnabled = false
ctrl.UseEnergyDispatch = true
ctrl.SlotDirective = func(now time.Time) (control.SlotDirective, bool) {
return control.SlotDirective{
SlotStart: now, SlotEnd: now.Add(15 * time.Minute),
BatteryEnergyWh: 2500, PlannedGridW: 11000, HasPlannedGridW: true,
}, true
}
tel := batteryLimitStore(1000)
soc := 0.9
tel.Update("battery", telemetry.DerBattery, 0, &soc, nil)
got := control.ComputeDispatch(tel, ctrl, map[string]float64{"battery": 15000}, 40000)
if len(got) != 1 || got[0].TargetW != 0 {
t.Fatalf("soc_max=0.9 at 90%% sent %+v, want one 0 W target", got)
}
})
}
}

func TestSoCMaxConfigPrecedenceAndReload(t *testing.T) {
cfg := parseBatteryLimitConfig(t, "", " soc_max: 0.9\n")
cfg.Planner = &config.Planner{SoCMax: .8}
ctrl := newControlStateFromConfig(cfg)
ctrl.Mode, ctrl.SlewEnabled = control.ModeCharge, false
tel := batteryLimitStore(1000)
capacities := map[string]float64{"battery": 10000}
check := func(soc float64, charging bool) {
t.Helper()
tel.Update("battery", telemetry.DerBattery, 0, &soc, nil)
got := control.ComputeDispatch(tel, ctrl, capacities, 40000)
if len(got) != 1 || (got[0].TargetW > 0) != charging {
t.Fatalf("SoC %.2f: got %+v, want charging=%v", soc, got, charging)
}
}
check(.85, true) // The battery's 90% overrides the planner's 80%.
check(.9, false)
// The config watcher replaces the limits through this same function.
cfg.Batteries = nil
ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner)
check(.85, false) // With no battery override, the planner's 80% applies.
cfg.Planner = nil
ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner)
check(.99, true) // No configured ceiling keeps the 100% default.
check(1, false)
zero := 0.0
cfg.Batteries = map[string]config.Battery{"battery": {SoCMax: &zero}}
ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner)
check(.5, false) // An explicit zero is not an absent limit.
}
83 changes: 83 additions & 0 deletions go/cmd/ftw/charge_restart_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
})
}
}
40 changes: 32 additions & 8 deletions go/cmd/ftw/control_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@ func newControlStateFromConfig(cfg *config.Config) *control.State {
ctrl.InverterGroups = inverterGroupsFrom(cfg.Drivers)
ctrl.SupportsPVCurtail = supportsPVCurtailFrom(cfg.Drivers)
ctrl.SolarFeedDrivers = solarFeedDriversFrom(cfg.Drivers)
ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries)
// Per-phase fuse params for the per-phase clamp inside applyFuseGuard
// + forceFuseDischarge. Reads l1_a/l2_a/l3_a from the meter driver
// when SiteFuseAmps > 0; otherwise the per-phase clamp is disabled.
ctrl.DriverLimits = driverLimitsFrom(cfg.ModbusControlDrivers(), cfg.Batteries, cfg.Planner)
// The fuse that control.fusePhases reads with the site meter's
// l1_a/l2_a/l3_a for every charger and battery decision.
ctrl.SiteFuseAmps = cfg.Fuse.MaxAmps
ctrl.SiteFuseVoltage = cfg.Fuse.Voltage
ctrl.SiteFusePhases = cfg.Fuse.Phases
Expand Down Expand Up @@ -77,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
Expand Down
17 changes: 11 additions & 6 deletions go/cmd/ftw/control_state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand All @@ -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)
Expand All @@ -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)
Expand Down
Loading