diff --git a/.changeset/battery-limit-words-fix.md b/.changeset/battery-limit-words-fix.md new file mode 100644 index 000000000..60366e0c7 --- /dev/null +++ b/.changeset/battery-limit-words-fix.md @@ -0,0 +1,9 @@ +--- +"ftw": patch +--- + +Fix two phrases from the battery limit verdicts. A reported battery limit +without a known target now reads "The battery reports a limit below what FTW +asked for." instead of doubling "the". The Numbers list now labels a +battery's learned current limit "Battery current limit", not "Charger lets +the car take". The words match the web app's. diff --git a/.changeset/inverter-stream-headroom.md b/.changeset/inverter-stream-headroom.md new file mode 100644 index 000000000..d99b5e779 --- /dev/null +++ b/.changeset/inverter-stream-headroom.md @@ -0,0 +1,30 @@ +--- +"ftw": minor +--- + +Read a hybrid's inverter stream, and say when its inverter has no grid +headroom left. + +The driver contract lets a battery or hybrid driver report its AC stage with +`host.emit("inverter", …)`: its power, phases, rating, and +`available_import_W` / `available_export_W`, how much more the inverter will +take from or give to the grid now. Core refused that emit, so the Solis C&I +drivers lost it on every poll. Core now keeps the latest inverter reading per +driver. `/api/status` shows it while the driver is live (`inverter_w`, +`inverter_available_import_w`, `inverter_available_export_w`, +`inverter_updated_at_ms`), and `/api/drivers/{name}` shows the last one with +its age (`inverter`). It is not a device type: no site total, dispatch, fuse +guard or energy ledger reads it, and none of it is written to history. A +field that is not a usable number is left out and the rest kept. + +A battery that gives part of its order while its inverter reports, in the +same driver poll, no more import headroom while charging, or no more export +headroom while discharging, now reads "Limited by the inverter", with words +such as "The inverter reports that it can take no more from the grid now. +FTW asked for 5.0 kW charge." A battery that gives nothing keeps its warning, +since a dead battery on a site that may not export sees no export headroom +either; only the battery's own report of 0 available explains it. Headroom +above 100 W, headroom from an earlier poll, and a stale, offline or faulted +driver explain nothing. Wrong direction, power above the order or while +idle, a changed setpoint and lost readings keep their own reasons. Limited +verdicts never send the "not following" notice. diff --git a/go/internal/api/api.go b/go/internal/api/api.go index 6c81d2678..a7c070143 100644 --- a/go/internal/api/api.go +++ b/go/internal/api/api.go @@ -1157,6 +1157,21 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { } } } + // The inverter stream is a battery or hybrid's AC stage. It sits + // beside the driver's readings and is never added to them. Shown + // only while the driver is live, with when it was read. + if inv, ok := s.deps.Tel.LiveInverter(name); ok { + d["inverter_updated_at_ms"] = inv.UpdatedAt.UnixMilli() + if inv.W != nil { + d["inverter_w"] = *inv.W + } + if inv.AvailableImportW != nil { + d["inverter_available_import_w"] = *inv.AvailableImportW + } + if inv.AvailableExportW != nil { + d["inverter_available_export_w"] = *inv.AvailableExportW + } + } drivers[name] = d } // Merge config drivers that aren't in the registry so the UI can diff --git a/go/internal/api/api_control_capability.go b/go/internal/api/api_control_capability.go index 2a2320470..b7b05b894 100644 --- a/go/internal/api/api_control_capability.go +++ b/go/internal/api/api_control_capability.go @@ -11,8 +11,9 @@ import ( // 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; +// against what it can do now: what its driver reports for the battery and +// for its inverter's grid headroom, 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 @@ -96,6 +97,14 @@ func (b batteryNow) standby() bool { return b.DeviceState == "standby" || b.Devi // 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 battery that gives part of its order while its inverter reports, +// in the same driver poll, no more grid headroom in the order's +// direction (available_import_W while charging, available_export_W +// while discharging, at most Core's smallest control tolerance) is +// limited / battery_limit, limit_kind inverter_import or +// inverter_export. A zero response keeps its warning: a dead battery +// on a site that may not export also sees no export headroom. Only the +// battery's own report of 0 available explains it; // - a trusted learned plateau the shortfall sits on is limited / // learned_limit. // @@ -126,6 +135,14 @@ func (s *Server) explainBatteryShortfall(f *ControlFeedback, data json.RawMessag f.LimitW, f.LimitSource, f.LimitKind = watts(*limit), "device", "battery_reported" return } + // The inverter takes no more from the grid, or gives no more to it, so + // the battery can get or give no more through it. That explains less + // power, never none. + if room, kind := s.inverterRoom(f.Driver, charge); f.Reason == "power_below_target" && room != nil && *room <= telemetry.ControlToleranceW(0) { + f.State, f.Reason, f.Severity = "limited", "battery_limit", "info" + f.LimitW, f.LimitSource, f.LimitKind = watts(*room), "device", kind + return + } if f.shortfall == nil { return } @@ -160,6 +177,23 @@ func (s *Server) explainBatteryShortfall(f *ControlFeedback, data json.RawMessag } } +// inverterRoom is how much more the battery's own inverter reports it will +// take from the grid while charging, or give to it while discharging, from +// the inverter stream of the battery reading's poll. Nil when the driver +// sends no such headroom, its inverter read failed, or the driver is stale, +// offline or faulted. +func (s *Server) inverterRoom(driver string, charge bool) (*float64, string) { + inv, ok := s.deps.Tel.LiveBatteryInverter(driver) + if !ok { + return nil, "" + } + kind := "inverter_export" + if charge { + kind = "inverter_import" + } + return inv.Headroom(charge), kind +} + 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 diff --git a/go/internal/api/api_control_capability_test.go b/go/internal/api/api_control_capability_test.go index 4d53a4685..d5a60e965 100644 --- a/go/internal/api/api_control_capability_test.go +++ b/go/internal/api/api_control_capability_test.go @@ -38,6 +38,11 @@ type sungrowTrace struct { // frozenMeterW, when set, is the one grid value a driver keeps resending // from its cache. frozenMeterW *float64 + // inverter, when set, gives the inverter stream emit of this poll, or + // "" when the inverter read failed. + inverter func() string + // polls numbers the driver's polls, as the driver host does. + polls uint64 } func newSungrowTrace() *sungrowTrace { @@ -64,7 +69,17 @@ func (s *sungrowTrace) poll() { } 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.polls++ + s.tel.UpdateFromPoll("sungrow", telemetry.DerBattery, w, &soc, []byte(fmt.Sprintf(`{"setpoint_w":%g,"a":%.1f,"v":%.1f%s}`, s.cmdW, a, v, extra)), s.polls) + if s.inverter != nil { + if data := s.inverter(); data != "" { + r, err := telemetry.ParseInverterReading([]byte(data)) + if err != nil { + panic(err) + } + s.tel.UpdateInverter("sungrow", r, s.polls) + } + } s.tel.RecordDriverSuccess("sungrow") } diff --git a/go/internal/api/api_control_feedback.go b/go/internal/api/api_control_feedback.go index deadee66e..402b7b13c 100644 --- a/go/internal/api/api_control_feedback.go +++ b/go/internal/api/api_control_feedback.go @@ -86,7 +86,8 @@ type ControlFeedback struct { // 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 + // "battery_current", "battery_power", "battery_reported", + // "inverter_import" or "inverter_export"), 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"` diff --git a/go/internal/api/api_control_inverter_test.go b/go/internal/api/api_control_inverter_test.go new file mode 100644 index 000000000..674bcc508 --- /dev/null +++ b/go/internal/api/api_control_inverter_test.go @@ -0,0 +1,242 @@ +package api + +import ( + "encoding/json" + "math" + "net/http/httptest" + "path/filepath" + "slices" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/control" + "github.com/srcfl/ftw/go/internal/state" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// A hybrid's inverter reports on its inverter stream how much more it will +// take from or give to the grid now. A battery that gives part of its order +// while that headroom is gone is limited by the inverter, not out of +// control. A battery that gives nothing keeps its warning. +func TestInverterHeadroomExplainsAShortfall(t *testing.T) { + for _, tc := range []struct { + name, battery, inverter string + orderW, w float64 + status, reason, kind string + limitW float64 + }{ + {"no import room while charging", "", `{"W":4300,"available_import_W":0,"available_export_W":5000}`, 5000, 3600, "limited", "battery_limit", "inverter_import", 0}, + {"import room within the tolerance", "", `{"W":4300,"available_import_W":60}`, 5000, 3600, "limited", "battery_limit", "inverter_import", 60}, + {"no export room while discharging", "", `{"W":-3200,"available_export_W":0}`, -5000, -3150, "limited", "battery_limit", "inverter_export", 0}, + // A dead battery on a site that may not export sees no export + // headroom either: only the battery's own report explains nothing. + {"no response, no import room", "", `{"W":800,"available_import_W":0}`, 5000, 0, "not_following", "no_power_response", "", 0}, + {"no response, no export room", "", `{"W":0,"available_export_W":0}`, -5000, 0, "not_following", "no_power_response", "", 0}, + {"no response, battery reports none available", `,"available_discharge_W":0`, `{"W":0,"available_export_W":0}`, -5000, 0, "limited", "battery_limit", "battery_reported", 0}, + {"no response, import room left", "", `{"W":800,"available_import_W":3000}`, 5000, 0, "not_following", "no_power_response", "", 0}, + {"no response, room just above the tolerance", "", `{"available_export_W":150}`, -5000, 0, "not_following", "no_power_response", "", 0}, + {"import room left", "", `{"W":4300,"available_import_W":1400}`, 5000, 3600, "not_following", "power_below_target", "", 0}, + {"room just above the tolerance", "", `{"available_import_W":150}`, 5000, 3600, "not_following", "power_below_target", "", 0}, + {"export room gone while charging", "", `{"available_import_W":2000,"available_export_W":0}`, 5000, 3600, "not_following", "power_below_target", "", 0}, + {"import room gone while discharging", "", `{"available_import_W":0,"available_export_W":2000}`, -5000, -3150, "not_following", "power_below_target", "", 0}, + {"headroom left out", "", `{"W":4300}`, 5000, 3600, "not_following", "power_below_target", "", 0}, + {"headroom out of range", "", `{"W":4300,"available_import_W":-10}`, 5000, 3600, "not_following", "power_below_target", "", 0}, + {"no inverter stream", "", ``, 5000, 3600, "not_following", "power_below_target", "", 0}, + // The battery's own report says more, and comes first. + {"battery reports its limit too", `,"available_charge_W":3600`, `{"available_import_W":0}`, 5000, 3600, "limited", "battery_limit", "battery_reported", 3600}, + {"standby", `,"device_state":"standby"`, `{"available_export_W":0}`, -5000, 0, "not_following", "device_standby", "", 0}, + } { + 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.battery } + s.inverter = func() string { return tc.inverter } + var last ControlFeedback + s.run(90*time.Second, tc.orderW, func(f ControlFeedback) { last = f }) + if last.Status != tc.status || last.Reason != tc.reason || last.LimitKind != tc.kind { + t.Fatalf("got %s/%s/%s %s, want %s/%s %s", last.Status, last.Reason, last.Severity, last.LimitKind, tc.status, tc.reason, tc.kind) + } + switch { + case tc.reason == "battery_limit": + if last.Severity != "info" || last.LimitSource != "device" || last.LimitW == nil || *last.LimitW != tc.limitW || last.LimitRoomW != nil { + t.Fatalf("limit fields %s", jsonOf(last)) + } + case last.LimitW != nil || last.LimitSource != "": + t.Fatalf("unexplained shortfall carries a limit: %s", jsonOf(last)) + } + }) + }) + } +} + +// Headroom from an earlier poll says nothing about now. When the inverter +// read starts failing while a 1 Hz battery keeps reporting, the shortfall +// is not following again from the next poll. +func TestStaleInverterStreamIsIgnored(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := newSungrowTrace() + s.houseW = 800 + s.battery = func() (float64, float64, float64, string) { return 3600, 3600 / 190.0, 190, "" } + inverter := `{"W":4300,"available_import_W":0}` + s.inverter = func() string { return inverter } + var last ControlFeedback + s.run(90*time.Second, 5000, func(f ControlFeedback) { last = f }) + if last.Reason != "battery_limit" || last.LimitKind != "inverter_import" { + t.Fatalf("fresh headroom: %s", jsonOf(last)) + } + inverter = "" + // The very next poll, a second later, already says not following. + time.Sleep(time.Second) + s.poll() + if f := s.batteryRow(time.Now()); f.Status != "not_following" || f.Reason != "power_below_target" { + t.Fatalf("a second-old headroom explained the next poll: %s", jsonOf(f)) + } + var seen []string + s.run(30*time.Second, 5000, func(f ControlFeedback) { seen = append(seen, f.Status+"/"+f.Reason) }) + for _, got := range seen { + if got != "not_following/power_below_target" { + t.Fatalf("old headroom still explained the shortfall: %v", seen) + } + } + if _, ok := s.tel.Inverter("sungrow"); !ok { + t.Fatal("the last inverter reading should stay for the driver views") + } + }) +} + +// Headroom explains only a shortfall in the right direction. Every other +// verdict keeps its own reason, however empty the inverter says it is. +func TestInverterHeadroomNeverExplainsOtherVerdicts(t *testing.T) { + const none = `{"W":0,"available_import_W":0,"available_export_W":0}` + for _, tc := range []struct { + name, extra string + orderW float64 + 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"}}, + {"no response", "", -5000, func(s *sungrowTrace) { + s.battery = func() (float64, float64, float64, string) { return 0, 0, 190, "" } + }, nil, []string{"no_power_response"}}, + {"no response while charging", "", 5000, func(s *sungrowTrace) { + s.battery = func() (float64, float64, float64, string) { return 0, 0, 190, "" } + }, nil, []string{"no_power_response"}}, + {"device fault", "", -3000, func(s *sungrowTrace) { s.tel.SetDriverDeviceFault("sungrow", true, "test fault") }, nil, []string{"device_fault"}}, + {"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"}}, + {"driver offline", "", -3000, nil, func(s *sungrowTrace) { + s.tel.DriverHealthMut("sungrow").SetOffline() + }, []string{"telemetry_stale", "readings_lost"}}, + } { + 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 -2000, 2000 / 190.0, 190, tc.extra } + s.inverter = func() string { return none } + 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()) + } + 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) + } + }) + }) + } +} + +// The status and driver views show the inverter stream beside the driver's +// readings. The site's grid, solar, battery and load stay what the DER +// readings say. +func TestStatusShowsTheInverterStreamApartFromSitePower(t *testing.T) { + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + tel := telemetry.NewStore() + soc := 0.5 + tel.Update("solis", telemetry.DerMeter, 1800, nil, []byte(`{"power_origin":"external_meter"}`)) + tel.Update("solis", telemetry.DerBattery, 3600, &soc, nil) + tel.Update("solis", telemetry.DerPV, -2400, nil, nil) + tel.RecordDriverSuccess("solis") + srv := New(&Deps{State: st, Tel: tel, Ctrl: &control.State{SiteMeterDriver: "solis"}, CtrlMu: &sync.Mutex{}, CapMu: &sync.RWMutex{}, + CfgMu: &sync.RWMutex{}, Cfg: &config.Config{}}) + status := func() map[string]any { + rr := httptest.NewRecorder() + srv.handleStatus(rr, httptest.NewRequest("GET", "/api/status", nil)) + var body map[string]any + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { + t.Fatalf("status: %v %s", err, rr.Body.String()) + } + return body + } + before := status() + r, err := telemetry.ParseInverterReading([]byte(`{"W":-9000,"available_import_W":0,"available_export_W":4100,"Hz":50}`)) + if err != nil { + t.Fatal(err) + } + tel.UpdateInverter("solis", r, 1) + after := status() + for _, key := range []string{"grid_w", "pv_w", "bat_w", "load_w", "ev_w"} { + if before[key] != after[key] { + t.Fatalf("%s moved: %v -> %v", key, before[key], after[key]) + } + } + d, _ := after["drivers"].(map[string]any)["solis"].(map[string]any) + if d["inverter_w"] != -9000.0 || d["inverter_available_import_w"] != 0.0 || d["inverter_available_export_w"] != 4100.0 || d["bat_w"] == nil { + t.Fatalf("driver status %v", d) + } + stored, _ := tel.Inverter("solis") + if at, _ := d["inverter_updated_at_ms"].(float64); int64(at) != stored.UpdatedAt.UnixMilli() { + t.Fatalf("reading time %v, want %d", d["inverter_updated_at_ms"], stored.UpdatedAt.UnixMilli()) + } + // A stale or faulted driver's cached values never show as live. + for name, setup := range map[string]func(){ + "offline": func() { tel.DriverHealthMut("solis").SetOffline() }, + "fault": func() { tel.SetDriverDeviceFault("solis", true, "test") }, + } { + tel.RecordDriverSuccess("solis") + tel.SetDriverDeviceFault("solis", false, "") + setup() + d, _ := status()["drivers"].(map[string]any)["solis"].(map[string]any) + for _, key := range []string{"inverter_w", "inverter_available_import_w", "inverter_available_export_w", "inverter_updated_at_ms"} { + if _, shown := d[key]; shown { + t.Fatalf("%s driver shows %s: %v", name, key, d) + } + } + } + tel.SetDriverDeviceFault("solis", false, "") + tel.RecordDriverSuccess("solis") + + rr := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/api/drivers/solis", nil) + req.SetPathValue("name", "solis") + srv.handleDriverDetail(rr, req) + var detail driverDetailResp + if err := json.Unmarshal(rr.Body.Bytes(), &detail); err != nil { + t.Fatal(err) + } + if detail.Inverter == nil || detail.Inverter.W == nil || *detail.Inverter.W != -9000 || detail.Inverter.AvailableImportW == nil || + *detail.Inverter.AvailableImportW != 0 || detail.Inverter.Stale || detail.Inverter.UpdatedAt == 0 || len(detail.Readings) != 3 { + t.Fatalf("driver detail %s", rr.Body.String()) + } +} diff --git a/go/internal/api/api_drivers_debug.go b/go/internal/api/api_drivers_debug.go index c1657a4e3..9adbe2582 100644 --- a/go/internal/api/api_drivers_debug.go +++ b/go/internal/api/api_drivers_debug.go @@ -43,6 +43,9 @@ type driverDetailResp struct { Readings []readingDTO `json:"readings"` Metrics []telemetry.MetricSnapshot `json:"metrics"` Identity driverIdentityDTO `json:"identity"` + // Inverter is the driver's inverter stream, apart from Readings + // because no site sum includes it. Absent until the driver sends one. + Inverter *inverterDTO `json:"inverter,omitempty"` // Controls are what this driver says an operator may command. Absent // for every driver that only reports. Controls []drivers.CatalogControl `json:"controls,omitempty"` @@ -72,6 +75,17 @@ type readingDTO struct { Stale bool `json:"stale"` } +// inverterDTO is a battery or hybrid driver's AC stage: its power, how much +// more it takes from or gives to the grid now, and the emit as sent. +type inverterDTO struct { + W *float64 `json:"w,omitempty"` + AvailableImportW *float64 `json:"available_import_w,omitempty"` + AvailableExportW *float64 `json:"available_export_w,omitempty"` + Data json.RawMessage `json:"data,omitempty"` + UpdatedAt int64 `json:"updated_at_ms"` + Stale bool `json:"stale"` +} + type driverIdentityDTO struct { Make string `json:"make,omitempty"` SN string `json:"sn,omitempty"` @@ -120,6 +134,10 @@ func (s *Server) handleDriverDetail(w http.ResponseWriter, r *http.Request) { Stale: time.Since(rd.UpdatedAt) > staleAfter, }) } + if inv, ok := s.deps.Tel.Inverter(name); ok { + resp.Inverter = &inverterDTO{W: inv.W, AvailableImportW: inv.AvailableImportW, AvailableExportW: inv.AvailableExportW, + Data: inv.Data, UpdatedAt: inv.UpdatedAt.UnixMilli(), Stale: time.Since(inv.UpdatedAt) > staleAfter} + } resp.Metrics = s.deps.Tel.LatestMetricsByDriver(name) sort.Slice(resp.Metrics, func(i, j int) bool { return resp.Metrics[i].Name < resp.Metrics[j].Name }) if s.deps.Registry != nil { diff --git a/go/internal/control/inverter_stream_test.go b/go/internal/control/inverter_stream_test.go new file mode 100644 index 000000000..b90a16d2e --- /dev/null +++ b/go/internal/control/inverter_stream_test.go @@ -0,0 +1,68 @@ +package control + +import ( + "reflect" + "slices" + "strings" + "testing" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// A hybrid's inverter stream says what its AC stage does and how much more +// it will take from or give to the grid. Dispatch, its fuse protection and +// the battery split never read it: the same site with and without the +// stream gets the same targets, in every mode, tick after tick. +func TestInverterStreamNeverChangesDispatch(t *testing.T) { + site := func(inverter bool) *telemetry.Store { + s := seedStore(9000, []struct { + name string + currentW, soc float64 + }{ + {"ferroamp", -1500, 0.6}, + {"solis", 2000, 0.4}, + }) + if inverter { + for _, name := range []string{"ferroamp", "solis"} { + r, err := telemetry.ParseInverterReading([]byte(`{"W":-20000,"available_import_W":0,"available_export_W":0,"L1_W":-7000}`)) + if err != nil { + t.Fatal(err) + } + s.UpdateInverter(name, r, 1) + } + } + return s + } + caps := map[string]float64{"ferroamp": 15200, "solis": 100000} + clamped := 0 + for _, mode := range []Mode{ModeSelfConsumption, ModeCharge, ModeIdle, ModePeakShaving} { + plain, with := site(false), site(true) + a, b := NewState(0, 50, "ferroamp"), NewState(0, 50, "ferroamp") + a.Mode, b.Mode = mode, mode + a.MinDispatchIntervalS, b.MinDispatchIntervalS = 0, 0 + for tick := range 5 { + // 9 kW import on a 16 A fuse: fuse protection is in play. + ta, tb := ComputeDispatch(plain, a, caps, 11040), ComputeDispatch(with, b, caps, 11040) + // Target order follows map order; the targets are what count. + byDriver := func(x, y DispatchTarget) int { return strings.Compare(x.Driver, y.Driver) } + slices.SortFunc(ta, byDriver) + slices.SortFunc(tb, byDriver) + if !reflect.DeepEqual(ta, tb) { + t.Fatalf("%s tick %d: targets moved with the inverter stream:\n%+v\n%+v", mode, tick, ta, tb) + } + if len(ta) == 0 { + t.Fatalf("%s tick %d: no targets to compare", mode, tick) + } + for _, target := range ta { + if target.Clamped { + clamped++ + } + } + plain.Update("ferroamp", telemetry.DerMeter, 9000, nil, nil) + with.Update("ferroamp", telemetry.DerMeter, 9000, nil, nil) + } + } + if clamped == 0 { + t.Fatal("no target was clamped, so fuse protection was never compared") + } +} diff --git a/go/internal/drivers/host.go b/go/internal/drivers/host.go index ee5609a55..eadca8b79 100644 --- a/go/internal/drivers/host.go +++ b/go/internal/drivers/host.go @@ -9,6 +9,7 @@ import ( "math" net_url "net/url" "sync" + "sync/atomic" "time" "github.com/srcfl/ftw/go/internal/telemetry" @@ -222,8 +223,16 @@ type HostEnv struct { lastPollEvidence pollEvidence pollTelemetry [][]byte pollMetrics []pollMetric + // pollID numbers the poll that runs or ran last. Every reading a poll + // emits carries it, so the store can tell one poll's readings from an + // earlier poll's however close in time they arrive. + pollID uint64 } +// pollIDs numbers driver polls across every host in the process, so a +// restarted host never reuses a number a stored reading still carries. +var pollIDs atomic.Uint64 + type pollMetric struct { name string value float64 @@ -314,6 +323,7 @@ func (h *HostEnv) allowWrite(permission string) error { func (h *HostEnv) beginPollEvidence() { h.mu.Lock() h.pollActive = true + h.pollID = pollIDs.Add(1) h.pollModbusAttempts = 0 h.pollModbusSuccesses = 0 h.pollModbusTransportFailures = 0 @@ -363,6 +373,7 @@ func (h *HostEnv) endPollEvidence(commit bool) (attempts, successes int, err err attempts = ev.Attempts successes = ev.Successes h.lastPollEvidence = ev + poll := h.pollID fresh := commit && ev.fresh() var pendingTelemetry [][]byte var pendingMetrics []pollMetric @@ -381,7 +392,7 @@ func (h *HostEnv) endPollEvidence(commit bool) (attempts, successes int, err err h.mu.Unlock() for _, rawJSON := range pendingTelemetry { - if emitErr := h.emitTelemetry(rawJSON); emitErr != nil { + if emitErr := h.emitTelemetryFrom(rawJSON, poll); emitErr != nil { return attempts, successes, emitErr } } @@ -588,9 +599,31 @@ func (h *HostEnv) setPollInterval(ms int32) { // // {"type": "meter"|"pv"|"battery"|"ev"|"v2x_charger"|"vehicle", "w": 123.4, "soc": 0.5 (optional), ...} // +// "inverter" is a stream, not a DER, and goes to emitInverter. +// // Extra fields are preserved in the reading's Data payload so the UI/API can // surface them verbatim. func (h *HostEnv) emitTelemetry(rawJSON []byte) error { + h.mu.Lock() + poll := uint64(0) + if h.pollActive { + poll = h.pollID + } + h.mu.Unlock() + return h.emitTelemetryFrom(rawJSON, poll) +} + +// emitTelemetryFrom is emitTelemetry for an emit of driver poll number poll, +// 0 outside a poll. +func (h *HostEnv) emitTelemetryFrom(rawJSON []byte, poll uint64) error { + // The inverter stream is read field by field, so it is routed before + // the DER envelope, where one bad power value would fail the emit. + var stream struct { + Type string `json:"type"` + } + if json.Unmarshal(rawJSON, &stream) == nil && stream.Type == "inverter" { + return h.emitInverter(rawJSON, poll) + } var env struct { Type string `json:"type"` W *float64 `json:"w"` @@ -667,7 +700,7 @@ func (h *HostEnv) emitTelemetry(rawJSON []byte) error { return nil } if h.Telemetry != nil { - h.Telemetry.Update(h.DriverName, t, rawW, soc, rawJSON) + h.Telemetry.UpdateFromPoll(h.DriverName, t, rawW, soc, rawJSON, poll) } // Successful emit counts as a tick for health if h.Telemetry != nil { @@ -676,6 +709,34 @@ func (h *HostEnv) emitTelemetry(rawJSON []byte) error { return nil } +// emitInverter keeps a driver's inverter stream: the AC stage of its battery +// or hybrid inverter, which is not a DER (telemetry/inverter.go). It follows +// the poll rules of a DER emit, so a poll whose reads failed drops it, but it +// is no sign of life: a driver that sends only this goes stale. +func (h *HostEnv) emitInverter(rawJSON []byte, poll uint64) error { + r, err := telemetry.ParseInverterReading(rawJSON) + if err != nil { + return fmt.Errorf("emit_telemetry: %w", err) + } + if h.bufferPollTelemetry(rawJSON) { + return nil + } + if h.Telemetry != nil { + h.Telemetry.UpdateInverter(h.DriverName, r, poll) + } + return nil +} + +// dropNonFinite leaves out the top-level numbers JSON cannot carry, NaN and +// ±Inf, so one failed register in an inverter emit does not lose the rest. +func dropNonFinite(fields map[string]any) { + for key, value := range fields { + if f, ok := value.(float64); ok && (math.IsNaN(f) || math.IsInf(f, 0)) { + delete(fields, key) + } + } +} + // emitMetric buffers a scalar diagnostic metric for the long-format TS DB. // Driver authors call this for anything beyond the standard pv/battery/meter // shape — temperatures, voltages, frequencies, MPPT currents, etc. unit is an diff --git a/go/internal/drivers/inverter_stream_test.go b/go/internal/drivers/inverter_stream_test.go new file mode 100644 index 000000000..a7740e263 --- /dev/null +++ b/go/internal/drivers/inverter_stream_test.go @@ -0,0 +1,157 @@ +package drivers + +import ( + "context" + "strings" + "testing" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The Solis C&I drivers (50-125k-svk*) send the battery's AC stage on the +// inverter stream right after the battery reading. The host keeps it, and +// it reaches neither the DER readings nor history. +func TestHostAcceptsTheInverterStream(t *testing.T) { + path := writeLua(t, ` +function driver_init(config) end +function driver_poll() + host.emit("battery", { W = 3600, SoC_nom_fract = 0.5, available_charge_W = 5000 }) + local err = host.emit("inverter", { W = 4000, available_import_W = 0, available_export_W = 5200, Hz = 50.01 }) + assert(err == nil, "inverter emit refused: " .. tostring(err)) + return 1000 +end +`) + tel := telemetry.NewStore() + env := NewHostEnv("solis", tel) + env.BatteryCapacityWh = 100000 + d, err := NewLuaDriver(path, env) + if err != nil { + t.Fatalf("load: %v", err) + } + defer d.Cleanup() + if err := d.Init(context.Background(), nil); err != nil { + t.Fatalf("init: %v", err) + } + tel.FlushSamples() + if _, err := d.Poll(context.Background()); err != nil { + t.Fatalf("poll: %v", err) + } + inv, ok := tel.LiveBatteryInverter("solis") + if !ok || inv.W == nil || *inv.W != 4000 || inv.AvailableImportW == nil || *inv.AvailableImportW != 0 || + inv.AvailableExportW == nil || *inv.AvailableExportW != 5200 || !strings.Contains(string(inv.Data), `"Hz":50.01`) { + t.Fatalf("inverter reading %+v %v", inv, ok) + } + if bat := tel.Get("solis", telemetry.DerBattery); bat == nil || bat.RawW != 3600 { + t.Fatalf("battery reading %+v", bat) + } + for _, kind := range telemetry.AllDerTypes() { + if kind != telemetry.DerBattery && tel.Get("solis", kind) != nil { + t.Fatalf("the inverter stream became a %s reading", kind) + } + } + for _, sample := range tel.FlushSamples() { + if strings.HasPrefix(sample.Metric, "inverter") { + t.Fatalf("the inverter stream reached history: %+v", sample) + } + } +} + +// An inverter emit alone is no sign of life, so it never keeps a driver's +// held battery reading in dispatch. A poll whose reads failed drops it with +// the rest of the poll. +func TestInverterStreamFollowsThePollRules(t *testing.T) { + tel := telemetry.NewStore() + env := NewHostEnv("solis", tel) + if err := env.emitTelemetry([]byte(`{"type":"inverter","W":4000,"available_import_W":0}`)); err != nil { + t.Fatalf("emit: %v", err) + } + if h := tel.DriverHealth("solis"); h != nil && h.LastSuccess != nil { + t.Fatalf("an inverter emit counted as a sign of life: %+v", h) + } + if _, ok := tel.Inverter("solis"); !ok { + t.Fatal("inverter reading not kept") + } + // One bad field is left out; the rest of the emit is kept. + if err := env.emitTelemetry([]byte(`{"type":"inverter","W":"high","available_import_W":0}`)); err != nil { + t.Fatalf("one bad field failed the emit: %v", err) + } + if r, _ := tel.Inverter("solis"); r.W != nil || r.AvailableImportW == nil || *r.AvailableImportW != 0 { + t.Fatalf("bad power field: %+v", r) + } + + tel = telemetry.NewStore() + env = NewHostEnv("solis", tel) + env.requiresFreshModbusRead = true + env.beginPollEvidence() + if err := env.emitTelemetry([]byte(`{"type":"inverter","W":4000,"available_import_W":0}`)); err != nil { + t.Fatalf("emit: %v", err) + } + if _, _, err := env.endPollEvidence(false); err != nil { + t.Fatalf("end poll: %v", err) + } + if _, ok := tel.Inverter("solis"); ok { + t.Fatal("an inverter reading from a failed poll was kept") + } + + // A good poll lands both, held until it ends, as one poll. + env.BatteryCapacityWh = 100000 + env.beginPollEvidence() + env.recordPollModbusRead(nil) + for _, blob := range []string{`{"type":"battery","W":3600,"SoC_nom_fract":0.5}`, `{"type":"inverter","W":4000,"available_import_W":0}`} { + if err := env.emitTelemetry([]byte(blob)); err != nil { + t.Fatalf("emit: %v", err) + } + } + if _, ok := tel.Inverter("solis"); ok { + t.Fatal("stored before the poll ended") + } + if _, _, err := env.endPollEvidence(true); err != nil { + t.Fatalf("end poll: %v", err) + } + if inv, ok := tel.LiveBatteryInverter("solis"); !ok || inv.Poll == 0 { + t.Fatalf("held poll did not pair: %+v %v", inv, ok) + } +} + +// A driver polled back to back that reads its inverter every other poll: +// the battery reading pairs with headroom only on the polls that read it, +// however close in time the polls are. A failed register (NaN) is left out +// and the rest of the emit kept. +func TestInverterStreamPairsByPoll(t *testing.T) { + path := writeLua(t, ` +local n = 0 +function driver_init(config) end +function driver_poll() + n = n + 1 + host.emit("battery", { W = 3600, SoC_nom_fract = 0.5 }) + if n % 2 == 0 then + local err = host.emit("inverter", { W = 0/0, available_import_W = 0, rated_W = 1/0 }) + assert(err == nil, "inverter emit refused: " .. tostring(err)) + end + return 1000 +end +`) + tel := telemetry.NewStore() + env := NewHostEnv("solis", tel) + env.BatteryCapacityWh = 100000 + d, err := NewLuaDriver(path, env) + if err != nil { + t.Fatalf("load: %v", err) + } + defer d.Cleanup() + if err := d.Init(context.Background(), nil); err != nil { + t.Fatalf("init: %v", err) + } + for n := 1; n <= 4; n++ { + if _, err := d.Poll(context.Background()); err != nil { + t.Fatalf("poll %d: %v", n, err) + } + inv, ok := tel.LiveBatteryInverter("solis") + if ok != (n%2 == 0) { + t.Fatalf("poll %d: paired %v", n, ok) + } + if ok && (inv.W != nil || inv.AvailableImportW == nil || *inv.AvailableImportW != 0 || strings.Contains(string(inv.Data), "rated_W")) { + t.Fatalf("poll %d: %+v %s", n, inv, inv.Data) + } + } +} diff --git a/go/internal/drivers/lua.go b/go/internal/drivers/lua.go index c629d8ad0..41d55eaa5 100644 --- a/go/internal/drivers/lua.go +++ b/go/internal/drivers/lua.go @@ -604,6 +604,12 @@ func registerHost(L *lua.LState, env *HostEnv) { // since stale_after_s — UI should de-emphasize). // w is unused for vehicle readings (charger's DerEV owns // the power number). + // inverter -> a stream, not a DER: a battery or hybrid driver's AC + // stage. W (AC power, site convention), VA, Hz, L1_V…L3_W, + // rated_W, available_import_W / available_export_W (how + // much more it takes from / gives to the grid now, 0 to + // 100 kW). Core keeps the latest reading per driver for + // the verdict and the driver views; no site sum reads it. host.RawSetString("emit", L.NewFunction(func(L *lua.LState) int { typ := L.CheckString(1) tbl := L.CheckTable(2) @@ -612,6 +618,9 @@ func registerHost(L *lua.LState, env *HostEnv) { m = map[string]any{} } m["type"] = typ + if typ == "inverter" { + dropNonFinite(m) + } blob, err := json.Marshal(m) if err != nil { L.Push(lua.LString("encode failed: " + err.Error())) diff --git a/go/internal/telemetry/inverter.go b/go/internal/telemetry/inverter.go new file mode 100644 index 000000000..6697e802f --- /dev/null +++ b/go/internal/telemetry/inverter.go @@ -0,0 +1,141 @@ +package telemetry + +import ( + "encoding/json" + "fmt" + "time" +) + +// The inverter stream is a battery or hybrid driver's AC stage, sent with +// host.emit("inverter", …) (srcfl/device-drivers spec/host-api-profile.json, +// "streams_vs_ders"): its AC power, frequency, phases, rating, and how much +// more it will take from or give to the grid now. It is not a DER. Its power +// is energy the driver's battery and PV readings already carry, seen at the +// AC port, so it is kept apart from the DER readings: no site sum, dispatch, +// fuse check, energy ledger or history total reads it, nothing of it is +// written to history, and it does not count as a sign of life for the +// driver. Only the latest reading per driver is kept, in memory. + +// inverterHeadroomMaxW is the driver guide's bound: a power outside 0 to +// 100 kW is dropped. +const inverterHeadroomMaxW = 100_000 + +// InverterReading is a driver's latest inverter stream reading. +type InverterReading struct { + Driver string + // W is the AC power at the inverter's grid port, in site convention, + // when the driver sent a finite number. + W *float64 + // AvailableImportW and AvailableExportW are how much more the inverter + // will take from, or give to, the grid now, in positive W. Nil when the + // driver left the field out or sent anything but a number from 0 to + // 100 kW. + AvailableImportW *float64 + AvailableExportW *float64 + // Data is the emit as the driver sent it. + Data json.RawMessage + UpdatedAt time.Time + // Poll is the driver poll the reading came from, as on DerReading. + Poll uint64 +} + +// Headroom is how much more the inverter will take from the grid while a +// battery charges, or give to it while one discharges. +func (r InverterReading) Headroom(charge bool) *float64 { + if charge { + return r.AvailableImportW + } + return r.AvailableExportW +} + +// ParseInverterReading reads an inverter emit by the canonical +// @srcful/data-models key names, exactly as Blixt L1 does; power also +// accepts the catalog's "w". Each field stands alone: one that is not a +// usable number is left out and the rest are kept. Only a blob that is not +// a JSON object is an error. +func ParseInverterReading(data json.RawMessage) (InverterReading, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return InverterReading{}, fmt.Errorf("inverter: %w", err) + } + w := finiteNumber(fields["W"]) + if w == nil { + w = finiteNumber(fields["w"]) + } + return InverterReading{W: w, AvailableImportW: headroomW(fields["available_import_W"]), + AvailableExportW: headroomW(fields["available_export_W"]), Data: data}, nil +} + +// finiteNumber is a JSON number that fits a finite float64, else nil. A +// JSON null stays nil: it never becomes 0. +func finiteNumber(raw json.RawMessage) *float64 { + var v *float64 + if len(raw) == 0 || json.Unmarshal(raw, &v) != nil || v == nil || !finite(*v) { + return nil + } + return v +} + +func headroomW(raw json.RawMessage) *float64 { + w := finiteNumber(raw) + if w == nil || *w < 0 || *w > inverterHeadroomMaxW { + return nil + } + return w +} + +// UpdateInverter stores a driver's latest inverter reading, from driver +// poll number poll (0 outside a poll). +func (s *Store) UpdateInverter(driver string, r InverterReading, poll uint64) { + r.Driver, r.UpdatedAt, r.Poll = driver, time.Now(), poll + s.mu.Lock() + defer s.mu.Unlock() + if s.inverters == nil { + s.inverters = map[string]InverterReading{} + } + s.inverters[driver] = r +} + +// Inverter returns a driver's latest inverter reading whatever the driver's +// health, for a view that shows its age and whether it is stale. Nothing +// that decides, and no view that shows it as live, may use it. +func (s *Store) Inverter(driver string) (InverterReading, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + r, ok := s.inverters[driver] + return r, ok +} + +// LiveInverter returns a driver's latest inverter reading only while the +// driver is live and its device reports no fault. A cached reading survives +// its driver going stale, offline or faulted; this one does not. +func (s *Store) LiveInverter(driver string) (InverterReading, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + return s.liveInverterLocked(driver) +} + +func (s *Store) liveInverterLocked(driver string) (InverterReading, bool) { + h, ok := s.health[driver] + if !ok || !h.TelemetryLive() || h.DeviceFault { + return InverterReading{}, false + } + r, ok := s.inverters[driver] + return r, ok +} + +// LiveBatteryInverter is LiveInverter for a reading that came in the same +// driver poll as the driver's latest battery reading. Polls are matched by +// number, not by time: when one of the two reads fails, the other is left +// from an earlier poll however close in time, and the pair is refused. +// Readings from outside a poll never pair. +func (s *Store) LiveBatteryInverter(driver string) (InverterReading, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + r, ok := s.liveInverterLocked(driver) + bat := s.readings[key(driver, DerBattery)] + if !ok || bat == nil || r.Poll == 0 || r.Poll != bat.Poll { + return InverterReading{}, false + } + return r, true +} diff --git a/go/internal/telemetry/inverter_test.go b/go/internal/telemetry/inverter_test.go new file mode 100644 index 000000000..ada5a5cc6 --- /dev/null +++ b/go/internal/telemetry/inverter_test.go @@ -0,0 +1,189 @@ +package telemetry + +import ( + "reflect" + "testing" + "testing/synctest" + "time" +) + +func inverterOf(t *testing.T, data string) InverterReading { + t.Helper() + r, err := ParseInverterReading([]byte(data)) + if err != nil { + t.Fatalf("parse %s: %v", data, err) + } + return r +} + +func TestParseInverterReadingKeepsWhatTheDeviceReports(t *testing.T) { + r := inverterOf(t, `{"W":-4200,"available_import_W":0,"available_export_W":3800,"Hz":50.01}`) + if r.W == nil || *r.W != -4200 || r.AvailableImportW == nil || *r.AvailableImportW != 0 || + r.AvailableExportW == nil || *r.AvailableExportW != 3800 || string(r.Data) == "" { + t.Fatalf("canonical names: %+v", r) + } + if r := inverterOf(t, `{"w":1200}`); r.W == nil || *r.W != 1200 || r.AvailableImportW != nil || r.AvailableExportW != nil { + t.Fatalf("catalog spelling: %+v", r) + } + // The driver guide drops a power outside 0 to 100 kW. A missing, + // null or misspelt field stays missing, never 0, and Blixt's exact + // names are the only ones read. + for _, data := range []string{ + `{"W":0,"available_import_W":-50,"available_export_W":100001}`, + `{"W":0}`, + `{"W":0,"available_import_W":null,"available_export_W":null}`, + `{"W":0,"available_import_W":"0","available_export_W":true}`, + `{"W":0,"available_import_w":0,"Available_Export_W":0}`, + `{"W":0,"available_import_W":1e999}`, + } { + if r := inverterOf(t, data); r.AvailableImportW != nil || r.AvailableExportW != nil { + t.Fatalf("%s kept headroom %+v", data, r) + } + } + // One bad field never costs the others. + for _, data := range []string{`{"W":"high","available_import_W":0}`, `{"W":1e999,"available_import_W":0}`, `{"W":null,"available_import_W":0}`} { + if r := inverterOf(t, data); r.W != nil || r.AvailableImportW == nil || *r.AvailableImportW != 0 { + t.Fatalf("%s: %+v", data, r) + } + } + if _, err := ParseInverterReading([]byte(`[1]`)); err == nil { + t.Fatal("not an object, accepted") + } +} + +// The inverter stream is the AC side of energy the battery and PV readings +// already carry. Storing it must change nothing that sums site power: the +// live and history balance, the per-type reads dispatch uses, and the +// samples that reach history. +func TestInverterReadingNeverChangesSitePower(t *testing.T) { + seed := func() *Store { + s := NewStore() + for _, d := range []string{"meter", "hybrid"} { + s.EnsureDriverHealth(d) + } + s.Update("meter", DerMeter, 1800, nil, []byte(`{"power_origin":"external_meter"}`)) + soc := 0.5 + s.Update("hybrid", DerBattery, 3600, &soc, nil) + s.Update("hybrid", DerPV, -2400, nil, nil) + s.RecordDriverSuccess("meter") + s.RecordDriverSuccess("hybrid") + s.FlushSamples() + return s + } + plain, with := seed(), seed() + with.UpdateInverter("hybrid", inverterOf(t, `{"W":-9000,"available_import_W":0,"available_export_W":0,"L1_W":-3000}`), 1) + + opts := ForecastOptions{} + if a, b := plain.LiveMeasurementNow("meter", opts), with.LiveMeasurementNow("meter", opts); a.LoadW != b.LoadW || a.PVW != b.PVW || + a.LoadKnown != b.LoadKnown || len(a.Sources) != len(b.Sources) || a.Reason != b.Reason { + t.Fatalf("live balance moved: %+v vs %+v", a, b) + } + if a, b := plain.ForecastMeasurementNow("meter", opts), with.ForecastMeasurementNow("meter", opts); a.Valid != b.Valid || + a.LoadW != b.LoadW || len(a.Sources) != len(b.Sources) { + t.Fatalf("history balance moved: %+v vs %+v", a, b) + } + for _, kind := range AllDerTypes() { + if a, b := plain.OnlineRawWByType(kind), with.OnlineRawWByType(kind); !reflect.DeepEqual(a, b) { + t.Fatalf("%s readings moved: %v vs %v", kind, a, b) + } + if a, b := len(plain.ReadingsByType(kind)), len(with.ReadingsByType(kind)); a != b { + t.Fatalf("%s reading count %d vs %d", kind, a, b) + } + } + if a, b := len(plain.ReadingsByDriver("hybrid")), len(with.ReadingsByDriver("hybrid")); a != b { + t.Fatalf("driver readings %d vs %d", a, b) + } + if a, b := plain.SumOnlineHigherW(DerBattery, DerPV, DerEV, DerV2X), with.SumOnlineHigherW(DerBattery, DerPV, DerEV, DerV2X); a != b { + t.Fatalf("site sum %v vs %v", a, b) + } + if got := with.FlushSamples(); len(got) != 0 { + t.Fatalf("the inverter reading reached history: %+v", got) + } +} + +// The pair is the driver poll, not a time window: a driver polled every +// second whose inverter read fails leaves a reading a second old, and that +// one never pairs with the new battery reading. +func TestLiveBatteryInverterComesWithTheBatteryReading(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + soc := 0.5 + headroom := inverterOf(t, `{"W":4000,"available_import_W":0}`) + poll := func(s *Store, n uint64, battery, inverter bool) { + time.Sleep(time.Second) + if battery { + s.UpdateFromPoll("hybrid", DerBattery, 3600, &soc, nil, n) + } + if inverter { + s.UpdateInverter("hybrid", headroom, n) + } + s.RecordDriverSuccess("hybrid") + } + s := NewStore() + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("nothing emitted, yet live") + } + poll(s, 1, false, true) + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("live without a battery reading") + } + if _, ok := s.LiveInverter("hybrid"); !ok { + t.Fatal("the view lost a live driver's reading") + } + poll(s, 2, true, true) + r, ok := s.LiveBatteryInverter("hybrid") + if !ok || r.AvailableImportW == nil || *r.AvailableImportW != 0 || r.Driver != "hybrid" || r.Poll != 2 { + t.Fatalf("same poll: %+v %v", r, ok) + } + // The next poll's inverter read fails, a second later. + poll(s, 3, true, false) + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("an inverter reading from an earlier poll counted") + } + if _, ok := s.LiveInverter("hybrid"); !ok { + t.Fatal("the last known reading went missing from the view") + } + // The battery read fails while the inverter read answers. + poll(s, 4, false, true) + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("an inverter reading without this poll's battery reading counted") + } + // A driver that reads its inverter every other poll pairs on those + // polls only. + for n := uint64(5); n < 11; n++ { + poll(s, n, true, n%2 == 0) + if _, ok := s.LiveBatteryInverter("hybrid"); ok != (n%2 == 0) { + t.Fatalf("poll %d: paired %v", n, ok) + } + } + // Readings from outside a poll never pair. + poll(s, 0, true, true) + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("readings from outside a poll paired") + } + + poll(s, 12, true, true) + s.SetDriverDeviceFault("hybrid", true, "test") + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("live while the device reports a fault") + } + if _, ok := s.LiveInverter("hybrid"); ok { + t.Fatal("the view shows a faulted device's reading as live") + } + s.SetDriverDeviceFault("hybrid", false, "") + poll(s, 13, true, true) + s.DriverHealthMut("hybrid").SetOffline() + if _, ok := s.LiveBatteryInverter("hybrid"); ok { + t.Fatal("live while the driver is offline") + } + if _, ok := s.LiveInverter("hybrid"); ok { + t.Fatal("the view shows an offline driver's reading as live") + } + if _, ok := s.Inverter("hybrid"); !ok { + t.Fatal("the last known reading went missing") + } + s.Remove("hybrid") + if _, ok := s.Inverter("hybrid"); ok { + t.Fatal("a removed driver kept its inverter reading") + } + }) +} diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index af0d36c03..d9bfe20e8 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -94,6 +94,9 @@ type DerReading struct { SoCUpdatedAt time.Time // last SoC source observation (receipt time for legacy drivers) Data json.RawMessage UpdatedAt time.Time + // Poll is the driver poll the reading came from, as the driver host + // numbers them; 0 when it came outside a poll. + Poll uint64 } // DriverStatus describes the health of one driver. @@ -306,6 +309,9 @@ type Store struct { health map[string]*DriverHealth commands map[string]CommandEvidence controlObservations map[string][]ControlObservation + // inverters holds each driver's latest inverter stream reading, apart + // from readings so no site sum can include it (inverter.go). + inverters map[string]InverterReading processNoise float64 measurementNoise float64 @@ -352,6 +358,7 @@ func NewStore() *Store { readings: make(map[string]*DerReading), filters: make(map[string]*KalmanFilter1D), health: make(map[string]*DriverHealth), + inverters: make(map[string]InverterReading), latestMetric: make(map[string]metricSnap), born: time.Now(), processNoise: 100, // W of expected change between samples @@ -430,6 +437,12 @@ const BatterySoCMaxAge = 5 * time.Minute // Update feeds a new reading. Applies Kalman smoothing and stores both raw // and smoothed values. func (s *Store) Update(driver string, t DerType, rawW float64, soc *float64, data json.RawMessage) { + s.UpdateFromPoll(driver, t, rawW, soc, data, 0) +} + +// UpdateFromPoll is Update for a reading from driver poll number poll, so +// readings from one poll can be told apart from an earlier poll's. +func (s *Store) UpdateFromPoll(driver string, t DerType, rawW float64, soc *float64, data json.RawMessage, poll uint64) { if err := ValidateReading(t, rawW, soc); err != nil { return } @@ -492,6 +505,7 @@ func (s *Store) Update(driver string, t DerType, rawW float64, soc *float64, dat SoCUpdatedAt: socUpdatedAt, Data: data, UpdatedAt: now, + Poll: poll, } s.observeCommand(driver, t, rawW, data, now) @@ -929,6 +943,7 @@ func (s *Store) Remove(driver string) { delete(s.filters, k) } delete(s.health, driver) + delete(s.inverters, driver) for _, kind := range allDerTypes { delete(s.controlObservations, key(driver, kind)) } diff --git a/web/control-feedback-battery-limits.test.mjs b/web/control-feedback-battery-limits.test.mjs index c72488397..5a177d832 100644 --- a/web/control-feedback-battery-limits.test.mjs +++ b/web/control-feedback-battery-limits.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {controlStatus} from './control-feedback.js'; +import {readFileSync} from 'node:fs'; +import {controlNumbers, 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). @@ -43,6 +44,33 @@ test('a limit the battery reports explains itself', () => { 'The battery reports that it cannot take power now. FTW asked for 5.0 kW charge.'); }); +test('an inverter with no grid headroom left names the inverter', () => { + const shown = controlStatus(row({reason: 'battery_limit', limit_source: 'device', limit_kind: 'inverter_import', limit_w: 0})); + assert.equal(shown.title, 'Limited by the inverter'); + assert.equal(shown.text, 'The inverter reports that it can take no more from the grid now. FTW asked for 5.0 kW charge.'); + assert.equal(shown.next, ''); + assert.equal(shown.tone, 'neutral'); + const discharge = {sent_w: -5000, requested_w: -5000, actual_w: -3150, reason: 'battery_limit', limit_source: 'device', limit_kind: 'inverter_export'}; + assert.equal(controlStatus(row({...discharge, limit_w: 0})).text, + 'The inverter reports that it can send no more to the grid now. FTW asked for 5.0 kW discharge.'); + assert.equal(controlStatus(row({...discharge, limit_w: 60})).text, + 'The inverter reports that it can send only 60 W more to the grid now. FTW asked for 5.0 kW discharge.'); + // The battery's own report keeps the battery's words. + assert.equal(controlStatus(row({reason: 'battery_limit', limit_kind: 'battery_reported', limit_w: 3600})).title, 'Limited by the battery'); +}); + +// Core names each inverter limit it sets; each one has the inverter's words. +test('every inverter limit Core sets has words', () => { + const go = readFileSync(new URL('../go/internal/api/api_control_capability.go', import.meta.url), 'utf8'); + const kinds = [...new Set([...go.matchAll(/"(inverter_[a-z]+)"/g)].map(m => m[1]))].sort(); + assert.deepEqual(kinds, ['inverter_export', 'inverter_import']); + for (const limit_kind of kinds) { + const shown = controlStatus(row({reason: 'battery_limit', limit_kind, limit_w: 0})); + assert.equal(shown.title, 'Limited by the inverter', limit_kind); + assert.match(shown.text, /^The inverter reports that it can (take|send) no more /, limit_kind); + } +}); + 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'); @@ -51,13 +79,30 @@ test('a battery on standby still asks for a look', () => { assert.equal(shown.tone, 'warning'); }); +// srcfl/ftw-webapp#144 found both; the box keeps the app's words. +test('a reported limit without a target says what FTW asked for once', () => { + assert.equal(controlStatus(row({reason: 'battery_limit', sent_w: undefined, requested_w: undefined})).text, + 'The battery reports a limit below what FTW asked for.'); + assert.equal(controlStatus(row({reason: 'battery_limit'})).text, 'The battery reports a limit below the 5.0 kW charge FTW asked for.'); +}); + +test('a battery current limit is the battery\'s, not a charger\'s', () => { + const numbers = controlNumbers(row({reason: 'learned_limit', limit_kind: 'battery_current', limit_a: 22.4, sent_w: -5000})); + assert.deepEqual(numbers.find(([label]) => label === 'Battery current limit'), ['Battery current limit', '22 A']); + assert.ok(!numbers.some(([label]) => /Charger|car/.test(label)), JSON.stringify(numbers)); + const charger = controlNumbers({driver: 'easee', kind: 'ev', status: 'limited', reason: 'offered_current_lower', limit_a: 10}); + assert.deepEqual(charger.find(([, value]) => value === '10 A'), ['Charger lets the car take', '10 A']); +}); + 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}]) { + {reason: 'learned_limit', limit_kind: 'battery_current', limit_seen: 4}, {reason: 'device_standby', sent_w: undefined}, + {reason: 'battery_limit', limit_kind: 'inverter_import'}, {reason: 'battery_limit', limit_kind: 'inverter_export', sent_w: undefined}, + {reason: 'battery_limit', 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)); + assert.doesNotMatch(text, /_|undefined|NaN|null|cannot describe|\bthe the\b/, JSON.stringify(extra)); } }); diff --git a/web/control-feedback.js b/web/control-feedback.js index 58bbb9a7e..cee66281c 100644 --- a/web/control-feedback.js +++ b/web/control-feedback.js @@ -99,9 +99,7 @@ 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 'battery_limit': return batteryLimit(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)}.`; @@ -145,6 +143,20 @@ 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 device reports now: the battery's own, or its inverter's grid +// headroom in the order's direction (limit_w is the headroom left). +const inverterLimit = row => row.reason === 'battery_limit' && (row.limit_kind === 'inverter_import' || row.limit_kind === 'inverter_export'); +function batteryLimit(row) { + if (inverterLimit(row)) { + const more = num(row.limit_w) && row.limit_w >= 1 ? `only ${controlPower(row.limit_w)} more` : 'no more'; + const grid = row.limit_kind === 'inverter_import' ? `take ${more} from the grid` : `send ${more} to the grid`; + return `The inverter reports that it can ${grid} now. FTW asked for ${target(row)}.`; + } + return !num(row.limit_w) ? `The battery reports a limit below ${num(row.sent_w) ? `the ${target(row)}` : 'what'} 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)}.`; +} + // 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) { @@ -243,7 +255,7 @@ export function planNowWords(value) { export function controlStatus(row, live = true) { if (!live) return {title: 'Status not current', text: 'FTW has not reported for a while.', proof: '', next: 'Waiting for a fresh report.', tone: 'stale'}; - const title = REASON_TITLES[row.reason] || STATUS_TITLES[row.status] || 'Checking'; + const title = (inverterLimit(row) && 'Limited by the inverter') || REASON_TITLES[row.reason] || STATUS_TITLES[row.status] || 'Checking'; const tone = row.severity === 'alarm' ? 'alarm' : row.severity === 'warning' ? 'warning' : row.status === 'following' ? 'ok' : 'neutral'; return {title, text: sentence(row), proof: proofLine(row), next: nextStep(row), tone}; } @@ -320,7 +332,9 @@ export function controlNumbers(row, live = true) { if (num(row.dynamic_limit_a)) values.push(['Dynamic current setting', amps(row.dynamic_limit_a)]); else if (num(row.offered_a)) values.push(['Reported current setting', amps(row.offered_a)]); if (num(row.device_limit_a)) values.push(['Charger limit', amps(row.device_limit_a)]); - if (num(row.limit_a)) values.push([row.limited_by === 'load_balancer' ? 'Load balancing allows' : 'Charger lets the car take', amps(row.limit_a)]); + // limit_a is a charger's limit, or a battery's learned current limit. + if (num(row.limit_a)) values.push([row.kind === 'battery' ? 'Battery current limit' + : row.limited_by === 'load_balancer' ? 'Load balancing allows' : 'Charger lets the car take', amps(row.limit_a)]); const e = row.site_evidence; if (e && typeof e === 'object') { for (const [label, key] of [['Grid before', 'grid_before_w'], ['Grid after', 'grid_after_w']]) {