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/__init__.py +26 -0
- sim86/_build.py +1 -0
- sim86/api.py +368 -0
- sim86/board.py +422 -0
- sim86/cli.py +750 -0
- sim86/pytest_plugin.py +137 -0
- sim86/run.py +902 -0
- sim86/session.py +592 -0
- sim86-0.1.0.dist-info/METADATA +416 -0
- sim86-0.1.0.dist-info/RECORD +12 -0
- sim86-0.1.0.dist-info/WHEEL +4 -0
- sim86-0.1.0.dist-info/entry_points.txt +5 -0
sim86/session.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
"""Drive a running board from the shell, one command at a time.
|
|
2
|
+
|
|
3
|
+
sim86 start board.json the run keeps going on the cloud
|
|
4
|
+
sim86 events last what happens on it, as JSON lines
|
|
5
|
+
sim86 press last mute --hold 200ms act on it
|
|
6
|
+
sim86 wait last "ready" --ms 2000 wait for output (simulated time)
|
|
7
|
+
|
|
8
|
+
Every command prints one JSON object (events prints one per line) and exits
|
|
9
|
+
non-zero on failure, so agents and scripts can chain them. `last` is the run
|
|
10
|
+
`sim86 start` started most recently on this machine.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Any, Dict, List, Optional
|
|
21
|
+
|
|
22
|
+
from .api import Client, Sim86Error, load_config, save_config
|
|
23
|
+
from .board import load_board, parse_ms
|
|
24
|
+
|
|
25
|
+
LAST = ("last", "-")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def emit(obj: Dict[str, Any]) -> None:
|
|
29
|
+
print(json.dumps(obj, ensure_ascii=False), flush=True)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_CSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def shown(line: str) -> str:
|
|
36
|
+
"""A console line as a terminal shows it: a carriage return starts the
|
|
37
|
+
line over (a shell redrawing its prompt), and colour and cursor codes are
|
|
38
|
+
dropped. Matching still uses the raw line."""
|
|
39
|
+
return _CSI.sub("", line.rstrip("\r").rsplit("\r", 1)[-1])
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def resolve_run(arg: str) -> str:
|
|
43
|
+
if arg in LAST:
|
|
44
|
+
run = load_config().get("lastRun")
|
|
45
|
+
if not run:
|
|
46
|
+
raise Sim86Error("no run started yet on this machine: `sim86 start board.json` first")
|
|
47
|
+
return run
|
|
48
|
+
return arg
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def remember(run_id: str) -> None:
|
|
52
|
+
cfg = load_config()
|
|
53
|
+
cfg["lastRun"] = run_id
|
|
54
|
+
save_config(cfg)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _runstate(run_id: str) -> Dict[str, Any]:
|
|
58
|
+
return (load_config().get("runs") or {}).get(run_id, {})
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _save_runstate(run_id: str, **changes: Any) -> None:
|
|
62
|
+
cfg = load_config()
|
|
63
|
+
runs = cfg.setdefault("runs", {})
|
|
64
|
+
entry = runs.setdefault(run_id, {})
|
|
65
|
+
entry.update(changes)
|
|
66
|
+
# keep the 20 most recent runs
|
|
67
|
+
for old in list(runs)[:-20]:
|
|
68
|
+
runs.pop(old, None)
|
|
69
|
+
save_config(cfg)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def acted(run, at_ms: Optional[float] = None) -> None: # noqa: ANN001
|
|
73
|
+
"""Remember when this command acted: `wait` looks at output from here on,
|
|
74
|
+
so lines printed between two commands are never missed."""
|
|
75
|
+
if at_ms is None:
|
|
76
|
+
at_ms = run.status().time_ms
|
|
77
|
+
_save_runstate(run.id, cursor=float(int(at_ms)))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def attach(args: argparse.Namespace, **kw: Any):
|
|
81
|
+
from .run import Run, RunEnded
|
|
82
|
+
|
|
83
|
+
client = Client(target=args.target)
|
|
84
|
+
run_id = resolve_run(args.run)
|
|
85
|
+
try:
|
|
86
|
+
run = Run(client, run_id, None, **kw)
|
|
87
|
+
except Exception as e: # noqa: BLE001
|
|
88
|
+
raise Sim86Error(f"can't reach run {run_id}: {e}") from None
|
|
89
|
+
if run.ended and run.ended != "disconnected":
|
|
90
|
+
reason = run.ended
|
|
91
|
+
run.close()
|
|
92
|
+
raise RunEnded(f"run {run_id} has ended ({reason}). Start a new one; `sim86 start board.json "
|
|
93
|
+
f"--duration 30m` runs longer, and --step keeps it paused between commands")
|
|
94
|
+
return run
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---- commands -----------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
def cmd_start(args: argparse.Namespace) -> int:
|
|
102
|
+
from .run import Run
|
|
103
|
+
|
|
104
|
+
client = Client(target=args.target)
|
|
105
|
+
board = load_board(args.board)
|
|
106
|
+
scenario = json.loads(open(args.scenario).read()) if args.scenario else None
|
|
107
|
+
# A session is interactive: the board file's `limits` are for `run` and
|
|
108
|
+
# tests, so they don't cut a session short. --duration sets it.
|
|
109
|
+
run = Run.start(board, client, duration=args.duration or "10m",
|
|
110
|
+
realtime=args.realtime or "30m", scenario=scenario, seed=args.seed)
|
|
111
|
+
remember(run.id)
|
|
112
|
+
step = args.step or args.paused
|
|
113
|
+
_save_runstate(run.id, step=bool(step))
|
|
114
|
+
if step:
|
|
115
|
+
run.pause()
|
|
116
|
+
interactive = sys.stdout.isatty() and not os.environ.get("CI")
|
|
117
|
+
if args.open or (interactive and not args.no_open):
|
|
118
|
+
client.open_live(run.url)
|
|
119
|
+
emit({"run": run.id, "url": run.url, "paused": bool(step), "step": bool(step),
|
|
120
|
+
"duration": args.duration or "10m"})
|
|
121
|
+
run.close() # the run keeps going on the cloud
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
_SOURCE_TYPES = {"driver": "action", "test": "note", "scenario": "plan", "node": "node", "sim": "node"}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def cmd_events(args: argparse.Namespace) -> int:
|
|
129
|
+
types = set(args.type.split(",")) if args.type else None
|
|
130
|
+
grep = re.compile(args.grep) if args.grep else None
|
|
131
|
+
printed: Dict[tuple, int] = {}
|
|
132
|
+
last_exec: Dict[str, Any] = {}
|
|
133
|
+
last_state: Dict[str, str] = {}
|
|
134
|
+
ended = {"reason": None}
|
|
135
|
+
|
|
136
|
+
def out(event: Dict[str, Any]) -> None:
|
|
137
|
+
if types and event["type"] not in types:
|
|
138
|
+
return
|
|
139
|
+
if args.part and event.get("part") not in (None, args.part):
|
|
140
|
+
return
|
|
141
|
+
if grep and not grep.search(json.dumps(event, ensure_ascii=False)):
|
|
142
|
+
return
|
|
143
|
+
emit(event)
|
|
144
|
+
|
|
145
|
+
def line_event(t: float, source: str, line: str) -> None:
|
|
146
|
+
key = (t, source, line)
|
|
147
|
+
if printed.get(key, 0) > 0:
|
|
148
|
+
printed[key] -= 1 # already printed from the history
|
|
149
|
+
return
|
|
150
|
+
kind = _SOURCE_TYPES.get(source)
|
|
151
|
+
if kind:
|
|
152
|
+
out({"t": t, "type": kind, "what": line})
|
|
153
|
+
else:
|
|
154
|
+
part, _, channel = source.partition(":")
|
|
155
|
+
out({"t": t, "type": "serial", "part": part, "channel": channel, "line": shown(line)})
|
|
156
|
+
|
|
157
|
+
def on_frame(frame: Dict[str, Any]) -> None:
|
|
158
|
+
kind = frame.get("type")
|
|
159
|
+
if kind == "log":
|
|
160
|
+
for l in frame.get("lines") or []:
|
|
161
|
+
line_event(float(l.get("t", 0)), str(l.get("source", "")), str(l.get("line", "")))
|
|
162
|
+
elif kind == "execution":
|
|
163
|
+
now = {"paused": bool(frame.get("paused")), "at_ms": (frame.get("simulationTimeNs") or 0) / 1e6}
|
|
164
|
+
if now["paused"] != last_exec.get("paused"):
|
|
165
|
+
out({"t": now["at_ms"], "type": "paused" if now["paused"] else "running", "at_ms": now["at_ms"]})
|
|
166
|
+
last_exec.update(now)
|
|
167
|
+
elif kind == "fault_event":
|
|
168
|
+
out({"t": (frame.get("atNs") or 0) / 1e6, "type": "plan", "plan": frame.get("plan"),
|
|
169
|
+
"event": frame.get("event"), "action": frame.get("action"), "message": frame.get("message")})
|
|
170
|
+
elif kind == "state" and args.state:
|
|
171
|
+
t = float(frame.get("t") or 0)
|
|
172
|
+
for part, value in (frame.get("ui") or {}).items():
|
|
173
|
+
if not value:
|
|
174
|
+
continue
|
|
175
|
+
text = json.dumps(value, sort_keys=True)
|
|
176
|
+
if len(text) > 400 and not args.full_state:
|
|
177
|
+
text = json.dumps({"changed": True})
|
|
178
|
+
if last_state.get(part) != text:
|
|
179
|
+
last_state[part] = text
|
|
180
|
+
out({"t": t, "type": "state", "part": part, "value": json.loads(text)})
|
|
181
|
+
elif kind == "done":
|
|
182
|
+
ended["reason"] = str(frame.get("reason") or "done")
|
|
183
|
+
|
|
184
|
+
run = attach(args, frame_listener=on_frame)
|
|
185
|
+
try:
|
|
186
|
+
if args.state:
|
|
187
|
+
run._send({"type": "subscribe", "component": "*", "throttleMs": 50})
|
|
188
|
+
if not args.new:
|
|
189
|
+
with run._cond:
|
|
190
|
+
history = list(run._logs)
|
|
191
|
+
for l in history:
|
|
192
|
+
key = (l.t, l.source, l.line)
|
|
193
|
+
printed[key] = printed.get(key, 0) + 1
|
|
194
|
+
line_event(l.t, l.source, l.line)
|
|
195
|
+
printed[key] -= 1
|
|
196
|
+
if args.until_text:
|
|
197
|
+
pattern = args.until_text
|
|
198
|
+
seen = threading_event()
|
|
199
|
+
prev = run._frame_listener
|
|
200
|
+
|
|
201
|
+
def stop_on(frame: Dict[str, Any]) -> None:
|
|
202
|
+
if prev:
|
|
203
|
+
prev(frame)
|
|
204
|
+
for l in frame.get("lines") or []:
|
|
205
|
+
if pattern in str(l.get("line", "")):
|
|
206
|
+
seen.set()
|
|
207
|
+
run._frame_listener = stop_on
|
|
208
|
+
seen.wait(args.wall)
|
|
209
|
+
else:
|
|
210
|
+
run.wait_done(timeout=args.wall)
|
|
211
|
+
if ended["reason"]:
|
|
212
|
+
out({"type": "ended", "reason": ended["reason"]})
|
|
213
|
+
except KeyboardInterrupt:
|
|
214
|
+
pass
|
|
215
|
+
finally:
|
|
216
|
+
run.close()
|
|
217
|
+
return 0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def threading_event():
|
|
221
|
+
import threading
|
|
222
|
+
|
|
223
|
+
return threading.Event()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cmd_status(args: argparse.Namespace) -> int:
|
|
227
|
+
run = attach(args)
|
|
228
|
+
try:
|
|
229
|
+
h = run.status()
|
|
230
|
+
emit({"run": run.id, "paused": h.paused, "at_ms": h.time_ms, "ended": run.ended})
|
|
231
|
+
finally:
|
|
232
|
+
run.close()
|
|
233
|
+
return 0
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _control(args: argparse.Namespace, action: str) -> int:
|
|
237
|
+
run = attach(args)
|
|
238
|
+
try:
|
|
239
|
+
h = run.pause() if action == "pause" else run.resume()
|
|
240
|
+
acted(run, h.time_ms)
|
|
241
|
+
emit({"paused": h.paused, "at_ms": h.time_ms})
|
|
242
|
+
finally:
|
|
243
|
+
run.close()
|
|
244
|
+
return 0
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def cmd_pause(args: argparse.Namespace) -> int:
|
|
248
|
+
return _control(args, "pause")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def cmd_resume(args: argparse.Namespace) -> int:
|
|
252
|
+
return _control(args, "resume")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def cmd_until(args: argparse.Namespace) -> int:
|
|
256
|
+
run = attach(args)
|
|
257
|
+
try:
|
|
258
|
+
if args.edge:
|
|
259
|
+
kind = "rising" if args.rising else "falling" if args.falling else "any"
|
|
260
|
+
h = run.until(edge=args.edge, kind=kind, nth=args.nth)
|
|
261
|
+
elif args.at:
|
|
262
|
+
h = run.until(at=args.at)
|
|
263
|
+
else:
|
|
264
|
+
raise Sim86Error("until needs --edge PIN or --at TIME")
|
|
265
|
+
acted(run, h.time_ms)
|
|
266
|
+
emit({"paused": h.paused, "at_ms": h.time_ms,
|
|
267
|
+
**({"edge_at_ms": h.edge_at_ns / 1e6} if h.edge_at_ns is not None else {})})
|
|
268
|
+
finally:
|
|
269
|
+
run.close()
|
|
270
|
+
return 0
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def cmd_advance(args: argparse.Namespace) -> int:
|
|
274
|
+
run = attach(args)
|
|
275
|
+
try:
|
|
276
|
+
h = run.advance(args.duration)
|
|
277
|
+
acted(run, h.time_ms)
|
|
278
|
+
emit({"paused": h.paused, "at_ms": h.time_ms})
|
|
279
|
+
finally:
|
|
280
|
+
run.close()
|
|
281
|
+
return 0
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def cmd_wait(args: argparse.Namespace) -> int:
|
|
285
|
+
from .run import SerialTimeout
|
|
286
|
+
|
|
287
|
+
run = attach(args)
|
|
288
|
+
try:
|
|
289
|
+
if not args.since_start:
|
|
290
|
+
# From the last action (or the last match) on; from now if none.
|
|
291
|
+
cursor = _runstate(run.id).get("cursor")
|
|
292
|
+
run._read_from(int((cursor if cursor is not None else run.status().time_ms) * 1e6))
|
|
293
|
+
after = _runstate(run.id).get("after")
|
|
294
|
+
if after:
|
|
295
|
+
run._last_hit = next((l for l in run._logs if [l.t, l.source, l.line] == after), None)
|
|
296
|
+
serial = run[args.part].serial if args.part else run.serial
|
|
297
|
+
if _runstate(run.id).get("step"):
|
|
298
|
+
hit = _step_wait(run, serial, args)
|
|
299
|
+
if hit is None:
|
|
300
|
+
emit({"found": False, "error": f"{args.text!r} did not appear within {args.ms} ms of simulated time",
|
|
301
|
+
"paused_at_ms": run.status().time_ms})
|
|
302
|
+
return 1
|
|
303
|
+
_save_runstate(run.id, cursor=hit.t, after=[hit.t, hit.source, hit.line])
|
|
304
|
+
emit({"found": True, "t": hit.t, "source": hit.source, "line": shown(hit.line),
|
|
305
|
+
"paused_at_ms": run.status().time_ms})
|
|
306
|
+
return 0
|
|
307
|
+
try:
|
|
308
|
+
hit = serial.wait_for(args.text, ms=args.ms, since_start=args.since_start)
|
|
309
|
+
except SerialTimeout as e:
|
|
310
|
+
emit({"found": False, "error": str(e).splitlines()[0], "paused_at_ms": run.status().time_ms})
|
|
311
|
+
return 1
|
|
312
|
+
_save_runstate(run.id, cursor=hit.t, after=[hit.t, hit.source, hit.line])
|
|
313
|
+
paused_at = None
|
|
314
|
+
if _runstate(run.id).get("step"):
|
|
315
|
+
paused_at = run.pause().time_ms # step mode: stop right after the match
|
|
316
|
+
emit({"found": True, "t": hit.t, "source": hit.source, "line": shown(hit.line),
|
|
317
|
+
**({"paused_at_ms": paused_at} if paused_at is not None else {})})
|
|
318
|
+
finally:
|
|
319
|
+
run.close()
|
|
320
|
+
return 0
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
STEP_SLICE_MS = 50.0
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _step_wait(run, serial, args): # noqa: ANN001
|
|
327
|
+
"""Step mode: advance in fixed slices of simulated time and look after
|
|
328
|
+
each one, so the board stops within one slice of the match however slow
|
|
329
|
+
the network or the caller is (deterministic, unlike a free-running wait)."""
|
|
330
|
+
window = parse_ms(args.ms, "--ms") or 0
|
|
331
|
+
start = run.status().time_ms
|
|
332
|
+
floor = 0.0 if args.since_start else run._floor_ms
|
|
333
|
+
after = None if args.since_start else run._last_hit
|
|
334
|
+
|
|
335
|
+
def find():
|
|
336
|
+
with run._cond:
|
|
337
|
+
logs = list(run._logs)
|
|
338
|
+
begin = 0
|
|
339
|
+
if after is not None:
|
|
340
|
+
begin = next((i + 1 for i, l in enumerate(logs) if l is after), 0)
|
|
341
|
+
return next((l for l in logs[begin:] if l.t >= floor and serial._match(l) and args.text in l.line), None)
|
|
342
|
+
|
|
343
|
+
hit = find()
|
|
344
|
+
while hit is None and run.status().time_ms - start < window:
|
|
345
|
+
run.advance(min(STEP_SLICE_MS, window - (run.status().time_ms - start)) or STEP_SLICE_MS)
|
|
346
|
+
hit = find() # advance() fills in output up to the stop
|
|
347
|
+
return hit
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def cmd_press(args: argparse.Namespace) -> int:
|
|
351
|
+
run = attach(args)
|
|
352
|
+
try:
|
|
353
|
+
acted(run)
|
|
354
|
+
if args.release:
|
|
355
|
+
run[args.part].release()
|
|
356
|
+
elif args.hold:
|
|
357
|
+
# --hold times the release exactly by advancing the board, which
|
|
358
|
+
# leaves it paused. A running board is paused first, or it would
|
|
359
|
+
# keep going while the advance request travels and the hold would
|
|
360
|
+
# stretch by the round trip; then it keeps running.
|
|
361
|
+
was_running = not run.status().paused
|
|
362
|
+
if was_running:
|
|
363
|
+
run.pause()
|
|
364
|
+
run[args.part].press(hold=args.hold)
|
|
365
|
+
if was_running:
|
|
366
|
+
run.resume()
|
|
367
|
+
else:
|
|
368
|
+
run[args.part].press()
|
|
369
|
+
emit({"ok": True, "part": args.part, "action": "released" if args.release else "pressed",
|
|
370
|
+
**({"held": args.hold} if args.hold else {})})
|
|
371
|
+
finally:
|
|
372
|
+
run.close()
|
|
373
|
+
return 0
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def cmd_input(args: argparse.Namespace) -> int:
|
|
377
|
+
run = attach(args)
|
|
378
|
+
try:
|
|
379
|
+
name, _, raw = args.setting.partition("=")
|
|
380
|
+
if not raw:
|
|
381
|
+
raise Sim86Error("input takes NAME=VALUE, e.g. temperature=72 or acceleration=0,0,9.8")
|
|
382
|
+
values = [float(v) for v in raw.split(",")]
|
|
383
|
+
acted(run)
|
|
384
|
+
run[args.part].set_input(name, values if len(values) > 1 else values[0])
|
|
385
|
+
emit({"ok": True, "part": args.part, "input": name, "value": values if len(values) > 1 else values[0]})
|
|
386
|
+
finally:
|
|
387
|
+
run.close()
|
|
388
|
+
return 0
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def cmd_event(args: argparse.Namespace) -> int:
|
|
392
|
+
run = attach(args)
|
|
393
|
+
try:
|
|
394
|
+
acted(run)
|
|
395
|
+
run.event(args.part, args.action, at=args.at)
|
|
396
|
+
emit({"ok": True, "part": args.part, "action": args.action})
|
|
397
|
+
finally:
|
|
398
|
+
run.close()
|
|
399
|
+
return 0
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def cmd_fault(args: argparse.Namespace) -> int:
|
|
403
|
+
run = attach(args)
|
|
404
|
+
try:
|
|
405
|
+
kind, rest = args.kind, args.pins
|
|
406
|
+
active = list(_runstate(run.id).get("faults") or [])
|
|
407
|
+
if kind != "clear":
|
|
408
|
+
acted(run)
|
|
409
|
+
if kind == "short":
|
|
410
|
+
if len(rest) != 2 or rest[1] not in ("gnd", "vcc"):
|
|
411
|
+
raise Sim86Error("fault short PIN gnd|vcc")
|
|
412
|
+
fid = run.short(rest[0], rest[1])
|
|
413
|
+
_save_runstate(run.id, faults=active + [fid])
|
|
414
|
+
emit({"fault": fid, "what": f"short {rest[0]} to {rest[1]}"})
|
|
415
|
+
elif kind in ("open", "bridge"):
|
|
416
|
+
if len(rest) != 2:
|
|
417
|
+
raise Sim86Error(f"fault {kind} PIN_A PIN_B")
|
|
418
|
+
fid = run.open(rest[0], rest[1]) if kind == "open" else run.bridge(rest[0], rest[1])
|
|
419
|
+
_save_runstate(run.id, faults=active + [fid])
|
|
420
|
+
emit({"fault": fid, "what": f"{kind} {rest[0]} {rest[1]}"})
|
|
421
|
+
elif kind == "clear":
|
|
422
|
+
ids = [int(x) for x in rest] or active
|
|
423
|
+
if not ids:
|
|
424
|
+
emit({"cleared": [], "note": "no faults applied from this machine; pass ids to clear others"})
|
|
425
|
+
return 0
|
|
426
|
+
acted(run)
|
|
427
|
+
results = {fid: bool(run._request({"type": "fault", "op": "clear", "id": fid}, "fault").get("cleared"))
|
|
428
|
+
for fid in ids}
|
|
429
|
+
_save_runstate(run.id, faults=[f for f in active if f not in results])
|
|
430
|
+
emit({"cleared": [f for f, ok in results.items() if ok],
|
|
431
|
+
"not_active": [f for f, ok in results.items() if not ok]})
|
|
432
|
+
return 0 if all(results.values()) else 1
|
|
433
|
+
else:
|
|
434
|
+
raise Sim86Error("fault short|open|bridge|clear")
|
|
435
|
+
finally:
|
|
436
|
+
run.close()
|
|
437
|
+
return 0
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _reading_json(r: Any) -> Any:
|
|
441
|
+
if isinstance(r, dict):
|
|
442
|
+
return {k: _reading_json(v) for k, v in r.items()}
|
|
443
|
+
return {"path": r.path, "value": r.value, "hex": r.raw.get("hex"), "meaning": r.meaning,
|
|
444
|
+
"fields": r.fields or None, "bytes": r.bytes}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def cmd_read(args: argparse.Namespace) -> int:
|
|
448
|
+
run = attach(args)
|
|
449
|
+
try:
|
|
450
|
+
r = run[args.part].read(*args.paths)
|
|
451
|
+
emit({"part": args.part, "readings": _reading_json(r) if len(args.paths) > 1 else {args.paths[0]: _reading_json(r)}})
|
|
452
|
+
finally:
|
|
453
|
+
run.close()
|
|
454
|
+
return 0
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def cmd_write(args: argparse.Namespace) -> int:
|
|
458
|
+
run = attach(args)
|
|
459
|
+
try:
|
|
460
|
+
value: Any = args.value
|
|
461
|
+
try:
|
|
462
|
+
value = int(value, 0)
|
|
463
|
+
except ValueError:
|
|
464
|
+
pass
|
|
465
|
+
acted(run)
|
|
466
|
+
emit({"part": args.part, "result": run[args.part].write(args.path, value)})
|
|
467
|
+
finally:
|
|
468
|
+
run.close()
|
|
469
|
+
return 0
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def cmd_state(args: argparse.Namespace) -> int:
|
|
473
|
+
run = attach(args)
|
|
474
|
+
try:
|
|
475
|
+
emit({"part": args.part, "state": run[args.part].state})
|
|
476
|
+
finally:
|
|
477
|
+
run.close()
|
|
478
|
+
return 0
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def cmd_inside(args: argparse.Namespace) -> int:
|
|
482
|
+
run = attach(args)
|
|
483
|
+
try:
|
|
484
|
+
emit({"part": args.part, "internals": run[args.part].internals()})
|
|
485
|
+
finally:
|
|
486
|
+
run.close()
|
|
487
|
+
return 0
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def cmd_measure(args: argparse.Namespace) -> int:
|
|
491
|
+
run = attach(args)
|
|
492
|
+
try:
|
|
493
|
+
m = run.measure(args.pin, over=args.over)
|
|
494
|
+
emit({"pin": m.pin, "from_ms": m.from_ns / 1e6, "to_ms": m.to_ns / 1e6, "analog": m.analog, "level": m.level,
|
|
495
|
+
"min_v": m.min, "max_v": m.max, "mean_v": m.mean, "last_v": m.last,
|
|
496
|
+
"edges": len(m.edges), "rising": len(m.rising), "falling": len(m.falling),
|
|
497
|
+
"rise_ns": [e.rise_ns for e in m.rising if e.rise_ns][:20] or None,
|
|
498
|
+
"fall_ns": [e.fall_ns for e in m.falling if e.fall_ns][:20] or None})
|
|
499
|
+
finally:
|
|
500
|
+
run.close()
|
|
501
|
+
return 0
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def cmd_note(args: argparse.Namespace) -> int:
|
|
505
|
+
run = attach(args)
|
|
506
|
+
try:
|
|
507
|
+
run.note(args.text)
|
|
508
|
+
emit({"ok": True})
|
|
509
|
+
finally:
|
|
510
|
+
run.close()
|
|
511
|
+
return 0
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def add_commands(sub: Any, common: Any) -> None:
|
|
515
|
+
"""Register the session commands on the main parser."""
|
|
516
|
+
def cmd(name: str, fn: Any, help_: str, run: bool = True) -> argparse.ArgumentParser:
|
|
517
|
+
p = sub.add_parser(name, help=help_)
|
|
518
|
+
if run:
|
|
519
|
+
p.add_argument("run", help="run id, or `last`")
|
|
520
|
+
p.set_defaults(fn=fn)
|
|
521
|
+
return p
|
|
522
|
+
|
|
523
|
+
p = cmd("start", cmd_start, "start a run that keeps going; prints its id (then drive it with the commands below)", run=False)
|
|
524
|
+
p.add_argument("board")
|
|
525
|
+
p.add_argument("--duration", help="simulated time it may run (default 10m; the board file's limits don't apply)")
|
|
526
|
+
p.add_argument("--realtime", help="wall-clock cap (default 30m)")
|
|
527
|
+
p.add_argument("--scenario")
|
|
528
|
+
p.add_argument("--seed", type=int)
|
|
529
|
+
p.add_argument("--step", action="store_true",
|
|
530
|
+
help="step mode: the board only moves inside wait/advance/until and stays paused between "
|
|
531
|
+
"commands, so fault windows and timings are exact however slow you are")
|
|
532
|
+
p.add_argument("--paused", action="store_true", help=argparse.SUPPRESS) # old name of --step
|
|
533
|
+
p.add_argument("--open", action="store_true", help="open the live page (default at a terminal)")
|
|
534
|
+
p.add_argument("--no-open", action="store_true", help="don't open the live page")
|
|
535
|
+
|
|
536
|
+
p = cmd("events", cmd_events, "stream what happens on a run as JSON lines (history first, then live)")
|
|
537
|
+
p.add_argument("--new", action="store_true", help="skip what already happened")
|
|
538
|
+
p.add_argument("--type", help="only these types: serial,action,note,plan,paused,running,state,node,ended")
|
|
539
|
+
p.add_argument("--part", help="only this part")
|
|
540
|
+
p.add_argument("--grep", help="only events matching this regex")
|
|
541
|
+
p.add_argument("--state", action="store_true", help="also stream part state changes (LEDs, displays…)")
|
|
542
|
+
p.add_argument("--full-state", action="store_true", help=argparse.SUPPRESS)
|
|
543
|
+
p.add_argument("--until-text", metavar="TEXT", help="stop once a line contains TEXT")
|
|
544
|
+
p.add_argument("--wall", type=float, default=None, metavar="SECONDS", help="stop after this much wall time")
|
|
545
|
+
|
|
546
|
+
cmd("status", cmd_status, "paused or running, and the simulated time")
|
|
547
|
+
cmd("pause", cmd_pause, "pause the run")
|
|
548
|
+
cmd("resume", cmd_resume, "resume the run")
|
|
549
|
+
p = cmd("until", cmd_until, "run until an edge or a time, then pause there")
|
|
550
|
+
p.add_argument("--edge", metavar="PIN")
|
|
551
|
+
g = p.add_mutually_exclusive_group()
|
|
552
|
+
g.add_argument("--rising", action="store_true")
|
|
553
|
+
g.add_argument("--falling", action="store_true")
|
|
554
|
+
p.add_argument("--nth", type=int, default=1)
|
|
555
|
+
p.add_argument("--at", metavar="TIME", help="absolute simulated time, e.g. 2s")
|
|
556
|
+
p = cmd("advance", cmd_advance, "run exactly this much simulated time, then pause")
|
|
557
|
+
p.add_argument("duration")
|
|
558
|
+
p = cmd("wait", cmd_wait, "run until a line containing TEXT is printed (resumes a paused run)")
|
|
559
|
+
p.add_argument("text")
|
|
560
|
+
p.add_argument("--part")
|
|
561
|
+
p.add_argument("--ms", default="2000", help="simulated time to wait (default 2000)")
|
|
562
|
+
p.add_argument("--since-start", action="store_true", help="also match lines printed before now")
|
|
563
|
+
p = cmd("press", cmd_press, "press a button (and release after --hold)")
|
|
564
|
+
p.add_argument("part")
|
|
565
|
+
p.add_argument("--hold", metavar="TIME")
|
|
566
|
+
p.add_argument("--release", action="store_true", help="release a button pressed without --hold")
|
|
567
|
+
p = cmd("input", cmd_input, "set what a sensor senses: temp temperature=72")
|
|
568
|
+
p.add_argument("part")
|
|
569
|
+
p.add_argument("setting", metavar="NAME=VALUE")
|
|
570
|
+
p = cmd("event", cmd_event, "send any part action (e.g. switch toggle)")
|
|
571
|
+
p.add_argument("part")
|
|
572
|
+
p.add_argument("action")
|
|
573
|
+
p.add_argument("--at", metavar="TIME", help="at this simulated time")
|
|
574
|
+
p = cmd("fault", cmd_fault, "short PIN gnd|vcc · open A B · bridge A B · clear ID")
|
|
575
|
+
p.add_argument("kind", choices=["short", "open", "bridge", "clear"])
|
|
576
|
+
p.add_argument("pins", nargs="*")
|
|
577
|
+
p = cmd("read", cmd_read, "read chip registers/fields/memory: read last mcu GPIO.IN cpu.pc")
|
|
578
|
+
p.add_argument("part")
|
|
579
|
+
p.add_argument("paths", nargs="+")
|
|
580
|
+
p = cmd("write", cmd_write, "write a chip register/field (exact while paused)")
|
|
581
|
+
p.add_argument("part")
|
|
582
|
+
p.add_argument("path")
|
|
583
|
+
p.add_argument("value")
|
|
584
|
+
p = cmd("state", cmd_state, "a part's live state (LED intensity, currents…)")
|
|
585
|
+
p.add_argument("part")
|
|
586
|
+
p = cmd("inside", cmd_inside, "a part's registers decoded, state and recent writes")
|
|
587
|
+
p.add_argument("part")
|
|
588
|
+
p = cmd("measure", cmd_measure, "volts and edges on a net over the last TIME: measure last temp.SDA --over 5ms")
|
|
589
|
+
p.add_argument("pin")
|
|
590
|
+
p.add_argument("--over", default="5ms")
|
|
591
|
+
p = cmd("note", cmd_note, "write a note into the run's activity (shown on the live page)")
|
|
592
|
+
p.add_argument("text")
|