diff --git a/.changeset/battery-what-it-can-do-now.md b/.changeset/battery-what-it-can-do-now.md new file mode 100644 index 000000000..5f01b1dfc --- /dev/null +++ b/.changeset/battery-what-it-can-do-now.md @@ -0,0 +1,34 @@ +--- +"ftw": minor +--- + +Judge a battery against what it can do now, not only against FTW's order. + +A home box with a Sungrow hybrid sent 23 "not following" notices in two +weeks, though its battery did all it could. At night the inverter held grid +import at about 4.3 kW, so the battery took 4.3 kW less the house load; on +discharge the battery gave a flat 22 A. + +Core now learns these limits per battery from its own control journal. When +a battery falls short of its order in the right direction and the grid +import, grid export, battery current or battery power stays flat, Core keeps +that run. Once the same level shows at least three times on two days, a +shortfall at that level reads "At its usual limit", with words such as "The +inverter takes at most 4.3 kW from the grid. FTW has seen this 14 times since +8 Nov." A battery that gives well below its limit still warns, and so does +one that gives less than half of its order, however often: a broken battery +never becomes normal. So a cold battery whose BMS lets it give, say, 46 % of +the order also stays a warning, unless its driver reports that limit. A grid limit counts only while the battery moves and +the meter shows live, changing readings, so a meter driver that resends a +cached value teaches nothing. A new, lower limit becomes normal only after it +repeats on two days, and the old one stays on record. Limits are kept per +temperature band when the battery reports its temperature. + +A battery whose driver reports `available_charge_W` or +`available_discharge_W` reads "Limited by the battery" at once when it gives +that much. A battery whose driver reports `device_state` standby or starting +still warns, now with that reason. These verdicts change the words and the +status only; dispatch, the fuse guard and commands do not read them. GET +/api/battery_models shows the learned limits, and POST +/api/battery_models/reset forgets them along with the rest of the model. +Limited verdicts never send the "not following" notice. diff --git a/go/internal/api/api.go b/go/internal/api/api.go index 1dd8cd0b2..6c81d2678 100644 --- a/go/internal/api/api.go +++ b/go/internal/api/api.go @@ -2288,6 +2288,8 @@ func (s *Server) handleGetModels(w http.ResponseWriter, r *http.Request) { "max_discharge_curve": m.MaxDischargeCurve, "a": m.A, "b": m.B, + // What the battery has shown it can do when short of an order. + "plateaus": m.Plateaus.View(), } } writeJSON(w, 200, out) diff --git a/go/internal/api/api_control_capability.go b/go/internal/api/api_control_capability.go new file mode 100644 index 000000000..2a2320470 --- /dev/null +++ b/go/internal/api/api_control_capability.go @@ -0,0 +1,236 @@ +package api + +import ( + "encoding/json" + "math" + "time" + + "github.com/srcfl/ftw/go/internal/battery" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// A battery that gives 4.3 kW of a 5 kW order because that is all it can do +// now is limited, not out of control. This file judges a battery's shortfall +// against what it can do now: what its driver reports, and the limits it has +// shown before (battery.Plateaus). It changes the verdict and nothing else; +// dispatch, fuse protection, clamps and commands never read it. + +// batteryNow is what a battery's driver reports it can do now +// (srcfl/device-drivers docs/WRITING-A-DRIVER.md, "What a battery can do +// now"). A read that failed leaves its field out, so a missing field +// changes nothing. +type batteryNow struct { + AvailableChargeW *float64 `json:"available_charge_W"` + AvailableDischargeW *float64 `json:"available_discharge_W"` + TemperatureC *float64 `json:"temperature_C"` + LegacyTempC *float64 `json:"temp_c"` + DeviceState string `json:"device_state"` + A *float64 `json:"A"` + LegacyA *float64 `json:"a"` + V *float64 `json:"V"` + LegacyV *float64 `json:"v"` +} + +func readBatteryNow(data json.RawMessage) batteryNow { + var b batteryNow + if len(data) > 0 { + _ = json.Unmarshal(data, &b) + } + return b +} + +// The driver guide drops a temperature outside -40 to 100 °C and a power +// outside 0 to 100 kW; Core does the same. +func (b batteryNow) tempC() *float64 { + t := b.TemperatureC + if t == nil { + t = b.LegacyTempC + } + if t == nil || !finiteW(*t) || *t < -40 || *t > 100 { + return nil + } + return t +} + +func (b batteryNow) available(charge bool) *float64 { + w := b.AvailableDischargeW + if charge { + w = b.AvailableChargeW + } + if w == nil || !finiteW(*w) || *w < 0 || *w > 100_000 { + return nil + } + return w +} + +func (b batteryNow) currentA() *float64 { + a := b.A + if a == nil { + a = b.LegacyA + } + if a == nil || !finiteW(*a) || *a == 0 { + return nil + } + return watts(math.Abs(*a)) +} + +func (b batteryNow) voltageV() *float64 { + v := b.V + if v == nil { + v = b.LegacyV + } + if v == nil || !finiteW(*v) || *v <= 0 { + return nil + } + return v +} + +// The device says it is not running, so it cannot follow an order. +func (b batteryNow) standby() bool { return b.DeviceState == "standby" || b.DeviceState == "starting" } + +// explainBatteryShortfall runs after every other verdict step. It relabels +// only a battery's settled shortfall in the right direction +// (power_below_target) or its zero response (no_power_response), from fresh +// readings of an accepted order: +// - device_state standby or starting keeps the warning as device_standby, +// so the words can say why; +// - a reported available_*_W below the order that the battery delivers, +// within the control tolerance, is limited / battery_limit; +// - a trusted learned plateau the shortfall sits on is limited / +// learned_limit. +// +// It also leaves the sample the limit learner takes on the journal's cadence. +// Wrong direction, power above the order or while idle, a changed setpoint, +// stale readings, faults and every Core stop keep their own reasons and are +// never sampled. +func (s *Server) explainBatteryShortfall(f *ControlFeedback, data json.RawMessage, meter, blocked string, now time.Time) { + if f.Kind != "battery" || f.SentW == nil || f.ActualW == nil || f.Reason != "power_below_target" && f.Reason != "no_power_response" { + return + } + b := readBatteryNow(data) + sent, actual := *f.SentW, *f.ActualW + charge := sent > 0 + if b.standby() { + f.State, f.Reason, f.Severity = "warning", "device_standby", "warning" + return + } + if f.Reason == "power_below_target" && math.Abs(actual) >= battery.PlateauMinShortfallW { + grid, gridAt := s.siteGridW(f.Driver, meter, blocked, charge, now) + f.shortfall = &battery.ShortfallSample{At: now, Charge: charge, OrderW: math.Abs(sent), BatteryW: math.Abs(actual), + BatteryA: b.currentA(), GridW: grid, GridAt: gridAt, TempC: b.tempC()} + } + // 0 means the device allows nothing now, as when charging below 0 °C. + if limit := b.available(charge); limit != nil && *limit < math.Abs(sent) && + math.Abs(math.Abs(actual)-*limit) <= telemetry.ControlToleranceW(*limit) { + f.State, f.Reason, f.Severity = "limited", "battery_limit", "info" + f.LimitW, f.LimitSource, f.LimitKind = watts(*limit), "device", "battery_reported" + return + } + if f.shortfall == nil { + return + } + known, ok := s.learnedLimit(f.Driver, *f.shortfall) + if !ok { + return + } + f.State, f.Reason, f.Severity = "limited", "learned_limit", "info" + f.LimitSource, f.LimitKind, f.LimitSeen, f.LimitSinceMs = "learned", known.Kind, known.Seen, known.SinceMs + // Limits are positive amounts in the order's direction. A current limit + // becomes watts at the pack's voltage now; without one it has no watts. + inW := func(value float64) *float64 { + if known.Kind != battery.LimitBatteryCurrent { + return watts(value) + } + if v := b.voltageV(); v != nil { + return watts(value * *v) + } + return nil + } + f.LimitW = inW(known.Value) + if known.Kind == battery.LimitBatteryCurrent { + f.LimitA = watts(known.Value) + } + if known.Earlier != nil { + f.LimitEarlierW = inW(known.Earlier.Value) + } + // Under a grid limit the battery has the limit less what the rest of + // the site takes or gives now. + if g := f.shortfall.GridW; g != nil && (known.Kind == battery.LimitGridImport || known.Kind == battery.LimitGridExport) { + f.LimitRoomW = watts(math.Max(0, known.Value-*g+math.Abs(actual))) + } +} + +func (s *Server) learnedLimit(driver string, sample battery.ShortfallSample) (battery.Plateau, bool) { + if s.deps.Models == nil || s.deps.ModelsMu == nil { + return battery.Plateau{}, false + } + s.deps.ModelsMu.Lock() + defer s.deps.ModelsMu.Unlock() + m := s.deps.Models[driver] + if m == nil { + return battery.Plateau{}, false + } + return m.Plateaus.Explain(sample) +} + +// siteGridMaxAge is how old a site meter reading may be for a shortfall +// sample: three journal samples. +const siteGridMaxAge = 15 * time.Second + +// siteGridW is the grid power a battery's shortfall is judged against: +// import while charging, export while discharging, as positive W. It comes +// only from a site meter Core trusts for site evidence: a sensor separate +// from the battery, live, without a fault, fresh, and while dispatch is free. +// It also gives when the meter measured it, by its own clock where it +// reports one; the learner asks a run's readings to show a live meter. +func (s *Server) siteGridW(driver, meter, blocked string, charge bool, now time.Time) (*float64, time.Time) { + if meter == "" || blocked != "" || !s.separateMeterSource(driver, meter) { + return nil, time.Time{} + } + obs, ok := s.deps.Tel.LiveMeterPower(meter) + if !ok || now.Sub(obs.Seen()) > siteGridMaxAge { + return nil, time.Time{} + } + w := obs.PowerW + if !charge { + w = -w + } + if w <= 0 { + return nil, time.Time{} + } + return &w, obs.At +} + +// learnBatteryLimits feeds each battery's limit learner one sample. The +// control journal calls it every 5 s, so how often a client reads the status +// never changes what is learned. +func (s *Server) learnBatteryLimits(rows []ControlFeedback, now time.Time) { + if s.deps.Models == nil || s.deps.ModelsMu == nil { + return + } + // Self-tune sends its own test steps; what a battery does under them + // is not its normal. + tuning := s.deps.SelfTune != nil && s.deps.SelfTune.Status().Active + samples := map[string]*battery.ShortfallSample{} + for i := range rows { + if rows[i].Kind == "battery" && rows[i].shortfall != nil && !tuning { + samples[rows[i].Driver] = rows[i].shortfall + } + } + s.deps.ModelsMu.Lock() + defer s.deps.ModelsMu.Unlock() + for name, m := range s.deps.Models { + if m == nil { + continue + } + if m.Plateaus == nil { + if samples[name] == nil { + continue + } + m.Plateaus = &battery.Plateaus{} + } + m.Plateaus.Tick(now, samples[name]) + } +} + +func finiteW(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) } diff --git a/go/internal/api/api_control_capability_test.go b/go/internal/api/api_control_capability_test.go new file mode 100644 index 000000000..4d53a4685 --- /dev/null +++ b/go/internal/api/api_control_capability_test.go @@ -0,0 +1,646 @@ +package api + +import ( + "encoding/json" + "fmt" + "math" + "math/rand" + "net/http/httptest" + "slices" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/srcfl/ftw/go/internal/battery" + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/control" + "github.com/srcfl/ftw/go/internal/selftune" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The owner's home box, 8-22 Nov 2026: a Sungrow SH-RT hybrid with a 9.6 kWh +// SBR096 battery on 3 x 20 A, relaying its own grid meter, polled once a +// second. Its control journal held 23 control.not_following notices in two +// weeks. Night grid charging ordered 5 kW; the inverter held grid import at +// about 4.3 kW, so the battery took 4.3 kW less the house load. Discharge +// ordered 5 kW; the battery gave a flat 21.6-23.1 A DC, 4.0-4.4 kW as the +// pack voltage moved. These traces replay those patterns. +type sungrowTrace struct { + tel *telemetry.Store + srv *Server + models map[string]*battery.Model + cmdW float64 + // battery reports what the battery does this second: its power, DC + // current and the extra fields of its emit. + battery func() (w, a, v float64, extra string) + houseW float64 + // frozenMeterW, when set, is the one grid value a driver keeps resending + // from its cache. + frozenMeterW *float64 +} + +func newSungrowTrace() *sungrowTrace { + tel := telemetry.NewStore() + tel.DriverHealthMut("sungrow") + models := map[string]*battery.Model{"sungrow": battery.New("sungrow")} + ctrl := &control.State{Mode: control.ModePlannerArbitrage, SiteMeterDriver: "sungrow"} + srv := New(&Deps{Tel: tel, Ctrl: ctrl, CtrlMu: &sync.Mutex{}, Cfg: &config.Config{}, CfgMu: &sync.RWMutex{}, + Models: models, ModelsMu: &sync.Mutex{}}) + return &sungrowTrace{tel: tel, srv: srv, models: models} +} + +func (s *sungrowTrace) order(w float64) { + s.cmdW = w + c := s.tel.BeginCommand("sungrow", []byte(fmt.Sprintf(`{"action":"battery","power_w":%g}`, w)), time.Now()) + s.tel.CompleteCommand(c, "accepted") +} + +func (s *sungrowTrace) poll() { + w, a, v, extra := s.battery() + grid := s.houseW + w + if s.frozenMeterW != nil { + grid = *s.frozenMeterW + } + s.tel.Update("sungrow", telemetry.DerMeter, grid, nil, []byte(`{"power_origin":"external_meter"}`)) + soc := 0.5 + s.tel.Update("sungrow", telemetry.DerBattery, w, &soc, []byte(fmt.Sprintf(`{"setpoint_w":%g,"a":%.1f,"v":%.1f%s}`, s.cmdW, a, v, extra))) + s.tel.RecordDriverSuccess("sungrow") +} + +// run holds the order for d, polling every second. The control journal +// samples every 5 s, which feeds the learner; each sample's verdict is +// passed to seen. +func (s *sungrowTrace) run(d time.Duration, orderW float64, seen func(ControlFeedback)) { + start := time.Now() + for sec := 0; time.Since(start) < d; sec++ { + if sec%30 == 0 { + s.order(orderW) + } + time.Sleep(time.Second) + s.poll() + if sec%5 == 4 { + now := time.Now() + s.srv.JournalVerdicts(now) + if seen != nil { + seen(s.batteryRow(now)) + } + } + } +} + +func (s *sungrowTrace) batteryRow(now time.Time) ControlFeedback { + for _, f := range s.srv.controlFeedback(now) { + if f.Kind == "battery" { + return f + } + } + return ControlFeedback{} +} + +// idle rests the battery until the same time next day. +func (s *sungrowTrace) idle(until time.Time) { + s.battery = func() (float64, float64, float64, string) { return 0, 0, 190, "" } + s.order(0) + for time.Now().Before(until) { + time.Sleep(5 * time.Minute) + s.poll() + s.srv.JournalVerdicts(time.Now()) + } +} + +// tally counts verdicts after the order settles. +type tally struct { + n int + hits map[string]int + last ControlFeedback +} + +func (t *tally) add(f ControlFeedback) { + if t.hits == nil { + t.hits = map[string]int{} + } + t.n++ + t.hits[f.Status+"/"+f.Reason+"/"+f.Severity]++ + t.last = f +} + +func (t *tally) share(key string) float64 { + if t.n == 0 { + return 0 + } + return float64(t.hits[key]) / float64(t.n) +} + +// gridCharge is a night of grid charging under the inverter's import cap: +// grid import sits at 4.3 kW while the house takes 0.3-3 kW, so the battery +// gets what is left. +func (s *sungrowTrace) gridCharge(rng *rand.Rand, battery func(house float64) float64) { + s.battery = func() (float64, float64, float64, string) { + s.houseW = math.Max(300, math.Min(3000, s.houseW+rng.NormFloat64()*150)) + w := battery(s.houseW) + v := 190.0 + return w, w / v, v, "" + } +} + +func importCap(rng *rand.Rand) func(house float64) float64 { + return func(house float64) float64 { return 4316 + rng.NormFloat64()*15 - house } +} + +func TestGridImportCapIsLearnedOverNights(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + rng := rand.New(rand.NewSource(3)) + s := newSungrowTrace() + s.houseW = 1000 + start := time.Now() + var nights [3]tally + notices := 0 + for n := range 3 { + s.gridCharge(rng, importCap(rng)) + s.run(5*time.Hour, 5000, func(f ControlFeedback) { + if f.Status == "waiting" { + return + } + nights[n].add(f) + // control.not_following reads the same status, so a + // known limit never fires it. + for _, st := range s.srv.ControlStates(time.Now()) { + if f.Reason == "learned_limit" && st.Kind == "battery" && st.Status != "limited" { + notices++ + } + } + }) + s.idle(start.Add(time.Duration(n+1) * 24 * time.Hour)) + } + if got := nights[0].share("not_following/power_below_target/warning"); got < 0.95 { + t.Fatalf("first night not following in %.0f%% of samples: %v", got*100, nights[0].hits) + } + if got := nights[2].share("limited/learned_limit/info"); got < 0.95 { + t.Fatalf("third night limited in %.0f%% of samples: %v", got*100, nights[2].hits) + } + f := nights[2].last + if f.LimitSource != "learned" || f.LimitKind != "grid_import" || f.LimitW == nil || math.Abs(*f.LimitW-4316) > 30 || + f.LimitSeen < 4 || f.LimitRoomW == nil || math.Abs(*f.LimitRoomW-math.Abs(*f.ActualW)) > 100 || f.LimitEarlierW != nil { + t.Fatalf("limit fields %s", jsonOf(f)) + } + if since := time.UnixMilli(f.LimitSinceMs); since.Before(start) || since.After(start.Add(time.Hour)) { + t.Fatalf("limit since %v, want the first night", since) + } + if notices > 0 { + t.Fatalf("a known limit read as %d other statuses for notifications", notices) + } + + // Discharging against a charge order is never explained or learned. + runs := runsOf(s.models["sungrow"]) + s.battery = func() (float64, float64, float64, string) { return -2000, 2000 / 190.0, 190, "" } + var wrong tally + s.run(10*time.Minute, 5000, func(f ControlFeedback) { + if f.Status != "waiting" { + wrong.add(f) + } + }) + if got := wrong.share("not_following/power_wrong_direction/warning"); got < 0.9 { + t.Fatalf("wrong direction: %v", wrong.hits) + } + if got := runsOf(s.models["sungrow"]); got != runs { + t.Fatalf("wrong direction was learned: %d runs, had %d", got, runs) + } + + // Later the battery takes 1 kW while the house takes 300 W: far + // below the plateau, so it warns. + s.houseW = 300 + s.battery = func() (float64, float64, float64, string) { return 1000, 1000 / 190.0, 190, "" } + var low tally + s.run(10*time.Minute, 5000, func(f ControlFeedback) { + if f.Status != "waiting" { + low.add(f) + } + }) + if got := low.share("not_following/power_below_target/warning"); got < 0.9 { + t.Fatalf("a drop to 1 kW was explained: %v", low.hits) + } + }) +} + +func TestDischargeCurrentLimitIsLearned(t *testing.T) { + for _, tc := range []struct{ name, extra string }{ + {"driver reports no limits", ""}, + // sungrow 1.7.0 on the home box, 22 Nov 2026: the BMS reports its + // 30 A rating both ways (5,973 W at 199 V) and 20 °C, well above the + // 22.5 A the battery gives. That report explains nothing here; the + // learned current limit still does. + {"BMS reports its 30 A rating", `,"available_charge_W":5973,"available_discharge_W":5973,"temperature_C":20`}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + rng := rand.New(rand.NewSource(5)) + s := newSungrowTrace() + s.houseW = 800 + start := time.Now() + var days [3]tally + for d := range 3 { + began := time.Now() + s.battery = func() (float64, float64, float64, string) { + s.houseW = math.Max(300, math.Min(3000, s.houseW+rng.NormFloat64()*150)) + v := 192 - 5*time.Since(began).Hours()/3 + a := 22.4 + rng.NormFloat64()*0.25 + return -a * v, a, v, tc.extra + } + s.run(3*time.Hour, -5000, func(f ControlFeedback) { + if f.Status != "waiting" { + days[d].add(f) + } + }) + s.idle(start.Add(time.Duration(d+1) * 24 * time.Hour)) + } + if got := days[0].share("not_following/power_below_target/warning"); got < 0.95 { + t.Fatalf("first discharge: %v", days[0].hits) + } + if got := days[2].share("limited/learned_limit/info"); got < 0.95 { + t.Fatalf("third discharge: %v", days[2].hits) + } + for _, day := range days { + if day.hits["limited/battery_limit/info"] > 0 { + t.Fatalf("a reported limit far above the delivery explained it: %v", day.hits) + } + } + f := days[2].last + if f.LimitKind != "battery_current" || f.LimitSource != "learned" || f.LimitA == nil || math.Abs(*f.LimitA-22.4) > 0.3 || + f.LimitW == nil || math.Abs(*f.LimitW-*f.LimitA*187) > 60 || f.LimitRoomW != nil { + t.Fatalf("limit fields %s", jsonOf(f)) + } + }) + }) + } +} + +// A battery whose driver reports what it can give now is limited at once. +func TestReportedBatteryLimitExplainsAtOnce(t *testing.T) { + for _, tc := range []struct { + name, extra string + orderW, w float64 + status, reason string + }{ + {"reported discharge limit", `,"available_discharge_W":3200`, -5000, -3150, "limited", "battery_limit"}, + {"canonical names", `,"available_charge_W":2400,"temperature_C":2`, 5000, 2380, "limited", "battery_limit"}, + {"charging not allowed now", `,"available_charge_W":0`, 5000, 0, "limited", "battery_limit"}, + {"gives far less than it reports", `,"available_discharge_W":3200`, -5000, -1000, "not_following", "power_below_target"}, + {"limit above the order", `,"available_discharge_W":6000`, -5000, -3150, "not_following", "power_below_target"}, + {"rating far above the delivery", `,"available_discharge_W":5973,"temperature_C":20`, -5000, -4300, "not_following", "power_below_target"}, + {"rating far above the delivery, larger order", `,"available_discharge_W":5973`, -6500, -4300, "not_following", "power_below_target"}, + {"no limit reported", ``, -5000, -3150, "not_following", "power_below_target"}, + {"limit out of range", `,"available_discharge_W":-3200`, -5000, -3150, "not_following", "power_below_target"}, + {"standby", `,"device_state":"standby"`, -5000, 0, "not_following", "device_standby"}, + {"starting", `,"device_state":"starting","available_discharge_W":0`, -5000, -200, "not_following", "device_standby"}, + {"running", `,"device_state":"running"`, -5000, 0, "not_following", "no_power_response"}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := newSungrowTrace() + s.houseW = 800 + s.battery = func() (float64, float64, float64, string) { return tc.w, math.Abs(tc.w) / 190, 190, tc.extra } + var last ControlFeedback + s.run(90*time.Second, tc.orderW, func(f ControlFeedback) { last = f }) + if last.Status != tc.status || last.Reason != tc.reason { + t.Fatalf("got %s/%s/%s, want %s/%s", last.Status, last.Reason, last.Severity, tc.status, tc.reason) + } + switch tc.reason { + case "battery_limit": + if last.Severity != "info" || last.LimitSource != "device" || last.LimitKind != "battery_reported" || last.LimitW == nil || last.LimitSeen != 0 { + t.Fatalf("limit fields %s", jsonOf(last)) + } + case "device_standby": + if last.Severity != "warning" || last.LimitW != nil { + t.Fatalf("standby %s", jsonOf(last)) + } + default: + if last.LimitW != nil || last.LimitSource != "" { + t.Fatalf("unexplained shortfall carries a limit: %s", jsonOf(last)) + } + } + }) + }) + } +} + +// A limit learned in the cold does not explain a warm day, and the reverse. +func TestColdPlateauDoesNotExplainWarmShortfall(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + rng := rand.New(rand.NewSource(9)) + s := newSungrowTrace() + s.houseW = 800 + start := time.Now() + discharge := func(tempC float64) { + s.battery = func() (float64, float64, float64, string) { + a := 12 + rng.NormFloat64()*0.2 + return -a * 190, a, 190, fmt.Sprintf(`,"temp_c":%.1f`, tempC) + } + } + for d := range 3 { + discharge(-5 + 4*rng.Float64()) + s.run(3*time.Hour, -4000, nil) + s.idle(start.Add(time.Duration(d+1) * 24 * time.Hour)) + } + var cold, warm tally + discharge(-3) + s.run(10*time.Minute, -4000, func(f ControlFeedback) { + if f.Status != "waiting" { + cold.add(f) + } + }) + if got := cold.share("limited/learned_limit/info"); got < 0.9 { + t.Fatalf("cold shortfall not explained: %v", cold.hits) + } + discharge(15) + s.run(10*time.Minute, -4000, func(f ControlFeedback) { + if f.Status != "waiting" { + warm.add(f) + } + }) + if got := warm.share("not_following/power_below_target/warning"); got < 0.9 { + t.Fatalf("a cold limit explained a warm shortfall: %v", warm.hits) + } + }) +} + +// GET /api/battery_models shows what was learned, and the learner never +// runs on HTTP reads: only the journal's cadence feeds it. +func TestBatteryModelsShowPlateaus(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + rng := rand.New(rand.NewSource(3)) + s := newSungrowTrace() + s.houseW = 1000 + start := time.Now() + s.gridCharge(rng, importCap(rng)) + for sec := 0; time.Since(start) < 10*time.Minute; sec++ { + if sec%30 == 0 { + s.order(5000) + } + time.Sleep(time.Second) + s.poll() + s.srv.controlFeedback(time.Now()) + } + if s.models["sungrow"].Plateaus != nil { + t.Fatal("status reads fed the learner") + } + for n := range 3 { + s.gridCharge(rng, importCap(rng)) + s.run(3*time.Hour, 5000, nil) + s.idle(start.Add(time.Duration(n+1) * 24 * time.Hour)) + } + rec := httptest.NewRecorder() + s.srv.handleGetModels(rec, httptest.NewRequest("GET", "/api/battery_models", nil)) + var body map[string]struct { + Plateaus battery.PlateauView `json:"plateaus"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + view := body["sungrow"].Plateaus + if len(view.Known) != 1 || view.Known[0].Kind != "grid_import" || view.Known[0].Unit != "W" || len(view.Series) == 0 { + t.Fatalf("battery models %s", rec.Body.String()) + } + }) +} + +func runsOf(m *battery.Model) int { + n := 0 + for _, s := range m.Plateaus.View().Series { + n += len(s.Runs) + } + return n +} + +func jsonOf(v any) string { + b, _ := json.Marshal(v) + return string(b) +} + +// Grid power reaches the learner only from a site meter Core trusts for site +// evidence: a separate sensor, live, without a fault, fresh, while dispatch +// is free. +func TestShortfallGridComesFromATrustedMeter(t *testing.T) { + for _, tc := range []struct { + name, data, blocked string + age time.Duration + fault, charge bool + want *float64 + }{ + {"meter it relays", `{"power_origin":"external_meter"}`, "", 0, false, true, watts(4300)}, + {"export while discharging", `{"power_origin":"external_meter"}`, "", 0, false, false, nil}, + {"meter computed from its own flows", `{"power_origin":"derived"}`, "", 0, false, true, nil}, + {"origin unknown", `{}`, "", 0, false, true, nil}, + {"old reading", `{"power_origin":"external_meter"}`, "", 20 * time.Second, false, true, nil}, + {"meter fault", `{"power_origin":"external_meter"}`, "", 0, true, true, nil}, + {"dispatch blocked", `{"power_origin":"external_meter"}`, "site_meter_stale", 0, false, true, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := newSungrowTrace() + s.tel.Update("sungrow", telemetry.DerMeter, 4300, nil, []byte(tc.data)) + s.tel.RecordDriverSuccess("sungrow") + if tc.fault { + s.tel.SetDriverDeviceFault("sungrow", true, "test") + } + time.Sleep(tc.age) + got, _ := s.srv.siteGridW("sungrow", "sungrow", tc.blocked, tc.charge, time.Now()) + if (got == nil) != (tc.want == nil) || got != nil && *got != *tc.want { + t.Fatalf("grid %v, want %v", got, tc.want) + } + }) + }) + } +} + +// A battery that breaks and gives a steady 0.7 kW against a 5 kW order for +// three nights is failing. Neither its own steady power nor a grid that sits +// still under a steady house makes that normal. A meter driver that resends +// one cached value looks like an import cap; it is not one either. +func TestFailureAndFrozenMeterAreNeverLearnedAsNormal(t *testing.T) { + for _, tc := range []struct { + name string + setup func(s *sungrowTrace, rng *rand.Rand) + }{ + {"failing battery, steady house", func(s *sungrowTrace, rng *rand.Rand) { + s.houseW = 600 + s.battery = func() (float64, float64, float64, string) { + w := 700 + rng.NormFloat64()*10 + return w, w / 190, 190, "" + } + }}, + {"failing battery, moving house", func(s *sungrowTrace, rng *rand.Rand) { + s.battery = func() (float64, float64, float64, string) { + s.houseW = math.Max(300, math.Min(3000, s.houseW+rng.NormFloat64()*150)) + w := 700 + rng.NormFloat64()*10 + return w, w / 190, 190, "" + } + }}, + {"frozen meter under a moving battery", func(s *sungrowTrace, rng *rand.Rand) { + frozen := 4316.0 + s.frozenMeterW = &frozen + s.gridCharge(rng, importCap(rng)) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + rng := rand.New(rand.NewSource(13)) + s := newSungrowTrace() + s.houseW = 1000 + start := time.Now() + var last tally + for n := range 3 { + tc.setup(s, rng) + last = tally{} + s.run(5*time.Hour, 5000, func(f ControlFeedback) { + if f.Status != "waiting" { + last.add(f) + } + }) + s.idle(start.Add(time.Duration(n+1) * 24 * time.Hour)) + } + if got := last.share("not_following/power_below_target/warning"); got < 0.95 { + t.Fatalf("third night: %v", last.hits) + } + if known := s.models["sungrow"].Plateaus.Known(); len(known) != 0 { + t.Fatalf("learned as normal: %s", jsonOf(known)) + } + }) + }) + } +} + +// seedLimits gives a battery trusted plateaus at 2 kW and 10.5 A both ways, +// seen on three days, so any verdict that asked would find one. +func seedLimits(m *battery.Model, start time.Time) { + m.Plateaus = &battery.Plateaus{} + for _, dir := range []string{"charge", "discharge"} { + for kind, value := range map[string]float64{battery.LimitBatteryPower: 2000, battery.LimitBatteryCurrent: 2000 / 190.0} { + series := battery.PlateauSeries{Direction: dir, Kind: kind} + for d := range 3 { + at := start.Add(time.Duration(d-3) * 24 * time.Hour) + series.Runs = append(series.Runs, battery.PlateauRun{StartMs: at.UnixMilli(), EndMs: at.Add(time.Hour).UnixMilli(), Median: value, Samples: 720}) + } + m.Plateaus.Series = append(m.Plateaus.Series, series) + } + } +} + +// Learned and reported limits explain only a shortfall in the right +// direction. Every other verdict keeps its own reason, and nothing is +// learned from it, nor from anything while self-tune runs. +func TestLimitsNeverExplainOtherVerdicts(t *testing.T) { + const limits = `,"available_charge_W":2000,"available_discharge_W":2000` + for _, tc := range []struct { + name, extra string + orderW float64 + // before runs ahead of the ten minutes under the order, then after. + before, then func(s *sungrowTrace) + reasons []string // any of these + }{ + {"setpoint changed", `,"setpoint_w":-2000`, -3000, nil, nil, []string{"setpoint_changed"}}, + {"power above target", "", -1500, nil, nil, []string{"power_above_target"}}, + {"power while idle", "", 0, nil, nil, []string{"power_while_idle"}}, + {"wrong direction", "", 3000, nil, nil, []string{"power_wrong_direction"}}, + {"device fault", "", -3000, func(s *sungrowTrace) { s.tel.SetDriverDeviceFault("sungrow", true, "test fault") }, nil, []string{"device_fault"}}, + // It follows its order, then its readings stop. + {"readings lost", "", -2000, nil, func(s *sungrowTrace) { + for range 24 { + time.Sleep(5 * time.Second) + s.srv.JournalVerdicts(time.Now()) + } + }, []string{"readings_lost"}}, + {"driver says offline", `,"is_online":false`, -3000, nil, nil, []string{"telemetry_stale", "readings_lost"}}, + {"self-tune runs", "", -3000, nil, nil, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := newSungrowTrace() + s.houseW = 800 + seedLimits(s.models["sungrow"], time.Now()) + before := runsOf(s.models["sungrow"]) + if tc.reasons == nil { + s.srv.deps.SelfTune = selftune.NewCoordinator() + if err := s.srv.deps.SelfTune.Start([]string{"sungrow"}, s.models, 5); err != nil { + t.Fatal(err) + } + } + s.battery = func() (float64, float64, float64, string) { return -2000, 2000 / 190.0, 190, limits + tc.extra } + if tc.before != nil { + tc.before(s) + } + var last ControlFeedback + s.run(10*time.Minute, tc.orderW, func(f ControlFeedback) { last = f }) + if tc.then != nil { + tc.then(s) + last = s.batteryRow(time.Now()) + } + s.idle(time.Now().Add(10 * time.Minute)) + if got := runsOf(s.models["sungrow"]); got != before { + t.Fatalf("learned %d runs from it", got-before) + } + if tc.reasons == nil { + return + } + if !slices.Contains(tc.reasons, last.Reason) || last.LimitSource != "" || last.LimitW != nil || last.Status == "limited" { + t.Fatalf("got %s/%s/%s %s, want one of %v and no limit", last.Status, last.Reason, last.Severity, jsonOf(last), tc.reasons) + } + }) + }) + } +} + +// srcfl/ftw#2017 (open) adds battery_calibrating, set before this step. Only +// power_below_target and no_power_response are ever relabelled or sampled, +// so a calibrating battery keeps its reason and teaches nothing. +func TestCalibratingBatteryIsNeverRelabelled(t *testing.T) { + s := newSungrowTrace() + seedLimits(s.models["sungrow"], time.Now()) + for _, reason := range []string{"battery_calibrating", "battery_nearly_full", "battery_nearly_empty", "core_limit", "site_meter_stale", "observe_only"} { + f := ControlFeedback{Kind: "battery", Driver: "sungrow", State: "waiting", Reason: reason, Severity: "info", SentW: watts(-3000), ActualW: watts(-2000)} + want := f + s.srv.explainBatteryShortfall(&f, []byte(`{"available_discharge_W":2000,"device_state":"standby","a":10.5,"v":190}`), "sungrow", "", time.Now()) + if f.Reason != want.Reason || f.State != want.State || f.Severity != want.Severity || f.LimitW != nil || f.shortfall != nil { + t.Fatalf("%s relabelled: %s", reason, jsonOf(f)) + } + } +} + +// A battery power or current limit below half the order is never learned: +// a failing battery must keep warning. So a cold BMS that lets the battery +// give 2.28 of 5 kW (46 %) stays not following, night after night, until +// its driver reports that limit. +func TestLowShareLimitNeedsTheDriversReport(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + rng := rand.New(rand.NewSource(17)) + s := newSungrowTrace() + s.houseW = 800 + start := time.Now() + extra := `,"temp_c":-3` + s.battery = func() (float64, float64, float64, string) { + a := 12 + rng.NormFloat64()*0.2 + return -a * 190, a, 190, extra + } + var third tally + for d := range 3 { + battery := s.battery + third = tally{} + s.run(3*time.Hour, -5000, func(f ControlFeedback) { + if f.Status != "waiting" { + third.add(f) + } + }) + s.idle(start.Add(time.Duration(d+1) * 24 * time.Hour)) + s.battery = battery + } + if got := third.share("not_following/power_below_target/warning"); got < 0.95 { + t.Fatalf("third night: %v", third.hits) + } + extra = `,"temp_c":-3,"available_discharge_W":2300` + var last ControlFeedback + s.run(90*time.Second, -5000, func(f ControlFeedback) { last = f }) + if last.Status != "limited" || last.Reason != "battery_limit" || last.LimitSource != "device" || last.LimitW == nil || *last.LimitW != 2300 { + t.Fatalf("reported limit: %s", jsonOf(last)) + } + }) +} diff --git a/go/internal/api/api_control_feedback.go b/go/internal/api/api_control_feedback.go index 16842e3b8..deadee66e 100644 --- a/go/internal/api/api_control_feedback.go +++ b/go/internal/api/api_control_feedback.go @@ -7,6 +7,7 @@ import ( "sort" "time" + "github.com/srcfl/ftw/go/internal/battery" "github.com/srcfl/ftw/go/internal/config" "github.com/srcfl/ftw/go/internal/control" "github.com/srcfl/ftw/go/internal/loadpoint" @@ -81,6 +82,21 @@ type ControlFeedback struct { // VehicleDeclined is Core's debounced record that the car refused its // offer. The reason carries the result. VehicleDeclined bool `json:"-"` + // A battery limit that explains a shortfall (api_control_capability.go): + // the limit in W and, under a grid limit, the battery's room, both + // positive in the order's direction; where it comes from ("device" or + // "learned"), what holds it ("grid_import", "grid_export", + // "battery_current", "battery_power" or "battery_reported"), how many + // runs showed it, since when, and the learned limit it replaced. + LimitW *float64 `json:"limit_w,omitempty"` + LimitRoomW *float64 `json:"limit_room_w,omitempty"` + LimitSource string `json:"limit_source,omitempty"` + LimitKind string `json:"limit_kind,omitempty"` + LimitSeen int `json:"limit_seen,omitempty"` + LimitSinceMs int64 `json:"limit_since_ms,omitempty"` + LimitEarlierW *float64 `json:"limit_earlier_w,omitempty"` + // shortfall is the sample the battery limit learner may take. + shortfall *battery.ShortfallSample } type feedbackReading struct { @@ -377,6 +393,9 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { if f.VerificationLost { f.Reason = "readings_lost" } + if kind == telemetry.DerBattery && commanded && cmd.Result == "accepted" && fresh { + s.explainBatteryShortfall(&f, rd.Data, meter, blocked, now) + } f.ReadingsFresh = fresh out = append(out, f) } @@ -433,6 +452,10 @@ func (s *Server) controlFeedback(now time.Time) []ControlFeedback { func setControlStatus(f *ControlFeedback) { status, severity := "waiting", "info" switch f.Reason { + case "battery_limit", "learned_limit": + status = "limited" + case "device_standby": + status, severity = "not_following", "warning" case "power_observed", "solar_below_ceiling", "idle", "plan", "manual_hold", "pv_surplus", "vehicle_complete", "vehicle_limit_completion", "vehicle_not_requesting": status = "following" diff --git a/go/internal/api/api_control_journal.go b/go/internal/api/api_control_journal.go index 6bab6e867..12a970fd6 100644 --- a/go/internal/api/api_control_journal.go +++ b/go/internal/api/api_control_journal.go @@ -19,6 +19,7 @@ import ( func (s *Server) JournalVerdicts(now time.Time) []journal.Verdict { var out []journal.Verdict rows := s.controlFeedback(now) + s.learnBatteryLimits(rows, now) plan := s.planNow(now, rows) markOnPlan(rows, plan) for _, f := range rows { diff --git a/go/internal/battery/model.go b/go/internal/battery/model.go index 3c22adcf9..ee8fe8c2f 100644 --- a/go/internal/battery/model.go +++ b/go/internal/battery/model.go @@ -67,6 +67,10 @@ type Model struct { LastUpdatedMs int64 `json:"last_updated_ts_ms"` ForgettingFactor float64 `json:"forgetting_factor"` + + // Plateaus are the limits this battery has shown when short of an order. + // They explain Core's verdict only; nothing in control reads them. + Plateaus *Plateaus `json:"plateaus,omitempty"` } // SoCPoint is one (SoC, value) pair in a saturation curve. diff --git a/go/internal/battery/plateau.go b/go/internal/battery/plateau.go new file mode 100644 index 000000000..4226ca901 --- /dev/null +++ b/go/internal/battery/plateau.go @@ -0,0 +1,475 @@ +package battery + +import ( + "math" + "sort" + "time" +) + +// Plateaus learns what a battery can do when it gives less than its order. +// While a battery falls short in the right direction, something is usually +// flat: grid import (the inverter's import cap), grid export (an export +// limit), the battery's DC current (a BMS or converter limit) or its power. +// A flat run that comes back on more than one day is what this device does, +// so a later shortfall that sits on it is a limit, not lost control. +// +// It only explains Core's verdict. Dispatch, fuse protection, clamps and +// commands never read it. The caller holds the model lock. +type Plateaus struct { + Series []PlateauSeries `json:"series"` + // open is the shortfall run under way. It is not stored: a restart + // loses at most one run. + open *plateauRun +} + +// What a shortfall can sit on. +const ( + LimitGridImport = "grid_import" + LimitGridExport = "grid_export" + LimitBatteryCurrent = "battery_current" + LimitBatteryPower = "battery_power" +) + +const ( + // PlateauMinShortfallW is the least battery power a sample needs. Below + // it a reading says more about noise and standby draw than about a limit. + PlateauMinShortfallW = 300.0 + // A run needs a minute of 5 s journal samples. A break up to + // plateauMaxGap does not end it; a run is cut at plateauMaxRun so that + // memory stays bounded and a long night still counts as more than one. + plateauMinSamples = 12 + plateauMaxGap = 30 * time.Second + plateauMaxRun = 2 * time.Hour + // Each series keeps its last plateauKeepMax runs of the last + // plateauKeepFor. + plateauKeepFor = 60 * 24 * time.Hour + plateauKeepMax = 50 + // A plateau is trusted after plateauTrustRuns runs on two days. Runs that + // start plateauDayApart or more apart are on different days, so one night + // across midnight counts once. + plateauTrustRuns = 3 + plateauDayApart = 12 * time.Hour + // Temperatures key plateaus in bands this wide, so a cold-weather limit + // never explains a warm-weather shortfall. + plateauTempBandC = 10 +) + +// Spread and match limits. A run is flat when the middle half of its samples +// lies within plateauFlatShare of their median, or within the floor: the +// inverter's grid regulation and a BMS current limit hold well inside that +// (a home Sungrow held its grid import at 4,276-4,344 W, under 2 %). Runs +// agree, and a sample sits on a plateau, within plateauNearShare: one +// sample's noise is wider than a run's middle half (its DC current read +// 21.6-23.1 A on a 22.4 A limit, under 4 %). The floors cover meter and +// register resolution at small values. +const ( + plateauFlatShare = 0.03 + plateauNearShare = 0.05 + plateauFloorW = 100.0 + plateauFloorA = 0.5 +) + +// plateauMinShare is the least share of the order a battery power or +// current plateau may stand for. A limit inside the battery still gives +// most of an order: the home Sungrow's discharge cap gave 4.3 of 5 kW +// (86 %). A battery that gives a steady 0.4-1 kW of 5 kW (8-20 %) is +// failing, and must keep warning however often it does so. A grid limit has +// no such floor: under the import cap the battery's share falls to 30 % +// when the house takes 3 kW. +const plateauMinShare = 0.5 + +// plateauMeterEvery is the slowest site meter a grid run accepts: one that +// measures at least every 20 s on average. That is also about the slowest +// whose readings stay inside the 15 s the verdict allows a grid reading, +// sampled every 5 s. +const plateauMeterEvery = 20 * time.Second + +// ShortfallSample is one settled journal sample of a battery short of its +// order in the right direction. Amounts are positive: watts or amps in the +// order's direction. GridW is grid import while charging or export while +// discharging, from a site meter Core trusts; nil when it has none. GridAt +// is when the meter measured it, by its own clock where it reports one. +type ShortfallSample struct { + At time.Time + Charge bool + OrderW float64 + BatteryW float64 + BatteryA *float64 + GridW *float64 + GridAt time.Time + TempC *float64 +} + +// share reports whether the battery gives enough of its order for a battery +// power or current plateau to stand for it (see plateauMinShare). +func (s ShortfallSample) share() bool { + return s.OrderW > 0 && s.BatteryW >= plateauMinShare*s.OrderW +} + +// PlateauRun is one flat run: the median of the flat amount and when it held. +type PlateauRun struct { + StartMs int64 `json:"start_ms"` + EndMs int64 `json:"end_ms"` + Median float64 `json:"median"` + Samples int `json:"samples"` +} + +// PlateauSeries keeps the recent flat runs of one amount, for one direction +// and temperature band. +type PlateauSeries struct { + Direction string `json:"direction"` + Kind string `json:"kind"` + // TempBandC is the lower edge of a 10 °C band; nil when the battery + // reports no temperature. + TempBandC *int `json:"temp_band_c,omitempty"` + Runs []PlateauRun `json:"runs"` +} + +// Plateau is a limit the battery has shown on more than one day. Value is in +// W, or in A for battery_current. Earlier is the plateau it replaced. +type Plateau struct { + Direction string `json:"direction"` + Kind string `json:"kind"` + TempBandC *int `json:"temp_band_c,omitempty"` + Value float64 `json:"value"` + Unit string `json:"unit"` + Seen int `json:"seen"` + SinceMs int64 `json:"since_ms"` + LastMs int64 `json:"last_ms"` + Earlier *Plateau `json:"earlier,omitempty"` +} + +type plateauRun struct { + charge bool + band *int + start, last time.Time + n int + values map[string][]float64 + // batteryW is every sample's battery power and gridAt each grid + // value's measurement time: what a grid run must show to be a cap. + batteryW []float64 + gridAt []time.Time +} + +// Tick feeds one journal sample; s is nil when the battery is not short of +// its order now. A run ends after a gap over plateauMaxGap, on a change of +// direction or temperature band, or at plateauMaxRun. +func (p *Plateaus) Tick(now time.Time, s *ShortfallSample) { + if p == nil { + return + } + if o := p.open; o != nil { + ended := now.Sub(o.last) > plateauMaxGap + if s != nil { + ended = s.At.Sub(o.last) > plateauMaxGap || s.Charge != o.charge || + !sameBand(tempBand(s.TempC), o.band) || s.At.Sub(o.start) >= plateauMaxRun + } + if ended { + p.close() + } + } + p.prune(now) + if s == nil || !finite(s.BatteryW) || s.BatteryW < PlateauMinShortfallW { + return + } + if p.open == nil { + p.open = &plateauRun{charge: s.Charge, band: tempBand(s.TempC), start: s.At, values: map[string][]float64{}} + } + o := p.open + o.n++ + o.last = s.At + add := func(kind string, v *float64) bool { + if v != nil && finite(*v) && *v > 0 { + o.values[kind] = append(o.values[kind], *v) + return true + } + return false + } + o.batteryW = append(o.batteryW, s.BatteryW) + if add(gridKind(s.Charge), s.GridW) { + o.gridAt = append(o.gridAt, s.GridAt) + } + if s.share() { + add(LimitBatteryCurrent, s.BatteryA) + add(LimitBatteryPower, &s.BatteryW) + } +} + +func gridKind(charge bool) string { + if charge { + return LimitGridImport + } + return LimitGridExport +} + +// liveCap reports whether a flat grid run shows a cap the inverter holds, +// not a meter that stopped. The battery must move while the grid holds: a +// steady house with a steady battery says nothing about the inverter, and a +// failing battery would look the same. The meter must also be live: its own +// measurement time moves on at least once per plateauMeterEvery on average +// over the run, and no single value makes up half of the samples. A driver +// that resends a cached value repeats it exactly; a real cap jitters (the +// home Sungrow's 4.32 kW cap had a 41 W spread). +func (o *plateauRun) liveCap(grid []float64) bool { + median, iqr := middle(o.batteryW) + if iqr <= math.Max(plateauFlatShare*median, plateauFloorW) { + return false + } + measured := 1 + for i := 1; i < len(o.gridAt); i++ { + if o.gridAt[i].After(o.gridAt[i-1]) { + measured++ + } + } + if time.Duration(measured)*plateauMeterEvery < o.last.Sub(o.start) { + return false + } + same := map[float64]int{} + for _, v := range grid { + same[v]++ + if 2*same[v] >= len(grid) { + return false + } + } + return true +} + +// close keeps each amount that stayed flat over the open run. An amount +// needs most of the run's samples, so a meter that came and went proves +// nothing. +func (p *Plateaus) close() { + o := p.open + p.open = nil + if o == nil || o.n < plateauMinSamples { + return + } + for _, kind := range []string{LimitGridImport, LimitGridExport, LimitBatteryCurrent, LimitBatteryPower} { + v := o.values[kind] + if len(v) < plateauMinSamples || float64(len(v)) < 0.8*float64(o.n) { + continue + } + median, iqr := middle(v) + if iqr > math.Max(plateauFlatShare*median, floor(kind)) { + continue + } + if (kind == LimitGridImport || kind == LimitGridExport) && !o.liveCap(v) { + continue + } + run := PlateauRun{StartMs: o.start.UnixMilli(), EndMs: o.last.UnixMilli(), Median: median, Samples: len(v)} + series := p.series(directionOf(o.charge), kind, o.band) + series.Runs = append(series.Runs, run) + } +} + +// prune drops runs older than plateauKeepFor, keeps the last plateauKeepMax +// of each series and drops empty series. +func (p *Plateaus) prune(now time.Time) { + cutoff := now.Add(-plateauKeepFor).UnixMilli() + kept := p.Series[:0] + for _, s := range p.Series { + runs := s.Runs[:0] + for _, r := range s.Runs { + if r.EndMs >= cutoff { + runs = append(runs, r) + } + } + if len(runs) > plateauKeepMax { + runs = runs[len(runs)-plateauKeepMax:] + } + if len(runs) > 0 { + s.Runs = runs + kept = append(kept, s) + } + } + p.Series = kept +} + +func (p *Plateaus) series(direction, kind string, band *int) *PlateauSeries { + for i := range p.Series { + s := &p.Series[i] + if s.Direction == direction && s.Kind == kind && sameBand(s.TempBandC, band) { + return s + } + } + p.Series = append(p.Series, PlateauSeries{Direction: direction, Kind: kind, TempBandC: band}) + return &p.Series[len(p.Series)-1] +} + +// Explain returns the trusted plateau a shortfall sits on, if any: grid first, +// since it is the outer limit, then DC current, then battery power. A sample +// well below its plateau sits on none and keeps its warning, and a battery +// power or current plateau never explains a battery that gives less than +// plateauMinShare of its order. +func (p *Plateaus) Explain(s ShortfallSample) (Plateau, bool) { + if p == nil || !finite(s.BatteryW) || s.BatteryW < PlateauMinShortfallW { + return Plateau{}, false + } + band := tempBand(s.TempC) + for _, c := range []struct { + kind string + value *float64 + }{{gridKind(s.Charge), s.GridW}, {LimitBatteryCurrent, s.BatteryA}, {LimitBatteryPower, &s.BatteryW}} { + if c.value == nil || !finite(*c.value) || (c.kind != gridKind(s.Charge) && !s.share()) { + continue + } + for i := range p.Series { + series := &p.Series[i] + if series.Direction != directionOf(s.Charge) || series.Kind != c.kind || !sameBand(series.TempBandC, band) { + continue + } + if known, ok := series.plateau(); ok && near(*c.value, known.Value, c.kind) { + return known, true + } + } + } + return Plateau{}, false +} + +// Known lists the trusted plateau of every series. +func (p *Plateaus) Known() []Plateau { + out := []Plateau{} + if p == nil { + return out + } + for i := range p.Series { + if known, ok := p.Series[i].plateau(); ok { + out = append(out, known) + } + } + return out +} + +// plateau is the series' trusted plateau: of the groups of runs that agree, +// the newest one seen at least plateauTrustRuns times on two days. A lower +// level becomes normal only once it repeats like that; until then the old +// one stands and a run at the new level does not match it. +func (s *PlateauSeries) plateau() (Plateau, bool) { + runs := append([]PlateauRun(nil), s.Runs...) + sort.Slice(runs, func(i, j int) bool { return runs[i].StartMs < runs[j].StartMs }) + var groups [][]PlateauRun + for _, r := range runs { + best := -1 + for i, g := range groups { + if near(r.Median, groupValue(g), s.Kind) && (best < 0 || g[len(g)-1].StartMs > groups[best][len(groups[best])-1].StartMs) { + best = i + } + } + if best < 0 { + groups = append(groups, []PlateauRun{r}) + } else { + groups[best] = append(groups[best], r) + } + } + var trusted []Plateau + for _, g := range groups { + if len(g) < plateauTrustRuns || days(g) < 2 { + continue + } + trusted = append(trusted, Plateau{Direction: s.Direction, Kind: s.Kind, TempBandC: s.TempBandC, Value: groupValue(g), + Unit: unit(s.Kind), Seen: len(g), SinceMs: g[0].StartMs, LastMs: g[len(g)-1].EndMs}) + } + if len(trusted) == 0 { + return Plateau{}, false + } + sort.Slice(trusted, func(i, j int) bool { return trusted[i].LastMs > trusted[j].LastMs }) + current := trusted[0] + if len(trusted) > 1 { + earlier := trusted[1] + current.Earlier = &earlier + } + return current, true +} + +func groupValue(g []PlateauRun) float64 { + v := make([]float64, len(g)) + for i, r := range g { + v[i] = r.Median + } + m, _ := middle(v) + return m +} + +// days counts the days a group of runs (sorted by start) was seen on: a run +// starting plateauDayApart after the last counted day starts a new one. +func days(g []PlateauRun) int { + n, anchor := 0, int64(0) + for _, r := range g { + if n == 0 || r.StartMs-anchor >= plateauDayApart.Milliseconds() { + n, anchor = n+1, r.StartMs + } + } + return n +} + +// middle returns the median and the interquartile range. +func middle(v []float64) (median, iqr float64) { + s := append([]float64(nil), v...) + sort.Float64s(s) + q := func(f float64) float64 { + x := f * float64(len(s)-1) + lo := int(math.Floor(x)) + hi := min(lo+1, len(s)-1) + return s[lo] + (x-float64(lo))*(s[hi]-s[lo]) + } + return q(0.5), q(0.75) - q(0.25) +} + +func near(v, ref float64, kind string) bool { + return math.Abs(v-ref) <= math.Max(plateauNearShare*math.Abs(ref), floor(kind)) +} + +func floor(kind string) float64 { + if kind == LimitBatteryCurrent { + return plateauFloorA + } + return plateauFloorW +} + +func unit(kind string) string { + if kind == LimitBatteryCurrent { + return "A" + } + return "W" +} + +func directionOf(charge bool) string { + if charge { + return "charge" + } + return "discharge" +} + +func tempBand(c *float64) *int { + if c == nil || !finite(*c) { + return nil + } + b := int(math.Floor(*c/plateauTempBandC)) * plateauTempBandC + return &b +} + +func sameBand(a, b *int) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} + +// PlateauView is what GET /api/battery_models shows: the trusted plateaus, +// each with the one it replaced, and the runs behind them. +type PlateauView struct { + Known []Plateau `json:"known"` + Series []PlateauSeries `json:"series"` +} + +// View copies the plateaus for the API. +func (p *Plateaus) View() PlateauView { + v := PlateauView{Known: p.Known(), Series: []PlateauSeries{}} + if p == nil { + return v + } + for _, s := range p.Series { + s.Runs = append([]PlateauRun(nil), s.Runs...) + v.Series = append(v.Series, s) + } + return v +} diff --git a/go/internal/battery/plateau_test.go b/go/internal/battery/plateau_test.go new file mode 100644 index 000000000..e6b80a1b3 --- /dev/null +++ b/go/internal/battery/plateau_test.go @@ -0,0 +1,359 @@ +package battery + +import ( + "encoding/json" + "math" + "testing" + "time" +) + +var day0 = time.Date(2026, 11, 8, 1, 0, 0, 0, time.UTC) + +type shortfall struct { + charge bool + orderW float64 // 5 kW when zero + grid, a, tempC *float64 + batteryW func(i int) float64 +} + +func f(v float64) *float64 { return &v } + +// feed ticks n samples five seconds apart from start, then idles long enough +// to end the run. It returns the time after the idle. +func feed(p *Plateaus, start time.Time, n int, s shortfall) time.Time { + at := start + for i := range n { + var grid, a *float64 + if s.grid != nil { + grid = f(*s.grid + 20*math.Sin(float64(i))) + } + if s.a != nil { + a = f(*s.a + 0.2*math.Sin(float64(i))) + } + order := s.orderW + if order == 0 { + order = 5000 + } + p.Tick(at, &ShortfallSample{At: at, Charge: s.charge, OrderW: order, BatteryW: s.batteryW(i), BatteryA: a, GridW: grid, GridAt: at, TempC: s.tempC}) + at = at.Add(5 * time.Second) + } + at = at.Add(time.Minute) + p.Tick(at, nil) + return at +} + +// A night of grid charging: the grid sits at 4.3 kW while the house load +// moves the battery's share between 1.3 and 4 kW. +func gridNight(i int) float64 { return 4300 - 300 - 2700*(0.5+0.5*math.Sin(float64(i)/7)) } + +func TestPlateauRunNeedsAFlatMinute(t *testing.T) { + p := &Plateaus{} + feed(p, day0, 11, shortfall{charge: true, grid: f(4300), batteryW: gridNight}) + if len(p.Series) != 0 { + t.Fatalf("under a minute made a run: %+v", p.Series) + } + feed(p, day0.Add(time.Hour), 60, shortfall{charge: true, grid: f(4300), batteryW: gridNight}) + if len(p.Series) != 1 || p.Series[0].Kind != LimitGridImport || p.Series[0].Direction != "charge" { + t.Fatalf("want one flat grid import series, got %+v", p.Series) + } + run := p.Series[0].Runs[0] + if math.Abs(run.Median-4300) > 25 || run.Samples != 60 || run.StartMs != day0.Add(time.Hour).UnixMilli() { + t.Fatalf("run %+v", run) + } +} + +func TestPlateauRunEndsOnGapAndDirection(t *testing.T) { + p := &Plateaus{} + at := day0 + flat := func(int) float64 { return 3000 } + for range 20 { + p.Tick(at, &ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: 3000}) + at = at.Add(5 * time.Second) + } + // A break under 30 s keeps the run going. + p.Tick(at, nil) + at = at.Add(20 * time.Second) + for range 20 { + p.Tick(at, &ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: 3000}) + at = at.Add(5 * time.Second) + } + // A change of direction ends it. + feed(p, at, 20, shortfall{charge: false, batteryW: flat}) + if len(p.Series) != 2 { + t.Fatalf("want a charge and a discharge series, got %+v", p.Series) + } + for _, s := range p.Series { + if len(s.Runs) != 1 { + t.Fatalf("%s: runs %+v", s.Direction, s.Runs) + } + if s.Direction == "charge" && s.Runs[0].Samples != 40 { + t.Fatalf("short break split the run: %+v", s.Runs) + } + } + // A gap over 30 s ends a run. + p = &Plateaus{} + at = day0 + for range 20 { + p.Tick(at, &ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: 3000}) + at = at.Add(5 * time.Second) + } + at = at.Add(40 * time.Second) + feed(p, at, 20, shortfall{charge: true, batteryW: flat}) + if len(p.Series) != 1 || len(p.Series[0].Runs) != 2 { + t.Fatalf("want two runs after a gap, got %+v", p.Series) + } +} + +func TestOnlyFlatAmountsMakeRuns(t *testing.T) { + p := &Plateaus{} + // Discharge on a current limit: 22.4 A while the pack voltage drifts + // from 187 to 192 V, so the power drifts with it. + feed(p, day0, 120, shortfall{charge: false, a: f(22.4), batteryW: func(i int) float64 { return 22.4 * (187 + 5*float64(i)/120) }}) + // Grid charge with a varying house: battery power is not flat. + feed(p, day0.Add(2*time.Hour), 120, shortfall{charge: true, grid: f(4300), a: nil, batteryW: gridNight}) + kinds := map[string]bool{} + for _, s := range p.Series { + kinds[s.Direction+"/"+s.Kind] = true + } + if !kinds["discharge/battery_current"] || !kinds["charge/grid_import"] || kinds["charge/battery_power"] { + t.Fatalf("flat amounts %v", kinds) + } +} + +func TestPlateauTrustNeedsThreeRunsOnTwoDays(t *testing.T) { + p := &Plateaus{} + night := shortfall{charge: true, grid: f(4316), batteryW: gridNight} + at := day0 + for range 3 { + at = feed(p, at, 60, night) + } + sample := ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: 2500, GridW: f(4320)} + if _, ok := p.Explain(sample); ok { + t.Fatal("one night of runs was trusted") + } + feed(p, day0.Add(24*time.Hour), 60, night) + known, ok := p.Explain(sample) + if !ok || known.Kind != LimitGridImport || known.Seen != 4 || known.SinceMs != day0.UnixMilli() || math.Abs(known.Value-4316) > 25 || known.Unit != "W" { + t.Fatalf("trusted plateau %+v ok=%v", known, ok) + } + // A battery well below its plateau is not explained. + if _, ok := p.Explain(ShortfallSample{Charge: true, OrderW: 5000, BatteryW: 1000, GridW: f(1500)}); ok { + t.Fatal("a drop to 1.5 kW grid import sat on the 4.3 kW plateau") + } + // Nor is the other direction. + if _, ok := p.Explain(ShortfallSample{Charge: false, OrderW: 5000, BatteryW: 2500, GridW: f(4320)}); ok { + t.Fatal("a charge plateau explained a discharge") + } + if got := p.Known(); len(got) != 1 { + t.Fatalf("known %+v", got) + } +} + +func TestLowerPlateauBecomesNormalAfterTwoDays(t *testing.T) { + p := &Plateaus{} + high := shortfall{charge: true, grid: f(4300), batteryW: gridNight} + low := shortfall{charge: true, grid: f(3100), batteryW: func(i int) float64 { return gridNight(i) * 0.6 }} + for d := range 3 { + feed(p, day0.Add(time.Duration(d)*24*time.Hour), 60, high) + } + lowSample := ShortfallSample{Charge: true, OrderW: 5000, BatteryW: 2000, GridW: f(3110)} + at := day0.Add(14 * 24 * time.Hour) + for range 3 { + at = feed(p, at, 60, low) + } + if known, ok := p.Explain(lowSample); ok { + t.Fatalf("a new lower level was normal after one day: %+v", known) + } + feed(p, day0.Add(15*24*time.Hour), 60, low) + known, ok := p.Explain(lowSample) + if !ok || math.Abs(known.Value-3100) > 25 || known.SinceMs != day0.Add(14*24*time.Hour).UnixMilli() { + t.Fatalf("lower plateau %+v ok=%v", known, ok) + } + if known.Earlier == nil || math.Abs(known.Earlier.Value-4300) > 25 || known.Earlier.Seen != 3 { + t.Fatalf("lost the earlier plateau: %+v", known.Earlier) + } + if _, ok := p.Explain(ShortfallSample{Charge: true, OrderW: 5000, BatteryW: 3500, GridW: f(4300)}); ok { + t.Fatal("the replaced plateau still explains") + } +} + +func TestPlateauTemperatureBands(t *testing.T) { + p := &Plateaus{} + cold := shortfall{charge: false, orderW: 4000, a: f(12), tempC: f(-3), batteryW: func(int) float64 { return 12 * 190 }} + for d := range 3 { + feed(p, day0.Add(time.Duration(d)*24*time.Hour), 60, cold) + } + inCold := ShortfallSample{Charge: false, OrderW: 4000, BatteryW: 2280, BatteryA: f(12.1), TempC: f(-4.5)} + if known, ok := p.Explain(inCold); !ok || known.Kind != LimitBatteryCurrent || known.TempBandC == nil || *known.TempBandC != -10 { + t.Fatalf("cold plateau %+v ok=%v", known, ok) + } + for _, temp := range []*float64{f(15), nil} { + warm := inCold + warm.TempC = temp + if _, ok := p.Explain(warm); ok { + t.Fatalf("a -3 °C plateau explained a shortfall at %v", temp) + } + } +} + +func TestPlateausStayBounded(t *testing.T) { + p := &Plateaus{} + at := day0 + for range 70 { + at = feed(p, at, 12, shortfall{charge: true, orderW: 3000, batteryW: func(int) float64 { return 2000 }}) + } + if n := len(p.Series[0].Runs); n != plateauKeepMax { + t.Fatalf("kept %d runs", n) + } + p.Tick(at.Add(61*24*time.Hour), nil) + if len(p.Series) != 0 { + t.Fatalf("runs older than 60 days kept: %+v", p.Series) + } + // A run is cut at two hours. + p = &Plateaus{} + feed(p, day0, 2*60*12+12, shortfall{charge: true, orderW: 3000, batteryW: func(int) float64 { return 2000 }}) + if n := len(p.Series[0].Runs); n != 2 { + t.Fatalf("a long run made %d runs", n) + } +} + +func TestPlateausSurviveTheModelStore(t *testing.T) { + m := New("battery") + m.Plateaus = &Plateaus{} + for d := range 3 { + feed(m.Plateaus, day0.Add(time.Duration(d)*24*time.Hour), 60, shortfall{charge: true, grid: f(4300), batteryW: gridNight}) + } + // An open run is not stored. + m.Plateaus.Tick(day0.Add(4*24*time.Hour), &ShortfallSample{At: day0.Add(4 * 24 * time.Hour), Charge: true, OrderW: 3000, BatteryW: 2000}) + blob, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + var back Model + if err := json.Unmarshal(blob, &back); err != nil { + t.Fatal(err) + } + before, after := m.Plateaus.Known(), back.Plateaus.Known() + if len(before) != 1 || len(after) != 1 || before[0].Value != after[0].Value || before[0].Seen != after[0].Seen || back.Plateaus.open != nil { + t.Fatalf("round trip: %+v -> %+v", before, after) + } + // A model stored before plateaus existed still loads. + var old Model + if err := json.Unmarshal([]byte(`{"name":"battery","a":0.7,"b":0.3}`), &old); err != nil || old.Plateaus != nil || len(old.Plateaus.Known()) != 0 { + t.Fatalf("old model: %+v %v", old, err) + } + old.Plateaus.Tick(day0, &ShortfallSample{At: day0, Charge: true, OrderW: 3000, BatteryW: 2000}) +} + +// A battery that breaks and gives a steady 0.4-1 kW against a 5 kW order, +// night after night, is failing, not at its usual limit. +func TestFailingBatteryIsNeverNormal(t *testing.T) { + for _, steadyHouse := range []bool{true, false} { + for _, w := range []float64{400, 700, 1000} { + p := &Plateaus{} + at := day0 + for d := range 4 { + at = day0.Add(time.Duration(d) * 24 * time.Hour) + for i := range 3 * 720 { + house := 600.0 + if !steadyHouse { + house = 300 + 2700*(0.5+0.5*math.Sin(float64(i)/40)) + } + battery := w + 10*math.Sin(float64(i)) + p.Tick(at, &ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: battery, BatteryA: f(battery / 190), + GridW: f(house + battery + 5*math.Cos(float64(i))), GridAt: at}) + at = at.Add(5 * time.Second) + } + p.Tick(at.Add(time.Minute), nil) + } + if known := p.Known(); len(known) != 0 { + t.Fatalf("%v W, steady house %v: a failing battery became normal: %+v", w, steadyHouse, known) + } + } + } + // A battery limit that gave most of one order does not explain a battery + // that gives too little of a larger one. + p := &Plateaus{} + for d := range 3 { + feed(p, day0.Add(time.Duration(d)*24*time.Hour), 60, shortfall{charge: false, orderW: 4000, a: f(12.6), batteryW: func(int) float64 { return 2400 }}) + } + if _, ok := p.Explain(ShortfallSample{Charge: false, OrderW: 4000, BatteryW: 2400, BatteryA: f(12.6)}); !ok { + t.Fatal("set-up plateau not trusted") + } + if known, ok := p.Explain(ShortfallSample{Charge: false, OrderW: 6000, BatteryW: 2400, BatteryA: f(12.6)}); ok { + t.Fatalf("40 %% of the order sat on %+v", known) + } +} + +// A driver that resends a cached meter value keeps its reading fresh, and a +// frozen grid with a moving battery looks just like an import cap. Only a +// meter shown to be live makes a grid plateau. +func TestFrozenMeterMakesNoGridPlateau(t *testing.T) { + for _, tc := range []struct { + name string + grid func(i int) float64 + gridAt func(at time.Time) time.Time + steady bool + want bool + }{ + {"live meter under a cap", func(i int) float64 { return 4316 + 40*math.Sin(float64(i)*1.7) }, func(at time.Time) time.Time { return at }, false, true}, + {"cached value resent", func(int) float64 { return 4316 }, func(at time.Time) time.Time { return at }, false, false}, + // A slower meter than the journal: a new measurement every 10 s or + // 15 s, its value held in between. Still a live cap. + {"meter every 10 s", func(i int) float64 { return 4316 + 40*math.Sin(float64(i/2)*1.7) }, slowMeter(10 * time.Second), false, true}, + {"meter every 15 s", func(i int) float64 { return 4316 + 40*math.Sin(float64(i/3)*1.7) }, slowMeter(15 * time.Second), false, true}, + {"meter every 20 s", func(i int) float64 { return 4316 + 40*math.Sin(float64(i/4)*1.7) }, slowMeter(20 * time.Second), false, true}, + {"meter every 60 s", func(i int) float64 { return 4316 + 40*math.Sin(float64(i/12)*1.7) }, slowMeter(time.Minute), false, false}, + {"meter's own time stands still", func(i int) float64 { return 4316 + 40*math.Sin(float64(i)*1.7) }, func(time.Time) time.Time { return day0 }, false, false}, + {"steady battery under a steady grid", func(i int) float64 { return 2600 + 40*math.Sin(float64(i)*1.7) }, func(at time.Time) time.Time { return at }, true, false}, + } { + t.Run(tc.name, func(t *testing.T) { + p := &Plateaus{} + at := day0 + for i := range 240 { + battery := 4316 - 300 - 2700*(0.5+0.5*math.Sin(float64(i)/7)) + if tc.steady { + battery = 2000 + } + p.Tick(at, &ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: battery, GridW: f(tc.grid(i)), GridAt: tc.gridAt(at)}) + at = at.Add(5 * time.Second) + } + p.Tick(at.Add(time.Minute), nil) + got := false + for _, s := range p.Series { + got = got || s.Kind == LimitGridImport + } + if got != tc.want { + t.Fatalf("grid run kept %v, want %v: %+v", got, tc.want, p.Series) + } + }) + } +} + +// slowMeter is a meter that measures once per every, from day0. +func slowMeter(every time.Duration) func(time.Time) time.Time { + return func(at time.Time) time.Time { return day0.Add(at.Sub(day0).Truncate(every)) } +} + +// A slow meter still makes a trusted cap over three nights. +func TestSlowMeterCapIsTrusted(t *testing.T) { + for _, every := range []time.Duration{10 * time.Second, 15 * time.Second} { + p := &Plateaus{} + for d := range 3 { + at := day0.Add(time.Duration(d) * 24 * time.Hour) + start := at + for i := range 720 { + meterAt := start.Add(at.Sub(start).Truncate(every)) + battery := 4316 - 300 - 2700*(0.5+0.5*math.Sin(float64(i)/7)) + grid := 4316 + 40*math.Sin(float64(meterAt.Unix())) + p.Tick(at, &ShortfallSample{At: at, Charge: true, OrderW: 5000, BatteryW: battery, GridW: f(grid), GridAt: meterAt}) + at = at.Add(5 * time.Second) + } + p.Tick(at.Add(time.Minute), nil) + } + known, ok := p.Explain(ShortfallSample{Charge: true, OrderW: 5000, BatteryW: 2500, GridW: f(4320)}) + if !ok || known.Kind != LimitGridImport { + t.Fatalf("a meter every %v: %+v ok=%v, series %+v", every, known, ok, p.Series) + } + } +} diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index 6bc61d1f7..af0d36c03 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -610,6 +610,25 @@ func (s *Store) Get(driver string, t DerType) *DerReading { return nil } +// LiveMeterPower returns a driver's measured meter power, with when it was +// measured, only while that driver is live and its device reports no fault. +// A cached reading survives its driver going stale, offline or faulted, so +// callers that judge the site from the meter ask here instead of reading the +// cache directly. +func (s *Store) LiveMeterPower(driver string) (ControlObservation, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + h, ok := s.health[driver] + if !ok || !h.TelemetryLive() || h.DeviceFault { + return ControlObservation{}, false + } + r := s.readings[key(driver, DerMeter)] + if r == nil { + return ControlObservation{}, false + } + return ControlPowerObservation(r.RawW, r.Data, r.UpdatedAt) +} + // ReadingsByType returns all readings of a given type (e.g. all batteries). func (s *Store) ReadingsByType(t DerType) []*DerReading { s.mu.RLock() diff --git a/web/control-feedback-battery-limits.test.mjs b/web/control-feedback-battery-limits.test.mjs new file mode 100644 index 000000000..c72488397 --- /dev/null +++ b/web/control-feedback-battery-limits.test.mjs @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {controlStatus} from './control-feedback.js'; + +// Core's verdict when a battery gives less than ordered because that is what +// it can do now (go/internal/api/api_control_capability.go). +const row = extra => ({driver: 'sungrow', kind: 'battery', mode: 'planner_arbitrage', status: 'limited', severity: 'info', + evidence: 'measured', readings_fresh: true, sent_w: 5000, requested_w: 5000, actual_w: 3600, ...extra}); +const nov8 = new Date(2026, 10, 8, 2).getTime(); + +test('a learned grid import limit says what holds the battery and since when', () => { + const shown = controlStatus(row({reason: 'learned_limit', limit_source: 'learned', limit_kind: 'grid_import', + limit_w: 4316, limit_room_w: 3610, limit_seen: 14, limit_since_ms: nov8})); + assert.equal(shown.title, 'At its usual limit'); + assert.equal(shown.text, 'The inverter takes at most 4.3 kW from the grid, which leaves 3.6 kW for the battery. FTW has seen this 14 times since 8 Nov.'); + assert.equal(shown.next, ''); + assert.equal(shown.tone, 'neutral'); +}); + +test('a learned limit that replaced another names both', () => { + const shown = controlStatus(row({reason: 'learned_limit', limit_kind: 'grid_import', limit_w: 3100, + limit_seen: 3, limit_since_ms: new Date(2026, 10, 22, 2).getTime(), limit_earlier_w: 4316})); + assert.equal(shown.text, 'The inverter takes at most 3.1 kW from the grid. FTW has seen this 3 times since 22 Nov. Earlier it was 4.3 kW.'); +}); + +test('a learned current limit gives amps and the watts they make now', () => { + const discharge = {sent_w: -5000, requested_w: -5000, actual_w: -4190, reason: 'learned_limit', limit_kind: 'battery_current', + limit_a: 22.4, limit_w: 4189, limit_seen: 5, limit_since_ms: nov8}; + assert.equal(controlStatus(row(discharge)).text, 'The battery gives at most 22 A (4.2 kW now). FTW has seen this 5 times since 8 Nov.'); + assert.equal(controlStatus(row({...discharge, limit_w: undefined})).text, 'The battery gives at most 22 A. FTW has seen this 5 times since 8 Nov.'); + assert.equal(controlStatus(row({reason: 'learned_limit', limit_kind: 'battery_power', limit_w: 4200})).text, 'The battery takes at most 4.2 kW.'); + assert.equal(controlStatus(row({reason: 'learned_limit', limit_kind: 'grid_export', limit_w: 3000, sent_w: -5000})).text, + 'The inverter sends at most 3.0 kW to the grid.'); +}); + +test('a limit the battery reports explains itself', () => { + const shown = controlStatus(row({reason: 'battery_limit', limit_source: 'device', limit_kind: 'battery_reported', + limit_w: 3200, sent_w: -5000, requested_w: -5000, actual_w: -3150})); + assert.equal(shown.title, 'Limited by the battery'); + assert.equal(shown.text, 'The battery reports that it can give at most 3.2 kW now. FTW asked for 5.0 kW discharge.'); + assert.equal(shown.tone, 'neutral'); + assert.equal(controlStatus(row({reason: 'battery_limit', limit_w: 0, actual_w: 0})).text, + 'The battery reports that it cannot take power now. FTW asked for 5.0 kW charge.'); +}); + +test('a battery on standby still asks for a look', () => { + const shown = controlStatus(row({status: 'not_following', severity: 'warning', reason: 'device_standby', sent_w: -5000, actual_w: 0})); + assert.equal(shown.title, 'On standby'); + assert.equal(shown.text, 'Asked for 5.0 kW discharge, but the battery reports that it is on standby or starting up.'); + assert.equal(shown.next, 'It usually starts again by itself. If it stays on standby, check the battery’s app or display.'); + assert.equal(shown.tone, 'warning'); +}); + +test('limit words never show codes or invent numbers', () => { + assert.equal(controlStatus(row({reason: 'learned_limit', limit_kind: 'grid_import'})).text, 'The battery is at a limit it has shown before.'); + assert.equal(controlStatus(row({reason: 'battery_limit'})).text, 'The battery reports a limit below the 5.0 kW charge FTW asked for.'); + for (const extra of [{reason: 'learned_limit'}, {reason: 'learned_limit', limit_kind: 'grid_import'}, {reason: 'battery_limit'}, + {reason: 'learned_limit', limit_kind: 'battery_current', limit_seen: 4}, {reason: 'device_standby', sent_w: undefined}]) { + const shown = controlStatus(row(extra)); + const text = [shown.title, shown.text, shown.next].join(' '); + assert.doesNotMatch(text, /_|undefined|NaN|null|cannot describe/, JSON.stringify(extra)); + } +}); diff --git a/web/control-feedback.js b/web/control-feedback.js index ee245257f..58bbb9a7e 100644 --- a/web/control-feedback.js +++ b/web/control-feedback.js @@ -66,6 +66,7 @@ const REASON_TITLES = { vehicle_complete: 'Car is full', vehicle_limit_completion: 'Car reached its limit', vehicle_not_requesting: 'Car not taking power', vehicle_declined: 'Car stopped charging', battery_full: 'Battery full', battery_nearly_full: 'Battery nearly full', battery_nearly_empty: 'Battery nearly empty', + battery_limit: 'Limited by the battery', learned_limit: 'At its usual limit', device_standby: 'On standby', core_limit: 'Limited by FTW', fuse_limit: 'Limited by the main fuse', fuse_cooldown: 'Waiting after a site power limit', import_limit: 'Limited by the hourly import limit', charger_limit: 'Limited by FTW’s charger setting', device_limit: 'Charger limit', offered_current_lower: 'Charger offers less current', @@ -98,6 +99,11 @@ function sentence(row) { case 'battery_full': return `FTW paused charging at ${percent(row.battery_soc)}. Charging resumes at ${percent(row.charge_resume_soc)} or lower; discharging works as normal.`; case 'battery_nearly_full': return `Taking ${controlPower(actual)} of ${controlPower(row.sent_w)} at ${percent(row.battery_soc)}. A battery charges slower when it is nearly full.`; case 'battery_nearly_empty': return `Giving ${controlPower(actual)} of ${controlPower(row.sent_w)} at ${percent(row.battery_soc)}. A battery limits discharge when it is nearly empty.`; + case 'battery_limit': return !num(row.limit_w) ? `The battery reports a limit below the ${target(row)} FTW asked for.` + : row.limit_w < 1 ? `The battery reports that it cannot ${takes(row)} power now. FTW asked for ${target(row)}.` + : `The battery reports that it can ${takes(row)} at most ${controlPower(row.limit_w)} now. FTW asked for ${target(row)}.`; + case 'learned_limit': return learnedLimit(row); + case 'device_standby': return `Asked for ${target(row)}, but the ${name} reports that it is on standby or starting up.`; case 'core_limit': return `FTW’s safety limits set the target to ${target(row)}.`; case 'fuse_limit': return `FTW lowered the rate to ${target(row)} to protect the main fuse.`; case 'import_limit': return `FTW lowered the rate to ${target(row)} to keep this hour’s grid import within its limit.`; @@ -134,6 +140,28 @@ function sentence(row) { } } +// A battery takes charge and gives discharge. +const takes = row => num(row.sent_w) && row.sent_w < 0 ? 'give' : 'take'; +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const day = ms => num(ms) && ms > 0 ? `${new Date(ms).getDate()} ${MONTHS[new Date(ms).getMonth()]}` : ''; + +// A limit the battery has shown on more than one day, so its shortfall is +// what it does, not a fault. Core says what holds it. +function learnedLimit(row) { + const seen = num(row.limit_seen) && day(row.limit_since_ms) + ? ` FTW has seen this ${row.limit_seen} time${row.limit_seen === 1 ? '' : 's'} since ${day(row.limit_since_ms)}.` : ''; + const earlier = num(row.limit_earlier_w) ? ` Earlier it was ${controlPower(row.limit_earlier_w)}.` : ''; + const room = num(row.limit_room_w) ? `, which leaves ${controlPower(row.limit_room_w)} for the battery` : ''; + const now = num(row.limit_w) ? ` (${controlPower(row.limit_w)} now)` : ''; + if (row.limit_kind === 'battery_current' ? !num(row.limit_a) : !num(row.limit_w)) return `The battery is at a limit it has shown before.${seen}`; + switch (row.limit_kind) { + case 'grid_import': return `The inverter takes at most ${controlPower(row.limit_w)} from the grid${room}.${seen}${earlier}`; + case 'grid_export': return `The inverter sends at most ${controlPower(row.limit_w)} to the grid${room}.${seen}${earlier}`; + case 'battery_current': return `The battery ${takes(row)}s at most ${amps(row.limit_a)}${now}.${seen}${earlier}`; + default: return `The battery ${takes(row)}s at most ${controlPower(row.limit_w)}.${seen}${earlier}`; + } +} + function evPowerWarning(row) { if (row.kind !== 'ev' || !row.readings_fresh || !num(row.requested_a) || !num(row.pilot_a) || !num(row.actual_w)) return ''; @@ -155,6 +183,7 @@ function nextStep(row) { case 'vehicle_declined': return 'Check the car’s charge limit and schedule.'; case 'setpoint_changed': return 'Another app or controller may be changing it.'; case 'device_fault': return `Check the ${name}.`; + case 'device_standby': return `It usually starts again by itself. If it stays on standby, check the ${name}’s app or display.`; case 'telemetry_stale': case 'readings_lost': case 'command_failed': case 'default_failed': return `Check the ${name}’s connection.`; case 'site_meter_stale': case 'site_phase_currents_stale': return 'Check the grid meter’s connection.';