wallmonitor 0.4.0__tar.gz → 0.5.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.4.0
3
+ Version: 0.5.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
@@ -65,7 +65,8 @@ between dashboards, and the service installer's `--name` does it all per
65
65
  charger in one command. See [More than one Wall Connector](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md#more-than-one-wall-connector).
66
66
 
67
67
  All history lands in a single `wallmonitor.db` SQLite file — back up that
68
- one file and you have everything. For every option, and for running it as a
68
+ one file and you have everything (`wallmonitor --backup DIR` writes a
69
+ verified, compressed snapshot wherever you point it, while running). For every option, and for running it as a
69
70
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
70
71
 
71
72
  ## At a glance
@@ -42,7 +42,8 @@ between dashboards, and the service installer's `--name` does it all per
42
42
  charger in one command. See [More than one Wall Connector](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md#more-than-one-wall-connector).
43
43
 
44
44
  All history lands in a single `wallmonitor.db` SQLite file — back up that
45
- one file and you have everything. For every option, and for running it as a
45
+ one file and you have everything (`wallmonitor --backup DIR` writes a
46
+ verified, compressed snapshot wherever you point it, while running). For every option, and for running it as a
46
47
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
47
48
 
48
49
  ## At a glance
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.4.0"
3
+ version = "0.5.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.4.0"
3
+ version = "0.5.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"
@@ -30,13 +30,17 @@ from .web import make_app
30
30
  log = logging.getLogger("wallmonitor")
31
31
 
32
32
 
33
- async def _maintenance(db: Database, cfg) -> None:
34
- """Background housekeeping: the one-time diagnostics backfill, then —
35
- when retention is enabled — a daily raw-JSON trim of samples older
36
- than the retention window. Chunked throughout, so live polling only
37
- ever waits a moment."""
33
+ async def _maintenance(db: Database, cfg, poller: Poller) -> None:
34
+ """Background housekeeping: the one-time diagnostics backfill, then a
35
+ daily pass that (a) refits the idle-offset model from this install's
36
+ own settled-idle history when a stationary ambient sensor has been
37
+ reporting, adopting it only on a material, sane change, and (b) when
38
+ retention is enabled, trims raw JSON older than the window. Chunked
39
+ throughout, so live polling only ever waits a moment."""
38
40
  import time as _time
39
41
 
42
+ from . import calibration, thermal
43
+
40
44
  def report(done: int, total: int) -> None:
41
45
  if done % 200_000 < 10_000 or done >= total:
42
46
  log.info("diagnostics backfill: %d / %d rows", done, total)
@@ -44,15 +48,27 @@ async def _maintenance(db: Database, cfg) -> None:
44
48
  touched = await asyncio.to_thread(db.backfill_diag_columns, 10_000, report)
45
49
  if touched:
46
50
  log.info("diagnostics backfill complete: %d rows", touched)
47
- if not cfg.retain_raw_days:
48
- return
49
51
  while True:
50
- cutoff = _time.time() - cfg.retain_raw_days * 86400.0
51
- counts = await asyncio.to_thread(db.trim_raw, cutoff)
52
- total = sum(counts.values())
53
- if total:
54
- log.info("retention: trimmed raw JSON from %d rows (%s)", total,
55
- ", ".join(f"{k}={v}" for k, v in counts.items() if v))
52
+ now = _time.time()
53
+ try:
54
+ old, new, why = await asyncio.to_thread(
55
+ calibration.maybe_adopt, db, now, thermal.IDLE_OFFSET_SETTING)
56
+ if new is not None:
57
+ log.info("idle-offset calibration adopted: %.2f C at %.0f C, slope %.4f, %d segments over %d days",
58
+ new["ref_c"], new["ambient_ref_c"], new["slope"], new["segments"], new["days"])
59
+ await poller._event(now, "idle_offset_calibrated", {"old": old, "new": new})
60
+ poller.invalidate_thermal()
61
+ elif why and why != "no material change":
62
+ log.info("idle-offset calibration not adopted: %s", why)
63
+ except Exception:
64
+ log.exception("idle-offset calibration failed")
65
+ if cfg.retain_raw_days:
66
+ cutoff = now - cfg.retain_raw_days * 86400.0
67
+ counts = await asyncio.to_thread(db.trim_raw, cutoff)
68
+ total = sum(counts.values())
69
+ if total:
70
+ log.info("retention: trimmed raw JSON from %d rows (%s)", total,
71
+ ", ".join(f"{k}={v}" for k, v in counts.items() if v))
56
72
  await asyncio.sleep(24 * 3600.0)
57
73
 
58
74
 
@@ -65,6 +81,16 @@ async def run(argv: list[str] | None = None) -> None:
65
81
  cfg = parse_args(argv)
66
82
  if cfg.discover is not None:
67
83
  raise SystemExit(await run_discovery(cfg.discover, split_phase_hint=cfg.split_phase))
84
+ if cfg.backup_dir:
85
+ from .backup import Keep, run_backup
86
+
87
+ result = run_backup(cfg.db_path, cfg.backup_dir, cfg.backup_compress, Keep.parse(cfg.backup_keep))
88
+ print(f"{result.path}: {result.snapshot_bytes / 1e6:.1f} MB snapshot (integrity {result.integrity}, "
89
+ f"{result.snapshot_s:.1f} s) -> {result.output_bytes / 1e6:.1f} MB "
90
+ f"{cfg.backup_compress} ({result.compress_s:.1f} s)")
91
+ if result.deleted:
92
+ print(f"rotated out {len(result.deleted)}: " + ", ".join(result.deleted))
93
+ raise SystemExit(0)
68
94
  if cfg.compact:
69
95
  db = Database(cfg.db_path)
70
96
  try:
@@ -87,7 +113,7 @@ async def run(argv: list[str] | None = None) -> None:
87
113
  client = aiohttp.ClientSession()
88
114
  poller = Poller(cfg, db, bus, client)
89
115
  await poller.start()
90
- backfill = asyncio.create_task(_maintenance(db, cfg), name="wallmonitor-maintenance")
116
+ backfill = asyncio.create_task(_maintenance(db, cfg, poller), name="wallmonitor-maintenance")
91
117
 
92
118
  app = make_app(db, bus, poller)
93
119
  runner = web.AppRunner(app)
@@ -0,0 +1,222 @@
1
+ """One-shot database backup: consistent snapshot, verified, compressed,
2
+ rotated — into a directory the user chooses.
3
+
4
+ Where that directory *is* — a local path, a mounted NAS, a folder a sync
5
+ client watches (iCloud Drive, Sync, Syncthing, Dropbox), or somewhere a
6
+ second machine pulls from with rsync — is deliberately none of this
7
+ module's business. wallmonitor never talks to a cloud; it writes a file.
8
+
9
+ Order of operations, and why:
10
+
11
+ 1. Snapshot with SQLite's online backup API into a temp file *next to the
12
+ source* (never in the destination: a sync-watched folder would upload a
13
+ transient uncompressed copy). Consistent under WAL while the service
14
+ keeps polling — measured at ~4 s for a 1.4 GB database.
15
+ 2. ``PRAGMA integrity_check`` on the snapshot before compressing. A backup
16
+ that is corrupt but looks fine is the worst outcome; better to fail loud.
17
+ 3. Compress (gzip by default: ~12x, seconds; xz: ~22x, minutes) to a temp
18
+ name in the destination, fsync, atomic rename — a sync client never sees
19
+ a half-written file.
20
+ 4. Rotate: keep the newest per day / per ISO week / per month for the
21
+ configured counts, judged by the date in the filename (sync clients
22
+ rewrite mtimes). Only files matching this module's own naming pattern
23
+ are ever deleted; anything else in the folder is left alone.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import datetime as _dt
29
+ import gzip
30
+ import lzma
31
+ import os
32
+ import re
33
+ import shutil
34
+ import sqlite3
35
+ import tempfile
36
+ import time
37
+ from dataclasses import dataclass
38
+
39
+ COMPRESSIONS = ("gzip", "xz", "none")
40
+ _SUFFIX = {"gzip": ".db.gz", "xz": ".db.xz", "none": ".db"}
41
+ _NAME_RE = re.compile(
42
+ r"^wallmonitor-(?P<serial>[A-Za-z0-9_-]+)-(?P<date>\d{8})T(?P<time>\d{6})Z\.db(?:\.gz|\.xz)?$"
43
+ )
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Keep:
48
+ """Rotation policy: how many daily / weekly / monthly snapshots to keep."""
49
+
50
+ daily: int = 7
51
+ weekly: int = 4
52
+ monthly: int = 12
53
+
54
+ @classmethod
55
+ def parse(cls, spec: str) -> "Keep":
56
+ try:
57
+ d, w, m = (int(part) for part in spec.split("/"))
58
+ except ValueError:
59
+ raise ValueError(f"--backup-keep must be DAILY/WEEKLY/MONTHLY, e.g. 7/4/12 (got {spec!r})")
60
+ if min(d, w, m) < 0:
61
+ raise ValueError("--backup-keep counts must be non-negative")
62
+ return cls(d, w, m)
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class BackupResult:
67
+ path: str
68
+ serial: str
69
+ snapshot_bytes: int
70
+ output_bytes: int
71
+ snapshot_s: float
72
+ compress_s: float
73
+ integrity: str
74
+ deleted: tuple[str, ...]
75
+
76
+
77
+ def _serial(db_path: str) -> str:
78
+ """The pinned charger serial, so multi-charger installs (or two boxes
79
+ sharing one folder) never collide on a filename; 'unpinned' before the
80
+ monitor has ever reached its charger."""
81
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
82
+ try:
83
+ row = conn.execute("SELECT value FROM settings WHERE key = 'device_serial'").fetchone()
84
+ except sqlite3.OperationalError:
85
+ row = None
86
+ finally:
87
+ conn.close()
88
+ serial = (row[0] if row else "") or "unpinned"
89
+ return re.sub(r"[^A-Za-z0-9_-]", "_", serial)
90
+
91
+
92
+ def snapshot(db_path: str, dest_path: str) -> tuple[float, str]:
93
+ """Online-backup the live database to dest_path and integrity-check the
94
+ copy. Returns (seconds, integrity result — 'ok' or the first problem)."""
95
+ src = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
96
+ t0 = time.monotonic()
97
+ try:
98
+ dst = sqlite3.connect(dest_path)
99
+ try:
100
+ src.backup(dst)
101
+ finally:
102
+ dst.close()
103
+ finally:
104
+ src.close()
105
+ took = time.monotonic() - t0
106
+ check = sqlite3.connect(f"file:{dest_path}?mode=ro", uri=True)
107
+ try:
108
+ integrity = check.execute("PRAGMA integrity_check").fetchone()[0]
109
+ finally:
110
+ check.close()
111
+ return took, integrity
112
+
113
+
114
+ def _compress(src_path: str, out_path: str, compression: str) -> None:
115
+ opener = {
116
+ "gzip": lambda p: gzip.open(p, "wb", compresslevel=6),
117
+ "xz": lambda p: lzma.open(p, "wb", preset=6),
118
+ "none": lambda p: open(p, "wb"),
119
+ }[compression]
120
+ with open(src_path, "rb") as fin, opener(out_path) as fout:
121
+ shutil.copyfileobj(fin, fout, 1 << 20)
122
+ fout.flush()
123
+ os.fsync(fout.fileno())
124
+
125
+
126
+ def _parse(name: str) -> tuple[str, _dt.datetime] | None:
127
+ m = _NAME_RE.match(name)
128
+ if not m:
129
+ return None
130
+ when = _dt.datetime.strptime(m["date"] + m["time"], "%Y%m%d%H%M%S").replace(tzinfo=_dt.timezone.utc)
131
+ return m["serial"], when
132
+
133
+
134
+ def rotate(names: list[str], serial: str, keep: Keep) -> list[str]:
135
+ """Which of these filenames to delete for this serial under the policy.
136
+ Pure: judged by the timestamp in each name, so sync clients rewriting
137
+ mtimes can't confuse it. Newest-per-bucket survives in each tier; a
138
+ file kept by any tier is kept. Foreign files are never returned."""
139
+ dated = []
140
+ for name in names:
141
+ parsed = _parse(name)
142
+ if parsed and parsed[0] == serial:
143
+ dated.append((parsed[1], name))
144
+ dated.sort(reverse=True) # newest first
145
+ if keep.daily == keep.weekly == keep.monthly == 0:
146
+ return [] # 0/0/0: rotate nothing, keep everything
147
+ survivors: set[str] = set()
148
+
149
+ def keep_newest_per(bucket, limit: int) -> None:
150
+ seen: list = []
151
+ for when, name in dated:
152
+ key = bucket(when)
153
+ if key in seen:
154
+ continue
155
+ if len(seen) >= limit:
156
+ break
157
+ seen.append(key)
158
+ survivors.add(name)
159
+
160
+ keep_newest_per(lambda w: w.date(), keep.daily)
161
+ keep_newest_per(lambda w: w.isocalendar()[:2], keep.weekly)
162
+ keep_newest_per(lambda w: (w.year, w.month), keep.monthly)
163
+ return [name for _, name in dated if name not in survivors]
164
+
165
+
166
+ def run_backup(db_path: str, dest_dir: str, compression: str = "gzip", keep: Keep = Keep(),
167
+ now: float | None = None) -> BackupResult:
168
+ """Snapshot → verify → compress → atomic place → rotate. Raises on any
169
+ failure before the destination is touched; a failed integrity check
170
+ raises RuntimeError with SQLite's first complaint."""
171
+ if compression not in COMPRESSIONS:
172
+ raise ValueError(f"compression must be one of {COMPRESSIONS}")
173
+ os.makedirs(dest_dir, exist_ok=True)
174
+ serial = _serial(db_path)
175
+ stamp = _dt.datetime.fromtimestamp(now if now is not None else time.time(), _dt.timezone.utc)
176
+ final_name = f"wallmonitor-{serial}-{stamp:%Y%m%dT%H%M%SZ}{_SUFFIX[compression]}"
177
+ final_path = os.path.join(dest_dir, final_name)
178
+
179
+ # Snapshot beside the source, never in the destination.
180
+ src_dir = os.path.dirname(os.path.abspath(db_path)) or "."
181
+ fd, snap_path = tempfile.mkstemp(prefix=".wallmonitor-snapshot-", suffix=".db", dir=src_dir)
182
+ os.close(fd)
183
+ os.remove(snap_path) # sqlite creates it; mkstemp only reserved the name
184
+ tmp_out = final_path + ".tmp"
185
+ try:
186
+ snapshot_s, integrity = snapshot(db_path, snap_path)
187
+ if integrity != "ok":
188
+ raise RuntimeError(f"snapshot failed integrity_check: {integrity}")
189
+ snapshot_bytes = os.path.getsize(snap_path)
190
+ t0 = time.monotonic()
191
+ _compress(snap_path, tmp_out, compression)
192
+ compress_s = time.monotonic() - t0
193
+ os.replace(tmp_out, final_path)
194
+ dir_fd = os.open(dest_dir, os.O_RDONLY)
195
+ try:
196
+ os.fsync(dir_fd)
197
+ except OSError:
198
+ pass # some filesystems (network mounts) refuse; the rename already landed
199
+ finally:
200
+ os.close(dir_fd)
201
+ finally:
202
+ # The snapshot inherits WAL mode from the source, so verifying it
203
+ # leaves -wal/-shm siblings behind; sweep those too.
204
+ for path in (snap_path, snap_path + "-journal", snap_path + "-wal", snap_path + "-shm", tmp_out):
205
+ try:
206
+ os.remove(path)
207
+ except FileNotFoundError:
208
+ pass
209
+
210
+ doomed = rotate(os.listdir(dest_dir), serial, keep)
211
+ for name in doomed:
212
+ os.remove(os.path.join(dest_dir, name))
213
+ return BackupResult(
214
+ path=final_path,
215
+ serial=serial,
216
+ snapshot_bytes=snapshot_bytes,
217
+ output_bytes=os.path.getsize(final_path),
218
+ snapshot_s=snapshot_s,
219
+ compress_s=compress_s,
220
+ integrity=integrity,
221
+ deleted=tuple(sorted(doomed)),
222
+ )
@@ -0,0 +1,311 @@
1
+ """Per-install calibration of the idle handle offset.
2
+
3
+ The handle-proxy ambient (``ambient ≈ idle handle − offset``) rests on a
4
+ model of how far above garage air the idle handle settles. The built-in
5
+ model was fitted on one install; this module refits it from *this*
6
+ install's own history whenever a stationary ambient sensor gives ground
7
+ truth, so the shipped constants are the seed every install starts from
8
+ rather than the calibration every install is stuck with.
9
+
10
+ Estimator (shared, verbatim, with ``contrib/calibrate_idle_offset.py``):
11
+
12
+ - **Settled idle only.** Contactor open, no current, and at least
13
+ ``settle_s`` since the last charging sample — the handle needs a few time
14
+ constants to shed charge heat; including the decay biases the offset up.
15
+ - **Quasi-static ambient only.** The handle lags air by ~tau, so during fast
16
+ ambient swings the pairing (handle now, ambient now) is wrong even though
17
+ both sensors are right. Samples count only when ambient moved less than
18
+ ``max_drift_c`` over the prior 30 min.
19
+ - **Per-segment means, not per-sample stats.** Consecutive samples are
20
+ massively autocorrelated; treating them as independent would shrink the
21
+ error bars by ~sqrt(n) for free. Contiguous idle runs collapse to one
22
+ observation each and all inference runs on segment means.
23
+ - **Day-clustered slope error.** Segments within a day share weather, so
24
+ the offset-vs-ambient slope's significance is jackknifed leave-one-day-out.
25
+
26
+ Adoption is separate from estimation and deliberately conservative: sanity
27
+ gates (segment count, coverage, a bounded slope — the proxy inverts through
28
+ ``1 + slope``), and hysteresis so the model only moves on a material
29
+ change. Every proxy-tier fit in history is reinterpreted under the adopted
30
+ model on its next read, and a drift comparison spanning the change sees a
31
+ step — so adoption is recorded as an event, not done silently.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import math
38
+ from dataclasses import asdict, dataclass
39
+ from datetime import datetime
40
+
41
+ # Ambient-sample sources that are stationary garage thermometers. A parked
42
+ # car's sensor (source "car") drives away and reads high after drives; it
43
+ # is never calibration ground truth.
44
+ CAR_SOURCE = "car"
45
+
46
+ # The one SQL both loaders use, so the in-process estimator and the contrib
47
+ # script see identical rows (255 is the handle sensor's glitch sentinel).
48
+ VITALS_SQL = (
49
+ "SELECT ts, total_power_w, contactor_closed, vehicle_current_a, "
50
+ "CASE WHEN handle_temp_c >= 255 THEN NULL ELSE handle_temp_c END AS handle_temp_c "
51
+ "FROM vitals_samples WHERE ts >= ? AND ts < ? ORDER BY ts"
52
+ )
53
+ AMBIENT_SQL = (
54
+ "SELECT ts, temp_c FROM ambient_samples "
55
+ "WHERE ts >= ? AND ts < ? AND temp_c IS NOT NULL AND (source IS NULL OR source != ?) ORDER BY ts"
56
+ )
57
+
58
+ AMBIENT_REF_C = 30.0 # the offset is reported at this ambient
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Calibration:
63
+ """One estimate: what the data says, with its uncertainty attached."""
64
+
65
+ n_samples: int
66
+ n_segments: int
67
+ n_days: int
68
+ mean_offset_c: float
69
+ sd_c: float
70
+ ci95_c: tuple[float, float]
71
+ slope: float
72
+ slope_se: float
73
+ ambient_lo_c: float
74
+ ambient_hi_c: float
75
+ offset_ref_c: float # offset at AMBIENT_REF_C from the regression line
76
+ residual_sd_c: float # segment scatter around the fitted line
77
+ day_mean_c: float | None
78
+ night_mean_c: float | None
79
+ from_ts: float
80
+ to_ts: float
81
+
82
+ def as_dict(self) -> dict:
83
+ return asdict(self)
84
+
85
+
86
+ def _interp(series: list[tuple[float, float]], ts: float, max_gap: float = 300.0) -> float | None:
87
+ """Linear interpolation with a gap guard: None when the bracketing
88
+ samples are too far apart to trust the line between them."""
89
+ if not series or ts < series[0][0] or ts > series[-1][0]:
90
+ return None
91
+ lo, hi = 0, len(series) - 1
92
+ while hi - lo > 1:
93
+ mid = (lo + hi) // 2
94
+ if series[mid][0] <= ts:
95
+ lo = mid
96
+ else:
97
+ hi = mid
98
+ (t0, v0), (t1, v1) = series[lo], series[hi]
99
+ if t1 - t0 > max_gap:
100
+ return None
101
+ if t1 == t0:
102
+ return v0
103
+ return v0 + (ts - t0) / (t1 - t0) * (v1 - v0)
104
+
105
+
106
+ def _mean_sd(vals: list[float]) -> tuple[float, float]:
107
+ mu = sum(vals) / len(vals)
108
+ if len(vals) < 2:
109
+ return mu, float("nan")
110
+ return mu, math.sqrt(sum((v - mu) ** 2 for v in vals) / (len(vals) - 1))
111
+
112
+
113
+ def estimate(vitals: list[dict], ambient: list[tuple[float, float]], *, settle_s: float = 3600.0,
114
+ max_drift_c: float = 0.5, min_seg_span_s: float = 1200.0, min_seg_samples: int = 10,
115
+ min_segments: int = 8) -> Calibration | None:
116
+ """The estimator. ``vitals`` are raw rows (VITALS_SQL shape, oldest
117
+ first); ``ambient`` is the stationary sensor series. None when the
118
+ data can't support an estimate — never a number from too little."""
119
+ if len(ambient) < 100:
120
+ return None
121
+ last_charge = None
122
+ samples: list[tuple[float, float, float]] = [] # ts, handle, ambient
123
+ for r in vitals:
124
+ if (r["total_power_w"] or 0) > 50:
125
+ last_charge = r["ts"]
126
+ continue
127
+ if r["contactor_closed"] or (r["vehicle_current_a"] or 0) >= 1:
128
+ continue
129
+ if r["handle_temp_c"] is None:
130
+ continue
131
+ if last_charge is not None and r["ts"] - last_charge < settle_s:
132
+ continue
133
+ a_now = _interp(ambient, r["ts"])
134
+ a_prev = _interp(ambient, r["ts"] - 1800.0)
135
+ if a_now is None or a_prev is None or abs(a_now - a_prev) >= max_drift_c:
136
+ continue
137
+ samples.append((r["ts"], r["handle_temp_c"], a_now))
138
+ if not samples:
139
+ return None
140
+
141
+ segs: list[list[tuple[float, float, float]]] = [[samples[0]]]
142
+ for s in samples[1:]:
143
+ if s[0] - segs[-1][-1][0] > 600.0:
144
+ segs.append([s])
145
+ else:
146
+ segs[-1].append(s)
147
+ segs = [g for g in segs if len(g) >= min_seg_samples and g[-1][0] - g[0][0] >= min_seg_span_s]
148
+ if len(segs) < min_segments:
149
+ return None
150
+
151
+ seg_off = [sum(h - a for _, h, a in g) / len(g) for g in segs]
152
+ seg_amb = [sum(a for _, _, a in g) / len(g) for g in segs]
153
+ seg_day = [datetime.fromtimestamp((g[0][0] + g[-1][0]) / 2).strftime("%Y-%m-%d") for g in segs]
154
+ seg_hour = [datetime.fromtimestamp((g[0][0] + g[-1][0]) / 2).hour for g in segs]
155
+
156
+ n = len(segs)
157
+ mean, sd = _mean_sd(seg_off)
158
+ se = sd / math.sqrt(n)
159
+ tcrit = 2.045 if n < 60 else 2.0
160
+
161
+ day = [o for o, h in zip(seg_off, seg_hour) if 8 <= h < 20]
162
+ night = [o for o, h in zip(seg_off, seg_hour) if not 8 <= h < 20]
163
+
164
+ mx, _ = _mean_sd(seg_amb)
165
+ sxx = sum((x - mx) ** 2 for x in seg_amb)
166
+ slope = sum((x - mx) * (y - mean) for x, y in zip(seg_amb, seg_off)) / sxx if sxx > 0 else 0.0
167
+ days = sorted(set(seg_day))
168
+ jk = []
169
+ for d in days:
170
+ keep = [(x, y) for x, y, sd_ in zip(seg_amb, seg_off, seg_day) if sd_ != d]
171
+ if len(keep) < 2:
172
+ continue
173
+ kx = [x for x, _ in keep]
174
+ ky = [y for _, y in keep]
175
+ kmx = sum(kx) / len(kx)
176
+ kmy = sum(ky) / len(ky)
177
+ ksxx = sum((x - kmx) ** 2 for x in kx)
178
+ if ksxx > 0:
179
+ jk.append(sum((x - kmx) * (y - kmy) for x, y in zip(kx, ky)) / ksxx)
180
+ if len(jk) >= 2:
181
+ mj = sum(jk) / len(jk)
182
+ slope_se = math.sqrt((len(jk) - 1) / len(jk) * sum((v - mj) ** 2 for v in jk))
183
+ else:
184
+ slope_se = float("nan")
185
+ offset_ref = mean + slope * (AMBIENT_REF_C - mx)
186
+ resid = [o - (offset_ref + slope * (a - AMBIENT_REF_C)) for o, a in zip(seg_off, seg_amb)]
187
+ residual_sd = math.sqrt(sum(r * r for r in resid) / max(n - 2, 1))
188
+ return Calibration(
189
+ n_samples=len(samples),
190
+ n_segments=n,
191
+ n_days=len(days),
192
+ mean_offset_c=mean,
193
+ sd_c=sd,
194
+ ci95_c=(mean - tcrit * se, mean + tcrit * se),
195
+ slope=slope,
196
+ slope_se=slope_se,
197
+ ambient_lo_c=min(seg_amb),
198
+ ambient_hi_c=max(seg_amb),
199
+ offset_ref_c=offset_ref,
200
+ residual_sd_c=residual_sd,
201
+ day_mean_c=_mean_sd(day)[0] if len(day) >= 2 else None,
202
+ night_mean_c=_mean_sd(night)[0] if len(night) >= 2 else None,
203
+ from_ts=samples[0][0],
204
+ to_ts=samples[-1][0],
205
+ )
206
+
207
+
208
+ def calibrate(db, now: float, lookback_days: float = 30.0, **kwargs) -> Calibration | None:
209
+ """Estimate from a Database, day-chunked so a month of raw rows never
210
+ sits in memory at once."""
211
+ t_from = now - lookback_days * 86400.0
212
+ ambient = db.ambient_series(t_from, now, exclude_source=CAR_SOURCE)
213
+ if len(ambient) < 100:
214
+ return None
215
+ vitals: list[dict] = []
216
+ t = t_from
217
+ while t < now:
218
+ vitals.extend(db.idle_calibration_rows(t, min(t + 86400.0, now)))
219
+ t += 86400.0
220
+ return estimate(vitals, ambient, **kwargs)
221
+
222
+
223
+ # ---------------- adoption ----------------
224
+
225
+ # Sanity gates: a fit outside these is more likely a contaminated sensor or
226
+ # a pathological window than physics, and must not become the proxy model.
227
+ OFFSET_REF_RANGE_C = (-1.0, 5.0)
228
+ MAX_ABS_SLOPE = 0.5 # the proxy inverts through (1 + slope)
229
+ MIN_RANGE_FOR_SLOPE_C = 3.0 # narrower coverage can't support a slope: use a constant
230
+ MIN_DAYS = 3
231
+ # Hysteresis: re-estimate daily, adopt only on material change, so the
232
+ # proxy-tier fit history doesn't creep a little every day.
233
+ ADOPT_DELTA_REF_C = 0.25
234
+ ADOPT_DELTA_SLOPE = 0.03
235
+ ADOPT_RANGE_EXTEND_C = 2.0
236
+
237
+
238
+ def gate(cal: Calibration) -> str | None:
239
+ """Why this calibration must not be adopted, or None if it may be."""
240
+ if cal.n_days < MIN_DAYS:
241
+ return f"only {cal.n_days} days of settled idle"
242
+ lo, hi = OFFSET_REF_RANGE_C
243
+ if not (lo <= cal.offset_ref_c <= hi):
244
+ return f"offset {cal.offset_ref_c:.2f} C at {AMBIENT_REF_C:.0f} C outside {lo}..{hi}"
245
+ if abs(cal.slope) > MAX_ABS_SLOPE and cal.ambient_hi_c - cal.ambient_lo_c >= MIN_RANGE_FOR_SLOPE_C:
246
+ return f"slope {cal.slope:.3f} C/C implausible"
247
+ return None
248
+
249
+
250
+ def proposed_model(cal: Calibration, now: float) -> dict:
251
+ """The idle-offset model this calibration implies, as the settings
252
+ JSON shape thermal.IdleOffset reads. A coverage too narrow to support
253
+ a slope yields a constant offset at the covered ambient."""
254
+ width = cal.ambient_hi_c - cal.ambient_lo_c
255
+ slope = cal.slope if width >= MIN_RANGE_FOR_SLOPE_C else 0.0
256
+ if width >= MIN_RANGE_FOR_SLOPE_C:
257
+ ref_c, ambient_ref_c = cal.offset_ref_c, AMBIENT_REF_C
258
+ else:
259
+ ref_c, ambient_ref_c = cal.mean_offset_c, (cal.ambient_lo_c + cal.ambient_hi_c) / 2.0
260
+ return {
261
+ "ref_c": round(ref_c, 3),
262
+ "slope": round(slope, 4),
263
+ "ambient_ref_c": round(ambient_ref_c, 2),
264
+ "ambient_range_c": [round(math.floor(cal.ambient_lo_c * 2) / 2, 1),
265
+ round(math.ceil(cal.ambient_hi_c * 2) / 2, 1)],
266
+ "source": "calibrated",
267
+ "segments": cal.n_segments,
268
+ "days": cal.n_days,
269
+ "residual_sd_c": round(cal.residual_sd_c, 3),
270
+ "calibrated_ts": now,
271
+ }
272
+
273
+
274
+ def material_change(old: dict | None, new: dict) -> bool:
275
+ """Hysteresis: is `new` different enough from the stored model to be
276
+ worth reinterpreting the proxy-tier history over?"""
277
+ if not old or old.get("source") != "calibrated":
278
+ return True
279
+ ref = AMBIENT_REF_C
280
+ old_at_ref = old["ref_c"] + old["slope"] * (ref - old["ambient_ref_c"])
281
+ new_at_ref = new["ref_c"] + new["slope"] * (ref - new["ambient_ref_c"])
282
+ if abs(new_at_ref - old_at_ref) > ADOPT_DELTA_REF_C:
283
+ return True
284
+ if abs(new["slope"] - old["slope"]) > ADOPT_DELTA_SLOPE:
285
+ return True
286
+ olo, ohi = old["ambient_range_c"]
287
+ nlo, nhi = new["ambient_range_c"]
288
+ return (olo - nlo) > ADOPT_RANGE_EXTEND_C or (nhi - ohi) > ADOPT_RANGE_EXTEND_C
289
+
290
+
291
+ def maybe_adopt(db, now: float, setting_key: str, lookback_days: float = 30.0) -> tuple[dict | None, dict | None, str | None]:
292
+ """Run a calibration and adopt it if it passes the gates and moves the
293
+ model materially. Returns (old_model, new_model, reason): new_model is
294
+ None when nothing was adopted and reason says why (or None when there
295
+ simply wasn't enough data)."""
296
+ cal = calibrate(db, now, lookback_days)
297
+ if cal is None:
298
+ return None, None, None
299
+ why = gate(cal)
300
+ if why:
301
+ return None, None, why
302
+ new = proposed_model(cal, now)
303
+ raw = db.get_setting(setting_key)
304
+ try:
305
+ old = json.loads(raw) if raw else None
306
+ except ValueError:
307
+ old = None
308
+ if not material_change(old, new):
309
+ return old, None, "no material change"
310
+ db.set_setting(setting_key, json.dumps(new))
311
+ return old, new, None
@@ -39,6 +39,11 @@ class Config:
39
39
  retain_raw_days: float = 0.0
40
40
  # One-shot: VACUUM the database to reclaim trimmed space, print sizes, exit.
41
41
  compact: bool = False
42
+ # One-shot backup: snapshot, verify, compress, rotate into this directory
43
+ # (any path — local, NAS mount, sync-client folder), then exit.
44
+ backup_dir: str | None = None
45
+ backup_compress: str = "gzip"
46
+ backup_keep: str = "7/4/12"
42
47
  # Sibling instances watching other chargers, as (label, url) pairs;
43
48
  # rendered as a switcher in the header so one browser hops between them.
44
49
  peers: tuple[tuple[str, str], ...] = ()
@@ -169,6 +174,31 @@ def parse_args(argv: list[str] | None = None) -> Config:
169
174
  help="VACUUM the database to reclaim space freed by retention, print sizes, and exit. "
170
175
  "Run it while the monitor service is stopped.",
171
176
  )
177
+ parser.add_argument(
178
+ "--backup",
179
+ dest="backup_dir",
180
+ metavar="DIR",
181
+ default=_env("WM_BACKUP_DIR", None),
182
+ help="Write a verified, compressed snapshot of the database into DIR (created if "
183
+ "missing), rotate older snapshots there, and exit. Safe while the monitor runs. "
184
+ "DIR can be anything: a local path, a NAS mount, a folder a sync client watches. "
185
+ "(env: WM_BACKUP_DIR)",
186
+ )
187
+ parser.add_argument(
188
+ "--backup-compress",
189
+ choices=("gzip", "xz", "none"),
190
+ default=_env("WM_BACKUP_COMPRESS", "gzip"),
191
+ help="Snapshot compression: gzip (~12x, seconds — default), xz (~22x, minutes), or none. "
192
+ "(env: WM_BACKUP_COMPRESS)",
193
+ )
194
+ parser.add_argument(
195
+ "--backup-keep",
196
+ default=_env("WM_BACKUP_KEEP", "7/4/12"),
197
+ metavar="D/W/M",
198
+ help="Rotation: keep the newest snapshot per day for D days, per week for W weeks, "
199
+ "per month for M months (default 7/4/12; 0/0/0 keeps everything). Only "
200
+ "wallmonitor's own snapshot files are ever removed. (env: WM_BACKUP_KEEP)",
201
+ )
172
202
  parser.add_argument(
173
203
  "--peer",
174
204
  action="append",
@@ -218,7 +248,16 @@ def parse_args(argv: list[str] | None = None) -> Config:
218
248
  if args.retain_raw_days and args.retain_raw_days < 7:
219
249
  parser.error("--retain-raw-days must be at least 7 (or 0 to disable)")
220
250
 
221
- if not args.demo and not args.host and args.discover is None and not args.compact:
251
+ if args.backup_dir:
252
+ from .backup import Keep
253
+
254
+ try:
255
+ Keep.parse(args.backup_keep)
256
+ except ValueError as ex:
257
+ parser.error(str(ex))
258
+
259
+ if (not args.demo and not args.host and args.discover is None and not args.compact
260
+ and not args.backup_dir):
222
261
  parser.error(
223
262
  "--host (or WM_WC_HOST) is required — run `wallmonitor --discover` to find "
224
263
  "your Wall Connector's address, or --demo for the built-in simulator"
@@ -234,6 +273,9 @@ def parse_args(argv: list[str] | None = None) -> Config:
234
273
  label=args.label,
235
274
  retain_raw_days=float(args.retain_raw_days),
236
275
  compact=bool(args.compact),
276
+ backup_dir=args.backup_dir,
277
+ backup_compress=args.backup_compress,
278
+ backup_keep=args.backup_keep,
237
279
  peers=peers,
238
280
  discover=args.discover,
239
281
  notify_url=args.notify_url,
@@ -615,6 +615,23 @@ class Database:
615
615
  )
616
616
  return rows[0] if rows else None
617
617
 
618
+ def ambient_series(self, t_from: float, t_to: float, exclude_source: str | None = None) -> list[tuple[float, float]]:
619
+ """(ts, temp_c) for every ambient sample in the window, oldest
620
+ first, unbucketed and unlimited — calibration needs the real
621
+ series. exclude_source drops one tag (the car's roaming sensor)."""
622
+ from .calibration import AMBIENT_SQL
623
+
624
+ rows = self._rows(AMBIENT_SQL, (t_from, t_to, exclude_source if exclude_source is not None else ""))
625
+ return [(row["ts"], row["temp_c"]) for row in rows]
626
+
627
+ def idle_calibration_rows(self, t_from: float, t_to: float) -> list[dict]:
628
+ """Raw (unbucketed) vitals for the idle-offset calibration, in the
629
+ exact shape contrib/calibrate_idle_offset.py reads — same SQL, so
630
+ the two can never disagree. Callers chunk by day."""
631
+ from .calibration import VITALS_SQL
632
+
633
+ return self._rows(VITALS_SQL, (t_from, t_to))
634
+
618
635
  def set_setting(self, key: str, value: str) -> None:
619
636
  """Upsert into the string key/value settings table (currently only
620
637
  the thermal baseline anchor lives here)."""
@@ -495,6 +495,11 @@ class Poller:
495
495
  await asyncio.to_thread(self.db.clear_alert, ts, IDENTITY_ALERT, "monitor")
496
496
  await self._event(ts, "device_restored", {"serial": serial, "host": self.cfg.host})
497
497
 
498
+ def invalidate_thermal(self) -> None:
499
+ """Drop the cached forecast params so the next tick refits under a
500
+ newly adopted idle-offset model (proxy-tier fits reinterpret)."""
501
+ self._params = None
502
+
498
503
  async def recheck_thermal_drift(self, ts: float) -> None:
499
504
  """Refit history and raise/clear the degradation alert.
500
505
 
@@ -1060,7 +1060,8 @@ async function viewLive(root) {
1060
1060
  const ambLabel = data.ambient_source === "measured"
1061
1061
  ? "Garage ambient (sensor)"
1062
1062
  : data.ambient_source === "measured_car"
1063
- ? "Garage ambient (car sensor)" : "Ambient at the charger ≈";
1063
+ ? "Garage ambient (car sensor)"
1064
+ : `Ambient at the charger ≈ (from the idle handle, ±${fmtNum(data.ambient_se_c || 1.5, 1)} °C)`;
1064
1065
  if (forecast.will_trip) {
1065
1066
  chip = chipFor("warning", "hot enough to derate");
1066
1067
  lines.push(`${ambLabel} ${amb}. A full-rate (${fmtNum(model.ref_current_a, 0)} A) charge started now ` +
@@ -1118,11 +1119,22 @@ async function viewLive(root) {
1118
1119
  (dev.tau_frac < -0.3 ? `, and with a τ this fast only charges of ≥ ${fmtNum(1.8 * dev.default_tau_min, 0)} min ` +
1119
1120
  "at steady current teach the model." : ".");
1120
1121
  }
1122
+ // The handle-proxy ambient rests on the idle-offset model; say whose
1123
+ // it is. Calibrated from this install's own sensor history, or the
1124
+ // built-in seed from one install — and, without a sensor, how far a
1125
+ // proxy read may sit from the truth.
1126
+ const io = model.idle_offset;
1127
+ const idleNote = !io ? "" : io.source === "calibrated"
1128
+ ? ` Idle-offset model calibrated to this install (${fmtNum(io.ref_c, 2)} °C at ${fmtNum(io.ambient_ref_c, 0)} °C from ` +
1129
+ `${io.segments} idle segments over ${io.days} days, ±${fmtNum(io.ambient_se_c, 1)} °C).`
1130
+ : ` Idle-offset model is the built-in seed from one install (±${fmtNum(io.ambient_se_c, 1)} °C on handle-derived ambient); ` +
1131
+ "a stationary sensor posting to /api/ambient calibrates it here automatically.";
1121
1132
  const modelNote = `Model: τ ≈ ${fmtNum(model.tau_min, 1)} min, +${fmtNum(model.rise_ref_c, 0)} °C at ${fmtNum(model.ref_current_a, 0)} A — ` +
1122
1133
  (model.fitted ? `fitted from ${model.tau_fits} recorded session ramp${model.tau_fits === 1 ? "" : "s"}.` + priorNote
1123
1134
  : "defaults from one verified install, used until this charger has fits of its own; refits automatically as sessions accumulate.") +
1124
1135
  (drift && !drift.drifting && !drift.lead ? ` Heat rise stable across the last ${drift.recent_n + drift.baseline_n} fitted sessions` +
1125
- `${drift.off_current_n ? ` (${drift.off_current_n} off-current session${drift.off_current_n === 1 ? "" : "s"} excluded)` : ""}.` : "");
1136
+ `${drift.off_current_n ? ` (${drift.off_current_n} off-current session${drift.off_current_n === 1 ? "" : "s"} excluded)` : ""}.` : "") +
1137
+ idleNote;
1126
1138
  thermalCard.append(el("div", { class: "chart-card" },
1127
1139
  el("div", { class: "chart-title" }, "Thermal derate forecast", chip ? " " : null, chip),
1128
1140
  ...lines.map((text) => el("div", { class: "note" }, text)),
@@ -1683,9 +1695,10 @@ async function viewAlerts(root, rangeKey = "7d") {
1683
1695
  const now = Date.now() / 1000;
1684
1696
  const from = now - rangeSeconds(rangeKey);
1685
1697
  root.append(el("h2", {}, "Alerts"));
1686
- const [data, thermalData] = await Promise.all([
1698
+ const [data, thermalData, calEvents] = await Promise.all([
1687
1699
  getJSON(`/api/alerts?from=${from}&to=${now}`),
1688
1700
  getJSON("/api/thermal").catch(() => null),
1701
+ getJSON(`/api/events?from=${now - 120 * 86400}&to=${now}&kinds=idle_offset_calibrated`).catch(() => null),
1689
1702
  loadAlertCodes(),
1690
1703
  ]);
1691
1704
 
@@ -1724,9 +1737,13 @@ async function viewAlerts(root, rangeKey = "7d") {
1724
1737
  `Fitted steady-state rise above ambient, normalized to ${fmtNum(thermalData.model.ref_current_a, 0)} A. ` +
1725
1738
  "A sustained climb at the same current means added resistance in the current path — inspect before it becomes heat.");
1726
1739
  root.append(rise.card);
1740
+ // An adopted idle-offset calibration reinterprets every proxy-tier fit
1741
+ // at once; mark it, so a step here carries its explanation instead of
1742
+ // reading as the connector changing.
1743
+ const calMarks = ((calEvents && calEvents.events) || []).map((ev) => ({ ts: ev.ts, label: "idle-offset recalibrated" }));
1727
1744
  lineChart(rise.box, {
1728
1745
  series: [{ name: "Rise (°C)", color: colors.s1, points: fits.map((fit) => [fit.start_ts, fit.rise_ref_c]) }],
1729
- unit: "°C", digits: 1, height: 180,
1746
+ unit: "°C", digits: 1, height: 180, vlines: calMarks,
1730
1747
  });
1731
1748
  if (drift) {
1732
1749
  // The verdict carries its own uncertainty — a delta from a handful of
@@ -31,6 +31,7 @@ is measured and removed instead of leaking into the fitted rise.
31
31
  from __future__ import annotations
32
32
 
33
33
  import math
34
+ import json
34
35
  from dataclasses import dataclass
35
36
  from statistics import median
36
37
 
@@ -63,35 +64,122 @@ IDLE_OFFSET_SLOPE = -0.124 # d(offset)/d(ambient)
63
64
  IDLE_OFFSET_AMBIENT_REF_C = 30.0
64
65
  IDLE_OFFSET_AMBIENT_RANGE_C = (23.0, 38.5) # calibration coverage; clamp outside
65
66
 
67
+ # These constants are the *seed*, not the calibration: when a stationary
68
+ # ambient sensor gives this install ground truth, calibration.maybe_adopt
69
+ # refits the same linear model from its own settled-idle history and
70
+ # stores it under this settings key; every proxy read then goes through
71
+ # the install's model. Without a sensor the seed stands, labelled as such.
72
+ IDLE_OFFSET_SETTING = "idle_offset_model"
73
+ # Proxy ambient uncertainty when no calibration exists: the built-in fit's
74
+ # own segment scatter was ~0.5 C on its install; a different garage can be
75
+ # off by a constant this large without any way to know.
76
+ IDLE_OFFSET_UNCALIBRATED_SE_C = 1.5
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class IdleOffset:
81
+ """The idle-offset model: offset = ref_c + slope * (ambient - ambient_ref_c),
82
+ linear inside ambient_range_c and held at the boundary value outside it
83
+ (continuous at both edges), so out-of-range readings degrade to a
84
+ constant-offset proxy instead of extrapolating the slope."""
85
+
86
+ ref_c: float = IDLE_OFFSET_REF_C
87
+ slope: float = IDLE_OFFSET_SLOPE
88
+ ambient_ref_c: float = IDLE_OFFSET_AMBIENT_REF_C
89
+ ambient_range_c: tuple[float, float] = IDLE_OFFSET_AMBIENT_RANGE_C
90
+ source: str = "built-in"
91
+ segments: int = 0
92
+ days: int = 0
93
+ residual_sd_c: float | None = None
94
+ calibrated_ts: float | None = None
95
+
96
+ def offset_c(self, ambient_c: float) -> float:
97
+ lo, hi = self.ambient_range_c
98
+ clamped = min(max(ambient_c, lo), hi)
99
+ return self.ref_c + self.slope * (clamped - self.ambient_ref_c)
100
+
101
+ def handle_c(self, ambient_c: float) -> float:
102
+ return ambient_c + self.offset_c(ambient_c)
103
+
104
+ def ambient_from_handle(self, handle_c: float) -> float:
105
+ ta = (handle_c - self.ref_c + self.slope * self.ambient_ref_c) / (1.0 + self.slope)
106
+ lo, hi = self.ambient_range_c
107
+ if ta < lo:
108
+ return handle_c - self.offset_c(lo)
109
+ if ta > hi:
110
+ return handle_c - self.offset_c(hi)
111
+ return ta
66
112
 
67
- def idle_offset_c(ambient_c: float) -> float:
113
+ @property
114
+ def ambient_se_c(self) -> float:
115
+ """How far a proxy ambient read may sit from the truth (1 sigma):
116
+ the calibration's own segment scatter, or the uncalibrated default."""
117
+ if self.source == "calibrated" and self.residual_sd_c is not None:
118
+ return max(self.residual_sd_c, 0.2)
119
+ return IDLE_OFFSET_UNCALIBRATED_SE_C
120
+
121
+ def as_dict(self) -> dict:
122
+ return {
123
+ "source": self.source,
124
+ "ref_c": round(self.ref_c, 3),
125
+ "slope": round(self.slope, 4),
126
+ "ambient_ref_c": self.ambient_ref_c,
127
+ "ambient_range_c": [self.ambient_range_c[0], self.ambient_range_c[1]],
128
+ "segments": self.segments,
129
+ "days": self.days,
130
+ "residual_sd_c": round(self.residual_sd_c, 3) if self.residual_sd_c is not None else None,
131
+ "ambient_se_c": round(self.ambient_se_c, 2),
132
+ "calibrated_ts": self.calibrated_ts,
133
+ }
134
+
135
+ @classmethod
136
+ def from_dict(cls, data: dict) -> "IdleOffset":
137
+ lo, hi = data["ambient_range_c"]
138
+ return cls(
139
+ ref_c=float(data["ref_c"]),
140
+ slope=float(data["slope"]),
141
+ ambient_ref_c=float(data["ambient_ref_c"]),
142
+ ambient_range_c=(float(lo), float(hi)),
143
+ source=str(data.get("source", "calibrated")),
144
+ segments=int(data.get("segments", 0)),
145
+ days=int(data.get("days", 0)),
146
+ residual_sd_c=data.get("residual_sd_c"),
147
+ calibrated_ts=data.get("calibrated_ts"),
148
+ )
149
+
150
+
151
+ BUILTIN_IDLE_OFFSET = IdleOffset()
152
+
153
+
154
+ def load_idle_offset(db: Database) -> IdleOffset:
155
+ """This install's idle-offset model: the calibrated one when a sane one
156
+ is stored, else the built-in seed. Never raises — a corrupt setting
157
+ falls back to the seed."""
158
+ raw = db.get_setting(IDLE_OFFSET_SETTING)
159
+ if not raw:
160
+ return BUILTIN_IDLE_OFFSET
161
+ try:
162
+ model = IdleOffset.from_dict(json.loads(raw))
163
+ except (ValueError, KeyError, TypeError):
164
+ return BUILTIN_IDLE_OFFSET
165
+ if not (-0.95 < model.slope < 0.95) or model.ambient_range_c[0] >= model.ambient_range_c[1]:
166
+ return BUILTIN_IDLE_OFFSET
167
+ return model
168
+
169
+
170
+ def idle_offset_c(ambient_c: float, model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float:
68
171
  """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)
172
+ return model.offset_c(ambient_c)
72
173
 
73
174
 
74
- def idle_handle_c(ambient_c: float) -> float:
175
+ def idle_handle_c(ambient_c: float, model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float:
75
176
  """Idle handle temperature expected at a given garage air temperature."""
76
- return ambient_c + idle_offset_c(ambient_c)
77
-
177
+ return model.handle_c(ambient_c)
78
178
 
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
179
 
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
180
+ def ambient_from_idle_handle(handle_c: float, model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float:
181
+ """Garage air implied by a settled idle handle: inverse of idle_handle_c."""
182
+ return model.ambient_from_handle(handle_c)
95
183
  REF_CURRENT_A = 48.0 # rise_ref_c is normalized to this charge current
96
184
 
97
185
  DEFAULT_TAU_MIN = 12.0
@@ -336,7 +424,7 @@ def _latest_measured_ambient(db: Database, now: float) -> tuple[float, str] | No
336
424
  return rows[-1]["temp_c"], tag
337
425
 
338
426
 
339
- def _ambient_before(db: Database, start_ts: float) -> float | None:
427
+ def _ambient_before(db: Database, start_ts: float, model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float | None:
340
428
  """Ambient estimate from the idle handle temperature before a session."""
341
429
  rows = db.vitals_range(start_ts - 2400, start_ts - 30, 5000)
342
430
  idle = [
@@ -348,7 +436,7 @@ def _ambient_before(db: Database, start_ts: float) -> float | None:
348
436
  ]
349
437
  if len(idle) < 5 or max(idle) - min(idle) > 2.0:
350
438
  return None
351
- return ambient_from_idle_handle(median(idle))
439
+ return ambient_from_idle_handle(median(idle), model)
352
440
 
353
441
 
354
442
  # Cool-down-tail ambient: gates for reading ambient from a still-warm
@@ -359,7 +447,7 @@ COOLDOWN_MIN_DROP_C = 1.0
359
447
  COOLDOWN_MAX_RMSE_C = 0.5
360
448
 
361
449
 
362
- def _decay_asymptote(tail: list[dict], tau_min: float) -> float | None:
450
+ def _decay_asymptote(tail: list[dict], tau_min: float, model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float | None:
363
451
  """Ambient from a cooling handle's decay: least-squares asymptote of a
364
452
  first-order lag at a known tau, minus the idle offset. Gated on span,
365
453
  visible drop, and fit quality; None when the tail can't be trusted."""
@@ -386,7 +474,7 @@ def _decay_asymptote(tail: list[dict], tau_min: float) -> float | None:
386
474
  )
387
475
  if rmse > COOLDOWN_MAX_RMSE_C:
388
476
  return None # not a clean single-exponential decay at this tau
389
- ambient = ambient_from_idle_handle(asymptote)
477
+ ambient = ambient_from_idle_handle(asymptote, model)
390
478
  if not (-30.0 <= ambient <= TRIP_HANDLE_C):
391
479
  return None
392
480
  return ambient
@@ -406,7 +494,8 @@ def _idle_rows(rows: list[dict]) -> list[dict]:
406
494
  ]
407
495
 
408
496
 
409
- def _ambient_from_cooldown(db: Database, start_ts: float, tau_min: float) -> float | None:
497
+ def _ambient_from_cooldown(db: Database, start_ts: float, tau_min: float,
498
+ model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float | None:
410
499
  """Ambient from the cool-down tail before a segment that starts warm.
411
500
 
412
501
  A stop/resume or post-derate segment begins before the handle has
@@ -430,10 +519,11 @@ def _ambient_from_cooldown(db: Database, start_ts: float, tau_min: float) -> flo
430
519
  break
431
520
  tail.append(row)
432
521
  tail.reverse()
433
- return _decay_asymptote(tail, tau_min)
522
+ return _decay_asymptote(tail, tau_min, model)
434
523
 
435
524
 
436
- def _ambient_after(db: Database, end_ts: float, tau_min: float) -> float | None:
525
+ def _ambient_after(db: Database, end_ts: float, tau_min: float,
526
+ model: IdleOffset = BUILTIN_IDLE_OFFSET) -> float | None:
437
527
  """Ambient at the end of a load window, from the cool-down that follows.
438
528
 
439
529
  The moment current stops, the handle decays from its working temperature
@@ -454,7 +544,7 @@ def _ambient_after(db: Database, end_ts: float, tau_min: float) -> float | None:
454
544
  if row["ts"] - tail[-1]["ts"] > 120.0:
455
545
  break
456
546
  tail.append(row)
457
- return _decay_asymptote(tail, tau_min)
547
+ return _decay_asymptote(tail, tau_min, model)
458
548
 
459
549
 
460
550
  def fit_sessions(db: Database, now: float, lookback_days: float = 120.0) -> list[dict]:
@@ -486,6 +576,7 @@ def fit_sessions(db: Database, now: float, lookback_days: float = 120.0) -> list
486
576
  if session.get("end_ts") and (session.get("charging_s") or 0) >= MIN_SEGMENT_S
487
577
  ][:40]
488
578
  fits: list[dict] = []
579
+ idle_model = load_idle_offset(db)
489
580
  for sess in sessions:
490
581
  # Coarse pass over the whole session to locate charging segments —
491
582
  # bucket-averaged is fine here (and keeps a multi-day session cheap);
@@ -539,14 +630,14 @@ def fit_sessions(db: Database, now: float, lookback_days: float = 120.0) -> list
539
630
  measured = _measured_ambient(db, seg_start - MEASURED_AMBIENT_WINDOW_S, seg_start + 60)
540
631
  ambient, ambient_source = measured if measured is not None else (None, None)
541
632
  if ambient is None:
542
- ambient = _ambient_before(db, seg_start)
633
+ ambient = _ambient_before(db, seg_start, idle_model)
543
634
  ambient_source = "pre_idle" if ambient is not None else None
544
635
  if ambient is None:
545
636
  # Hot-handle start (stop/resume, post-derate): read ambient
546
637
  # from the previous charge's cool-down tail instead, using
547
638
  # this install's fitted tau (this segment's own plus any
548
639
  # earlier fits this pass).
549
- ambient = _ambient_from_cooldown(db, seg_start, tau_est)
640
+ ambient = _ambient_from_cooldown(db, seg_start, tau_est, idle_model)
550
641
  if ambient is not None:
551
642
  ambient_source = "cooldown_tail"
552
643
  ambient_end = None
@@ -554,7 +645,7 @@ def fit_sessions(db: Database, now: float, lookback_days: float = 120.0) -> list
554
645
  measured_end = _measured_ambient(db, seg_end - 60, seg_end + MEASURED_AMBIENT_WINDOW_S)
555
646
  ambient_end = measured_end[0] if measured_end is not None else None
556
647
  if ambient_end is None:
557
- ambient_end = _ambient_after(db, seg_end, tau_est)
648
+ ambient_end = _ambient_after(db, seg_end, tau_est, idle_model)
558
649
  if ambient_end is not None:
559
650
  # Bracketed: de-trend the samples against the linear ambient
560
651
  # ramp across the load window and refit. With ambient
@@ -883,7 +974,9 @@ def _recent_steady_ambient(recent: list[dict], params: ThermalParams) -> float |
883
974
 
884
975
  def predict(db: Database, now: float, params: ThermalParams) -> dict:
885
976
  """Forecast alert-40 for the current state (live session or idle)."""
886
- out: dict = {"model": params.as_dict(), "state": "no_data", "forecast": None}
977
+ idle_model = load_idle_offset(db)
978
+ out: dict = {"model": {**params.as_dict(), "idle_offset": idle_model.as_dict()},
979
+ "state": "no_data", "forecast": None}
887
980
  recent = [
888
981
  row for row in db.vitals_range(now - 900, now, 2000) if row.get("handle_temp_c") is not None
889
982
  ]
@@ -942,7 +1035,7 @@ def predict(db: Database, now: float, params: ThermalParams) -> dict:
942
1035
  if ambient is None:
943
1036
  sid = last.get("session_id")
944
1037
  sess = db.session(int(sid)) if sid else None
945
- ambient = _ambient_before(db, sess["start_ts"]) if sess else None
1038
+ ambient = _ambient_before(db, sess["start_ts"], idle_model) if sess else None
946
1039
  source = "pre_session"
947
1040
  if ambient is None:
948
1041
  ambient = _recent_steady_ambient(recent, params)
@@ -957,6 +1050,10 @@ def predict(db: Database, now: float, params: ThermalParams) -> dict:
957
1050
  t_inf = ambient + params.rise_ref_c * (current / REF_CURRENT_A) ** 2
958
1051
  forecast["basis"] = "model"
959
1052
  forecast["ambient_source"] = source
1053
+ # A model-basis plateau is only as good as its ambient: a sensor
1054
+ # reads air directly; every handle-derived route carries the
1055
+ # idle-offset model's own uncertainty, 1:1 into the plateau.
1056
+ forecast["ambient_se_c"] = 0.3 if source in ("measured", "measured_car") else idle_model.ambient_se_c
960
1057
  # No flooring of t_inf at the current temperature: a steady state
961
1058
  # below the handle is real, not noise — it's what cooling toward a
962
1059
  # lower equilibrium looks like after a current cut or a derate.
@@ -989,10 +1086,11 @@ def predict(db: Database, now: float, params: ThermalParams) -> dict:
989
1086
  ambient, ambient_source = measured
990
1087
  stable = True
991
1088
  else:
992
- ambient = ambient_from_idle_handle(last["handle_temp_c"])
1089
+ ambient = ambient_from_idle_handle(last["handle_temp_c"], idle_model)
993
1090
  ambient_source = "idle_handle"
994
1091
  out["ambient_c"] = round(ambient, 1)
995
1092
  out["ambient_source"] = ambient_source
1093
+ out["ambient_se_c"] = 0.3 if measured is not None else idle_model.ambient_se_c
996
1094
  out["ambient_stable"] = stable
997
1095
  # Hypothetical: a full-rate session started right now.
998
1096
  t_inf = ambient + params.rise_ref_c
@@ -224,22 +224,27 @@ def make_app(db: Database, bus: EventBus, poller: Poller | None) -> web.Applicat
224
224
 
225
225
  # Model parameters change only as new sessions land, so the (SQLite-heavy)
226
226
  # history fit is cached; the live prediction is computed on every call.
227
- thermal_fit: dict = {"params": None, "fits": [], "ts": 0.0}
227
+ thermal_fit: dict = {"params": None, "fits": [], "ts": 0.0, "idle_offset": None}
228
228
 
229
229
  async def api_thermal(request: web.Request) -> web.Response:
230
230
  """The full thermal picture: fitted model, live forecast, per-segment
231
231
  fits, drift verdict, baseline anchor. Also what the BLE amp
232
232
  controller polls every 30 s. ?refit busts the 6 h fit cache."""
233
233
  now = time.time()
234
+ # A newly adopted idle-offset model reinterprets every proxy-tier
235
+ # fit, so the cache is keyed on the stored model too.
236
+ idle_offset = await asyncio.to_thread(db.get_setting, thermal.IDLE_OFFSET_SETTING)
234
237
  if (
235
238
  thermal_fit["params"] is None
236
239
  or now - thermal_fit["ts"] > 6 * 3600
240
+ or thermal_fit["idle_offset"] != idle_offset
237
241
  or "refit" in request.query
238
242
  ):
239
243
  fits = await asyncio.to_thread(thermal.fit_sessions, db, now)
240
244
  thermal_fit["fits"] = fits
241
245
  thermal_fit["params"] = thermal.fit_history(db, now, fits=fits)
242
246
  thermal_fit["ts"] = now
247
+ thermal_fit["idle_offset"] = idle_offset
243
248
  result = await asyncio.to_thread(thermal.predict, db, now, thermal_fit["params"])
244
249
  anchor = await asyncio.to_thread(thermal.baseline_anchor, db)
245
250
  return web.json_response(