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/cli.py ADDED
@@ -0,0 +1,750 @@
1
+ """The `sim86` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import getpass
7
+ import json
8
+ import os
9
+ import signal
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ from . import NOTICE, __version__
15
+ from .api import IS_DEV_BUILD, TARGETS, Client, Sim86Error, load_config, save_config
16
+ from .board import SCHEMA_PATH, board_schema, check_board, load_board, parse_ms
17
+
18
+ DEFAULT_DURATION = "30s" # simulated; a board's limits.duration or --duration overrides it
19
+ DEFAULT_REALTIME = "10m" # wall clock cap so a forgotten run can't burn credits
20
+
21
+ FEEDBACK_KINDS = ["bug", "wrong_simulation", "missing", "confusing", "idea"]
22
+
23
+
24
+ def _out(msg: str = "") -> None:
25
+ print(msg, flush=True)
26
+
27
+
28
+ def _err(msg: str) -> None:
29
+ print(msg, file=sys.stderr, flush=True)
30
+
31
+
32
+ def _overrides(values: Optional[List[str]]) -> Dict[str, str]:
33
+ out: Dict[str, str] = {}
34
+ for v in values or []:
35
+ if "=" not in v:
36
+ raise Sim86Error(f"--firmware {v!r}: write it as <part id>=<path>, e.g. motor=build/motor.elf")
37
+ k, p = v.split("=", 1)
38
+ out[k] = p
39
+ return out
40
+
41
+
42
+ def _load_checked(args: argparse.Namespace, client: Client):
43
+ board = load_board(args.board, _overrides(getattr(args, "firmware", None)))
44
+ problems = check_board(board, client)
45
+ return board, problems
46
+
47
+
48
+ # ---- commands ---------------------------------------------------------------
49
+
50
+ def cmd_check(args: argparse.Namespace) -> int:
51
+ client = Client(target=args.target)
52
+ board, problems = _load_checked(args, client)
53
+ if args.json:
54
+ _out(json.dumps({"board": board.name, "ok": not problems, "problems": problems}))
55
+ return 1 if problems else 0
56
+ if problems:
57
+ _err(f"✗ {board.name}: {len(problems)} problem{'s' if len(problems) > 1 else ''}")
58
+ for p in problems:
59
+ _err(f" - {p}")
60
+ return 1
61
+ chips = ", ".join(f"{p.id} ({p.type}) ← {p.firmware}" for p in board.mcus) or "none"
62
+ _out(f"✓ {board.name}: {len(board.parts)} parts, {len(board.wires)} wires; firmware: {chips}")
63
+ return 0
64
+
65
+
66
+ def _nets(board) -> List[List[str]]: # noqa: ANN001
67
+ """Pins joined by wires, as groups ("a.P", "b.Q", …), biggest first."""
68
+ parent: Dict[str, str] = {}
69
+
70
+ def find(x: str) -> str:
71
+ parent.setdefault(x, x)
72
+ while parent[x] != x:
73
+ parent[x] = parent[parent[x]]
74
+ x = parent[x]
75
+ return x
76
+
77
+ for a, b in board.wires:
78
+ ra, rb = find(f"{a[0]}.{a[1]}"), find(f"{b[0]}.{b[1]}")
79
+ if ra != rb:
80
+ parent[ra] = rb
81
+ groups: Dict[str, List[str]] = {}
82
+ for pin in parent:
83
+ groups.setdefault(find(pin), []).append(pin)
84
+ return sorted((sorted(g) for g in groups.values()), key=lambda g: (-len(g), g))
85
+
86
+
87
+ def _net_name(pins: List[str]) -> str:
88
+ """A readable name: the rail or bus a net carries, from the pins on it."""
89
+ names = [p.split(".", 1)[1] for p in pins]
90
+ for rail in ("GND", "VSS", "3V3", "3.3V", "5V", "VCC", "VDD", "VIN"):
91
+ if any(n.upper() == rail or n.upper().startswith(rail + " ") for n in names):
92
+ return "GND" if rail in ("GND", "VSS") else rail
93
+ for bus in ("SDA", "SCL", "MOSI", "MISO", "SCK", "TX", "RX", "CS"):
94
+ if bus in (n.upper() for n in names):
95
+ return bus
96
+ return ""
97
+
98
+
99
+ def cmd_info(args: argparse.Namespace) -> int:
100
+ client = Client(target=args.target)
101
+ board = load_board(args.board)
102
+ problems = check_board(board, client)
103
+ _out(f"{board.name} ({board.path})")
104
+ lim = ", ".join(f"{k} {v}" for k, v in board.limits.items())
105
+ if lim or board.seed is not None:
106
+ _out(f" runs for: {lim or 'defaults'}" + (f", seed {board.seed}" if board.seed is not None else ""))
107
+ _out("\nParts")
108
+ for p in board.parts:
109
+ entry = client.part(p.type) or {}
110
+ what = entry.get("name") or "unknown part"
111
+ _out(f" {p.id:<12} {p.type:<18} {what}" + (f" [{p.label}]" if p.label else ""))
112
+ if p.firmware is not None:
113
+ _out(f" {'':<12} runs firmware {p.firmware}")
114
+ if p.config:
115
+ _out(f" {'':<12} settings: " + ", ".join(f"{k}={v}" for k, v in p.config.items()))
116
+ if entry.get("i2cAddress"):
117
+ _out(f" {'':<12} I2C address {entry['i2cAddress']}")
118
+ for i in entry.get("inputs") or []:
119
+ if not i.get("advanced"):
120
+ _out(f" {'':<12} set {i['name']} ({i['min']}…{i['max']} {i['unit']}): "
121
+ f"sim86 input last {p.id} {i['name']}=… | board[\"{p.id}\"].set_input(\"{i['name']}\", …)")
122
+ if p.type.lower() in ("btn", "button"):
123
+ _out(f" {'':<12} press it: sim86 press last {p.id} --hold 200ms | board[\"{p.id}\"].press(hold=\"200ms\")")
124
+ _out("\nNets (pins joined by wires)")
125
+ for pins in _nets(board):
126
+ name = _net_name(pins)
127
+ _out(f" {name:<6} " + " ".join(pins))
128
+ if problems:
129
+ _out("\nProblems (sim86 check)")
130
+ for pr in problems:
131
+ _out(f" - {pr}")
132
+ nets = _nets(board)
133
+ rails = ("GND", "3V3", "3.3V", "5V", "VCC", "VDD", "VIN")
134
+ signal = next((g for g in nets if _net_name(g) and _net_name(g) not in rails), None) or next(
135
+ (g for g in nets if _net_name(g) not in rails), None)
136
+ example = next((p for p in signal if not p.startswith(tuple(m.id + "." for m in board.mcus))), signal[0]) if signal else "part.PIN"
137
+ _out(f"\nFault-inject any pin above: sim86 fault last short {example} gnd | board.short(\"{example}\", \"gnd\")")
138
+ if board.mcus:
139
+ _out(f"Read a chip register: sim86 read last {board.mcus[0].id} <REG> (names: sim86 registers {board.mcus[0].type} <words>)")
140
+ return 1 if problems else 0
141
+
142
+
143
+ def cmd_run(args: argparse.Namespace) -> int:
144
+ from .run import Run, SerialTimeout
145
+
146
+ client = Client(target=args.target)
147
+ board, problems = _load_checked(args, client)
148
+ if problems:
149
+ _err(f"✗ {board.name} can't run:")
150
+ for p in problems:
151
+ _err(f" - {p}")
152
+ return 1
153
+ scenario = None
154
+ if args.scenario:
155
+ try:
156
+ scenario = json.loads(Path(args.scenario).read_text())
157
+ except (OSError, ValueError) as e:
158
+ _err(f"✗ scenario {args.scenario}: {e}")
159
+ return 1
160
+ duration = args.duration or board.limits.get("duration") or DEFAULT_DURATION
161
+ realtime = args.realtime or board.limits.get("realtime") or DEFAULT_REALTIME
162
+ _err(f"▸ starting {board.name} on the Simulator86 cloud "
163
+ f"({len(board.parts)} parts, {len(board.mcus)} chip{'s' if len(board.mcus) != 1 else ''}, "
164
+ f"up to {duration} simulated)…")
165
+ run = Run.start(board, client, duration=duration, realtime=realtime, scenario=scenario, seed=args.seed)
166
+ from .session import remember
167
+ remember(run.id) # `sim86 open last`, `sim86 logs last`…
168
+ _err(f"▸ run {run.id}\n▸ watch it live: {run.url}")
169
+ # Open the live page for a person at a terminal; never in CI or scripts.
170
+ interactive = sys.stdout.isatty() and not os.environ.get("CI")
171
+ if args.open or (interactive and not args.no_open and not args.json):
172
+ client.open_live(run.url)
173
+
174
+ def show(line) -> None: # noqa: ANN001
175
+ if args.json:
176
+ _out(json.dumps({"t": line.t, "source": line.source, "line": line.line}))
177
+ elif not args.quiet:
178
+ _out(str(line))
179
+
180
+ run.on_line(show)
181
+ for line in run.serial.lines:
182
+ show(line)
183
+
184
+ def interrupt(*_: Any) -> None:
185
+ _err("\n▸ stopping run…")
186
+ run.stop()
187
+ sys.exit(130)
188
+
189
+ signal.signal(signal.SIGINT, interrupt)
190
+ try:
191
+ if args.expect:
192
+ try:
193
+ hit = run.serial.wait_for(args.expect, ms=args.timeout or duration, since_start=True)
194
+ except SerialTimeout as e:
195
+ _err(f"✗ {e}")
196
+ run.stop()
197
+ return 1
198
+ _err(f"✓ saw {args.expect!r} at {hit.t:.3f} ms ({hit.source})")
199
+ run.stop()
200
+ return 0
201
+ reason = run.wait_done()
202
+ _err(f"▸ run ended: {reason}")
203
+ return 0 if reason in ("duration", "done", "firmware-exit", "realtime", "stopped", "user-stop") else 2
204
+ finally:
205
+ run.close()
206
+
207
+
208
+ def cmd_parts(args: argparse.Namespace) -> int:
209
+ client = Client(target=args.target)
210
+ if args.show:
211
+ entry = client.part(args.show)
212
+ if entry is None:
213
+ hits = client.search_parts(args.show, limit=5)
214
+ _err(f"✗ no part {args.show!r}" + (f"; closest: {', '.join(h['type'] for h in hits)}" if hits else ""))
215
+ return 1
216
+ if args.json:
217
+ _out(json.dumps(entry, indent=2))
218
+ return 0
219
+ _out(f"{entry['type']} — {entry['name']} [{entry['kind']}]")
220
+ _out(f" {entry.get('summary', '')}")
221
+ _out(f" pins: {', '.join(p['name'] for p in entry.get('pins', [])) or '(none: not wired)'}")
222
+ if entry.get("i2cAddress"):
223
+ _out(f" i2c: {entry['i2cAddress']}")
224
+ if entry.get("firmware"):
225
+ _out(f" firmware: {', '.join(entry['firmware'].get('formats', []))} — {entry['firmware'].get('note', '')}")
226
+ props = (entry.get("config") or {}).get("properties") or {}
227
+ for k, v in props.items():
228
+ if k == "binaries":
229
+ continue
230
+ _out(f" config.{k}: {v.get('description', v.get('type', ''))}")
231
+ for i in entry.get("inputs") or []:
232
+ _out(f" input {i['name']}: {i['min']}…{i['max']} {i['unit']} (default {i['default']})")
233
+ if entry.get("description"):
234
+ _out(f"\n {entry['description']}")
235
+ return 0
236
+ hits = client.search_parts(args.query or "", kind=args.kind, limit=args.limit)
237
+ if args.json:
238
+ _out(json.dumps(hits, indent=2))
239
+ return 0
240
+ for h in hits:
241
+ _out(f"{h['type']:<22} {h['kind']:<11} {h['summary'][:90]}")
242
+ if not args.query:
243
+ _out("\n`sim86 parts <word>` searches, `sim86 parts --show <type>` shows pins and settings.")
244
+ return 0
245
+
246
+
247
+ def cmd_registers(args: argparse.Namespace) -> int:
248
+ res = Client(target=args.target).search_registers(args.chip, " ".join(args.query), limit=args.limit)
249
+ if args.json:
250
+ _out(json.dumps(res, indent=2))
251
+ return 0
252
+ for r in res.get("registers", []):
253
+ where = r.get("address") or (f"bits {r['bits']}" if r.get("bits") else "")
254
+ _out(f"{r['path']:<34} {r['kind']:<9} {where:<12} {r.get('access', ''):<11} {r.get('description', '')[:60]}")
255
+ return 0
256
+
257
+
258
+ def cmd_runs(args: argparse.Namespace) -> int:
259
+ client = Client(target=args.target)
260
+ for r in client.runs()[: args.limit]:
261
+ _out(f"{r['id']} {r['status']:<8} {str(r.get('reason') or ''):<16} {r.get('startedAt', '')}")
262
+ return 0
263
+
264
+
265
+ def cmd_logs(args: argparse.Namespace) -> int:
266
+ client = Client(target=args.target)
267
+ from .session import resolve_run
268
+ for l in client.run_logs(resolve_run(args.run))["lines"]:
269
+ _out(f"[{l['t']:10.3f} ms] {l['source']:<18} {l['line']}")
270
+ return 0
271
+
272
+
273
+ def cmd_stop(args: argparse.Namespace) -> int:
274
+ from .session import resolve_run
275
+ run_id = resolve_run(args.run)
276
+ Client(target=args.target).stop_run(run_id)
277
+ _out(json.dumps({"stopped": run_id}))
278
+ return 0
279
+
280
+
281
+ def cmd_open(args: argparse.Namespace) -> int:
282
+ client = Client(target=args.target)
283
+ from .session import resolve_run
284
+ url = client.live_url(resolve_run(args.run))
285
+ _out(url)
286
+ client.open_live(url)
287
+ return 0
288
+
289
+
290
+ def _browser_login(client: Client) -> Optional[str]:
291
+ """Sign in through the browser (the device flow the MCP installer uses):
292
+ show a code, open the approval page, wait for the key. None if the
293
+ request was denied or ran out of time."""
294
+ import socket
295
+ import time
296
+ from .api import ApiError, open_browser
297
+
298
+ name = f"sim86 CLI · {socket.gethostname().split('.')[0] or 'computer'}"
299
+ code = client._request("POST", "/device/code", json.dumps({"clientName": name}).encode(),
300
+ {"content-type": "application/json"}, auth=False)
301
+ # next=watch: after Approve, that tab stays open and shows the boards this
302
+ # CLI starts, live.
303
+ url = code["verificationUriComplete"] + ("&" if "?" in code["verificationUriComplete"] else "?") + "next=watch"
304
+ _out(f"Your code: {code['userCode']}")
305
+ if open_browser(url):
306
+ _out(f"Approve it in the browser tab that just opened (or go to {url})")
307
+ else:
308
+ _out(f"Open {url} and approve it")
309
+ deadline = time.monotonic() + int(code.get("expiresIn") or 600)
310
+ interval = max(1, int(code.get("interval") or 3))
311
+ body = json.dumps({"deviceCode": code["deviceCode"]}).encode()
312
+ while time.monotonic() < deadline:
313
+ time.sleep(interval)
314
+ try:
315
+ res = client._request("POST", "/device/token", body, {"content-type": "application/json"}, auth=False)
316
+ except ApiError as e:
317
+ if e.status == 403:
318
+ _err("✗ sign-in was denied")
319
+ return None
320
+ if e.status == 410:
321
+ break
322
+ raise
323
+ if res.get("apiKey"):
324
+ return res["apiKey"]
325
+ _err("✗ the code expired; run `sim86 login` again")
326
+ return None
327
+
328
+
329
+ def cmd_login(args: argparse.Namespace) -> int:
330
+ if args.key:
331
+ key = args.key
332
+ elif args.paste:
333
+ key = getpass.getpass("API key (app.sim86.com → Cloud → API keys): ").strip()
334
+ else:
335
+ # The browser sign-in also works from an agent's shell (no terminal):
336
+ # the approval tab opens on the user's screen.
337
+ key = _browser_login(Client(target=args.target))
338
+ if not key:
339
+ return 1
340
+ client = Client(api_key=key, target=args.target)
341
+ client.gql("query { workspaces { id } }") # proves the key works
342
+ cfg = load_config()
343
+ cfg["apiKey"] = key
344
+ save_config(cfg)
345
+ _out(f"✓ signed in to {client.api_url}")
346
+ return 0
347
+
348
+
349
+ def _feedback_text(r: Dict[str, Any]) -> str:
350
+ target = ", ".join(f"{k}: {v}" for k, v in (r.get("target") or {}).items() if v)
351
+ ids = ", ".join(x for x in [f"tool: sim86-cli {__version__}", r.get("board") and f"board: {r['board']}",
352
+ r.get("runId") and f"run: {r['runId']}"] if x)
353
+ lines = [
354
+ r["summary"],
355
+ f"[{r.get('kind', 'bug')} · {r.get('impact', 'minor')} · reproducible: {r.get('reproducible', 'untried')}]",
356
+ ]
357
+ if target:
358
+ lines.append(target)
359
+ lines.append(ids)
360
+ for key, label in (("goal", "Goal"), ("steps", "Steps"), ("expected", "Expected"), ("actual", "Actual"),
361
+ ("workaround", "Workaround"), ("details", "Details")):
362
+ if r.get(key):
363
+ lines += ["", f"{label}:", str(r[key])]
364
+ return "\n".join(lines)
365
+
366
+
367
+ def cmd_feedback(args: argparse.Namespace) -> int:
368
+ report: Dict[str, Any] = {}
369
+ if args.json:
370
+ raw = sys.stdin.read() if args.json == "-" else Path(args.json).read_text()
371
+ report = json.loads(raw)
372
+ for key in ("kind", "summary", "goal", "steps", "expected", "actual", "details", "impact", "reproducible"):
373
+ v = getattr(args, key, None)
374
+ if v:
375
+ report[key] = v
376
+ if args.run:
377
+ report["runId"] = args.run
378
+ if args.board:
379
+ report["board"] = args.board
380
+ try:
381
+ b = load_board(args.board)
382
+ report.setdefault("target", {})["chip"] = ", ".join(sorted({p.type for p in b.mcus}))
383
+ except Sim86Error:
384
+ pass
385
+ if not report.get("summary") or len(report["summary"]) < 10:
386
+ _err("✗ feedback needs --summary (one specific line, 10+ characters)")
387
+ return 1
388
+ kind = report.get("kind", "bug")
389
+ if kind not in FEEDBACK_KINDS:
390
+ _err(f"✗ --kind must be one of {', '.join(FEEDBACK_KINDS)}")
391
+ return 1
392
+ Client(target=args.target).send_feedback(_feedback_text(report), kind=f"cli:{kind}")
393
+ _out("✓ sent to the Simulator86 team — thank you")
394
+ return 0
395
+
396
+
397
+ INIT_BOARD = {
398
+ "$schema": SCHEMA_PATH,
399
+ "name": "my-board",
400
+ "parts": [
401
+ {"id": "mcu", "type": "XiaoESP32C3", "firmware": "build/firmware.merged.bin"},
402
+ {"id": "sensor", "type": "BMP280"},
403
+ {"id": "led", "type": "Led", "config": {"color": "red"}},
404
+ ],
405
+ "wires": [
406
+ ["mcu.3V3", "sensor.VCC"], ["mcu.GND", "sensor.GND"],
407
+ ["mcu.D4", "sensor.SDA"], ["mcu.D5", "sensor.SCL"],
408
+ ["mcu.D2", "led.+"], ["led.-", "mcu.GND"],
409
+ ],
410
+ "limits": {"duration": "10s"},
411
+ }
412
+
413
+ INIT_TEST = '''"""Runs on the Simulator86 cloud: `pytest` (needs SIM86_API_KEY)."""
414
+
415
+
416
+ def test_boots(board):
417
+ board["mcu"].serial.wait_for("ready", ms=2000)
418
+
419
+
420
+ def test_survives_a_shorted_sda(board):
421
+ board["mcu"].serial.wait_for("ready", ms=2000)
422
+ board.until(edge="sensor.SCL", kind="falling", nth=3) # pause on the exact edge
423
+ fault = board.short("sensor.SDA", "gnd")
424
+ board.advance("5ms")
425
+ board.clear(fault)
426
+ board["mcu"].serial.wait_for("sensor", ms=1000)
427
+ '''
428
+
429
+
430
+ def _write_schema(root: Path, client: Optional[Client]) -> Path:
431
+ types = None
432
+ if client is not None:
433
+ try:
434
+ types = client.search_parts("", limit=1000)
435
+ except Sim86Error:
436
+ types = None # offline: the schema still explains every key
437
+ path = root / SCHEMA_PATH
438
+ path.parent.mkdir(parents=True, exist_ok=True)
439
+ path.write_text(json.dumps(board_schema(types), indent=2) + "\n")
440
+ return path
441
+
442
+
443
+ def cmd_schema(args: argparse.Namespace) -> int:
444
+ path = _write_schema(Path(args.dir), Client(target=args.target))
445
+ _out(f"wrote {path} — add \"$schema\": \"{SCHEMA_PATH}\" at the top of your board file")
446
+ return 0
447
+
448
+
449
+ # Ready-to-run example projects: board file, built firmware, tests.
450
+ EXAMPLES = {
451
+ "uferris": "uFerris Megalops base board: XIAO nRF52840, 7-segment display, buzzer, RTC (Rust)",
452
+ }
453
+ EXAMPLES_URL = "https://sim86.com/examples"
454
+
455
+
456
+ def _extract_example(data: bytes, root: Path) -> List[str]:
457
+ """Unpack an example archive into root. Only plain files and folders,
458
+ and only inside root."""
459
+ import io
460
+ import tarfile
461
+
462
+ written = []
463
+ base = root.resolve()
464
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tar:
465
+ for m in tar.getmembers():
466
+ dest = (root / m.name).resolve()
467
+ if (base not in dest.parents and dest != base) or not (m.isfile() or m.isdir()):
468
+ raise Sim86Error(f"example archive has an unsafe entry: {m.name}")
469
+ if m.isdir():
470
+ dest.mkdir(parents=True, exist_ok=True)
471
+ continue
472
+ dest.parent.mkdir(parents=True, exist_ok=True)
473
+ src = tar.extractfile(m)
474
+ dest.write_bytes(src.read() if src else b"")
475
+ written.append(m.name)
476
+ return written
477
+
478
+
479
+ def _init_example(args: argparse.Namespace) -> int:
480
+ import urllib.error
481
+ import urllib.request
482
+
483
+ name = args.example
484
+ if name not in EXAMPLES:
485
+ _err(f"✗ no example {name!r}; there is: " + ", ".join(EXAMPLES))
486
+ return 1
487
+ root = Path(name if args.dir == "." else args.dir)
488
+ if root.exists() and any(root.iterdir()):
489
+ _err(f"✗ {root} already exists and isn't empty")
490
+ return 1
491
+ url = f"{os.environ.get('SIM86_EXAMPLES_URL', EXAMPLES_URL)}/{name}.tar.gz"
492
+ try:
493
+ req = urllib.request.Request(url, headers={"user-agent": f"sim86-python/{__version__}"})
494
+ with urllib.request.urlopen(req, timeout=60) as res:
495
+ data = res.read()
496
+ except urllib.error.URLError as e:
497
+ _err(f"✗ couldn't download the example from {url}: {getattr(e, 'reason', e)}")
498
+ return 1
499
+ root.mkdir(parents=True, exist_ok=True)
500
+ files = _extract_example(data, root)
501
+ _out(f"✓ {EXAMPLES[name]}")
502
+ _out(f" {len(files)} files in {root}/: board.json, built firmware, tests")
503
+ _out("")
504
+ _out("next:")
505
+ _out(f" cd {root}")
506
+ _out(" sim86 start board.json # boot it and watch it live in the browser")
507
+ _out(" sim86 test # run its tests")
508
+ return 0
509
+
510
+
511
+ def cmd_init(args: argparse.Namespace) -> int:
512
+ if args.example:
513
+ return _init_example(args)
514
+ root = Path(args.dir)
515
+ root.mkdir(parents=True, exist_ok=True)
516
+ written = []
517
+ for rel, content in (("board.json", json.dumps(INIT_BOARD, indent=2) + "\n"),
518
+ ("tests/test_board.py", INIT_TEST),
519
+ ("pytest.ini", "[pytest]\nsim86_board = board.json\n")):
520
+ p = root / rel
521
+ if p.exists():
522
+ continue
523
+ p.parent.mkdir(parents=True, exist_ok=True)
524
+ p.write_text(content)
525
+ written.append(rel)
526
+ _write_schema(root, Client(target=args.target))
527
+ written.append(SCHEMA_PATH)
528
+ _out("wrote " + (", ".join(written) or "nothing (files already exist)"))
529
+ _out("next: put your merged firmware image at build/firmware.merged.bin, then `sim86 check board.json` and `pytest`")
530
+ return 0
531
+
532
+
533
+ # ---- parser -----------------------------------------------------------------
534
+
535
+ def build_parser() -> argparse.ArgumentParser:
536
+ p = argparse.ArgumentParser(
537
+ prog="sim86",
538
+ description="Run firmware on simulated boards in the Simulator86 cloud.",
539
+ epilog=NOTICE,
540
+ )
541
+ p.add_argument("--version", action="version",
542
+ version=f"sim86 {__version__}" + ("" if not IS_DEV_BUILD else " (dev build)")
543
+ + " — demo/feedback preview, not for production (t@simulator86.com)")
544
+ if IS_DEV_BUILD: # dev builds only: test Simulator86 itself against dev servers
545
+ p.add_argument("--target", choices=sorted(TARGETS), default=None,
546
+ help="servers to use (dev build only)")
547
+ else:
548
+ p.set_defaults(target=None)
549
+ sub = p.add_subparsers(dest="cmd", metavar="<command>")
550
+
551
+ r = sub.add_parser("run", help="run a board and stream what it prints")
552
+ r.add_argument("board", help="board JSON file")
553
+ r.add_argument("--firmware", action="append", metavar="ID=PATH", help="use another image for one chip")
554
+ r.add_argument("--duration", help=f"simulated time to run (default: board limits or {DEFAULT_DURATION})")
555
+ r.add_argument("--realtime", help=f"wall-clock cap (default {DEFAULT_REALTIME})")
556
+ r.add_argument("--scenario", help="scenario JSON: faults and inputs planned up front")
557
+ r.add_argument("--seed", type=int, help="simulation seed (same seed = same run)")
558
+ r.add_argument("--expect", metavar="TEXT", help="succeed as soon as TEXT is printed, fail if it never is")
559
+ r.add_argument("--timeout", help="simulated time to wait for --expect (default: --duration)")
560
+ r.add_argument("--open", action="store_true", help="open the live page even when not at a terminal")
561
+ r.add_argument("--no-open", action="store_true", help="don't open the live page in the browser")
562
+ r.add_argument("--json", action="store_true", help="print each line as JSON")
563
+ r.add_argument("-q", "--quiet", action="store_true", help="don't print firmware output")
564
+ r.set_defaults(fn=cmd_run)
565
+
566
+ c = sub.add_parser("check", help="check a board file against the part catalog")
567
+ c.add_argument("board")
568
+ c.add_argument("--firmware", action="append", metavar="ID=PATH")
569
+ c.add_argument("--json", action="store_true")
570
+ c.set_defaults(fn=cmd_check)
571
+
572
+ inf = sub.add_parser("info", help="explain a board file: parts, firmware, nets, what tests can do")
573
+ inf.add_argument("board")
574
+ inf.set_defaults(fn=cmd_info)
575
+
576
+ pa = sub.add_parser("parts", help="search the part catalog, or --show one part's pins and settings")
577
+ pa.add_argument("query", nargs="?")
578
+ pa.add_argument("--show", metavar="TYPE")
579
+ pa.add_argument("--kind", choices=["mcu", "sensor", "display", "output", "input", "network", "peripheral"])
580
+ pa.add_argument("--limit", type=int, default=100)
581
+ pa.add_argument("--json", action="store_true")
582
+ pa.set_defaults(fn=cmd_parts)
583
+
584
+ rg = sub.add_parser("registers", help="search a chip's registers and bit fields (names for read/write)")
585
+ rg.add_argument("chip", help="part type, e.g. XiaoESP32C3")
586
+ rg.add_argument("query", nargs="*")
587
+ rg.add_argument("--limit", type=int, default=40)
588
+ rg.add_argument("--json", action="store_true")
589
+ rg.set_defaults(fn=cmd_registers)
590
+
591
+ sc = sub.add_parser("schema", help="write the board-file schema (editor hover docs + autocomplete)")
592
+ sc.add_argument("dir", nargs="?", default=".")
593
+ sc.set_defaults(fn=cmd_schema)
594
+
595
+ i = sub.add_parser("init", help="write a starter board.json and test, or fetch a ready-to-run example")
596
+ i.add_argument("dir", nargs="?", default=".")
597
+ i.add_argument("--example", metavar="NAME",
598
+ help="a working example with built firmware and tests: " + ", ".join(EXAMPLES))
599
+ i.set_defaults(fn=cmd_init)
600
+
601
+ ru = sub.add_parser("runs", help="your recent runs")
602
+ ru.add_argument("--limit", type=int, default=20)
603
+ ru.set_defaults(fn=cmd_runs)
604
+ for name, fn, text in (("logs", cmd_logs, "a run's output"), ("stop", cmd_stop, "stop a run"),
605
+ ("open", cmd_open, "watch a run live in the browser")):
606
+ s = sub.add_parser(name, help=text)
607
+ s.add_argument("run", help="run id")
608
+ s.set_defaults(fn=fn)
609
+
610
+ sub.add_parser("test", help="run your pytest tests with the board fixture (any pytest options: -v, -k, -n 4, --junitxml)",
611
+ add_help=False)
612
+ from .session import add_commands
613
+ add_commands(sub, p)
614
+
615
+ lg = sub.add_parser("login", help="sign in through the browser and save an API key")
616
+ lg.add_argument("--key", help="save this key instead of signing in through the browser")
617
+ lg.add_argument("--paste", action="store_true", help="paste a key instead of signing in through the browser")
618
+ lg.set_defaults(fn=cmd_login)
619
+
620
+ f = sub.add_parser("feedback", help="report a problem with Simulator86 to the team (agents welcome)",
621
+ description="Report a problem with the simulator itself, not with your firmware. "
622
+ "Agents: pass --json - with {kind, summary, goal, steps, expected, actual, "
623
+ "reproducible, impact, target:{chip,framework,part,peripheral}}.")
624
+ f.add_argument("--kind", choices=FEEDBACK_KINDS, help="bug (default), wrong_simulation, missing, confusing, idea")
625
+ f.add_argument("--summary", "-m", help="one specific line: what is wrong")
626
+ f.add_argument("--goal", help="what you were trying to get done")
627
+ f.add_argument("--steps", help="what you did, in order")
628
+ f.add_argument("--expected")
629
+ f.add_argument("--actual", help="exact output or error text")
630
+ f.add_argument("--details")
631
+ f.add_argument("--impact", choices=["blocked", "worked_around", "minor"])
632
+ f.add_argument("--reproducible", choices=["always", "sometimes", "once", "untried"])
633
+ f.add_argument("--run", help="run id it happened in")
634
+ f.add_argument("--board", help="board file involved")
635
+ f.add_argument("--json", metavar="FILE", help="read the report as JSON from FILE, or - for stdin")
636
+ f.set_defaults(fn=cmd_feedback)
637
+ return p
638
+
639
+
640
+ def _utf8_console() -> None:
641
+ """Windows consoles default to a code page that can't print ✓ ▸ ↔: never
642
+ crash on output, whatever the terminal."""
643
+ for stream in (sys.stdout, sys.stderr):
644
+ try:
645
+ stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
646
+ except (AttributeError, ValueError):
647
+ pass
648
+
649
+
650
+ def _act_as_python(argv: List[str]) -> Optional[int]:
651
+ """Inside the standalone executable, `sim86` is also the Python that
652
+ pytest-xdist starts its workers with (`<python> -u -c "<code>"`)."""
653
+ if not getattr(sys, "frozen", False):
654
+ return None
655
+ flags = []
656
+ rest = list(argv)
657
+ while rest and rest[0] in ("-u", "-B", "-E", "-s", "-I"):
658
+ flags.append(rest.pop(0))
659
+ if len(rest) < 2 or rest[0] != "-c":
660
+ return None
661
+ if "-u" in flags:
662
+ for stream in (sys.stdout, sys.stderr):
663
+ try:
664
+ stream.reconfigure(write_through=True) # type: ignore[attr-defined]
665
+ except (AttributeError, ValueError):
666
+ pass
667
+ code, sys.argv = rest[1], ["-c"] + rest[2:]
668
+ exec(compile(code, "<string>", "exec"), {"__name__": "__main__", "__builtins__": __builtins__})
669
+ return 0
670
+
671
+
672
+ def cmd_test(argv: List[str]) -> int:
673
+ """`sim86 test [pytest options]`: run pytest with the sim86 plugin — the
674
+ standalone executable carries pytest and pytest-xdist inside."""
675
+ try:
676
+ import pytest
677
+ except ImportError:
678
+ _err("✗ pytest isn't installed: `pip install pytest` (the standalone sim86 executable includes it)")
679
+ return 1
680
+ # sim86 itself is already imported (it is running this command); only
681
+ # the user's test files need pytest's assert rewriting.
682
+ args = ["-W", "ignore:Module already imported so cannot be rewritten:pytest.PytestAssertRewriteWarning"] + list(argv)
683
+ try:
684
+ from importlib.metadata import entry_points
685
+
686
+ autoloaded = any(ep.name == "sim86" for ep in entry_points(group="pytest11"))
687
+ except Exception: # noqa: BLE001
688
+ autoloaded = False
689
+ if not autoloaded:
690
+ # The executable has no package metadata for pytest to discover the
691
+ # plugin through; name it (by module, so xdist workers load it too).
692
+ args = ["-p", "sim86.pytest_plugin"] + args
693
+ return int(pytest.main(args))
694
+
695
+
696
+ def _first_use_notice() -> None:
697
+ """Say once per machine what this is (stderr, so JSON output stays clean)."""
698
+ cfg = load_config()
699
+ if cfg.get("noticeShown"):
700
+ return
701
+ _err("─" * 72 + "\n" + NOTICE + "\n" + "─" * 72)
702
+ cfg["noticeShown"] = True
703
+ try:
704
+ save_config(cfg)
705
+ except OSError:
706
+ pass
707
+
708
+
709
+ def _trust_bundled_certificates() -> None:
710
+ """The standalone executable's own CA list: its Python looks for one where
711
+ the build machine keeps it, which on the user's machine is usually nothing.
712
+ Test workers inherit it. A SSL_CERT_FILE the user set still wins."""
713
+ if getattr(sys, "frozen", False) and "SSL_CERT_FILE" not in os.environ:
714
+ import certifi
715
+
716
+ os.environ["SSL_CERT_FILE"] = certifi.where()
717
+
718
+
719
+ def main(argv: Optional[List[str]] = None) -> int:
720
+ _trust_bundled_certificates()
721
+ raw = list(sys.argv[1:] if argv is None else argv)
722
+ as_python = _act_as_python(raw)
723
+ if as_python is not None:
724
+ return as_python
725
+ _utf8_console()
726
+ _first_use_notice()
727
+ if raw[:1] == ["test"]:
728
+ return cmd_test(raw[1:])
729
+ parser = build_parser()
730
+ args = parser.parse_args(argv)
731
+ if not getattr(args, "fn", None):
732
+ parser.print_help()
733
+ return 0
734
+ try:
735
+ return args.fn(args)
736
+ except Sim86Error as e:
737
+ _err(f"✗ {e}")
738
+ return 1
739
+ except KeyboardInterrupt:
740
+ return 130
741
+ except BrokenPipeError: # `sim86 logs … | head`
742
+ try:
743
+ sys.stdout = open(os.devnull, "w")
744
+ except OSError:
745
+ pass
746
+ return 0
747
+
748
+
749
+ if __name__ == "__main__":
750
+ sys.exit(main())