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.
wallmonitor/poller.py ADDED
@@ -0,0 +1,630 @@
1
+ """Polling engine: reads the Wall Connector and records everything.
2
+
3
+ Safety model (the "highest fidelity the device can safely operate" part):
4
+ - Requests are strictly sequential — never more than one in flight. The Gen 3
5
+ Wall Connector runs a small embedded web server that degrades under
6
+ concurrent or very aggressive polling.
7
+ - Vitals cadence adapts: tight (default 2s) while a vehicle is attached,
8
+ relaxed (default 5s) while idle. Lower-value endpoints (wifi, lifetime,
9
+ version) poll far less often.
10
+ - Consecutive failures back off exponentially up to a cap, so a struggling or
11
+ rebooting device is left alone instead of hammered.
12
+
13
+ Timekeeping: every stored record and event carries the host's UTC epoch time
14
+ captured when the response arrived. One clock for samples, sessions, alerts
15
+ and events, so timelines line up exactly. The charger's own uptime_s is also
16
+ stored with each sample so device-side time can be cross-referenced.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import json
23
+ import logging
24
+ import time
25
+ from typing import Any
26
+
27
+ import aiohttp
28
+
29
+ from tesla_wall_connector import WallConnector
30
+ from tesla_wall_connector.exceptions import WallConnectorError
31
+ from tesla_wall_connector.wifi_status import WifiStatus
32
+
33
+ from . import thermal
34
+ from .config import Config
35
+ from .db import Database
36
+
37
+ log = logging.getLogger("wallmonitor.poller")
38
+
39
+
40
+ class EventBus:
41
+ """Fan-out of live updates to SSE subscribers."""
42
+
43
+ def __init__(self) -> None:
44
+ self._subscribers: set[asyncio.Queue] = set()
45
+
46
+ def subscribe(self) -> asyncio.Queue:
47
+ """New bounded queue receiving every published message from now on.
48
+ The bound (500) is the contract: a subscriber that stops draining
49
+ gets dropped by publish() rather than allowed to grow unbounded."""
50
+ queue: asyncio.Queue = asyncio.Queue(maxsize=500)
51
+ self._subscribers.add(queue)
52
+ return queue
53
+
54
+ def unsubscribe(self, queue: asyncio.Queue) -> None:
55
+ self._subscribers.discard(queue)
56
+
57
+ def publish(self, message: dict) -> None:
58
+ """Fan one message out to every subscriber, never blocking."""
59
+ for queue in list(self._subscribers):
60
+ try:
61
+ queue.put_nowait(message)
62
+ except asyncio.QueueFull:
63
+ # Slow consumer: drop it rather than stall the poller.
64
+ self._subscribers.discard(queue)
65
+
66
+
67
+ def _total_power(raw: dict, split_phase: bool) -> float | None:
68
+ """Instantaneous vehicle power (W) from one vitals body: grid_v ×
69
+ vehicle_current for a North American split-phase install, else the sum
70
+ of per-phase V×I. None when fields are missing (device still booting)."""
71
+ try:
72
+ if split_phase:
73
+ return round(raw["grid_v"] * raw["vehicle_current_a"], 1)
74
+ return round(
75
+ raw["voltageA_v"] * raw["currentA_a"]
76
+ + raw["voltageB_v"] * raw["currentB_a"]
77
+ + raw["voltageC_v"] * raw["currentC_a"],
78
+ 1,
79
+ )
80
+ except (KeyError, TypeError):
81
+ return None
82
+
83
+
84
+ class Poller:
85
+ """The single owner of all Wall Connector I/O.
86
+
87
+ One asyncio task polls the four device endpoints on their own cadences,
88
+ stores every response, derives events/alerts by diffing against the
89
+ previous sample, runs the in-line derate forecast, and publishes live
90
+ frames on the EventBus. The web layer never talks to the charger — it
91
+ reads the DB and this object's status() — so dashboard load can never
92
+ add device load.
93
+
94
+ Threading model: everything here runs on the event loop; the only
95
+ blocking work (SQLite) hops to a worker thread via asyncio.to_thread,
96
+ which is safe because Database serializes access internally.
97
+ """
98
+
99
+ def __init__(self, cfg: Config, db: Database, bus: EventBus, session: aiohttp.ClientSession):
100
+ self.cfg = cfg
101
+ self.db = db
102
+ self.bus = bus
103
+ self._http = session
104
+ self.wc = WallConnector(host=cfg.host, timeout=cfg.request_timeout, session=session)
105
+ self._verify_resumed = False
106
+ # per-endpoint scheduling state: next due time and current backoff interval
107
+ self._due: dict[str, float] = {"vitals": 0.0, "wifi": 0.0, "lifetime": 0.0, "version": 0.0}
108
+ self._fail_streak: dict[str, int] = dict.fromkeys(self._due, 0)
109
+ # device state tracking
110
+ self._prev_vitals: dict | None = None
111
+ self._prev_wifi: dict | None = None
112
+ self._session_id: int | None = None
113
+ self._active_alerts: set[str] = set()
114
+ self._offline = False
115
+ self._had_success = False
116
+ # Thermal params for the in-poller derate forecast: fitted lazily,
117
+ # refreshed whenever a session closes (the only time fits change).
118
+ self._params: thermal.ThermalParams | None = None
119
+ self._next_forecast_ts = 0.0
120
+ self._derate_active = False
121
+ self._alert_labels: dict | None = None
122
+ self.last_poll_ok_ts: float | None = None
123
+ self.last_poll_error: str | None = None
124
+ self.started_ts = time.time()
125
+ self._stop = asyncio.Event()
126
+
127
+ # ---------- lifecycle ----------
128
+
129
+ async def start(self) -> None:
130
+ """Reconcile persisted state with reality, then launch the poll task."""
131
+ now = time.time()
132
+ await asyncio.to_thread(self._startup_reconcile, now)
133
+ self._task = asyncio.create_task(self._run(), name="wallmonitor-poller")
134
+
135
+ # A hole longer than this since the last recorded activity is reported as
136
+ # a monitoring gap (covers hard reboots that never wrote monitor_stop).
137
+ GAP_THRESHOLD_S = 120.0
138
+
139
+ def _startup_reconcile(self, now: float) -> None:
140
+ """Runs once (in a thread) before the first poll: record any
141
+ monitoring gap plus monitor_start, adopt a session the previous run
142
+ left open (its legitimacy is verified against the charger's own
143
+ session timer on the first sample), and re-latch alerts that were
144
+ active when the last run exited so they clear on real edges."""
145
+ last = self.db.last_activity_ts()
146
+ if last is not None and now - last > self.GAP_THRESHOLD_S:
147
+ self.db.add_event(
148
+ now,
149
+ "monitor_gap",
150
+ {"offline_since": last, "gap_s": round(now - last, 1)},
151
+ )
152
+ self.db.add_event(now, "monitor_start", {"host": self.cfg.host})
153
+ # A session left open by a previous run: keep it only if the vehicle is
154
+ # still connected once we get our first sample; remember it for now.
155
+ self._session_id = self.db.open_session_id()
156
+ self._verify_resumed = self._session_id is not None
157
+ for alert in self.db.active_alerts():
158
+ if alert["source"] == "device":
159
+ self._active_alerts.add(alert["alert"])
160
+ elif alert["alert"] == thermal.DERATE_ALERT:
161
+ self._derate_active = True
162
+
163
+ async def stop(self) -> None:
164
+ """Signal the loop, wait for it to finish, record monitor_stop."""
165
+ self._stop.set()
166
+ task = getattr(self, "_task", None)
167
+ if task:
168
+ await task
169
+ await asyncio.to_thread(self.db.add_event, time.time(), "monitor_stop", None)
170
+
171
+ async def _run(self) -> None:
172
+ """The scheduler loop. Each endpoint has a next-due timestamp; every
173
+ iteration polls at most one (most overdue first), then sleeps until
174
+ the earliest due time, capped at 1 s so stop() stays responsive."""
175
+ handlers = {
176
+ "vitals": self._handle_vitals,
177
+ "wifi": self._handle_wifi,
178
+ "lifetime": self._handle_lifetime,
179
+ "version": self._handle_version,
180
+ }
181
+ while not self._stop.is_set():
182
+ now = time.time()
183
+ # Strictly sequential: at most one endpoint polled per iteration.
184
+ # Most-overdue first, so a tight vitals cadence can't starve the
185
+ # slower endpoints.
186
+ due_now = [ep for ep, due_ts in self._due.items() if now >= due_ts]
187
+ if due_now:
188
+ endpoint = min(due_now, key=lambda ep: self._due[ep])
189
+ await self._poll(endpoint, handlers[endpoint])
190
+ next_due = min(self._due.values())
191
+ delay = max(0.05, min(next_due - time.time(), 1.0))
192
+ try:
193
+ await asyncio.wait_for(self._stop.wait(), timeout=delay)
194
+ except TimeoutError:
195
+ pass
196
+
197
+ # ---------- polling core ----------
198
+
199
+ def _base_interval(self, endpoint: str) -> float:
200
+ """Healthy poll interval for an endpoint; vitals is the only one
201
+ that adapts (tight while a vehicle is attached)."""
202
+ if endpoint == "vitals":
203
+ active = bool(self._prev_vitals and self._prev_vitals.get("vehicle_connected"))
204
+ return self.cfg.vitals_interval_active if active else self.cfg.vitals_interval_idle
205
+ if endpoint == "wifi":
206
+ return self.cfg.wifi_interval
207
+ if endpoint == "lifetime":
208
+ return self.cfg.lifetime_interval
209
+ return self.cfg.version_interval
210
+
211
+ async def _poll(self, endpoint: str, handler) -> None:
212
+ """One request → handler cycle. Success resets that endpoint's
213
+ backoff and clears any 'unreachable' alert (recovery, or first
214
+ success of a run whose predecessor died offline). A handler
215
+ exception is logged with the raw body but never kills the loop —
216
+ one malformed response must not stop recording."""
217
+ try:
218
+ raw = await self.wc.api.async_request(endpoint if endpoint != "wifi" else "wifi_status")
219
+ except (WallConnectorError, aiohttp.ClientError, OSError, asyncio.CancelledError) as ex:
220
+ if isinstance(ex, asyncio.CancelledError):
221
+ raise
222
+ await self._on_poll_error(endpoint, ex)
223
+ return
224
+ ts = time.time()
225
+ self.last_poll_ok_ts = ts
226
+ self._fail_streak[endpoint] = 0
227
+ self._due[endpoint] = ts + self._base_interval(endpoint)
228
+ if self._offline:
229
+ self._offline = False
230
+ self.last_poll_error = None
231
+ await asyncio.to_thread(self.db.clear_alert, ts, "Wall Connector unreachable", "monitor")
232
+ await asyncio.to_thread(self.db.add_event, ts, "poll_recovered", {"endpoint": endpoint})
233
+ self.bus.publish({"type": "event", "ts": ts, "kind": "poll_recovered", "detail": {"endpoint": endpoint}})
234
+ elif not self._had_success:
235
+ # First success of this run: clear any unreachable alert left
236
+ # active by a previous run that never recovered before exiting.
237
+ await asyncio.to_thread(self.db.clear_alert, ts, "Wall Connector unreachable", "monitor")
238
+ self._had_success = True
239
+ try:
240
+ await handler(ts, raw)
241
+ except Exception:
242
+ log.exception("handler for %s failed; raw=%s", endpoint, json.dumps(raw)[:500])
243
+
244
+ async def _on_poll_error(self, endpoint: str, ex: Exception) -> None:
245
+ """Back the failing endpoint off exponentially (factor^streak, capped)
246
+ and, on the third consecutive vitals failure, declare the device
247
+ offline: raise the alert, record the event, notify. Three failures
248
+ ≈ seconds of outage — early enough to matter, late enough that one
249
+ dropped packet doesn't page anyone."""
250
+ ts = time.time()
251
+ streak = self._fail_streak[endpoint] = self._fail_streak[endpoint] + 1
252
+ base = self._base_interval(endpoint)
253
+ backoff = min(base * (self.cfg.backoff_factor ** min(streak, 8)), self.cfg.backoff_max)
254
+ self._due[endpoint] = ts + backoff
255
+ self.last_poll_error = f"{type(ex).__name__}: {ex}"
256
+ 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:
259
+ self._offline = True
260
+ await asyncio.to_thread(self.db.raise_alert, ts, "Wall Connector unreachable", "monitor")
261
+ await asyncio.to_thread(self.db.add_event, ts, "poll_error", {"endpoint": endpoint, "error": str(ex)})
262
+ self.bus.publish(
263
+ {"type": "event", "ts": ts, "kind": "poll_error", "detail": {"endpoint": endpoint, "error": str(ex)}}
264
+ )
265
+ await self._notify(
266
+ "poll_error",
267
+ "Charger unreachable",
268
+ "Repeated polls failed — check the breaker, Wi-Fi, or the charger itself.",
269
+ {"endpoint": endpoint, "error": str(ex)},
270
+ )
271
+
272
+ # ---------- handlers ----------
273
+
274
+ async def _handle_vitals(self, ts: float, raw: dict) -> None:
275
+ """The heart of the monitor: store one vitals sample and derive
276
+ everything stateful by diffing against the previous one.
277
+
278
+ Events that originate here: charger_reboot (uptime went backwards),
279
+ session_start/session_end (vehicle_connected edges, with backdating
280
+ from the charger's session timer), charging_start/charging_stop
281
+ (contactor edges), evse_state_change, evse_not_ready_change, and
282
+ alert_raised/alert_cleared (current_alerts set-diff). Order at the
283
+ end matters: store the sample, run the derate forecast (which may
284
+ publish a thermal frame), then publish the vitals frame."""
285
+ prev = self._prev_vitals
286
+ power = _total_power(raw, self.cfg.split_phase)
287
+
288
+ # Charger reboot detection: uptime went backwards.
289
+ if prev is not None and isinstance(raw.get("uptime_s"), (int, float)) and isinstance(
290
+ prev.get("uptime_s"), (int, float)
291
+ ) and raw["uptime_s"] < prev["uptime_s"] - 5:
292
+ await self._event(ts, "charger_reboot", {"uptime_before": prev["uptime_s"], "uptime_after": raw["uptime_s"]})
293
+
294
+ connected = bool(raw.get("vehicle_connected"))
295
+ was_connected = bool(prev.get("vehicle_connected")) if prev is not None else None
296
+
297
+ # A session resumed across a monitor restart might actually be a
298
+ # different plug-in (car left and returned while we were down). The
299
+ # charger's session timer exposes that: if the implied start disagrees
300
+ # with the stored one by a lot, split into a new session.
301
+ if connected and self._session_id is not None and self._verify_resumed:
302
+ self._verify_resumed = False
303
+ session_s = raw.get("session_s")
304
+ if isinstance(session_s, (int, float)) and 0 <= session_s < 30 * 86400:
305
+ implied_start = ts - session_s
306
+ row = await asyncio.to_thread(self.db.session, self._session_id)
307
+ if row and implied_start - row["start_ts"] > 600:
308
+ stale = self._session_id
309
+ await asyncio.to_thread(self.db.close_session, stale, implied_start, "ended_during_monitor_gap")
310
+ await self._event(ts, "session_end", {"session_id": stale, "reason": "ended_during_monitor_gap"})
311
+ self._session_id = await asyncio.to_thread(self.db.start_session, implied_start)
312
+ await self._event(
313
+ ts, "session_start", {"session_id": self._session_id, "backdated_s": round(session_s, 1)}
314
+ )
315
+ elif self._verify_resumed:
316
+ self._verify_resumed = False
317
+
318
+ # Session lifecycle. The charger reports session_s (seconds since
319
+ # plug-in), so a session already in progress when monitoring starts
320
+ # gets its true start time instead of "when we first saw it".
321
+ if connected and self._session_id is None:
322
+ session_s = raw.get("session_s")
323
+ if isinstance(session_s, (int, float)) and 0 <= session_s < 30 * 86400:
324
+ start_ts = ts - session_s
325
+ else:
326
+ start_ts = ts
327
+ self._session_id = await asyncio.to_thread(self.db.start_session, start_ts)
328
+ detail = {"session_id": self._session_id}
329
+ if start_ts < ts - 60:
330
+ detail["backdated_s"] = round(ts - start_ts, 1)
331
+ await self._event(ts, "session_start", detail)
332
+ elif not connected and self._session_id is not None:
333
+ sid = self._session_id
334
+ self._session_id = None
335
+ reason = "vehicle_disconnected" if was_connected else "not_connected_on_startup"
336
+ await asyncio.to_thread(self.db.close_session, sid, ts, reason)
337
+ await self._event(ts, "session_end", {"session_id": sid, "reason": reason})
338
+ await self.recheck_thermal_drift(ts)
339
+
340
+ # Contactor transitions (actual charging on/off)
341
+ if prev is not None and bool(raw.get("contactor_closed")) != bool(prev.get("contactor_closed")):
342
+ kind = "charging_start" if raw.get("contactor_closed") else "charging_stop"
343
+ await self._event(ts, kind, {"session_id": self._session_id})
344
+
345
+ # EVSE state transitions
346
+ if prev is not None and raw.get("evse_state") != prev.get("evse_state"):
347
+ await self._event(
348
+ ts, "evse_state_change", {"from": prev.get("evse_state"), "to": raw.get("evse_state")}
349
+ )
350
+
351
+ # Not-ready reason changes (newer firmware; undocumented codes)
352
+ reasons_now = sorted(raw.get("evse_not_ready_reasons") or [])
353
+ reasons_prev = sorted(prev.get("evse_not_ready_reasons") or []) if prev is not None else None
354
+ if reasons_prev is not None and reasons_now != reasons_prev:
355
+ await self._event(ts, "evse_not_ready_change", {"from": reasons_prev, "to": reasons_now})
356
+
357
+ # Device alert diffing
358
+ alerts_now = {str(alert_id) for alert_id in raw.get("current_alerts") or []}
359
+ for alert in alerts_now - self._active_alerts:
360
+ await asyncio.to_thread(self.db.raise_alert, ts, alert, "device")
361
+ await self._event(ts, "alert_raised", {"alert": alert})
362
+ await self._notify(
363
+ "alert_raised",
364
+ "Wall Connector alert",
365
+ f"{self._alert_label(alert)} — see the Alerts page for details.",
366
+ {"alert": alert},
367
+ )
368
+ for alert in self._active_alerts - alerts_now:
369
+ await asyncio.to_thread(self.db.clear_alert, ts, alert, "device")
370
+ await self._event(ts, "alert_cleared", {"alert": alert})
371
+ self._active_alerts = alerts_now
372
+
373
+ row_id = await asyncio.to_thread(self.db.insert_vitals, ts, raw, self._session_id, power)
374
+ await self._check_derate_forecast(ts, raw)
375
+ self._prev_vitals = raw
376
+ self.bus.publish(
377
+ {
378
+ "type": "vitals",
379
+ "ts": ts,
380
+ "id": row_id,
381
+ "session_id": self._session_id,
382
+ "total_power_w": power,
383
+ "data": raw,
384
+ }
385
+ )
386
+
387
+ async def _handle_wifi(self, ts: float, raw: dict) -> None:
388
+ """Store a Wi-Fi sample; derive connect/disconnect and internet
389
+ lost/restored events (plus the Wi-Fi alert) from edges."""
390
+ prev = self._prev_wifi
391
+ if prev is not None:
392
+ if bool(raw.get("wifi_connected")) != bool(prev.get("wifi_connected")):
393
+ kind = "wifi_reconnected" if raw.get("wifi_connected") else "wifi_disconnected"
394
+ await self._event(ts, kind, {"ssid": raw.get("wifi_ssid")})
395
+ if kind == "wifi_disconnected":
396
+ await asyncio.to_thread(self.db.raise_alert, ts, "Charger Wi-Fi disconnected", "wifi")
397
+ else:
398
+ await asyncio.to_thread(self.db.clear_alert, ts, "Charger Wi-Fi disconnected", "wifi")
399
+ if bool(raw.get("internet")) != bool(prev.get("internet")):
400
+ await self._event(ts, "internet_restored" if raw.get("internet") else "internet_lost", None)
401
+ # The device reports the SSID base64-encoded on most firmware; store
402
+ # the decoded form in the column (the raw JSON keeps the original).
403
+ try:
404
+ ssid = WifiStatus(raw).wifi_ssid
405
+ except KeyError:
406
+ ssid = None
407
+ await asyncio.to_thread(self.db.insert_wifi, ts, raw, ssid)
408
+ self._prev_wifi = raw
409
+ self.bus.publish({"type": "wifi", "ts": ts, "data": {**raw, "wifi_ssid_decoded": ssid}})
410
+
411
+ async def _handle_lifetime(self, ts: float, raw: dict) -> None:
412
+ await asyncio.to_thread(self.db.insert_lifetime, ts, raw)
413
+ self.bus.publish({"type": "lifetime", "ts": ts, "data": raw})
414
+
415
+ 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."""
418
+ latest = await asyncio.to_thread(self.db.latest_version)
419
+ if latest is not None and latest.get("firmware_version") != raw.get("firmware_version"):
420
+ await self._event(
421
+ ts,
422
+ "firmware_changed",
423
+ {"from": latest.get("firmware_version"), "to": raw.get("firmware_version")},
424
+ )
425
+ if latest is None or json.loads(latest["raw"]) != raw:
426
+ await asyncio.to_thread(self.db.insert_version, ts, raw)
427
+
428
+ async def recheck_thermal_drift(self, ts: float) -> None:
429
+ """Refit history and raise/clear the degradation alert.
430
+
431
+ Drift changes in exactly two situations, and both call here: a
432
+ session completes (new fit lands), or the verified-baseline anchor
433
+ moves (the web handler re-evaluates immediately so a no-longer-
434
+ justified alert doesn't stay latched until the next unplug). Also
435
+ the one place the cached forecast params need refreshing."""
436
+ try:
437
+ fits = await asyncio.to_thread(thermal.fit_sessions, self.db, ts)
438
+ self._params = await asyncio.to_thread(thermal.fit_history, self.db, ts, fits=fits)
439
+ anchor = await asyncio.to_thread(thermal.baseline_anchor, self.db)
440
+ drift = thermal.detect_drift(fits, anchor_ts=anchor)
441
+ except Exception:
442
+ log.exception("thermal drift check failed")
443
+ return
444
+ if drift is None:
445
+ # No verdict — the comparable history got too thin (sessions aged
446
+ # out of the lookback, or off-current sessions were set aside). An
447
+ # active alert can no longer be justified either, so let it clear.
448
+ cleared = await asyncio.to_thread(self.db.clear_alert, ts, thermal.DRIFT_ALERT, "monitor")
449
+ if cleared:
450
+ await self._event(ts, "thermal_drift_cleared", {"reason": "insufficient_history"})
451
+ return
452
+ if drift["drifting"]:
453
+ _, newly = await asyncio.to_thread(self.db.raise_alert, ts, thermal.DRIFT_ALERT, "monitor")
454
+ if newly:
455
+ await self._event(ts, "thermal_drift", drift)
456
+ ci_lo, ci_hi = drift["delta_ci95_c"]
457
+ sureness = (
458
+ "statistically confirmed"
459
+ if drift["confident"]
460
+ else f"not yet confirmed at n={drift['baseline_n']}+{drift['recent_n']} — treat as a lead"
461
+ )
462
+ await self._notify(
463
+ "thermal_drift",
464
+ "Heat rise climbing vs baseline",
465
+ f"Recent sessions run +{drift['recent_rise_c']:.1f} °C vs a +{drift['baseline_rise_c']:.1f} °C "
466
+ f"baseline at the same current (Δ {drift['delta_c']:.1f} °C, 95% CI {ci_lo:.1f}..{ci_hi:.1f}, "
467
+ f"{sureness}) — inspect the handle and charge-port pins, and have the terminal torque checked.",
468
+ drift,
469
+ )
470
+ else:
471
+ cleared = await asyncio.to_thread(self.db.clear_alert, ts, thermal.DRIFT_ALERT, "monitor")
472
+ if cleared:
473
+ await self._event(ts, "thermal_drift_cleared", drift)
474
+
475
+ async def _check_derate_forecast(self, ts: float, raw: dict) -> None:
476
+ """While charging: warn while the user can still act — a capped
477
+ current sustains, a tripped one folds back to 50% for the session."""
478
+ charging = bool(raw.get("contactor_closed")) and (raw.get("vehicle_current_a") or 0) >= 6
479
+ if not charging:
480
+ await self._clear_derate(ts)
481
+ return
482
+ if ts < self._next_forecast_ts:
483
+ return
484
+ self._next_forecast_ts = ts + 30.0
485
+ try:
486
+ if self._params is None:
487
+ fits = await asyncio.to_thread(thermal.fit_sessions, self.db, ts)
488
+ self._params = await asyncio.to_thread(thermal.fit_history, self.db, ts, fits=fits)
489
+ out = await asyncio.to_thread(thermal.predict, self.db, ts, self._params)
490
+ except Exception:
491
+ log.exception("derate forecast check failed")
492
+ return
493
+ if out.get("state") != "charging":
494
+ return
495
+ # Every computed forecast is recorded and streamed, not just alert
496
+ # edges — these are the values the amp controller acts on, and the
497
+ # recorded history is what re-seeds the live chart across reloads.
498
+ self.bus.publish({"type": "thermal", **out})
499
+ await asyncio.to_thread(self.db.insert_forecast, ts, out, self._session_id)
500
+ forecast = out.get("forecast") or {}
501
+ will_trip = forecast.get("will_trip")
502
+ minutes = forecast.get("minutes_to_trip")
503
+ if will_trip is True and minutes is not None and minutes <= thermal.DERATE_WARN_MIN:
504
+ _, newly = await asyncio.to_thread(self.db.raise_alert, ts, thermal.DERATE_ALERT, "monitor")
505
+ if newly:
506
+ self._derate_active = True
507
+ detail = {
508
+ "minutes_to_trip": minutes,
509
+ "steady_state_c": forecast.get("steady_state_c"),
510
+ "suggested_max_a": forecast.get("suggested_max_a"),
511
+ "basis": forecast.get("basis"),
512
+ "current_a": raw.get("vehicle_current_a"),
513
+ }
514
+ await self._event(ts, "derate_warning", detail)
515
+ cap = forecast.get("suggested_max_a")
516
+ action = (
517
+ f"Set the vehicle's charge current to ≤{cap:.0f} A to keep a sustained rate."
518
+ if cap
519
+ else "Reduce the vehicle's charge current."
520
+ )
521
+ await self._notify(
522
+ "derate_warning",
523
+ "Thermal derate predicted",
524
+ f"~{max(round(minutes), 1)} min until the handle hits 65 °C and charging folds "
525
+ f"back to 50%. {action}",
526
+ detail,
527
+ )
528
+ elif will_trip is False:
529
+ # will_trip None (insufficient data) is unknown, not safe — leave
530
+ # an active warning standing until the forecast actually recovers.
531
+ await self._clear_derate(ts)
532
+
533
+ async def _clear_derate(self, ts: float) -> None:
534
+ """Clear the derate warning once (edge-triggered via _derate_active)."""
535
+ if not self._derate_active:
536
+ return
537
+ self._derate_active = False
538
+ cleared = await asyncio.to_thread(self.db.clear_alert, ts, thermal.DERATE_ALERT, "monitor")
539
+ if cleared:
540
+ await self._event(ts, "derate_warning_cleared", None)
541
+
542
+ def _alert_label(self, code: str) -> str:
543
+ if self._alert_labels is None:
544
+ try:
545
+ from importlib import resources
546
+
547
+ data = json.loads(
548
+ resources.files("wallmonitor").joinpath("alert_codes.json").read_text()
549
+ )
550
+ self._alert_labels = data.get("codes", {})
551
+ except Exception:
552
+ self._alert_labels = {}
553
+ entry = self._alert_labels.get(str(code))
554
+ return entry["label"] if entry else f"code {code} (undocumented)"
555
+
556
+ # ntfy rendering per warning kind: how loudly the phone should interrupt,
557
+ # and the tag emoji shown before the title.
558
+ NTFY_PRIORITY = {
559
+ "derate_warning": "urgent", # actionable *now* — lower the amps
560
+ "alert_raised": "high",
561
+ "thermal_drift": "high",
562
+ "poll_error": "default",
563
+ }
564
+ NTFY_TAGS = {
565
+ "derate_warning": "zap,warning",
566
+ "alert_raised": "rotating_light",
567
+ "thermal_drift": "wrench",
568
+ "poll_error": "electric_plug,x",
569
+ }
570
+
571
+ async def _notify(self, kind: str, title: str, body: str, detail: dict | None) -> None:
572
+ """POST an actionable warning to the configured LAN webhook.
573
+
574
+ Fire-and-forget: notification failures must never disturb polling,
575
+ and with no URL configured this is a no-op. Local-only by design —
576
+ the monitor itself never talks to anything beyond the charger and
577
+ this user-chosen LAN endpoint.
578
+
579
+ Format "json" posts one JSON object (for Home Assistant, Node-RED,
580
+ custom receivers); "ntfy" posts plain text with ntfy's publish
581
+ headers so notify_url can be a self-hosted ntfy topic directly.
582
+ """
583
+ url = self.cfg.notify_url
584
+ if not url:
585
+ return
586
+ try:
587
+ if self.cfg.notify_format == "ntfy":
588
+ headers = {
589
+ "X-Title": title,
590
+ "X-Priority": self.NTFY_PRIORITY.get(kind, "default"),
591
+ "X-Tags": self.NTFY_TAGS.get(kind, "warning"),
592
+ }
593
+ async with self._http.post(
594
+ url, data=body.encode(), headers=headers, timeout=aiohttp.ClientTimeout(total=5)
595
+ ) as resp:
596
+ await resp.read()
597
+ else:
598
+ payload = {"ts": time.time(), "kind": kind, "title": title, "body": body, "detail": detail}
599
+ async with self._http.post(
600
+ url, json=payload, timeout=aiohttp.ClientTimeout(total=5)
601
+ ) as resp:
602
+ await resp.read()
603
+ except Exception as ex:
604
+ log.debug("notify webhook failed: %s", ex)
605
+
606
+ async def _event(self, ts: float, kind: str, detail: dict | None) -> None:
607
+ """Record an event and publish it live — the one path every poller
608
+ event takes, so the DB and the SSE stream can never disagree."""
609
+ await asyncio.to_thread(self.db.add_event, ts, kind, detail)
610
+ self.bus.publish({"type": "event", "ts": ts, "kind": kind, "detail": detail})
611
+
612
+ # ---------- status ----------
613
+
614
+ def status(self) -> dict[str, Any]:
615
+ """Live poller state for /api/status (the header's online dot and
616
+ the footer's "watching …" line)."""
617
+ return {
618
+ "host": self.cfg.host,
619
+ "offline": self._offline,
620
+ "last_poll_ok_ts": self.last_poll_ok_ts,
621
+ "last_poll_error": self.last_poll_error,
622
+ "started_ts": self.started_ts,
623
+ "session_id": self._session_id,
624
+ "intervals": {
625
+ "vitals_active": self.cfg.vitals_interval_active,
626
+ "vitals_idle": self.cfg.vitals_interval_idle,
627
+ "wifi": self.cfg.wifi_interval,
628
+ "lifetime": self.cfg.lifetime_interval,
629
+ },
630
+ }