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/thermal.py ADDED
@@ -0,0 +1,911 @@
1
+ """Thermal-derate (alert 40) model fitting and prediction.
2
+
3
+ The Gen 3 Wall Connector raises alert 40 ("High temperature detected;
4
+ charging is limited") from its plug-handle sensor: observed on firmware
5
+ 26.18.0, the alert raises the moment handle_temp_c reaches 65 C, charge
6
+ current is cut to 50%, and the alert clears once the handle cools to ~60 C
7
+ (the derate persists for the rest of the session).
8
+
9
+ While charging at steady current the handle follows a first-order lag
10
+ toward a steady state that sits a roughly constant rise above ambient:
11
+
12
+ T(t) = T_inf - (T_inf - T0) * exp(-t / tau)
13
+ T_inf = ambient + rise_ref * (I / REF_CURRENT_A)^2 (resistive heating)
14
+
15
+ and at idle the handle settles a small offset above ambient, so the charger
16
+ doubles as its own ambient thermometer. The offset is not constant: measured
17
+ against a week of LAN ambient-sensor overlap it shrinks as the garage warms
18
+ (~2.3 C on cool nights, ~0.7 C on hot afternoons; see idle_offset_c), so the
19
+ proxy models it as linear in ambient, clamped to the calibrated range. tau
20
+ and rise_ref are fitted per install from recorded sessions; the defaults
21
+ come from a verified alert-40 event where the fit reproduced the observed
22
+ time-to-trip within 1%.
23
+
24
+ The unit of thermal analysis is the load window — the stretch where current
25
+ actually flows — not the plug-in session. Ambient is read at both ends of
26
+ the window (flat idle or cool-down tail before; the charge's own cool-down
27
+ tail after) and interpolated across it, so weather moving during a charge
28
+ is measured and removed instead of leaking into the fitted rise.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import math
34
+ from dataclasses import dataclass
35
+ from statistics import median
36
+
37
+ from .db import Database
38
+
39
+ TRIP_HANDLE_C = 65.0 # alert 40 raises here (observed, firmware 26.18.0)
40
+ CLEAR_HANDLE_C = 60.0 # ...and clears here, but the 50% derate persists
41
+ # Idle handle offset above garage air. Calibrated against the LAN ambient
42
+ # sensor (source "ecowitt", 2026-08-04..11): 42 settled-idle segments across
43
+ # 8 days — samples >= 1 h after any charging, ambient quasi-static, segment
44
+ # means used so autocorrelation can't fake precision. The old constant 2.0
45
+ # was rejected (mean 1.45, 95% CI [1.13, 1.78]); the offset falls as the
46
+ # garage warms — night ~2.3 C vs hot afternoon ~0.7 C, slope -0.124 C/C
47
+ # (t = -4.0 under leave-one-day-out jackknife) — so it is modeled linear in
48
+ # ambient and clamped to the ambient range the calibration actually covered.
49
+ # Recalibrate with contrib/calibrate_idle_offset.py as seasons extend the
50
+ # covered range.
51
+ #
52
+ # Changing these constants reinterprets history: fits are recomputed from
53
+ # raw vitals on every read, so adopting a new offset model shifts the
54
+ # rise_ref of every fit whose ambient came through the proxy
55
+ # (ambient_source "pre_idle" or "cooldown_tail") while leaving
56
+ # measured-sourced fits untouched. That shift is the correction working —
57
+ # but a drift comparison spanning a recalibration will show it as a step
58
+ # in proxy-era fits. Compare rise_ref within one ambient_source tier, or
59
+ # re-anchor the verified baseline after recalibrating, before reading any
60
+ # movement as hardware degradation.
61
+ IDLE_OFFSET_REF_C = 1.4 # offset at IDLE_OFFSET_AMBIENT_REF_C
62
+ IDLE_OFFSET_SLOPE = -0.124 # d(offset)/d(ambient)
63
+ IDLE_OFFSET_AMBIENT_REF_C = 30.0
64
+ IDLE_OFFSET_AMBIENT_RANGE_C = (23.0, 38.5) # calibration coverage; clamp outside
65
+
66
+
67
+ def idle_offset_c(ambient_c: float) -> float:
68
+ """How far above garage air the idle handle settles, at this ambient."""
69
+ lo, hi = IDLE_OFFSET_AMBIENT_RANGE_C
70
+ clamped = min(max(ambient_c, lo), hi)
71
+ return IDLE_OFFSET_REF_C + IDLE_OFFSET_SLOPE * (clamped - IDLE_OFFSET_AMBIENT_REF_C)
72
+
73
+
74
+ def idle_handle_c(ambient_c: float) -> float:
75
+ """Idle handle temperature expected at a given garage air temperature."""
76
+ return ambient_c + idle_offset_c(ambient_c)
77
+
78
+
79
+ def ambient_from_idle_handle(handle_c: float) -> float:
80
+ """Garage air implied by a settled idle handle: inverse of idle_handle_c.
81
+
82
+ Linear inside the calibrated ambient band; beyond it the offset holds at
83
+ the boundary value (continuous at both edges), so out-of-range readings
84
+ degrade to a constant-offset proxy instead of extrapolating the slope.
85
+ """
86
+ ta = (handle_c - IDLE_OFFSET_REF_C + IDLE_OFFSET_SLOPE * IDLE_OFFSET_AMBIENT_REF_C) / (
87
+ 1.0 + IDLE_OFFSET_SLOPE
88
+ )
89
+ lo, hi = IDLE_OFFSET_AMBIENT_RANGE_C
90
+ if ta < lo:
91
+ return handle_c - idle_offset_c(lo)
92
+ if ta > hi:
93
+ return handle_c - idle_offset_c(hi)
94
+ return ta
95
+ REF_CURRENT_A = 48.0 # rise_ref_c is normalized to this charge current
96
+
97
+ DEFAULT_TAU_MIN = 12.0
98
+ DEFAULT_RISE_REF_C = 36.0
99
+
100
+ # Fit acceptance gates: a segment must actually contain a thermal ramp and
101
+ # the exponential must describe it well, or it teaches the model nothing.
102
+ MIN_SEGMENT_S = 480.0
103
+ MIN_SEGMENT_SAMPLES = 12
104
+ MIN_RISE_SEEN_C = 4.0
105
+ MAX_FIT_RMSE_C = 0.6
106
+ TAU_RANGE_MIN = (3.0, 40.0)
107
+ RISE_RANGE_C = (10.0, 80.0)
108
+
109
+ # Live-forecast gate: a steady-current window must hold this many samples
110
+ # over this much time before its trajectory is projected.
111
+ TRAJECTORY_MIN_SAMPLES = 8
112
+ TRAJECTORY_MIN_SPAN_S = 120.0
113
+ # A session is one plug-in, but charging within it comes in distinct
114
+ # segments, often hours apart: the vehicle's own state-of-charge top-offs,
115
+ # scheduled-departure preconditioning, or a charging schedule. (The charger
116
+ # itself exposes no "scheduled charging" state — verified on firmware
117
+ # 26.18.0: with a vehicle-side schedule armed overnight it idles in plain
118
+ # connected states until the car starts drawing.) Charging gaps longer than
119
+ # this split segments; each segment's opening ramp is a fit candidate.
120
+ SEGMENT_SPLIT_GAP_S = 300.0
121
+ MAX_SEGMENTS_PER_SESSION = 4
122
+
123
+
124
+ @dataclass
125
+ class ThermalParams:
126
+ """The fitted model, portable: tau (minutes), rise at the 48 A reference
127
+ current, how many segment fits back each number, and the median
128
+ per-segment RMSE (the noise floor the amp controller's confidence guard
129
+ measures against). Defaults are from the telemetry-verified alert-40
130
+ event and apply until this install has fits of its own."""
131
+
132
+ tau_min: float = DEFAULT_TAU_MIN
133
+ rise_ref_c: float = DEFAULT_RISE_REF_C
134
+ tau_fits: int = 0
135
+ rise_fits: int = 0
136
+ fit_rmse_c: float | None = None
137
+
138
+ @property
139
+ def fitted(self) -> bool:
140
+ return self.tau_fits > 0 and self.rise_fits > 0
141
+
142
+ def as_dict(self) -> dict:
143
+ """The `model` object served by /api/thermal and the SSE thermal
144
+ frame — fitted values plus the fixed thresholds."""
145
+ return {
146
+ "tau_min": round(self.tau_min, 2),
147
+ "rise_ref_c": round(self.rise_ref_c, 1),
148
+ "ref_current_a": REF_CURRENT_A,
149
+ "trip_c": TRIP_HANDLE_C,
150
+ "clear_c": CLEAR_HANDLE_C,
151
+ "idle_offset_ref_c": IDLE_OFFSET_REF_C,
152
+ "idle_offset_slope": IDLE_OFFSET_SLOPE,
153
+ "tau_fits": self.tau_fits,
154
+ "rise_fits": self.rise_fits,
155
+ "fit_rmse_c": round(self.fit_rmse_c, 3) if self.fit_rmse_c is not None else None,
156
+ "fitted": self.fitted,
157
+ }
158
+
159
+
160
+ def _fit_exponential(points: list[tuple[float, float]]) -> tuple[float, float, float] | None:
161
+ """Least-squares fit of T(t) = T_inf - (T_inf - T0)*exp(-t/tau).
162
+
163
+ T0 is pinned to the first sample; tau is grid-searched and T_inf is the
164
+ closed-form optimum for each tau. Returns (tau_s, t_inf, rmse) or None.
165
+ """
166
+ start_ts, start_temp = points[0]
167
+ best: tuple[float, float, float] | None = None
168
+ tau = TAU_RANGE_MIN[0] * 60.0
169
+ while tau <= TAU_RANGE_MIN[1] * 60.0:
170
+ decays = [math.exp(-(ts - start_ts) / tau) for ts, _ in points]
171
+ num = den = 0.0
172
+ for (_, temp), decay in zip(points, decays):
173
+ num += (1.0 - decay) * (temp - start_temp * decay)
174
+ den += (1.0 - decay) ** 2
175
+ if den > 1e-9:
176
+ t_inf = num / den
177
+ sse = sum(
178
+ (t_inf - (t_inf - start_temp) * decay - temp) ** 2
179
+ for (_, temp), decay in zip(points, decays)
180
+ )
181
+ rmse = math.sqrt(sse / len(points))
182
+ if best is None or rmse < best[2]:
183
+ best = (tau, t_inf, rmse)
184
+ tau += 15.0
185
+ return best
186
+
187
+
188
+ def _steady_current_prefix(samples: list[dict]) -> list[dict]:
189
+ """The session's first steady-current run.
190
+
191
+ The reference current is the median of the first 10 minutes of charging,
192
+ not of the whole session: a session that derates midway spends most of
193
+ its samples at the reduced current, and a whole-session median would put
194
+ the initial full-rate ramp — the part with the thermal signal — outside
195
+ the band. Leading samples still ramping up to the plateau are skipped
196
+ rather than treated as the end of the run.
197
+ """
198
+ charging = [
199
+ sample
200
+ for sample in samples
201
+ if sample.get("contactor_closed") and (sample.get("vehicle_current_a") or 0) >= 16
202
+ ]
203
+ if not charging:
204
+ return []
205
+ charge_start_ts = charging[0]["ts"]
206
+ i_ref = median(
207
+ sample["vehicle_current_a"]
208
+ for sample in charging
209
+ if sample["ts"] - charge_start_ts <= 600
210
+ )
211
+ band = max(2.0, 0.1 * i_ref)
212
+ prefix: list[dict] = []
213
+ for sample in charging:
214
+ if prefix and sample["ts"] - prefix[-1]["ts"] > SEGMENT_SPLIT_GAP_S:
215
+ break # a charging gap: the next samples belong to a later segment
216
+ if abs(sample["vehicle_current_a"] - i_ref) > band:
217
+ if prefix:
218
+ break # the steady run ended (derate or charge stop)
219
+ continue # still ramping up to the plateau
220
+ prefix.append(sample)
221
+ if sample["ts"] - prefix[0]["ts"] > 1800: # first 30 min is where the ramp lives
222
+ break
223
+ return prefix
224
+
225
+
226
+ def _segments(rows: list[dict]) -> list[tuple[float, float]]:
227
+ """(start, end) timestamps of distinct charging segments in a session.
228
+
229
+ Works on bucket-averaged rows as well as raw ones: a bucket that saw any
230
+ charging keeps contactor_closed via MAX(), and its MIN(ts) lands at or
231
+ before the actual charge start, so the per-segment raw fetch that follows
232
+ never misses the ramp's beginning. The end is the last charging row of
233
+ the run — on bucketed rows up to one bucket early, which only trims the
234
+ top of the cool-down tail read from it.
235
+ """
236
+ segments: list[tuple[float, float]] = []
237
+ start: float | None = None
238
+ prev: float | None = None
239
+ for row in rows:
240
+ if not row.get("contactor_closed"):
241
+ continue
242
+ if prev is None or row["ts"] - prev > SEGMENT_SPLIT_GAP_S:
243
+ if start is not None:
244
+ segments.append((start, prev))
245
+ start = row["ts"]
246
+ prev = row["ts"]
247
+ if start is not None and prev is not None:
248
+ segments.append((start, prev))
249
+ return segments
250
+
251
+
252
+ # Measured ambient (an optional LAN sensor POSTing to /api/ambient) beats
253
+ # every handle-derived estimate: the handle proxy carries the idle-offset
254
+ # assumption and goes blind when the handle is warm, while a sensor reads
255
+ # the garage air directly at any moment. All reads fall back to the proxy
256
+ # when no samples cover the window, so the sensor can appear, disappear, or
257
+ # never exist without configuration.
258
+ #
259
+ # Samples tagged source "car" come from a vehicle parked in the garage — a
260
+ # real thermometer, but one that drives away and reads high for a while
261
+ # after a drive (heat-soaked housing). A stationary sensor therefore
262
+ # outranks it whenever both report; car samples fill in only when they are
263
+ # all there is. The readers return (temp_c, tag) so callers can say which
264
+ # kind of measurement they used ("measured" vs "measured_car").
265
+ MEASURED_AMBIENT_WINDOW_S = 900.0
266
+ MEASURED_AMBIENT_FRESH_S = 600.0
267
+ CAR_AMBIENT_SOURCE = "car"
268
+
269
+
270
+ def _split_by_mobility(rows: list[dict]) -> tuple[list[dict], str]:
271
+ """Apply the stationary-beats-car tier (block comment above): drop car
272
+ rows whenever any fixed-sensor row exists in the set."""
273
+ fixed = [row for row in rows if row.get("source") != CAR_AMBIENT_SOURCE]
274
+ return (fixed, "measured") if fixed else (rows, "measured_car")
275
+
276
+
277
+ def _measured_ambient(db: Database, t_from: float, t_to: float) -> tuple[float, str] | None:
278
+ """Median measured ambient over a window (median, so one glitchy sample
279
+ or a warm car pulling in can't drag it far), or None if uncovered."""
280
+ rows = db.ambient_range(t_from, t_to, 500)
281
+ if not rows:
282
+ return None
283
+ rows, tag = _split_by_mobility(rows)
284
+ return median(row["temp_c"] for row in rows), tag
285
+
286
+
287
+ def _latest_measured_ambient(db: Database, now: float) -> tuple[float, str] | None:
288
+ """Newest measured sample no older than MEASURED_AMBIENT_FRESH_S, or
289
+ None — the live-forecast reader, where staleness matters more than
290
+ smoothing."""
291
+ rows = db.ambient_range(now - MEASURED_AMBIENT_FRESH_S, now + 1.0, 500)
292
+ if not rows:
293
+ return None
294
+ rows, tag = _split_by_mobility(rows)
295
+ return rows[-1]["temp_c"], tag
296
+
297
+
298
+ def _ambient_before(db: Database, start_ts: float) -> float | None:
299
+ """Ambient estimate from the idle handle temperature before a session."""
300
+ rows = db.vitals_range(start_ts - 2400, start_ts - 30, 5000)
301
+ idle = [
302
+ row["handle_temp_c"]
303
+ for row in rows
304
+ if not row.get("contactor_closed")
305
+ and (row.get("vehicle_current_a") or 0) < 1
306
+ and row.get("handle_temp_c") is not None
307
+ ]
308
+ if len(idle) < 5 or max(idle) - min(idle) > 2.0:
309
+ return None
310
+ return ambient_from_idle_handle(median(idle))
311
+
312
+
313
+ # Cool-down-tail ambient: gates for reading ambient from a still-warm
314
+ # handle's decay when no flat idle window exists before a segment.
315
+ COOLDOWN_MIN_SAMPLES = 10
316
+ COOLDOWN_MIN_SPAN_S = 300.0
317
+ COOLDOWN_MIN_DROP_C = 1.0
318
+ COOLDOWN_MAX_RMSE_C = 0.5
319
+
320
+
321
+ def _decay_asymptote(tail: list[dict], tau_min: float) -> float | None:
322
+ """Ambient from a cooling handle's decay: least-squares asymptote of a
323
+ first-order lag at a known tau, minus the idle offset. Gated on span,
324
+ visible drop, and fit quality; None when the tail can't be trusted."""
325
+ if len(tail) < COOLDOWN_MIN_SAMPLES or tail[-1]["ts"] - tail[0]["ts"] < COOLDOWN_MIN_SPAN_S:
326
+ return None
327
+ start_temp = tail[0]["handle_temp_c"]
328
+ if start_temp - tail[-1]["handle_temp_c"] < COOLDOWN_MIN_DROP_C:
329
+ return None # not visibly cooling; nothing to extrapolate
330
+ tau_s = tau_min * 60.0
331
+ decays = [math.exp(-(row["ts"] - tail[0]["ts"]) / tau_s) for row in tail]
332
+ num = den = 0.0
333
+ for row, decay in zip(tail, decays):
334
+ num += (1.0 - decay) * (row["handle_temp_c"] - start_temp * decay)
335
+ den += (1.0 - decay) ** 2
336
+ if den < 1e-9:
337
+ return None
338
+ asymptote = num / den
339
+ rmse = math.sqrt(
340
+ sum(
341
+ (asymptote - (asymptote - start_temp) * decay - row["handle_temp_c"]) ** 2
342
+ for row, decay in zip(tail, decays)
343
+ )
344
+ / len(tail)
345
+ )
346
+ if rmse > COOLDOWN_MAX_RMSE_C:
347
+ return None # not a clean single-exponential decay at this tau
348
+ ambient = ambient_from_idle_handle(asymptote)
349
+ if not (-30.0 <= ambient <= TRIP_HANDLE_C):
350
+ return None
351
+ return ambient
352
+
353
+
354
+ def _idle_rows(rows: list[dict]) -> list[dict]:
355
+ """Rows where the handle should sit at idle_handle_c(ambient):
356
+ contactor open, no meaningful current, sensor sane (255 sentinel
357
+ excluded by the < 200 guard)."""
358
+ return [
359
+ row
360
+ for row in rows
361
+ if not row.get("contactor_closed")
362
+ and (row.get("vehicle_current_a") or 0) < 1
363
+ and row.get("handle_temp_c") is not None
364
+ and row["handle_temp_c"] < 200
365
+ ]
366
+
367
+
368
+ def _ambient_from_cooldown(db: Database, start_ts: float, tau_min: float) -> float | None:
369
+ """Ambient from the cool-down tail before a segment that starts warm.
370
+
371
+ A stop/resume or post-derate segment begins before the handle has
372
+ cooled, so _ambient_before finds no stable idle window and the segment
373
+ loses its rise fit. But the decay itself encodes ambient: idle cooling
374
+ follows the same first-order lag as the charge ramp, settling at
375
+ the idle handle temperature. With tau known from this install's fitted
376
+ ramps, the asymptote is a closed-form least squares over a few minutes
377
+ of tail — no flat stretch needed. (The live forecast bridges the same
378
+ gap by inferring ambient *from* the fitted rise; that would be circular
379
+ here, where the rise is the thing being measured.)
380
+ """
381
+ idle = _idle_rows(db.vitals_range(start_ts - 2400, start_ts - 5, 5000))
382
+ if not idle:
383
+ return None
384
+ # The contiguous idle run ending at the segment start (tolerating normal
385
+ # polling gaps) — the tail of the previous charge's cool-down.
386
+ tail = [idle[-1]]
387
+ for row in reversed(idle[:-1]):
388
+ if tail[-1]["ts"] - row["ts"] > 120.0:
389
+ break
390
+ tail.append(row)
391
+ tail.reverse()
392
+ return _decay_asymptote(tail, tau_min)
393
+
394
+
395
+ def _ambient_after(db: Database, end_ts: float, tau_min: float) -> float | None:
396
+ """Ambient at the end of a load window, from the cool-down that follows.
397
+
398
+ The moment current stops, the handle decays from its working temperature
399
+ toward idle_handle_c(ambient) along the same first-order lag as the
400
+ charge ramp, so the tail right after the window closes encodes the
401
+ ambient *then* — the other bracket of the window. A point ambient read
402
+ only at the window's start silently assumes the garage held still for
403
+ the whole charge; on a summer afternoon (or a cooling night) it didn't,
404
+ and the fitted rise absorbed the weather.
405
+ """
406
+ idle = _idle_rows(db.vitals_range(end_ts + 5, end_ts + 2400, 5000))
407
+ if not idle:
408
+ return None
409
+ # The contiguous idle run starting at the window's close (tolerating
410
+ # normal polling gaps) — this charge's own cool-down.
411
+ tail = [idle[0]]
412
+ for row in idle[1:]:
413
+ if row["ts"] - tail[-1]["ts"] > 120.0:
414
+ break
415
+ tail.append(row)
416
+ return _decay_asymptote(tail, tau_min)
417
+
418
+
419
+ def fit_sessions(db: Database, now: float, lookback_days: float = 120.0) -> list[dict]:
420
+ """Per-load-window fits, oldest first: one dict per charging segment
421
+ whose ramp passed the quality gates. A session that idles for hours and
422
+ then charges (a vehicle top-off, preconditioning, a charging schedule)
423
+ yields its fits from wherever the ramps actually are, not just the
424
+ plug-in moment.
425
+
426
+ Ambient is a bracket, not a point. The window's start ambient comes from
427
+ the flat idle stretch before the segment, or — when the segment starts
428
+ with a still-warm handle (stop/resume, post-derate) — from the previous
429
+ charge's cool-down tail extrapolated to its asymptote. The window's end
430
+ ambient comes from this charge's own cool-down tail after current stops.
431
+ When both ends read, the samples are de-trended against the linear
432
+ ambient ramp between them and refitted, so a garage that warmed (or
433
+ cooled) during the charge stops masquerading as connector resistance.
434
+ When only the start reads, the fit falls back to the old point-ambient
435
+ behavior and says so (ambient_end_c/ambient_drift_c are None).
436
+
437
+ rise_ref_c is None only when no ambient read succeeds; each fit carries
438
+ ambient_source ("measured" for a stationary LAN sensor, "measured_car"
439
+ for a parked vehicle's sensor, else "pre_idle" or "cooldown_tail"),
440
+ ambient_c, and — when bracketed — ambient_end_c and ambient_drift_c
441
+ (end minus start)."""
442
+ sessions = [
443
+ session
444
+ for session in db.sessions_range(now - lookback_days * 86400, now)
445
+ if session.get("end_ts") and (session.get("charging_s") or 0) >= MIN_SEGMENT_S
446
+ ][:40]
447
+ fits: list[dict] = []
448
+ for sess in sessions:
449
+ # Coarse pass over the whole session to locate charging segments —
450
+ # bucket-averaged is fine here (and keeps a multi-day session cheap);
451
+ # each segment then gets a narrow raw-resolution fetch, since only
452
+ # the ramp's first ~45 min carries the thermal signal.
453
+ coarse = db.vitals_range(sess["start_ts"] - 1, sess["end_ts"] + 1, 2000)
454
+ segments = _segments(coarse)[:MAX_SEGMENTS_PER_SESSION]
455
+ for idx, (seg_start, seg_end) in enumerate(segments):
456
+ next_start = segments[idx + 1][0] if idx + 1 < len(segments) else sess["end_ts"] + 1
457
+ t_hi = min(sess["end_ts"], seg_start + 2700, next_start - 1)
458
+ samples = db.vitals_range(seg_start - 1, t_hi + 1, 5000)
459
+ prefix = _steady_current_prefix(samples)
460
+ seg = [
461
+ (sample["ts"], sample["handle_temp_c"])
462
+ for sample in prefix
463
+ if sample.get("handle_temp_c") is not None
464
+ ]
465
+ if len(seg) < MIN_SEGMENT_SAMPLES or seg[-1][0] - seg[0][0] < MIN_SEGMENT_S:
466
+ continue
467
+ if max(temp for _, temp in seg) - seg[0][1] < MIN_RISE_SEEN_C:
468
+ continue
469
+ fit = _fit_exponential(seg)
470
+ if fit is None:
471
+ continue
472
+ tau_s, t_inf, rmse = fit
473
+ if rmse > MAX_FIT_RMSE_C or t_inf <= seg[0][1] + 3.0:
474
+ continue
475
+ i_med = median(sample["vehicle_current_a"] for sample in prefix)
476
+ tau_est = median([tau_s / 60.0] + [fit["tau_min"] for fit in fits])
477
+ measured = _measured_ambient(db, seg_start - MEASURED_AMBIENT_WINDOW_S, seg_start + 60)
478
+ ambient, ambient_source = measured if measured is not None else (None, None)
479
+ if ambient is None:
480
+ ambient = _ambient_before(db, seg_start)
481
+ ambient_source = "pre_idle" if ambient is not None else None
482
+ if ambient is None:
483
+ # Hot-handle start (stop/resume, post-derate): read ambient
484
+ # from the previous charge's cool-down tail instead, using
485
+ # this install's fitted tau (this segment's own plus any
486
+ # earlier fits this pass).
487
+ ambient = _ambient_from_cooldown(db, seg_start, tau_est)
488
+ if ambient is not None:
489
+ ambient_source = "cooldown_tail"
490
+ ambient_end = None
491
+ if ambient is not None and seg_end - seg_start > 0:
492
+ measured_end = _measured_ambient(db, seg_end - 60, seg_end + MEASURED_AMBIENT_WINDOW_S)
493
+ ambient_end = measured_end[0] if measured_end is not None else None
494
+ if ambient_end is None:
495
+ ambient_end = _ambient_after(db, seg_end, tau_est)
496
+ if ambient_end is not None:
497
+ # Bracketed: de-trend the samples against the linear ambient
498
+ # ramp across the load window and refit. With ambient
499
+ # a(t) = a0 + r*t the lag ODE solves to the constant-ambient
500
+ # exponential plus the ramp, its asymptote shifted by -r*tau
501
+ # — so the corrected rise adds r*tau back after the refit.
502
+ rate = (ambient_end - ambient) / (seg_end - seg_start)
503
+ detrended = [
504
+ (ts, temp - rate * (ts - seg[0][0])) for ts, temp in seg
505
+ ]
506
+ refit = _fit_exponential(detrended)
507
+ if refit is not None and refit[2] <= MAX_FIT_RMSE_C:
508
+ tau_s, t_inf, rmse = refit
509
+ t_inf += rate * tau_s
510
+ # Ambient at the fit's own t0, not the coarse window start
511
+ # (the steady prefix can begin a ramp-up later).
512
+ ambient += rate * (seg[0][0] - seg_start)
513
+ else:
514
+ ambient_end = None # refit failed gates; fall back
515
+ rise = None
516
+ if ambient is not None:
517
+ rise = (t_inf - ambient) * (REF_CURRENT_A / i_med) ** 2
518
+ if not (RISE_RANGE_C[0] <= rise <= RISE_RANGE_C[1]):
519
+ rise = None
520
+ fits.append(
521
+ {
522
+ "session_id": sess["id"],
523
+ "start_ts": seg[0][0],
524
+ "tau_min": round(tau_s / 60.0, 2),
525
+ "rise_ref_c": round(rise, 2) if rise is not None else None,
526
+ "rmse_c": round(rmse, 3),
527
+ "current_a": round(i_med, 1),
528
+ "ambient_source": ambient_source if rise is not None else None,
529
+ "ambient_c": round(ambient, 2) if rise is not None else None,
530
+ "ambient_end_c": (
531
+ round(ambient_end, 2)
532
+ if rise is not None and ambient_end is not None
533
+ else None
534
+ ),
535
+ "ambient_drift_c": (
536
+ round(ambient_end - ambient, 2)
537
+ if rise is not None and ambient_end is not None
538
+ else None
539
+ ),
540
+ }
541
+ )
542
+ fits.sort(key=lambda fit: fit["start_ts"])
543
+ return fits
544
+
545
+
546
+ def fit_history(db: Database, now: float, lookback_days: float = 120.0,
547
+ fits: list[dict] | None = None) -> ThermalParams:
548
+ """Aggregate per-session fits into model parameters; defaults where thin."""
549
+ if fits is None:
550
+ fits = fit_sessions(db, now, lookback_days)
551
+ taus = [fit["tau_min"] for fit in fits]
552
+ rises = [fit["rise_ref_c"] for fit in fits if fit["rise_ref_c"] is not None]
553
+ rmses = [fit["rmse_c"] for fit in fits]
554
+ return ThermalParams(
555
+ tau_min=median(taus) if taus else DEFAULT_TAU_MIN,
556
+ rise_ref_c=median(rises) if rises else DEFAULT_RISE_REF_C,
557
+ tau_fits=len(taus),
558
+ rise_fits=len(rises),
559
+ fit_rmse_c=median(rmses) if rmses else None,
560
+ )
561
+
562
+
563
+ # ---------------- degradation watch ----------------
564
+
565
+ # A loose lug or degrading contact shows up as extra resistance: more heat
566
+ # rise for the same current. Prediction alone hides that (the rolling median
567
+ # just follows it), so the drift watch compares recent sessions against the
568
+ # earlier baseline and flags a sustained increase.
569
+ DRIFT_RECENT_N = 3
570
+ DRIFT_MIN_BASELINE_N = 3
571
+ DRIFT_WARN_C = 2.5
572
+ DRIFT_ALERT = "Handle heat rise increasing (check connector/wiring)"
573
+
574
+ # Cross-current pooling: fits whose ambient was bracketed at both ends are
575
+ # trustworthy enough under the I^2 normalization to join the comparison from
576
+ # a wider current band; start-only fits must still match the typical current.
577
+ DRIFT_POOL_BAND_FRAC = 0.25
578
+
579
+ # The settings key holding the baseline anchor: a timestamp before which
580
+ # fits are excluded from the drift comparison. Set it when the hardware has
581
+ # been inspected and verified (or fixed) — from then on "baseline" means
582
+ # "verified healthy", not "the first charges the monitor happened to see".
583
+ BASELINE_ANCHOR_KEY = "thermal_baseline_anchor_ts"
584
+
585
+ # Two-sided 95% Student-t multipliers by degrees of freedom, for the delta's
586
+ # confidence interval. Small-sample medians are noisy; a plain 1.96 would
587
+ # overstate the confidence exactly when the history is thinnest.
588
+ _T95 = {1: 12.71, 2: 4.30, 3: 3.18, 4: 2.78, 5: 2.57, 6: 2.45, 7: 2.36, 8: 2.31, 9: 2.26, 10: 2.23}
589
+
590
+
591
+ def _median_stats(values: list[float]) -> tuple[float, float, float]:
592
+ """(median, MAD, standard error of the median).
593
+
594
+ Spread comes from the median absolute deviation — robust to the odd wild
595
+ fit — scaled to a normal-equivalent sigma (1.4826) and to the median's
596
+ sampling efficiency (1.2533 / sqrt(n))."""
597
+ med = median(values)
598
+ mad = median(abs(value - med) for value in values)
599
+ return med, mad, 1.2533 * (1.4826 * mad) / math.sqrt(len(values))
600
+
601
+ # Actionable warning: the live forecast puts the 65 C trip inside this
602
+ # horizon, so the user still has time to lower the vehicle's charge current
603
+ # and keep a sustained rate instead of eating the 50% foldback.
604
+ DERATE_WARN_MIN = 15.0
605
+ DERATE_ALERT = "Derate predicted (lower vehicle charge current to avoid it)"
606
+
607
+
608
+ def detect_drift(fits: list[dict], anchor_ts: float | None = None) -> dict | None:
609
+ """Compare the last few sessions' fitted rise against the baseline.
610
+
611
+ Returns None while there is too little history to judge; otherwise a
612
+ verdict dict with the medians compared. Only rise (not tau) is watched:
613
+ added contact resistance changes how much heat is made, not how fast the
614
+ handle mass warms.
615
+
616
+ Only sessions charging near the install's typical current are compared.
617
+ rise_ref_c is normalized by (REF/I)^2, and far from the measured current
618
+ that normalization amplifies ordinary fit error — a session at 40 A with
619
+ an unremarkable raw rise extrapolates to an alarming number at 48 A, and
620
+ with only DRIFT_RECENT_N recent sessions a single such point can swing
621
+ the median past the threshold and manufacture a drift verdict. Fits with
622
+ bracketed ambient are cleaner, so they join from a wider current band —
623
+ that is what lets a baseline recorded at 48 A keep judging charges after
624
+ the vehicle is capped to 40 A, instead of the verdict going dark.
625
+
626
+ "Typical" is the median current of the newest fits, not of all history:
627
+ when the user caps the vehicle at a new current, the watch follows the
628
+ new operating point.
629
+
630
+ anchor_ts, when set, excludes fits from before it: the user has had the
631
+ hardware inspected and verified, so "baseline" means "verified healthy"
632
+ from that moment, not "the first charges the monitor happened to see".
633
+
634
+ The verdict carries its own uncertainty: MAD spread per side and a
635
+ Student-t ~95% confidence interval on the delta. "drifting" stays a
636
+ plain threshold tripwire; "confident" says whether the interval clears
637
+ zero — a Δ from a four-fit baseline is a lead, not a conviction, and the
638
+ UI should show the difference.
639
+ """
640
+ usable = [fit for fit in fits if fit["rise_ref_c"] is not None]
641
+ if anchor_ts is not None:
642
+ usable = [fit for fit in usable if fit["start_ts"] >= anchor_ts]
643
+ if len(usable) < DRIFT_RECENT_N + DRIFT_MIN_BASELINE_N:
644
+ return None
645
+ usable.sort(key=lambda fit: fit["start_ts"])
646
+ typical_a = median(fit["current_a"] for fit in usable[-DRIFT_RECENT_N:])
647
+ band = max(2.0, 0.1 * typical_a)
648
+ pool_band = DRIFT_POOL_BAND_FRAC * typical_a
649
+ comparable = [
650
+ fit
651
+ for fit in usable
652
+ if abs(fit["current_a"] - typical_a) <= band
653
+ or (
654
+ fit.get("ambient_drift_c") is not None
655
+ and abs(fit["current_a"] - typical_a) <= pool_band
656
+ )
657
+ ]
658
+ rises = [(fit["start_ts"], fit["rise_ref_c"]) for fit in comparable]
659
+ rises.sort(key=lambda entry: entry[0])
660
+ if len(rises) < DRIFT_RECENT_N + DRIFT_MIN_BASELINE_N:
661
+ return None
662
+ recent = [rise for _, rise in rises[-DRIFT_RECENT_N:]]
663
+ baseline = [rise for _, rise in rises[:-DRIFT_RECENT_N]]
664
+ recent_med, recent_mad, recent_se = _median_stats(recent)
665
+ baseline_med, baseline_mad, baseline_se = _median_stats(baseline)
666
+ delta = recent_med - baseline_med
667
+ delta_se = math.sqrt(recent_se**2 + baseline_se**2)
668
+ t_mult = _T95.get(len(recent) + len(baseline) - 2, 2.0)
669
+ ci_lo, ci_hi = delta - t_mult * delta_se, delta + t_mult * delta_se
670
+ cross_current = sum(1 for fit in comparable if abs(fit["current_a"] - typical_a) > band)
671
+ return {
672
+ "drifting": delta >= DRIFT_WARN_C,
673
+ "confident": ci_lo > 0.0,
674
+ "recent_rise_c": round(recent_med, 2),
675
+ "baseline_rise_c": round(baseline_med, 2),
676
+ "delta_c": round(delta, 2),
677
+ "delta_ci95_c": [round(ci_lo, 2), round(ci_hi, 2)],
678
+ "recent_mad_c": round(recent_mad, 2),
679
+ "baseline_mad_c": round(baseline_mad, 2),
680
+ "recent_n": len(recent),
681
+ "baseline_n": len(baseline),
682
+ "typical_current_a": round(typical_a, 1),
683
+ "off_current_n": len(usable) - len(comparable),
684
+ "cross_current_n": cross_current,
685
+ "anchor_ts": anchor_ts,
686
+ "threshold_c": DRIFT_WARN_C,
687
+ }
688
+
689
+
690
+ def baseline_anchor(db: Database) -> float | None:
691
+ """The verified-baseline anchor timestamp, or None when unset."""
692
+ raw = db.get_setting(BASELINE_ANCHOR_KEY)
693
+ try:
694
+ return float(raw) if raw is not None else None
695
+ except ValueError:
696
+ return None
697
+
698
+
699
+ def _minutes_to_trip(t_now: float, t_inf: float, tau_min: float) -> float | None:
700
+ """Minutes until the handle reaches the trip point, or None if it never will.
701
+
702
+ The steady-state check comes first: a handle currently at/above the trip
703
+ point but settling below it (cooling after a current cut or a derate) is
704
+ recovering, not tripping.
705
+ """
706
+ if t_inf <= TRIP_HANDLE_C + 0.2:
707
+ return None
708
+ if t_now >= TRIP_HANDLE_C:
709
+ return 0.0
710
+ return tau_min * math.log((t_inf - t_now) / (t_inf - TRIP_HANDLE_C))
711
+
712
+
713
+ SUGGEST_MARGIN_C = 2.0 # keep the suggested current's steady state this far under the trip
714
+
715
+
716
+ def suggest_max_current(ambient_c: float, params: ThermalParams) -> float | None:
717
+ """Highest charge current whose steady-state handle temp stays safely
718
+ below the trip point at the given ambient — the alternative to letting
719
+ the charger fold back to a blunt 50%. Vehicles take whole amps, so the
720
+ value is floored. None when even a minimal rate would trip (or when no
721
+ cap is needed at all, i.e. full rate is already safe)."""
722
+ headroom = TRIP_HANDLE_C - SUGGEST_MARGIN_C - ambient_c
723
+ if headroom <= 0:
724
+ return None
725
+ amps = math.floor(REF_CURRENT_A * math.sqrt(headroom / params.rise_ref_c))
726
+ if amps < 6: # J1772 floor — below this the vehicle won't charge anyway
727
+ return None
728
+ if amps >= REF_CURRENT_A:
729
+ return None # full rate is safe; no cap to suggest
730
+ return float(amps)
731
+
732
+
733
+ def _project_t_inf(window: list[tuple[float, float]], tau_min: float) -> float:
734
+ """Steady state projected from a steady-current window's trajectory.
735
+
736
+ With tau known, T(t) = T_inf - C*exp(-t/tau) is linear in (T_inf, C), so
737
+ an ordinary least-squares line on x = exp(-t/tau) gives an unbiased T_inf
738
+ (a straight-line slope would read the window's average rate and overshoot
739
+ during a fast ramp). No ambient input needed. A flat window (variance ~0,
740
+ i.e. already converged) reads as the latest temperature.
741
+ """
742
+ count = len(window)
743
+ decays = [math.exp(-(ts - window[0][0]) / (tau_min * 60.0)) for ts, _ in window]
744
+ mean_decay = sum(decays) / count
745
+ mean_temp = sum(temp for _, temp in window) / count
746
+ var = sum((decay - mean_decay) ** 2 for decay in decays)
747
+ cov = sum(
748
+ (decay - mean_decay) * (temp - mean_temp)
749
+ for decay, (_, temp) in zip(decays, window)
750
+ )
751
+ return mean_temp - (cov / var) * mean_decay if var > 1e-9 else window[-1][1]
752
+
753
+
754
+ def _recent_steady_ambient(recent: list[dict], params: ThermalParams) -> float | None:
755
+ """Ambient inferred from the newest steady-current run in the buffer.
756
+
757
+ Back-to-back sessions leave no idle gap to read ambient from, and a
758
+ mid-session current change resets the live trajectory window — but the
759
+ buffer usually still holds an earlier steady run (this session's stretch
760
+ before the change, or the previous session's tail). Its projected steady
761
+ state at that run's current implies the ambient, which the I^2 model then
762
+ rescales to the present current.
763
+ """
764
+ runs: list[list[dict]] = [[]]
765
+ for sample in recent:
766
+ current = sample.get("vehicle_current_a") or 0.0
767
+ run = runs[-1]
768
+ if not sample.get("contactor_closed") or current < 6.0:
769
+ if run:
770
+ runs.append([])
771
+ continue
772
+ ref = run[0]["vehicle_current_a"] if run else current
773
+ if abs(current - ref) > max(2.0, 0.1 * ref):
774
+ runs.append([sample])
775
+ continue
776
+ run.append(sample)
777
+ for run in reversed(runs):
778
+ if len(run) < TRAJECTORY_MIN_SAMPLES or run[-1]["ts"] - run[0]["ts"] < TRAJECTORY_MIN_SPAN_S:
779
+ continue
780
+ window = [(sample["ts"], sample["handle_temp_c"]) for sample in run]
781
+ t_inf = _project_t_inf(window, params.tau_min)
782
+ run_current = median(sample["vehicle_current_a"] for sample in run)
783
+ ambient = t_inf - params.rise_ref_c * (run_current / REF_CURRENT_A) ** 2
784
+ if -30.0 <= ambient <= TRIP_HANDLE_C:
785
+ return ambient
786
+ return None
787
+
788
+
789
+ def predict(db: Database, now: float, params: ThermalParams) -> dict:
790
+ """Forecast alert-40 for the current state (live session or idle)."""
791
+ out: dict = {"model": params.as_dict(), "state": "no_data", "forecast": None}
792
+ recent = [
793
+ row for row in db.vitals_range(now - 900, now, 2000) if row.get("handle_temp_c") is not None
794
+ ]
795
+ if not recent:
796
+ return out
797
+ last = recent[-1]
798
+ out.update(
799
+ {
800
+ "ts": last["ts"],
801
+ "handle_c": round(last["handle_temp_c"], 1),
802
+ "current_a": last.get("vehicle_current_a"),
803
+ }
804
+ )
805
+ if now - last["ts"] > 120:
806
+ out["state"] = "stale"
807
+ return out
808
+
809
+ tau_min = params.tau_min
810
+ current = last.get("vehicle_current_a") or 0.0
811
+ charging = bool(last.get("contactor_closed")) and current >= 6.0
812
+
813
+ if charging:
814
+ out["state"] = "charging"
815
+ band = max(2.0, 0.1 * current)
816
+ window: list[tuple[float, float]] = []
817
+ # Why the window ended matters when the forecast comes up empty:
818
+ # breaking on an out-of-band sample means the current just changed
819
+ # mid-session, not that charging began moments ago.
820
+ gap_reason = "warming_up"
821
+ for sample in reversed(recent):
822
+ if not sample.get("contactor_closed") or last["ts"] - sample["ts"] > 360:
823
+ break
824
+ if abs((sample.get("vehicle_current_a") or 0) - current) > band:
825
+ gap_reason = "current_changed"
826
+ break
827
+ window.append((sample["ts"], sample["handle_temp_c"]))
828
+ window.reverse()
829
+ forecast: dict = {}
830
+ if len(window) >= TRAJECTORY_MIN_SAMPLES and window[-1][0] - window[0][0] >= TRAJECTORY_MIN_SPAN_S:
831
+ t_inf = _project_t_inf(window, tau_min)
832
+ forecast["basis"] = "trajectory"
833
+ else:
834
+ # Too early at this current for a slope: model from ambient and
835
+ # the present current scaled by I^2. Ambient comes from the LAN
836
+ # sensor when one is reporting, else the idle stretch before the
837
+ # session, or — when sessions run back-to-back and there was
838
+ # none — from the newest steady run in the buffer.
839
+ measured = _latest_measured_ambient(db, now)
840
+ ambient, source = measured if measured is not None else (None, None)
841
+ if ambient is None:
842
+ sid = last.get("session_id")
843
+ sess = db.session(int(sid)) if sid else None
844
+ ambient = _ambient_before(db, sess["start_ts"]) if sess else None
845
+ source = "pre_session"
846
+ if ambient is None:
847
+ ambient = _recent_steady_ambient(recent, params)
848
+ source = "recent_trajectory"
849
+ if ambient is None:
850
+ # A session's opening ramp also breaks the band; within the
851
+ # first minutes "just started" is the truthful story even so.
852
+ if sess and last["ts"] - sess["start_ts"] < 180:
853
+ gap_reason = "warming_up"
854
+ out["forecast"] = {"basis": "insufficient", "will_trip": None, "reason": gap_reason}
855
+ return out
856
+ t_inf = ambient + params.rise_ref_c * (current / REF_CURRENT_A) ** 2
857
+ forecast["basis"] = "model"
858
+ forecast["ambient_source"] = source
859
+ # No flooring of t_inf at the current temperature: a steady state
860
+ # below the handle is real, not noise — it's what cooling toward a
861
+ # lower equilibrium looks like after a current cut or a derate.
862
+ minutes = _minutes_to_trip(last["handle_temp_c"], t_inf, tau_min)
863
+ forecast.update(
864
+ {
865
+ "steady_state_c": round(t_inf, 1),
866
+ "will_trip": minutes is not None,
867
+ "minutes_to_trip": round(minutes, 1) if minutes is not None else None,
868
+ "trip_ts": last["ts"] + minutes * 60.0 if minutes is not None else None,
869
+ }
870
+ )
871
+ if minutes is not None:
872
+ # Ambient implied by the steady state at this current; from it,
873
+ # the highest cap that avoids the trip (and the 50% foldback).
874
+ ambient = t_inf - params.rise_ref_c * (current / REF_CURRENT_A) ** 2
875
+ forecast["suggested_max_a"] = suggest_max_current(ambient, params)
876
+ out["forecast"] = forecast
877
+ return out
878
+
879
+ if current < 1.0 and not last.get("contactor_closed"):
880
+ out["state"] = "idle"
881
+ temps = [row["handle_temp_c"] for row in recent if last["ts"] - row["ts"] <= 900]
882
+ stable = len(temps) >= 3 and max(temps) - min(temps) <= 1.5
883
+ measured = _latest_measured_ambient(db, now)
884
+ if measured is not None:
885
+ # A reporting LAN sensor reads the garage air directly — no idle
886
+ # offset assumption, and valid even while the handle is still
887
+ # cooling from a recent charge (when the proxy reads high).
888
+ ambient, ambient_source = measured
889
+ stable = True
890
+ else:
891
+ ambient = ambient_from_idle_handle(last["handle_temp_c"])
892
+ ambient_source = "idle_handle"
893
+ out["ambient_c"] = round(ambient, 1)
894
+ out["ambient_source"] = ambient_source
895
+ out["ambient_stable"] = stable
896
+ # Hypothetical: a full-rate session started right now.
897
+ t_inf = ambient + params.rise_ref_c
898
+ minutes = _minutes_to_trip(last["handle_temp_c"], t_inf, tau_min)
899
+ out["forecast"] = {
900
+ "basis": "hypothetical",
901
+ "steady_state_c": round(t_inf, 1),
902
+ "will_trip": minutes is not None,
903
+ "minutes_to_trip": round(minutes, 1) if minutes is not None else None,
904
+ "trip_ts": None,
905
+ "safe_ambient_max_c": round(TRIP_HANDLE_C - params.rise_ref_c, 1),
906
+ "suggested_max_a": suggest_max_current(ambient, params) if minutes is not None else None,
907
+ }
908
+ return out
909
+
910
+ out["state"] = "connected"
911
+ return out