Repository navigation
feat: EV cloud driver improvements — observations API, provider patte… - #72
Conversation
There was a problem hiding this comment.
Pull request overview
This PR improves EV charger/cloud driver integration end-to-end: it upgrades the Easee cloud driver polling API, introduces an evcloud provider interface for listing chargers, adds API endpoints for EV status/commands/charger discovery, and updates the web UI to support connecting/selecting chargers and a live EV detail modal on the dashboard.
Changes:
- Add
evcloudprovider abstraction with an Easee implementation and a new/api/ev/chargersendpoint for charger discovery. - Add dashboard EV detail modal with
/api/ev/status+/api/ev/commandwiring for live status and Start/Pause/Resume actions. - Normalize driver path handling (resolve/unresolve) so the UI round-trips config-relative paths.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 11 comments.
Show a summary per file
| File | Description |
|---|---|
| web/settings.js | Adds “Connect” flow for cloud EV drivers and charger selection syncing into config. |
| web/index.html | Makes the EV card clickable and adds the EV detail modal markup. |
| web/app.js | Implements modal open/close, periodic refresh, and EV command dispatch from the dashboard. |
| go/internal/evcloud/evcloud.go | Introduces provider registry + interface for listing chargers. |
| go/internal/evcloud/easee.go | Adds Easee provider implementation (login + list chargers). |
| go/internal/config/config.go | Consolidates driver path resolving/unresolving and strips leading ../. |
| go/internal/api/api.go | Adds EV status/command/charger endpoints and returns un-resolved driver paths in GET config. |
| go/cmd/forty-two-watts/main.go | Wires driver registry into API deps and centralizes driver path resolution. |
| drivers/easee_cloud.lua | Switches to Easee observations endpoint and adjusts parsing/auto-detect. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Hi @erikarenhill — quick status report and a heads-up before we touch this branch. What's happened since you opened the PR:
What I'm planning to do now: Rebase your branch against current master, resolve conflicts conservatively (preserving your Let me know if you'd rather take this yourself — I'll back off. Otherwise I'll update here when it's green. |
570b329 to
b6a5c78
Compare
|
Done — branch has been force-pushed ( Conflict resolution (3 files):
Addressed from Copilot's review:
Not addressed (left as open discussions):
Tests green ( |
…rn, dashboard modal
Easee driver:
- Switch from deprecated /chargers/{id}/state to /state/{id}/observations
endpoint with specific observation IDs (power, mode, session energy)
- Parse wrapped {observations: [...]} response format
- Fix charger auto-detect field (use .id from chargers list)
EV cloud provider pattern:
- New evcloud package with Provider interface (ListChargers)
- Easee implementation self-registers via init()
- API dispatches by provider name, defaults to "easee"
Driver path fixes:
- Strip leading "../" from driver paths on config load
- GET /api/config returns config-relative paths (no ../ in UI)
- Consolidated ResolveDriverPaths/UnresolveDriverPaths methods
- InjectEVChargerDriver paths now properly resolved
Settings UI:
- Connect button on cloud driver cards loads chargers into dropdown
- Selected charger syncs to both driver config and ev_charger config
- Grid tariff label clarified as "excl. VAT"
Dashboard:
- Clickable EV card opens detail modal with live status and power
- Start/Pause/Resume buttons dispatch commands to the EV driver
- Modal auto-refreshes every 5s while open
- New /api/ev/status, /api/ev/command endpoints
- Driver registry wired into API deps for command dispatch
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
b6a5c78 to
4f3ad01
Compare
|
Rebased on master again (0.8.0 — the new Zap driver has landed). Only one conflict this time, in |
Three items in the 11-comment review are still outstanding after the earlier rebase — the rest were already addressed in b6a5c78 / 4f3ad01: - #3 EV card keyboard accessibility (web/index.html + web/app.js): add role="button", tabindex="0", aria-label, and Enter/Space key handler so the summary card can be activated without a mouse and is announced correctly by assistive tech. - #9 Hardcoded "easee" provider (web/settings.js): Connect button now derives the provider name from the driver's lua path (strip dirs, trailing "_cloud", ".lua"), falling back to "easee" when the driver config is missing or oddly named. Lets a second cloud driver slot in without touching the button. - #5 Missing tests for path normalization (config_test.go): cover stripLeadingDotDot, ResolveDriverPaths (relative / absolute-in-tree / absolute-out-of-tree / leading-"../"), and the full Resolve → Unresolve → Resolve round-trip. The round-trip test is the one that pins down Copilot #11 — absolute paths outside baseDir must stay absolute so the next Resolve doesn't strip a "../" from filepath.Rel and silently re-anchor the driver under baseDir. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Removes the wazero-based WASM driver path (drivers-wasm/ and wasm-drivers/ were already deleted; this commit sweeps the remaining Go/web/docs refs). Lua is now the only driver runtime — one less format for operators to reason about and no cross-compile step in deploys. Code-review follow-ups bundled in: - drivers/zap.lua — raise the fallback PV-reading cap from 1e6 W to 16 A × 3 φ × 230 V ≈ 11 kW when an inverter doesn't report rated_power_W, so a single garbage sample can't blow out the site PV aggregate. - drivers/easee_cloud.lua — log only the HTTP status prefix on login failure (the body has historically echoed submitted credentials); fix the "attempt to index nil global 'state'" crash by replacing every state.X reference with observation-ID lookups (OBS_DYN_CURRENT=48, OBS_REASON_NO_CUR=96, OBS_CABLE_LOCKED=103) and deriving is_online from op_mode != 0. - go/internal/drivers/registry.go — sameDriverConfig now uses reflect.DeepEqual on the Config map instead of the brittle JSON-marshal-and-compare that could false-positive on marshal errors. - go/internal/config/config.go — delete the dead InjectEVChargerDriver method and its orphan call-site comment in main.go. - web/app.js + web/index.html — EV modal gets role="dialog" / aria-modal, ESC-to-close, a focus trap across the four buttons, and focus is restored to the card when the modal closes. evCommand now awaits the POST via a promise chain and debounces all three action buttons while any is inflight so Pause→Resume can't double-fire. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The MPC plan chart previously autoscaled the power band to the largest plan/forecast sample it saw, which meant the y-axis re-interpreted every render — hard to eyeball magnitudes across runs. Fix it at the physical ceiling instead: fuse.max_amps × phases × voltage (e.g. 16 A × 3 φ × 230 V ≈ 11 kW) with 15% headroom to absorb transient peaks without clipping. plan.js now fetches /api/config alongside prices/forecast/mpc so it has access to fuse config. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ntion The Zap gateway normalizes inverter readings so pv.W is negative when generating. The driver was negating at the boundary on the assumption that generation came through as positive, which meant a site generating 2.7 kW of PV was emitting pv.w = +2745 W — the control loop then saw PV as additional household load and over-imported from the grid. Verified against a live gateway: house drawing net -33 W (barely exporting) while a SolarEdge inverter reports pv.W = -2745. For the site-convention math to balance (load = meter - pv ⇒ 2712 W), pv.W has to pass through unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
New scripts/install.sh gets a fresh Pi (or any Debian/Ubuntu box) from zero to a running forty-two-watts in one copy-pasted command: curl -fsSL https://raw.githubusercontent.com/frahlg/forty-two-watts/master/scripts/install.sh | bash The script installs Docker via get.docker.com, adds the current user to the docker group, creates ~/forty-two-watts/data/ owned by the in-container ftw user (uid 100/gid 101 — the bind-mount ownership footgun documented in Dockerfile), fetches docker-compose.yml, and starts the container. Every step is idempotent so it's safe to re-run for upgrades. docker-compose.yml gets refreshed to point at the pre-built GHCR image instead of the stale Rust-era 'home-ems: build: .' entry. Keeps network_mode: host so Modbus / MQTT / mDNS driver discovery works against LAN hardware. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Registry.Remove was stopping the driver goroutine but leaving the driver's entries in telemetry.Store intact — readings, Kalman filters, and the health map. Net effect: a user removes a driver from config.yaml (or it gets restarted on hot-reload) and the dashboard keeps rendering a card with frozen SmoothedW values from the final poll. The stale reading also leaks into top-level aggregates (ReadingsByType iterates everything it has, so a removed PV driver keeps double-counting pv_w against whatever is still reporting). New telemetry.Store.Remove(driver) method clears the readings/filters/ health for the named driver in one critical section. Registry.Remove calls it after the driver's runLoop has exited. TS-DB historical samples are untouched — those remain queryable for post-mortem. For a config-driven hot reload that RESTARTS a driver (capabilities or credentials change), the card will briefly disappear from the UI and reappear on the next successful poll — acceptable since the driver's smoothed state is being reset anyway. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
98bc8f5 refactored the power-band scale computation and accidentally dropped the `const plan = state.plan;` alias. Six later sections in render() — the predicted-zone shade, load forecast line, battery action band, plan battery bars, SoC line, and summary — still refer to `plan` directly, which became undefined. Every render threw a ReferenceError and the canvas stayed blank. Restore the alias and comment why it has to stay even though the immediate consumer (pMagMax) no longer uses it. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
buildMPC summed each battery's max_charge_w / max_discharge_w to get the planner's aggregate limit, with no awareness of the grid fuse. Result: a site with a 16 A / 11 kW fuse and the default easee+pixii battery config would plan to charge at 45 kW — physically impossible. The per-tick fuse guard in the control loop still clamps actuals to 11 kW, but the plan's SoC trajectory is already fiction, and every downstream decision (when to discharge into expensive slots, when to idle, total cost) is based on a future that can't happen. Clamp maxChg and maxDis to cfg.Fuse.MaxPowerW() before handing them to mpc.Params. The planner now produces trajectories the site can actually realise. Logs 'mpc: clamping MaxChargeW to fuse capacity requested_w=45500 fuse_w=11040' so operators can see the cap kick in. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 29 out of 30 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (1)
go/internal/config/config.go:576
SaveAtomicusesfilepath.Relunconditionally viarelDriverPath. For a driver Lua path that is absolute but outsidebaseDir(e.g./opt/drivers/x.lua),filepath.Relproduces a../-prefixed path. On the next load,ResolveDriverPathsstrips leading../and re-anchors the driver underbaseDir, corrupting the path. Consider reusingrelToBaseDir/UnresolveDriverPathshere (leave out-of-tree absolute paths untouched) so save→load is a stable roundtrip.
// SaveAtomic writes config to disk via tmp-file + rename. Safe from partial writes.
func SaveAtomic(path string, c *Config) error {
// Driver paths are resolved to absolute-ish paths at Load() time.
// Convert them back to config-relative before writing so that
// repeated save cycles don't accumulate extra "../" prefixes.
baseDir := filepath.Dir(path)
out := *c
if len(out.Drivers) > 0 {
drivers := make([]Driver, len(out.Drivers))
copy(drivers, out.Drivers)
for i := range drivers {
drivers[i].Lua = relDriverPath(baseDir, drivers[i].Lua)
}
out.Drivers = drivers
}
data, err := yaml.Marshal(&out)
if err != nil {
return fmt.Errorf("yaml marshal: %w", err)
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0644); err != nil {
return fmt.Errorf("write tmp: %w", err)
}
return os.Rename(tmp, path)
}
func relDriverPath(baseDir, p string) string {
if p == "" {
return ""
}
rel, err := filepath.Rel(baseDir, p)
if err != nil {
return p
}
return rel
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
The Easee provider hardcoded the production base URL and stored the http.Client as a package-level var, making it impossible to test without spinning up a real Easee account or monkey-patching. This also made it easy to miss that the timeout was set at all — the concern was raised in review based on the original version that used http.Post / http.DefaultClient. Refactor Easee into a struct with client + baseURL fields and wrap construction in NewEasee() (15 s default timeout, prod URL). WithHTTPClient / WithBaseURL return copies so tests can point at an httptest.Server cleanly. api.go is untouched — the Provider interface is unchanged. Three new tests, all using httptest.Server: - TestEaseeListChargers — happy path, verifies credentials are posted, bearer token is passed to /chargers, and the decoded list round-trips. - TestEaseeLoginRejectsBadCreds — a 401 from an upstream that echoes the submitted password in the body must NOT leak the password into the returned error message. Locks in the redaction behavior. - TestEaseeTimeoutBounded — a handler that stalls forever must not hang the caller: with a 200 ms client timeout, ListChargers returns within the 2 s test ceiling. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
postJson was updated to rethrow in .catch so evCommand could chain
.finally() and react to failures. Three pre-existing callers
(setTarget, setPeakLimit, setEvCharging) never attached a handler, so
any network hiccup now surfaces as "Uncaught (in promise)" in the
browser console. Add explicit .catch(() => {}) on each — postJson has
already logged the failure, so the callers genuinely don't care.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
@frahlg please have a testdrive of this branch, and review |
Easee: - redact_http_err() helper strips HTTP error bodies from log lines so Easee-echoed credentials (on 4xx validation failures) can't leak. Applied to login (was already redacted), do_refresh, get_chargers init-time, and get_observations poll. - phases is now read from config.phases (1/2/3, default 3). Hardcoded 3-phase previously under-requested by 3x on single-phase Easee Home installs — often landing below the 6 A minimum and silently halting the session. - ev_set_current now rounds rather than floors (so 4000 W / 3φ / 230 V ≈ 5.8 rounds to 6 A instead of flooring to 5 and being rejected), and clamps to the 0..32 A Easee band with anything in 1..5 normalised to 0 so we don't land in a "no current" no-op. Zap: - Discovery now latches after the first success. Meter-only Zap deploys were re-hitting /api/devices every 1 s, logging "no PV inverters found" forever. - P1 data-fetch failures no longer share the discovery backoff. A transient /api/devices/<sn>/data glitch was stalling the site meter fetch for up to 60 s and tripping the watchdog on every network hiccup. Introduced a p1_fail_count counter that retries each 1 s tick and only forces rediscovery after 10 consecutive failures (in case the Zap rebooted and the P1 serial rotated). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The plan chart's PV curve was reading from state.forecast (the raw weather-derived estimator). For operators diagnosing "why did the battery charge when the plan said idle?", what you actually want to see is the plan's internal pv_w — the number the optimiser used when deciding charge vs idle vs discharge. Plan actions already carry site-signed pv_w per slot; use it when a plan exists, keep the raw forecast as the fallback when no plan is running. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Unit tests for the action validation added earlier: confirms that both unknown actions and malformed requests return 400, and that every allowlisted action gets past the gate (verified via the 503 branch that fires when Registry is nil in the test setup). Prevents future regressions where a typo in the allowlist map or a reordered guard would let unknown actions slip through — the Lua command hook silently returns nil for unknowns, so the API would otherwise 200-OK a no-op. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Heads-up on a regression I found while adding a unit test for the action allowlist: Bisect against this branch:
Failure mode is deterministic: The PV reading never populates in the status endpoint. Likely fixes, in order of preference:
I'll leave this for you to pick. Doesn't block merge of the rest of the PR from my side, but CI on master would go red the moment this merges if e2e is wired into a pull-request workflow later. For reference: unit test for |
The catalog scan derived its path as dirname(configPath)/drivers, which in Docker resolves to /app/data/drivers (the bind-mounted data volume) while drivers actually ship at /app/drivers inside the image. The setup-wizard dropdown and Settings "Add from catalog" picker were both empty as a result, and any driver added via the wizard would fail to load on restart for the same reason. Add a -drivers flag with the old behaviour as its default, thread it through api.Deps.DriverDir + bootstrap, and point the Dockerfile CMD at /app/drivers. Local layouts (make dev) are unaffected. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The installer invoked `sudo docker compose pull/up -d`, which makes the Docker daemon emit the "run Docker as non-privileged user" notice. Since step 2 already adds the user to the docker group, we can execute via `sg docker -c ...` to pick up the new primary group without a relogin — no sudo needed for the container lifecycle. Also pre-install `uidmap` so `dockerd-rootless-setuptool.sh install` works out of the box instead of erroring on missing newuidmap/newgidmap. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The 3s warmup in setupStack was tuned for the WASM driver runtime. Lua's `driver_init` + first MQTT round-trip is slower and variable, so TestE2E_FullStack started reading /api/status before the ferroamp driver had emitted any telemetry — regression landed in 80e5ae4 when the e2e harness was flipped from WASM to Lua. Replace the sleep with a bounded 10s poll that exits as soon as pv_w becomes non-zero (signals MQTT round-trip is working). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The persisted-mode allowlist in main.go only covered the six non-planner Modes, so a UI-selected planner strategy (planner_self / planner_cheap / planner_arbitrage) was silently dropped on restart and the dashboard reverted to ModeSelfConsumption. /api/mode validates + saves all nine, but the restore path didn't match. Add the three planner variants to the restore switch, and — when the restored mode is a planner one — push the matching mpc.Mode into the live Service so the plan is built with the strategy the user actually picked instead of whatever cfg.planner.mode says in YAML. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Both charts read better full-width than squeezed into 50% of the row, even on wide desktops. Remove the >=1800px media query that re-enabled the side-by-side layout. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The grid was `repeat(4, 1fr)` — a leftover from when EV charging was a fourth slider. After that card was removed, the three remaining cards (Strategy, Grid target, Peak limit) each took 1/4 of the row and the rightmost quarter was empty space on desktop. Switch to `repeat(3, 1fr)` so each card takes 1/3. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rn, dashboard modal
Easee driver:
EV cloud provider pattern:
Driver path fixes:
Settings UI:
Dashboard: