wallmonitor 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: wallmonitor
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3
5
5
  Keywords: tesla,wall-connector,ev-charging,monitoring,self-hosted,thermal-model
6
6
  Author: Fernando Gonzalez
@@ -46,15 +46,19 @@ uvx wallmonitor --demo
46
46
 
47
47
  Then open <http://127.0.0.1:8480>.
48
48
 
49
- Against your real Wall Connector (find its IP in your router's client list —
50
- it registers a DHCP hostname like `TeslaWallConnector_XXXXXX`, which some
51
- routers also make resolvable by name; add `--split-phase` on a North
52
- American split-phase install):
49
+ Against your real Wall Connector — let the tool find it on your LAN (a
50
+ polite sweep of your own subnet; nothing leaves the network), then run with
51
+ the address it prints (add `--split-phase` on a North American install):
53
52
 
54
53
  ```bash
54
+ uvx wallmonitor --discover
55
55
  uvx wallmonitor --host 192.168.1.50 --split-phase
56
56
  ```
57
57
 
58
+ On first contact the monitor pins the charger's serial number: if a
59
+ different unit ever answers at that address, it alarms and pauses recording
60
+ rather than blending two chargers' histories.
61
+
58
62
  All history lands in a single `wallmonitor.db` SQLite file — back up that
59
63
  one file and you have everything. For every option, and for running it as a
60
64
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
@@ -23,15 +23,19 @@ uvx wallmonitor --demo
23
23
 
24
24
  Then open <http://127.0.0.1:8480>.
25
25
 
26
- Against your real Wall Connector (find its IP in your router's client list —
27
- it registers a DHCP hostname like `TeslaWallConnector_XXXXXX`, which some
28
- routers also make resolvable by name; add `--split-phase` on a North
29
- American split-phase install):
26
+ Against your real Wall Connector — let the tool find it on your LAN (a
27
+ polite sweep of your own subnet; nothing leaves the network), then run with
28
+ the address it prints (add `--split-phase` on a North American install):
30
29
 
31
30
  ```bash
31
+ uvx wallmonitor --discover
32
32
  uvx wallmonitor --host 192.168.1.50 --split-phase
33
33
  ```
34
34
 
35
+ On first contact the monitor pins the charger's serial number: if a
36
+ different unit ever answers at that address, it alarms and pauses recording
37
+ rather than blending two chargers' histories.
38
+
35
39
  All history lands in a single `wallmonitor.db` SQLite file — back up that
36
40
  one file and you have everything. For every option, and for running it as a
37
41
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -22,6 +22,7 @@ from aiohttp import web
22
22
 
23
23
  from .config import parse_args
24
24
  from .db import Database
25
+ from .discover import run_discovery
25
26
  from .poller import EventBus, Poller
26
27
  from .simulator import start_simulator
27
28
  from .web import make_app
@@ -29,6 +30,19 @@ from .web import make_app
29
30
  log = logging.getLogger("wallmonitor")
30
31
 
31
32
 
33
+ async def _backfill(db: Database) -> None:
34
+ """One-time, in the background: fill diagnostics columns for rows
35
+ recorded before those columns existed. Chunked, so live polling only
36
+ ever waits a moment; a settings flag makes later startups a no-op."""
37
+ def report(done: int, total: int) -> None:
38
+ if done % 200_000 < 10_000 or done >= total:
39
+ log.info("diagnostics backfill: %d / %d rows", done, total)
40
+
41
+ touched = await asyncio.to_thread(db.backfill_diag_columns, 10_000, report)
42
+ if touched:
43
+ log.info("diagnostics backfill complete: %d rows", touched)
44
+
45
+
32
46
  async def run(argv: list[str] | None = None) -> None:
33
47
  """Construct every component, serve until cancelled, unwind in order.
34
48
 
@@ -36,6 +50,8 @@ async def run(argv: list[str] | None = None) -> None:
36
50
  then the web runner (readers), then the shared HTTP client, and close
37
51
  the database last so nothing can touch a closed connection."""
38
52
  cfg = parse_args(argv)
53
+ if cfg.discover is not None:
54
+ raise SystemExit(await run_discovery(cfg.discover, split_phase_hint=cfg.split_phase))
39
55
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
40
56
 
41
57
  sim_runner = None
@@ -49,6 +65,7 @@ async def run(argv: list[str] | None = None) -> None:
49
65
  client = aiohttp.ClientSession()
50
66
  poller = Poller(cfg, db, bus, client)
51
67
  await poller.start()
68
+ backfill = asyncio.create_task(_backfill(db), name="wallmonitor-backfill")
52
69
 
53
70
  app = make_app(db, bus, poller)
54
71
  runner = web.AppRunner(app)
@@ -62,6 +79,7 @@ async def run(argv: list[str] | None = None) -> None:
62
79
  except (KeyboardInterrupt, asyncio.CancelledError):
63
80
  pass
64
81
  finally:
82
+ backfill.cancel()
65
83
  await poller.stop()
66
84
  await runner.cleanup()
67
85
  if sim_runner:
@@ -11,6 +11,7 @@ off exponentially instead of hammering a struggling device.
11
11
  from __future__ import annotations
12
12
 
13
13
  import argparse
14
+ import re
14
15
  import os
15
16
  from dataclasses import dataclass
16
17
 
@@ -29,6 +30,15 @@ class Config:
29
30
  db_path: str = "wallmonitor.db"
30
31
  demo: bool = False
31
32
  split_phase: bool = False
33
+ # Human name for this charger, shown in the UI header, tab title and
34
+ # notifications so several instances side by side stay attributable.
35
+ label: str = ""
36
+ # Sibling instances watching other chargers, as (label, url) pairs;
37
+ # rendered as a switcher in the header so one browser hops between them.
38
+ peers: tuple[tuple[str, str], ...] = ()
39
+ # --discover [RANGE]: sweep the LAN for chargers and exit. None = not
40
+ # requested; "auto" = the host's own subnet; otherwise a CIDR.
41
+ discover: str | None = None
32
42
  # Optional LAN webhook: actionable warnings are POSTed here.
33
43
  # Local-only by design — point it at something on your own network
34
44
  # (Home Assistant, a self-hosted ntfy, node-RED); leave empty to disable.
@@ -78,11 +88,21 @@ def _env(name: str, default):
78
88
  return val
79
89
 
80
90
 
91
+ def parse_peer(spec: str) -> tuple[str, str]:
92
+ """'Label=http://host:port' → (label, url). The URL must be absolute
93
+ http(s); the label is whatever the user wants to see on the switch."""
94
+ label, sep, url = spec.partition("=")
95
+ label, url = label.strip(), url.strip()
96
+ if not sep or not label or not re.match(r"^https?://[^\s/]+", url):
97
+ raise ValueError(f"--peer expects LABEL=http://host:port, got {spec!r}")
98
+ return label, url.rstrip("/")
99
+
100
+
81
101
  def parse_args(argv: list[str] | None = None) -> Config:
82
102
  """Build the Config: CLI flag beats WM_* env var beats hardcoded default.
83
103
 
84
104
  One validation rule: --host is required unless --demo runs the built-in
85
- simulator instead of real hardware. Note the boolean flags can only
105
+ simulator instead of real hardware, or --discover is asked to find it. Note the boolean flags can only
86
106
  assert True — an env-var-enabled --demo/--split-phase has no --no-*
87
107
  override; unset the variable instead."""
88
108
  parser = argparse.ArgumentParser(
@@ -123,6 +143,29 @@ def parse_args(argv: list[str] | None = None) -> Config:
123
143
  )
124
144
  parser.add_argument("--wifi-interval", type=float, default=_env("WM_WIFI_INTERVAL", 30.0))
125
145
  parser.add_argument("--lifetime-interval", type=float, default=_env("WM_LIFETIME_INTERVAL", 60.0))
146
+ parser.add_argument(
147
+ "--label",
148
+ default=_env("WM_LABEL", ""),
149
+ help="Name for this charger, shown in the UI and notifications — useful when "
150
+ "running one instance per Wall Connector (env: WM_LABEL)",
151
+ )
152
+ parser.add_argument(
153
+ "--peer",
154
+ action="append",
155
+ default=None,
156
+ metavar="LABEL=URL",
157
+ help="Another wallmonitor instance to link from the header, e.g. "
158
+ "'Garage right=http://192.168.1.10:8481'; repeatable (env: WM_PEERS, comma-separated)",
159
+ )
160
+ parser.add_argument(
161
+ "--discover",
162
+ nargs="?",
163
+ const="auto",
164
+ default=None,
165
+ metavar="RANGE",
166
+ help="Find Wall Connectors on the LAN and exit. Sweeps this host's own subnet, "
167
+ "or the private CIDR given (e.g. 192.168.2.0/24). Never leaves the LAN.",
168
+ )
126
169
  parser.add_argument(
127
170
  "--split-phase",
128
171
  action="store_true",
@@ -144,8 +187,19 @@ def parse_args(argv: list[str] | None = None) -> Config:
144
187
  )
145
188
  args = parser.parse_args(argv)
146
189
 
147
- if not args.demo and not args.host:
148
- parser.error("--host (or WM_WC_HOST) is required unless --demo is set")
190
+ peer_specs = args.peer if args.peer is not None else [
191
+ part for part in os.getenv("WM_PEERS", "").split(",") if part.strip()
192
+ ]
193
+ try:
194
+ peers = tuple(parse_peer(spec) for spec in peer_specs)
195
+ except ValueError as ex:
196
+ parser.error(str(ex))
197
+
198
+ if not args.demo and not args.host and args.discover is None:
199
+ parser.error(
200
+ "--host (or WM_WC_HOST) is required — run `wallmonitor --discover` to find "
201
+ "your Wall Connector's address, or --demo for the built-in simulator"
202
+ )
149
203
 
150
204
  return Config(
151
205
  host=args.host,
@@ -154,6 +208,9 @@ def parse_args(argv: list[str] | None = None) -> Config:
154
208
  db_path=args.db_path,
155
209
  demo=bool(args.demo),
156
210
  split_phase=bool(args.split_phase),
211
+ label=args.label,
212
+ peers=peers,
213
+ discover=args.discover,
157
214
  notify_url=args.notify_url,
158
215
  notify_format=args.notify_format,
159
216
  vitals_interval_active=args.vitals_active,
@@ -180,8 +180,34 @@ VITALS_COLUMNS = {
180
180
  "evse_state": "evse_state",
181
181
  "config_status": "config_status",
182
182
  "uptime_s": "uptime_s",
183
+ # J1772 handshake / relay diagnostics. Added as columns later than the
184
+ # rest (they used to be read out of the raw JSON on every query, which
185
+ # made long sessions slow to chart); rows from before the column existed
186
+ # are backfilled by backfill_diag_columns and served via COALESCE until
187
+ # then.
188
+ "pilot_high_v": "pilot_high_v",
189
+ "pilot_low_v": "pilot_low_v",
190
+ "prox_v": "prox_v",
191
+ "relay_k1_v": "relay_k1_v",
192
+ "relay_k2_v": "relay_k2_v",
183
193
  }
184
194
 
195
+ # Columns added after the table was first shipped: ALTER TABLE'd in on
196
+ # open when missing (CREATE TABLE IF NOT EXISTS can't add them).
197
+ VITALS_LATER_COLUMNS = ("pilot_high_v", "pilot_low_v", "prox_v", "relay_k1_v", "relay_k2_v")
198
+ DIAG_BACKFILL_SETTING = "diag_backfill_done"
199
+
200
+
201
+ def _round_rows(rows: list[dict], digits: int = 2) -> list[dict]:
202
+ """Trim float noise before JSON: bucket averages come out with 15
203
+ digits, which roughly doubles the payload for no visible difference
204
+ on a chart. Timestamps keep full precision."""
205
+ for row in rows:
206
+ for key, value in row.items():
207
+ if key != "ts" and isinstance(value, float):
208
+ row[key] = round(value, digits)
209
+ return rows
210
+
185
211
 
186
212
  class Database:
187
213
  """Thread-safe wrapper around a single SQLite connection."""
@@ -204,6 +230,59 @@ class Database:
204
230
  )
205
231
  self._conn.executescript(SCHEMA)
206
232
  self._conn.commit()
