wallmonitor 0.3.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.3.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
@@ -59,18 +59,30 @@ On first contact the monitor pins the charger's serial number: if a
59
59
  different unit ever answers at that address, it alarms and pauses recording
60
60
  rather than blending two chargers' histories.
61
61
 
62
+ More than one Wall Connector? Run one instance per charger — `--label` names
63
+ each in the header and notifications, `--peer` links them so the header hops
64
+ between dashboards, and the service installer's `--name` does it all per
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
+
62
67
  All history lands in a single `wallmonitor.db` SQLite file — back up that
63
- 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
64
70
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
65
71
 
66
72
  ## At a glance
67
73
 
74
+ - Zero-config setup — `--discover` finds the charger on your LAN; the
75
+ serial is pinned on first contact so a swapped or second unit can never
76
+ blend into your history
68
77
  - Full-fidelity recording — every response stored with its complete raw JSON
78
+ (optional retention trims old raw blobs so the database stays near-flat)
69
79
  - Live dashboard (SSE) with rolling charts, an active-alert banner, and a
70
80
  live derate-forecast chart: measured handle temperature against the
71
81
  model's projected plateau and the trip threshold, projection drawn
72
82
  forward so the predicted trip intercept is visible on the chart
73
- - Session review: energy, peak/average power, per-phase telemetry, drillable charts
83
+ - Session review: energy, peak/average power, per-phase telemetry, drillable
84
+ charts, and forecast hindsight — what the model predicted at each tick
85
+ against what the handle actually did
74
86
  - Event timeline with range presets, category filters, and paging
75
87
  - Alert decoding and EVSE-state labels, each marked verified vs community-reported
76
88
  - Wi-Fi health history and connectivity events
@@ -86,6 +98,8 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
86
98
  webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
87
99
  - Resilience: seamless restarts, downtime recorded as explicit gap events,
88
100
  sensor-glitch quarantine
101
+ - Several chargers: one labeled instance each, linked by a header switcher;
102
+ per-install thermal models stay separate by construction
89
103
 
90
104
  ## Works out of the box — everything else is additive
91
105
 
@@ -100,7 +114,7 @@ plain LAN webhook, a REST call) rather than being wired into the core.
100
114
 
101
115
  | Page | What's in it |
102
116
  |---|---|
103
- | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install, tests |
117
+ | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, finding your charger, device identity, multiple chargers, systemd service install |
104
118
  | [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
105
119
  | [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
106
120
  | [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
@@ -36,18 +36,30 @@ On first contact the monitor pins the charger's serial number: if a
36
36
  different unit ever answers at that address, it alarms and pauses recording
37
37
  rather than blending two chargers' histories.
38
38
 
39
+ More than one Wall Connector? Run one instance per charger — `--label` names
40
+ each in the header and notifications, `--peer` links them so the header hops
41
+ between dashboards, and the service installer's `--name` does it all per
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
+
39
44
  All history lands in a single `wallmonitor.db` SQLite file — back up that
40
- 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
41
47
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
42
48
 
43
49
  ## At a glance
44
50
 
51
+ - Zero-config setup — `--discover` finds the charger on your LAN; the
52
+ serial is pinned on first contact so a swapped or second unit can never
53
+ blend into your history
45
54
  - Full-fidelity recording — every response stored with its complete raw JSON
55
+ (optional retention trims old raw blobs so the database stays near-flat)
46
56
  - Live dashboard (SSE) with rolling charts, an active-alert banner, and a
47
57
  live derate-forecast chart: measured handle temperature against the
48
58
  model's projected plateau and the trip threshold, projection drawn
49
59
  forward so the predicted trip intercept is visible on the chart
50
- - Session review: energy, peak/average power, per-phase telemetry, drillable charts
60
+ - Session review: energy, peak/average power, per-phase telemetry, drillable
61
+ charts, and forecast hindsight — what the model predicted at each tick
62
+ against what the handle actually did
51
63
  - Event timeline with range presets, category filters, and paging
52
64
  - Alert decoding and EVSE-state labels, each marked verified vs community-reported
53
65
  - Wi-Fi health history and connectivity events
@@ -63,6 +75,8 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
63
75
  webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
64
76
  - Resilience: seamless restarts, downtime recorded as explicit gap events,
65
77
  sensor-glitch quarantine
78
+ - Several chargers: one labeled instance each, linked by a header switcher;
79
+ per-install thermal models stay separate by construction
66
80
 
67
81
  ## Works out of the box — everything else is additive
68
82
 
@@ -77,7 +91,7 @@ plain LAN webhook, a REST call) rather than being wired into the core.
77
91
 
78
92
  | Page | What's in it |
79
93
  |---|---|
80
- | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install, tests |
94
+ | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, finding your charger, device identity, multiple chargers, systemd service install |
81
95
  | [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
82
96
  | [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
83
97
  | [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.3.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.3.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,10 +30,17 @@ from .web import make_app
30
30
  log = logging.getLogger("wallmonitor")
31
31
 
32
32
 
33
- async def _backfill(db: Database) -> None:
34
- """One-time, in the background: fill diagnostics columns for rows
35
- recorded before those columns existed. Chunked, so live polling only
36
- ever waits a moment; a settings flag makes later startups a no-op."""
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."""
40
+ import time as _time
41
+
42
+ from . import calibration, thermal
43
+
37
44
  def report(done: int, total: int) -> None:
38
45
  if done % 200_000 < 10_000 or done >= total:
39
46
  log.info("diagnostics backfill: %d / %d rows", done, total)
@@ -41,6 +48,28 @@ async def _backfill(db: Database) -> None:
41
48
  touched = await asyncio.to_thread(db.backfill_diag_columns, 10_000, report)
42
49
  if touched:
43
50
  log.info("diagnostics backfill complete: %d rows", touched)
51
+ while True:
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))
72
+ await asyncio.sleep(24 * 3600.0)
44
73
 
45
74
 
46
75
  async def run(argv: list[str] | None = None) -> None:
@@ -52,6 +81,25 @@ async def run(argv: list[str] | None = None) -> None:
52
81
  cfg = parse_args(argv)
53
82
  if cfg.discover is not None:
54
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)
94
+ if cfg.compact:
95
+ db = Database(cfg.db_path)
96
+ try:
97
+ before, after = db.vacuum()
98
+ finally:
99
+ db.close()
100
+ print(f"{cfg.db_path}: {before / 1e6:.1f} MB -> {after / 1e6:.1f} MB "
101
+ f"({(before - after) / 1e6:.1f} MB reclaimed)")
102
+ raise SystemExit(0)
55
103
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
56
104
 
57
105
  sim_runner = None
@@ -65,7 +113,7 @@ async def run(argv: list[str] | None = None) -> None:
65
113
  client = aiohttp.ClientSession()
66
114
  poller = Poller(cfg, db, bus, client)
67
115
  await poller.start()
68
- backfill = asyncio.create_task(_backfill(db), name="wallmonitor-backfill")
116
+ backfill = asyncio.create_task(_maintenance(db, cfg, poller), name="wallmonitor-maintenance")
69
117
 
70
118
  app = make_app(db, bus, poller)
71
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
+ )