wallmonitor 0.1.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.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.3
2
+ Name: wallmonitor
3
+ Version: 0.1.0
4
+ Summary: Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3
5
+ Keywords: tesla,wall-connector,ev-charging,monitoring,self-hosted,thermal-model
6
+ Author: Fernando Gonzalez
7
+ License: MIT
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Environment :: Web Environment
10
+ Classifier: Intended Audience :: End Users/Desktop
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Home Automation
15
+ Classifier: Topic :: System :: Monitoring
16
+ Requires-Dist: aiohttp>=3.13.5,<4
17
+ Requires-Dist: tesla-wall-connector>=1.2.0,<2
18
+ Requires-Python: >=3.11
19
+ Project-URL: Homepage, https://github.com/zebraengine/wallmonitor
20
+ Project-URL: Repository, https://github.com/zebraengine/wallmonitor
21
+ Project-URL: Issues, https://github.com/zebraengine/wallmonitor/issues
22
+ Description-Content-Type: text/markdown
23
+
24
+ # wallmonitor
25
+
26
+ A **local-only** companion for the Tesla Wall Connector Gen 3 that grew well
27
+ beyond reading data off the charger: it records everything the device
28
+ reports, turns that history into a thermal model fitted to *your* install,
29
+ forecasts derates before they happen (with the charge-current cap that
30
+ avoids them), watches for connector degradation with honest statistics, and
31
+ pushes actionable warnings to your browser or phone.
32
+
33
+ Everything stays on your machine and your LAN: the only network traffic is
34
+ HTTP GETs to the charger's local API, storage is a local SQLite file, and the
35
+ web UI serves no external assets (no CDNs, fonts, or analytics).
36
+
37
+ ## Try it in 30 seconds
38
+
39
+ No hardware needed — demo mode runs a built-in charger simulator:
40
+
41
+ ```bash
42
+ uvx wallmonitor --demo
43
+ ```
44
+
45
+ Then open <http://127.0.0.1:8480>.
46
+
47
+ Against your real Wall Connector (find its IP in your router, or use the
48
+ `TeslaWallConnector_XXXXXX.local` hostname; add `--split-phase` on a North
49
+ American split-phase install):
50
+
51
+ ```bash
52
+ uvx wallmonitor --host 192.168.1.50 --split-phase
53
+ ```
54
+
55
+ All history lands in a single `wallmonitor.db` SQLite file — back up that
56
+ one file and you have everything. For every option, and for running it as a
57
+ systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
58
+
59
+ ## At a glance
60
+
61
+ - Full-fidelity recording — every response stored with its complete raw JSON
62
+ - Live dashboard (SSE) with rolling charts, an active-alert banner, and a
63
+ live derate-forecast chart: measured handle temperature against the
64
+ model's projected plateau and the trip threshold, projection drawn
65
+ forward so the predicted trip intercept is visible on the chart
66
+ - Session review: energy, peak/average power, per-phase telemetry, drillable charts
67
+ - Event timeline with range presets, category filters, and paging
68
+ - Alert decoding and EVSE-state labels, each marked verified vs community-reported
69
+ - Wi-Fi health history and connectivity events
70
+ - **Thermal derate forecast** — a per-install fitted model predicts alert 40
71
+ live and suggests the highest current that avoids the 50% foldback
72
+ - **Automatic derate prevention** — an optional daemon caps the vehicle's
73
+ charge current through a least-privilege BLE pairing when the forecast
74
+ firms up, and restores it once the risk clears
75
+ - **Degradation watch** — ambient-corrected heat-rise trend with confidence
76
+ intervals and a verified-baseline anchor, so "getting worse" is a
77
+ statistical claim, not a vibe
78
+ - **Actionable notifications, local-only** — browser push and LAN
79
+ webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
80
+ - Resilience: seamless restarts, downtime recorded as explicit gap events,
81
+ sensor-glitch quarantine
82
+
83
+ ## Works out of the box — everything else is additive
84
+
85
+ The core needs nothing but the charger. Integrations are optional, degrade
86
+ gracefully when absent, and the absence paths are covered by the test suite:
87
+ without an ambient sensor the charger doubles as its own thermometer, with
88
+ no webhook configured notifications are a tested no-op, and TeslaMate /
89
+ ntfy / ESP32-BLE each plug into a generic interface (`POST /api/ambient`, a
90
+ plain LAN webhook, a REST call) rather than being wired into the core.
91
+
92
+ ## Documentation
93
+
94
+ | Page | What's in it |
95
+ |---|---|
96
+ | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install, tests |
97
+ | [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
98
+ | [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
99
+ | [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
100
+ | [Ambient sensing](https://github.com/zebraengine/wallmonitor/blob/main/docs/ambient-sensors.md) | Garage sensors (Ecowitt or any JSON poster), placement, contamination checks, the TeslaMate car bridge |
101
+ | [Notifications](https://github.com/zebraengine/wallmonitor/blob/main/docs/notifications.md) | Browser push and self-hosted ntfy phone alerts |
102
+ | [Measured charging efficiency](https://github.com/zebraengine/wallmonitor/blob/main/docs/efficiency.md) | What three cross-referenced meters say about wall-to-battery efficiency |
103
+
104
+ ## Tests
105
+
106
+ ```bash
107
+ uv run pytest
108
+ ```
109
+
110
+ The suite runs the full pipeline against the simulator — polling, session
111
+ detection, alert lifecycle, the web API, and the thermal model end to end.
112
+
113
+ ## License
114
+
115
+ [MIT](https://github.com/zebraengine/wallmonitor/blob/main/LICENSE). Built on the
116
+ [`tesla-wall-connector`](https://github.com/einarhauks/tesla-wall-connector)
117
+ library (MIT, by Einar Bragi Hauksson).
@@ -0,0 +1,94 @@
1
+ # wallmonitor
2
+
3
+ A **local-only** companion for the Tesla Wall Connector Gen 3 that grew well
4
+ beyond reading data off the charger: it records everything the device
5
+ reports, turns that history into a thermal model fitted to *your* install,
6
+ forecasts derates before they happen (with the charge-current cap that
7
+ avoids them), watches for connector degradation with honest statistics, and
8
+ pushes actionable warnings to your browser or phone.
9
+
10
+ Everything stays on your machine and your LAN: the only network traffic is
11
+ HTTP GETs to the charger's local API, storage is a local SQLite file, and the
12
+ web UI serves no external assets (no CDNs, fonts, or analytics).
13
+
14
+ ## Try it in 30 seconds
15
+
16
+ No hardware needed — demo mode runs a built-in charger simulator:
17
+
18
+ ```bash
19
+ uvx wallmonitor --demo
20
+ ```
21
+
22
+ Then open <http://127.0.0.1:8480>.
23
+
24
+ Against your real Wall Connector (find its IP in your router, or use the
25
+ `TeslaWallConnector_XXXXXX.local` hostname; add `--split-phase` on a North
26
+ American split-phase install):
27
+
28
+ ```bash
29
+ uvx wallmonitor --host 192.168.1.50 --split-phase
30
+ ```
31
+
32
+ All history lands in a single `wallmonitor.db` SQLite file — back up that
33
+ one file and you have everything. For every option, and for running it as a
34
+ systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
35
+
36
+ ## At a glance
37
+
38
+ - Full-fidelity recording — every response stored with its complete raw JSON
39
+ - Live dashboard (SSE) with rolling charts, an active-alert banner, and a
40
+ live derate-forecast chart: measured handle temperature against the
41
+ model's projected plateau and the trip threshold, projection drawn
42
+ forward so the predicted trip intercept is visible on the chart
43
+ - Session review: energy, peak/average power, per-phase telemetry, drillable charts
44
+ - Event timeline with range presets, category filters, and paging
45
+ - Alert decoding and EVSE-state labels, each marked verified vs community-reported
46
+ - Wi-Fi health history and connectivity events
47
+ - **Thermal derate forecast** — a per-install fitted model predicts alert 40
48
+ live and suggests the highest current that avoids the 50% foldback
49
+ - **Automatic derate prevention** — an optional daemon caps the vehicle's
50
+ charge current through a least-privilege BLE pairing when the forecast
51
+ firms up, and restores it once the risk clears
52
+ - **Degradation watch** — ambient-corrected heat-rise trend with confidence
53
+ intervals and a verified-baseline anchor, so "getting worse" is a
54
+ statistical claim, not a vibe
55
+ - **Actionable notifications, local-only** — browser push and LAN
56
+ webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
57
+ - Resilience: seamless restarts, downtime recorded as explicit gap events,
58
+ sensor-glitch quarantine
59
+
60
+ ## Works out of the box — everything else is additive
61
+
62
+ The core needs nothing but the charger. Integrations are optional, degrade
63
+ gracefully when absent, and the absence paths are covered by the test suite:
64
+ without an ambient sensor the charger doubles as its own thermometer, with
65
+ no webhook configured notifications are a tested no-op, and TeslaMate /
66
+ ntfy / ESP32-BLE each plug into a generic interface (`POST /api/ambient`, a
67
+ plain LAN webhook, a REST call) rather than being wired into the core.
68
+
69
+ ## Documentation
70
+
71
+ | Page | What's in it |
72
+ |---|---|
73
+ | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install, tests |
74
+ | [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
75
+ | [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
76
+ | [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
77
+ | [Ambient sensing](https://github.com/zebraengine/wallmonitor/blob/main/docs/ambient-sensors.md) | Garage sensors (Ecowitt or any JSON poster), placement, contamination checks, the TeslaMate car bridge |
78
+ | [Notifications](https://github.com/zebraengine/wallmonitor/blob/main/docs/notifications.md) | Browser push and self-hosted ntfy phone alerts |
79
+ | [Measured charging efficiency](https://github.com/zebraengine/wallmonitor/blob/main/docs/efficiency.md) | What three cross-referenced meters say about wall-to-battery efficiency |
80
+
81
+ ## Tests
82
+
83
+ ```bash
84
+ uv run pytest
85
+ ```
86
+
87
+ The suite runs the full pipeline against the simulator — polling, session
88
+ detection, alert lifecycle, the web API, and the thermal model end to end.
89
+
90
+ ## License
91
+
92
+ [MIT](https://github.com/zebraengine/wallmonitor/blob/main/LICENSE). Built on the
93
+ [`tesla-wall-connector`](https://github.com/einarhauks/tesla-wall-connector)
94
+ library (MIT, by Einar Bragi Hauksson).
@@ -0,0 +1,60 @@
1
+ [project]
2
+ name = "wallmonitor"
3
+ version = "0.1.0"
4
+ description = "Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ keywords = [
8
+ "tesla",
9
+ "wall-connector",
10
+ "ev-charging",
11
+ "monitoring",
12
+ "self-hosted",
13
+ "thermal-model",
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Environment :: Web Environment",
18
+ "Intended Audience :: End Users/Desktop",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Home Automation",
23
+ "Topic :: System :: Monitoring",
24
+ ]
25
+ dependencies = [
26
+ "aiohttp>=3.13.5,<4",
27
+ "tesla-wall-connector>=1.2.0,<2",
28
+ ]
29
+
30
+ [project.license]
31
+ text = "MIT"
32
+
33
+ [[project.authors]]
34
+ name = "Fernando Gonzalez"
35
+
36
+ [project.scripts]
37
+ wallmonitor = "wallmonitor.__main__:main"
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/zebraengine/wallmonitor"
41
+ Repository = "https://github.com/zebraengine/wallmonitor"
42
+ Issues = "https://github.com/zebraengine/wallmonitor/issues"
43
+
44
+ [dependency-groups]
45
+ dev = [
46
+ "pytest>=9.1,<10",
47
+ "pytest-asyncio>=1.4,<2",
48
+ ]
49
+
50
+ [build-system]
51
+ requires = ["uv_build>=0.11.6,<0.12"]
52
+ build-backend = "uv_build"
53
+
54
+ [tool.uv.build-backend]
55
+ module-root = ""
56
+ module-name = "wallmonitor"
57
+
58
+ [tool.pytest.ini_options]
59
+ asyncio_mode = "auto"
60
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "wallmonitor"
3
+ version = "0.1.0"
4
+ description = "Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = { text = "MIT" }
8
+ authors = [{ name = "Fernando Gonzalez" }]
9
+ keywords = ["tesla", "wall-connector", "ev-charging", "monitoring", "self-hosted", "thermal-model"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Environment :: Web Environment",
13
+ "Intended Audience :: End Users/Desktop",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Topic :: Home Automation",
18
+ "Topic :: System :: Monitoring",
19
+ ]
20
+ dependencies = [
21
+ "aiohttp>=3.13.5,<4",
22
+ "tesla-wall-connector>=1.2.0,<2",
23
+ ]
24
+
25
+ [project.scripts]
26
+ wallmonitor = "wallmonitor.__main__:main"
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/zebraengine/wallmonitor"
30
+ Repository = "https://github.com/zebraengine/wallmonitor"
31
+ Issues = "https://github.com/zebraengine/wallmonitor/issues"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "pytest>=9.1,<10",
36
+ "pytest-asyncio>=1.4,<2",
37
+ ]
38
+
39
+ [build-system]
40
+ requires = ["uv_build>=0.11.6,<0.12"]
41
+ build-backend = "uv_build"
42
+
43
+ [tool.uv.build-backend]
44
+ module-root = ""
45
+ module-name = "wallmonitor"
46
+
47
+ [tool.pytest.ini_options]
48
+ asyncio_mode = "auto"
49
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,3 @@
1
+ """Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,81 @@
1
+ """Entry point: wire up config, DB, poller, web UI (and simulator in demo mode).
2
+
3
+ Component map — one process, one asyncio loop:
4
+
5
+ Wall Connector ──HTTP──▶ Poller ──writes──▶ Database (SQLite)
6
+ │ └─publishes──▶ EventBus ──SSE──▶ browser
7
+ └──POSTs──▶ notify webhook (optional, LAN)
8
+ browser ◀──JSON/static── web.make_app ◀──reads── Database
9
+
10
+ The Poller owns all device I/O; the web layer only reads the DB (plus the
11
+ poller's in-memory status), so a busy dashboard can never add load on the
12
+ charger.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import logging
19
+
20
+ import aiohttp
21
+ from aiohttp import web
22
+
23
+ from .config import parse_args
24
+ from .db import Database
25
+ from .poller import EventBus, Poller
26
+ from .simulator import start_simulator
27
+ from .web import make_app
28
+
29
+ log = logging.getLogger("wallmonitor")
30
+
31
+
32
+ async def run(argv: list[str] | None = None) -> None:
33
+ """Construct every component, serve until cancelled, unwind in order.
34
+
35
+ Shutdown order is deliberate: stop the poller first (the only writer),
36
+ then the web runner (readers), then the shared HTTP client, and close
37
+ the database last so nothing can touch a closed connection."""
38
+ cfg = parse_args(argv)
39
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
40
+
41
+ sim_runner = None
42
+ if cfg.demo:
43
+ sim_runner, sim_port = await start_simulator()
44
+ cfg.host = f"127.0.0.1:{sim_port}"
45
+ log.info("demo mode: simulator running at http://%s", cfg.host)
46
+
47
+ db = Database(cfg.db_path)
48
+ bus = EventBus()
49
+ client = aiohttp.ClientSession()
50
+ poller = Poller(cfg, db, bus, client)
51
+ await poller.start()
52
+
53
+ app = make_app(db, bus, poller)
54
+ runner = web.AppRunner(app)
55
+ await runner.setup()
56
+ site = web.TCPSite(runner, cfg.bind, cfg.port)
57
+ await site.start()
58
+ log.info("wallmonitor UI on http://%s:%d (watching Wall Connector at %s)", cfg.bind, cfg.port, cfg.host)
59
+
60
+ try:
61
+ await asyncio.Event().wait()
62
+ except (KeyboardInterrupt, asyncio.CancelledError):
63
+ pass
64
+ finally:
65
+ await poller.stop()
66
+ await runner.cleanup()
67
+ if sim_runner:
68
+ await sim_runner.cleanup()
69
+ await client.close()
70
+ db.close()
71
+
72
+
73
+ def main() -> None:
74
+ try:
75
+ asyncio.run(run())
76
+ except KeyboardInterrupt:
77
+ pass
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
@@ -0,0 +1,70 @@
1
+ {
2
+ "_about": [
3
+ "Decoding data for Wall Connector Gen 3 alerts as reported by the local API's",
4
+ "current_alerts field. Tesla does not document these codes; on modern firmware",
5
+ "they are numeric IDs (e.g. [27]). Entries here must be VERIFIED before they",
6
+ "are labeled: the reliable method is to open the Tesla app while an alert is",
7
+ "active on your charger — the app names active alerts — and record the code",
8
+ "the local API showed at the same moment. Unverified guesses do not belong in",
9
+ "this file; a wrong label is worse than a raw number.",
10
+ "Each code entry: {label, description, source, verified}."
11
+ ],
12
+ "codes": {
13
+ "40": {
14
+ "label": "High temperature detected",
15
+ "description": "High temperature detected; charging is limited. Observed behavior on firmware 26.18.0: raises when handle_temp_c reaches 65 C and instantly derates charge current to 50%; clears once the handle cools to ~60 C, but the derate persists for the rest of the session. Check the faceplate and cable handle for excessive warmth and rule out wiring issues (conductor sizing, terminal torque); in a hot garage this can simply be ambient heat.",
16
+ "source": "Tesla app > Wall Connector Troubleshooting, confirmed against an active alert on 2026-07-14 (matches the manual's 'High temperature' fault category); thresholds observed from monitor telemetry of that event",
17
+ "verified": true
18
+ }
19
+ },
20
+ "categories": [
21
+ {
22
+ "led": "Solid red",
23
+ "label": "Internal error",
24
+ "description": "Charging disabled. Power-cycle the breaker for 5 seconds; contact Tesla if it persists.",
25
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
26
+ },
27
+ {
28
+ "led": "1 red blink",
29
+ "label": "Ground fault (earth fault circuit interruption)",
30
+ "description": "Unsafe current path detected; charging disabled. Inspect handle, cable, connector, and vehicle charge port for damage or water ingress.",
31
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
32
+ },
33
+ {
34
+ "led": "2 red blinks",
35
+ "label": "Earth assurance fault",
36
+ "description": "High ground resistance detected; charging disabled. Verify the ground connection and physical connections in the supply.",
37
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
38
+ },
39
+ {
40
+ "led": "3 red blinks",
41
+ "label": "High temperature",
42
+ "description": "Charging limited or disabled due to heat. Check the faceplate and cable handle for excessive warmth; verify conductor sizing and terminal torque.",
43
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
44
+ },
45
+ {
46
+ "led": "4 red blinks",
47
+ "label": "Internet connection lost",
48
+ "description": "Online features disabled; charging still works. Check Wi-Fi signal and router; update Wi-Fi settings if credentials changed.",
49
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
50
+ },
51
+ {
52
+ "led": "5 red blinks",
53
+ "label": "Power-sharing communication issue",
54
+ "description": "Charging reduced. Re-link power-sharing Wall Connectors via the commissioning process.",
55
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
56
+ },
57
+ {
58
+ "led": "6 red blinks",
59
+ "label": "Overvoltage / poor grid quality",
60
+ "description": "Charging disabled. Verify supply voltage; have an electrician check terminal readings.",
61
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
62
+ },
63
+ {
64
+ "led": "7 red blinks",
65
+ "label": "Vehicle overcurrent",
66
+ "description": "The vehicle drew more current than allowed. Reduce the vehicle's charge current setting.",
67
+ "source": "Tesla Gen 3 Wall Connector manual, Error Codes"
68
+ }
69
+ ]
70
+ }
@@ -0,0 +1,163 @@
1
+ """Runtime configuration for wallmonitor.
2
+
3
+ All values come from CLI arguments with environment-variable fallbacks so the
4
+ app can run as a service. Poll cadence defaults are chosen to stay well within
5
+ what the Wall Connector Gen 3's small embedded web server handles reliably:
6
+ requests are always sequential (never concurrent), the vitals cadence only
7
+ tightens while a vehicle is attached, and repeated failures back the poller
8
+ off exponentially instead of hammering a struggling device.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import os
15
+ from dataclasses import dataclass
16
+
17
+
18
+ @dataclass
19
+ class Config:
20
+ """Everything the app runs with, resolved once by parse_args.
21
+
22
+ Fields without CLI flags (request_timeout, the backoff pair,
23
+ min_interval) are deliberately not user-tunable: they are the
24
+ guardrails protecting the charger's small embedded web server."""
25
+
26
+ host: str
27
+ port: int = 8480
28
+ bind: str = "127.0.0.1"
29
+ db_path: str = "wallmonitor.db"
30
+ demo: bool = False
31
+ split_phase: bool = False
32
+ # Optional LAN webhook: actionable warnings are POSTed here.
33
+ # Local-only by design — point it at something on your own network
34
+ # (Home Assistant, a self-hosted ntfy, node-RED); leave empty to disable.
35
+ notify_url: str = ""
36
+ # Payload shape for the webhook: "json" posts one JSON object; "ntfy"
37
+ # posts plain-text with X-Title/X-Priority/X-Tags headers so notify_url
38
+ # can be a ntfy topic (e.g. http://<lan-host>:8481/wallmonitor) directly.
39
+ notify_format: str = "json"
40
+ # Poll cadence (seconds). Vitals tighten while a vehicle is connected.
41
+ vitals_interval_active: float = 2.0
42
+ vitals_interval_idle: float = 5.0
43
+ wifi_interval: float = 30.0
44
+ lifetime_interval: float = 60.0
45
+ version_interval: float = 6 * 3600.0
46
+ request_timeout: float = 5.0
47
+ # Error backoff
48
+ backoff_factor: float = 1.6
49
+ backoff_max: float = 60.0
50
+ # Floor: never poll any endpoint faster than this, whatever the flags say.
51
+ min_interval: float = 1.0
52
+
53
+ def clamp(self) -> "Config":
54
+ """Enforce the polling floor whatever the flags said; returns self."""
55
+ self.vitals_interval_active = max(self.min_interval, self.vitals_interval_active)
56
+ self.vitals_interval_idle = max(self.min_interval, self.vitals_interval_idle)
57
+ self.wifi_interval = max(self.min_interval, self.wifi_interval)
58
+ self.lifetime_interval = max(self.min_interval, self.lifetime_interval)
59
+ return self
60
+
61
+
62
+ def _env(name: str, default):
63
+ """Environment fallback for a CLI default, coerced to the default's type.
64
+
65
+ The bool check must stay ahead of int: bool is an int subclass, so the
66
+ int branch would otherwise catch bool defaults and int("true") would
67
+ crash at import. Returning a real bool also keeps store_true flags
68
+ honest — WM_DEMO=false must not become a truthy default."""
69
+ val = os.getenv(name)
70
+ if val is None:
71
+ return default
72
+ if isinstance(default, bool):
73
+ return val.lower() in ("1", "true", "yes", "on")
74
+ if isinstance(default, float):
75
+ return float(val)
76
+ if isinstance(default, int):
77
+ return int(val)
78
+ return val
79
+
80
+
81
+ def parse_args(argv: list[str] | None = None) -> Config:
82
+ """Build the Config: CLI flag beats WM_* env var beats hardcoded default.
83
+
84
+ One validation rule: --host is required unless --demo runs the built-in
85
+ simulator instead of real hardware. Note the boolean flags can only
86
+ assert True — an env-var-enabled --demo/--split-phase has no --no-*
87
+ override; unset the variable instead."""
88
+ parser = argparse.ArgumentParser(
89
+ prog="wallmonitor",
90
+ description="Local-only monitoring UI for a Tesla Wall Connector Gen 3",
91
+ )
92
+ parser.add_argument(
93
+ "--host",
94
+ default=_env("WM_WC_HOST", ""),
95
+ help="Hostname or IP of the Wall Connector on your LAN (env: WM_WC_HOST)",
96
+ )
97
+ parser.add_argument("--port", type=int, default=_env("WM_PORT", 8480), help="Web UI port (env: WM_PORT)")
98
+ parser.add_argument(
99
+ "--bind",
100
+ default=_env("WM_BIND", "127.0.0.1"),
101
+ help="Web UI bind address; default localhost only (env: WM_BIND)",
102
+ )
103
+ parser.add_argument(
104
+ "--db", dest="db_path", default=_env("WM_DB", "wallmonitor.db"), help="SQLite database path (env: WM_DB)"
105
+ )
106
+ parser.add_argument(
107
+ "--demo",
108
+ action="store_true",
109
+ default=_env("WM_DEMO", False),
110
+ help="Run against a built-in Wall Connector simulator instead of real hardware (env: WM_DEMO)",
111
+ )
112
+ parser.add_argument(
113
+ "--vitals-active",
114
+ type=float,
115
+ default=_env("WM_VITALS_ACTIVE", 2.0),
116
+ help="Vitals poll interval in seconds while a vehicle is connected (default 2)",
117
+ )
118
+ parser.add_argument(
119
+ "--vitals-idle",
120
+ type=float,
121
+ default=_env("WM_VITALS_IDLE", 5.0),
122
+ help="Vitals poll interval in seconds while idle (default 5)",
123
+ )
124
+ parser.add_argument("--wifi-interval", type=float, default=_env("WM_WIFI_INTERVAL", 30.0))
125
+ parser.add_argument("--lifetime-interval", type=float, default=_env("WM_LIFETIME_INTERVAL", 60.0))
126
+ parser.add_argument(
127
+ "--split-phase",
128
+ action="store_true",
129
+ default=_env("WM_SPLIT_PHASE", False),
130
+ help="Compute total power for a North American split-phase install (env: WM_SPLIT_PHASE)",
131
+ )
132
+ parser.add_argument(
133
+ "--notify-url",
134
+ default=_env("WM_NOTIFY_URL", ""),
135
+ help="Optional LAN webhook that receives actionable warnings as POSTs, "
136
+ "e.g. Home Assistant or a self-hosted ntfy on your own network (env: WM_NOTIFY_URL)",
137
+ )
138
+ parser.add_argument(
139
+ "--notify-format",
140
+ choices=("json", "ntfy"),
141
+ default=_env("WM_NOTIFY_FORMAT", "json"),
142
+ help="Webhook payload shape: 'json' for one JSON object per warning, 'ntfy' for "
143
+ "plain-text + ntfy headers so --notify-url can be a ntfy topic (env: WM_NOTIFY_FORMAT)",
144
+ )
145
+ args = parser.parse_args(argv)
146
+
147
+ if not args.demo and not args.host:
148
+ parser.error("--host (or WM_WC_HOST) is required unless --demo is set")
149
+
150
+ return Config(
151
+ host=args.host,
152
+ port=args.port,
153
+ bind=args.bind,
154
+ db_path=args.db_path,
155
+ demo=bool(args.demo),
156
+ split_phase=bool(args.split_phase),
157
+ notify_url=args.notify_url,
158
+ notify_format=args.notify_format,
159
+ vitals_interval_active=args.vitals_active,
160
+ vitals_interval_idle=args.vitals_idle,
161
+ wifi_interval=args.wifi_interval,
162
+ lifetime_interval=args.lifetime_interval,
163
+ ).clamp()