233
+ self._migrate()
234
+ # Once every row carries the diagnostics columns, range queries stop
235
+ # mentioning raw entirely — merely referencing the blob column makes
236
+ # SQLite read it for every row, which is most of what made long
237
+ # sessions slow to chart.
238
+ self._diag_backfilled = self.get_setting(DIAG_BACKFILL_SETTING) == "1"
239
+
240
+ def _migrate(self) -> None:
241
+ """Additive column migrations (caller holds the lock)."""
242
+ have = {row[1] for row in self._conn.execute("PRAGMA table_info(vitals_samples)")}
243
+ for col in VITALS_LATER_COLUMNS:
244
+ if col not in have:
245
+ self._conn.execute(f"ALTER TABLE vitals_samples ADD COLUMN {col} REAL")
246
+ self._conn.commit()
247
+
248
+ def backfill_diag_columns(self, chunk: int = 10_000, progress=None) -> int:
249
+ """Fill the diagnostics columns for rows recorded before they
250
+ existed, from each row's raw JSON, in id-ordered chunks so the
251
+ poller's inserts only ever wait one chunk. Idempotent and
252
+ resumable; returns rows touched. Runs once — a settings flag
253
+ records completion."""
254
+ if self.get_setting(DIAG_BACKFILL_SETTING):
255
+ return 0
256
+ touched = 0
257
+ last = int(self.get_setting("diag_backfill_id") or 0)
258
+ while True:
259
+ with self._lock:
260
+ top = self._conn.execute("SELECT MAX(id) FROM vitals_samples").fetchone()[0] or 0
261
+ if last >= top:
262
+ self._execute("INSERT INTO settings(key, value) VALUES (?, '1') "
263
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
264
+ (DIAG_BACKFILL_SETTING,))
265
+ self._execute("DELETE FROM settings WHERE key = 'diag_backfill_id'")
266
+ self._diag_backfilled = True
267
+ return touched
268
+ upto = min(top, last + chunk)
269
+ cur = self._execute(
270
+ """UPDATE vitals_samples SET
271
+ pilot_high_v = json_extract(raw, '$.pilot_high_v'),
272
+ pilot_low_v = json_extract(raw, '$.pilot_low_v'),
273
+ prox_v = json_extract(raw, '$.prox_v'),
274
+ relay_k1_v = COALESCE(json_extract(raw, '$.relay_k1_v'),
275
+ json_extract(raw, '$.relay_coil_v')),
276
+ relay_k2_v = json_extract(raw, '$.relay_k2_v')
277
+ WHERE id > ? AND id <= ? AND prox_v IS NULL""",
278
+ (last, upto),
279
+ )
280
+ touched += cur.rowcount
281
+ last = upto
282
+ self._execute("INSERT INTO settings(key, value) VALUES ('diag_backfill_id', ?) "
283
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value", (str(last),))
284
+ if progress:
285
+ progress(last, top)
207
286
 
208
287
  def close(self) -> None:
209
288
  """Close the shared connection. Owner-only: called once at process
@@ -229,6 +308,8 @@ class Database:
229
308
  the complete raw JSON. Returns the new row id (the SSE frame carries
230
309
  it so clients can de-duplicate)."""
231
310
  cols = {col: raw.get(json_key) for col, json_key in VITALS_COLUMNS.items()}
311
+ if cols["relay_k1_v"] is None:
312
+ cols["relay_k1_v"] = raw.get("relay_coil_v") # older firmware's name for it
232
313
  with self._lock:
233
314
  cur = self._execute(
234
315
  f"""INSERT INTO vitals_samples
@@ -530,13 +611,23 @@ class Database:
530
611
  )
531
612
  # Handshake diagnostics live only in the raw JSON; json_extract makes
532
613
  # them chartable retroactively for every sample ever recorded.
533
- diag = """json_extract(raw, '$.pilot_high_v') AS pilot_high_v,
534
- json_extract(raw, '$.pilot_low_v') AS pilot_low_v,
535
- json_extract(raw, '$.prox_v') AS prox_v,
536
- COALESCE(json_extract(raw, '$.relay_k1_v'), json_extract(raw, '$.relay_coil_v')) AS relay_k1_v,
537
- json_extract(raw, '$.relay_k2_v') AS relay_k2_v"""
614
+ # Diagnostics are columns now; the json_extract fallback only runs
615
+ # for rows the one-time backfill hasn't reached (COALESCE stops at
616
+ # the first non-NULL, so backfilled rows never touch the JSON).
617
+ if self._diag_backfilled:
618
+ d = {col: col for col in VITALS_LATER_COLUMNS}
619
+ else:
620
+ d = {
621
+ "pilot_high_v": "COALESCE(pilot_high_v, json_extract(raw, '$.pilot_high_v'))",
622
+ "pilot_low_v": "COALESCE(pilot_low_v, json_extract(raw, '$.pilot_low_v'))",
623
+ "prox_v": "COALESCE(prox_v, json_extract(raw, '$.prox_v'))",
624
+ "relay_k1_v": "COALESCE(relay_k1_v, json_extract(raw, '$.relay_k1_v'), "
625
+ "json_extract(raw, '$.relay_coil_v'))",
626
+ "relay_k2_v": "COALESCE(relay_k2_v, json_extract(raw, '$.relay_k2_v'))",
627
+ }
628
+ diag = ", ".join(f"{expr} AS {col}" for col, expr in d.items())
538
629
  if sample_count <= max_points:
539
- return self._rows(
630
+ return _round_rows(self._rows(
540
631
  f"""SELECT ts, total_power_w, vehicle_current_a, current_a_a, current_b_a, current_c_a,
541
632
  voltage_a_v, voltage_b_v, voltage_c_v, grid_v, grid_hz,
542
633
  {t_pcba} AS pcba_temp_c, {t_handle} AS handle_temp_c, {t_mcu} AS mcu_temp_c,
@@ -545,9 +636,9 @@ class Database:
545
636
  {diag}
546
637
  FROM vitals_samples WHERE ts >= ? AND ts <= ? ORDER BY ts""",
547
638
  (t_from, t_to),
548
- )
639
+ ))
549
640
  width = (t_to - t_from) / max_points
550
- return self._rows(
641
+ return _round_rows(self._rows(
551
642
  f"""SELECT MIN(ts) AS ts, AVG(total_power_w) AS total_power_w, MAX(total_power_w) AS max_power_w,
552
643
  AVG(vehicle_current_a) AS vehicle_current_a,
553
644
  AVG(current_a_a) AS current_a_a, AVG(current_b_a) AS current_b_a,
@@ -561,15 +652,11 @@ class Database:
561
652
  MAX(vehicle_connected) AS vehicle_connected,
562
653
  MAX(contactor_closed) AS contactor_closed,
563
654
  MAX(evse_state) AS evse_state, MAX(session_id) AS session_id,
564
- AVG(json_extract(raw, '$.pilot_high_v')) AS pilot_high_v,
565
- AVG(json_extract(raw, '$.pilot_low_v')) AS pilot_low_v,
566
- AVG(json_extract(raw, '$.prox_v')) AS prox_v,
567
- AVG(COALESCE(json_extract(raw, '$.relay_k1_v'), json_extract(raw, '$.relay_coil_v'))) AS relay_k1_v,
568
- AVG(json_extract(raw, '$.relay_k2_v')) AS relay_k2_v
655
+ {", ".join(f"AVG({expr}) AS {col}" for col, expr in d.items())}
569
656
  FROM vitals_samples WHERE ts >= ? AND ts <= ?
570
657
  GROUP BY CAST((ts - ?) / ? AS INTEGER) ORDER BY ts""",
571
658
  (t_from, t_to, t_from, width),
572
- )
659
+ ))
573
660
 
574
661
  def lifetime_range(self, t_from: float, t_to: float, max_points: int = 3000) -> list[dict]:
575
662
  """Lifetime counter samples in a range (counters are monotonic, so
@@ -0,0 +1,197 @@
1
+ """Find Tesla Wall Connector(s) on the local network.
2
+
3
+ The Gen 3 advertises nothing discoverable — no mDNS, no SSDP — and its DHCP
4
+ hostname lives only inside the router. So discovery is active: a polite
5
+ TCP sweep of port 80 across one private subnet, then a content fingerprint
6
+ of each responder via ``GET /api/1/version``. Only a Wall Connector returns
7
+ JSON carrying ``firmware_version``, ``part_number`` and ``serial_number``
8
+ together, which makes false positives practically impossible.
9
+
10
+ Guardrails, because this is a network scanner shipped in a monitoring tool:
11
+ only RFC 1918 ranges are ever swept; the default range is the host's own
12
+ /24; anything wider than /22 needs to be asked for explicitly; and each
13
+ responsive host receives exactly one sub-kilobyte request.
14
+
15
+ Tesla-assigned MAC prefixes seen in the neighbour (ARP) cache are probed
16
+ first, so on a flat network the answer usually arrives before the sweep
17
+ has really begun.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import ipaddress
24
+ import json
25
+ import re
26
+ import socket
27
+ import subprocess
28
+ import sys
29
+ from dataclasses import dataclass
30
+
31
+ # IEEE OUIs registered to Tesla (cars, Powerwalls and Wall Connectors all
32
+ # draw from these). A hint for probe ordering only — identity always comes
33
+ # from the version fingerprint.
34
+ TESLA_OUIS = frozenset({"98:ED:5C", "4C:FC:AA", "54:F8:F0", "DC:44:27", "E8:E5:D6"})
35
+
36
+ FINGERPRINT_KEYS = ("firmware_version", "part_number", "serial_number")
37
+ MAX_PREFIX_DEFAULT = 22 # wider than this requires --discover with an explicit range
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Found:
42
+ ip: str
43
+ firmware_version: str
44
+ part_number: str
45
+ serial_number: str
46
+
47
+
48
+ def local_subnet() -> ipaddress.IPv4Network | None:
49
+ """The /24 containing this host's default-route address, or None when
50
+ that address isn't private (the tool then refuses to guess)."""
51
+ try:
52
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
53
+ sock.connect(("10.255.255.255", 1)) # no packet is sent for UDP connect
54
+ ip = ipaddress.ip_address(sock.getsockname()[0])
55
+ except OSError:
56
+ return None
57
+ if not ip.is_private or ip.is_loopback:
58
+ return None
59
+ return ipaddress.ip_network(f"{ip}/24", strict=False)
60
+
61
+
62
+ def parse_range(spec: str | None) -> ipaddress.IPv4Network:
63
+ """Validate a user-supplied range (or pick the local subnet). Refuses
64
+ public ranges outright and over-wide ranges unless explicit."""
65
+ if spec is None or spec == "auto":
66
+ net = local_subnet()
67
+ if net is None:
68
+ raise ValueError(
69
+ "could not determine a private local subnet; pass one explicitly, "
70
+ "e.g. --discover 192.168.1.0/24"
71
+ )
72
+ return net
73
+ net = ipaddress.ip_network(spec, strict=False)
74
+ if not isinstance(net, ipaddress.IPv4Network) or not net.is_private:
75
+ raise ValueError(f"{spec} is not a private IPv4 range; discovery never leaves the LAN")
76
+ if net.prefixlen < 16:
77
+ raise ValueError(f"{spec} is too wide ({net.num_addresses} addresses); use /16 or narrower")
78
+ return net
79
+
80
+
81
+ def arp_hints() -> list[str]:
82
+ """IPs from the neighbour cache whose MAC carries a Tesla OUI.
83
+ Best-effort: any failure just means no head start."""
84
+ commands = (["ip", "-4", "neigh"], ["arp", "-an"])
85
+ text = ""
86
+ for cmd in commands:
87
+ try:
88
+ text = subprocess.run(cmd, capture_output=True, text=True, timeout=3).stdout
89
+ except (OSError, subprocess.SubprocessError):
90
+ continue
91
+ if text:
92
+ break
93
+ hints = []
94
+ for line in text.splitlines():
95
+ mac = re.search(r"([0-9a-f]{1,2}:[0-9a-f]{1,2}:[0-9a-f]{1,2}):", line, re.I)
96
+ ip = re.search(r"(\d+\.\d+\.\d+\.\d+)", line)
97
+ if not (mac and ip):
98
+ continue
99
+ oui = ":".join(part.zfill(2) for part in mac.group(1).split(":")).upper()
100
+ if oui in TESLA_OUIS:
101
+ hints.append(ip.group(1))
102
+ return hints
103
+
104
+
105
+ async def probe(ip: str, port: int = 80, timeout: float = 1.5) -> Found | None:
106
+ """One fingerprint request. Returns the device if, and only if, the
107
+ body is the Wall Connector's version document."""
108
+ try:
109
+ reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, port), timeout=0.6)
110
+ except (OSError, asyncio.TimeoutError):
111
+ return None
112
+ try:
113
+ writer.write(
114
+ b"GET /api/1/version HTTP/1.1\r\nHost: " + ip.encode()
115
+ + b"\r\nConnection: close\r\n\r\n"
116
+ )
117
+ await writer.drain()
118
+ # The real device answers chunked over a keep-alive connection, so
119
+ # read until a complete JSON object is in hand rather than to EOF.
120
+ raw = b""
121
+ while b"}" not in raw and len(raw) < 65536:
122
+ piece = await asyncio.wait_for(reader.read(4096), timeout=timeout)
123
+ if not piece:
124
+ break
125
+ raw += piece
126
+ except (OSError, asyncio.TimeoutError):
127
+ return None
128
+ finally:
129
+ writer.close()
130
+ start, end = raw.find(b"{"), raw.rfind(b"}")
131
+ if start < 0 or end <= start:
132
+ return None
133
+ try:
134
+ info = json.loads(raw[start : end + 1])
135
+ except ValueError:
136
+ return None
137
+ if not isinstance(info, dict) or not all(isinstance(info.get(k), str) for k in FINGERPRINT_KEYS):
138
+ return None
139
+ return Found(ip, *(_clean(info[k]) for k in FINGERPRINT_KEYS))
140
+
141
+
142
+ def _clean(value: str, limit: int = 48) -> str:
143
+ """Printable ASCII only, bounded length. These strings come from
144
+ whatever answered on the LAN and go straight to the operator's
145
+ terminal; a hostile responder must not be able to smuggle control or
146
+ escape sequences into the output it is trying to get copy-pasted."""
147
+ return "".join(ch if 0x20 <= ord(ch) < 0x7F else "?" for ch in value)[:limit]
148
+
149
+
150
+ async def sweep(net: ipaddress.IPv4Network, port: int = 80, concurrency: int = 128,
151
+ hints: list[str] | None = None) -> list[Found]:
152
+ """Probe every host in the range (hinted addresses first); return all
153
+ Wall Connectors found, sorted by address."""
154
+ sem = asyncio.Semaphore(concurrency)
155
+
156
+ async def guarded(ip: str) -> Found | None:
157
+ async with sem:
158
+ return await probe(ip, port)
159
+
160
+ ordered = list(dict.fromkeys((hints or []) + [str(h) for h in net.hosts()]))
161
+ in_range = [ip for ip in ordered if ipaddress.ip_address(ip) in net]
162
+ results = await asyncio.gather(*(guarded(ip) for ip in in_range))
163
+ found = [r for r in results if r is not None]
164
+ return sorted(found, key=lambda f: ipaddress.ip_address(f.ip))
165
+
166
+
167
+ async def run_discovery(spec: str | None, split_phase_hint: bool = False) -> int:
168
+ """The --discover command: sweep, print what was found and the exact
169
+ command to run next. Exit status 0 when at least one device answered."""
170
+ try:
171
+ net = parse_range(spec)
172
+ except ValueError as ex:
173
+ print(f"discover: {ex}", file=sys.stderr)
174
+ return 2
175
+ hints = arp_hints()
176
+ print(f"Scanning {net} for Wall Connectors"
177
+ + (f" (checking {len(hints)} Tesla-MAC neighbour(s) first)" if hints else "") + " …")
178
+ found = await sweep(net, hints=hints)
179
+ if not found:
180
+ print("No Wall Connector answered on this range.")
181
+ print("If the charger lives on another subnet or VLAN, pass that range: "
182
+ "wallmonitor --discover 192.168.2.0/24")
183
+ return 1
184
+ flag = " --split-phase" if split_phase_hint else ""
185
+ print(f"Found {len(found)} Wall Connector{'s' if len(found) > 1 else ''}:")
186
+ for dev in found:
187
+ print(f" {dev.ip:<15} firmware {dev.firmware_version} part {dev.part_number}"
188
+ f" serial …{dev.serial_number[-6:]}")
189
+ print()
190
+ if len(found) == 1:
191
+ print(f"Run: wallmonitor --host {found[0].ip}{flag}")
192
+ else:
193
+ print("Run one instance per charger, each with its own --db and --port, e.g.:")
194
+ for i, dev in enumerate(found):
195
+ print(f" wallmonitor --host {dev.ip}{flag} --label wc-{i + 1} "
196
+ f"--db wc-{i + 1}.db --port {8480 + i}")
197
+ return 0
@@ -36,6 +36,9 @@ from .db import Database
36
36
 
37
37
  log = logging.getLogger("wallmonitor.poller")
38
38
 
39
+ IDENTITY_ALERT = "Different charger at this address"
40
+ SERIAL_SETTING = "device_serial"
41
+
39
42
 
40
43
  class EventBus:
41
44
  """Fan-out of live updates to SSE subscribers."""
@@ -105,6 +108,12 @@ class Poller:
105
108
  self._verify_resumed = False
106
109
  # per-endpoint scheduling state: next due time and current backoff interval
107
110
  self._due: dict[str, float] = {"vitals": 0.0, "wifi": 0.0, "lifetime": 0.0, "version": 0.0}
111
+ # Device identity. The serial pinned on first contact is the charger
112
+ # this database belongs to; until this run has confirmed the device
113
+ # at --host carries it, nothing is recorded (see _poll).
114
+ self.device_serial: str | None = None
115
+ self.serial_mismatch: str | None = None
116
+ self._identity_checked = False
108
117
  self._fail_streak: dict[str, int] = dict.fromkeys(self._due, 0)
109
118
  # device state tracking
110
119
  self._prev_vitals: dict | None = None
@@ -154,11 +163,15 @@ class Poller:
154
163
  # still connected once we get our first sample; remember it for now.
155
164
  self._session_id = self.db.open_session_id()
156
165
  self._verify_resumed = self._session_id is not None
166
+ self.device_serial = self.db.get_setting(SERIAL_SETTING)
157
167
  for alert in self.db.active_alerts():
158
168
  if alert["source"] == "device":
159
169
  self._active_alerts.add(alert["alert"])
160
170
  elif alert["alert"] == thermal.DERATE_ALERT:
161
171
  self._derate_active = True
172
+ elif alert["alert"] == IDENTITY_ALERT:
173
+ # Re-latch so the first matching serial this run clears it.
174
+ self.serial_mismatch = "?"
162
175
 
163
176
  async def stop(self) -> None:
164
177
  """Signal the loop, wait for it to finish, record monitor_stop."""
@@ -186,6 +199,10 @@ class Poller:
186
199
  due_now = [ep for ep, due_ts in self._due.items() if now >= due_ts]
187
200
  if due_now:
188
201
  endpoint = min(due_now, key=lambda ep: self._due[ep])
202
+ # Identity before data: until this run has read the serial,
203
+ # the only endpoint worth polling is version.
204
+ if not self._identity_checked:
205
+ endpoint = "version"
189
206
  await self._poll(endpoint, handlers[endpoint])
190
207
  next_due = min(self._due.values())
191
208
  delay = max(0.05, min(next_due - time.time(), 1.0))
@@ -236,6 +253,12 @@ class Poller:
236
253
  # active by a previous run that never recovered before exiting.
237
254
  await asyncio.to_thread(self.db.clear_alert, ts, "Wall Connector unreachable", "monitor")
238
255
  self._had_success = True
256
+ if endpoint != "version" and (not self._identity_checked or self.serial_mismatch):
257
+ # Unverified or wrong device: poll (so recovery is noticed) but
258
+ # record nothing — blending another charger's telemetry into
259
+ # this database's per-install history is the one unrecoverable
260
+ # failure, so it is the one we refuse outright.
261
+ return
239
262
  try:
240
263
  await handler(ts, raw)
241
264
  except Exception:
@@ -249,13 +272,17 @@ class Poller:
249
272
  dropped packet doesn't page anyone."""
250
273
  ts = time.time()
251
274
  streak = self._fail_streak[endpoint] = self._fail_streak[endpoint] + 1
252
- base = self._base_interval(endpoint)
275
+ # Until identity is verified the version probe carries the run, so it
276
+ # retries on the vitals cadence (not its own six-hour one) and its
277
+ # failures are what count as "unreachable".
278
+ liveness = "vitals" if self._identity_checked else "version"
279
+ base = self._base_interval(endpoint if self._identity_checked else "vitals")
253
280
  backoff = min(base * (self.cfg.backoff_factor ** min(streak, 8)), self.cfg.backoff_max)
254
281
  self._due[endpoint] = ts + backoff
255
282
  self.last_poll_error = f"{type(ex).__name__}: {ex}"
256
283
  log.warning("poll %s failed (streak %d, retry in %.0fs): %s", endpoint, streak, backoff, ex)
257
- # Declare the device offline after 3 consecutive vitals failures.
258
- if endpoint == "vitals" and streak == 3 and not self._offline:
284
+ # Declare the device offline after 3 consecutive liveness failures.
285
+ if endpoint == liveness and streak == 3 and not self._offline:
259
286
  self._offline = True
260
287
  await asyncio.to_thread(self.db.raise_alert, ts, "Wall Connector unreachable", "monitor")
261
288
  await asyncio.to_thread(self.db.add_event, ts, "poll_error", {"endpoint": endpoint, "error": str(ex)})
@@ -413,8 +440,12 @@ class Poller:
413
440
  self.bus.publish({"type": "lifetime", "ts": ts, "data": raw})
414
441
 
415
442
  async def _handle_version(self, ts: float, raw: dict) -> None:
416
- """Store version info only when it changed (it's polled every 6 h
417
- but almost never differs), and event on firmware changes."""
443
+ """Verify device identity, then store version info only when it
444
+ changed (it's polled every 6 h but almost never differs), and event
445
+ on firmware changes."""
446
+ await self._check_identity(ts, raw.get("serial_number"))
447
+ if self.serial_mismatch:
448
+ return
418
449
  latest = await asyncio.to_thread(self.db.latest_version)
419
450
  if latest is not None and latest.get("firmware_version") != raw.get("firmware_version"):
420
451
  await self._event(
@@ -425,6 +456,44 @@ class Poller:
425
456
  if latest is None or json.loads(latest["raw"]) != raw:
426
457
  await asyncio.to_thread(self.db.insert_version, ts, raw)
427
458
 
459
+ async def _check_identity(self, ts: float, serial: str | None) -> None:
460
+ """Pin the serial on first contact; afterwards insist on it.
461
+
462
+ The database's thermal model, degradation trend and session history
463
+ describe one physical charger. If a different one answers at --host
464
+ (DHCP reshuffle, a second unit, a typo) we alarm and stop recording
465
+ until the right device is back, rather than quietly fit a chimera."""
466
+ self._identity_checked = True
467
+ if not serial:
468
+ return # firmware that doesn't report one: nothing to pin against
469
+ if self.device_serial is None:
470
+ self.device_serial = serial
471
+ await asyncio.to_thread(self.db.set_setting, SERIAL_SETTING, serial)
472
+ await self._event(ts, "device_pinned", {"serial": serial, "host": self.cfg.host})
473
+ return
474
+ if serial != self.device_serial:
475
+ if self.serial_mismatch != serial:
476
+ self.serial_mismatch = serial
477
+ log.error("serial mismatch at %s: expected %s, found %s — recording suspended",
478
+ self.cfg.host, self.device_serial, serial)
479
+ await asyncio.to_thread(self.db.raise_alert, ts, IDENTITY_ALERT, "monitor")
480
+ await self._event(ts, "device_mismatch",
481
+ {"expected": self.device_serial, "found": serial, "host": self.cfg.host})
482
+ await self._notify(
483
+ "device_mismatch", IDENTITY_ALERT,
484
+ f"{self.cfg.host} now answers as serial …{serial[-6:]}, but this database "
485
+ f"belongs to …{self.device_serial[-6:]}. Recording is paused until the "
486
+ "right charger is back at this address (or --host is corrected).",
487
+ {"expected": self.device_serial, "found": serial},
488
+ )
489
+ # Re-check soon rather than in six hours.
490
+ self._due["version"] = ts + max(30.0, self.cfg.vitals_interval_idle * 6)
491
+ return
492
+ if self.serial_mismatch:
493
+ self.serial_mismatch = None
494
+ await asyncio.to_thread(self.db.clear_alert, ts, IDENTITY_ALERT, "monitor")
495
+ await self._event(ts, "device_restored", {"serial": serial, "host": self.cfg.host})
496
+
428
497
  async def recheck_thermal_drift(self, ts: float) -> None:
429
498
  """Refit history and raise/clear the degradation alert.
430
499
 
@@ -580,6 +649,8 @@ class Poller:
580
649
  custom receivers); "ntfy" posts plain text with ntfy's publish
581
650
  headers so notify_url can be a self-hosted ntfy topic directly.
582
651
  """
652
+ if self.cfg.label:
653
+ title = f"[{self.cfg.label}] {title}"
583
654
  url = self.cfg.notify_url
584
655
  if not url:
585
656
  return
@@ -616,6 +687,10 @@ class Poller:
616
687
  the footer's "watching …" line)."""
617
688
  return {
618
689
  "host": self.cfg.host,
690
+ "label": self.cfg.label,
691
+ "peers": [{"label": label, "url": url} for label, url in self.cfg.peers],
692
+ "device_serial": self.device_serial,
693
+ "serial_mismatch": self.serial_mismatch,
619
694
  "offline": self._offline,
620
695
  "last_poll_ok_ts": self.last_poll_ok_ts,
621
696
  "last_poll_error": self.last_poll_error,
@@ -36,11 +36,13 @@ class SimState:
36
36
  world as of "now", and a test can pin `start` to make it deterministic."""
37
37
 
38
38
  def __init__(
39
- self, speedup: float = 1.0, start: float | None = None, split_phase: bool = False
39
+ self, speedup: float = 1.0, start: float | None = None, split_phase: bool = False,
40
+ serial: str = "SIM12345678901",
40
41
  ):
41
42
  self.t0 = start if start is not None else time.time()
42
43
  self.speedup = speedup
43
44
  self.split_phase = split_phase
45
+ self.serial = serial
44
46
  self.boot_ts = self.t0
45
47
  self.lifetime_energy_wh = 2_566_837.0
46
48
  self.charge_starts = 450
@@ -171,7 +173,7 @@ class SimState:
171
173
  "firmware_version": "24.36.3+gsimulated00",
172
174
  "git_branch": "HEAD",
173
175
  "part_number": "1529455-02-D",
174
- "serial_number": "SIM12345678901",
176
+ "serial_number": self.serial,
175
177
  "web_service": "h3-hermes-prd.sn.tesla.services",
176
178
  }
177
179
 
@@ -224,10 +226,12 @@ def make_app(state: SimState | None = None) -> web.Application:
224
226
 
225
227
 
226
228
  async def start_simulator(
227
- port: int = 0, speedup: float = 1.0, start: float | None = None, split_phase: bool = False
229
+ port: int = 0, speedup: float = 1.0, start: float | None = None, split_phase: bool = False,
230
+ serial: str = "SIM12345678901",
228
231
  ) -> tuple[web.AppRunner, int]:
229
232
  """Start the simulator on localhost. Returns (runner, bound_port)."""
230
- runner = web.AppRunner(make_app(SimState(speedup=speedup, start=start, split_phase=split_phase)))
233
+ state = SimState(speedup=speedup, start=start, split_phase=split_phase, serial=serial)
234
+ runner = web.AppRunner(make_app(state))
231
235
  await runner.setup()
232
236
  site = web.TCPSite(runner, "127.0.0.1", port)
233
237
  await site.start()
@@ -161,6 +161,10 @@ function alertDisplay(alertStr, source) {
161
161
  // 255 (0xFF) is the device's "sensor read invalid" sentinel for temperatures.
162
162
  const realTemp = (value) => (value != null && value >= 255 ? null : value);
163
163
 
164
+ // Forecast ticks arrive every 30 s while charging; a break longer than this
165
+ // means charging stopped, and the dashed forecast line must not bridge it.
166
+ const FORECAST_GAP_S = 300;
167
+
164
168
  // Community-observed (not Tesla-published) circuit-board temperature at which
165
169
  // the Gen 3 begins throttling charge current. Shown as a reference line so
166
170
  // headroom is visible; ambient-driven foldback in hot installs is the usual
@@ -351,7 +355,8 @@ function scatterChart(box, opts) {
351
355
  // unit?, digits?, height?, area? (single series only), zeroBase?, xFrom?,
352
356
  // xTo?, refLines?: [{value, label, below?}]}) — time-series lines with a
353
357
  // shared crosshair tooltip and auto legend (≥ 2 series). Null/non-finite
354
- // values are dropped per series (the path connects across gaps). Every call
358
+ // values are dropped per series (the path connects across them unless the
359
+ // series sets `gap`, seconds, beyond which the line breaks). Every call
355
360
  // is a full teardown + redraw; there is no incremental update path, which is
356
361
  // what makes 2 s live refreshes safe to reason about.
357
362
  function lineChart(box, opts) {
@@ -415,15 +420,22 @@ function lineChart(box, opts) {
415
420
 
416
421
  for (const dataset of series) {
417
422
  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("");
423
+ // A series with `gap` (seconds) is drawn as separate runs wherever two
424
+ // consecutive points are further apart than that — the forecast only
425
+ // exists while charging, and bridging a multi-hour idle stretch with
426
+ // one straight segment invents a slope nobody predicted.
427
+ const pathData = dataset.points.map((point, idx) => {
428
+ const broken = idx && dataset.gap && point[0] - dataset.points[idx - 1][0] > dataset.gap;
429
+ return `${idx && !broken ? "L" : "M"}${xOf(point[0]).toFixed(1)},${yOf(point[1]).toFixed(1)}`;
430
+ }).join("");
420
431
  if (opts.area && series.length === 1) {
421
432
  const areaPath = pathData + `L${xOf(dataset.points[dataset.points.length - 1][0]).toFixed(1)},${yOf(yt.min).toFixed(1)}` +
422
433
  `L${xOf(dataset.points[0][0]).toFixed(1)},${yOf(yt.min).toFixed(1)}Z`;
423
434
  root.append(svg("path", { d: areaPath, fill: dataset.color, "fill-opacity": 0.1, stroke: "none" }));
424
435
  }
425
- const stroke = { d: pathData, fill: "none", stroke: dataset.color, "stroke-width": 2, "stroke-linejoin": "round", "stroke-linecap": "round" };
436
+ const stroke = { d: pathData, fill: "none", stroke: dataset.color, "stroke-width": dataset.width || 2, "stroke-linejoin": "round", "stroke-linecap": "round" };
426
437
  if (dataset.dash) stroke["stroke-dasharray"] = dataset.dash;
438
+ if (dataset.opacity != null) stroke["stroke-opacity"] = dataset.opacity;
427
439
  root.append(svg("path", stroke));
428
440
  }
429
441
 
@@ -763,6 +775,35 @@ function connectSSE() {
763
775
  es.onerror = () => setConnDot(false, "stream reconnecting…");
764
776
  }
765
777
 
778
+ // Device identity in the header: the --label if one was given, else the
779
+ // serial tail, so several instances side by side stay attributable — and
780
+ // the tab title carries it too, for the same reason.
781
+ function renderDeviceChip(poller) {
782
+ const chip = $("#device-chip");
783
+ const serial = poller.device_serial || "";
784
+ const name = poller.label || (serial ? `serial …${serial.slice(-6)}` : "");
785
+ if (!name) { chip.hidden = true; document.title = "Wall Connector Monitor"; return; }
786
+ chip.hidden = false;
787
+ chip.textContent = name;
788
+ chip.title = serial ? `Pinned to serial ${serial}` : "Which charger this instance watches";
789
+ chip.classList.toggle("bad", Boolean(poller.serial_mismatch));
790
+ document.title = `${poller.label || name} · Wall Connector Monitor`;
791
+ }
792
+
793
+ // Sibling instances (--peer): one chip per other charger, linking straight
794
+ // to its dashboard, with this page's current view carried along so hopping
795
+ // between chargers keeps you on the same tab.
796
+ function renderPeers(peers) {
797
+ const nav = $("#peer-switch");
798
+ nav.textContent = "";
799
+ if (!peers.length) { nav.hidden = true; return; }
800
+ nav.hidden = false;
801
+ nav.append(el("span", { class: "peers-label" }, "also:"));
802
+ for (const peer of peers) {
803
+ nav.append(el("a", { class: "chip", href: peer.url + "/" + (location.hash || ""), title: `Open ${peer.label}` }, peer.label));
804
+ }
805
+ }
806
+
766
807
  function setConnDot(ok, text) {
767
808
  const dot = $("#conn-dot"), textEl = $("#conn-text");
768
809
  dot.className = "dot " + (ok ? "ok" : "bad");
@@ -774,8 +815,11 @@ async function refreshStatus() {
774
815
  const st = await getJSON("/api/status");
775
816
  live.status = st;
776
817
  const poller = st.poller || {};
818
+ renderDeviceChip(poller);
819
+ renderPeers(poller.peers || []);
777
820
  const stale = st.vitals ? (st.server_ts - st.vitals.ts) : null;
778
821
  if (poller.offline) setConnDot(false, `charger unreachable (${poller.last_poll_error || "no response"})`);
822
+ else if (poller.serial_mismatch) setConnDot(false, `wrong charger at ${poller.host} — recording paused`);
779
823
  else if (st.vitals) setConnDot(true, `charger online — last sample ${stale < 2 ? "now" : fmtDur(stale) + " ago"}`);
780
824
  else setConnDot(false, "no data yet");
781
825
  renderBanner(st.active_alerts || []);
@@ -1106,7 +1150,7 @@ async function viewLive(root) {
1106
1150
  };
1107
1151
  const series = [
1108
1152
  { 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]) },
1153
+ { name: "Projected plateau (if this current holds)", color: colors.s5, dash: "6 4", gap: FORECAST_GAP_S, points: tbuf.map((point) => [point.ts, point.steady]) },
1110
1154
  { name: "Garage ambient", color: colors.s3, points: thin(abuf.filter((point) => point[0] >= xFrom)) },
1111
1155
  ];
1112
1156
  if (projecting) {
@@ -1314,7 +1358,9 @@ async function viewSessionDetail(root, id) {
1314
1358
  const temp = chartCard("Temperatures",
1315
1359
  `Plug handle, charger circuit board (PCBA), and processor (MCU). At ${HANDLE_TRIP_C}°C on the handle, alert 40 raises ` +
1316
1360
  `and current is halved (observed on this firmware); the ≈${PCBA_THROTTLE_C}°C line is the community-observed PCBA throttle point. ` +
1317
- `The dashed line is the plateau the forecast predicted at each 30 s tick — watch it converge onto the measured curve as the fit gets data.`);
1361
+ `The dashed line is the plateau the forecast predicted at each 30 s tick — where the handle would settle if that current held, ` +
1362
+ `not where a short top-off will stop. Faint dots are the model-only estimate before the handle has produced trajectory data; ` +
1363
+ `watch the firm line converge onto the measured curve as the fit gets data.`);
1318
1364
  const pilot = chartCard("Pilot & proximity", "J1772 handshake signals — flaky values here often precede charging errors");
1319
1365
  const relay = chartCard("Relay voltages", "Contactor coil drive");
1320
1366
  const eventsWrap = el("div", {});
@@ -1368,16 +1414,34 @@ async function viewSessionDetail(root, id) {
1368
1414
  // would plateau at, at each 30 s tick. Early guesses run high on thin
1369
1415
  // trajectory data and converge as the fit firms up — that convergence
1370
1416
  // is the point of drawing it against the measured curve.
1371
- const forecastPts = fullForecasts
1372
- .filter((row) => row.ts >= xFrom && row.ts <= xTo)
1373
- .map((row) => [row.ts, row.steady_state_c]);
1417
+ // Two series by basis. Before the handle has produced a few minutes of
1418
+ // trajectory, the forecaster answers from the model alone (ambient +
1419
+ // rise at the present current) — the honest asymptote, but it ramps up
1420
+ // from ambient as current ramps and reads like a spike on short
1421
+ // top-offs. Those early ticks are drawn faint; the trajectory-based
1422
+ // ticks are the line to read. The boundary tick is shared so the two
1423
+ // runs join instead of leaving a hole.
1424
+ const inWindow = fullForecasts.filter((row) => row.ts >= xFrom && row.ts <= xTo);
1425
+ const earlyPts = [], firmPts = [];
1426
+ inWindow.forEach((row, idx) => {
1427
+ const firm = row.basis === "trajectory";
1428
+ const point = [row.ts, row.steady_state_c];
1429
+ (firm ? firmPts : earlyPts).push(point);
1430
+ const next = inWindow[idx + 1];
1431
+ if (!firm && next && next.basis === "trajectory" && next.ts - row.ts <= FORECAST_GAP_S) firmPts.push(point);
1432
+ });
1374
1433
  const tempSeries = [
1375
1434
  { name: "Circuit board (PCBA)", color: colors.s1, points: samples.map((sample) => [sample.ts, sample.tPcba]) },
1376
1435
  { name: "Plug handle", color: colors.s2, points: samples.map((sample) => [sample.ts, sample.tHandle]) },
1377
1436
  { name: "Processor (MCU)", color: colors.s3, points: samples.map((sample) => [sample.ts, sample.tMcu]) },
1378
1437
  ];
1379
- if (forecastPts.length) {
1380
- tempSeries.push({ name: "Predicted plateau", color: colors.s5, dash: "6 4", points: forecastPts });
1438
+ if (earlyPts.length) {
1439
+ tempSeries.push({ name: "Early estimate (model only, no trajectory yet)", color: colors.s5, dash: "2 4",
1440
+ width: 1.5, opacity: 0.45, gap: FORECAST_GAP_S, points: earlyPts });
1441
+ }
1442
+ if (firmPts.length) {
1443
+ tempSeries.push({ name: "Predicted plateau (if this current holds)", color: colors.s5, dash: "6 4",
1444
+ gap: FORECAST_GAP_S, points: firmPts });
1381
1445
  }
1382
1446
  lineChart(temp.box, {
1383
1447
  series: tempSeries, unit: "°C", digits: 1, xFrom, xTo, height: 190,
@@ -10,6 +10,8 @@
10
10
  <body>
11
11
  <header class="topbar">
12
12
  <div class="brand">&#9889; Wall Connector Monitor</div>
13
+ <span id="device-chip" class="chip device" hidden title="Which charger this instance watches"></span>
14
+ <nav id="peer-switch" class="peers" hidden aria-label="Other chargers"></nav>
13
15
  <nav class="tabs">
14
16
  <a href="#/live" data-view="live">Live</a>
15
17
  <a href="#/sessions" data-view="sessions">Sessions</a>
@@ -57,6 +57,11 @@ body {
57
57
  position: sticky; top: 0; z-index: 20;
58
58
  }
59
59
  .brand { font-weight: 650; font-size: 15px; }
60
+ .chip.device { cursor: default; font-weight: 600; color: var(--text-primary); }
61
+ .chip.device.bad { color: var(--status-critical); border-color: var(--status-critical); }
62
+ .peers { display: flex; align-items: center; gap: 6px; }
63
+ .peers-label { color: var(--text-muted); font-size: 12px; }
64
+ .peers a.chip { text-decoration: none; }
60
65
  .tabs { display: flex; gap: 4px; }
61
66
  .tabs a {
62
67
  color: var(--text-secondary); text-decoration: none;
@@ -32,6 +32,23 @@ def _float_q(request: web.Request, name: str, default: float) -> float:
32
32
  return default
33
33
 
34
34
 
35
+ @web.middleware
36
+ async def _compress_json(request: web.Request, handler):
37
+ """gzip the JSON API when the client accepts it. A session page is a
38
+ megabyte of numbers that compresses ~8×; the SSE stream and static
39
+ files are left alone (streams must not be buffered, and the UI assets
40
+ are small)."""
41
+ response = await handler(request)
42
+ if (
43
+ isinstance(response, web.Response)
44
+ and response.body is not None
45
+ and response.content_type == "application/json"
46
+ and len(response.body) > 2048
47
+ ):
48
+ response.enable_compression()
49
+ return response
50
+
51
+
35
52
  def make_app(db: Database, bus: EventBus, poller: Poller | None) -> web.Application:
36
53
  """Assemble the HTTP app: static UI, JSON API, SSE stream, two ingests.
37
54
 
@@ -42,7 +59,7 @@ def make_app(db: Database, bus: EventBus, poller: Poller | None) -> web.Applicat
42
59
  reads come from the DB, live data from the poller's EventBus. poller is
43
60
  None only in tests that exercise the API without a device.
44
61
  """
45
- app = web.Application()
62
+ app = web.Application(middlewares=[_compress_json])
46
63
 
47
64
  # Without cache headers browsers cache heuristically, so after an update
48
65
  # they may keep running stale UI code until a manual hard refresh.