sim86 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.
sim86/run.py ADDED
@@ -0,0 +1,902 @@
1
+ """A live run: serial output, exact stops, faults, inputs and chip state.
2
+
3
+ Everything time-related happens inside the simulator: `until` arms a stop
4
+ the simulator takes on the exact cycle, faults apply at the paused simulated
5
+ time, so network latency never changes what the firmware sees.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import itertools
11
+ import json
12
+ import secrets
13
+ import threading
14
+ import time
15
+ from dataclasses import dataclass
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ from websockets.sync.client import connect
19
+
20
+ from .api import Client, Sim86Error
21
+ from .board import Board, parse_ms, parse_pin, run_spec, upload_flash_files
22
+
23
+ #: How long a request keeps asking while the node is still building the board.
24
+ BOARD_BUILD_PATIENCE_S = 120
25
+
26
+ WS_AUTH_PROTOCOL = "sim86.auth"
27
+ # Log sources that are not firmware output: the node's own lines, what a
28
+ # program driving the run did, and its notes (pytest's test markers).
29
+ NOT_FIRMWARE = {"node", "sim", "driver", "test", "scenario"}
30
+ TERMINAL = {"done", "failed", "stopped", "lost"}
31
+
32
+
33
+ class RunEnded(Sim86Error):
34
+ """The run is over, so live commands can't reach it any more."""
35
+
36
+
37
+ class SerialTimeout(Sim86Error, AssertionError):
38
+ """The text didn't appear within the simulated time allowed."""
39
+
40
+
41
+ @dataclass
42
+ class LogLine:
43
+ t: float # simulated time, ms
44
+ source: str # "<part>:<channel>", e.g. "gateway:uart0"
45
+ line: str
46
+
47
+ def __str__(self) -> str:
48
+ return f"[{self.t:10.3f} ms] {self.source:<18} {self.line}"
49
+
50
+
51
+ @dataclass
52
+ class Halt:
53
+ paused: bool
54
+ time_ns: int
55
+ edge_at_ns: Optional[int] = None
56
+
57
+ @property
58
+ def time_ms(self) -> float:
59
+ return self.time_ns / 1e6
60
+
61
+
62
+ Pin = Union[str, "PinHandle"]
63
+
64
+
65
+ def _pin_frame(pin: Pin) -> Dict[str, str]:
66
+ part, name = parse_pin(pin) if isinstance(pin, str) else (pin.part, pin.name)
67
+ return {"component": part, "pin": name}
68
+
69
+
70
+ class PinHandle:
71
+ def __init__(self, part: str, name: str):
72
+ self.part, self.name = part, name
73
+
74
+ def __str__(self) -> str:
75
+ return f"{self.part}.{self.name}"
76
+
77
+
78
+ class Serial:
79
+ """What one part prints (all its channels), or the whole board's output."""
80
+
81
+ def __init__(self, run: "Run", part: Optional[str]):
82
+ self._run, self._part = run, part
83
+
84
+ def _match(self, line: LogLine) -> bool:
85
+ if line.source in NOT_FIRMWARE:
86
+ return False
87
+ return self._part is None or line.source == self._part or line.source.startswith(self._part + ":")
88
+
89
+ @property
90
+ def lines(self) -> List[LogLine]:
91
+ with self._run._cond:
92
+ return [l for l in self._run._logs if self._match(l)]
93
+
94
+ @property
95
+ def text(self) -> str:
96
+ return "\n".join(l.line for l in self.lines)
97
+
98
+ def wait_for(self, text: str, ms: Union[str, float] = 1000, *, since_start: bool = False) -> LogLine:
99
+ """Run until a line containing `text` appears, for at most `ms` of SIMULATED time.
100
+
101
+ Output is read in order: a wait looks at lines after the one the
102
+ previous wait matched, and after the last until()/advance() stop.
103
+ since_start=True searches everything printed. On timeout the board is
104
+ left paused exactly at the deadline, so you can inspect it.
105
+ """
106
+ return self._run._wait_for_line(lambda l: self._match(l) and text in l.line, ms, since_start,
107
+ f"{text!r} from {self._part or 'the board'}")
108
+
109
+ def __contains__(self, text: str) -> bool:
110
+ return any(text in l.line for l in self.lines)
111
+
112
+
113
+ class Reading:
114
+ """What one register / field / memory range holds."""
115
+
116
+ def __init__(self, raw: Dict[str, Any]):
117
+ self.raw = raw
118
+ self.path: str = raw.get("path", "")
119
+ self.value: Optional[int] = raw.get("value")
120
+ self.meaning: Optional[str] = raw.get("meaning")
121
+ self.bytes: Optional[str] = raw.get("bytes")
122
+ self.fields: Dict[str, int] = {f["name"]: f["value"] for f in raw.get("fields") or []}
123
+
124
+ def __getitem__(self, field_name: str) -> int:
125
+ try:
126
+ return self.fields[field_name]
127
+ except KeyError:
128
+ raise KeyError(f"{self.path} has no field {field_name!r}; fields: {', '.join(self.fields)}") from None
129
+
130
+ def __int__(self) -> int:
131
+ if self.value is None:
132
+ raise Sim86Error(f"{self.path} has no single value")
133
+ return int(self.value)
134
+
135
+ def __eq__(self, other: object) -> bool:
136
+ if isinstance(other, int):
137
+ return self.value == other
138
+ return isinstance(other, Reading) and other.raw == self.raw
139
+
140
+ def __repr__(self) -> str:
141
+ if self.bytes is not None:
142
+ return f"<{self.path} = {self.bytes}>"
143
+ extra = f" {self.meaning}" if self.meaning else ""
144
+ return f"<{self.path} = {self.raw.get('hex') or self.value}{extra}>"
145
+
146
+
147
+ WIFI_CHANNEL_MHZ = {ch: 2407 + 5 * ch for ch in range(1, 14)}
148
+ WIFI_CHANNEL_MHZ[14] = 2484
149
+
150
+
151
+ class Radio:
152
+ """The radio room of a board (its RfEnvironment part): change the air mid-run.
153
+
154
+ board.radio.loss("mcu", "ap", 110) # walk out of range
155
+ board.radio.jam(channel=6, dbm=-40) # a strong interferer on channel 6
156
+ board.radio.restore() # back to the board file's setup
157
+ """
158
+
159
+ def __init__(self, run: "Run", part_id: str, base: Dict[str, Any]):
160
+ self._run, self.id = run, part_id
161
+ self._base = dict(base)
162
+ self._links: Dict[tuple, int] = {}
163
+ self._noise: Dict[str, Dict[str, Any]] = {}
164
+
165
+ def _apply(self, what: str) -> None:
166
+ config = dict(self._base)
167
+ links = [l for l in config.get("links", []) if (l.get("sourceId"), l.get("receiverId")) not in self._links]
168
+ links += [{"sourceId": a, "receiverId": b, "pathLossDb": db} for (a, b), db in self._links.items()]
169
+ noise = [n for n in config.get("noiseSources", []) if n.get("id") not in self._noise]
170
+ noise += list(self._noise.values())
171
+ config["links"], config["noiseSources"] = links, noise
172
+ self._run.event(self.id, "configure_room:" + json.dumps(config))
173
+ self._run.note(f"radio: {what}")
174
+
175
+ def loss(self, a: str, b: str, db: int, *, both_ways: bool = True) -> None:
176
+ """Path loss between two radios in dB (about 40 = same desk, 90 = far, 110+ = out of range)."""
177
+ self._links[(a, b)] = int(db)
178
+ if both_ways:
179
+ self._links[(b, a)] = int(db)
180
+ self._apply(f"path loss {a} ↔ {b} = {db} dB")
181
+
182
+ def jam(self, channel: int = 6, dbm: int = -40, *, mhz: int = 22, name: str = "jammer") -> None:
183
+ """Noise centred on a Wi-Fi channel, `mhz` wide (22 = one Wi-Fi channel, 80+ = the
184
+ whole 2.4 GHz band). `dbm` is the power the jammer transmits; like every
185
+ radio in the room it is about 40 dB of path loss from the others, and its
186
+ power is spread over its width, so a 0 dBm jammer across 90 MHz is weak."""
187
+ if channel not in WIFI_CHANNEL_MHZ:
188
+ raise Sim86Error("Wi-Fi channel must be 1–14")
189
+ self._noise[name] = {"id": name, "centerFrequencyHz": WIFI_CHANNEL_MHZ[channel] * 1_000_000,
190
+ "bandwidthHz": mhz * 1_000_000, "powerDbm": int(dbm)}
191
+ self._apply(f"{name} on channel {channel} at {dbm} dBm")
192
+
193
+ def restore(self) -> None:
194
+ """Undo every change: the room as the board file set it up."""
195
+ self._links.clear()
196
+ self._noise.clear()
197
+ self._apply("restored")
198
+
199
+
200
+ @dataclass
201
+ class EdgeTiming:
202
+ at_ns: float
203
+ rising: bool
204
+ from_volts: float
205
+ to_volts: float
206
+ driver: str = ""
207
+ transition_ns: Optional[float] = None # 10–90 % rise or 90–10 % fall
208
+ delay_ns: Optional[float] = None # driver switch -> receiver threshold
209
+
210
+ @property
211
+ def rise_ns(self) -> Optional[float]:
212
+ return self.transition_ns if self.rising else None
213
+
214
+ @property
215
+ def fall_ns(self) -> Optional[float]:
216
+ return None if self.rising else self.transition_ns
217
+
218
+
219
+ @dataclass
220
+ class Measurement:
221
+ """What a net did over a window: volts and edges."""
222
+ pin: str
223
+ from_ns: int
224
+ to_ns: int
225
+ min: Optional[float]
226
+ max: Optional[float]
227
+ mean: Optional[float]
228
+ last: Optional[float]
229
+ edges: List[EdgeTiming]
230
+ analog: bool # True: the analog solver's exact volts; False: digital rail levels
231
+ raw: Dict[str, Any]
232
+ level: Optional[str] = None # the line's logic level at the end: "low", "high", "floating", "unknown"
233
+
234
+ @property
235
+ def rising(self) -> List[EdgeTiming]:
236
+ return [e for e in self.edges if e.rising]
237
+
238
+ @property
239
+ def falling(self) -> List[EdgeTiming]:
240
+ return [e for e in self.edges if not e.rising]
241
+
242
+
243
+ def _measurement(pin: str, wire: Dict[str, Any], from_ns: int, to_ns: int) -> Measurement:
244
+ analog = wire.get("analog")
245
+ if analog:
246
+ pts = [(float(t), float(v)) for t, v in analog.get("points") or []]
247
+ buckets = analog.get("buckets") or []
248
+ if pts:
249
+ inside = [(t, v) for t, v in pts if t >= from_ns] or pts[-1:]
250
+ lo, hi = min(v for _, v in inside), max(v for _, v in inside)
251
+ # time-weighted mean of the piecewise-linear waveform over the window
252
+ area, span = 0.0, 0.0
253
+ seq = [(max(t, from_ns), v) for t, v in pts if t <= to_ns]
254
+ seq.append((to_ns, pts[-1][1] if pts[-1][0] <= to_ns else seq[-1][1]))
255
+ for (t0, v0), (t1, v1) in zip(seq, seq[1:]):
256
+ if t1 > t0:
257
+ area += (v0 + v1) / 2 * (t1 - t0)
258
+ span += t1 - t0
259
+ mean = area / span if span else inside[-1][1]
260
+ last = pts[-1][1]
261
+ elif buckets:
262
+ lo = min(b["min"] for b in buckets)
263
+ hi = max(b["max"] for b in buckets)
264
+ mean = (lo + hi) / 2
265
+ last = (buckets[-1]["min"] + buckets[-1]["max"]) / 2
266
+ else:
267
+ lo = hi = mean = last = None
268
+ edges = [EdgeTiming(float(e["switchNs"]), bool(e["rising"]), float(e["fromVolts"]), float(e["toVolts"]),
269
+ e.get("driver", ""), e.get("transitionNs"), e.get("skewNs"))
270
+ for e in analog.get("edges") or [] if from_ns <= e["switchNs"] <= to_ns]
271
+ return Measurement(pin, from_ns, to_ns, lo, hi, mean, last, edges, True, wire)
272
+ # Digital net: logic states (1 low, 2 high, 4 floating), plus the rail
273
+ # volts each edge drove to on nodes new enough to report them.
274
+ trace = wire.get("wireTrace") or {}
275
+ LOW, HIGH = 1, 2
276
+ level = {LOW: 0, HIGH: 1}
277
+ volts = [trace.get("initialVolts")] + [e.get("volts") for e in trace.get("edges") or []]
278
+ for bk in trace.get("buckets") or []:
279
+ volts += [bk.get("minVolts"), bk.get("maxVolts")]
280
+ volts = [v for v in volts if v is not None]
281
+ edges: List[EdgeTiming] = []
282
+ prev_state, prev_v = trace.get("initialState"), trace.get("initialVolts")
283
+ for e in trace.get("edges") or []:
284
+ state, v = e.get("state"), e.get("volts")
285
+ if e.get("timeNs", 0) >= from_ns and state in level and prev_state in level and state != prev_state:
286
+ hi_v = v if state == HIGH else prev_v
287
+ edges.append(EdgeTiming(float(e["timeNs"]), state == HIGH,
288
+ float(prev_v) if prev_v is not None else float(level[prev_state]),
289
+ float(v) if v is not None else float(level[state]), "", 0.0, None))
290
+ prev_state, prev_v = state, (v if v is not None else prev_v)
291
+ last = volts[-1] if volts else None
292
+ names = {LOW: "low", HIGH: "high", 4: "floating"}
293
+ final = (trace.get("edges") or [{}])[-1].get("state", trace.get("initialState")) if trace.get("edges") \
294
+ else trace.get("initialState")
295
+ return Measurement(pin, from_ns, to_ns, min(volts) if volts else None, max(volts) if volts else None,
296
+ (sum(volts) / len(volts)) if volts else None, last, edges, False, wire,
297
+ names.get(final, "unknown" if final is not None else None))
298
+
299
+
300
+ class PartHandle:
301
+ """One part on the running board: `board["imu"]`."""
302
+
303
+ def __init__(self, run: "Run", part_id: str):
304
+ self._run, self.id = run, part_id
305
+ self.serial = Serial(run, part_id)
306
+
307
+ @property
308
+ def history(self) -> List[tuple]:
309
+ """Every distinct state this part showed since board.record(part), as (ms, state)."""
310
+ self._run._part_state_now(self.id)
311
+ with self._run._cond:
312
+ return list(self._run._part_history.get(self.id, []))
313
+
314
+ @property
315
+ def state(self) -> Dict[str, Any]:
316
+ """What this part shows right now: an LED's {"intensity": 0-100}, a display's
317
+ pixels, a motor's angle… Live while running; exact while paused."""
318
+ return self._run._part_state_now(self.id)
319
+
320
+ def pin(self, name: str) -> PinHandle:
321
+ return PinHandle(self.id, name)
322
+
323
+ def read(self, *paths: str) -> Any:
324
+ """Chip registers / fields / memory by name: read("I2C0.STATUS"), read("cpu.pc", "mem[0x3fc80000:16]").
325
+
326
+ One path returns a Reading (int(r), r.value, r["FIELD"], r.fields);
327
+ a path covering several registers ("I2C0") returns {path: Reading};
328
+ several paths return {path: Reading-or-dict}. Exact while paused.
329
+ """
330
+ results = self._run._request({"type": "state", "op": "read", "component": self.id, "paths": list(paths)},
331
+ "state")["results"]
332
+ out: Dict[str, Any] = {}
333
+ for p, r in zip(paths, results):
334
+ if r.get("error"):
335
+ raise Sim86Error(f"{self.id}: can't read {p}: {r['error']}")
336
+ readings = [Reading(x) for x in r.get("readings") or []]
337
+ out[p] = readings[0] if len(readings) == 1 else {x.path: x for x in readings}
338
+ return out[paths[0]] if len(paths) == 1 else out
339
+
340
+ def write(self, path: str, value: Union[int, str, List[int]]) -> Dict[str, Any]:
341
+ """Store a value at a chip register/field/memory path while the board is paused."""
342
+ return self._run._request({"type": "state", "op": "write", "component": self.id, "path": path,
343
+ "value": value}, "state")["results"][0]
344
+
345
+ def internals(self) -> Dict[str, Any]:
346
+ """A part's registers decoded, its state in units and recent writes to it."""
347
+ return self._run._request({"type": "state", "op": "internals", "component": self.id}, "state").get(
348
+ "internals", {})
349
+
350
+ def change(self, path: str, value: Union[int, str]) -> Dict[str, Any]:
351
+ """Change a part's register through its own write path, e.g. change("PWR_MGMT_1.SLEEP", "awake")."""
352
+ return self._run._request({"type": "state", "op": "set", "component": self.id, "path": path,
353
+ "value": value, "by": "sim86-cli"}, "state").get("internals", {})
354
+
355
+ def press(self, hold: Union[str, float, None] = None) -> None:
356
+ """Press a button (and release it after `hold` of simulated time)."""
357
+ self._run.event(self.id, "pressed")
358
+ if hold is not None:
359
+ self._run.advance(hold)
360
+ self._run.event(self.id, "released")
361
+
362
+ def release(self) -> None:
363
+ """Let go of a button pressed with press() (no hold)."""
364
+ self._run.event(self.id, "released")
365
+
366
+ def set_input(self, name: str, value: Union[float, List[float]]) -> None:
367
+ """Set what a sensor senses: set_input("temperature", 85) or ("acceleration", [0, 0, 9.8])."""
368
+ values = value if isinstance(value, list) else [value]
369
+ self._run.event(self.id, f"input:{name}=" + ",".join(str(v) for v in values))
370
+
371
+
372
+ def _connect(url: str, **kw: Any) -> Any:
373
+ # websockets >= 16 wants long-lived sync connections opened with legacy=True.
374
+ try:
375
+ return connect(url, legacy=True, **kw)
376
+ except TypeError:
377
+ return connect(url, **kw)
378
+
379
+
380
+ class Run:
381
+ """A run on the Simulator86 cloud, attached over its live socket."""
382
+
383
+ def __init__(self, client: Client, run_id: str, board: Optional[Board] = None,
384
+ frame_listener: Optional[Callable[[Dict[str, Any]], None]] = None):
385
+ self.client, self.id, self.board = client, run_id, board
386
+ self._cond = threading.Condition()
387
+ self._logs: List[LogLine] = []
388
+ self._pending: Dict[str, Dict[str, Any]] = {}
389
+ self._replies: Dict[str, Dict[str, Any]] = {}
390
+ self._ids = itertools.count(1)
391
+ self._ended: Optional[str] = None
392
+ self._closed = False
393
+ self._listeners: List[Callable[[LogLine], None]] = []
394
+ self._frame_listener = frame_listener # every socket frame, as it arrives (sim86 events)
395
+ self.faults: Dict[int, str] = {}
396
+ self._watched: Dict[str, Dict[str, str]] = {}
397
+ self._part_state: Dict[str, Dict[str, Any]] = {}
398
+ self._part_state_t: Dict[str, float] = {}
399
+ self._part_history: Dict[str, List[tuple]] = {}
400
+ self._subscribed: set = set()
401
+ self._floor_ms = 0.0
402
+ self._last_hit: Optional[LogLine] = None
403
+ self.plan_events: List[Dict[str, Any]] = []
404
+ self._ws = _connect(client.ws_url(f"/sdk/runs/{run_id}/attach"),
405
+ subprotocols=[WS_AUTH_PROTOCOL, client._require_key()], # type: ignore[list-item]
406
+ max_size=None, open_timeout=60)
407
+ self._reader = threading.Thread(target=self._read, name=f"sim86-run-{run_id[:8]}", daemon=True)
408
+ self._reader.start()
409
+ # The socket only carries lines printed after it connected; the
410
+ # node's log history has the ones before (boot banners, "ready").
411
+ self._backfill()
412
+
413
+ def _backfill(self) -> None:
414
+ try:
415
+ lines = self.client.run_logs(self.id)["lines"]
416
+ except Sim86Error:
417
+ return
418
+ history = [LogLine(float(l.get("t", 0)), str(l.get("source", "")), str(l.get("line", ""))) for l in lines]
419
+ history = [l for l in history if l.source not in ("node", "sim")]
420
+ with self._cond:
421
+ have: Dict[tuple, int] = {}
422
+ for l in self._logs:
423
+ k = (l.t, l.source, l.line)
424
+ have[k] = have.get(k, 0) + 1
425
+ added = []
426
+ for l in history:
427
+ k = (l.t, l.source, l.line)
428
+ if have.get(k):
429
+ have[k] -= 1
430
+ else:
431
+ added.append(l)
432
+ if added:
433
+ self._logs = sorted(self._logs + added, key=lambda l: l.t)
434
+ self._cond.notify_all()
435
+ listeners = list(self._listeners)
436
+ for cb in listeners:
437
+ for l in added:
438
+ cb(l)
439
+
440
+ # ---- starting ----------------------------------------------------------
441
+
442
+ @classmethod
443
+ def start(cls, board: Board, client: Optional[Client] = None, *, duration: Union[str, float, None] = None,
444
+ realtime: Union[str, float, None] = None, scenario: Optional[Dict[str, Any]] = None,
445
+ seed: Optional[int] = None) -> "Run":
446
+ client = client or Client()
447
+ project = client.runs_project()
448
+ upload_flash_files(board, client, project)
449
+ spec, firmware = run_spec(board, client, project, duration_ms=parse_ms(duration),
450
+ realtime_ms=parse_ms(realtime), scenario=scenario, seed=seed)
451
+ return cls(client, client.create_run(spec, firmware), board)
452
+
453
+ @property
454
+ def url(self) -> str:
455
+ """The live page for this run (board, parts, inputs, serial)."""
456
+ return self.client.live_url(self.id, self.board.name if self.board else None)
457
+
458
+ def __getitem__(self, part_id: str) -> PartHandle:
459
+ if self.board is not None:
460
+ self.board.part(part_id) # clear error for a typo
461
+ return PartHandle(self, part_id)
462
+
463
+ @property
464
+ def radio(self) -> Radio:
465
+ """The board's radio room (its RfEnvironment part), to degrade Wi-Fi/BLE mid-run."""
466
+ if getattr(self, "_radio", None) is None:
467
+ rooms = [p for p in (self.board.parts if self.board else []) if p.type == "RfEnvironment"]
468
+ if not rooms:
469
+ raise Sim86Error("this board has no RfEnvironment part: add one with the radios in config.members")
470
+ self._radio = Radio(self, rooms[0].id, rooms[0].config)
471
+ return self._radio
472
+
473
+ @property
474
+ def serial(self) -> Serial:
475
+ """Output of every part on the board."""
476
+ return Serial(self, None)
477
+
478
+ # ---- socket ------------------------------------------------------------
479
+
480
+ def _read(self) -> None:
481
+ try:
482
+ for raw in self._ws:
483
+ try:
484
+ frame = json.loads(raw)
485
+ except ValueError:
486
+ continue
487
+ self._on_frame(frame)
488
+ except Exception:
489
+ pass
490
+ finally:
491
+ with self._cond:
492
+ self._closed = True
493
+ if self._ended is None:
494
+ self._ended = "disconnected"
495
+ self._cond.notify_all()
496
+
497
+ def _on_frame(self, frame: Dict[str, Any]) -> None:
498
+ if self._frame_listener is not None:
499
+ try:
500
+ self._frame_listener(frame)
501
+ except Exception:
502
+ pass
503
+ kind = frame.get("type")
504
+ rid = frame.get("requestId")
505
+ with self._cond:
506
+ if rid in self._pending:
507
+ self._replies[rid] = frame
508
+ self._cond.notify_all()
509
+ return
510
+ if kind == "log":
511
+ new = [LogLine(float(l.get("t", 0)), str(l.get("source", "")), str(l.get("line", "")))
512
+ for l in frame.get("lines", [])]
513
+ self._logs.extend(new)
514
+ listeners = list(self._listeners)
515
+ self._cond.notify_all()
516
+ elif kind == "data":
517
+ part = str(frame.get("ch", ""))
518
+ for t, value in frame.get("samples") or []:
519
+ if isinstance(value, dict):
520
+ merged = dict(self._part_state.get(part, {}))
521
+ merged.update(value)
522
+ self._part_state[part] = merged
523
+ else:
524
+ self._part_state[part] = {"value": value}
525
+ self._part_state_t[part] = float(t)
526
+ hist = self._part_history.setdefault(part, [])
527
+ if not hist or hist[-1][1] != self._part_state[part]:
528
+ hist.append((float(t), dict(self._part_state[part])))
529
+ if len(hist) > 20000:
530
+ del hist[: len(hist) - 20000]
531
+ self._cond.notify_all()
532
+ return
533
+ elif kind == "fault_event":
534
+ self.plan_events.append(frame)
535
+ self._cond.notify_all()
536
+ return
537
+ elif kind == "done":
538
+ self._ended = str(frame.get("reason") or "done")
539
+ self._cond.notify_all()
540
+ return
541
+ else:
542
+ return
543
+ for cb in listeners:
544
+ for l in new:
545
+ cb(l)
546
+
547
+ def _send(self, frame: Dict[str, Any]) -> None:
548
+ if self._ended is not None:
549
+ raise RunEnded(f"run {self.id} has ended ({self._ended}); start a new one "
550
+ f"(a longer --duration keeps it going)")
551
+ self._ws.send(json.dumps(frame))
552
+
553
+ def _request(self, frame: Dict[str, Any], ok: str, timeout: float = 300) -> Dict[str, Any]:
554
+ # A big board takes a while to build: until it has, the node refuses
555
+ # requests without acting on them, so asking again is safe.
556
+ deadline = time.monotonic() + BOARD_BUILD_PATIENCE_S
557
+ while True:
558
+ try:
559
+ return self._request_once(frame, ok, timeout)
560
+ except Sim86Error as e:
561
+ if "not ready yet" not in str(e) or time.monotonic() >= deadline:
562
+ raise
563
+ time.sleep(0.25)
564
+
565
+ def _request_once(self, frame: Dict[str, Any], ok: str, timeout: float) -> Dict[str, Any]:
566
+ rid = f"py{next(self._ids)}-{secrets.token_hex(4)}"
567
+ with self._cond:
568
+ self._pending[rid] = {"ok": ok}
569
+ self._send({**frame, "requestId": rid})
570
+ deadline = time.monotonic() + timeout
571
+ with self._cond:
572
+ while rid not in self._replies:
573
+ if self._closed:
574
+ self._pending.pop(rid, None)
575
+ raise RunEnded(f"run {self.id} ended ({self._ended}) before it answered")
576
+ left = deadline - time.monotonic()
577
+ if left <= 0:
578
+ self._pending.pop(rid, None)
579
+ raise Sim86Error(f"no answer to {frame.get('type')} within {timeout:.0f} s")
580
+ self._cond.wait(left)
581
+ self._pending.pop(rid, None)
582
+ reply = self._replies.pop(rid)
583
+ if reply.get("type") != ok:
584
+ raise Sim86Error(reply.get("message") or f"{frame.get('type')} failed")
585
+ return reply
586
+
587
+ # ---- time --------------------------------------------------------------
588
+
589
+ def status(self) -> Halt:
590
+ r = self._request({"type": "execution_control", "action": "status"}, "execution")
591
+ return Halt(bool(r.get("paused")), int(r.get("simulationTimeNs") or 0))
592
+
593
+ def pause(self) -> Halt:
594
+ r = self._request({"type": "execution_control", "action": "pause"}, "execution")
595
+ return Halt(bool(r.get("paused")), int(r.get("simulationTimeNs") or 0))
596
+
597
+ def resume(self) -> Halt:
598
+ r = self._request({"type": "execution_control", "action": "resume"}, "execution")
599
+ return Halt(bool(r.get("paused")), int(r.get("simulationTimeNs") or 0))
600
+
601
+ @property
602
+ def time_ms(self) -> float:
603
+ return self.status().time_ms
604
+
605
+ def until(self, edge: Optional[Pin] = None, *, kind: str = "any", nth: int = 1,
606
+ at: Union[str, float, None] = None) -> Halt:
607
+ """Run until the nth edge on a pin (counted from now), or until simulated time `at`, then pause.
608
+
609
+ until(edge="imu.SCL", kind="falling", nth=3) until(at="250ms")
610
+ """
611
+ if (edge is None) == (at is None):
612
+ raise Sim86Error("until() takes either edge=… or at=…")
613
+ if edge is not None:
614
+ if kind not in ("rising", "falling", "any"):
615
+ raise Sim86Error("kind must be 'rising', 'falling' or 'any'")
616
+ target: Dict[str, Any] = {"edge": {"pin": _pin_frame(edge), "kind": kind, "nth": int(nth)}}
617
+ else:
618
+ target = {"timeNs": int(parse_ms(at, "at") * 1e6)} # type: ignore[operator]
619
+ # Wall-clock patience scales with how far the board must run: a slow
620
+ # board (busy display, analog nets) can take longer than real time.
621
+ patience = 1800.0
622
+ if at is not None:
623
+ ahead_s = max(0.0, (parse_ms(at, "at") or 0) / 1000 - self.status().time_ns / 1e9)
624
+ patience = max(300.0, ahead_s * 30)
625
+ r = self._request({"type": "until", **target}, "until", timeout=patience)
626
+ # Output printed just before the stop can still be in flight on the
627
+ # socket: take it from the run's history so the board's output is
628
+ # complete up to the instant it paused.
629
+ self._backfill()
630
+ self._read_from(int(r.get("haltedAtNs") or 0))
631
+ return Halt(bool(r.get("paused", True)), int(r.get("haltedAtNs") or 0),
632
+ None if r.get("edgeAtNs") is None else int(r["edgeAtNs"]))
633
+
634
+ def _read_from(self, time_ns: int) -> None:
635
+ # Lines are stamped in whole simulated ms: keep the ms the stop is in.
636
+ self._floor_ms = float(int(time_ns / 1e6))
637
+ if self._last_hit is not None and self._last_hit.t < self._floor_ms:
638
+ self._last_hit = None
639
+
640
+ def advance(self, duration: Union[str, float]) -> Halt:
641
+ """Run exactly `duration` more simulated time ('5ms', 2000), then pause."""
642
+ now = self.status().time_ns
643
+ return self.until(at=(now + parse_ms(duration) * 1e6) / 1e6) # type: ignore[operator]
644
+
645
+ def _wait_for_line(self, match: Callable[[LogLine], bool], ms: Union[str, float], since_start: bool,
646
+ what: str) -> LogLine:
647
+ window = parse_ms(ms, "ms")
648
+ now = self.status().time_ns
649
+ # Output is read in order, like pexpect: a wait looks after the line
650
+ # the previous wait matched, and after the last until()/advance().
651
+ floor_ms = 0.0 if since_start else self._floor_ms
652
+ after = None if since_start else self._last_hit
653
+
654
+ def find() -> Optional[LogLine]:
655
+ start = 0
656
+ if after is not None:
657
+ start = next((i + 1 for i, l in enumerate(self._logs) if l is after), 0)
658
+ return next((l for l in self._logs[start:] if l.t >= floor_ms and match(l)), None)
659
+
660
+ with self._cond:
661
+ hit = find()
662
+ if hit:
663
+ self._last_hit = hit
664
+ return hit
665
+ deadline_ns = now + int(window * 1e6) # type: ignore[operator]
666
+ rid = f"py{next(self._ids)}-{secrets.token_hex(4)}"
667
+ with self._cond:
668
+ self._pending[rid] = {"ok": "until"}
669
+ # Arm a stop at the deadline: it also resumes a paused board. If the
670
+ # line shows up first the stop is cancelled and the board keeps going.
671
+ self._send({"type": "until", "timeNs": deadline_ns, "requestId": rid})
672
+ with self._cond:
673
+ while True:
674
+ hit = find()
675
+ if hit or rid in self._replies or self._closed or self._ended:
676
+ break
677
+ self._cond.wait(5)
678
+ if not hit:
679
+ # Lines can be skipped on the socket under load; the history has them all.
680
+ self._backfill()
681
+ with self._cond:
682
+ hit = find()
683
+ if hit:
684
+ if rid not in self._replies and not self._ended:
685
+ try:
686
+ self._request({"type": "until", "cancel": True}, "until", timeout=30)
687
+ except Sim86Error:
688
+ pass
689
+ with self._cond:
690
+ self._pending.pop(rid, None)
691
+ self._replies.pop(rid, None)
692
+ self._last_hit = hit
693
+ return hit
694
+ with self._cond:
695
+ self._pending.pop(rid, None)
696
+ reply = self._replies.pop(rid, None)
697
+ if reply is None:
698
+ raise RunEnded(f"run ended ({self._ended}) while waiting for {what}")
699
+ if reply.get("type") != "until":
700
+ raise Sim86Error(reply.get("message") or "until failed")
701
+ tail = "\n".join(str(l) for l in self.serial.lines[-15:]) or "(nothing printed)"
702
+ raise SerialTimeout(f"{what} did not appear within {window:g} ms of simulated time "
703
+ f"(board paused at {deadline_ns / 1e6:.3f} ms). Last output:\n{tail}")
704
+
705
+ # ---- volts and waveforms ----------------------------------------------
706
+
707
+ def _graph_wires(self) -> List[tuple]:
708
+ """The run's wires: from the board file, or from the run itself when
709
+ driving a run started elsewhere (sim86 start / another machine)."""
710
+ if self.board is not None:
711
+ return list(self.board.wires)
712
+ if getattr(self, "_run_wires", None) is None:
713
+ graph = self.client.gql("query($id: UUID!) { runGraph(id: $id) }", {"id": self.id}).get("runGraph") or {}
714
+ self._run_wires = [((e["source"], e.get("sourceHandle") or ""), (e["target"], e.get("targetHandle") or ""))
715
+ for e in graph.get("edges") or []]
716
+ return self._run_wires
717
+
718
+ def _wire_for(self, pin: Pin) -> Dict[str, str]:
719
+ part, name = parse_pin(pin) if isinstance(pin, str) else (pin.part, pin.name)
720
+ other = (part, name)
721
+ for a, b in self._graph_wires():
722
+ if a == (part, name):
723
+ other = b
724
+ break
725
+ if b == (part, name):
726
+ other = a
727
+ break
728
+ return {"id": f"{part}.{name}", "source": part, "sourceHandle": name,
729
+ "target": other[0], "targetHandle": other[1]}
730
+
731
+ def _observe(self, window_ns: int, end_ns: Optional[int] = None, pixels: int = 1024) -> Dict[str, Any]:
732
+ view: Dict[str, Any] = {"windowNs": max(1, int(window_ns)), "pixels": max(16, min(1024, pixels)), "decoders": []}
733
+ if end_ns is not None:
734
+ view["endNs"] = int(end_ns)
735
+ return self._request({"type": "observe", "wires": list(self._watched.values()), "view": view},
736
+ "observe")["snapshot"]
737
+
738
+ def watch(self, *pins: Pin) -> None:
739
+ """Start recording these nets (every edge, and volts on analog nets) from now."""
740
+ for pin in pins:
741
+ w = self._wire_for(pin)
742
+ self._watched[w["id"]] = w
743
+ if len(self._watched) > 64:
744
+ raise Sim86Error("at most 64 nets can be recorded at once")
745
+ self._observe(1000, pixels=16)
746
+
747
+ def measure(self, pin: Pin, over: Union[str, float]) -> Measurement:
748
+ """Volts and edges on a net over the last `over` of simulated time.
749
+
750
+ A net not yet recorded starts recording now and the board runs `over`
751
+ first. measure("U3.SDA", over="5ms").rising[0].rise_ns
752
+ """
753
+ key = self._wire_for(pin)["id"]
754
+ window = int(parse_ms(over, "over") * 1e6) # type: ignore[operator]
755
+ if key not in self._watched:
756
+ self.watch(pin)
757
+ self.advance(over)
758
+ now = self.status().time_ns
759
+ snap = self._observe(window, end_ns=now)
760
+ wire = next((w for w in snap.get("wires", []) if w.get("id") == key), None)
761
+ if wire is None:
762
+ raise Sim86Error(f"{key}: the simulator returned no recording for this net")
763
+ return _measurement(key, wire, now - window, now)
764
+
765
+ def volts(self, pin: Pin) -> float:
766
+ """A net's voltage right now (exact on analog nets; the rail level on digital ones)."""
767
+ key = self._wire_for(pin)["id"]
768
+ if key not in self._watched:
769
+ self.watch(pin)
770
+ self.advance("10us")
771
+ m = self.measure(pin, over="10us")
772
+ if m.last is None:
773
+ raise Sim86Error(f"{key}: no voltage recorded. Volts come from the analog layer "
774
+ f"(and rail volts on digital nets) on simulator versions from 2026-11-06")
775
+ return m.last
776
+
777
+ # ---- inputs, faults ----------------------------------------------------
778
+
779
+ def _part_state_now(self, part: str, timeout: float = 10.0) -> Dict[str, Any]:
780
+ if part not in self._subscribed:
781
+ self._subscribed.add(part)
782
+ self._send({"type": "subscribe", "component": part})
783
+ deadline = time.monotonic() + timeout
784
+ with self._cond:
785
+ while part not in self._part_state:
786
+ left = deadline - time.monotonic()
787
+ if left <= 0 or self._closed:
788
+ raise Sim86Error(f"{part} reports no live state (only parts that show something do: "
789
+ f"LEDs, displays, motors, buzzers…)")
790
+ self._cond.wait(left)
791
+ return dict(self._part_state[part])
792
+
793
+ def record(self, *parts: str) -> None:
794
+ """Start keeping every state these parts show (board[part].history).
795
+ Call it early: history starts when recording does."""
796
+ for part in parts:
797
+ self._part_state_now(part)
798
+
799
+ def wait_until(self, condition: Callable[[], bool], ms: Union[str, float] = 1000,
800
+ step: Union[str, float] = "20ms", what: str = "the condition") -> float:
801
+ """Advance in `step` slices of simulated time until condition() holds;
802
+ returns the simulated time (ms) it first held. Deterministic."""
803
+ window = parse_ms(ms, "ms") or 0
804
+ start = self.status().time_ms
805
+ while True:
806
+ if condition():
807
+ return self.status().time_ms
808
+ if self.status().time_ms - start >= window:
809
+ raise SerialTimeout(f"{what} did not happen within {window:g} ms of simulated time")
810
+ self.advance(step)
811
+
812
+ def note(self, text: str) -> None:
813
+ """Say what you're doing, for everyone watching the run live ("▶ heating test")."""
814
+ if self._ended is None:
815
+ self._send({"type": "note", "text": text})
816
+
817
+ @property
818
+ def activity(self) -> List[LogLine]:
819
+ """What programs did to this run (stops, faults, inputs, notes), as the node recorded it."""
820
+ with self._cond:
821
+ return [l for l in self._logs if l.source in ("driver", "test")]
822
+
823
+ def event(self, part: str, action: str, at: Union[str, float, None] = None) -> None:
824
+ frame: Dict[str, Any] = {"type": "event", "component": part, "action": action}
825
+ if at is not None:
826
+ # Whole milliseconds: the simulator ignores a fractional atMs and
827
+ # would apply the event at once.
828
+ frame["atMs"] = int(round(parse_ms(at, "at"))) # type: ignore[arg-type]
829
+ self._send(frame)
830
+
831
+ def _fault(self, fault: Dict[str, Any], label: str) -> int:
832
+ fid = int(self._request({"type": "fault", "op": "apply", "fault": fault}, "fault")["id"])
833
+ self.faults[fid] = label
834
+ return fid
835
+
836
+ def short(self, pin: Pin, to: str = "gnd") -> int:
837
+ """Tie the net on `pin` to "gnd" or "vcc". Returns a fault id for clear()."""
838
+ if to not in ("gnd", "vcc"):
839
+ raise Sim86Error("short(pin, to): to is 'gnd' or 'vcc'")
840
+ return self._fault({"kind": "short", "pin": _pin_frame(pin), "to": to}, f"short {pin} to {to}")
841
+
842
+ def open(self, a: Pin, b: Pin) -> int:
843
+ """Break the wire between two pins."""
844
+ return self._fault({"kind": "open", "a": _pin_frame(a), "b": _pin_frame(b)}, f"open {a} / {b}")
845
+
846
+ def bridge(self, a: Pin, b: Pin) -> int:
847
+ """Join the nets on two pins, like a solder bridge."""
848
+ return self._fault({"kind": "bridge", "a": _pin_frame(a), "b": _pin_frame(b)}, f"bridge {a} + {b}")
849
+
850
+ def drive(self, pin: Pin, steps: List[List[Union[int, float]]], repeat: Union[str, float, None] = None) -> int:
851
+ """Force a waveform onto a net: steps = [[at_ns, level], …], level 0/1; repeat period optional."""
852
+ frame = {"kind": "drive", "pin": _pin_frame(pin), "steps": steps,
853
+ "repeatNs": None if repeat is None else int(parse_ms(repeat) * 1e6)} # type: ignore[operator]
854
+ return self._fault(frame, f"drive {pin}")
855
+
856
+ def clear(self, fault_id: Optional[int] = None) -> None:
857
+ """Remove one fault, or every fault this run applied."""
858
+ ids = [fault_id] if fault_id is not None else list(self.faults)
859
+ for fid in ids:
860
+ self._request({"type": "fault", "op": "clear", "id": fid}, "fault")
861
+ self.faults.pop(fid, None)
862
+
863
+ # ---- lifecycle ---------------------------------------------------------
864
+
865
+ def on_line(self, cb: Callable[[LogLine], None]) -> None:
866
+ with self._cond:
867
+ self._listeners.append(cb)
868
+
869
+ @property
870
+ def ended(self) -> Optional[str]:
871
+ return self._ended
872
+
873
+ def wait_done(self, timeout: Optional[float] = None) -> str:
874
+ """Block until the run ends; returns why (duration, firmware exit, stopped …)."""
875
+ end = None if timeout is None else time.monotonic() + timeout
876
+ with self._cond:
877
+ while self._ended is None:
878
+ left = None if end is None else end - time.monotonic()
879
+ if left is not None and left <= 0:
880
+ break
881
+ self._cond.wait(left if left is not None else 1)
882
+ return self._ended or "running"
883
+
884
+ def stop(self) -> None:
885
+ if self._ended is None or self._ended == "disconnected":
886
+ try:
887
+ self.client.stop_run(self.id)
888
+ except Sim86Error:
889
+ pass
890
+ self.close()
891
+
892
+ def close(self) -> None:
893
+ try:
894
+ self._ws.close()
895
+ except Exception:
896
+ pass
897
+
898
+ def __enter__(self) -> "Run":
899
+ return self
900
+
901
+ def __exit__(self, *exc: Any) -> None:
902
+ self.stop()