diff --git a/.changeset/read-only-shown.md b/.changeset/read-only-shown.md new file mode 100644 index 000000000..509efce34 --- /dev/null +++ b/.changeset/read-only-shown.md @@ -0,0 +1,21 @@ +--- +"ftw": patch +--- + +Say when FTW reads a charger, car, heat pump or battery but cannot control it. + +A driver that declares `read_only = true` used to show only a small +"telemetry only" badge in Settings, so an owner who added a Zaptec Go through +the read-only `zaptec_cloud` saw FTW accept the charger and never steer it, +with nothing to say why. Now the EV card, Settings → Devices, Settings → +Chargers, the device cards when adding one, the setup wizard and the advanced +charger panel say "FTW reads this charger but cannot control it", with the +driver's own reason when its description gives one. The EV card leaves out +Charge now and Pause charging for such a charger; a hold set before still +shows so it can be returned to the plan. A charger set to Observe only reads +the same way. + +`/api/drivers/catalog` entries carry `read_only_reason`, and `/api/loadpoints` +carries `driver_read_only` and `driver_read_only_reason`, taken from the +driver that runs. Meters, solar inverters and gateways that also read a +battery, such as Zap, get no note. No setting changes. diff --git a/go/internal/api/api_control_feedback.go b/go/internal/api/api_control_feedback.go index 8da4d47c9..51606da85 100644 --- a/go/internal/api/api_control_feedback.go +++ b/go/internal/api/api_control_feedback.go @@ -739,9 +739,14 @@ type loadpointFeedbackView struct { // level, and the box does not guess one (docs/cars.md). Level *float64 `json:"current_soc,omitempty"` ControlFeedback *ControlFeedback `json:"control_feedback,omitempty"` + // DriverReadOnly says the charger's driver reads it but cannot control + // it; DriverReadOnlyReason is the driver's own reason when it gives one. + DriverReadOnly bool `json:"driver_read_only,omitempty"` + DriverReadOnlyReason string `json:"driver_read_only_reason,omitempty"` } func (s *Server) loadpointsWithFeedback(states []loadpoint.State) []loadpointFeedbackView { + readOnly := s.readOnlyDrivers() feedback := s.controlFeedback(time.Now()) byDriver := map[string]*ControlFeedback{} for i := range feedback { @@ -752,6 +757,10 @@ func (s *Server) loadpointsWithFeedback(states []loadpoint.State) []loadpointFee out := make([]loadpointFeedbackView, 0, len(states)) for _, st := range states { view := loadpointFeedbackView{State: st, ControlFeedback: byDriver[st.DriverName]} + if e, ok := readOnly[st.DriverName]; ok { + view.DriverReadOnly = true + view.DriverReadOnlyReason = e.Reason + } if !st.SoCUnknown { level := st.CurrentSoC view.Level = &level diff --git a/go/internal/api/api_driver_read_only.go b/go/internal/api/api_driver_read_only.go new file mode 100644 index 000000000..c3399e127 --- /dev/null +++ b/go/internal/api/api_driver_read_only.go @@ -0,0 +1,129 @@ +package api + +import ( + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/drivers" +) + +// driverReadOnly is a configured driver whose device FTW reads but cannot +// control, with the reason the owner reads, when there is one. +type driverReadOnly struct { + Reason string +} + +// observeOnlyReason is the reason when the owner keeps FTW from steering the +// device with Observe only in Settings → Devices. +const observeOnlyReason = "Observe only is on for this device in Settings → Devices." + +// readOnlyDrivers maps each configured driver name to why FTW cannot control +// its device. A charger added through such a driver is accepted and shown, +// and FTW never steers it; the owner needs to be told so where they look at +// the charger, not left to guess. +// +// The fact comes from what runs: the registry's loaded driver and the +// owner's observe_only. The catalog entry of the file the driver runs gives +// the reason, and the fact too while the driver is not loaded. +func (s *Server) readOnlyDrivers() map[string]driverReadOnly { + out := map[string]driverReadOnly{} + if s.deps == nil || s.deps.Cfg == nil || s.deps.CfgMu == nil { + return out + } + s.deps.CfgMu.RLock() + configured := append([]config.Driver(nil), s.deps.Cfg.Drivers...) + s.deps.CfgMu.RUnlock() + for _, d := range configured { + if d.Name == "" { + continue + } + if d.ObserveOnly { + out[d.Name] = driverReadOnly{Reason: observeOnlyReason} + continue + } + readOnly, loaded := false, false + if s.deps.Registry != nil { + readOnly, loaded = s.deps.Registry.DeclaresReadOnly(d.Name) + } + if loaded && !readOnly { + continue + } + entry, found := cachedCatalogEntry(s.driverFile(d.Lua)) + if !loaded { + readOnly = found && entry.ReadOnly + } + if readOnly { + out[d.Name] = driverReadOnly{Reason: entry.ReadOnlyReason} + } + } + return out +} + +// driverFile is the file a configured lua path runs. A running config holds +// resolved absolute paths; a relative "drivers/..." path is looked up the +// way config.ResolveDriverPaths does: local override, then the owner's +// signed driver, then the release's own. +func (s *Server) driverFile(lua string) string { + if lua == "" || filepath.IsAbs(lua) { + return lua + } + bundled := s.deps.DriverDir + if bundled == "" { + bundled = filepath.Join(filepath.Dir(s.deps.ConfigPath), "drivers") + } + if rel, ok := strings.CutPrefix(filepath.ToSlash(lua), "drivers/"); ok { + for _, dir := range []string{s.deps.UserDriverDir, s.managedDriverDir()} { + if dir == "" { + continue + } + candidate := filepath.Join(dir, filepath.FromSlash(rel)) + if _, err := os.Stat(candidate); err == nil { + return candidate + } + } + return filepath.Join(bundled, filepath.FromSlash(rel)) + } + return filepath.Join(filepath.Dir(s.deps.ConfigPath), lua) +} + +// catalogFiles holds each driver file's DRIVER metadata by path, size and +// modification time. The loadpoint list is read on every status poll; a +// file is parsed again only after it changes, so an edit, a version switch +// or a new install shows on the next poll without scanning every driver. +var catalogFiles = struct { + sync.Mutex + byPath map[string]cachedCatalogFile +}{byPath: map[string]cachedCatalogFile{}} + +type cachedCatalogFile struct { + modTime time.Time + size int64 + entry drivers.CatalogEntry + ok bool +} + +// parseCatalogFile is drivers.ParseCatalogFile; tests count its calls. +var parseCatalogFile = drivers.ParseCatalogFile + +func cachedCatalogEntry(path string) (drivers.CatalogEntry, bool) { + if path == "" { + return drivers.CatalogEntry{}, false + } + info, err := os.Stat(path) + if err != nil { + return drivers.CatalogEntry{}, false + } + catalogFiles.Lock() + defer catalogFiles.Unlock() + if c, ok := catalogFiles.byPath[path]; ok && c.modTime.Equal(info.ModTime()) && c.size == info.Size() { + return c.entry, c.ok + } + entry, err := parseCatalogFile(path) + c := cachedCatalogFile{modTime: info.ModTime(), size: info.Size(), entry: entry, ok: err == nil} + catalogFiles.byPath[path] = c + return c.entry, c.ok +} diff --git a/go/internal/api/api_driver_read_only_test.go b/go/internal/api/api_driver_read_only_test.go new file mode 100644 index 000000000..be18a3872 --- /dev/null +++ b/go/internal/api/api_driver_read_only_test.go @@ -0,0 +1,191 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/srcfl/ftw/go/internal/config" + "github.com/srcfl/ftw/go/internal/drivers" + "github.com/srcfl/ftw/go/internal/loadpoint" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The Wall Connector's description at srcfl/device-drivers c4c39af. +const wallConnectorDescription = "Reads a Tesla Wall Connector Gen 3 on your network. FTW can read it but not control it: Tesla offers no way for another system to set its current. Control goes through the car (tesla_vehicle) or a charger FTW can control, such as one on OCPP." + +const wallConnectorReason = "Tesla offers no way for another system to set its current. Control goes through the car (tesla_vehicle) or a charger FTW can control, such as one on OCPP." + +func writeDriverFile(t *testing.T, dir, name string, readOnly bool, description string) string { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + src := fmt.Sprintf("DRIVER = {\n id = %q,\n capabilities = { \"ev\" },\n read_only = %t,\n description = %q,\n}\n"+ + "function driver_init(config) end\nfunction driver_poll() return 1000 end\n"+ + "function driver_command(action, w, cmd) return true end\nfunction driver_default_mode() end\n", + name, readOnly, description) + path := filepath.Join(dir, name+".lua") + if err := os.WriteFile(path, []byte(src), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +// chargerLoadpoints configures one loadpoint per driver and returns +// /api/loadpoints by loadpoint id. +func chargerLoadpoints(t *testing.T, deps *Deps, driverNames ...string) map[string]map[string]any { + t.Helper() + mgr := loadpoint.NewManager() + var cfgs []loadpoint.Config + for _, name := range driverNames { + cfgs = append(cfgs, loadpoint.Config{ID: "lp-" + name, DriverName: name, MinChargeW: 1380, MaxChargeW: 11000}) + } + mgr.Load(cfgs) + deps.Loadpoints = mgr + if deps.CfgMu == nil { + deps.CfgMu = &sync.RWMutex{} + } + s := New(deps) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/loadpoints", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String()) + } + var body struct { + Loadpoints []map[string]any `json:"loadpoints"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + byID := map[string]map[string]any{} + for _, lp := range body.Loadpoints { + byID[lp["id"].(string)] = lp + } + return byID +} + +// A charger whose driver only reads it says so on /api/loadpoints, with the +// driver's own reason when it gives one. A new owner added a Zaptec Go this +// way and FTW accepted it, never steered it and never said why. +func TestLoadpointsSayWhenTheChargerDriverOnlyReads(t *testing.T) { + bundled := t.TempDir() + writeDriverFile(t, bundled, "zaptec_cloud", true, "Zaptec Go via Zaptec Cloud.") + writeDriverFile(t, bundled, "wall", true, wallConnectorDescription) + writeDriverFile(t, bundled, "easee_cloud", false, "Easee via Cloud.") + cfg := &config.Config{Drivers: []config.Driver{ + {Name: "zaptec", Lua: "drivers/zaptec_cloud.lua"}, + {Name: "wall", Lua: "drivers/wall.lua"}, + {Name: "easee", Lua: "drivers/easee_cloud.lua"}, + {Name: "watched", Lua: "drivers/easee_cloud.lua", ObserveOnly: true}, + }} + byID := chargerLoadpoints(t, &Deps{Cfg: cfg, DriverDir: bundled}, "zaptec", "wall", "easee", "watched") + + if byID["lp-zaptec"]["driver_read_only"] != true { + t.Errorf("zaptec driver_read_only = %v, want true", byID["lp-zaptec"]["driver_read_only"]) + } + if _, ok := byID["lp-zaptec"]["driver_read_only_reason"]; ok { + t.Errorf("a product description is not a reason, got %v", byID["lp-zaptec"]["driver_read_only_reason"]) + } + if got := byID["lp-wall"]["driver_read_only_reason"]; got != wallConnectorReason { + t.Errorf("wall connector reason = %v", got) + } + if _, ok := byID["lp-easee"]["driver_read_only"]; ok { + t.Errorf("a controlling charger must not say read only: %v", byID["lp-easee"]) + } + // observe_only keeps FTW from steering the charger as surely as a + // read-only driver, so it reads the same, with the owner's own setting + // as the reason. + if byID["lp-watched"]["driver_read_only"] != true || byID["lp-watched"]["driver_read_only_reason"] != observeOnlyReason { + t.Errorf("observe-only charger = %v", byID["lp-watched"]) + } +} + +// A running config holds resolved absolute paths, and a driver in the user +// folder shadows the release's copy of the same name. The answer has to +// come from the file that runs. +func TestLoadpointReadOnlyFollowsTheFileThatRuns(t *testing.T) { + bundled := t.TempDir() + user := t.TempDir() + elsewhere := t.TempDir() + writeDriverFile(t, bundled, "zaptec_cloud", true, "Zaptec Go via Zaptec Cloud. Read-only: this copy has no control path written yet.") + writeDriverFile(t, user, "zaptec_cloud", false, "Zaptec Go via Zaptec Cloud, with control.") + writeDriverFile(t, bundled, "wall", false, "A copy that must not be read.") + absolute := writeDriverFile(t, elsewhere, "wall", true, wallConnectorDescription) + cfg := &config.Config{Drivers: []config.Driver{ + {Name: "zaptec", Lua: "drivers/zaptec_cloud.lua"}, + {Name: "wall", Lua: absolute}, + }} + byID := chargerLoadpoints(t, &Deps{Cfg: cfg, DriverDir: bundled, UserDriverDir: user}, "zaptec", "wall") + if _, ok := byID["lp-zaptec"]["driver_read_only"]; ok { + t.Errorf("the user folder's controlling copy runs, got %v", byID["lp-zaptec"]) + } + if byID["lp-wall"]["driver_read_only"] != true || byID["lp-wall"]["driver_read_only_reason"] != wallConnectorReason { + t.Errorf("absolute path = %v", byID["lp-wall"]) + } +} + +// The registry's loaded driver decides; the file only gives the reason. A +// file edited after the driver loaded does not change what the box does +// until the driver reloads, so it must not change what the box says. +func TestLoadpointReadOnlyAsksTheLoadedDriver(t *testing.T) { + dir := t.TempDir() + reg := drivers.NewRegistry(telemetry.NewStore()) + t.Cleanup(reg.ShutdownAll) + controls := writeDriverFile(t, dir, "controls", false, "Controls a charger.") + reads := writeDriverFile(t, dir, "reads", true, wallConnectorDescription) + for name, path := range map[string]string{"controls": controls, "reads": reads} { + if err := reg.Add(context.Background(), config.Driver{Name: name, Lua: path}); err != nil { + t.Fatal(err) + } + } + writeDriverFile(t, dir, "controls", true, "Edited after it loaded. Read-only: not yet reloaded by the box.") + writeDriverFile(t, dir, "reads", false, "Edited after it loaded, with control.") + cfg := &config.Config{Drivers: []config.Driver{{Name: "controls", Lua: controls}, {Name: "reads", Lua: reads}}} + byID := chargerLoadpoints(t, &Deps{Cfg: cfg, Registry: reg}, "controls", "reads") + if _, ok := byID["lp-controls"]["driver_read_only"]; ok { + t.Errorf("the loaded driver controls, got %v", byID["lp-controls"]) + } + if byID["lp-reads"]["driver_read_only"] != true { + t.Errorf("the loaded driver reads only, got %v", byID["lp-reads"]) + } +} + +// /api/loadpoints is read on every status poll. A driver file is parsed once +// and again only after it changes. +func TestLoadpointReadOnlyParsesADriverFileOnce(t *testing.T) { + dir := t.TempDir() + path := writeDriverFile(t, dir, "wall", true, wallConnectorDescription) + parses := 0 + orig := parseCatalogFile + parseCatalogFile = func(p string) (drivers.CatalogEntry, error) { + if p == path { + parses++ + } + return orig(p) + } + t.Cleanup(func() { parseCatalogFile = orig }) + cfg := &config.Config{Drivers: []config.Driver{{Name: "wall", Lua: path}}} + s := New(&Deps{Cfg: cfg, CfgMu: &sync.RWMutex{}}) + for i := 0; i < 3; i++ { + if got := s.readOnlyDrivers()["wall"].Reason; got != wallConnectorReason { + t.Fatalf("reason = %q", got) + } + } + if parses != 1 { + t.Fatalf("parsed %d times for three reads, want 1", parses) + } + writeDriverFile(t, dir, "wall", true, "Reads the charger. Read-only: the vendor offers no way to set its current from here.") + if got := s.readOnlyDrivers()["wall"].Reason; got != "The vendor offers no way to set its current from here." { + t.Fatalf("after an edit, reason = %q", got) + } + if parses != 2 { + t.Fatalf("parsed %d times, want 2 after one edit", parses) + } +} diff --git a/go/internal/drivers/catalog.go b/go/internal/drivers/catalog.go index 7e714ac37..4bfbedf7b 100644 --- a/go/internal/drivers/catalog.go +++ b/go/internal/drivers/catalog.go @@ -8,6 +8,8 @@ import ( "sort" "strconv" "strings" + "unicode" + "unicode/utf8" ) // CatalogEntry describes one available driver discovered in the drivers @@ -54,6 +56,10 @@ type CatalogEntry struct { // ReadOnly means the driver never accepts dispatch commands. The catalog // UI uses it to avoid presenting battery capacity as a control opt-in. ReadOnly bool `json:"read_only,omitempty"` + // ReadOnlyReason is why a read-only driver does not control, in the words + // of its own description. Empty when the description only says what the + // device is. See readOnlyReason. + ReadOnlyReason string `json:"read_only_reason,omitempty"` // ReadOnlyDeclared distinguishes an explicit false value from old metadata // that did not state whether the driver can control hardware. ReadOnlyDeclared bool `json:"-"` @@ -232,6 +238,9 @@ func parseCatalogEntry(path string) (CatalogEntry, error) { e.WSHosts = pickList(block, "ws_hosts") e.ConnectionDefaults = pickKVBlock(block, "connection_defaults") e.ReadOnly, e.ReadOnlyDeclared = pickOptionalBool(block, "read_only") + if e.ReadOnly { + e.ReadOnlyReason = readOnlyReason(e.Description) + } e.VerificationStatus = normalizeVerificationStatus(pickString(block, "verification_status")) e.VerifiedBy = pickList(block, "verified_by") e.VerifiedAt = pickString(block, "verified_at") @@ -290,17 +299,61 @@ func IsEVOrVehicleDriver(catalog []CatalogEntry, luaPath string) bool { // declares read_only=true. Control-pool construction uses this as a safety // boundary for read-only telemetry drivers such as Sourceful Zap. func IsReadOnlyDriver(catalog []CatalogEntry, luaPath string) bool { + e, ok := FindCatalogEntry(catalog, luaPath) + return ok && e.ReadOnly +} + +// FindCatalogEntry returns the catalog entry a configured lua path runs, +// matched by portable path first and then by file name, as +// IsEVOrVehicleDriver does. +func FindCatalogEntry(catalog []CatalogEntry, luaPath string) (CatalogEntry, bool) { if luaPath == "" { - return false + return CatalogEntry{}, false } wantPath := filepath.ToSlash(luaPath) wantFilename := filepath.Base(wantPath) for _, e := range catalog { if strings.EqualFold(e.Path, wantPath) || strings.EqualFold(e.Filename, wantFilename) { - return e.ReadOnly + return e, true } } - return false + return CatalogEntry{}, false +} + +// readOnlyWords are the words a description uses when it says why a driver +// does not control: "Read-only until a held-zero command is verified on +// hardware", "Tesla offers no way ... to set its current", "sends nothing +// back". The driver catalog page does the same in read_only_reason in +// tools/generate_site.py in srcfl/device-drivers; change the two together. +var readOnlyWords = regexp.MustCompile(`(?i)read[- ]?only|observ|\bcontrol(s|led|ling)?\b|\bcommand(s|ed)?\b|\bwrites?\b`) + +// readOnlyLeadIn is an opening that repeats what the owner already reads +// ("FTW reads this charger but cannot control it"), so the reason drops it. +var readOnlyLeadIn = regexp.MustCompile(`(?i)^(ftw can read it but not control it|read-only)\s*[:.]\s*`) + +// minReasonWords is the least a reason must keep after its lead-in to say +// more than "the driver never writes". +const minReasonWords = 5 + +// readOnlyReason keeps a description only when it talks about reading or +// control, starting at the sentence that does, without a lead-in that +// repeats the note, and with a capital first letter. "Zaptec Go / Go 2 / Pro +// via Zaptec Cloud" says what the device is, and sonnen's "Read-only." or +// zap's "The driver never writes." add nothing, so they give no reason. +func readOnlyReason(description string) string { + loc := readOnlyWords.FindStringIndex(description) + if loc == nil { + return "" + } + if i := strings.LastIndex(description[:loc[0]], ". "); i >= 0 { + description = description[i+2:] + } + reason := readOnlyLeadIn.ReplaceAllString(strings.TrimSpace(description), "") + if len(strings.Fields(reason)) < minReasonWords { + return "" + } + r, size := utf8.DecodeRuneInString(reason) + return string(unicode.ToUpper(r)) + reason[size:] } // normalizeVerificationStatus coerces the Lua string into one of the diff --git a/go/internal/drivers/catalog_test.go b/go/internal/drivers/catalog_test.go index 3135a1da2..23d0db25c 100644 --- a/go/internal/drivers/catalog_test.go +++ b/go/internal/drivers/catalog_test.go @@ -1,6 +1,7 @@ package drivers import ( + "fmt" "os" "path/filepath" "testing" @@ -195,3 +196,68 @@ func TestCatalogMyUplinkDeclaresAuthPostPath(t *testing.T) { } t.Fatal("myuplink missing from catalog") } + +// A read-only driver's description is its reason only when it says why, and +// without a lead-in that repeats the note the owner already reads. The +// descriptions are the drivers' own at srcfl/device-drivers c4c39af. +func TestLoadCatalogReadOnlyReason(t *testing.T) { + dir := t.TempDir() + driver := func(id, caps string, readOnly bool, description string) string { + return fmt.Sprintf("DRIVER = {\n id = %q,\n capabilities = { %s },\n read_only = %t,\n description = %q,\n}\n", + id, caps, readOnly, description) + } + files := map[string]string{ + "tesla_wall_connector.lua": driver("tesla_wall_connector", `"ev"`, true, + "Reads a Tesla Wall Connector Gen 3 on your network. FTW can read it but not control it: Tesla offers no way for another system to set its current. Control goes through the car (tesla_vehicle) or a charger FTW can control, such as one on OCPP."), + "tesla_cloud.lua": driver("tesla_cloud", `"vehicle"`, true, + "Reads a Tesla's charge level, limit, charging state and cable from Tesla's Fleet API. Read-only: Tesla accepts a command only when it is signed with a key paired to the car, and this driver cannot sign. Use tesla_vehicle (BLE) to start the car's charge, or a charger FTW can control."), + "sonnen.lua": driver("sonnen", `"battery"`, true, + "sonnenBatterie local JSON API v2: SoC + charge/discharge power. Read-only."), + "zap.lua": driver("zap", `"meter", "pv", "battery"`, true, + "P1/HAN site meter from a Sourceful Zap. Optionally read PV and battery telemetry from devices Zap already talks to. Prefer a native driver; use this when Zap is the only reader. The driver never writes."), + "zaptec_cloud.lua": driver("zaptec_cloud", `"ev"`, true, + "Zaptec Go / Go 2 / Pro via Zaptec Cloud. Email + password; optional charger serial."), + "huawei.lua": driver("huawei", `"battery", "meter", "pv"`, true, + "Huawei SUN2000 via Modbus TCP. Read-only until a held-zero command is verified on hardware."), + // A controlling driver never carries a read-only reason, whatever its + // description says. + "easee_cloud.lua": driver("easee_cloud", `"ev"`, false, + "Easee via Cloud. Read-only: this sentence must never reach the owner."), + } + for name, src := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0644); err != nil { + t.Fatal(err) + } + } + entries, err := LoadCatalog(dir) + if err != nil { + t.Fatalf("LoadCatalog: %v", err) + } + want := map[string]string{ + "tesla_wall_connector": "Tesla offers no way for another system to set its current. Control goes through the car (tesla_vehicle) or a charger FTW can control, such as one on OCPP.", + "tesla_cloud": "Tesla accepts a command only when it is signed with a key paired to the car, and this driver cannot sign. Use tesla_vehicle (BLE) to start the car's charge, or a charger FTW can control.", + "sonnen": "", + "zap": "", + "zaptec_cloud": "", + "huawei": "Read-only until a held-zero command is verified on hardware.", + "easee_cloud": "", + } + for _, e := range entries { + if got := e.ReadOnlyReason; got != want[e.ID] { + t.Errorf("%s ReadOnlyReason = %q, want %q", e.ID, got, want[e.ID]) + } + } + if got := readOnlyReason("Reads a car. read-only: the car takes no commands from this driver at all."); got != "The car takes no commands from this driver at all." { + t.Errorf("a lowercase reason must start with a capital, got %q", got) + } + wall, ok := FindCatalogEntry(entries, "drivers/tesla_wall_connector.lua") + if !ok || !wall.ReadOnly { + t.Fatalf("FindCatalogEntry(tesla_wall_connector) = %+v, %v; want the read-only entry", wall, ok) + } + if !IsReadOnlyDriver(entries, "sonnen.lua") || IsReadOnlyDriver(entries, "easee_cloud.lua") { + t.Error("IsReadOnlyDriver must follow FindCatalogEntry") + } + if _, ok := FindCatalogEntry(entries, ""); ok { + t.Error("an empty lua path must match nothing") + } +} diff --git a/go/internal/drivers/registry.go b/go/internal/drivers/registry.go index 8fb6dc8e1..5d7f4ecff 100644 --- a/go/internal/drivers/registry.go +++ b/go/internal/drivers/registry.go @@ -1479,6 +1479,20 @@ func (r *Registry) CanControl(name string) bool { return ok && !rd.readOnly && !rd.cfg.ObserveOnly } +// DeclaresReadOnly reports whether the loaded driver named name declares +// read_only = true in its DRIVER table. loaded is false when no driver of +// that name runs, so a caller can tell "reads only" from "not running"; +// CanControl answers false for both. +func (r *Registry) DeclaresReadOnly(name string) (readOnly, loaded bool) { + r.mu.Lock() + defer r.mu.Unlock() + rd, ok := r.rec[name] + if !ok { + return false, false + } + return rd.readOnly, true +} + // ControlStatus returns the command safety state for the current driver // generation without creating or changing any state. func (r *Registry) ControlStatus(name string) (DriverControlStatus, bool) { diff --git a/go/internal/drivers/registry_control_authority_test.go b/go/internal/drivers/registry_control_authority_test.go index b812d58b4..6863f2860 100644 --- a/go/internal/drivers/registry_control_authority_test.go +++ b/go/internal/drivers/registry_control_authority_test.go @@ -37,3 +37,36 @@ function driver_default_mode() end } } } + +// DeclaresReadOnly answers from the loaded driver, and says when none runs: +// the API must not report "reads only" for a charger whose driver is just +// restarting, nor "controls" for one that declares read_only. +func TestDeclaresReadOnlyFollowsLoadedDriver(t *testing.T) { + r := NewRegistry(telemetry.NewStore()) + t.Cleanup(r.ShutdownAll) + if readOnly, loaded := r.DeclaresReadOnly("charger"); readOnly || loaded { + t.Fatalf("missing driver: readOnly=%v loaded=%v", readOnly, loaded) + } + for _, tc := range []struct{ readOnly, observeOnly bool }{ + {true, false}, {false, false}, {false, true}, + } { + path := writeTestDriver(t, fmt.Sprintf(` +DRIVER = { id = "charger", capabilities = { "ev" }, read_only = %t } +function driver_init(config) end +function driver_poll() return 1000 end +function driver_command(action, w, cmd) return true end +function driver_default_mode() end +`, tc.readOnly)) + if err := r.Add(context.Background(), config.Driver{Name: "charger", Lua: path, ObserveOnly: tc.observeOnly}); err != nil { + t.Fatal(err) + } + // observe_only is the owner's setting, not the driver's declaration. + if readOnly, loaded := r.DeclaresReadOnly("charger"); readOnly != tc.readOnly || !loaded { + t.Fatalf("read_only=%v observe_only=%v: got readOnly=%v loaded=%v", tc.readOnly, tc.observeOnly, readOnly, loaded) + } + r.Remove("charger") + if _, loaded := r.DeclaresReadOnly("charger"); loaded { + t.Fatal("removed driver still reads as loaded") + } + } +} diff --git a/web/app.css b/web/app.css index d3708ad01..6302d3985 100644 --- a/web/app.css +++ b/web/app.css @@ -2290,6 +2290,15 @@ body.ftw-app .drv-version-detail { color: var(--fg-muted); font-size: 0.75rem; } +/* FTW reads this device but cannot control it. A plain sentence, set apart + so it is read before anyone relies on the device. */ +body.ftw-app .read-only-note { + border-left: 2px solid var(--accent-e, var(--fg-muted)); + color: var(--fg); + font-size: 0.8rem; + margin: 6px 0 10px; + padding: 2px 0 2px 8px; +} /* What changed in a version: a quiet link beside the prose, not a button. */ body.ftw-app .drv-version-changes { color: var(--accent-e, var(--fg-muted)); diff --git a/web/app.js b/web/app.js index 5b8c9ac4c..e98bab371 100644 --- a/web/app.js +++ b/web/app.js @@ -3184,6 +3184,21 @@ } else if (setupNote) { setupNote.remove(); } + // A charger whose driver only reads it: the plan and the charge buttons + // below cannot move it, so the modal says so first. + var readOnlyNote = evModalBody.querySelector(".ev-read-only-note"); + var readOnly = window.FTWDriverControl ? window.FTWDriverControl.loadpointNote(matched) : null; + if (readOnly) { + if (!readOnlyNote) { + readOnlyNote = document.createElement("p"); + readOnlyNote.className = "ev-read-only-note read-only-note"; + readOnlyNote.setAttribute("role", "status"); + evModalBody.insertBefore(readOnlyNote, evModalBody.firstChild); + } + readOnlyNote.textContent = window.FTWDriverControl.sentence(readOnly); + } else if (readOnlyNote) { + readOnlyNote.remove(); + } // Plan view: what the box will do with this car (one sentence + // the planned windows on a 24 h track) and the car's charge level, // which the plan is built from. Mounted once per loadpoint so the @@ -4683,7 +4698,13 @@ container.appendChild(goal); container.update = function (nextLp, d) { - manual.el.hidden = !nextLp.plugged_in; + // A charger FTW only reads gets no Charge now or Pause charging: they + // cannot work, and showing them says FTW controls it. The note at the + // top of the sheet says why. A hold left from before still shows, so + // it can be returned to the plan. + var readOnlyIdle = nextLp.driver_read_only === true && !nextLp.manual_active && + !nextLp.manual_restore_unconfirmed; + manual.el.hidden = !nextLp.plugged_in || readOnlyIdle; manual.update(nextLp, d); retentionError.hidden = nextLp.goal_retention !== "error"; var s = nextLp.schedule; diff --git a/web/driver-control.js b/web/driver-control.js new file mode 100644 index 000000000..838f8ae76 --- /dev/null +++ b/web/driver-control.js @@ -0,0 +1,64 @@ +// Whether FTW can control a configured device, in the words every view uses. +// +// Core states the facts: a catalog entry's read_only, capabilities and +// read_only_reason, or a loadpoint's driver_read_only and +// driver_read_only_reason. This file only chooses the words, so Settings, +// setup and the EV card say the same thing. +// +// A new owner added a Zaptec Go through a read-only driver. FTW accepted the +// charger and never controlled it, and nothing on the box said why. +(function () { + 'use strict'; + + // Kinds an owner expects FTW to steer, with the word for each. A meter, a + // solar inverter, or a gateway or hybrid inverter that also reads a + // battery (Zap, SMA, Fronius) is complete when FTW only reads it, so it + // gets no note. A battery counts only when it is the driver's main job: + // the driver reads no solar. + var KINDS = [ + ['ev', 'charger'], + ['v2x_charger', 'charger'], + ['vehicle', 'car'], + ['heatpump', 'heat pump'], + ]; + + function kindWord(caps) { + for (var i = 0; i < KINDS.length; i++) { + if (caps.indexOf(KINDS[i][0]) >= 0) return KINDS[i][1]; + } + if (caps.indexOf('battery') >= 0 && caps.indexOf('pv') < 0) return 'battery'; + return null; + } + + // {label, text, reason} for a read-only driver of a kind FTW would + // otherwise control; null for everything else. + function readOnlyNote(entry) { + if (!entry || entry.read_only !== true) return null; + var word = kindWord(entry.capabilities || []); + if (!word) return null; + return { + label: 'reads only', + text: 'FTW reads this ' + word + ' but cannot control it.', + reason: typeof entry.read_only_reason === 'string' ? entry.read_only_reason.trim() : '', + }; + } + + // The note as one line of text, the driver's own reason after it. Core + // has already dropped a reason that only repeats the note. + function sentence(note) { + if (!note) return ''; + return note.reason ? note.text + ' ' + note.reason : note.text; + } + + // A loadpoint carries the facts under its own names; it is always a charger. + function loadpointNote(lp) { + if (!lp) return null; + return readOnlyNote({ + read_only: lp.driver_read_only === true, + capabilities: ['ev'], + read_only_reason: lp.driver_read_only_reason, + }); + } + + window.FTWDriverControl = { readOnlyNote: readOnlyNote, loadpointNote: loadpointNote, sentence: sentence }; +})(); diff --git a/web/driver-control.test.mjs b/web/driver-control.test.mjs new file mode 100644 index 000000000..0fa1b08b8 --- /dev/null +++ b/web/driver-control.test.mjs @@ -0,0 +1,166 @@ +// node --test web/driver-control.test.mjs +// +// Whether FTW can control a device, said where people choose and look at it. +// A new owner added a Zaptec Go through a read-only driver; FTW accepted the +// charger, never controlled it and never said why. + +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { describe, it } from 'node:test'; + +globalThis.window = {}; +await import('./driver-control.js'); +await import('./settings/tabs/loadpoints.js'); +const words = window.FTWDriverControl; +const S = window.FTWSettings; + +const read = path => readFileSync(new URL(path, import.meta.url), 'utf8'); +const escHtml = s => String(s).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"'); + +// Reasons as Core serves them for drivers at srcfl/device-drivers c4c39af: +// the lead-in that repeats the note is gone, and sonnen and zap give none. +const WALL_REASON = 'Tesla offers no way for another system to set its current. Control goes through the car (tesla_vehicle) or a charger FTW can control, such as one on OCPP.'; +const TESLA_CLOUD_REASON = "Tesla accepts a command only when it is signed with a key paired to the car, and this driver cannot sign. Use tesla_vehicle (BLE) to start the car's charge, or a charger FTW can control."; + +describe('the words for a read-only driver', () => { + it('names a charger, a car and a heat pump, and gives the driver its own reason', () => { + const zaptec = words.readOnlyNote({ read_only: true, capabilities: ['ev'] }); + assert.equal(words.sentence(zaptec), 'FTW reads this charger but cannot control it.'); + const wall = words.readOnlyNote({ read_only: true, capabilities: ['ev'], read_only_reason: WALL_REASON }); + assert.equal(words.sentence(wall), 'FTW reads this charger but cannot control it. ' + WALL_REASON); + const car = words.readOnlyNote({ read_only: true, capabilities: ['vehicle'], read_only_reason: TESLA_CLOUD_REASON }); + assert.equal(words.sentence(car), 'FTW reads this car but cannot control it. ' + TESLA_CLOUD_REASON); + assert.match(words.sentence(words.readOnlyNote({ read_only: true, capabilities: ['heatpump'] })), /reads this heat pump/); + }); + + it('names a battery only when the battery is the driver\'s main job', () => { + // sonnen at c4c39af: battery only, and no reason left after "Read-only.". + assert.equal(words.sentence(words.readOnlyNote({ read_only: true, capabilities: ['battery'], read_only_reason: '' })), + 'FTW reads this battery but cannot control it.'); + assert.match(words.sentence(words.readOnlyNote({ read_only: true, capabilities: ['battery', 'meter'] })), /reads this battery/); + // Zap, SMA and Fronius read a battery beside solar and the meter. FTW + // reading them is no surprise, so they carry no note. + assert.equal(words.readOnlyNote({ read_only: true, capabilities: ['meter', 'pv', 'battery'] }), null); + assert.equal(words.readOnlyNote({ read_only: true, capabilities: ['battery', 'meter', 'pv'] }), null); + }); + + it('says nothing for a driver that controls, or a meter or solar inverter that is only read', () => { + assert.equal(words.readOnlyNote({ read_only: false, capabilities: ['ev'] }), null); + assert.equal(words.readOnlyNote({ capabilities: ['ev'] }), null); + assert.equal(words.readOnlyNote({ read_only: true, capabilities: ['meter'] }), null); + assert.equal(words.readOnlyNote({ read_only: true, capabilities: ['meter', 'pv'] }), null); + assert.equal(words.readOnlyNote(null), null); + assert.equal(words.sentence(null), ''); + }); + + it('reads a loadpoint by its own field names', () => { + assert.equal(words.loadpointNote({ driver_read_only: false }), null); + assert.equal(words.loadpointNote(null), null); + assert.equal(words.sentence(words.loadpointNote({ driver_read_only: true, driver_read_only_reason: WALL_REASON })), + 'FTW reads this charger but cannot control it. ' + WALL_REASON); + assert.equal(words.sentence(words.loadpointNote({ driver_read_only: true })), + 'FTW reads this charger but cannot control it.'); + }); +}); + +describe('Settings → Chargers', () => { + const render = config => S.tabs.loadpoints.render({ config, escHtml, help: () => '' }); + const config = () => ({ + drivers: [ + { name: 'zaptec', lua: 'drivers/zaptec_cloud.lua' }, + { name: 'easee', lua: 'drivers/easee_cloud.lua' }, + ], + loadpoints: [{ id: 'drive', driver_name: 'zaptec' }, { id: 'street', driver_name: 'easee' }], + }); + + it('says on the charger card, and in the charger list, that FTW cannot control a read-only charger', () => { + S.ocppStatus = { enabled: false, chargers: [] }; + S.catalogByLua = { + 'drivers/zaptec_cloud.lua': { capabilities: ['ev'], read_only: true }, + 'drivers/easee_cloud.lua': { capabilities: ['ev'] }, + }; + const html = render(config()); + assert.match(html, /data-charger-read-only="0" role="note">FTW reads this charger but cannot control it\.zaptec \(reads only\)<\/option>/); + assert.match(html, /