Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .changeset/b-ev-fuse-line-at-rating.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
"ftw": patch
---

The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. When a battery goes offline, its share of that discharge counts for 20 s, the time Core gives the battery's default mode to reach the meter, and then stops holding the car back, whether or not another battery is online.
The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with a 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. When a battery goes offline, its share of that discharge counts for 20 s, the time Core gives the battery's default mode to reach the meter, and then stops holding the car back, whether or not another battery is online.
5 changes: 5 additions & 0 deletions .changeset/d-fuse-margin-default-0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

`fuse.safety_margin_a` now defaults to 0. On a site with no saved margin, FTW works to the fuse rating: the car, the home battery's charge and fuse relief, and the fuse's total import and export ceilings each move up 0.5 A per phase, to the rating. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to drop it.
5 changes: 2 additions & 3 deletions go/cmd/ftw/control_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ func newControlStateFromConfig(cfg *config.Config) *control.State {
ctrl.SiteFuseAmps = cfg.Fuse.MaxAmps
ctrl.SiteFuseVoltage = cfg.Fuse.Voltage
ctrl.SiteFusePhases = cfg.Fuse.Phases
// EffectiveSafetyMarginA distinguishes nil ("unset, use default")
// from explicit 0 ("operator chose to disable"). The earlier
// `<= 0 -> default` shortcut clobbered the disable case.
// EffectiveSafetyMarginA resolves nil to the default (0: work to the
// fuse rating) and keeps any explicit value, 0 included.
ctrl.SiteFuseSafetyA = cfg.Fuse.EffectiveSafetyMarginA()
// PV surplus absorber underlay (opt-in). cap == 0 keeps it off.
ctrl.PVSurplusAbsorbSoCCap = cfg.Site.PVSurplusAbsorbSoCCap
Expand Down
23 changes: 23 additions & 0 deletions go/cmd/ftw/control_state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,29 @@ func TestBatteryLimitConfigBothZeroUsesDefault(t *testing.T) {
}
}

// A config with no fuse.safety_margin_a reaches Core at the fuse rating, and
// an explicit value still wins.
func TestUnsetFuseMarginReachesCoreAsZero(t *testing.T) {
cfg := parseBatteryLimitConfig(t, "", " max_charge_w: 10000\n")
ctrl := newControlStateFromConfig(cfg)
if ctrl.SiteFuseSafetyA != 0 {
t.Fatalf("unset margin reached Core as %v A, want 0", ctrl.SiteFuseSafetyA)
}
// 63 A × 230 V × 3 = 43470 W is the ceiling with no margin.
if err := ctrl.SetPeakLimit(43470); err != nil {
t.Fatalf("peak limit at the fuse: %v", err)
}
if err := ctrl.SetPeakLimit(43471); err == nil {
t.Fatal("a peak limit 1 W over the fuse was accepted")
}

half := 0.5
cfg.Fuse.SafetyMarginA = &half
if got := newControlStateFromConfig(cfg).SiteFuseSafetyA; got != 0.5 {
t.Fatalf("explicit 0.5 A reached Core as %v A", got)
}
}

