wallmonitor 0.4.0__tar.gz → 0.6.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.6.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
@@ -90,9 +91,11 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
90
91
  - **Automatic derate prevention** — an optional daemon caps the vehicle's
91
92
  charge current through a least-privilege BLE pairing when the forecast
92
93
  firms up, and restores it once the risk clears
93
- - **Degradation watch** — ambient-corrected heat-rise trend with confidence
94
- intervals and a verified-baseline anchor, so "getting worse" is a
95
- statistical claim, not a vibe
94
+ - **Degradation watch** — heat rise regressed on time while ambient and
95
+ charge current are held, over windows the charger was not regulating,
96
+ with confidence intervals and a verified-baseline anchor, so "getting
97
+ worse" is a statistical claim about the connector and not about the
98
+ weather
96
99
  - **Actionable notifications, local-only** — browser push and LAN
97
100
  webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
98
101
  - Resilience: seamless restarts, downtime recorded as explicit gap events,
@@ -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
@@ -67,9 +68,11 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
67
68
  - **Automatic derate prevention** — an optional daemon caps the vehicle's
68
69
  charge current through a least-privilege BLE pairing when the forecast
69
70
  firms up, and restores it once the risk clears
70
- - **Degradation watch** — ambient-corrected heat-rise trend with confidence
71
- intervals and a verified-baseline anchor, so "getting worse" is a
72
- statistical claim, not a vibe
71
+ - **Degradation watch** — heat rise regressed on time while ambient and
72
+ charge current are held, over windows the charger was not regulating,
73
+ with confidence intervals and a verified-baseline anchor, so "getting
74
+ worse" is a statistical claim about the connector and not about the
75
+ weather
73
76
  - **Actionable notifications, local-only** — browser push and LAN
74
77
  webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
75
78
  - Resilience: seamless restarts, downtime recorded as explicit gap events,
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.4.0"
3
+ version = "0.6.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.6.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
+ )