wallmonitor 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2050 @@
1
+ /* Wall Connector Monitor — single-file frontend. No external dependencies.
2
+ All timestamps arrive as UTC epoch seconds and are rendered in the browser's
3
+ local timezone by one shared formatter, so every view agrees on the clock. */
4
+ "use strict";
5
+
6
+ /* ---------------- utilities ---------------- */
7
+
8
+ const $ = (sel, root) => (root || document).querySelector(sel);
9
+
10
+ function el(tag, attrs, ...children) {
11
+ const node = document.createElement(tag);
12
+ if (attrs) {
13
+ for (const [key, value] of Object.entries(attrs)) {
14
+ if (key === "class") node.className = value;
15
+ else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
16
+ else node.setAttribute(key, value);
17
+ }
18
+ }
19
+ for (const child of children.flat()) {
20
+ if (child == null) continue;
21
+ node.append(child.nodeType ? child : document.createTextNode(String(child)));
22
+ }
23
+ return node;
24
+ }
25
+
26
+ const pad = (num) => String(num).padStart(2, "0");
27
+ function fmtDT(ts) {
28
+ if (ts == null) return "—";
29
+ const date = new Date(ts * 1000);
30
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
31
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
32
+ }
33
+ function fmtT(ts) {
34
+ const date = new Date(ts * 1000);
35
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
36
+ }
37
+ function fmtDur(seconds) {
38
+ if (seconds == null) return "—";
39
+ seconds = Math.round(seconds);
40
+ const hours = Math.floor(seconds / 3600), mins = Math.floor((seconds % 3600) / 60), secs = seconds % 60;
41
+ if (hours) return `${hours}h ${pad(mins)}m`;
42
+ if (mins) return `${mins}m ${pad(secs)}s`;
43
+ return `${secs}s`;
44
+ }
45
+ function fmtNum(value, digits = 1) {
46
+ if (value == null || Number.isNaN(value)) return "—";
47
+ return Number(value).toLocaleString(undefined, { maximumFractionDigits: digits, minimumFractionDigits: 0 });
48
+ }
49
+ function cToF(celsius) {
50
+ return (celsius * 9) / 5 + 32;
51
+ }
52
+
53
+ async function getJSON(url) {
54
+ const res = await fetch(url);
55
+ if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
56
+ return res.json();
57
+ }
58
+
59
+ const CSSVAR = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
60
+ const COLORS = () => ({
61
+ s1: CSSVAR("--series-1"), s2: CSSVAR("--series-2"), s3: CSSVAR("--series-3"), s5: CSSVAR("--series-5"),
62
+ });
63
+
64
+ // Tesla doesn't document evse_state. Labels below are verified against this
65
+ // monitor's own telemetry on firmware 26.18.0 (cross-tab of a week of samples
66
+ // vs vehicle_connected/contactor_closed, ~132k samples):
67
+ // 1 — vehicle_connected false in all 35,785 samples; every unplug lands
68
+ // here. Verified.
69
+ // 4 — vehicle_connected true in all 31,009 samples, contactor always open.
70
+ // Pilot swings ±12 V (J1772 state B: vehicle present, not ready), vs
71
+ // state 9's low pilot levels — consistent with the car asleep, hence
72
+ // "idle", but the asleep reading itself is inference. Verified as
73
+ // connected-not-charging.
74
+ // 9 — contactor open at ~0 W in all 53,148 samples. Verified. (Community
75
+ // lists 9 as "Charging" and 11 as "Charging paused", i.e. swapped.)
76
+ // 11 — contactor closed, full power, in all 12,021 samples. Verified.
77
+ // Contradicted community labels: 7 ("Error") appeared only as a benign 5-6 s
78
+ // plug-in transient (1 → 7 → 11, charging started normally) — same handshake
79
+ // slot where 2 and 3 also occur; too few samples to verify a meaning, but not
80
+ // an error state. 5 ("Scheduled charging") never appeared even with a
81
+ // vehicle-side scheduled charge armed overnight — the charger just sat in
82
+ // 9/4; the schedule lives in the car. 8 never appeared even during a real
83
+ // thermal derate (the charger stayed in 11 and signaled via alert 40 only).
84
+ // evse_not_ready_reasons are likewise undocumented; observed correlations:
85
+ // [4,8] when no vehicle, narrowing to [4] during the plug-in handshake, then
86
+ // [1] whenever a vehicle is connected (including while charging) — meanings
87
+ // unverified, so the UI shows the raw codes.
88
+ const EVSE_STATES = {
89
+ 0: "Booting", 1: "Standby — no vehicle", 2: "Vehicle detected", 3: "Ready",
90
+ 4: "Connected, idle", 5: "Scheduled charging", 6: "Negotiating", 7: "Plug-in transition",
91
+ 8: "Charging (de-rated)", 9: "Connected, not charging", 10: "Charging finished", 11: "Charging",
92
+ };
93
+ const EVSE_VERIFIED = new Set([1, 4, 9, 11]);
94
+ const evseLabel = (state) => state == null ? "—" : `${EVSE_STATES[state] || "State"} (${state})`;
95
+
96
+ // kind -> [human label, severity chip class]. Unknown kinds render as their
97
+ // raw name in muted — new server-side kinds degrade visibly, never crash.
98
+ const EVENT_META = {
99
+ session_start: ["Session started", "good"],
100
+ session_end: ["Session ended", "muted"],
101
+ charging_start: ["Charging started", "good"],
102
+ charging_stop: ["Charging stopped", "muted"],
103
+ alert_raised: ["Alert raised", "critical"],
104
+ alert_cleared: ["Alert cleared", "good"],
105
+ evse_state_change: ["EVSE state change", "muted"],
106
+ evse_not_ready_change: ["Not-ready reasons changed", "muted"],
107
+ charger_reboot: ["Charger rebooted", "serious"],
108
+ poll_error: ["Charger unreachable", "critical"],
109
+ poll_recovered: ["Charger reachable again", "good"],
110
+ wifi_disconnected: ["Wi-Fi disconnected", "serious"],
111
+ wifi_reconnected: ["Wi-Fi reconnected", "good"],
112
+ internet_lost: ["Internet connectivity lost", "warning"],
113
+ internet_restored: ["Internet connectivity restored", "good"],
114
+ firmware_changed: ["Firmware version changed", "warning"],
115
+ monitor_start: ["Monitor started", "muted"],
116
+ monitor_stop: ["Monitor stopped", "muted"],
117
+ monitor_gap: ["Monitoring gap — service was off", "warning"],
118
+ thermal_drift: ["Handle heat rise increasing vs baseline", "serious"],
119
+ thermal_drift_cleared: ["Handle heat rise back to baseline", "good"],
120
+ derate_warning: ["Derate predicted — lower charge current", "serious"],
121
+ derate_warning_cleared: ["Derate no longer predicted", "good"],
122
+ amp_capped: ["Charge current capped (auto)", "warning"],
123
+ amp_restored: ["Charge current stepped up (auto)", "good"],
124
+ amp_adjust_failed: ["Charge-current change failed", "serious"],
125
+ };
126
+ const eventLabel = (kind) => (EVENT_META[kind] || [kind, "muted"])[0];
127
+ const eventSeverity = (kind) => (EVENT_META[kind] || [kind, "muted"])[1];
128
+
129
+ /* ---------------- alert decoding ---------------- */
130
+
131
+ // Loaded once from /api/alert-codes. Tesla doesn't document the numeric codes
132
+ // the charger reports in current_alerts, so only verified entries are labeled;
133
+ // everything else renders honestly as an undocumented code.
134
+ let alertCodes = null;
135
+ async function loadAlertCodes() {
136
+ if (alertCodes) return alertCodes;
137
+ try { alertCodes = await getJSON("/api/alert-codes"); } catch { alertCodes = { codes: {}, categories: [] }; }
138
+ return alertCodes;
139
+ }
140
+
141
+ const UNDOCUMENTED_HINT =
142
+ "undocumented code — open the Tesla app while this alert is active to see its name, then add it to alert_codes.json";
143
+
144
+ function alertDisplay(alertStr, source) {
145
+ const alertText = String(alertStr);
146
+ const known = alertCodes && alertCodes.codes && alertCodes.codes[alertText];
147
+ if (known) {
148
+ return {
149
+ label: known.label,
150
+ sub: `code ${alertText} — ${known.description}${known.verified ? "" : " (community-reported, unverified)"}`,
151
+ };
152
+ }
153
+ const numeric = /^\d+$/.test(alertText);
154
+ if (numeric) return { label: `Alert code ${alertText}`, sub: UNDOCUMENTED_HINT };
155
+ // Monitor/wifi alerts (and any string alerts) are already human-readable.
156
+ return { label: alertText, sub: source === "device" ? UNDOCUMENTED_HINT : null };
157
+ }
158
+
159
+ /* ------------- unified vitals sample (DB row or SSE message) ------------- */
160
+
161
+ // 255 (0xFF) is the device's "sensor read invalid" sentinel for temperatures.
162
+ const realTemp = (value) => (value != null && value >= 255 ? null : value);
163
+
164
+ // Community-observed (not Tesla-published) circuit-board temperature at which
165
+ // the Gen 3 begins throttling charge current. Shown as a reference line so
166
+ // headroom is visible; ambient-driven foldback in hot installs is the usual
167
+ // cause of a real event. See the Alerts page notes.
168
+ const PCBA_THROTTLE_C = 95;
169
+ // Handle temperature that raises alert 40 and halves charge current
170
+ // (observed on firmware 26.18.0 — see alert_codes.json).
171
+ const HANDLE_TRIP_C = 65;
172
+ // Handle temperature below which an active alert 40 clears.
173
+ const HANDLE_CLEAR_C = 60;
174
+
175
+ // The two sample normalizers: /api/vitals rows and SSE vitals frames use
176
+ // different key names (db columns vs raw device JSON); both funnel into one
177
+ // shape so every chart and tile reads the same fields regardless of origin.
178
+ function fromDbRow(row) {
179
+ return {
180
+ ts: row.ts, power: row.total_power_w, maxPower: row.max_power_w,
181
+ iv: row.vehicle_current_a,
182
+ ia: row.current_a_a, ib: row.current_b_a, ic: row.current_c_a,
183
+ va: row.voltage_a_v, vb: row.voltage_b_v, vc: row.voltage_c_v,
184
+ gridV: row.grid_v, gridHz: row.grid_hz,
185
+ tPcba: realTemp(row.pcba_temp_c), tHandle: realTemp(row.handle_temp_c), tMcu: realTemp(row.mcu_temp_c),
186
+ energy: row.session_energy_wh, connected: !!row.vehicle_connected,
187
+ charging: !!row.contactor_closed, evse: row.evse_state, sessionId: row.session_id,
188
+ pilotHigh: row.pilot_high_v, pilotLow: row.pilot_low_v, prox: row.prox_v,
189
+ relayK1: row.relay_k1_v, relayK2: row.relay_k2_v,
190
+ };
191
+ }
192
+ function fromSse(msg) {
193
+ const data = msg.data || {};
194
+ return {
195
+ ts: msg.ts, power: msg.total_power_w,
196
+ iv: data.vehicle_current_a,
197
+ ia: data.currentA_a, ib: data.currentB_a, ic: data.currentC_a,
198
+ va: data.voltageA_v, vb: data.voltageB_v, vc: data.voltageC_v,
199
+ gridV: data.grid_v, gridHz: data.grid_hz,
200
+ tPcba: realTemp(data.pcba_temp_c), tHandle: realTemp(data.handle_temp_c), tMcu: realTemp(data.mcu_temp_c),
201
+ energy: data.session_energy_wh, connected: !!data.vehicle_connected,
202
+ charging: !!data.contactor_closed, evse: data.evse_state, sessionId: msg.session_id,
203
+ sessionS: data.session_s, alerts: data.current_alerts || [],
204
+ notReady: data.evse_not_ready_reasons || [],
205
+ pilotHigh: data.pilot_high_v, pilotLow: data.pilot_low_v, prox: data.prox_v,
206
+ relayK1: data.relay_k1_v ?? data.relay_coil_v, relayK2: data.relay_k2_v,
207
+ };
208
+ }
209
+
210
+ /* ---------------- chart engine (SVG, crosshair tooltip) ---------------- */
211
+
212
+ const SVGNS = "http://www.w3.org/2000/svg";
213
+ function svg(tag, attrs) {
214
+ const node = document.createElementNS(SVGNS, tag);
215
+ for (const [key, value] of Object.entries(attrs || {})) node.setAttribute(key, value);
216
+ return node;
217
+ }
218
+
219
+ function niceTicks(min, max, count) {
220
+ if (!(isFinite(min) && isFinite(max))) return { ticks: [0, 1], min: 0, max: 1 };
221
+ if (min === max) { min -= 1; max += 1; }
222
+ const span = max - min;
223
+ const step0 = span / Math.max(1, count);
224
+ const mag = Math.pow(10, Math.floor(Math.log10(step0)));
225
+ const step = [1, 2, 2.5, 5, 10].map((mult) => mult * mag).find((candidate) => span / candidate <= count + 0.5) || 10 * mag;
226
+ const lo = Math.floor(min / step) * step;
227
+ const hi = Math.ceil(max / step) * step;
228
+ const ticks = [];
229
+ for (let value = lo; value <= hi + step / 2; value += step) ticks.push(Math.round(value * 1e6) / 1e6);
230
+ return { ticks, min: lo, max: hi };
231
+ }
232
+
233
+ function timeTickFormat(ts, spanS) {
234
+ if (spanS > 36 * 3600) {
235
+ const date = new Date(ts * 1000);
236
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
237
+ }
238
+ const date = new Date(ts * 1000);
239
+ return spanS <= 900 ? fmtT(ts) : `${pad(date.getHours())}:${pad(date.getMinutes())}`;
240
+ }
241
+
242
+ /* scatterChart(box, {series: [{name, color, points: [[x, y, title?]]}],
243
+ xLabel, height, digits}) — numeric x axis (not time), one dot per point.
244
+ Used where the relationship between two measured quantities is the story
245
+ (e.g. fitted heat rise vs window ambient), not their history. */
246
+ // scatterChart(box, {series: [{name, color, points: [[x, y, meta]]}], xLabel,
247
+ // height?, digits?, tip(meta, dataset) -> Node[]}) — numeric x axis, nearest-
248
+ // dot tooltip (custom content via opts.tip). Rebuilt from scratch per call.
249
+ function scatterChart(box, opts) {
250
+ box.style.minHeight = `${opts.height || 210}px`;
251
+ box.textContent = "";
252
+ box.classList.add("chart-box");
253
+ const series = (opts.series || []).map((dataset) => (
254
+ { ...dataset, points: dataset.points.filter((point) => point[0] != null && point[1] != null && isFinite(point[0]) && isFinite(point[1])) }
255
+ ));
256
+ const height = opts.height || 210;
257
+ const width = Math.max(320, box.clientWidth || 800);
258
+ const margin = { left: 48, right: 14, top: 12, bottom: 34 };
259
+ const pw = width - margin.left - margin.right, ph = height - margin.top - margin.bottom;
260
+ const allPts = series.flatMap((dataset) => dataset.points);
261
+ if (allPts.length < 2) {
262
+ box.append(el("div", { class: "empty" }, "Not enough fits yet — each completed charge adds a point"));
263
+ return;
264
+ }
265
+ const xt = niceTicks(Math.min(...allPts.map((p) => p[0])), Math.max(...allPts.map((p) => p[0])), 6);
266
+ const yt = niceTicks(Math.min(...allPts.map((p) => p[1])), Math.max(...allPts.map((p) => p[1])), 4);
267
+ const xOf = (value) => margin.left + ((value - xt.min) / (xt.max - xt.min || 1)) * pw;
268
+ const yOf = (value) => margin.top + ph - ((value - yt.min) / (yt.max - yt.min || 1)) * ph;
269
+ const root = svg("svg", { viewBox: `0 0 ${width} ${height}`, width, height });
270
+ for (const value of yt.ticks) {
271
+ root.append(svg("line", { x1: margin.left, x2: width - margin.right, y1: yOf(value), y2: yOf(value), stroke: "var(--grid)", "stroke-width": 1 }));
272
+ const label = svg("text", { x: margin.left - 6, y: yOf(value) + 3.5, "text-anchor": "end", class: "axis-text" });
273
+ label.textContent = fmtNum(value, 0);
274
+ root.append(label);
275
+ }
276
+ for (const value of xt.ticks) {
277
+ const label = svg("text", { x: xOf(value), y: height - 18, "text-anchor": "middle", class: "axis-text" });
278
+ label.textContent = fmtNum(value, 0);
279
+ root.append(label);
280
+ }
281
+ if (opts.xLabel) {
282
+ const label = svg("text", { x: margin.left + pw / 2, y: height - 4, "text-anchor": "middle", class: "axis-text" });
283
+ label.textContent = opts.xLabel;
284
+ root.append(label);
285
+ }
286
+ root.append(svg("line", { x1: margin.left, x2: width - margin.right, y1: margin.top + ph, y2: margin.top + ph, stroke: "var(--baseline)", "stroke-width": 1 }));
287
+ const dotInfo = [];
288
+ for (const dataset of series) {
289
+ for (const point of dataset.points) {
290
+ const cx = xOf(point[0]), cy = yOf(point[1]);
291
+ const dot = svg("circle", { cx: cx.toFixed(1), cy: cy.toFixed(1), r: 4.5, fill: dataset.color, "fill-opacity": 0.85 });
292
+ root.append(dot);
293
+ dotInfo.push({ cx, cy, dot, dataset, point });
294
+ }
295
+ }
296
+ box.append(root);
297
+
298
+ // Instant styled tooltip on the nearest dot (the SVG-native <title> is
299
+ // slow to appear and can't explain what a reading means). opts.tip(meta,
300
+ // dataset) supplies the content nodes; without it, x/y values are shown.
301
+ const tip = el("div", { class: "tooltip" });
302
+ box.append(tip);
303
+ const hit = svg("rect", { x: 0, y: 0, width, height, fill: "transparent" });
304
+ root.append(hit);
305
+ const resetDots = () => dotInfo.forEach((info) => { info.dot.setAttribute("r", 4.5); info.dot.setAttribute("fill-opacity", 0.85); });
306
+ function onMove(ev) {
307
+ const rect = root.getBoundingClientRect();
308
+ const px = ((ev.clientX - rect.left) / rect.width) * width;
309
+ const py = ((ev.clientY - rect.top) / rect.height) * height;
310
+ let best = null, bestDist = Infinity;
311
+ for (const info of dotInfo) {
312
+ const dist = Math.hypot(info.cx - px, info.cy - py);
313
+ if (dist < bestDist) { bestDist = dist; best = info; }
314
+ }
315
+ if (!best || bestDist > 28) {
316
+ tip.style.display = "none";
317
+ resetDots();
318
+ return;
319
+ }
320
+ resetDots();
321
+ best.dot.setAttribute("r", 6.5);
322
+ best.dot.setAttribute("fill-opacity", 1);
323
+ tip.textContent = "";
324
+ const nodes = opts.tip
325
+ ? opts.tip(best.point[2], best.dataset)
326
+ : [el("div", { class: "tt-row" }, el("span", { class: "tt-val" }, `${fmtNum(best.point[0], 1)}, ${fmtNum(best.point[1], 1)}`))];
327
+ for (const node of nodes) tip.append(node);
328
+ tip.style.display = "block";
329
+ const boxWidth = box.clientWidth, boxHeight = box.clientHeight;
330
+ const leftPx = (best.cx / width) * boxWidth;
331
+ const topPx = (best.cy / height) * boxHeight;
332
+ tip.style.left = `${Math.min(boxWidth - 240, Math.max(0, leftPx + 14))}px`;
333
+ tip.style.top = `${Math.max(4, Math.min(boxHeight - 120, topPx - 30))}px`;
334
+ }
335
+ hit.addEventListener("pointermove", onMove);
336
+ hit.addEventListener("pointerleave", () => { tip.style.display = "none"; resetDots(); });
337
+
338
+ if (series.length > 1) {
339
+ const legend = el("div", { class: "note" });
340
+ for (const dataset of series) {
341
+ const swatch = el("span", {}, "● ");
342
+ swatch.style.color = dataset.color;
343
+ legend.append(swatch, `${dataset.name} (${dataset.points.length}) `);
344
+ }
345
+ box.append(legend);
346
+ }
347
+ }
348
+
349
+ /* lineChart(box, {series, height, unit, digits, area, zeroBase, xFrom, xTo}) */
350
+ // lineChart(box, {series: [{name, color, points: [[ts, value]], dash?}],
351
+ // unit?, digits?, height?, area? (single series only), zeroBase?, xFrom?,
352
+ // xTo?, refLines?: [{value, label, below?}]}) — time-series lines with a
353
+ // shared crosshair tooltip and auto legend (≥ 2 series). Null/non-finite
354
+ // values are dropped per series (the path connects across gaps). Every call
355
+ // is a full teardown + redraw; there is no incremental update path, which is
356
+ // what makes 2 s live refreshes safe to reason about.
357
+ function lineChart(box, opts) {
358
+ // Reserve the chart's height before clearing so a live re-render never
359
+ // collapses the page and yanks the scroll position around.
360
+ box.style.minHeight = `${opts.height || 210}px`;
361
+ box.textContent = "";
362
+ box.classList.add("chart-box");
363
+ const series = (opts.series || []).map((dataset) => (
364
+ { ...dataset, points: dataset.points.filter((point) => point[1] != null && isFinite(point[1])) }
365
+ ));
366
+ const height = opts.height || 210;
367
+ const width = Math.max(320, box.clientWidth || 800);
368
+ const margin = { left: 48, right: 14, top: 12, bottom: 24 };
369
+ const pw = width - margin.left - margin.right, ph = height - margin.top - margin.bottom;
370
+
371
+ const allPts = series.flatMap((dataset) => dataset.points);
372
+ if (!allPts.length) {
373
+ box.append(el("div", { class: "empty" }, "No data in this range"));
374
+ return;
375
+ }
376
+ const xFrom = opts.xFrom ?? Math.min(...allPts.map((point) => point[0]));
377
+ const xTo = opts.xTo ?? Math.max(...allPts.map((point) => point[0]));
378
+ const spanS = Math.max(1, xTo - xFrom);
379
+ let yMin = Math.min(...allPts.map((point) => point[1]));
380
+ let yMax = Math.max(...allPts.map((point) => point[1]));
381
+ if (opts.zeroBase) yMin = Math.min(0, yMin);
382
+ // Reference lines (e.g. a thermal-foldback threshold) are drawn in-frame so
383
+ // the headroom between the live value and the limit is visible at a glance.
384
+ const refLines = opts.refLines || [];
385
+ for (const refLine of refLines) {
386
+ if (refLine.value > yMax) yMax = refLine.value;
387
+ if (refLine.value < yMin) yMin = refLine.value;
388
+ }
389
+ const yt = niceTicks(yMin, yMax, 4);
390
+ const xOf = (ts) => margin.left + ((ts - xFrom) / spanS) * pw;
391
+ const yOf = (value) => margin.top + ph - ((value - yt.min) / (yt.max - yt.min || 1)) * ph;
392
+
393
+ const root = svg("svg", { viewBox: `0 0 ${width} ${height}`, width, height });
394
+
395
+ // Label precision follows the tick step, so ticks never collapse into
396
+ // duplicate rounded values (e.g. 0.5 steps labelled "1, 1, 0, -1, -1").
397
+ const yStep = yt.ticks.length > 1 ? yt.ticks[1] - yt.ticks[0] : 1;
398
+ const tickDigits = Math.max(0, Math.min(3, -Math.floor(Math.log10(yStep) + 1e-9)));
399
+ for (const value of yt.ticks) {
400
+ root.append(svg("line", { x1: margin.left, x2: width - margin.right, y1: yOf(value), y2: yOf(value), stroke: "var(--grid)", "stroke-width": 1 }));
401
+ const label = svg("text", { x: margin.left - 6, y: yOf(value) + 3.5, "text-anchor": "end", class: "axis-text" });
402
+ label.textContent = fmtNum(value, tickDigits);
403
+ label.classList.add("axis-text");
404
+ root.append(label);
405
+ }
406
+ root.append(svg("line", { x1: margin.left, x2: width - margin.right, y1: margin.top + ph, y2: margin.top + ph, stroke: "var(--baseline)", "stroke-width": 1 }));
407
+
408
+ const nXTicks = Math.max(2, Math.min(6, Math.floor(pw / 110)));
409
+ for (let i = 0; i <= nXTicks; i++) {
410
+ const ts = xFrom + (spanS * i) / nXTicks;
411
+ const label = svg("text", { x: xOf(ts), y: height - 6, "text-anchor": i === 0 ? "start" : i === nXTicks ? "end" : "middle", class: "axis-text" });
412
+ label.textContent = timeTickFormat(ts, spanS);
413
+ root.append(label);
414
+ }
415
+
416
+ for (const dataset of series) {
417
+ if (!dataset.points.length) continue;
418
+ const pathData = dataset.points.map((point, idx) =>
419
+ `${idx ? "L" : "M"}${xOf(point[0]).toFixed(1)},${yOf(point[1]).toFixed(1)}`).join("");
420
+ if (opts.area && series.length === 1) {
421
+ const areaPath = pathData + `L${xOf(dataset.points[dataset.points.length - 1][0]).toFixed(1)},${yOf(yt.min).toFixed(1)}` +
422
+ `L${xOf(dataset.points[0][0]).toFixed(1)},${yOf(yt.min).toFixed(1)}Z`;
423
+ root.append(svg("path", { d: areaPath, fill: dataset.color, "fill-opacity": 0.1, stroke: "none" }));
424
+ }
425
+ const stroke = { d: pathData, fill: "none", stroke: dataset.color, "stroke-width": 2, "stroke-linejoin": "round", "stroke-linecap": "round" };
426
+ if (dataset.dash) stroke["stroke-dasharray"] = dataset.dash;
427
+ root.append(svg("path", stroke));
428
+ }
429
+
430
+ // Reference/threshold lines sit above the data, below the crosshair: a thin
431
+ // warning-toned solid line with a right-anchored label.
432
+ for (const refLine of refLines) {
433
+ const y = yOf(refLine.value);
434
+ if (y < margin.top || y > margin.top + ph) continue;
435
+ root.append(svg("line", {
436
+ x1: margin.left, x2: width - margin.right, y1: y, y2: y,
437
+ stroke: "var(--status-warning)", "stroke-width": 1, "stroke-opacity": 0.7,
438
+ }));
439
+ const refLabel = svg("text", { x: width - margin.right, y: refLine.below ? y + 12 : y - 4, "text-anchor": "end", class: "axis-text" });
440
+ refLabel.textContent = refLine.label;
441
+ refLabel.setAttribute("fill", "var(--status-warning)");
442
+ root.append(refLabel);
443
+ }
444
+
445
+ // Vertical rules (e.g. the now-line separating measured past from
446
+ // projected future) — same layer as refLines: above data, below crosshair.
447
+ for (const vline of opts.vlines || []) {
448
+ const x = xOf(vline.ts);
449
+ if (x < margin.left || x > width - margin.right) continue;
450
+ root.append(svg("line", {
451
+ x1: x, x2: x, y1: margin.top, y2: margin.top + ph,
452
+ stroke: "var(--baseline)", "stroke-width": 1, "stroke-dasharray": "4 3",
453
+ }));
454
+ if (vline.label) {
455
+ const vlabel = svg("text", { x: x + 4, y: margin.top + 10, class: "axis-text" });
456
+ vlabel.textContent = vline.label;
457
+ root.append(vlabel);
458
+ }
459
+ }
460
+
461
+ const cross = svg("line", { x1: 0, x2: 0, y1: margin.top, y2: margin.top + ph, stroke: "var(--baseline)", "stroke-width": 1, visibility: "hidden" });
462
+ root.append(cross);
463
+ const dots = series.map((dataset) => {
464
+ const dot = svg("circle", { r: 4, fill: dataset.color, stroke: "var(--surface-1)", "stroke-width": 2, visibility: "hidden" });
465
+ root.append(dot);
466
+ return dot;
467
+ });
468
+
469
+ box.append(root);
470
+
471
+ const tip = el("div", { class: "tooltip" });
472
+ box.append(tip);
473
+
474
+ const tsUnion = [...new Set(allPts.map((point) => point[0]))].sort((tsA, tsB) => tsA - tsB);
475
+ const hit = svg("rect", { x: margin.left, y: margin.top, width: pw, height: ph, fill: "transparent" });
476
+ root.append(hit);
477
+
478
+ function nearest(arr, target) {
479
+ let lo = 0, hi = arr.length - 1;
480
+ while (hi - lo > 1) { const mid = (hi + lo) >> 1; (arr[mid] < target ? (lo = mid) : (hi = mid)); }
481
+ return target - arr[lo] < arr[hi] - target ? arr[lo] : arr[hi];
482
+ }
483
+
484
+ function onMove(ev) {
485
+ const rect = root.getBoundingClientRect();
486
+ const px = ((ev.clientX - rect.left) / rect.width) * width;
487
+ const ts = nearest(tsUnion, xFrom + ((px - margin.left) / pw) * spanS);
488
+ const xPos = xOf(ts);
489
+ cross.setAttribute("x1", xPos); cross.setAttribute("x2", xPos);
490
+ cross.setAttribute("visibility", "visible");
491
+ tip.textContent = "";
492
+ const timeRow = el("div", { class: "tt-time" }, fmtDT(ts));
493
+ tip.append(timeRow);
494
+ series.forEach((dataset, idx) => {
495
+ let best = null;
496
+ for (const point of dataset.points) {
497
+ if (best === null || Math.abs(point[0] - ts) < Math.abs(best[0] - ts)) best = point;
498
+ }
499
+ if (!best || Math.abs(best[0] - ts) > spanS / 8) { dots[idx].setAttribute("visibility", "hidden"); return; }
500
+ dots[idx].setAttribute("cx", xOf(best[0])); dots[idx].setAttribute("cy", yOf(best[1]));
501
+ dots[idx].setAttribute("visibility", "visible");
502
+ const row = el("div", { class: "tt-row" });
503
+ const swatch = el("span", { class: "swatch" }); swatch.style.background = dataset.color;
504
+ row.append(swatch, el("span", { class: "tt-name" }, dataset.name),
505
+ el("span", { class: "tt-val" }, `${fmtNum(best[1], opts.digits ?? 1)}${opts.unit ? " " + opts.unit : ""}`));
506
+ tip.append(row);
507
+ });
508
+ tip.style.display = "block";
509
+ const boxWidth = box.clientWidth;
510
+ const leftPct = (xPos / width) * boxWidth;
511
+ tip.style.left = `${Math.min(boxWidth - 150, Math.max(0, leftPct + 12))}px`;
512
+ tip.style.top = "8px";
513
+ }
514
+ hit.addEventListener("pointermove", onMove);
515
+ hit.addEventListener("pointerleave", () => {
516
+ tip.style.display = "none";
517
+ cross.setAttribute("visibility", "hidden");
518
+ dots.forEach((dot) => dot.setAttribute("visibility", "hidden"));
519
+ });
520
+
521
+ if (series.length >= 2) {
522
+ const legend = el("div", { class: "legend" });
523
+ for (const dataset of series) {
524
+ const swatch = el("span", { class: "swatch" }); swatch.style.background = dataset.color;
525
+ legend.append(el("span", { class: "lkey" }, swatch, dataset.name));
526
+ }
527
+ box.append(legend);
528
+ }
529
+ }
530
+
531
+ /* barChart(box, {bars: [{label, value}], unit, digits, height}) — columns with
532
+ rounded caps, square baseline, per-bar hover tooltip. */
533
+ // barChart(box, {bars: [{label, value}], unit?, digits?, height?, seriesName?})
534
+ function barChart(box, opts) {
535
+ box.style.minHeight = `${opts.height || 220}px`;
536
+ box.textContent = "";
537
+ box.classList.add("chart-box");
538
+ const bars = opts.bars || [];
539
+ if (!bars.length) {
540
+ box.append(el("div", { class: "empty" }, "No data in this range yet — the chart fills in as history accumulates"));
541
+ return;
542
+ }
543
+ const height = opts.height || 220;
544
+ const width = Math.max(320, box.clientWidth || 800);
545
+ const margin = { left: 48, right: 14, top: 12, bottom: 24 };
546
+ const pw = width - margin.left - margin.right, ph = height - margin.top - margin.bottom;
547
+ const yt = niceTicks(0, Math.max(...bars.map((bar) => bar.value), 0.001), 4);
548
+ const yOf = (value) => margin.top + ph - (value / (yt.max || 1)) * ph;
549
+ const root = svg("svg", { viewBox: `0 0 ${width} ${height}`, width, height });
550
+
551
+ const yStep = yt.ticks.length > 1 ? yt.ticks[1] - yt.ticks[0] : 1;
552
+ const tickDigits = Math.max(0, Math.min(3, -Math.floor(Math.log10(yStep) + 1e-9)));
553
+ for (const value of yt.ticks) {
554
+ if (value < 0) continue;
555
+ root.append(svg("line", { x1: margin.left, x2: width - margin.right, y1: yOf(value), y2: yOf(value), stroke: "var(--grid)", "stroke-width": 1 }));
556
+ const lbl = svg("text", { x: margin.left - 6, y: yOf(value) + 3.5, "text-anchor": "end", class: "axis-text" });
557
+ lbl.textContent = fmtNum(value, tickDigits);
558
+ root.append(lbl);
559
+ }
560
+ root.append(svg("line", { x1: margin.left, x2: width - margin.right, y1: margin.top + ph, y2: margin.top + ph, stroke: "var(--baseline)", "stroke-width": 1 }));
561
+
562
+ const slot = pw / bars.length;
563
+ const barWidth = Math.min(24, Math.max(3, slot - 2));
564
+ const color = COLORS().s1;
565
+ const tip = el("div", { class: "tooltip" });
566
+ const baseY = margin.top + ph;
567
+ const labelEvery = Math.max(1, Math.ceil(bars.length / Math.floor(pw / 60)));
568
+
569
+ bars.forEach((bar, idx) => {
570
+ const xPos = margin.left + slot * idx + (slot - barWidth) / 2;
571
+ const topY = yOf(bar.value);
572
+ const barHeight = Math.max(0, baseY - topY);
573
+ const cornerRadius = Math.min(4, barWidth / 2, barHeight);
574
+ const pathData = barHeight <= 0
575
+ ? ""
576
+ : `M${xPos},${baseY} L${xPos},${topY + cornerRadius} Q${xPos},${topY} ${xPos + cornerRadius},${topY} L${xPos + barWidth - cornerRadius},${topY} ` +
577
+ `Q${xPos + barWidth},${topY} ${xPos + barWidth},${topY + cornerRadius} L${xPos + barWidth},${baseY} Z`;
578
+ const rect = pathData ? svg("path", { d: pathData, fill: color }) : null;
579
+ if (rect) root.append(rect);
580
+ if (idx % labelEvery === 0) {
581
+ const xLabel = svg("text", { x: xPos + barWidth / 2, y: height - 6, "text-anchor": "middle", class: "axis-text" });
582
+ xLabel.textContent = bar.label;
583
+ root.append(xLabel);
584
+ }
585
+ // Hit target spans the full slot height, wider than the mark.
586
+ const hit = svg("rect", { x: margin.left + slot * idx, y: margin.top, width: slot, height: ph, fill: "transparent" });
587
+ hit.addEventListener("pointermove", () => {
588
+ if (rect) rect.setAttribute("fill-opacity", "0.8");
589
+ tip.textContent = "";
590
+ tip.append(el("div", { class: "tt-time" }, bar.label));
591
+ const row = el("div", { class: "tt-row" });
592
+ const swatch = el("span", { class: "swatch" }); swatch.style.background = color;
593
+ row.append(swatch, el("span", { class: "tt-name" }, opts.seriesName || ""),
594
+ el("span", { class: "tt-val" }, `${fmtNum(bar.value, opts.digits ?? 1)}${opts.unit ? " " + opts.unit : ""}`));
595
+ tip.append(row);
596
+ tip.style.display = "block";
597
+ const boxWidth = box.clientWidth;
598
+ tip.style.left = `${Math.min(boxWidth - 150, Math.max(0, ((xPos + barWidth / 2) / width) * boxWidth + 10))}px`;
599
+ tip.style.top = "8px";
600
+ });
601
+ hit.addEventListener("pointerleave", () => {
602
+ if (rect) rect.removeAttribute("fill-opacity");
603
+ tip.style.display = "none";
604
+ });
605
+ root.append(hit);
606
+ });
607
+
608
+ box.append(root, tip);
609
+ }
610
+
611
+ /* timeBrush(box, {samples, range, win, onChange}) — an overview strip of the
612
+ session's power with a draggable selection window. Drag the handles to
613
+ resize, drag the middle to pan, drag on empty track to select fresh.
614
+ onChange(win|null) fires as the user drags; null = full range. */
615
+ // timeBrush(box, {samples, range: [t0, t1], win, onChange(win|null)}) — the
616
+ // draggable zoom strip under session-detail charts: drag a new window, move
617
+ // or resize the existing one, or clear it (onChange(null) = full range).
618
+ function timeBrush(box, opts) {
619
+ const HEIGHT = 64;
620
+ box.textContent = "";
621
+ box.classList.add("chart-box");
622
+ box.style.minHeight = `${HEIGHT}px`;
623
+ const width = Math.max(320, box.clientWidth || 800);
624
+ const margin = { left: 48, right: 14 };
625
+ const pw = width - margin.left - margin.right;
626
+ const [tFrom, tTo] = opts.range;
627
+ const span = Math.max(1, tTo - tFrom);
628
+ const xOf = (ts) => margin.left + ((ts - tFrom) / span) * pw;
629
+ const tsOf = (xPos) => tFrom + ((xPos - margin.left) / pw) * span;
630
+ const clampT = (ts) => Math.min(tTo, Math.max(tFrom, ts));
631
+ const MIN_WIN = Math.min(15, span / 4);
632
+ const color = COLORS().s1;
633
+
634
+ const root = svg("svg", { viewBox: `0 0 ${width} ${HEIGHT}`, width, height: HEIGHT, style: "touch-action:none" });
635
+ root.append(svg("rect", { x: margin.left, y: 4, width: pw, height: HEIGHT - 8, fill: "transparent", stroke: "var(--grid)", "stroke-width": 1 }));
636
+
637
+ // overview: total power as a compact area
638
+ const pts = (opts.samples || []).map((sample) => [sample.ts, sample.power])
639
+ .filter((point) => point[1] != null && isFinite(point[1]));
640
+ if (pts.length > 1) {
641
+ const vMax = Math.max(...pts.map((point) => point[1]), 1);
642
+ const yOf = (value) => (HEIGHT - 10) - (Math.max(0, value) / vMax) * (HEIGHT - 18);
643
+ const pathData = pts.map((point, idx) =>
644
+ `${idx ? "L" : "M"}${xOf(point[0]).toFixed(1)},${yOf(point[1]).toFixed(1)}`).join("");
645
+ root.append(svg("path", {
646
+ d: pathData + `L${xOf(pts[pts.length - 1][0]).toFixed(1)},${HEIGHT - 10}L${xOf(pts[0][0]).toFixed(1)},${HEIGHT - 10}Z`,
647
+ fill: color, "fill-opacity": 0.12, stroke: "none",
648
+ }));
649
+ root.append(svg("path", { d: pathData, fill: "none", stroke: color, "stroke-width": 1.5, "stroke-linejoin": "round" }));
650
+ }
651
+
652
+ // selection window
653
+ const winRect = svg("rect", { y: 4, height: HEIGHT - 8, fill: color, "fill-opacity": 0.14, stroke: color, "stroke-width": 1.5, rx: 3 });
654
+ const handleLeft = svg("rect", { y: HEIGHT / 2 - 12, width: 7, height: 24, rx: 3, fill: color, style: "cursor:ew-resize" });
655
+ const handleRight = svg("rect", { y: HEIGHT / 2 - 12, width: 7, height: 24, rx: 3, fill: color, style: "cursor:ew-resize" });
656
+ root.append(winRect, handleLeft, handleRight);
657
+
658
+ let win = opts.win ? [...opts.win] : null;
659
+ function draw() {
660
+ const [winStart, winEnd] = win || [tFrom, tTo];
661
+ const xStart = xOf(winStart), xEnd = xOf(winEnd);
662
+ winRect.setAttribute("x", xStart);
663
+ winRect.setAttribute("width", Math.max(1, xEnd - xStart));
664
+ winRect.setAttribute("stroke-opacity", win ? 1 : 0.35);
665
+ winRect.setAttribute("fill-opacity", win ? 0.14 : 0.04);
666
+ winRect.style.cursor = win ? "grab" : "crosshair";
667
+ handleLeft.setAttribute("x", xStart - 3.5);
668
+ handleRight.setAttribute("x", xEnd - 3.5);
669
+ handleLeft.style.display = handleRight.style.display = win ? "" : "none";
670
+ }
671
+ draw();
672
+
673
+ let mode = null, grabT = 0, winAtGrab = null;
674
+ function pxT(ev) {
675
+ const rect = root.getBoundingClientRect();
676
+ return tsOf(((ev.clientX - rect.left) / rect.width) * width);
677
+ }
678
+ root.addEventListener("pointerdown", (ev) => {
679
+ const ts = pxT(ev);
680
+ root.setPointerCapture(ev.pointerId);
681
+ if (win && ev.target === handleLeft) mode = "l";
682
+ else if (win && ev.target === handleRight) mode = "r";
683
+ else if (win && ts > win[0] && ts < win[1]) { mode = "move"; grabT = ts; winAtGrab = [...win]; }
684
+ else { mode = "new"; grabT = clampT(ts); win = [grabT, grabT]; }
685
+ ev.preventDefault();
686
+ });
687
+ root.addEventListener("pointermove", (ev) => {
688
+ if (!mode) return;
689
+ const ts = clampT(pxT(ev));
690
+ if (mode === "l") win[0] = Math.min(ts, win[1] - MIN_WIN);
691
+ else if (mode === "r") win[1] = Math.max(ts, win[0] + MIN_WIN);
692
+ else if (mode === "move") {
693
+ const dt = ts - grabT;
694
+ const winSpan = winAtGrab[1] - winAtGrab[0];
695
+ let newStart = winAtGrab[0] + dt;
696
+ newStart = Math.min(Math.max(newStart, tFrom), tTo - winSpan);
697
+ win = [newStart, newStart + winSpan];
698
+ } else if (mode === "new") {
699
+ win = grabT < ts ? [grabT, ts] : [ts, grabT];
700
+ }
701
+ draw();
702
+ });
703
+ root.addEventListener("pointerup", () => {
704
+ if (!mode) return;
705
+ if (mode === "new" && win && win[1] - win[0] < MIN_WIN) win = null; // a click clears
706
+ mode = null;
707
+ draw();
708
+ opts.onChange(win ? [...win] : null);
709
+ });
710
+
711
+ box.append(root);
712
+ }
713
+
714
+ function chartCard(title, sub) {
715
+ const box = el("div", { class: "chart-box" });
716
+ const card = el("div", { class: "chart-card" },
717
+ el("div", { class: "chart-title" }, title),
718
+ sub ? el("div", { class: "chart-sub" }, sub) : null,
719
+ box);
720
+ return { card, box };
721
+ }
722
+
723
+ function statTile(label, value, unit, sub) {
724
+ // Always render the sub element so callers can patch it after the fact.
725
+ return el("div", { class: "card" },
726
+ el("div", { class: "tile-label" }, label),
727
+ el("div", { class: "tile-value" }, value, unit ? el("span", { class: "unit" }, unit) : null),
728
+ el("div", { class: "tile-sub" }, sub ?? ""));
729
+ }
730
+
731
+ function presetRow(presets, activeKey, onPick) {
732
+ const row = el("div", { class: "filters" }, el("span", { class: "flabel" }, "Range"));
733
+ for (const preset of presets) {
734
+ row.append(el("button", { class: "chip" + (preset.key === activeKey ? " active" : ""), onclick: () => onPick(preset.key) }, preset.label));
735
+ }
736
+ return row;
737
+ }
738
+
739
+ /* ---------------- live connection state ---------------- */
740
+
741
+ const live = {
742
+ es: null,
743
+ listeners: new Set(),
744
+ lastMsgTs: 0,
745
+ status: null,
746
+ };
747
+
748
+ // One process-wide EventSource; views register a listener in live.listeners
749
+ // and remove it in their cleanup. Reconnection is the browser's native
750
+ // EventSource retry — the server sends no event ids, so views re-seed
751
+ // history over the JSON API on mount rather than expecting replay.
752
+ function connectSSE() {
753
+ if (live.es) return;
754
+ const es = new EventSource("/api/stream");
755
+ live.es = es;
756
+ es.onmessage = (ev) => {
757
+ let msg;
758
+ try { msg = JSON.parse(ev.data); } catch { return; }
759
+ live.lastMsgTs = Date.now() / 1000;
760
+ for (const fn of live.listeners) fn(msg);
761
+ if (msg.type === "event" || (msg.type === "vitals" && msg.data && (msg.data.current_alerts || []).length)) refreshStatus();
762
+ };
763
+ es.onerror = () => setConnDot(false, "stream reconnecting…");
764
+ }
765
+
766
+ function setConnDot(ok, text) {
767
+ const dot = $("#conn-dot"), textEl = $("#conn-text");
768
+ dot.className = "dot " + (ok ? "ok" : "bad");
769
+ textEl.textContent = text;
770
+ }
771
+
772
+ async function refreshStatus() {
773
+ try {
774
+ const st = await getJSON("/api/status");
775
+ live.status = st;
776
+ const poller = st.poller || {};
777
+ const stale = st.vitals ? (st.server_ts - st.vitals.ts) : null;
778
+ if (poller.offline) setConnDot(false, `charger unreachable (${poller.last_poll_error || "no response"})`);
779
+ else if (st.vitals) setConnDot(true, `charger online — last sample ${stale < 2 ? "now" : fmtDur(stale) + " ago"}`);
780
+ else setConnDot(false, "no data yet");
781
+ renderBanner(st.active_alerts || []);
782
+ const counts = st.counts || {};
783
+ $("#foot-info").textContent =
784
+ `${fmtNum(counts.vitals_samples, 0)} vitals samples · ${fmtNum(counts.sessions, 0)} sessions · ` +
785
+ `${fmtNum(counts.events, 0)} events recorded` + (poller.host ? ` · watching ${poller.host}` : "");
786
+ } catch {
787
+ setConnDot(false, "monitor unreachable");
788
+ }
789
+ }
790
+
791
+ function renderBanner(alerts) {
792
+ const holder = $("#alert-banner");
793
+ holder.textContent = "";
794
+ for (const alertItem of alerts) {
795
+ const sev = alertItem.source === "device" ? "critical" : alertItem.source === "wifi" ? "serious" : "critical";
796
+ const disp = alertDisplay(alertItem.alert, alertItem.source);
797
+ const label = el("span", {}, disp.label);
798
+ if (disp.sub) label.title = disp.sub;
799
+ holder.append(el("div", { class: "banner " + sev },
800
+ el("span", { class: "icon" }, "⚠"),
801
+ label,
802
+ el("span", { class: "when" }, `active since ${fmtDT(alertItem.first_ts)}`)));
803
+ }
804
+ }
805
+
806
+ /* ---------------- views ---------------- */
807
+
808
+ let cleanup = null;
809
+
810
+ async function viewLive(root) {
811
+ const colors = COLORS();
812
+ const tiles = el("div", { class: "cards" });
813
+ const sessionCard = el("div", {});
814
+ const thermalCard = el("div", {});
815
+ const fcast = chartCard("Derate forecast — live", "Waiting for data…");
816
+ const power = chartCard("Power", "Total power drawn by the vehicle — live");
817
+ const currents = chartCard("Phase currents", "Per-phase current at the charger — live");
818
+ root.append(tiles, sessionCard, thermalCard, fcast.card, power.card, currents.card);
819
+
820
+ // Seed the buffer from the DB — the last 15 minutes normally, or the whole
821
+ // session so far when a charge is in progress, so the session-pinned window
822
+ // (below) has its full history even after a reload mid-charge.
823
+ const now = Date.now() / 1000;
824
+ let seedFrom = now - 900;
825
+ try {
826
+ const st = live.status || (live.status = await getJSON("/api/status"));
827
+ const sess = st.active_session;
828
+ if (sess && sess.start_ts && st.vitals && st.vitals.contactor_closed) {
829
+ seedFrom = Math.min(seedFrom, sess.start_ts - 60);
830
+ }
831
+ } catch { /* no status yet — fall back to the rolling window */ }
832
+ let buf = [];
833
+ try {
834
+ const points = Math.min(5000, Math.ceil(now - seedFrom));
835
+ const hist = await getJSON(`/api/vitals?from=${seedFrom}&to=${now}&points=${points}`);
836
+ buf = hist.samples.map(fromDbRow);
837
+ } catch { /* fresh DB */ }
838
+
839
+ // Measured ambient for the same window. The stationary sensor outranks the
840
+ // car bridge here for the same reason it does in the thermal model.
841
+ const ambientRows = (rows) => {
842
+ const fixed = rows.filter((sample) => sample.source !== "car");
843
+ return (fixed.length ? fixed : rows).map((sample) => [sample.ts, sample.temp_c]);
844
+ };
845
+ let abuf = [];
846
+ try {
847
+ const amb = await getJSON(`/api/ambient?from=${seedFrom}&to=${now}`);
848
+ abuf = ambientRows(amb.samples || []);
849
+ } catch { /* no ambient feed yet */ }
850
+ // Forecast snapshots: one point per 30 s poller tick, seeded from the
851
+ // recorded history (so the prediction line survives tab switches and
852
+ // reloads) and then extended live by SSE thermal frames, with the 60 s
853
+ // /api/thermal poll as fallback. The prediction is session-scoped: it seeds
854
+ // only while a charge is running and is dropped when the charge ends.
855
+ // insufficient-basis ticks are recorded for fidelity but carry no
856
+ // chartable plateau — filter them exactly as pushThermal does, so every
857
+ // tbuf entry has a steady value the chart and sub-line rely on.
858
+ const tickFromRow = (row) => ({
859
+ ts: row.ts, steady: row.steady_state_c, willTrip: row.will_trip,
860
+ mtt: row.minutes_to_trip, basis: row.basis, suggested: row.suggested_max_a,
861
+ rmse: row.fit_rmse_c, trip: row.trip_c, tau: row.tau_min, tripTs: row.trip_ts,
862
+ });
863
+ let tbuf = [];
864
+ async function seedForecasts(from) {
865
+ const fc = await getJSON(`/api/forecasts?from=${from}&to=${Date.now() / 1000}`);
866
+ const rows = (fc.samples || []).filter((row) => row.steady_state_c != null).map(tickFromRow);
867
+ // Keep any live SSE ticks that arrived while the fetch was in flight.
868
+ const lastTs = rows.length ? rows[rows.length - 1].ts : -Infinity;
869
+ tbuf = rows.concat(tbuf.filter((point) => point.ts > lastTs + 1));
870
+ }
871
+ try {
872
+ if (buf.length && buf[buf.length - 1].charging) await seedForecasts(seedFrom);
873
+ } catch { /* server predates forecast recording */ }
874
+
875
+ // While a charge runs, the forecast chart pins its window to the start of
876
+ // the current charging stretch so the whole charge — measured lines and
877
+ // every prediction tick — stays on screen instead of scrolling off. The
878
+ // stretch is read from the buffer itself rather than the session record:
879
+ // a session spans plug-in to unplug, so an overnight top-off burst would
880
+ // otherwise pin the window back to the previous evening. A short grace
881
+ // keeps the pin through momentary contactor pauses (current ramps, brief
882
+ // vehicle pauses); once the charge is really over — grace expired with no
883
+ // charging sample — the view returns to the rolling 15-minute window.
884
+ const PIN_GRACE_S = 180;
885
+ function sessionAnchorTs() {
886
+ const last = buf.length ? buf[buf.length - 1] : null;
887
+ if (!last) return null;
888
+ let anchor = null;
889
+ let newer = last.ts;
890
+ for (let i = buf.length - 1; i >= 0; i--) {
891
+ const sample = buf[i];
892
+ // A hole in the samples longer than the grace also ends the stretch —
893
+ // without this, a buffer holding two bursts hours apart (or an SSE
894
+ // dropout) would let the walk jump the gap and over-extend the anchor.
895
+ if (newer - sample.ts > PIN_GRACE_S) break;
896
+ newer = sample.ts;
897
+ if (sample.charging) { anchor = sample.ts; continue; }
898
+ // Walking back from the newest charging sample found so far (or from
899
+ // the tail while still looking): a non-charging gap longer than the
900
+ // grace ends the stretch.
901
+ if ((anchor ?? last.ts) - sample.ts > PIN_GRACE_S) break;
902
+ }
903
+ return anchor;
904
+ }
905
+ function bufferCutoff() {
906
+ const rolling = Date.now() / 1000 - 960;
907
+ const pinned = sessionAnchorTs();
908
+ return pinned != null ? Math.min(pinned - 60, rolling) : rolling;
909
+ }
910
+
911
+ function renderTiles(sample) {
912
+ tiles.textContent = "";
913
+ const st = live.status || {};
914
+ tiles.append(
915
+ statTile("Power", fmtNum((sample.power ?? 0) / 1000, 2), "kW", sample.charging ? "charging" : sample.connected ? "connected, not charging" : "idle"),
916
+ statTile("Vehicle current", fmtNum(sample.iv ?? (sample.ia != null ? Math.max(sample.ia, sample.ib ?? 0, sample.ic ?? 0) : null), 1), "A"),
917
+ statTile("Grid", `${fmtNum(sample.gridV, 1)}`, "V", `${fmtNum(sample.gridHz, 3)} Hz`),
918
+ statTile("Session energy", fmtNum((sample.energy ?? 0) / 1000, 2), "kWh", sample.sessionId ? `session #${sample.sessionId}` : "no session"),
919
+ statTile("Plug handle temp", fmtNum(sample.tHandle, 1), "°C",
920
+ `circuit board ${fmtNum(sample.tPcba, 1)} °C · processor ${fmtNum(sample.tMcu, 1)} °C`),
921
+ statTile("EVSE state", "", null, ""),
922
+ );
923
+ const evseTile = tiles.lastChild;
924
+ evseTile.querySelector(".tile-value").textContent = evseLabel(sample.evse);
925
+ evseTile.querySelector(".tile-value").style.fontSize = "16px";
926
+ let notReady = sample.notReady;
927
+ if (notReady == null && st.vitals && st.vitals.raw) {
928
+ try { notReady = JSON.parse(st.vitals.raw).evse_not_ready_reasons || []; } catch { notReady = []; }
929
+ }
930
+ // This firmware reports evse_not_ready_reasons [1] persistently — on
931
+ // every connected sample, including while actively charging — so the
932
+ // codes only carry meaning when no power is flowing. Suppress them during
933
+ // charging rather than caption "Charging" with "not-ready reasons".
934
+ const showNotReady = !sample.charging && notReady && notReady.length;
935
+ evseTile.querySelector(".tile-sub").textContent =
936
+ (showNotReady ? `not-ready reason codes: ${notReady.join(", ")} — ` : "") +
937
+ (EVSE_VERIFIED.has(sample.evse)
938
+ ? "label verified from this charger's own telemetry; (n) is the charger's raw value"
939
+ : "label is community-reported, unverified — Tesla doesn't document these codes; (n) is the charger's raw value");
940
+ if (st.version) {
941
+ tiles.append(statTile("Firmware", "", null, ""));
942
+ const tile = tiles.lastChild;
943
+ tile.querySelector(".tile-value").textContent = st.version.firmware_version || "—";
944
+ tile.querySelector(".tile-value").style.fontSize = "15px";
945
+ tile.querySelector(".tile-sub").textContent = `S/N ${st.version.serial_number || "?"}`;
946
+ }
947
+ }
948
+
949
+ function renderSessionCard(sample) {
950
+ sessionCard.textContent = "";
951
+ if (!sample.sessionId) return;
952
+ const started = buf.find((entry) => entry.sessionId === sample.sessionId);
953
+ const startTs = (live.status && live.status.active_session && live.status.active_session.start_ts) || (started && started.ts);
954
+ sessionCard.append(el("div", { class: "chart-card" },
955
+ el("div", { class: "chart-title" }, `Live charging session #${sample.sessionId}`),
956
+ el("dl", { class: "kv" },
957
+ el("dt", {}, "Plugged in"), el("dd", {}, startTs ? `${fmtDT(startTs)} (${fmtDur(sample.ts - startTs)} ago)` : "—"),
958
+ el("dt", {}, "Energy this session"), el("dd", {}, `${fmtNum((sample.energy ?? 0) / 1000, 2)} kWh`),
959
+ el("dt", {}, "State"), el("dd", {}, evseLabel(sample.evse)),
960
+ el("dt", {}, "Device alerts"), el("dd", {},
961
+ (sample.alerts && sample.alerts.length) ? sample.alerts.map((alertId) => alertDisplay(alertId, "device").label).join(", ") : "none")),
962
+ el("div", { class: "note" }, "Full history for this session appears under Sessions once it ends — or open it live: "),
963
+ el("a", { href: `#/sessions/${sample.sessionId}` }, "open session detail")));
964
+ }
965
+
966
+ function renderCharts() {
967
+ const xTo = Date.now() / 1000;
968
+ const xFrom = xTo - 900;
969
+ const pts = buf.filter((sample) => sample.ts >= xFrom);
970
+ lineChart(power.box, {
971
+ series: [{ name: "Power (W)", color: colors.s1, points: pts.map((sample) => [sample.ts, sample.power]) }],
972
+ unit: "W", digits: 0, area: true, zeroBase: true, xFrom, xTo, height: 230,
973
+ });
974
+ lineChart(currents.box, {
975
+ series: [
976
+ { name: "Phase A", color: colors.s1, points: pts.map((sample) => [sample.ts, sample.ia]) },
977
+ { name: "Phase B", color: colors.s2, points: pts.map((sample) => [sample.ts, sample.ib]) },
978
+ { name: "Phase C", color: colors.s3, points: pts.map((sample) => [sample.ts, sample.ic]) },
979
+ ],
980
+ unit: "A", digits: 1, zeroBase: true, xFrom, xTo, height: 200,
981
+ });
982
+ }
983
+
984
+ function renderThermal(data) {
985
+ thermalCard.textContent = "";
986
+ const forecast = data.forecast, model = data.model || {};
987
+ let chip = null;
988
+ const lines = [];
989
+ if (data.state === "charging" && forecast && forecast.will_trip != null) {
990
+ if (forecast.will_trip && forecast.minutes_to_trip <= 0.5) {
991
+ chip = chipFor("critical", "at the derate threshold now");
992
+ } else if (forecast.will_trip) {
993
+ chip = chipFor("warning", `derate expected ≈ ${fmtT(forecast.trip_ts).slice(0, 5)} (in ~${fmtNum(forecast.minutes_to_trip, 0)} min)`);
994
+ lines.push(`Handle is at ${fmtNum(data.handle_c, 1)} °C and heading to ~${fmtNum(forecast.steady_state_c, 1)} °C — ` +
995
+ `alert 40 raises at ${fmtNum(model.trip_c, 0)} °C and halves the charge current for the rest of the session.`);
996
+ if (forecast.suggested_max_a) {
997
+ lines.push(`Capping the vehicle's charge current at ~${fmtNum(forecast.suggested_max_a, 0)} A now would stay under the limit — ` +
998
+ `a faster charge overall than riding it into the 50% foldback.`);
999
+ }
1000
+ } else {
1001
+ chip = chipFor("good", "no derate expected");
1002
+ lines.push(`Handle is at ${fmtNum(data.handle_c, 1)} °C, settling near ~${fmtNum(forecast.steady_state_c, 1)} °C — ` +
1003
+ `below the ${fmtNum(model.trip_c, 0)} °C alert-40 threshold.`);
1004
+ }
1005
+ lines.push(forecast.basis === "trajectory"
1006
+ ? "Based on the handle's temperature trajectory over the last few minutes."
1007
+ : forecast.ambient_source === "recent_trajectory"
1008
+ ? "Based on ambient inferred from the last steady stretch of charging — switches to the live trajectory once the current holds steady for a couple of minutes."
1009
+ : "Based on pre-session ambient and charge current — refines as the session warms up.");
1010
+ } else if (data.state === "charging") {
1011
+ lines.push(forecast && forecast.reason === "current_changed"
1012
+ ? "Charge current changed a moment ago — the forecast rebuilds after a couple of minutes at the new rate."
1013
+ : "Charging just started — the forecast needs a few minutes of steady data.");
1014
+ } else if (data.state === "idle" && forecast) {
1015
+ const amb = `${fmtNum(data.ambient_c, 1)} °C (${fmtNum(cToF(data.ambient_c), 0)} °F)`;
1016
+ const ambLabel = data.ambient_source === "measured"
1017
+ ? "Garage ambient (sensor)"
1018
+ : data.ambient_source === "measured_car"
1019
+ ? "Garage ambient (car sensor)" : "Ambient at the charger ≈";
1020
+ if (forecast.will_trip) {
1021
+ chip = chipFor("warning", "hot enough to derate");
1022
+ lines.push(`${ambLabel} ${amb}. A full-rate (${fmtNum(model.ref_current_a, 0)} A) charge started now ` +
1023
+ `would hit the ${fmtNum(model.trip_c, 0)} °C handle limit in ~${fmtNum(forecast.minutes_to_trip, 0)} min and drop to half current.`);
1024
+ if (forecast.suggested_max_a) {
1025
+ lines.push(`Setting the vehicle to ~${fmtNum(forecast.suggested_max_a, 0)} A before plugging in would avoid the derate ` +
1026
+ `and beat a full-rate start that folds back to ${fmtNum(model.ref_current_a / 2, 0)} A.`);
1027
+ }
1028
+ } else {
1029
+ chip = chipFor("good", "full-rate charging safe");
1030
+ lines.push(`${ambLabel} ${amb}. A full-rate (${fmtNum(model.ref_current_a, 0)} A) charge would settle ` +
1031
+ `near ~${fmtNum(forecast.steady_state_c, 1)} °C, below the ${fmtNum(model.trip_c, 0)} °C limit — derates start above ` +
1032
+ `~${fmtNum(forecast.safe_ambient_max_c, 0)} °C (${fmtNum(cToF(forecast.safe_ambient_max_c), 0)} °F) ambient.`);
1033
+ }
1034
+ if (data.ambient_stable === false) lines.push("Handle is still cooling from recent charging, so the ambient estimate reads high.");
1035
+ } else if (data.state === "connected") {
1036
+ lines.push("Vehicle connected but not charging — the forecast resumes when current flows.");
1037
+ } else {
1038
+ lines.push("No recent samples to forecast from.");
1039
+ }
1040
+ // Degradation watch: same fits, watched over time. Rising heat at the
1041
+ // same current means added resistance somewhere in the current path.
1042
+ const drift = data.drift;
1043
+ let driftLine = null;
1044
+ if (drift && drift.drifting) {
1045
+ driftLine = el("div", { class: "note" },
1046
+ chipFor("serious", "heat rise increasing"),
1047
+ ` Recent sessions average +${fmtNum(drift.recent_rise_c, 1)} °C at ${fmtNum(model.ref_current_a, 0)} A vs a ` +
1048
+ `+${fmtNum(drift.baseline_rise_c, 1)} °C baseline (Δ ${fmtNum(drift.delta_c, 1)} °C). More heat at the same current ` +
1049
+ `means added resistance — inspect the handle and charge-port pins, and have the terminal torque checked.` +
1050
+ (drift.off_current_n ? ` (${drift.off_current_n} session${drift.off_current_n === 1 ? "" : "s"} away from the usual ` +
1051
+ `~${fmtNum(drift.typical_current_a, 0)} A excluded from the comparison.)` : ""));
1052
+ }
1053
+ const modelNote = `Model: τ ≈ ${fmtNum(model.tau_min, 1)} min, +${fmtNum(model.rise_ref_c, 0)} °C at ${fmtNum(model.ref_current_a, 0)} A — ` +
1054
+ (model.fitted ? `fitted from ${model.tau_fits} recorded session ramp${model.tau_fits === 1 ? "" : "s"}.`
1055
+ : "defaults from the verified alert-40 event; refits automatically as sessions accumulate.") +
1056
+ (drift && !drift.drifting ? ` Heat rise stable across the last ${drift.recent_n + drift.baseline_n} fitted sessions` +
1057
+ `${drift.off_current_n ? ` (${drift.off_current_n} off-current session${drift.off_current_n === 1 ? "" : "s"} excluded)` : ""}.` : "");
1058
+ thermalCard.append(el("div", { class: "chart-card" },
1059
+ el("div", { class: "chart-title" }, "Thermal derate forecast", chip ? " " : null, chip),
1060
+ ...lines.map((text) => el("div", { class: "note" }, text)),
1061
+ driftLine,
1062
+ el("div", { class: "chart-sub" }, modelNote)));
1063
+ }
1064
+
1065
+ function pushThermal(data) {
1066
+ // One point per forecast tick, whether it arrived by stream or by poll.
1067
+ if (data.state !== "charging" || !data.forecast || data.forecast.steady_state_c == null) return;
1068
+ const ts = data.ts || data.server_ts;
1069
+ if (tbuf.length && ts - tbuf[tbuf.length - 1].ts < 1) return;
1070
+ const forecast = data.forecast, model = data.model || {};
1071
+ tbuf.push({
1072
+ ts, steady: forecast.steady_state_c, willTrip: forecast.will_trip,
1073
+ mtt: forecast.minutes_to_trip, basis: forecast.basis, suggested: forecast.suggested_max_a,
1074
+ rmse: model.fit_rmse_c, trip: model.trip_c, tau: model.tau_min, tripTs: forecast.trip_ts,
1075
+ });
1076
+ const cutoff = bufferCutoff();
1077
+ while (tbuf.length && tbuf[0].ts < cutoff) tbuf.shift();
1078
+ }
1079
+
1080
+ // How far past "now" the projection curve extends. 20 min matches the
1081
+ // controller's lead-time horizon, so by the time a predicted trip is
1082
+ // actionable its intercept with the trip line is on screen.
1083
+ const FORECAST_FUTURE_S = 1200;
1084
+
1085
+ function renderForecast() {
1086
+ const now = Date.now() / 1000;
1087
+ const pinned = sessionAnchorTs();
1088
+ const xFrom = pinned != null ? Math.min(pinned - 60, now - 900) : now - 900;
1089
+ const latest = tbuf[tbuf.length - 1];
1090
+ // Project forward only with a live forecast AND a live handle sample to
1091
+ // anchor the curve on — otherwise the future region would extrapolate
1092
+ // from stale data and the chart falls back to its measured-only layout.
1093
+ const anchor = buf.length ? buf[buf.length - 1] : null;
1094
+ const projecting = Boolean(
1095
+ latest && now - latest.ts <= 180 && latest.steady != null && latest.tau > 0 &&
1096
+ anchor && anchor.tHandle != null && now - anchor.ts <= 120
1097
+ );
1098
+ // A pinned multi-hour session accumulates thousands of 2 s handle samples;
1099
+ // temperatures move on minutes, so thin the drawn line instead of pushing
1100
+ // an ever-growing polyline through the SVG on every tick.
1101
+ const thin = (points) => {
1102
+ const stride = Math.ceil(points.length / 1200);
1103
+ return stride > 1
1104
+ ? points.filter((_, index) => index % stride === 0 || index === points.length - 1)
1105
+ : points;
1106
+ };
1107
+ const series = [
1108
+ { name: "Plug handle", color: colors.s2, points: thin(buf.filter((sample) => sample.ts >= xFrom).map((sample) => [sample.ts, sample.tHandle])) },
1109
+ { name: "Projected plateau", color: colors.s5, dash: "6 4", points: tbuf.map((point) => [point.ts, point.steady]) },
1110
+ { name: "Garage ambient", color: colors.s3, points: thin(abuf.filter((point) => point[0] >= xFrom)) },
1111
+ ];
1112
+ if (projecting) {
1113
+ // The model's own forward path from the newest measured sample:
1114
+ // T(t) = plateau − (plateau − T_now)·e^(−t/τ). Where this curve meets
1115
+ // the 65 °C line IS the predicted trip moment — the intercept is the
1116
+ // whole point of extending the axis into the future.
1117
+ const tauS = latest.tau * 60;
1118
+ const pts = [];
1119
+ for (let dt = 0; dt <= FORECAST_FUTURE_S; dt += 30) {
1120
+ pts.push([now + dt, latest.steady - (latest.steady - anchor.tHandle) * Math.exp(-dt / tauS)]);
1121
+ }
1122
+ series.push({ name: "Projected path", color: colors.s5, dash: "2 4", points: pts });
1123
+ }
1124
+ lineChart(fcast.box, {
1125
+ series,
1126
+ unit: "°C", digits: 1, xFrom, xTo: projecting ? now + FORECAST_FUTURE_S : now, height: 210,
1127
+ refLines: [
1128
+ { value: HANDLE_TRIP_C, label: `${HANDLE_TRIP_C}°C handle → alert 40 derate` },
1129
+ { value: HANDLE_CLEAR_C, label: `${HANDLE_CLEAR_C}°C → clears`, below: true },
1130
+ ],
1131
+ vlines: projecting ? [{ ts: now, label: "now" }] : [],
1132
+ });
1133
+ // The sub line spells out the same arithmetic the amp controller's
1134
+ // confidence guard runs: margin to trip, measured in fit-noise units.
1135
+ const sub = fcast.card.querySelector(".chart-sub");
1136
+ if (!latest || now - latest.ts > 180) {
1137
+ sub.textContent = "The dashed plateau appears while charging — recomputed every 30 s from the handle's live trajectory. Solid lines are measured.";
1138
+ } else if (latest.willTrip) {
1139
+ sub.textContent = `Projected to reach ${fmtNum(latest.trip ?? HANDLE_TRIP_C, 0)} °C in ~${fmtNum(latest.mtt, 0)} min` +
1140
+ (latest.tripTs ? ` (≈ ${fmtT(latest.tripTs).slice(0, 5)})` : "") +
1141
+ (latest.suggested ? ` — capping at ≤ ${fmtNum(latest.suggested, 0)} A avoids the derate.` : ".");
1142
+ } else {
1143
+ const trip = latest.trip ?? HANDLE_TRIP_C;
1144
+ const margin = trip - latest.steady;
1145
+ const sigma = latest.rmse > 0 ? margin / latest.rmse : null;
1146
+ // A plateau below the live handle means the projection points DOWN —
1147
+ // typically right after the amp controller cut current. Name it, so a
1148
+ // descending dashed curve reads as recovery rather than a glitch.
1149
+ const recovering = anchor && anchor.tHandle != null && latest.steady < anchor.tHandle - 0.3;
1150
+ sub.textContent = `${latest.basis} basis · ${recovering ? "recovering, settling toward" : "plateau"} ~${fmtNum(latest.steady, 1)} °C · margin to trip ${fmtNum(margin, 1)} °C` +
1151
+ (sigma != null ? ` = ${fmtNum(sigma, 0)}× the model's fit noise` +
1152
+ (sigma < 2 ? " — inside the controller's 2× guard band, treated as trip risk" : "") : "") + ".";
1153
+ }
1154
+ }
1155
+
1156
+ async function loadThermal() {
1157
+ try {
1158
+ const data = await getJSON("/api/thermal");
1159
+ renderThermal(data);
1160
+ pushThermal(data);
1161
+ } catch { /* keep last card */ }
1162
+ try {
1163
+ const from = abuf.length ? abuf[abuf.length - 1][0] + 0.001 : Date.now() / 1000 - 900;
1164
+ const amb = await getJSON(`/api/ambient?from=${from}`);
1165
+ abuf.push(...ambientRows(amb.samples || []).filter((point) => !abuf.length || point[0] > abuf[abuf.length - 1][0]));
1166
+ const cutoff = bufferCutoff();
1167
+ while (abuf.length && abuf[0][0] < cutoff) abuf.shift();
1168
+ } catch { /* no ambient feed yet */ }
1169
+ renderForecast();
1170
+ }
1171
+ loadThermal();
1172
+ const thermalTimer = setInterval(loadThermal, 60000);
1173
+
1174
+ if (buf.length) { renderTiles(buf[buf.length - 1]); renderSessionCard(buf[buf.length - 1]); }
1175
+ renderCharts();
1176
+ renderForecast();
1177
+
1178
+ let lastCharging = null;
1179
+ const onMsg = (msg) => {
1180
+ if (msg.type === "thermal") { pushThermal(msg); renderForecast(); return; }
1181
+ if (msg.type !== "vitals") return;
1182
+ const sample = fromSse(msg);
1183
+ buf.push(sample);
1184
+ const cutoff = bufferCutoff();
1185
+ while (buf.length && buf[0].ts < cutoff) buf.shift();
1186
+ // Refresh the forecast immediately when charging starts or stops rather
1187
+ // than waiting out the poll interval — and scope the prediction to the
1188
+ // session: rebuild its recorded ticks on a (re)start, drop them the
1189
+ // moment the charge ends so a finished session shows measured lines only.
1190
+ if (lastCharging !== null && sample.charging !== lastCharging) {
1191
+ if (sample.charging) seedForecasts(sessionAnchorTs() ?? Date.now() / 1000 - 900).then(renderForecast, () => {});
1192
+ else tbuf.length = 0;
1193
+ loadThermal();
1194
+ }
1195
+ lastCharging = sample.charging;
1196
+ renderTiles(sample);
1197
+ renderSessionCard(sample);
1198
+ renderCharts();
1199
+ renderForecast();
1200
+ };
1201
+ live.listeners.add(onMsg);
1202
+ return () => { live.listeners.delete(onMsg); clearInterval(thermalTimer); };
1203
+ }
1204
+
1205
+ const RANGE_PRESETS = [
1206
+ { key: "1h", label: "Last hour", seconds: 3600 },
1207
+ { key: "6h", label: "6 hours", seconds: 6 * 3600 },
1208
+ { key: "24h", label: "24 hours", seconds: 24 * 3600 },
1209
+ { key: "7d", label: "7 days", seconds: 7 * 24 * 3600 },
1210
+ { key: "30d", label: "30 days", seconds: 30 * 24 * 3600 },
1211
+ { key: "90d", label: "90 days", seconds: 90 * 24 * 3600 },
1212
+ ];
1213
+ const rangeSeconds = (key) => (RANGE_PRESETS.find((preset) => preset.key === key) || RANGE_PRESETS[3]).seconds;
1214
+
1215
+ async function viewSessions(root, rangeKey = "30d") {
1216
+ const now = Date.now() / 1000;
1217
+ const from = now - rangeSeconds(rangeKey);
1218
+ root.append(el("h2", {}, "Charging sessions"));
1219
+ root.append(presetRow(RANGE_PRESETS.slice(2), rangeKey, (key) => { render("sessions", key); }));
1220
+
1221
+ const data = await getJSON(`/api/sessions?from=${from}&to=${now}`);
1222
+ const wrap = el("div", { class: "tbl-wrap" });
1223
+ if (!data.sessions.length) {
1224
+ wrap.append(el("div", { class: "empty" }, "No sessions recorded in this range yet. Plug in a vehicle and it will appear here."));
1225
+ } else {
1226
+ const tbl = el("table", {},
1227
+ el("thead", {}, el("tr", {},
1228
+ el("th", {}, "#"), el("th", {}, "Plugged in"), el("th", {}, "Unplugged"),
1229
+ el("th", { class: "num" }, "Duration"), el("th", { class: "num" }, "Charging time"),
1230
+ el("th", { class: "num" }, "Energy (kWh)"), el("th", { class: "num" }, "Peak power (kW)"),
1231
+ el("th", { class: "num" }, "Samples"), el("th", {}, "Status"))));
1232
+ const tbody = el("tbody", {});
1233
+ for (const session of data.sessions) {
1234
+ const ongoing = session.end_ts == null;
1235
+ const row = el("tr", { class: "clickable", onclick: () => { location.hash = `#/sessions/${session.id}`; } },
1236
+ el("td", {}, `#${session.id}`),
1237
+ el("td", {}, fmtDT(session.start_ts)),
1238
+ el("td", {}, ongoing ? "ongoing" : fmtDT(session.end_ts)),
1239
+ el("td", { class: "num" }, fmtDur((ongoing ? now : session.end_ts) - session.start_ts)),
1240
+ el("td", { class: "num" }, fmtDur(session.charging_s)),
1241
+ el("td", { class: "num" }, fmtNum((session.energy_wh ?? 0) / 1000, 2)),
1242
+ el("td", { class: "num" }, fmtNum((session.max_power_w ?? 0) / 1000, 2)),
1243
+ el("td", { class: "num" }, fmtNum(session.sample_count, 0)),
1244
+ el("td", {}, chipFor(ongoing ? "good" : "muted", ongoing ? "live" : (session.end_reason || "ended").replaceAll("_", " "))));
1245
+ tbody.append(row);
1246
+ }
1247
+ tbl.append(tbody);
1248
+ wrap.append(tbl);
1249
+ }
1250
+ root.append(wrap);
1251
+ root.append(el("div", { class: "note" }, "Click a session to review its full recorded telemetry."));
1252
+ }
1253
+
1254
+ function chipFor(sev, text) {
1255
+ return el("span", { class: `schip ${sev}` }, el("span", { class: "sdot" }), text);
1256
+ }
1257
+
1258
+ async function viewEnergy(root, rangeKey = "30d") {
1259
+ const now = Date.now() / 1000;
1260
+ const from = now - rangeSeconds(rangeKey);
1261
+ root.append(el("h2", {}, "Charger lifetime"));
1262
+
1263
+ const st = live.status || await getJSON("/api/status");
1264
+ const lifetime = st.lifetime;
1265
+ const tiles = el("div", { class: "cards" });
1266
+ if (lifetime) {
1267
+ tiles.append(
1268
+ statTile("Energy delivered", fmtNum(lifetime.energy_wh / 1e6, 2), "MWh", "over the charger's whole life"),
1269
+ statTile("Charge sessions", fmtNum(lifetime.charge_starts, 0), null, `${fmtNum(lifetime.connector_cycles, 0)} plug-in cycles`),
1270
+ statTile("Time charging", fmtNum(lifetime.charging_time_s / 3600, 0), "h", `uptime ${fmtNum(lifetime.uptime_s / 86400, 0)} days`),
1271
+ statTile("Thermal foldbacks", fmtNum(lifetime.thermal_foldbacks, 0), null, "times charging was slowed by heat"),
1272
+ statTile("Lifetime alerts", fmtNum(lifetime.alert_count, 0), null),
1273
+ statTile("Contactor cycles", fmtNum(lifetime.contactor_cycles, 0), null, `${fmtNum(lifetime.contactor_cycles_loaded, 0)} under load`),
1274
+ );
1275
+ } else {
1276
+ tiles.append(el("div", { class: "card" }, el("div", { class: "empty" }, "No lifetime data recorded yet.")));
1277
+ }
1278
+ root.append(tiles);
1279
+
1280
+ root.append(el("h2", {}, "Energy per day"));
1281
+ root.append(presetRow(RANGE_PRESETS.slice(3), rangeKey, (key) => render("energy", key)));
1282
+ const daily = chartCard("Daily energy delivered",
1283
+ "From the charger's cumulative counter, sampled every minute — days before monitoring began can't be reconstructed");
1284
+ root.append(daily.card);
1285
+
1286
+ const data = await getJSON(`/api/lifetime?from=${from}&to=${now}`);
1287
+ const byDay = new Map();
1288
+ for (const sample of data.samples) {
1289
+ if (sample.energy_wh == null) continue;
1290
+ const key = fmtDT(sample.ts).slice(0, 10);
1291
+ const cur = byDay.get(key);
1292
+ if (!cur) byDay.set(key, { min: sample.energy_wh, max: sample.energy_wh });
1293
+ else { cur.min = Math.min(cur.min, sample.energy_wh); cur.max = Math.max(cur.max, sample.energy_wh); }
1294
+ }
1295
+ const bars = [...byDay.entries()].map(([day, range]) => ({ label: day.slice(5), value: (range.max - range.min) / 1000 }));
1296
+ barChart(daily.box, { bars, unit: "kWh", digits: 1, seriesName: "Energy", height: 240 });
1297
+ const total = bars.reduce((sum, bar) => sum + bar.value, 0);
1298
+ if (bars.length) {
1299
+ root.append(el("div", { class: "note" },
1300
+ `${fmtNum(total, 1)} kWh across ${bars.length} recorded day${bars.length > 1 ? "s" : ""} ` +
1301
+ `(avg ${fmtNum(total / bars.length, 1)} kWh/day)`));
1302
+ }
1303
+ }
1304
+
1305
+ async function viewSessionDetail(root, id) {
1306
+ const colors = COLORS();
1307
+ // The skeleton is built once; live refreshes fetch first and then update
1308
+ // content in place, so the page never blanks or flashes mid-update.
1309
+ const heading = el("h2", {}, `Session #${id}`);
1310
+ const tiles = el("div", { class: "cards" });
1311
+ const power = chartCard("Power", "Total power over the session");
1312
+ const cur = chartCard("Phase currents", "Per-phase current");
1313
+ const volt = chartCard("Phase voltages", "Per-phase voltage");
1314
+ const temp = chartCard("Temperatures",
1315
+ `Plug handle, charger circuit board (PCBA), and processor (MCU). At ${HANDLE_TRIP_C}°C on the handle, alert 40 raises ` +
1316
+ `and current is halved (observed on this firmware); the ≈${PCBA_THROTTLE_C}°C line is the community-observed PCBA throttle point.`);
1317
+ const pilot = chartCard("Pilot & proximity", "J1772 handshake signals — flaky values here often precede charging errors");
1318
+ const relay = chartCard("Relay voltages", "Contactor coil drive");
1319
+ const eventsWrap = el("div", {});
1320
+ const brush = chartCard("Time window",
1321
+ "Drag across the strip to zoom every chart and the event list into that window — drag the edges to resize, the middle to pan, click once to reset");
1322
+ const brushInfo = el("div", { class: "note" });
1323
+ brush.card.append(brushInfo);
1324
+ root.append(
1325
+ heading,
1326
+ el("div", { class: "filters" }, el("a", { class: "chip", href: "#/sessions" }, "← all sessions")),
1327
+ tiles,
1328
+ brush.card,
1329
+ power.card, el("div", { class: "grid-2" }, cur.card, volt.card), temp.card,
1330
+ el("div", { class: "grid-2" }, pilot.card, relay.card),
1331
+ el("h2", {}, "Events during this session"),
1332
+ eventsWrap);
1333
+
1334
+ let ongoing = false;
1335
+ // Time-window state: win = [t0, t1] or null (full session). Windowing is
1336
+ // pure view filtering — nothing is deleted — and a windowed view re-fetches
1337
+ // that range at high resolution for a deeper dive than the whole-session
1338
+ // downsample can show.
1339
+ let win = null;
1340
+ let fullSamples = [];
1341
+ let fullEvents = [];
1342
+ let sessionRange = [0, 1];
1343
+ let winSeq = 0;
1344
+ let winTimer = null;
1345
+
1346
+ function renderCharts(samples, xFrom, xTo) {
1347
+ lineChart(power.box, {
1348
+ series: [{ name: "Power (W)", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.power]) }],
1349
+ unit: "W", digits: 0, area: true, zeroBase: true, xFrom, xTo, height: 240,
1350
+ });
1351
+ lineChart(cur.box, {
1352
+ series: [
1353
+ { name: "Phase A", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.ia]) },
1354
+ { name: "Phase B", color: colors.s2, points: samples.map((sample) => [sample.ts, sample.ib]) },
1355
+ { name: "Phase C", color: colors.s3, points: samples.map((sample) => [sample.ts, sample.ic]) },
1356
+ ], unit: "A", digits: 1, zeroBase: true, xFrom, xTo, height: 190,
1357
+ });
1358
+ lineChart(volt.box, {
1359
+ series: [
1360
+ { name: "Phase A", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.va]) },
1361
+ { name: "Phase B", color: colors.s2, points: samples.map((sample) => [sample.ts, sample.vb]) },
1362
+ { name: "Phase C", color: colors.s3, points: samples.map((sample) => [sample.ts, sample.vc]) },
1363
+ ], unit: "V", digits: 1, xFrom, xTo, height: 190,
1364
+ });
1365
+ lineChart(temp.box, {
1366
+ series: [
1367
+ { name: "Circuit board (PCBA)", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.tPcba]) },
1368
+ { name: "Plug handle", color: colors.s2, points: samples.map((sample) => [sample.ts, sample.tHandle]) },
1369
+ { name: "Processor (MCU)", color: colors.s3, points: samples.map((sample) => [sample.ts, sample.tMcu]) },
1370
+ ], unit: "°C", digits: 1, xFrom, xTo, height: 190,
1371
+ refLines: [
1372
+ { value: HANDLE_TRIP_C, label: `${HANDLE_TRIP_C}°C handle → alert 40 derate` },
1373
+ { value: PCBA_THROTTLE_C, label: `≈${PCBA_THROTTLE_C}°C PCBA throttle (approx.)` },
1374
+ ],
1375
+ });
1376
+ lineChart(pilot.box, {
1377
+ series: [
1378
+ { name: "Pilot high", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.pilotHigh]) },
1379
+ { name: "Pilot low", color: colors.s2, points: samples.map((sample) => [sample.ts, sample.pilotLow]) },
1380
+ { name: "Proximity", color: colors.s3, points: samples.map((sample) => [sample.ts, sample.prox]) },
1381
+ ], unit: "V", digits: 1, xFrom, xTo, height: 190,
1382
+ });
1383
+ lineChart(relay.box, {
1384
+ series: [
1385
+ { name: "Relay K1", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.relayK1]) },
1386
+ { name: "Relay K2", color: colors.s2, points: samples.map((sample) => [sample.ts, sample.relayK2]) },
1387
+ ], unit: "V", digits: 1, zeroBase: true, xFrom, xTo, height: 190,
1388
+ });
1389
+ }
1390
+
1391
+ function renderEvents() {
1392
+ const evs = win ? fullEvents.filter((event) => event.ts >= win[0] && event.ts <= win[1]) : fullEvents;
1393
+ eventsWrap.replaceChildren(eventsTable(evs));
1394
+ }
1395
+
1396
+ function updateBrushInfo() {
1397
+ brushInfo.textContent = win
1398
+ ? `Window: ${fmtDT(win[0])} → ${fmtT(win[1])} (${fmtDur(win[1] - win[0])}) — full-resolution data for this range`
1399
+ : "Showing the full session";
1400
+ }
1401
+
1402
+ function renderBrush() {
1403
+ timeBrush(brush.box, { samples: fullSamples, range: sessionRange, win, onChange: onBrushChange });
1404
+ updateBrushInfo();
1405
+ }
1406
+
1407
+ async function applyWindow() {
1408
+ const seq = ++winSeq;
1409
+ if (!win) {
1410
+ renderCharts(fullSamples, sessionRange[0], sessionRange[1]);
1411
+ renderEvents();
1412
+ return;
1413
+ }
1414
+ // Immediate feedback from data already in hand…
1415
+ renderCharts(fullSamples.filter((sample) => sample.ts >= win[0] && sample.ts <= win[1]), win[0], win[1]);
1416
+ renderEvents();
1417
+ // …then upgrade to full-resolution samples for the window.
1418
+ try {
1419
+ const data = await getJSON(`/api/vitals?from=${win[0]}&to=${win[1]}&points=1500`);
1420
+ if (seq !== winSeq || !win) return;
1421
+ renderCharts(data.samples.map(fromDbRow), win[0], win[1]);
1422
+ } catch { /* keep the client-filtered render */ }
1423
+ }
1424
+
1425
+ function onBrushChange(newWin) {
1426
+ win = newWin;
1427
+ updateBrushInfo();
1428
+ clearTimeout(winTimer);
1429
+ winTimer = setTimeout(applyWindow, 200);
1430
+ }
1431
+
1432
+ async function refresh() {
1433
+ const data = await getJSON(`/api/sessions/${id}`); // fetch completes before any DOM change
1434
+ const session = data.session;
1435
+ ongoing = session.end_ts == null;
1436
+ const now = Date.now() / 1000;
1437
+ const samples = data.samples.map(fromDbRow);
1438
+
1439
+ heading.replaceChildren(`Session #${session.id} `, ongoing ? chipFor("good", "live") : chipFor("muted", "ended"));
1440
+
1441
+ const energyKwh = (session.energy_wh ?? (samples.length ? samples[samples.length - 1].energy : 0) ?? 0) / 1000;
1442
+ const maxP = session.max_power_w ?? Math.max(0, ...samples.map((sample) => sample.power || 0));
1443
+ // The plug-in time can predate monitoring (derived from the charger's own
1444
+ // session timer); charts still start at the first observed sample.
1445
+ const firstSeen = samples.length ? samples[0].ts : session.start_ts;
1446
+ const backdated = firstSeen - session.start_ts > 120;
1447
+ tiles.replaceChildren(
1448
+ statTile("Plugged in", fmtDT(session.start_ts).slice(11), null,
1449
+ fmtDT(session.start_ts).slice(0, 10) + (backdated ? ` — from charger's timer; monitoring since ${fmtT(firstSeen)}` : "")),
1450
+ ongoing
1451
+ ? statTile("Status", "Plugged in", null, "session in progress")
1452
+ : statTile("Unplugged", fmtDT(session.end_ts).slice(11), null, fmtDT(session.end_ts).slice(0, 10)),
1453
+ statTile("Duration", fmtDur((ongoing ? now : session.end_ts) - session.start_ts), null,
1454
+ session.charging_s != null ? `charging ${fmtDur(session.charging_s)}` : "charging time totals when the session ends"),
1455
+ statTile("Energy", fmtNum(energyKwh, 2), "kWh"),
1456
+ statTile("Peak power", fmtNum(maxP / 1000, 2), "kW", session.avg_power_w != null ? `avg ${fmtNum(session.avg_power_w / 1000, 2)} kW` : null),
1457
+ statTile("Samples", fmtNum(session.sample_count ?? samples.length, 0), null, "full fidelity retained"));
1458
+
1459
+ fullSamples = samples;
1460
+ fullEvents = data.events;
1461
+ sessionRange = [backdated ? firstSeen : session.start_ts, ongoing ? now : session.end_ts];
1462
+ renderBrush();
1463
+ await applyWindow();
1464
+ }
1465
+
1466
+ await refresh();
1467
+
1468
+ if (ongoing) {
1469
+ // Refresh in place at most every 5s while live; stop once the session ends.
1470
+ let timer = null;
1471
+ const throttled = (msg) => {
1472
+ if (msg.type !== "vitals" && msg.type !== "event") return;
1473
+ if (timer) return;
1474
+ timer = setTimeout(async () => {
1475
+ timer = null;
1476
+ try { await refresh(); } catch { /* transient fetch failure; next tick retries */ }
1477
+ if (!ongoing) { live.listeners.delete(throttled); }
1478
+ }, 5000);
1479
+ };
1480
+ live.listeners.add(throttled);
1481
+ return () => { live.listeners.delete(throttled); if (timer) clearTimeout(timer); };
1482
+ }
1483
+ }
1484
+
1485
+ function eventsTable(events) {
1486
+ const wrap = el("div", { class: "tbl-wrap" });
1487
+ if (!events || !events.length) {
1488
+ wrap.append(el("div", { class: "empty" }, "No events in this range."));
1489
+ return wrap;
1490
+ }
1491
+ const tbl = el("table", {},
1492
+ el("thead", {}, el("tr", {},
1493
+ el("th", {}, "Time (local)"), el("th", {}, "Event"), el("th", {}, "Detail"))));
1494
+ const tbody = el("tbody", {});
1495
+ for (const ev of events) {
1496
+ let detail = "";
1497
+ if (ev.detail) {
1498
+ try {
1499
+ const detailObj = JSON.parse(ev.detail);
1500
+ if (ev.kind === "evse_state_change") detail = `${evseLabel(detailObj.from)} → ${evseLabel(detailObj.to)}`;
1501
+ else if (ev.kind === "derate_warning")
1502
+ detail = `~${fmtNum(detailObj.minutes_to_trip, 0)} min to 65 °C at ${fmtNum(detailObj.current_a, 0)} A` +
1503
+ (detailObj.suggested_max_a ? ` — cap vehicle charge current at ${fmtNum(detailObj.suggested_max_a, 0)} A to keep charging` : "");
1504
+ else if (ev.kind === "amp_capped" || ev.kind === "amp_restored")
1505
+ detail = `${detailObj.from_a != null ? fmtNum(detailObj.from_a, 0) : "?"} → ${fmtNum(detailObj.to_a, 0)} A` +
1506
+ (detailObj.minutes_to_trip != null ? ` — forecast had ~${fmtNum(detailObj.minutes_to_trip, 0)} min to 65 °C` :
1507
+ detailObj.steady_state_c != null ? ` — plateau read ~${fmtNum(detailObj.steady_state_c, 1)} °C` : "");
1508
+ else if (ev.kind === "amp_adjust_failed")
1509
+ detail = `could not ${detailObj.attempted} to ${fmtNum(detailObj.to_a, 0)} A — ${detailObj.error || "BLE bridge unreachable"}`;
1510
+ else if (ev.kind === "monitor_gap") detail = `no data since ${fmtDT(detailObj.offline_since)} (${fmtDur(detailObj.gap_s)})`;
1511
+ else if (ev.kind === "evse_not_ready_change")
1512
+ detail = `codes [${(detailObj.from || []).join(", ")}] → [${(detailObj.to || []).join(", ")}] (undocumented)`;
1513
+ else if ((ev.kind === "alert_raised" || ev.kind === "alert_cleared") && detailObj.alert != null) {
1514
+ const disp = alertDisplay(detailObj.alert, "device");
1515
+ detail = disp.sub ? `${disp.label} · ${disp.sub}` : disp.label;
1516
+ }
1517
+ else if (ev.kind === "session_start" && detailObj.backdated_s)
1518
+ detail = `session_id: ${detailObj.session_id} · start backdated ${fmtDur(detailObj.backdated_s)} from the charger's session timer`;
1519
+ else detail = Object.entries(detailObj).map(([key, value]) => `${key}: ${value}`).join(" · ");
1520
+ } catch { detail = String(ev.detail); }
1521
+ }
1522
+ tbody.append(el("tr", {},
1523
+ el("td", {}, fmtDT(ev.ts)),
1524
+ el("td", {}, chipFor(eventSeverity(ev.kind), eventLabel(ev.kind))),
1525
+ el("td", {}, el("code", { class: "mono" }, detail))));
1526
+ }
1527
+ tbl.append(tbody);
1528
+ wrap.append(tbl);
1529
+ return wrap;
1530
+ }
1531
+
1532
+ async function viewWifi(root, rangeKey = "24h") {
1533
+ const colors = COLORS();
1534
+ const now = Date.now() / 1000;
1535
+ const from = now - rangeSeconds(rangeKey);
1536
+ root.append(el("h2", {}, "Wi-Fi health"));
1537
+ root.append(presetRow(RANGE_PRESETS.slice(0, 4), rangeKey, (key) => render("wifi", key)));
1538
+
1539
+ const [data, evData] = await Promise.all([
1540
+ getJSON(`/api/wifi?from=${from}&to=${now}`),
1541
+ getJSON(`/api/events?from=${from}&to=${now}&kinds=wifi_disconnected,wifi_reconnected,internet_lost,internet_restored,poll_error,poll_recovered`),
1542
+ ]);
1543
+ const st = live.status || await getJSON("/api/status");
1544
+ const wifi = st.wifi;
1545
+
1546
+ const tiles = el("div", { class: "cards" });
1547
+ if (wifi) {
1548
+ tiles.append(
1549
+ statTile("Charger Wi-Fi", "", null, ""),
1550
+ statTile("Internet (charger → Tesla)", "", null, ""),
1551
+ statTile("Signal", fmtNum(wifi.signal_strength, 0), "%", `RSSI ${fmtNum(wifi.rssi, 0)} dBm · SNR ${fmtNum(wifi.snr, 0)} dB`),
1552
+ statTile("Network", "", null, ""));
1553
+ const [wifiTile, netTile, , netInfo] = tiles.children;
1554
+ wifiTile.querySelector(".tile-value").replaceChildren(chipFor(wifi.connected ? "good" : "critical", wifi.connected ? "connected" : "disconnected"));
1555
+ wifiTile.querySelector(".tile-sub").textContent = `as of ${fmtDT(wifi.ts)}`;
1556
+ netTile.querySelector(".tile-value").replaceChildren(chipFor(wifi.internet ? "good" : "warning", wifi.internet ? "reachable" : "unreachable"));
1557
+ netTile.querySelector(".tile-sub").textContent = "the charger's own cloud link — the monitor never uses it";
1558
+ netInfo.querySelector(".tile-value").textContent = wifi.ssid || "—";
1559
+ netInfo.querySelector(".tile-value").style.fontSize = "16px";
1560
+ netInfo.querySelector(".tile-sub").textContent = `${wifi.infra_ip || "?"} · ${wifi.mac || "?"}`;
1561
+ } else {
1562
+ tiles.append(el("div", { class: "card" }, el("div", { class: "empty" }, "No Wi-Fi data recorded yet.")));
1563
+ }
1564
+ root.append(tiles);
1565
+
1566
+ const pts = data.samples;
1567
+ const rssi = chartCard("RSSI", "Received signal strength, dBm — higher (less negative) is better");
1568
+ const snr = chartCard("Signal-to-noise ratio", "dB — above ~20 dB is healthy");
1569
+ const sig = chartCard("Signal strength", "Charger-reported quality, %");
1570
+ root.append(el("div", { class: "grid-3" }, rssi.card, snr.card, sig.card));
1571
+ lineChart(rssi.box, { series: [{ name: "RSSI", color: colors.s1, points: pts.map((sample) => [sample.ts, sample.rssi]) }], unit: "dBm", digits: 0, xFrom: from, xTo: now, height: 170 });
1572
+ lineChart(snr.box, { series: [{ name: "SNR", color: colors.s1, points: pts.map((sample) => [sample.ts, sample.snr]) }], unit: "dB", digits: 0, xFrom: from, xTo: now, height: 170 });
1573
+ lineChart(sig.box, { series: [{ name: "Signal", color: colors.s1, points: pts.map((sample) => [sample.ts, sample.signal_strength]) }], unit: "%", digits: 0, zeroBase: true, xFrom: from, xTo: now, height: 170 });
1574
+
1575
+ root.append(el("h2", {}, "Connectivity events"));
1576
+ root.append(eventsTable(evData.events));
1577
+ }
1578
+
1579
+ async function viewAlerts(root, rangeKey = "7d") {
1580
+ const colors = COLORS();
1581
+ const now = Date.now() / 1000;
1582
+ const from = now - rangeSeconds(rangeKey);
1583
+ root.append(el("h2", {}, "Alerts"));
1584
+ const [data, thermalData] = await Promise.all([
1585
+ getJSON(`/api/alerts?from=${from}&to=${now}`),
1586
+ getJSON("/api/thermal").catch(() => null),
1587
+ loadAlertCodes(),
1588
+ ]);
1589
+
1590
+ const activeWrap = el("div", { class: "cards" });
1591
+ if (!data.active.length) {
1592
+ activeWrap.append(el("div", { class: "card" },
1593
+ el("div", { class: "tile-label" }, "Active alerts"),
1594
+ el("div", { class: "tile-value" }, chipFor("good", "none")),
1595
+ el("div", { class: "tile-sub" }, "the charger reports no active alerts")));
1596
+ } else {
1597
+ for (const alertItem of data.active) {
1598
+ const disp = alertDisplay(alertItem.alert, alertItem.source);
1599
+ // Verified descriptions can run to a paragraph; inline only the first
1600
+ // sentence (the official alert text) and keep the full description in
1601
+ // the hover tooltip, like the banner and history table. The card spans
1602
+ // the grid row so a lone active alert doesn't render as a tall column.
1603
+ const firstSentence = disp.sub ? disp.sub.split(". ")[0] : null;
1604
+ const card = el("div", { class: "card wide" },
1605
+ el("div", { class: "tile-label" }, `${alertItem.source} alert`),
1606
+ el("div", { class: "tile-value" }, chipFor(alertItem.source === "wifi" ? "serious" : "critical", disp.label)),
1607
+ el("div", { class: "tile-sub" },
1608
+ `since ${fmtDT(alertItem.first_ts)} (${fmtDur(now - alertItem.first_ts)})` + (firstSentence ? ` · ${firstSentence}` : "")));
1609
+ if (disp.sub) card.title = disp.sub;
1610
+ activeWrap.append(card);
1611
+ }
1612
+ }
1613
+ root.append(activeWrap);
1614
+
1615
+ // Degradation watch: fitted heat rise per charging segment at reference
1616
+ // current. Prediction uses the rolling median, which would silently follow
1617
+ // a slow increase; this trend is where a contact/wiring problem shows.
1618
+ const fits = ((thermalData && thermalData.session_fits) || []).filter((fit) => fit.rise_ref_c != null);
1619
+ if (fits.length >= 2) {
1620
+ const drift = thermalData.drift;
1621
+ const rise = chartCard("Handle heat rise per charging segment",
1622
+ `Fitted steady-state rise above ambient, normalized to ${fmtNum(thermalData.model.ref_current_a, 0)} A. ` +
1623
+ "A sustained climb at the same current means added resistance in the current path — inspect before it becomes heat.");
1624
+ root.append(rise.card);
1625
+ lineChart(rise.box, {
1626
+ series: [{ name: "Rise (°C)", color: colors.s1, points: fits.map((fit) => [fit.start_ts, fit.rise_ref_c]) }],
1627
+ unit: "°C", digits: 1, height: 180,
1628
+ });
1629
+ if (drift) {
1630
+ // The verdict carries its own uncertainty — a delta from a handful of
1631
+ // fits is a lead, not a conviction, and the note must show which.
1632
+ const [ciLo, ciHi] = drift.delta_ci95_c || [null, null];
1633
+ const sureness = ciLo == null ? "" :
1634
+ ` · 95% CI ${fmtNum(ciLo, 1)}..${fmtNum(ciHi, 1)} °C from n=${drift.baseline_n}+${drift.recent_n}` +
1635
+ (drift.confident ? "" : " — not yet statistically confirmed; more sessions will tighten this");
1636
+ const pooled = drift.cross_current_n
1637
+ ? ` (${drift.cross_current_n} ambient-bracketed fit${drift.cross_current_n > 1 ? "s" : ""} pooled from other charge currents)`
1638
+ : "";
1639
+ rise.card.append(el("div", { class: "note" },
1640
+ (drift.drifting
1641
+ ? `Recent median +${fmtNum(drift.recent_rise_c, 1)} °C vs baseline +${fmtNum(drift.baseline_rise_c, 1)} °C ` +
1642
+ `(Δ ${fmtNum(drift.delta_c, 1)} °C ≥ ${fmtNum(drift.threshold_c, 1)} °C threshold) — a monitor alert is active`
1643
+ : `Stable: recent median +${fmtNum(drift.recent_rise_c, 1)} °C vs baseline +${fmtNum(drift.baseline_rise_c, 1)} °C ` +
1644
+ `(alert threshold Δ ≥ ${fmtNum(drift.threshold_c, 1)} °C)`) + sureness + pooled + "."));
1645
+ }
1646
+ // Ambient bracketing: fits that read ambient at both ends of the load
1647
+ // window are de-trended for weather that moved during the charge — the
1648
+ // difference between "the garage warmed 3 °C" and "the connector is
1649
+ // going bad". Start-only fits carry that ambiguity; say so.
1650
+ const bracketed = fits.filter((fit) => fit.ambient_drift_c != null);
1651
+ if (bracketed.length) {
1652
+ const maxDrift = bracketed.reduce(
1653
+ (acc, fit) => Math.abs(fit.ambient_drift_c) > Math.abs(acc) ? fit.ambient_drift_c : acc, 0);
1654
+ rise.card.append(el("div", { class: "note" },
1655
+ `Ambient bracketing: ${bracketed.length} of ${fits.length} fits read ambient at both ends of ` +
1656
+ `their load window and are corrected for in-window ambient drift ` +
1657
+ `(largest ${maxDrift > 0 ? "+" : ""}${fmtNum(maxDrift, 1)} °C); the rest assume it held still.`));
1658
+ }
1659
+ // Verified-baseline anchor: without one, "baseline" only means "the
1660
+ // first charges the monitor happened to see". After a hardware
1661
+ // inspection, anchoring here makes the comparison mean "vs verified
1662
+ // healthy" — the claim the alert text is actually making.
1663
+ const anchorTs = thermalData.baseline_anchor_ts;
1664
+ const anchorRow = el("div", { class: "filters" },
1665
+ el("span", { class: "flabel" }, "Baseline"),
1666
+ el("span", { class: "note" }, anchorTs
1667
+ ? `anchored at ${fmtDT(anchorTs)} — fits before it sit out the drift comparison. `
1668
+ : "all recorded fits (hardware never verified). After an inspection, anchor here so the " +
1669
+ "baseline means “verified healthy”. "));
1670
+ const anchorBtn = el("button", { class: "chip", onclick: async () => {
1671
+ const verb = anchorTs ? "Clear the verified-baseline anchor?" :
1672
+ "Anchor the baseline now? Only fits recorded from this moment on will form the drift baseline. " +
1673
+ "Do this right after the hardware has been inspected and verified (or fixed).";
1674
+ if (!window.confirm(verb)) return;
1675
+ await fetch("/api/thermal/baseline-anchor", { method: anchorTs ? "DELETE" : "POST",
1676
+ headers: { "Content-Type": "application/json" },
1677
+ body: anchorTs ? undefined : JSON.stringify({}) });
1678
+ render("alerts", rangeKey);
1679
+ } }, anchorTs ? "Clear anchor" : "Mark hardware verified — anchor baseline now");
1680
+ anchorRow.append(anchorBtn);
1681
+ rise.card.append(anchorRow);
1682
+
1683
+ // Rise vs ambient: the confounder detector. Healthy hardware with a
1684
+ // complete thermal model shows a flat cloud — the fitted rise should not
1685
+ // care what the garage temperature was, because ambient is already
1686
+ // subtracted out. A cloud that still slopes upward with ambient means
1687
+ // the model is missing an environment term (heat-soaked cable/structure
1688
+ // in an uninsulated garage, not the weather at fit time); a flat cloud
1689
+ // sitting higher than the old fits at the same ambient is hardware.
1690
+ const scatter = chartCard("Heat rise vs ambient",
1691
+ "Each completed charge adds a point: fitted rise (48 A-normalized) against the ambient measured for " +
1692
+ "that load window. Flat cloud = model complete, ambient truly removed. Upward slope = residual " +
1693
+ "environment effect (e.g. multi-day heat soak) still masquerading as rise. Elevated-but-flat = " +
1694
+ "genuine added resistance. Hover a point for its session.");
1695
+ root.append(scatter.card);
1696
+ const fitPoint = (fit) => {
1697
+ const ambient = fit.ambient_end_c != null ? (fit.ambient_c + fit.ambient_end_c) / 2 : fit.ambient_c;
1698
+ return [ambient, fit.rise_ref_c, { ...fit, window_ambient: ambient }];
1699
+ };
1700
+ const typicalRise = thermalData.model.rise_ref_c;
1701
+ const ttRow = (name, value) => {
1702
+ const row = el("div", { class: "tt-row" });
1703
+ row.append(el("span", { class: "tt-name" }, name), el("span", { class: "tt-val" }, value));
1704
+ return row;
1705
+ };
1706
+ scatterChart(scatter.box, {
1707
+ xLabel: "window ambient, °C",
1708
+ series: [
1709
+ { name: "ambient-bracketed", color: colors.s1,
1710
+ points: fits.filter((fit) => fit.ambient_drift_c != null && fit.ambient_c != null).map(fitPoint) },
1711
+ { name: "start-only ambient", color: colors.s3,
1712
+ points: fits.filter((fit) => fit.ambient_drift_c == null && fit.ambient_c != null).map(fitPoint) },
1713
+ ],
1714
+ height: 210,
1715
+ tip: (fit) => {
1716
+ const nodes = [el("div", { class: "tt-time" }, `Session ${fit.session_id} · ${fmtDT(fit.start_ts)}`)];
1717
+ nodes.push(ttRow("heat rise", `+${fmtNum(fit.rise_ref_c, 1)} °C @ 48 A`));
1718
+ nodes.push(ttRow("window ambient", `${fmtNum(fit.window_ambient, 1)} °C (${fmtNum(cToF(fit.window_ambient), 0)} °F)`));
1719
+ nodes.push(ttRow("charge current", `${fmtNum(fit.current_a, 1)} A`));
1720
+ const srcNames = { measured: "garage sensor", measured_car: "car sensor",
1721
+ cooldown_tail: "cool-down tail", pre_idle: "pre-charge idle" };
1722
+ nodes.push(ttRow("ambient read", fit.ambient_drift_c != null
1723
+ ? `both ends (drifted ${fit.ambient_drift_c > 0 ? "+" : ""}${fmtNum(fit.ambient_drift_c, 1)} °C, corrected)`
1724
+ : `${srcNames[fit.ambient_source] || "pre-charge idle"} only`));
1725
+ // What the number means: this charge made the handle settle this far
1726
+ // above the garage air (scaled to 48 A) — compared against what this
1727
+ // install typically does. Position on the x-axis is context, not
1728
+ // cause: ambient is already subtracted, so a healthy install reads
1729
+ // about the same rise at any garage temperature.
1730
+ const delta = fit.rise_ref_c - typicalRise;
1731
+ nodes.push(el("div", { class: "tt-note" },
1732
+ Math.abs(delta) < 1.5
1733
+ ? `In line with this install's typical +${fmtNum(typicalRise, 0)} °C rise — the connector made a normal amount of heat for this current.`
1734
+ : delta > 0
1735
+ ? `Ran ${fmtNum(delta, 1)} °C hotter than this install's typical +${fmtNum(typicalRise, 0)} °C — extra heat at the connector beyond what garage temperature explains.`
1736
+ : `Ran ${fmtNum(-delta, 1)} °C cooler than this install's typical +${fmtNum(typicalRise, 0)} °C rise.`));
1737
+ return nodes;
1738
+ },
1739
+ });
1740
+ }
1741
+
1742
+ root.append(el("h2", {}, "Alert history"));
1743
+ root.append(presetRow(RANGE_PRESETS.slice(2), rangeKey, (key) => render("alerts", key)));
1744
+ const wrap = el("div", { class: "tbl-wrap" });
1745
+ if (!data.history.length) {
1746
+ wrap.append(el("div", { class: "empty" }, "No alerts recorded in this range."));
1747
+ } else {
1748
+ const tbl = el("table", {},
1749
+ el("thead", {}, el("tr", {},
1750
+ el("th", {}, "Alert"), el("th", {}, "Source"), el("th", {}, "First seen"),
1751
+ el("th", {}, "Cleared"), el("th", { class: "num" }, "Duration"), el("th", {}, "Status"))));
1752
+ const tbody = el("tbody", {});
1753
+ for (const alertItem of data.history) {
1754
+ const disp = alertDisplay(alertItem.alert, alertItem.source);
1755
+ const cell = el("td", {}, disp.label);
1756
+ if (disp.sub) cell.title = disp.sub;
1757
+ tbody.append(el("tr", {},
1758
+ cell, el("td", {}, alertItem.source),
1759
+ el("td", {}, fmtDT(alertItem.first_ts)),
1760
+ el("td", {}, alertItem.cleared_ts ? fmtDT(alertItem.cleared_ts) : "—"),
1761
+ el("td", { class: "num" }, fmtDur((alertItem.cleared_ts ?? now) - alertItem.first_ts)),
1762
+ el("td", {}, alertItem.active ? chipFor("critical", "active") : chipFor("good", "cleared"))));
1763
+ }
1764
+ tbl.append(tbody);
1765
+ wrap.append(tbl);
1766
+ }
1767
+ root.append(wrap);
1768
+
1769
+ // The official fault-category table is static reference material; it lives
1770
+ // on its own page so the timeline below stays one short scroll away.
1771
+ root.append(el("div", { class: "note" },
1772
+ el("a", { href: "#/alerts/reference" }, "Alert reference — official fault categories →"),
1773
+ " Tesla's LED blink patterns and what each fault means."));
1774
+
1775
+ root.append(el("h2", {}, "Event timeline"),
1776
+ el("div", { class: "note" },
1777
+ "Every recorded state change with its exact local timestamp — use this to reconstruct the operating conditions around an error, " +
1778
+ "then open the matching session for the telemetry at that moment."));
1779
+
1780
+ // The timeline grows without bound, so it gets its own range, category
1781
+ // filters, and incremental paging — independent of the page-level range
1782
+ // so narrowing the timeline doesn't refetch the alert history above.
1783
+ const EVENT_GROUPS = [
1784
+ { key: "charging", label: "Charging & sessions",
1785
+ kinds: ["session_start", "session_end", "charging_start", "charging_stop"] },
1786
+ { key: "evse", label: "EVSE state",
1787
+ kinds: ["evse_state_change", "evse_not_ready_change"] },
1788
+ { key: "alerts", label: "Alerts & thermal",
1789
+ kinds: ["alert_raised", "alert_cleared", "thermal_drift", "thermal_drift_cleared",
1790
+ "derate_warning", "derate_warning_cleared", "charger_reboot",
1791
+ "amp_capped", "amp_restored", "amp_adjust_failed"] },
1792
+ { key: "conn", label: "Connectivity",
1793
+ kinds: ["poll_error", "poll_recovered", "wifi_disconnected", "wifi_reconnected",
1794
+ "internet_lost", "internet_restored"] },
1795
+ { key: "monitor", label: "Monitor",
1796
+ kinds: ["monitor_start", "monitor_stop", "monitor_gap", "firmware_changed"] },
1797
+ ];
1798
+ const TL_PAGE = 100;
1799
+ const tl = { rangeKey, groups: new Set(EVENT_GROUPS.map((group) => group.key)), events: [], shown: TL_PAGE };
1800
+ const tlControls = el("div", {});
1801
+ const tlInfo = el("div", { class: "note" });
1802
+ const tlBody = el("div", {});
1803
+ const tlPager = el("div", { class: "filters" });
1804
+ root.append(tlControls, tlInfo, tlBody, tlPager);
1805
+
1806
+ function tlVisibleEvents() {
1807
+ // With every category on, pass everything through — including any event
1808
+ // kind added later that no group lists yet.
1809
+ if (tl.groups.size === EVENT_GROUPS.length) return tl.events;
1810
+ const kinds = new Set(EVENT_GROUPS.filter((group) => tl.groups.has(group.key))
1811
+ .flatMap((group) => group.kinds));
1812
+ return tl.events.filter((event) => kinds.has(event.kind));
1813
+ }
1814
+
1815
+ function tlRender() {
1816
+ const evs = tlVisibleEvents();
1817
+ const visible = evs.slice(0, tl.shown);
1818
+ tlBody.replaceChildren(eventsTable(visible));
1819
+ const filtered = tl.groups.size < EVENT_GROUPS.length;
1820
+ tlInfo.textContent =
1821
+ `${evs.length}${tl.events.length >= 2000 ? "+" : ""} event${evs.length === 1 ? "" : "s"} in range` +
1822
+ (filtered ? ` (filtered from ${tl.events.length})` : "") +
1823
+ (visible.length < evs.length ? ` — showing the newest ${visible.length}` : "") +
1824
+ (tl.events.length >= 2000 ? " · range capped at the most recent 2000; narrow the range for older events" : "");
1825
+ tlPager.replaceChildren();
1826
+ if (visible.length < evs.length) {
1827
+ tlPager.append(
1828
+ el("button", { class: "chip", onclick: () => { tl.shown += TL_PAGE; tlRender(); } },
1829
+ `Show ${Math.min(TL_PAGE, evs.length - visible.length)} more`),
1830
+ el("button", { class: "chip", onclick: () => { tl.shown = evs.length; tlRender(); } },
1831
+ `Show all ${evs.length}`));
1832
+ }
1833
+ }
1834
+
1835
+ function tlControlsRender() {
1836
+ const rangeRow = presetRow(RANGE_PRESETS, tl.rangeKey, (key) => {
1837
+ tl.rangeKey = key;
1838
+ tl.shown = TL_PAGE;
1839
+ tlFetch();
1840
+ });
1841
+ const filterRow = el("div", { class: "filters" }, el("span", { class: "flabel" }, "Show"));
1842
+ for (const group of EVENT_GROUPS) {
1843
+ filterRow.append(el("button", {
1844
+ class: "chip" + (tl.groups.has(group.key) ? " active" : ""),
1845
+ onclick: () => {
1846
+ if (tl.groups.has(group.key)) tl.groups.delete(group.key);
1847
+ else tl.groups.add(group.key);
1848
+ tl.shown = TL_PAGE;
1849
+ tlControlsRender();
1850
+ tlRender();
1851
+ },
1852
+ }, group.label));
1853
+ }
1854
+ tlControls.replaceChildren(rangeRow, filterRow);
1855
+ }
1856
+
1857
+ async function tlFetch() {
1858
+ tlControlsRender();
1859
+ tlInfo.textContent = "Loading events…";
1860
+ try {
1861
+ const nowTs = Date.now() / 1000;
1862
+ const data = await getJSON(`/api/events?from=${nowTs - rangeSeconds(tl.rangeKey)}&to=${nowTs}`);
1863
+ tl.events = data.events; // newest first from the API
1864
+ } catch {
1865
+ tlInfo.textContent = "Could not load events.";
1866
+ return;
1867
+ }
1868
+ tlRender();
1869
+ }
1870
+
1871
+ await tlFetch();
1872
+ }
1873
+
1874
+ /* ---------------- router ---------------- */
1875
+
1876
+ let lastViewKey = "";
1877
+
1878
+ async function viewAlertReference(root) {
1879
+ // Official fault categories (from Tesla's Gen 3 manual) as a reference —
1880
+ // the numeric API codes themselves are undocumented by Tesla, so an
1881
+ // unmapped code can be cross-read against the charger's LED blink pattern.
1882
+ await loadAlertCodes(); // deep links can land here before the boot fetch resolves
1883
+ root.append(el("div", { class: "note" }, el("a", { href: "#/alerts" }, "← Alerts & events")));
1884
+ root.append(el("h2", {}, "Alert reference — official fault categories"),
1885
+ el("div", { class: "note" },
1886
+ "Tesla documents Wall Connector faults by LED blink pattern, not by the numeric codes the local API reports. " +
1887
+ "If an undocumented code appears here, check the charger's LED and the Tesla app (it names active alerts), " +
1888
+ "then teach the monitor by adding the code to alert_codes.json."));
1889
+ const cats = (alertCodes && alertCodes.categories) || [];
1890
+ if (!cats.length) {
1891
+ root.append(el("div", { class: "empty" }, "No fault-category reference data available."));
1892
+ return;
1893
+ }
1894
+ const rtbl = el("table", {},
1895
+ el("thead", {}, el("tr", {}, el("th", {}, "LED"), el("th", {}, "Fault"), el("th", {}, "Meaning / action"))));
1896
+ const rbody = el("tbody", {});
1897
+ for (const category of cats) {
1898
+ rbody.append(el("tr", {},
1899
+ el("td", {}, category.led),
1900
+ el("td", {}, category.label),
1901
+ el("td", { style: "white-space:normal" }, category.description)));
1902
+ }
1903
+ rtbl.append(rbody);
1904
+ root.append(el("div", { class: "tbl-wrap" }, rtbl));
1905
+ }
1906
+
1907
+ async function render(view, arg) {
1908
+ if (cleanup) { try { cleanup(); } catch { /* noop */ } cleanup = null; }
1909
+ // Re-rendering the same view (live session refresh) must not move the
1910
+ // reader: hold the page height during the rebuild and restore the scroll
1911
+ // position afterwards, so the browser never clamps the scroll to the top.
1912
+ const viewKey = `${view}:${arg ?? ""}`;
1913
+ const sameView = viewKey === lastViewKey;
1914
+ lastViewKey = viewKey;
1915
+ const scrollY = window.scrollY;
1916
+ const root = $("#view");
1917
+ root.style.minHeight = sameView ? `${root.offsetHeight}px` : "";
1918
+ root.textContent = "";
1919
+ const tabFor = view === "session" ? "sessions" : view === "alertref" ? "alerts" : view;
1920
+ document.querySelectorAll(".tabs a").forEach((tab) => {
1921
+ tab.classList.toggle("active", tab.dataset.view === tabFor);
1922
+ });
1923
+ try {
1924
+ if (view === "live") cleanup = await viewLive(root);
1925
+ else if (view === "sessions") await viewSessions(root, arg);
1926
+ else if (view === "session") cleanup = await viewSessionDetail(root, arg);
1927
+ else if (view === "energy") await viewEnergy(root, arg);
1928
+ else if (view === "wifi") await viewWifi(root, arg);
1929
+ else if (view === "alerts") await viewAlerts(root, arg);
1930
+ else if (view === "alertref") await viewAlertReference(root);
1931
+ } catch (ex) {
1932
+ root.append(el("div", { class: "empty" }, `Failed to load: ${ex.message}`));
1933
+ }
1934
+ if (sameView) window.scrollTo(0, scrollY);
1935
+ root.style.minHeight = "";
1936
+ }
1937
+
1938
+ // Hash router: #/view, plus two sub-routes (#/sessions/{id} and
1939
+ // #/alerts/reference) that keep their parent tab highlighted. Anything
1940
+ // unrecognized falls through to Live.
1941
+ function route() {
1942
+ const hash = location.hash || "#/live";
1943
+ const parts = hash.replace(/^#\//, "").split("/");
1944
+ if (parts[0] === "sessions" && parts[1]) render("session", parts[1]);
1945
+ else if (parts[0] === "alerts" && parts[1] === "reference") render("alertref");
1946
+ else if (["live", "sessions", "energy", "wifi", "alerts"].includes(parts[0])) render(parts[0]);
1947
+ else render("live");
1948
+ }
1949
+
1950
+ /* ---------------- boot ---------------- */
1951
+
1952
+ function tickClock() {
1953
+ const now = new Date();
1954
+ $("#clock").textContent = fmtDT(now.getTime() / 1000);
1955
+ }
1956
+
1957
+ function tzNote() {
1958
+ const offMin = -new Date().getTimezoneOffset();
1959
+ const sign = offMin >= 0 ? "+" : "-";
1960
+ const abs = Math.abs(offMin);
1961
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "local";
1962
+ $("#tz-note").textContent =
1963
+ `All timestamps are shown in ${tz} (UTC${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}); ` +
1964
+ "recorded internally as UTC from a single host clock.";
1965
+ }
1966
+
1967
+ /* ---------------- local browser notifications ----------------
1968
+ * Actionable warnings only, fired from the SSE stream while the dashboard
1969
+ * is open in any tab. Entirely local: the Notification API here involves no
1970
+ * push service and no traffic beyond this page — matching the project's
1971
+ * nothing-phones-home rule. (For warnings with the dashboard closed, point
1972
+ * WM_NOTIFY_URL at a LAN endpoint instead.)
1973
+ */
1974
+ const NOTIFY_KEY = "wm-notify";
1975
+ const NOTIFY_BUILDERS = {
1976
+ derate_warning: (d) => ["Thermal derate predicted",
1977
+ `~${fmtNum((d || {}).minutes_to_trip, 0)} min until the handle hits 65 °C and charging folds back to 50%. ` +
1978
+ ((d || {}).suggested_max_a
1979
+ ? `Set the vehicle's charge current to ≤${fmtNum(d.suggested_max_a, 0)} A to keep a sustained rate.`
1980
+ : "Reduce the vehicle's charge current.")],
1981
+ alert_raised: (d) => {
1982
+ const disp = alertDisplay(String((d || {}).alert), "device");
1983
+ return ["Wall Connector alert", disp.sub ? `${disp.label} — ${disp.sub}` : disp.label];
1984
+ },
1985
+ thermal_drift: (d) => ["Heat rise climbing vs baseline",
1986
+ `Recent sessions run +${fmtNum((d || {}).recent_rise_c, 1)} °C vs a +${fmtNum((d || {}).baseline_rise_c, 1)} °C baseline ` +
1987
+ "at the same current — inspect the handle and charge-port pins, and have the terminal torque checked."],
1988
+ poll_error: () => ["Charger unreachable",
1989
+ "Repeated polls failed — check the breaker, Wi-Fi, or the charger itself."],
1990
+ };
1991
+
1992
+ function initNotifications() {
1993
+ const btn = $("#notif-btn");
1994
+ if (!btn || !("Notification" in window)) return;
1995
+ btn.hidden = false;
1996
+ // Browsers only grant notification permission on secure origins (HTTPS or
1997
+ // localhost). Served over plain http:// on a LAN IP — the normal deploy —
1998
+ // the permission prompt silently auto-denies, so a clickable toggle would
1999
+ // be a lie. Say so instead, and point at the paths that do work.
2000
+ if (!window.isSecureContext) {
2001
+ btn.disabled = true;
2002
+ btn.textContent = "\u{1F515} warnings need HTTPS";
2003
+ btn.title =
2004
+ "Browsers only allow notifications on HTTPS or localhost. Options: open the dashboard " +
2005
+ "through an SSH tunnel (ssh -L 8480:localhost:8480 <host>, then http://localhost:8480), " +
2006
+ "serve it behind HTTPS, or use the WM_NOTIFY_URL webhook — server-side delivery that " +
2007
+ "doesn't involve the browser at all.";
2008
+ return;
2009
+ }
2010
+ const enabled = () => localStorage.getItem(NOTIFY_KEY) === "1" && Notification.permission === "granted";
2011
+ const paint = () => {
2012
+ if (Notification.permission === "denied") {
2013
+ btn.textContent = "\u{1F515} warnings blocked";
2014
+ btn.title = "Notifications are blocked for this site in the browser's settings — " +
2015
+ "re-allow them there, then click again.";
2016
+ btn.classList.remove("active");
2017
+ return;
2018
+ }
2019
+ btn.textContent = enabled() ? "\u{1F514} warnings on" : "\u{1F515} warnings off";
2020
+ btn.classList.toggle("active", enabled());
2021
+ };
2022
+ btn.onclick = async () => {
2023
+ if (enabled()) localStorage.setItem(NOTIFY_KEY, "0");
2024
+ else if ((await Notification.requestPermission()) === "granted") localStorage.setItem(NOTIFY_KEY, "1");
2025
+ paint();
2026
+ };
2027
+ paint();
2028
+ live.listeners.add((msg) => {
2029
+ if (msg.type !== "event" || !enabled()) return;
2030
+ const build = NOTIFY_BUILDERS[msg.kind];
2031
+ if (!build) return;
2032
+ // The dashboard in front of the user already shows it; notify when the
2033
+ // tab is hidden or unfocused (other window, phone in a pocket).
2034
+ if (document.visibilityState === "visible" && document.hasFocus()) return;
2035
+ try {
2036
+ const [title, body] = build(msg.detail);
2037
+ new Notification(title, { body, tag: `wm-${msg.kind}` });
2038
+ } catch { /* denied or unsupported at fire time — nothing to do */ }
2039
+ });
2040
+ }
2041
+
2042
+ window.addEventListener("hashchange", route);
2043
+ connectSSE();
2044
+ initNotifications();
2045
+ loadAlertCodes().finally(refreshStatus);
2046
+ setInterval(refreshStatus, 10000);
2047
+ setInterval(tickClock, 1000);
2048
+ tickClock();
2049
+ tzNote();
2050
+ route();