// A "NaN" saved from an MQTT command must not come back as the PI setpoint
// on every boot.
func TestRestoredGridTargetIgnoresNonFinite(t *testing.T) {
Expand Down
55 changes: 34 additions & 21 deletions go/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ type Config struct {
LoadWarnings []string `yaml:"-" json:"-"`
LoadpointWarnings []string `yaml:"-" json:"-"`
// Retired names settings of removed features that loading dropped so
// they cannot steer the site. Startup warns once for each;
// DropRetiredSettings deletes them from stored settings.
// they cannot steer the site, and stored values that match an old
// default. Startup warns once for each; DropRetiredSettings deletes the
// removed settings from stored settings and leaves the values alone.
Retired []string `yaml:"-" json:"-"`
// Used once at startup to end an old calendar's persisted away selection.
RetiredCalendarEnabled bool `yaml:"-" json:"-"`
Expand Down Expand Up @@ -868,27 +869,28 @@ type Site struct {
MaxExportW float64 `yaml:"max_export_w,omitempty" json:"max_export_w,omitempty"`
}

// DefaultFuseSafetyMarginA is the fall-back per-phase amp headroom
// applied when fuse.safety_margin_a is unset (nil) in the YAML.
// Single source of truth — main.go routes through Fuse.Effective-
// SafetyMarginA() rather than re-declaring it.
const DefaultFuseSafetyMarginA = 0.5
// DefaultFuseSafetyMarginA is the per-phase margin applied when
// fuse.safety_margin_a is unset (nil). Core works to the fuse rating by
// default; a margin is opt-in. Single source of truth: main.go routes
// through Fuse.EffectiveSafetyMarginA() rather than re-declaring it.
const DefaultFuseSafetyMarginA = 0.0

// oldDefaultFuseSafetyMarginA was the default until FTW worked to the fuse
// rating. A stored value equal to it may be the settings form's old prefill
// rather than a choice, so loading names it once and keeps it.
const oldDefaultFuseSafetyMarginA = 0.5

// Fuse describes the shared breaker limit used by the fuse guard.
type Fuse struct {
MaxAmps float64 `yaml:"max_amps" json:"max_amps"`
Phases int `yaml:"phases" json:"phases"`
Voltage float64 `yaml:"voltage" json:"voltage"`

// SafetyMarginA reserves headroom (per-phase amps) below MaxAmps
// inside the dispatch fuse guard. Pointer so we can distinguish
// "unset" (nil → DefaultFuseSafetyMarginA) from "explicitly
// disabled" (non-nil 0.0). Inverters often have their own per-
// phase current protection that trips before the breaker; without
// a margin the dispatch can ride right up to MaxAmps and the
// inverter cuts to 0 W in one tick, then dispatch ramps back up —
// visible as a flap. 0.5 A × 230 V × 3 phases ≈ 345 W of aggregate
// headroom.
// SafetyMarginA is an opt-in per-phase margin below MaxAmps: each
// phase's working limit is MaxAmps − SafetyMarginA. Pointer so an
// explicit value, 0 included, always wins over the default (nil →
// DefaultFuseSafetyMarginA, which is 0). Set it for an inverter whose
// own per-phase limiter trips at the rating and cuts to 0 W.
SafetyMarginA *float64 `yaml:"safety_margin_a,omitempty" json:"safety_margin_a,omitempty"`
}

Expand All @@ -897,17 +899,27 @@ func (f Fuse) MaxPowerW() float64 {
return f.MaxAmps * f.Voltage * float64(f.Phases)
}

// EffectiveSafetyMarginA returns the per-phase amp headroom to apply,
// resolving nil ("unset → use default") vs an explicit value (including
// 0.0 to disable the margin entirely). Single read site so the default
// can never drift across consumers.
// EffectiveSafetyMarginA returns the per-phase margin to apply: the
// explicit value when set, otherwise DefaultFuseSafetyMarginA. Single read
// site so the default can never drift across consumers.
func (f Fuse) EffectiveSafetyMarginA() float64 {
if f.SafetyMarginA == nil {
return DefaultFuseSafetyMarginA
}
return *f.SafetyMarginA
}

// noteOldFuseMargin adds one notice when fuse.safety_margin_a holds FTW's
// old default. The value stays: from April to September 2026 the settings
// form saved its 0.5 A prefill on any save, but a value saved later is the
// user's choice, and the stored document cannot tell the two apart.
func (c *Config) noteOldFuseMargin() {
if m := c.Fuse.SafetyMarginA; m != nil && *m == oldDefaultFuseSafetyMarginA {
c.Retired = append(c.Retired,
"fuse.safety_margin_a is 0.5 A, FTW's old default. FTW now works to the fuse rating. Set 0 to use it.")
}
}

// Driver is one driver entry. Each driver is a Lua script loaded by
// the driver host at startup (or on hot-reload via the file watcher).
type Driver struct {
Expand Down Expand Up @@ -1496,6 +1508,7 @@ func Parse(data []byte, baseDir string) (*Config, error) {
var retiredControl retiredControlSettings
_ = doc.Decode(&retiredControl)
c.applyRetiredControl(retiredControl)
c.noteOldFuseMargin()
// An omitted app_link section follows the new default. An explicit YAML
// null was a valid opt-out before that default changed, so retain it as an
// explicit disabled section instead of letting applyDefaults turn it on.
Expand Down Expand Up @@ -2074,7 +2087,7 @@ func (c *Config) Validate() error {
}
// safety_margin_a must be in [0, max_amps) when explicitly set.
// Negative would *raise* the per-phase threshold above the breaker
// rating (defeating the guard); >= max_amps zeroes the headroom
// rating (defeating the guard); >= max_amps leaves no working limit
// and silently disables the per-phase clamp — both are real safety
// holes if reached through a typo'd config. nil (unset) is OK and
// resolves to DefaultFuseSafetyMarginA at the consumer.
Expand Down
39 changes: 35 additions & 4 deletions go/internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1260,12 +1260,43 @@ func TestNotificationsMaskSecrets(t *testing.T) {
}
}

// An unset margin works to the fuse rating: the default is 0 and a margin
// is opt-in (owner rule, 27 Oct 2026).
func TestFuseSafetyMarginNilUsesDefault(t *testing.T) {
// Field omitted in YAML → nil pointer → default 0.5 A.
f := Fuse{MaxAmps: 16, Voltage: 230, Phases: 3}
if got := f.EffectiveSafetyMarginA(); got != DefaultFuseSafetyMarginA {
t.Errorf("nil margin: got %v, want %v (DefaultFuseSafetyMarginA)",
got, DefaultFuseSafetyMarginA)
if got := f.EffectiveSafetyMarginA(); got != 0 || DefaultFuseSafetyMarginA != 0 {
t.Errorf("nil margin: got %v (default %v), want 0", got, DefaultFuseSafetyMarginA)
}
}

// Every explicit margin is kept. Exactly 0.5 A was the old default, which
// the settings form once saved on any save, so loading adds one notice for
// it and changes nothing.
func TestFuseSafetyMarginLoadKeepsExplicitValues(t *testing.T) {
for _, tc := range []struct {
line string
want float64
wantNotice bool
}{
{"", 0, false},
{" safety_margin_a: 0\n", 0, false},
{" safety_margin_a: 0.5\n", 0.5, true},
{" safety_margin_a: 0.4\n", 0.4, false},
{" safety_margin_a: 1.2\n", 1.2, false},
} {
yaml := strings.Replace(minimalYAML, " max_amps: 16\n", " max_amps: 16\n"+tc.line, 1)
c, err := Parse([]byte(yaml), "/tmp")
if err != nil {
t.Fatalf("%q: %v", tc.line, err)
}
if got := c.Fuse.EffectiveSafetyMarginA(); got != tc.want {
t.Errorf("%q: margin %v, want %v", tc.line, got, tc.want)
}
notice := len(c.Retired) == 1 && strings.Contains(c.Retired[0], "old default") &&
strings.Contains(c.Retired[0], "Set 0")
if notice != tc.wantNotice || (!tc.wantNotice && len(c.Retired) != 0) {
t.Errorf("%q: notices %q, want the old-default notice: %v", tc.line, c.Retired, tc.wantNotice)
}
}
}

Expand Down
48 changes: 48 additions & 0 deletions go/internal/config/retired_control_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,51 @@ func TestStoredRetiredControlSettingsMigrateAndAreDeleted(t *testing.T) {
t.Fatalf("second DropRetiredSettings = %v, %v; want nothing", removed, err)
}
}

// A stored 0.5 A margin keeps steering the site and stays in state.db; the
// notice comes from loading it, so dropping retired settings leaves it alone.
func TestStoredOldDefaultFuseMarginIsKeptWithANotice(t *testing.T) {
dir := t.TempDir()
path, database := filepath.Join(dir, "config.yaml"), filepath.Join(dir, "state.db")
yaml := strings.Replace(minimalYAML, " max_amps: 16\n", " max_amps: 16\n safety_margin_a: 0.5\n", 1)
if err := os.WriteFile(path, []byte(yaml), 0600); err != nil {
t.Fatal(err)
}
cfg, err := Load(path)
if err != nil {
t.Fatal(err)
}
st, err := state.Open(database)
if err != nil {
t.Fatal(err)
}
defer st.Close()
if _, err := InitializeStorage(path, database, cfg, st); err != nil {
t.Fatal(err)
}
for range 2 {
loaded, err := Load(path)
if err != nil {
t.Fatal(err)
}
if loaded.ConfigDatabase == "" {
t.Fatal("loaded from the YAML file, not from stored settings")
}
if got := loaded.Fuse.EffectiveSafetyMarginA(); got != 0.5 {
t.Fatalf("stored margin = %v, want 0.5", got)
}
if len(loaded.Retired) != 1 || !strings.Contains(loaded.Retired[0], "safety_margin_a is 0.5 A") {
t.Fatalf("notices = %q, want one naming the old 0.5 A default", loaded.Retired)
}
if removed, err := DropRetiredSettings(st, path, loaded); err != nil || len(removed) != 0 {
t.Fatalf("DropRetiredSettings = %v, %v; the margin is a setting, not a retired one", removed, err)
}
}
after, _, err := st.Configuration()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(after.Document), `"safety_margin_a":0.5`) {
t.Fatalf("stored settings lost the margin: %s", after.Document)
}
}
1 change: 1 addition & 0 deletions go/internal/config/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ func decodeStored(c state.Configuration, database, baseDir string) (*Config, err
}
_ = json.Unmarshal(c.Document, &legacyControl)
cfg.applyRetiredControl(legacyControl.Config)
cfg.noteOldFuseMargin()
// This is the same typed config that was validated on save. Do not apply new
// defaults during a storage-only reload: nil, false and zero stay distinct.
// The only exception is the site timings, which have no meaning at zero.
Expand Down
3 changes: 2 additions & 1 deletion go/internal/configreload/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ func Apply(
ctrl.SiteFuseAmps = newCfg.Fuse.MaxAmps
ctrl.SiteFuseVoltage = newCfg.Fuse.Voltage
ctrl.SiteFusePhases = newCfg.Fuse.Phases
// nil → 0.5, explicit 0 → disabled. See EffectiveSafetyMarginA.
// nil → 0 (work to the fuse rating), an explicit value wins. See
// EffectiveSafetyMarginA.
ctrl.SiteFuseSafetyA = newCfg.Fuse.EffectiveSafetyMarginA()
ctrl.MaxExportW = newCfg.Site.MaxExportW
// Site-meter swap (operator moved `is_site_meter: true` from one
Expand Down
15 changes: 10 additions & 5 deletions go/internal/control/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,9 +327,10 @@ type State struct {
SiteFuseVoltage float64
SiteFusePhases int

// SiteFuseSafetyA is amps held back from the breaker. Without it the
// inverter's own limiter trips first, output falls to 0, and dispatch
// ramps from idle. Zero disables the margin.
// SiteFuseSafetyA is an opt-in margin in amps per phase below the
// breaker; zero, the default, works to the rating. Set it for an
// inverter whose own limiter trips at the rating: output falls to 0
// and dispatch ramps from idle.
SiteFuseSafetyA float64

// Peak limit — enforced only in PeakShaving mode
Expand Down Expand Up @@ -1107,11 +1108,15 @@ func (s *State) SetPeakLimit(w float64) error {
return fmt.Errorf("peak_limit_w must be ≥ 0, got %.0f W", w)
}
if ceiling := s.peakLimitCeilingW(); ceiling > 0 && w > ceiling {
margin := ""
if s.SiteFuseSafetyA > 0 {
margin = fmt.Sprintf(", less a %.1f A safety margin", s.SiteFuseSafetyA)
}
return fmt.Errorf(
"peak_limit_w %.0f W is above the site's import ceiling %.0f W "+
"(fuse %.0f A × %.0f V × %d phases, less a %.1f A safety margin) "+
"(fuse %.0f A × %.0f V × %d phases%s) "+
"— a peak limit above the fuse can never bind",
w, ceiling, s.SiteFuseAmps, s.SiteFuseVoltage, s.SiteFusePhases, s.SiteFuseSafetyA)
w, ceiling, s.SiteFuseAmps, s.SiteFuseVoltage, s.SiteFusePhases, margin)
}
s.PeakLimitW = w
return nil
Expand Down
27 changes: 14 additions & 13 deletions go/internal/control/fuse_line_property_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,11 @@ func testFuseLineIdleStart(t *testing.T, inA float64, phases int, marginA, lineA
}
}

// fitScenario runs a 3 × 16 A site, safety margin 0.5 A, with houseLoadA of
// house on each phase. At 3.5 A twelve steps of the car fit exactly under
// the 15.5 A line. The car asks for 16 A.
func fitScenario(houseLoadA float64, run time.Duration, noise func() float64) *simSite {
// fitScenario runs a 3 × 16 A site with the default safety margin and
// enough house on each phase to leave roomA under the line. With 12 A of
// room, twelve steps of the car fit exactly. The car asks for 16 A.
func fitScenario(roomA float64, run time.Duration, noise func() float64) *simSite {
houseLoadA := 16 - simFuseSafetyA - roomA
sc := simScenario{name: "exact fit", run: run,
plant: func(p *sitesim.Plant) {
p.Fuse.RatingA = 16
Expand All @@ -240,12 +241,12 @@ func fitScenario(houseLoadA float64, run time.Duration, noise func() float64) *s

// Closed loop: the car climbs to the line and stays there for 30 min.
func TestSiteSimCarEndsAtTheLine(t *testing.T) {
s := fitScenario(3.5, 30*time.Minute, nil)
s := fitScenario(12, 30*time.Minute, nil)
if s.failure != "" {
t.Fatal(s.failure)
}
lineA := s.state.fuseLineA()
if want := (lineA - 3.5) * 690; s.p.EVSE.DrawW != want || s.peakA > lineA+1e-6 {
if want := 12.0 * 690; s.p.EVSE.DrawW != want || s.peakA > lineA+1e-6 {
t.Fatalf("car %.0f W, peak phase %.3f A; want %.0f W with every phase at most %.1f A", s.p.EVSE.DrawW, s.peakA, want, lineA)
}
var last float64
Expand Down Expand Up @@ -275,16 +276,16 @@ func TestSiteSimCarEndsAtTheLine(t *testing.T) {
// faster hunt fails.
func TestSiteSimNoisyLineCyclesSlowly(t *testing.T) {
for _, tc := range []struct {
houseA, sigma float64
cutsPerHour float64 // the most allowed after the climb
dropSteps float64 // the furthest below the top
roomA, sigma float64
cutsPerHour float64 // the most allowed after the climb
dropSteps float64 // the furthest below the top
}{
{3.25, .1, 0, 0}, {3.75, .2, 0, 0}, // part of a step left
{3.5, .03, 5, 1}, {3.5, .1, 5, 1}, {3.5, .2, 5, 2}, // exact fit
{12.25, .1, 0, 0}, {11.75, .2, 0, 0}, // part of a step left
{12, .03, 5, 1}, {12, .1, 5, 1}, {12, .2, 5, 2}, // exact fit
} {
t.Run(fmt.Sprintf("house_%.2fA/noise_%.2fA", tc.houseA, tc.sigma), func(t *testing.T) {
t.Run(fmt.Sprintf("room_%.2fA/noise_%.2fA", tc.roomA, tc.sigma), func(t *testing.T) {
rng := rand.New(rand.NewPCG(1, 0))
s := fitScenario(tc.houseA, 2*time.Hour, func() float64 { return tc.sigma * rng.NormFloat64() })
s := fitScenario(tc.roomA, 2*time.Hour, func() float64 { return tc.sigma * rng.NormFloat64() })
if s.failure != "" {
t.Fatal(s.failure)
}
Expand Down
21 changes: 19 additions & 2 deletions go/internal/control/peak_limit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
)

// SetPeakLimit is the one place the peak-shaving threshold is validated
// against the site's fuse. A 16 A / 230 V / 3-phase site is 11040 W; the
// default 0.5 A safety margin costs 345 W, so the highest limit that can
// against the site's fuse. A 16 A / 230 V / 3-phase site is 11040 W; an
// opt-in 0.5 A safety margin costs 345 W, so the highest limit that can
// still be the first thing to bind is 10695 W.
func fusedState() *State {
st := NewState(0, 50, "ferroamp")
Expand Down Expand Up @@ -63,6 +63,23 @@ func TestSetPeakLimitRejectsValueInsideTheSafetyMargin(t *testing.T) {
}
}

// The message names the margin only when the site has one. With the
// default 0 the ceiling is the fuse itself.
func TestSetPeakLimitMessageNamesOnlyARealMargin(t *testing.T) {
st := fusedState()
if err := st.SetPeakLimit(20000); err == nil || !strings.Contains(err.Error(), "less a 0.5 A safety margin") {
t.Fatalf("with a 0.5 A margin the message must name it, got %v", err)
}
st.SiteFuseSafetyA = 0
err := st.SetPeakLimit(20000)
if err == nil || strings.Contains(err.Error(), "margin") || !strings.Contains(err.Error(), "11040 W") {
t.Fatalf("with no margin the message must give the fuse as the ceiling and no margin, got %v", err)
}
if err := st.SetPeakLimit(11040); err != nil {
t.Fatalf("with no margin the fuse itself is the ceiling, got %v", err)
}
}

// Zero is a real threshold in peak shaving — "correct everything above
// 0 W of import" — not the zero-means-disabled convention that
// PeakImportCeilingW and MaxExportW use. Dispatch has always read it that
Expand Down
Loading