wallmonitor 0.1.0__py3-none-any.whl

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,215 @@
1
+ """A local Tesla Wall Connector Gen 3 simulator.
2
+
3
+ Serves the same four endpoints as the real device and walks through a
4
+ plausible charge cycle (idle → plug in → charge → complete → unplug) so the
5
+ monitor can be exercised end-to-end without hardware. Also reproduces the
6
+ device's JSON quirks (occasional literal ``nan``) so the library's workarounds
7
+ stay exercised.
8
+
9
+ Not a byte-perfect emulation — just realistic enough for demos and tests.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import json
16
+ import math
17
+ import random
18
+ import time
19
+
20
+ from aiohttp import web
21
+
22
+ CYCLE = [
23
+ # (phase name, duration seconds)
24
+ ("idle", 40.0),
25
+ ("connected", 15.0),
26
+ ("charging", 240.0),
27
+ ("complete", 60.0),
28
+ ]
29
+
30
+
31
+ class SimState:
32
+ """The simulated world, derived purely from the wall clock.
33
+
34
+ Phase comes from elapsed-time-modulo-cycle (× speedup), so there is no
35
+ background task to run or state to advance — every request computes the
36
+ world as of "now", and a test can pin `start` to make it deterministic."""
37
+
38
+ def __init__(self, speedup: float = 1.0, start: float | None = None):
39
+ self.t0 = start if start is not None else time.time()
40
+ self.speedup = speedup
41
+ self.boot_ts = self.t0
42
+ self.lifetime_energy_wh = 2_566_837.0
43
+ self.charge_starts = 450
44
+ self.alert_after_cycles = 2 # inject a device alert on the Nth cycle
45
+ self.rng = random.Random(7)
46
+
47
+ def _elapsed(self) -> float:
48
+ return (time.time() - self.t0) * self.speedup
49
+
50
+ def phase(self) -> tuple[str, float, int]:
51
+ """Current phase name, seconds into the phase, and cycle count."""
52
+ total = sum(duration for _, duration in CYCLE)
53
+ elapsed = self._elapsed()
54
+ cycle_n = int(elapsed // total)
55
+ into = elapsed % total
56
+ for name, dur in CYCLE:
57
+ if into < dur:
58
+ return name, into, cycle_n
59
+ into -= dur
60
+ return "idle", 0.0, cycle_n
61
+
62
+ def vitals(self) -> dict:
63
+ """Synthesize a /api/1/vitals body for the current phase: current
64
+ ramps in and tapers, the handle warms while charging, and a device
65
+ alert appears mid-charge from the Nth cycle on so alert plumbing
66
+ gets exercised without waiting for real trouble."""
67
+ name, into, cycle_n = self.phase()
68
+ rng = self.rng
69
+ grid_v = 230.0 + rng.uniform(-1.5, 1.5)
70
+ grid_hz = 50.0 + rng.uniform(-0.02, 0.02)
71
+ connected = name in ("connected", "charging", "complete")
72
+ charging = name == "charging"
73
+ # Ramp current up over the first 20s of charging, taper near the end.
74
+ amps = 0.0
75
+ if charging:
76
+ ramp = min(1.0, into / 20.0)
77
+ taper = 1.0 - max(0.0, (into - 200.0) / 40.0) * 0.6
78
+ amps = 16.0 * ramp * taper + rng.uniform(-0.2, 0.2)
79
+ if name == "connected":
80
+ session_s = int(into)
81
+ elif name == "charging":
82
+ session_s = int(CYCLE[1][1] + into)
83
+ elif name == "complete":
84
+ session_s = int(CYCLE[1][1] + CYCLE[2][1] + into)
85
+ else:
86
+ session_s = 0
87
+ # session energy: integrate the trapezoid roughly — good enough for a sim
88
+ session_energy = 0.0
89
+ if name == "charging":
90
+ session_energy = 3 * 230.0 * 14.0 * (into / 3600.0)
91
+ elif name == "complete":
92
+ session_energy = 3 * 230.0 * 14.0 * (CYCLE[2][1] / 3600.0)
93
+ alerts = []
94
+ if cycle_n >= self.alert_after_cycles and name == "charging" and 60 < into < 120:
95
+ # Real firmware reports numeric alert IDs (e.g. [27]).
96
+ alerts = [27]
97
+ # Telemetry-verified states: 1 no vehicle, 4 connected idle,
98
+ # 11 charging (contactor closed), 9 connected not charging.
99
+ evse_state = {"idle": 1, "connected": 4, "charging": 11, "complete": 9}[name]
100
+ handle_temp = 20.0 + (12.0 * min(1.0, into / 120.0) if charging else 0.0) + rng.uniform(-0.3, 0.3)
101
+ data = {
102
+ "contactor_closed": charging,
103
+ "vehicle_connected": connected,
104
+ "session_s": session_s,
105
+ "grid_v": round(grid_v, 1),
106
+ "grid_hz": round(grid_hz, 3),
107
+ "vehicle_current_a": round(amps, 1),
108
+ "currentA_a": round(amps if charging else 0.1, 1),
109
+ "currentB_a": round(amps if charging else 0.1, 1),
110
+ "currentC_a": round(amps if charging else 0.1, 1),
111
+ "currentN_a": round(rng.uniform(0.0, 0.4), 1),
112
+ "voltageA_v": round(grid_v + rng.uniform(-0.5, 0.5), 1),
113
+ "voltageB_v": round(grid_v + rng.uniform(-0.5, 0.5), 1),
114
+ "voltageC_v": round(grid_v + rng.uniform(-0.5, 0.5), 1),
115
+ "relay_coil_v": 11.9,
116
+ "pcba_temp_c": round(18.0 + (8.0 if charging else 0.0) + rng.uniform(-0.4, 0.4), 1),
117
+ "handle_temp_c": round(handle_temp, 1),
118
+ "mcu_temp_c": round(24.0 + (10.0 if charging else 0.0) + rng.uniform(-0.4, 0.4), 1),
119
+ "uptime_s": int((time.time() - self.boot_ts) * self.speedup),
120
+ "input_thermopile_uv": -151,
121
+ "prox_v": 1.5 if connected else 0.0,
122
+ "pilot_high_v": 8.9 if charging else 11.9,
123
+ "pilot_low_v": -11.9 if connected else 11.9,
124
+ "session_energy_wh": round(session_energy, 1),
125
+ "config_status": 5,
126
+ "evse_state": evse_state,
127
+ "current_alerts": alerts,
128
+ # Real firmware reports [1] whenever a vehicle is connected (even
129
+ # while charging) and [4, 8] when unplugged.
130
+ "evse_not_ready_reasons": [1] if connected else [4, 8],
131
+ }
132
+ return data
133
+
134
+ def lifetime(self) -> dict:
135
+ _, _, cycle_n = self.phase()
136
+ return {
137
+ "contactor_cycles": 175 + cycle_n,
138
+ "contactor_cycles_loaded": 3,
139
+ "alert_count": 1603,
140
+ "thermal_foldbacks": 0,
141
+ "avg_startup_temp": 27.8,
142
+ "charge_starts": self.charge_starts + cycle_n,
143
+ "energy_wh": int(self.lifetime_energy_wh + cycle_n * 2500),
144
+ "connector_cycles": 23 + cycle_n,
145
+ "uptime_s": int((time.time() - self.boot_ts) * self.speedup),
146
+ "charging_time_s": 183022 + cycle_n * int(CYCLE[2][1]),
147
+ }
148
+
149
+ def version(self) -> dict:
150
+ return {
151
+ "firmware_version": "24.36.3+gsimulated00",
152
+ "git_branch": "HEAD",
153
+ "part_number": "1529455-02-D",
154
+ "serial_number": "SIM12345678901",
155
+ "web_service": "h3-hermes-prd.sn.tesla.services",
156
+ }
157
+
158
+ def wifi_status(self) -> dict:
159
+ # RSSI drifts slowly; dips periodically so the health chart has shape.
160
+ elapsed = self._elapsed()
161
+ rssi = -62 + int(6 * math.sin(elapsed / 90.0)) - (8 if int(elapsed) % 300 < 20 else 0)
162
+ return {
163
+ "wifi_ssid": base64.b64encode(b"HomeNetwork").decode(),
164
+ "wifi_signal_strength": max(0, min(100, 2 * (rssi + 100))),
165
+ "wifi_rssi": rssi,
166
+ "wifi_snr": max(5, rssi + 88),
167
+ "wifi_connected": True,
168
+ "wifi_infra_ip": "127.0.0.1",
169
+ "internet": int(elapsed) % 600 > 30, # brief internet dropout every 10 sim-minutes
170
+ "wifi_mac": "AA:BB:CC:DD:EE:FF",
171
+ }
172
+
173
+
174
+ def make_app(state: SimState | None = None) -> web.Application:
175
+ """The four real device endpoints; vitals additionally reproduces the
176
+ firmware's occasional literal-nan JSON quirk."""
177
+ state = state or SimState()
178
+ app = web.Application()
179
+
180
+ def _json_response(data: dict, quirky: bool = False) -> web.Response:
181
+ body = json.dumps(data)
182
+ if quirky and state.rng.random() < 0.05:
183
+ # The real device occasionally emits literal nan values.
184
+ body = body.replace('"currentN_a": 0.0', '"currentN_a": nan')
185
+ return web.Response(text=body, content_type="application/json")
186
+
187
+ async def vitals(_request):
188
+ return _json_response(state.vitals(), quirky=True)
189
+
190
+ async def lifetime(_request):
191
+ return _json_response(state.lifetime())
192
+
193
+ async def version(_request):
194
+ return _json_response(state.version())
195
+
196
+ async def wifi_status(_request):
197
+ return _json_response(state.wifi_status())
198
+
199
+ app.router.add_get("/api/1/vitals", vitals)
200
+ app.router.add_get("/api/1/lifetime", lifetime)
201
+ app.router.add_get("/api/1/version", version)
202
+ app.router.add_get("/api/1/wifi_status", wifi_status)
203
+ return app
204
+
205
+
206
+ async def start_simulator(
207
+ port: int = 0, speedup: float = 1.0, start: float | None = None
208
+ ) -> tuple[web.AppRunner, int]:
209
+ """Start the simulator on localhost. Returns (runner, bound_port)."""
210
+ runner = web.AppRunner(make_app(SimState(speedup=speedup, start=start)))
211
+ await runner.setup()
212
+ site = web.TCPSite(runner, "127.0.0.1", port)
213
+ await site.start()
214
+ bound = site._server.sockets[0].getsockname()[1] # type: ignore[union-attr]
215
+ return runner, bound
@@ -0,0 +1 @@
1
+ """Static assets for the wallmonitor web UI (served locally, no external deps)."""