wallmonitor 0.2.0__tar.gz → 0.4.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.
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/PKG-INFO +24 -7
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/README.md +23 -6
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/pyproject.toml +1 -1
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/pyproject.toml.orig +1 -1
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/__main__.py +40 -0
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/config.py +85 -3
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/db.py +174 -14
- wallmonitor-0.4.0/wallmonitor/discover.py +197 -0
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/poller.py +115 -18
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/simulator.py +8 -4
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/static/app.js +117 -21
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/static/index.html +2 -0
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/static/style.css +5 -0
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/thermal.py +131 -30
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/web.py +18 -1
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/__init__.py +0 -0
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/alert_codes.json +0 -0
- {wallmonitor-0.2.0 → wallmonitor-0.4.0}/wallmonitor/static/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: wallmonitor
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.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
|
|
@@ -46,27 +46,42 @@ uvx wallmonitor --demo
|
|
|
46
46
|
|
|
47
47
|
Then open <http://127.0.0.1:8480>.
|
|
48
48
|
|
|
49
|
-
Against your real Wall Connector
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
American split-phase install):
|
|
49
|
+
Against your real Wall Connector — let the tool find it on your LAN (a
|
|
50
|
+
polite sweep of your own subnet; nothing leaves the network), then run with
|
|
51
|
+
the address it prints (add `--split-phase` on a North American install):
|
|
53
52
|
|
|
54
53
|
```bash
|
|
54
|
+
uvx wallmonitor --discover
|
|
55
55
|
uvx wallmonitor --host 192.168.1.50 --split-phase
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
+
On first contact the monitor pins the charger's serial number: if a
|
|
59
|
+
different unit ever answers at that address, it alarms and pauses recording
|
|
60
|
+
rather than blending two chargers' histories.
|
|
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
|
+
|
|
58
67
|
All history lands in a single `wallmonitor.db` SQLite file — back up that
|
|
59
68
|
one file and you have everything. For every option, and for running it as a
|
|
60
69
|
systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
|
|
61
70
|
|
|
62
71
|
## At a glance
|
|
63
72
|
|
|
73
|
+
- Zero-config setup — `--discover` finds the charger on your LAN; the
|
|
74
|
+
serial is pinned on first contact so a swapped or second unit can never
|
|
75
|
+
blend into your history
|
|
64
76
|
- Full-fidelity recording — every response stored with its complete raw JSON
|
|
77
|
+
(optional retention trims old raw blobs so the database stays near-flat)
|
|
65
78
|
- Live dashboard (SSE) with rolling charts, an active-alert banner, and a
|
|
66
79
|
live derate-forecast chart: measured handle temperature against the
|
|
67
80
|
model's projected plateau and the trip threshold, projection drawn
|
|
68
81
|
forward so the predicted trip intercept is visible on the chart
|
|
69
|
-
- Session review: energy, peak/average power, per-phase telemetry, drillable
|
|
82
|
+
- Session review: energy, peak/average power, per-phase telemetry, drillable
|
|
83
|
+
charts, and forecast hindsight — what the model predicted at each tick
|
|
84
|
+
against what the handle actually did
|
|
70
85
|
- Event timeline with range presets, category filters, and paging
|
|
71
86
|
- Alert decoding and EVSE-state labels, each marked verified vs community-reported
|
|
72
87
|
- Wi-Fi health history and connectivity events
|
|
@@ -82,6 +97,8 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
|
|
|
82
97
|
webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
|
|
83
98
|
- Resilience: seamless restarts, downtime recorded as explicit gap events,
|
|
84
99
|
sensor-glitch quarantine
|
|
100
|
+
- Several chargers: one labeled instance each, linked by a header switcher;
|
|
101
|
+
per-install thermal models stay separate by construction
|
|
85
102
|
|
|
86
103
|
## Works out of the box — everything else is additive
|
|
87
104
|
|
|
@@ -96,7 +113,7 @@ plain LAN webhook, a REST call) rather than being wired into the core.
|
|
|
96
113
|
|
|
97
114
|
| Page | What's in it |
|
|
98
115
|
|---|---|
|
|
99
|
-
| [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install
|
|
116
|
+
| [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, finding your charger, device identity, multiple chargers, systemd service install |
|
|
100
117
|
| [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
|
|
101
118
|
| [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
|
|
102
119
|
| [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
|
|
@@ -23,27 +23,42 @@ uvx wallmonitor --demo
|
|
|
23
23
|
|
|
24
24
|
Then open <http://127.0.0.1:8480>.
|
|
25
25
|
|
|
26
|
-
Against your real Wall Connector
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
American split-phase install):
|
|
26
|
+
Against your real Wall Connector — let the tool find it on your LAN (a
|
|
27
|
+
polite sweep of your own subnet; nothing leaves the network), then run with
|
|
28
|
+
the address it prints (add `--split-phase` on a North American install):
|
|
30
29
|
|
|
31
30
|
```bash
|
|
31
|
+
uvx wallmonitor --discover
|
|
32
32
|
uvx wallmonitor --host 192.168.1.50 --split-phase
|
|
33
33
|
```
|
|
34
34
|
|
|
35
|
+
On first contact the monitor pins the charger's serial number: if a
|
|
36
|
+
different unit ever answers at that address, it alarms and pauses recording
|
|
37
|
+
rather than blending two chargers' histories.
|
|
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
|
+
|
|
35
44
|
All history lands in a single `wallmonitor.db` SQLite file — back up that
|
|
36
45
|
one file and you have everything. For every option, and for running it as a
|
|
37
46
|
systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
|
|
38
47
|
|
|
39
48
|
## At a glance
|
|
40
49
|
|
|
50
|
+
- Zero-config setup — `--discover` finds the charger on your LAN; the
|
|
51
|
+
serial is pinned on first contact so a swapped or second unit can never
|
|
52
|
+
blend into your history
|
|
41
53
|
- Full-fidelity recording — every response stored with its complete raw JSON
|
|
54
|
+
(optional retention trims old raw blobs so the database stays near-flat)
|
|
42
55
|
- Live dashboard (SSE) with rolling charts, an active-alert banner, and a
|
|
43
56
|
live derate-forecast chart: measured handle temperature against the
|
|
44
57
|
model's projected plateau and the trip threshold, projection drawn
|
|
45
58
|
forward so the predicted trip intercept is visible on the chart
|
|
46
|
-
- Session review: energy, peak/average power, per-phase telemetry, drillable
|
|
59
|
+
- Session review: energy, peak/average power, per-phase telemetry, drillable
|
|
60
|
+
charts, and forecast hindsight — what the model predicted at each tick
|
|
61
|
+
against what the handle actually did
|
|
47
62
|
- Event timeline with range presets, category filters, and paging
|
|
48
63
|
- Alert decoding and EVSE-state labels, each marked verified vs community-reported
|
|
49
64
|
- Wi-Fi health history and connectivity events
|
|
@@ -59,6 +74,8 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
|
|
|
59
74
|
webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
|
|
60
75
|
- Resilience: seamless restarts, downtime recorded as explicit gap events,
|
|
61
76
|
sensor-glitch quarantine
|
|
77
|
+
- Several chargers: one labeled instance each, linked by a header switcher;
|
|
78
|
+
per-install thermal models stay separate by construction
|
|
62
79
|
|
|
63
80
|
## Works out of the box — everything else is additive
|
|
64
81
|
|
|
@@ -73,7 +90,7 @@ plain LAN webhook, a REST call) rather than being wired into the core.
|
|
|
73
90
|
|
|
74
91
|
| Page | What's in it |
|
|
75
92
|
|---|---|
|
|
76
|
-
| [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install
|
|
93
|
+
| [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, finding your charger, device identity, multiple chargers, systemd service install |
|
|
77
94
|
| [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
|
|
78
95
|
| [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
|
|
79
96
|
| [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
|
|
@@ -22,6 +22,7 @@ from aiohttp import web
|
|
|
22
22
|
|
|
23
23
|
from .config import parse_args
|
|
24
24
|
from .db import Database
|
|
25
|
+
from .discover import run_discovery
|
|
25
26
|
from .poller import EventBus, Poller
|
|
26
27
|
from .simulator import start_simulator
|
|
27
28
|
from .web import make_app
|
|
@@ -29,6 +30,32 @@ from .web import make_app
|
|
|
29
30
|
log = logging.getLogger("wallmonitor")
|
|
30
31
|
|
|
31
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."""
|
|
38
|
+
import time as _time
|
|
39
|
+
|
|
40
|
+
def report(done: int, total: int) -> None:
|
|
41
|
+
if done % 200_000 < 10_000 or done >= total:
|
|
42
|
+
log.info("diagnostics backfill: %d / %d rows", done, total)
|
|
43
|
+
|
|
44
|
+
touched = await asyncio.to_thread(db.backfill_diag_columns, 10_000, report)
|
|
45
|
+
if touched:
|
|
46
|
+
log.info("diagnostics backfill complete: %d rows", touched)
|
|
47
|
+
if not cfg.retain_raw_days:
|
|
48
|
+
return
|
|
49
|
+
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))
|
|
56
|
+
await asyncio.sleep(24 * 3600.0)
|
|
57
|
+
|
|
58
|
+
|
|
32
59
|
async def run(argv: list[str] | None = None) -> None:
|
|
33
60
|
"""Construct every component, serve until cancelled, unwind in order.
|
|
34
61
|
|
|
@@ -36,6 +63,17 @@ async def run(argv: list[str] | None = None) -> None:
|
|
|
36
63
|
then the web runner (readers), then the shared HTTP client, and close
|
|
37
64
|
the database last so nothing can touch a closed connection."""
|
|
38
65
|
cfg = parse_args(argv)
|
|
66
|
+
if cfg.discover is not None:
|
|
67
|
+
raise SystemExit(await run_discovery(cfg.discover, split_phase_hint=cfg.split_phase))
|
|
68
|
+
if cfg.compact:
|
|
69
|
+
db = Database(cfg.db_path)
|
|
70
|
+
try:
|
|
71
|
+
before, after = db.vacuum()
|
|
72
|
+
finally:
|
|
73
|
+
db.close()
|
|
74
|
+
print(f"{cfg.db_path}: {before / 1e6:.1f} MB -> {after / 1e6:.1f} MB "
|
|
75
|
+
f"({(before - after) / 1e6:.1f} MB reclaimed)")
|
|
76
|
+
raise SystemExit(0)
|
|
39
77
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
|
40
78
|
|
|
41
79
|
sim_runner = None
|
|
@@ -49,6 +87,7 @@ async def run(argv: list[str] | None = None) -> None:
|
|
|
49
87
|
client = aiohttp.ClientSession()
|
|
50
88
|
poller = Poller(cfg, db, bus, client)
|
|
51
89
|
await poller.start()
|
|
90
|
+
backfill = asyncio.create_task(_maintenance(db, cfg), name="wallmonitor-maintenance")
|
|
52
91
|
|
|
53
92
|
app = make_app(db, bus, poller)
|
|
54
93
|
runner = web.AppRunner(app)
|
|
@@ -62,6 +101,7 @@ async def run(argv: list[str] | None = None) -> None:
|
|
|
62
101
|
except (KeyboardInterrupt, asyncio.CancelledError):
|
|
63
102
|
pass
|
|
64
103
|
finally:
|
|
104
|
+
backfill.cancel()
|
|
65
105
|
await poller.stop()
|
|
66
106
|
await runner.cleanup()
|
|
67
107
|
if sim_runner:
|
|
@@ -11,6 +11,7 @@ off exponentially instead of hammering a struggling device.
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
13
|
import argparse
|
|
14
|
+
import re
|
|
14
15
|
import os
|
|
15
16
|
from dataclasses import dataclass
|
|
16
17
|
|
|
@@ -29,6 +30,21 @@ class Config:
|
|
|
29
30
|
db_path: str = "wallmonitor.db"
|
|
30
31
|
demo: bool = False
|
|
31
32
|
split_phase: bool = False
|
|
33
|
+
# Human name for this charger, shown in the UI header, tab title and
|
|
34
|
+
# notifications so several instances side by side stay attributable.
|
|
35
|
+
label: str = ""
|
|
36
|
+
# Optional retention: rows older than this many days keep every extracted
|
|
37
|
+
# column forever but have their raw JSON blob trimmed to "". 0 = never
|
|
38
|
+
# trim (the default — full re-interpretability retained indefinitely).
|
|
39
|
+
retain_raw_days: float = 0.0
|
|
40
|
+
# One-shot: VACUUM the database to reclaim trimmed space, print sizes, exit.
|
|
41
|
+
compact: bool = False
|
|
42
|
+
# Sibling instances watching other chargers, as (label, url) pairs;
|
|
43
|
+
# rendered as a switcher in the header so one browser hops between them.
|
|
44
|
+
peers: tuple[tuple[str, str], ...] = ()
|
|
45
|
+
# --discover [RANGE]: sweep the LAN for chargers and exit. None = not
|
|
46
|
+
# requested; "auto" = the host's own subnet; otherwise a CIDR.
|
|
47
|
+
discover: str | None = None
|
|
32
48
|
# Optional LAN webhook: actionable warnings are POSTed here.
|
|
33
49
|
# Local-only by design — point it at something on your own network
|
|
34
50
|
# (Home Assistant, a self-hosted ntfy, node-RED); leave empty to disable.
|
|
@@ -78,11 +94,21 @@ def _env(name: str, default):
|
|
|
78
94
|
return val
|
|
79
95
|
|
|
80
96
|
|
|
97
|
+
def parse_peer(spec: str) -> tuple[str, str]:
|
|
98
|
+
"""'Label=http://host:port' → (label, url). The URL must be absolute
|
|
99
|
+
http(s); the label is whatever the user wants to see on the switch."""
|
|
100
|
+
label, sep, url = spec.partition("=")
|
|
101
|
+
label, url = label.strip(), url.strip()
|
|
102
|
+
if not sep or not label or not re.match(r"^https?://[^\s/]+", url):
|
|
103
|
+
raise ValueError(f"--peer expects LABEL=http://host:port, got {spec!r}")
|
|
104
|
+
return label, url.rstrip("/")
|
|
105
|
+
|
|
106
|
+
|
|
81
107
|
def parse_args(argv: list[str] | None = None) -> Config:
|
|
82
108
|
"""Build the Config: CLI flag beats WM_* env var beats hardcoded default.
|
|
83
109
|
|
|
84
110
|
One validation rule: --host is required unless --demo runs the built-in
|
|
85
|
-
simulator instead of real hardware. Note the boolean flags can only
|
|
111
|
+
simulator instead of real hardware, or --discover is asked to find it. Note the boolean flags can only
|
|
86
112
|
assert True — an env-var-enabled --demo/--split-phase has no --no-*
|
|
87
113
|
override; unset the variable instead."""
|
|
88
114
|
parser = argparse.ArgumentParser(
|
|
@@ -123,6 +149,43 @@ def parse_args(argv: list[str] | None = None) -> Config:
|
|
|
123
149
|
)
|
|
124
150
|
parser.add_argument("--wifi-interval", type=float, default=_env("WM_WIFI_INTERVAL", 30.0))
|
|
125
151
|
parser.add_argument("--lifetime-interval", type=float, default=_env("WM_LIFETIME_INTERVAL", 60.0))
|
|
152
|
+
parser.add_argument(
|
|
153
|
+
"--label",
|
|
154
|
+
default=_env("WM_LABEL", ""),
|
|
155
|
+
help="Name for this charger, shown in the UI and notifications — useful when "
|
|
156
|
+
"running one instance per Wall Connector (env: WM_LABEL)",
|
|
157
|
+
)
|
|
158
|
+
parser.add_argument(
|
|
159
|
+
"--retain-raw-days",
|
|
160
|
+
type=float,
|
|
161
|
+
default=_env("WM_RETAIN_RAW_DAYS", 0.0),
|
|
162
|
+
help="Trim the raw JSON blob from samples older than this many days (columns are "
|
|
163
|
+
"kept forever; 0 disables — the default). Minimum 7. (env: WM_RETAIN_RAW_DAYS)",
|
|
164
|
+
)
|
|
165
|
+
parser.add_argument(
|
|
166
|
+
"--compact",
|
|
167
|
+
action="store_true",
|
|
168
|
+
default=False,
|
|
169
|
+
help="VACUUM the database to reclaim space freed by retention, print sizes, and exit. "
|
|
170
|
+
"Run it while the monitor service is stopped.",
|
|
171
|
+
)
|
|
172
|
+
parser.add_argument(
|
|
173
|
+
"--peer",
|
|
174
|
+
action="append",
|
|
175
|
+
default=None,
|
|
176
|
+
metavar="LABEL=URL",
|
|
177
|
+
help="Another wallmonitor instance to link from the header, e.g. "
|
|
178
|
+
"'Garage right=http://192.168.1.10:8481'; repeatable (env: WM_PEERS, comma-separated)",
|
|
179
|
+
)
|
|
180
|
+
parser.add_argument(
|
|
181
|
+
"--discover",
|
|
182
|
+
nargs="?",
|
|
183
|
+
const="auto",
|
|
184
|
+
default=None,
|
|
185
|
+
metavar="RANGE",
|
|
186
|
+
help="Find Wall Connectors on the LAN and exit. Sweeps this host's own subnet, "
|
|
187
|
+
"or the private CIDR given (e.g. 192.168.2.0/24). Never leaves the LAN.",
|
|
188
|
+
)
|
|
126
189
|
parser.add_argument(
|
|
127
190
|
"--split-phase",
|
|
128
191
|
action="store_true",
|
|
@@ -144,8 +207,22 @@ def parse_args(argv: list[str] | None = None) -> Config:
|
|
|
144
207
|
)
|
|
145
208
|
args = parser.parse_args(argv)
|
|
146
209
|
|
|
147
|
-
|
|
148
|
-
|
|
210
|
+
peer_specs = args.peer if args.peer is not None else [
|
|
211
|
+
part for part in os.getenv("WM_PEERS", "").split(",") if part.strip()
|
|
212
|
+
]
|
|
213
|
+
try:
|
|
214
|
+
peers = tuple(parse_peer(spec) for spec in peer_specs)
|
|
215
|
+
except ValueError as ex:
|
|
216
|
+
parser.error(str(ex))
|
|
217
|
+
|
|
218
|
+
if args.retain_raw_days and args.retain_raw_days < 7:
|
|
219
|
+
parser.error("--retain-raw-days must be at least 7 (or 0 to disable)")
|
|
220
|
+
|
|
221
|
+
if not args.demo and not args.host and args.discover is None and not args.compact:
|
|
222
|
+
parser.error(
|
|
223
|
+
"--host (or WM_WC_HOST) is required — run `wallmonitor --discover` to find "
|
|
224
|
+
"your Wall Connector's address, or --demo for the built-in simulator"
|
|
225
|
+
)
|
|
149
226
|
|
|
150
227
|
return Config(
|
|
151
228
|
host=args.host,
|
|
@@ -154,6 +231,11 @@ def parse_args(argv: list[str] | None = None) -> Config:
|
|
|
154
231
|
db_path=args.db_path,
|
|
155
232
|
demo=bool(args.demo),
|
|
156
233
|
split_phase=bool(args.split_phase),
|
|
234
|
+
label=args.label,
|
|
235
|
+
retain_raw_days=float(args.retain_raw_days),
|
|
236
|
+
compact=bool(args.compact),
|
|
237
|
+
peers=peers,
|
|
238
|
+
discover=args.discover,
|
|
157
239
|
notify_url=args.notify_url,
|
|
158
240
|
notify_format=args.notify_format,
|
|
159
241
|
vitals_interval_active=args.vitals_active,
|
|
@@ -180,8 +180,34 @@ VITALS_COLUMNS = {
|
|
|
180
180
|
"evse_state": "evse_state",
|
|
181
181
|
"config_status": "config_status",
|
|
182
182
|
"uptime_s": "uptime_s",
|
|
183
|
+
# J1772 handshake / relay diagnostics. Added as columns later than the
|
|
184
|
+
# rest (they used to be read out of the raw JSON on every query, which
|
|
185
|
+
# made long sessions slow to chart); rows from before the column existed
|
|
186
|
+
# are backfilled by backfill_diag_columns and served via COALESCE until
|
|
187
|
+
# then.
|
|
188
|
+
"pilot_high_v": "pilot_high_v",
|
|
189
|
+
"pilot_low_v": "pilot_low_v",
|
|
190
|
+
"prox_v": "prox_v",
|
|
191
|
+
"relay_k1_v": "relay_k1_v",
|
|
192
|
+
"relay_k2_v": "relay_k2_v",
|
|
183
193
|
}
|
|
184
194
|
|
|
195
|
+
# Columns added after the table was first shipped: ALTER TABLE'd in on
|
|
196
|
+
# open when missing (CREATE TABLE IF NOT EXISTS can't add them).
|
|
197
|
+
VITALS_LATER_COLUMNS = ("pilot_high_v", "pilot_low_v", "prox_v", "relay_k1_v", "relay_k2_v")
|
|
198
|
+
DIAG_BACKFILL_SETTING = "diag_backfill_done"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _round_rows(rows: list[dict], digits: int = 2) -> list[dict]:
|
|
202
|
+
"""Trim float noise before JSON: bucket averages come out with 15
|
|
203
|
+
digits, which roughly doubles the payload for no visible difference
|
|
204
|
+
on a chart. Timestamps keep full precision."""
|
|
205
|
+
for row in rows:
|
|
206
|
+
for key, value in row.items():
|
|
207
|
+
if key != "ts" and isinstance(value, float):
|
|
208
|
+
row[key] = round(value, digits)
|
|
209
|
+
return rows
|
|
210
|
+
|
|
185
211
|
|
|
186
212
|
class Database:
|
|
187
213
|
"""Thread-safe wrapper around a single SQLite connection."""
|
|
@@ -195,6 +221,7 @@ class Database:
|
|
|
195
221
|
telemetry). The schema is pure CREATE IF NOT EXISTS, re-run on
|
|
196
222
|
every startup: "migrations" are additive statements appended here.
|
|
197
223
|
"""
|
|
224
|
+
self.path = path
|
|
198
225
|
self._conn = sqlite3.connect(path, check_same_thread=False)
|
|
199
226
|
self._conn.row_factory = sqlite3.Row
|
|
200
227
|
self._lock = threading.Lock()
|
|
@@ -204,6 +231,126 @@ class Database:
|
|
|
204
231
|
)
|
|
205
232
|
self._conn.executescript(SCHEMA)
|
|
206
233
|
self._conn.commit()
|
|
234
|
+
self._migrate()
|
|
235
|
+
# Once every row carries the diagnostics columns, range queries stop
|
|
236
|
+
# mentioning raw entirely — merely referencing the blob column makes
|
|
237
|
+
# SQLite read it for every row, which is most of what made long
|
|
238
|
+
# sessions slow to chart.
|
|
239
|
+
self._diag_backfilled = self.get_setting(DIAG_BACKFILL_SETTING) == "1"
|
|
240
|
+
|
|
241
|
+
def _migrate(self) -> None:
|
|
242
|
+
"""Additive column migrations (caller holds the lock)."""
|
|
243
|
+
have = {row[1] for row in self._conn.execute("PRAGMA table_info(vitals_samples)")}
|
|
244
|
+
for col in VITALS_LATER_COLUMNS:
|
|
245
|
+
if col not in have:
|
|
246
|
+
self._conn.execute(f"ALTER TABLE vitals_samples ADD COLUMN {col} REAL")
|
|
247
|
+
self._conn.commit()
|
|
248
|
+
|
|
249
|
+
# Tables whose raw JSON blob is trimmed by the retention policy. The
|
|
250
|
+
# extracted columns stay forever; forecast_samples and version_info are
|
|
251
|
+
# exempt (tiny, and their raw payloads carry fields with no column).
|
|
252
|
+
RAW_TRIM_TABLES = ("vitals_samples", "wifi_samples", "lifetime_samples", "ambient_samples")
|
|
253
|
+
|
|
254
|
+
def trim_raw(self, cutoff_ts: float, chunk: int = 10_000) -> dict[str, int]:
|
|
255
|
+
"""Retention: blank the raw JSON on samples older than cutoff_ts.
|
|
256
|
+
|
|
257
|
+
Columns are untouched, so charts, fits and the degradation watch see
|
|
258
|
+
exactly the same history — what is given up is re-interpreting old
|
|
259
|
+
rows for fields that were never extracted. Vitals are only trimmed
|
|
260
|
+
once the diagnostics backfill has finished (its json_extract source
|
|
261
|
+
is the raw blob). A per-table timestamp cursor in settings makes the
|
|
262
|
+
daily run scan only rows that newly aged past the cutoff, and the
|
|
263
|
+
chunked updates hold the write lock briefly each. Freed pages are
|
|
264
|
+
reused by new inserts, so the file stops growing; a one-shot VACUUM
|
|
265
|
+
(--compact) reclaims the space for the filesystem.
|
|
266
|
+
"""
|
|
267
|
+
counts: dict[str, int] = {}
|
|
268
|
+
for table in self.RAW_TRIM_TABLES:
|
|
269
|
+
if table == "vitals_samples" and self.get_setting(DIAG_BACKFILL_SETTING) != "1":
|
|
270
|
+
continue
|
|
271
|
+
cursor_key = f"raw_trim_ts:{table}"
|
|
272
|
+
start_ts = float(self.get_setting(cursor_key) or 0.0)
|
|
273
|
+
trimmed = 0
|
|
274
|
+
while True:
|
|
275
|
+
with self._lock:
|
|
276
|
+
rows = self._conn.execute(
|
|
277
|
+
f"SELECT id, ts FROM {table} WHERE ts >= ? AND ts < ? "
|
|
278
|
+
"ORDER BY ts LIMIT ?",
|
|
279
|
+
(start_ts, cutoff_ts, chunk),
|
|
280
|
+
).fetchall()
|
|
281
|
+
if not rows:
|
|
282
|
+
break
|
|
283
|
+
ids = [row[0] for row in rows]
|
|
284
|
+
placeholders = ",".join("?" for _ in ids)
|
|
285
|
+
cur = self._execute(
|
|
286
|
+
f"UPDATE {table} SET raw = '' WHERE id IN ({placeholders}) AND raw != ''",
|
|
287
|
+
tuple(ids),
|
|
288
|
+
)
|
|
289
|
+
trimmed += cur.rowcount
|
|
290
|
+
start_ts = rows[-1][1]
|
|
291
|
+
self._execute(
|
|
292
|
+
"INSERT INTO settings(key, value) VALUES (?, ?) "
|
|
293
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
294
|
+
(cursor_key, repr(start_ts)),
|
|
295
|
+
)
|
|
296
|
+
if len(rows) < chunk:
|
|
297
|
+
break
|
|
298
|
+
counts[table] = trimmed
|
|
299
|
+
return counts
|
|
300
|
+
|
|
301
|
+
def vacuum(self) -> tuple[int, int]:
|
|
302
|
+
"""VACUUM, returning (bytes_before, bytes_after). Exclusive — run
|
|
303
|
+
while nothing else is writing (the --compact command exists so this
|
|
304
|
+
never happens implicitly under a live poller)."""
|
|
305
|
+
import os
|
|
306
|
+
|
|
307
|
+
with self._lock:
|
|
308
|
+
self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
309
|
+
before = os.path.getsize(self.path)
|
|
310
|
+
with self._lock:
|
|
311
|
+
self._conn.execute("VACUUM")
|
|
312
|
+
self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
313
|
+
after = os.path.getsize(self.path)
|
|
314
|
+
return before, after
|
|
315
|
+
|
|
316
|
+
def backfill_diag_columns(self, chunk: int = 10_000, progress=None) -> int:
|
|
317
|
+
"""Fill the diagnostics columns for rows recorded before they
|
|
318
|
+
existed, from each row's raw JSON, in id-ordered chunks so the
|
|
319
|
+
poller's inserts only ever wait one chunk. Idempotent and
|
|
320
|
+
resumable; returns rows touched. Runs once — a settings flag
|
|
321
|
+
records completion."""
|
|
322
|
+
if self.get_setting(DIAG_BACKFILL_SETTING):
|
|
323
|
+
return 0
|
|
324
|
+
touched = 0
|
|
325
|
+
last = int(self.get_setting("diag_backfill_id") or 0)
|
|
326
|
+
while True:
|
|
327
|
+
with self._lock:
|
|
328
|
+
top = self._conn.execute("SELECT MAX(id) FROM vitals_samples").fetchone()[0] or 0
|
|
329
|
+
if last >= top:
|
|
330
|
+
self._execute("INSERT INTO settings(key, value) VALUES (?, '1') "
|
|
331
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
332
|
+
(DIAG_BACKFILL_SETTING,))
|
|
333
|
+
self._execute("DELETE FROM settings WHERE key = 'diag_backfill_id'")
|
|
334
|
+
self._diag_backfilled = True
|
|
335
|
+
return touched
|
|
336
|
+
upto = min(top, last + chunk)
|
|
337
|
+
cur = self._execute(
|
|
338
|
+
"""UPDATE vitals_samples SET
|
|
339
|
+
pilot_high_v = json_extract(raw, '$.pilot_high_v'),
|
|
340
|
+
pilot_low_v = json_extract(raw, '$.pilot_low_v'),
|
|
341
|
+
prox_v = json_extract(raw, '$.prox_v'),
|
|
342
|
+
relay_k1_v = COALESCE(json_extract(raw, '$.relay_k1_v'),
|
|
343
|
+
json_extract(raw, '$.relay_coil_v')),
|
|
344
|
+
relay_k2_v = json_extract(raw, '$.relay_k2_v')
|
|
345
|
+
WHERE id > ? AND id <= ? AND prox_v IS NULL AND raw != ''""",
|
|
346
|
+
(last, upto),
|
|
347
|
+
)
|
|
348
|
+
touched += cur.rowcount
|
|
349
|
+
last = upto
|
|
350
|
+
self._execute("INSERT INTO settings(key, value) VALUES ('diag_backfill_id', ?) "
|
|
351
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value", (str(last),))
|
|
352
|
+
if progress:
|
|
353
|
+
progress(last, top)
|
|
207
354
|
|
|
208
355
|
def close(self) -> None:
|
|
209
356
|
"""Close the shared connection. Owner-only: called once at process
|
|
@@ -229,6 +376,8 @@ class Database:
|
|
|
229
376
|
the complete raw JSON. Returns the new row id (the SSE frame carries
|
|
230
377
|
it so clients can de-duplicate)."""
|
|
231
378
|
cols = {col: raw.get(json_key) for col, json_key in VITALS_COLUMNS.items()}
|
|
379
|
+
if cols["relay_k1_v"] is None:
|
|
380
|
+
cols["relay_k1_v"] = raw.get("relay_coil_v") # older firmware's name for it
|
|
232
381
|
with self._lock:
|
|
233
382
|
cur = self._execute(
|
|
234
383
|
f"""INSERT INTO vitals_samples
|
|
@@ -530,13 +679,28 @@ class Database:
|
|
|
530
679
|
)
|
|
531
680
|
# Handshake diagnostics live only in the raw JSON; json_extract makes
|
|
532
681
|
# them chartable retroactively for every sample ever recorded.
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
682
|
+
# Diagnostics are columns now; the json_extract fallback only runs
|
|
683
|
+
# for rows the one-time backfill hasn't reached (COALESCE stops at
|
|
684
|
+
# the first non-NULL, so backfilled rows never touch the JSON).
|
|
685
|
+
if self._diag_backfilled:
|
|
686
|
+
d = {col: col for col in VITALS_LATER_COLUMNS}
|
|
687
|
+
else:
|
|
688
|
+
# CASE-guarded: a retention-trimmed row has raw = '' and
|
|
689
|
+
# json_extract('') is a hard error, not NULL — and SQLite does
|
|
690
|
+
# not promise to short-circuit COALESCE past it even when the
|
|
691
|
+
# column is populated.
|
|
692
|
+
j = "CASE WHEN raw = '' THEN NULL ELSE json_extract(raw, '{key}') END"
|
|
693
|
+
d = {
|
|
694
|
+
"pilot_high_v": f"COALESCE(pilot_high_v, {j.format(key='$.pilot_high_v')})",
|
|
695
|
+
"pilot_low_v": f"COALESCE(pilot_low_v, {j.format(key='$.pilot_low_v')})",
|
|
696
|
+
"prox_v": f"COALESCE(prox_v, {j.format(key='$.prox_v')})",
|
|
697
|
+
"relay_k1_v": f"COALESCE(relay_k1_v, {j.format(key='$.relay_k1_v')}, "
|
|
698
|
+
f"{j.format(key='$.relay_coil_v')})",
|
|
699
|
+
"relay_k2_v": f"COALESCE(relay_k2_v, {j.format(key='$.relay_k2_v')})",
|
|
700
|
+
}
|
|
701
|
+
diag = ", ".join(f"{expr} AS {col}" for col, expr in d.items())
|
|
538
702
|
if sample_count <= max_points:
|
|
539
|
-
return self._rows(
|
|
703
|
+
return _round_rows(self._rows(
|
|
540
704
|
f"""SELECT ts, total_power_w, vehicle_current_a, current_a_a, current_b_a, current_c_a,
|
|
541
705
|
voltage_a_v, voltage_b_v, voltage_c_v, grid_v, grid_hz,
|
|
542
706
|
{t_pcba} AS pcba_temp_c, {t_handle} AS handle_temp_c, {t_mcu} AS mcu_temp_c,
|
|
@@ -545,9 +709,9 @@ class Database:
|
|
|
545
709
|
{diag}
|
|
546
710
|
FROM vitals_samples WHERE ts >= ? AND ts <= ? ORDER BY ts""",
|
|
547
711
|
(t_from, t_to),
|
|
548
|
-
)
|
|
712
|
+
))
|
|
549
713
|
width = (t_to - t_from) / max_points
|
|
550
|
-
return self._rows(
|
|
714
|
+
return _round_rows(self._rows(
|
|
551
715
|
f"""SELECT MIN(ts) AS ts, AVG(total_power_w) AS total_power_w, MAX(total_power_w) AS max_power_w,
|
|
552
716
|
AVG(vehicle_current_a) AS vehicle_current_a,
|
|
553
717
|
AVG(current_a_a) AS current_a_a, AVG(current_b_a) AS current_b_a,
|
|
@@ -561,15 +725,11 @@ class Database:
|
|
|
561
725
|
MAX(vehicle_connected) AS vehicle_connected,
|
|
562
726
|
MAX(contactor_closed) AS contactor_closed,
|
|
563
727
|
MAX(evse_state) AS evse_state, MAX(session_id) AS session_id,
|
|
564
|
-
AVG(
|
|
565
|
-
AVG(json_extract(raw, '$.pilot_low_v')) AS pilot_low_v,
|
|
566
|
-
AVG(json_extract(raw, '$.prox_v')) AS prox_v,
|
|
567
|
-
AVG(COALESCE(json_extract(raw, '$.relay_k1_v'), json_extract(raw, '$.relay_coil_v'))) AS relay_k1_v,
|
|
568
|
-
AVG(json_extract(raw, '$.relay_k2_v')) AS relay_k2_v
|
|
728
|
+
{", ".join(f"AVG({expr}) AS {col}" for col, expr in d.items())}
|
|
569
729
|
FROM vitals_samples WHERE ts >= ? AND ts <= ?
|
|
570
730
|
GROUP BY CAST((ts - ?) / ? AS INTEGER) ORDER BY ts""",
|
|
571
731
|
(t_from, t_to, t_from, width),
|
|
572
|
-
)
|
|
732
|
+
))
|
|
573
733
|
|
|
574
734
|
def lifetime_range(self, t_from: float, t_to: float, max_points: int = 3000) -> list[dict]:
|
|
575
735
|
"""Lifetime counter samples in a range (counters are monotonic, so
|