Skip to main content

litz_engine/
runner.rs

1//! Loading a project, booting it and deciding pass or fail.
2
3use crate::config::{
4    BoardSection, Config, DecodeSection, Runtime, TestSpec, WifiSpec, parse_duration, parse_size,
5};
6use crate::image::{self, FirmwareLayout};
7use crate::lock::Lock;
8use crate::scenario::{Scenario, Step};
9use litz_board::chip::{Chip, ImageKind, Input, Stop};
10use litz_board::probe;
11use litz_board::{Board, FlatBoard};
12use litz_catalog::Registry;
13use litz_core::{Level, PartState};
14use litz_diagram::{Circuit, Diagnostic, Severity};
15use litz_net::{AccessPoint, NearbyNetwork, NetworkConfig, Service};
16
17use crate::machine::{Attachments, builtin_chip};
18
19// A wasm guest chip needs wasmtime, which cannot itself be built for a wasm32
20// host. The browser module uses `machine::boot_c3` only, so the runner's wasm
21// chip backend is compiled out there rather than dragging wasmtime along.
22#[cfg(not(target_family = "wasm"))]
23use litz_mcu_wasm::WasmChip;
24use std::collections::BTreeMap;
25use std::io::Write;
26use std::path::{Path, PathBuf};
27
28const DEFAULT_TIMEOUT: &str = "10s";
29const DEFAULT_MAC: [u8; 6] = [0x24, 0x0a, 0xc4, 0x12, 0x34, 0x56];
30const EXIT_TIMEOUT: i32 = 42;
31/// MicroPython's friendly-REPL prompt. It is the only sign the interpreter is
32/// ready to accept a paste; matching a banner would tie the runner to one
33/// build's wording.
34const REPL_PROMPT: &str = ">>> ";
35/// How often a CircuitPython board that has not answered yet is sent a key.
36/// Long enough that one press survives a `code.py` that is still starting,
37/// short enough that a boot which already finished does not wait.
38const CIRCUITPYTHON_NUDGE: u64 = 200_000_000;
39/// A paste is assembled in RAM before it is sent, so it is capped at the size
40/// a REPL session can reasonably swallow. A project that needs more should
41/// ship a filesystem image instead.
42const MAX_SCRIPT: usize = 64 * 1024;
43/// Simulated time granted after a paste is queued before an `expect` that
44/// already matched the boot output may end the run. It gives the UART queue
45/// time to drain and the interpreter time to start the script, so a test that
46/// asserts on the banner cannot pass without the script ever running.
47const PASTE_GRACE_NS: u64 = 200_000_000;
48
49#[derive(Clone, Copy, PartialEq, Eq)]
50pub enum Mode {
51    Run,
52    Test,
53    Check,
54}
55
56/// What the caller wants recorded about a run, beyond pass or fail.
57#[derive(Clone, Default)]
58pub struct Options {
59    /// Write every net transition to this file as a VCD.
60    pub vcd: Option<PathBuf>,
61    /// Stop the first run at this program counter and report the registers.
62    pub break_at: Option<u32>,
63    /// Solve the circuit's analog network alongside the digital run. Off by
64    /// default; `[sim] analog = true` turns it on for the project.
65    pub analog: bool,
66    /// Override the project's Wi-Fi access point for this run.
67    pub wifi: Option<String>,
68    /// Turn on instruction coverage and print the backend's report after the
69    /// run. A backend without coverage ignores it.
70    pub coverage: bool,
71    /// Forward lines typed on stdin to one board's console, so a REPL or a
72    /// firmware that asks a question can be answered from the terminal.
73    pub interactive: Option<Interactive>,
74    /// Write a simulated display here as a PNG: at the end of a `run`, and
75    /// when a test fails.
76    pub screenshot: Option<Screenshot>,
77    /// Points to watch, in addition to the project's `[[probe]]` entries.
78    /// Each is its own channel name.
79    pub probes: Vec<String>,
80    /// Write every probe's record here as a CSV at the end of the run.
81    pub scope: Option<PathBuf>,
82    /// Start the scope's window at a logic-analyzer trigger instead of at
83    /// time zero. The trigger names a probe the run already watches.
84    pub trigger: Option<litz_board::probe::Trigger>,
85    /// Protocols to read off the probed channels, in addition to the project's
86    /// `[[decode]]` entries.
87    pub decodes: Vec<DecodeSection>,
88    /// Serve the GDB remote protocol on one board's chip once it is booted.
89    pub gdb: Option<GdbRequest>,
90    /// Write the simulated network's traffic here as a pcap at the end of the
91    /// run, for Wireshark.
92    pub pcap: Option<PathBuf>,
93    /// Write every 802.11 frame the radio carries into a link-type-105 pcap
94    /// as the run goes.
95    pub pcap_air: Option<PathBuf>,
96    /// Write the Ethernet frames the station's MAC carries into a
97    /// link-type-1 pcap as the run goes.
98    pub pcap_eth: Option<PathBuf>,
99    /// Put host sockets behind the Wi-Fi gateway. Non-deterministic by
100    /// nature; the forwarded ports are `tcp:[host:]port-[guest:]port`.
101    pub host_network: bool,
102    pub host_forwards: Vec<String>,
103    /// Ask the firmware for its free heap at the end of the run and print it.
104    /// A firmware that cannot answer makes the run fail, so CI can gate on it.
105    pub heap_sample: bool,
106    /// Sample the free heap every this many nanoseconds of simulated time.
107    /// `None` keeps the end-of-run sample that `heap_sample` asks for.
108    pub heap_interval: Option<u64>,
109    /// Fail the run when the free heap drops below this many bytes.
110    pub heap_min_free: Option<u32>,
111    /// Append every heap sample to this CSV as it is taken.
112    pub heap_csv: Option<PathBuf>,
113    /// Save the image of every SPI microSD card the guest wrote, after the
114    /// run. One card writes to the path; several treat it as a directory.
115    pub sd_export: Option<PathBuf>,
116}
117
118/// `--interactive[=BOARD]`: whose console receives what is typed.
119#[derive(Clone, Debug, Default)]
120pub struct Interactive {
121    /// The board whose console stdin reaches; `None` means the first board.
122    pub board: Option<String>,
123}
124
125/// `--screenshot [<board>@]FILE`: which display to capture, and where.
126#[derive(Clone, Debug)]
127pub struct Screenshot {
128    /// The board whose display to capture; `None` means the first board that
129    /// has a framebuffer.
130    pub board: Option<String>,
131    pub path: PathBuf,
132}
133
134/// Heap samples taken while the run proceeds.
135///
136/// The firmware's own getter is the source, so the numbers are the ones the
137/// firmware sees. Sampling happens at chunk boundaries, which is where the
138/// core is between instructions; a sample never changes the program's state
139/// beyond the simulated time the call itself spends.
140struct HeapLog {
141    label: String,
142    interval_ns: u64,
143    next_ns: u64,
144    limit: Option<u32>,
145    csv: Option<(PathBuf, std::io::BufWriter<std::fs::File>)>,
146    samples: Vec<(u64, u32)>,
147    lowest: Option<u32>,
148    failure: Option<String>,
149    last_error: Option<String>,
150}
151
152impl HeapLog {
153    fn from_options(options: &Options, label: String) -> Result<Option<Self>, String> {
154        let enabled = options.heap_sample
155            || options.heap_interval.is_some()
156            || options.heap_min_free.is_some()
157            || options.heap_csv.is_some();
158        if !enabled {
159            return Ok(None);
160        }
161        let interval_ns = options.heap_interval.unwrap_or(1_000_000_000).max(1);
162        let csv = options
163            .heap_csv
164            .as_ref()
165            .map(|path| {
166                let file =
167                    std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
168                let mut writer = std::io::BufWriter::new(file);
169                writer
170                    .write_all(b"part,time_s,free,min_free\n")
171                    .map_err(|e| format!("{}: {e}", path.display()))?;
172                Ok::<(PathBuf, std::io::BufWriter<std::fs::File>), String>((path.clone(), writer))
173            })
174            .transpose()?;
175        Ok(Some(Self {
176            label,
177            interval_ns,
178            next_ns: 0,
179            limit: options.heap_min_free,
180            csv,
181            samples: Vec::new(),
182            lowest: None,
183            failure: None,
184            last_error: None,
185        }))
186    }
187
188    /// Take a sample when the interval has elapsed. Sampling more than once
189    /// per chunk is pointless: the shape is bounded by the chunk size, not by
190    /// how many times the loop asks.
191    fn sample(&mut self, mcu: &mut Fleet, now_ns: u64) {
192        if now_ns < self.next_ns || self.failure.is_some() {
193            return;
194        }
195        while self.next_ns <= now_ns {
196            self.next_ns = self.next_ns.saturating_add(self.interval_ns);
197        }
198        self.record(mcu, now_ns);
199    }
200
201    /// Record one sample now, regardless of the interval, for the run's end.
202    fn record(&mut self, mcu: &mut Fleet, now_ns: u64) {
203        let free = match mcu.sample_heap() {
204            Ok(free) => free,
205            Err(error) => {
206                self.last_error = Some(error);
207                return;
208            }
209        };
210        self.samples.push((now_ns, free));
211        self.lowest = Some(self.lowest.map_or(free, |lowest| lowest.min(free)));
212        let lowest = self.lowest.unwrap_or(free);
213        if let Some((path, writer)) = &mut self.csv {
214            let line = format!(
215                "{},{:.3},{},{}\n",
216                csv_field(&self.label),
217                now_ns as f64 / 1e9,
218                free,
219                lowest
220            );
221            if let Err(error) = writer.write_all(line.as_bytes()) {
222                self.failure = Some(format!("{}: {error}", path.display()));
223            }
224        }
225        if let Some(limit) = self.limit
226            && free < limit
227        {
228            self.failure = Some(format!(
229                "free heap {free} dropped below {limit} bytes at {:.3}s",
230                now_ns as f64 / 1e9
231            ));
232        }
233    }
234
235    /// The report lines, the failure that should turn the run red, and the
236    /// samples themselves.
237    fn finish(mut self, mcu: &mut Fleet, now_ns: u64) -> (Vec<String>, Option<String>) {
238        // The end of the run is a sample point in its own right: a leak that
239        // only shows after the last interval must not be missed.
240        if !self.samples.iter().any(|(at, _)| *at == now_ns) {
241            self.record(mcu, now_ns);
242        }
243        let mut lines = Vec::new();
244        if self.samples.is_empty() {
245            let why = self
246                .last_error
247                .unwrap_or_else(|| "the firmware never answered".into());
248            let message = format!("no samples: {why}");
249            // A bare `--heap` is informational, as Wokwi's is; a minimum is a
250            // gate, and a gate that cannot read the heap must fail.
251            return if self.limit.is_some() {
252                (Vec::new(), Some(message))
253            } else {
254                (vec![message], None)
255            };
256        }
257        let first = self.samples[0];
258        let last = *self.samples.last().expect("checked non-empty");
259        let mut last_free = None;
260        for (at, free) in &self.samples {
261            if last_free == Some(*free) {
262                continue;
263            }
264            last_free = Some(*free);
265            lines.push(format!(
266                "[heap {}] {:.3}s free={free} min={}",
267                self.label,
268                *at as f64 / 1e9,
269                self.lowest.unwrap_or(*free)
270            ));
271        }
272        let lost = first.1.saturating_sub(last.1);
273        let seconds = (last.0.saturating_sub(first.0)) as f64 / 1e9;
274        let rate = if seconds > 0.0 {
275            lost as f64 / seconds
276        } else {
277            0.0
278        };
279        lines.push(format!(
280            "Heap: {} samples, free {} -> {}, lowest {}, {:.0} bytes/s lost",
281            self.samples.len(),
282            first.1,
283            last.1,
284            self.lowest.unwrap_or(last.1),
285            rate
286        ));
287        (lines, self.failure)
288    }
289}
290
291/// A CSV field is quoted only when it contains a separator or a quote; board
292/// ids are simple, but a project may name one anything.
293fn csv_field(text: &str) -> String {
294    if text.contains([',', '"', '\n']) {
295        format!("\"{}\"", text.replace('"', "\"\""))
296    } else {
297        text.to_string()
298    }
299}
300
301impl HeapLog {
302    /// The failure so far, for the loop to stop early when the limit is hit.
303    fn failed(&self) -> bool {
304        self.failure.is_some()
305    }
306}
307
308/// Which board to debug, and where to listen for the client.
309///
310/// A GDB session owns the chip's clock for as long as the client is attached,
311/// so one session is served at a time: `board` says which chip, and its
312/// absence picks the first board whose backend has a debug target.
313#[derive(Clone, Debug)]
314pub struct GdbRequest {
315    pub board: Option<String>,
316    pub port: u16,
317}
318
319pub struct Outcome {
320    pub exit_code: i32,
321    pub output: String,
322    /// Simulated milliseconds the run reached, for a report that wants to say
323    /// how much of the timeline a passing test actually looked at.
324    pub sim_ms: u32,
325    /// One entry per `[[test]]`; empty for `run` and `check`.
326    pub tests: Vec<TestOutcome>,
327}
328
329pub struct TestOutcome {
330    pub name: String,
331    pub passed: bool,
332    pub exit_code: i32,
333    pub output: String,
334    pub sim_ms: u32,
335}
336
337/// A run whose console was captured instead of streamed.
338///
339/// `run` writes bytes to stdout as they arrive because a person is watching a
340/// terminal. A host that owns stdout — the MCP server is one — cannot allow
341/// that, so this path collects the same serial text and the part states the
342/// UI would read back.
343pub struct CaptureOutcome {
344    pub exit_code: i32,
345    pub output: String,
346    pub sim_ms: u32,
347    /// Parts whose state is not [`litz_core::PartState::None`], by id.
348    pub part_states: BTreeMap<String, PartState>,
349    /// Electrical faults the board found, in net order.
350    pub faults: Vec<String>,
351}
352
353struct Prepared {
354    config: Config,
355    dir: PathBuf,
356    registry: Registry,
357    circuit: Circuit,
358    /// One entry per development board in diagram order; each boots its own
359    /// image onto its own chip pins.
360    boards: Vec<BoardPlan>,
361}
362
363/// Everything one development board boots and asserts against.
364struct BoardPlan {
365    /// The board instance's id in `diagram.json`.
366    id: String,
367    /// The board's own manifest: which MCU it names, and where its files are.
368    manifest: litz_catalog::PartManifest,
369    flash_size: usize,
370    rom: Vec<u8>,
371    firmware: Vec<u8>,
372    /// The firmware's symbol table, when the project names one.
373    elf: Option<Vec<u8>>,
374    /// Whether `firmware` holds a whole flash image or only an application.
375    layout: FirmwareLayout,
376    bootloader: Option<Vec<u8>>,
377    partition_table: Option<Vec<u8>>,
378    /// The runtime this board's console speaks, and the Python pasted into it.
379    /// The first staged file is the entry the REPL executes; the rest are
380    /// written to the device first so the entry can import them.
381    runtime: Runtime,
382    /// Which Python the console speaks, resolved from the runtime and the
383    /// image name: CircuitPython boots `code.py`, MicroPython `main.py`.
384    python: crate::python::PythonRuntime,
385    scripts: Vec<StagedScript>,
386    mac: [u8; 6],
387}
388
389/// One Python file a MicroPython project stages on the device before it runs.
390struct StagedScript {
391    /// The path on the device, relative to the REPL's working directory.
392    name: String,
393    bytes: Vec<u8>,
394}
395
396pub fn execute(dir: &Path, mode: Mode, strict: bool, update_lock: bool) -> Result<Outcome, String> {
397    execute_with(dir, mode, strict, update_lock, &Options::default())
398}
399
400/// `execute` with recording options: a VCD file and a breakpoint.
401pub fn execute_with(
402    dir: &Path,
403    mode: Mode,
404    strict: bool,
405    update_lock: bool,
406    options: &Options,
407) -> Result<Outcome, String> {
408    let config = match Config::load_project(dir) {
409        Ok(config) => config,
410        Err(e) if mode == Mode::Check => {
411            let _ = e;
412            Config::default()
413        }
414        Err(e) => return Err(e),
415    };
416
417    let mut registry = Registry::builtin();
418    for sub in ["parts", "boards"] {
419        let path = dir.join(sub);
420        if path.is_dir() {
421            registry.load_dir(&path).map_err(|e| e.to_string())?;
422        }
423    }
424
425    let diagram_path = dir.join(config.project.diagram());
426    let text = std::fs::read_to_string(&diagram_path)
427        .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
428    let circuit =
429        Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
430
431    let diagnostics = circuit.validate(&registry);
432    if blocks(&diagnostics, strict) {
433        return Ok(Outcome {
434            exit_code: 1,
435            output: render(&diagnostics),
436            sim_ms: 0,
437            tests: Vec::new(),
438        });
439    }
440
441    if mode == Mode::Check {
442        let mut output = render(&diagnostics);
443        if output.is_empty() {
444            output.push_str("diagram is valid\n");
445        }
446        return Ok(Outcome {
447            exit_code: 0,
448            output,
449            sim_ms: 0,
450            tests: Vec::new(),
451        });
452    }
453
454    let prepared = prepare(config, dir, registry, circuit)?;
455    enforce_lock(&prepared, update_lock)?;
456
457    match mode {
458        Mode::Run => run_once(&prepared, None, strict, options),
459        Mode::Test => {
460            let specs = if prepared.config.test.is_empty() {
461                vec![TestSpec {
462                    name: "run".into(),
463                    timeout: None,
464                    expect: None,
465                    fail: None,
466                    input: Vec::new(),
467                    expect_state: None,
468                    state_at: None,
469                    state_stays: None,
470                }]
471            } else {
472                prepared.config.test.clone()
473            };
474            let mut output = String::new();
475            let mut tests = Vec::new();
476            let mut failed = 0;
477            let mut sim_ms = 0;
478            for spec in &specs {
479                let outcome = run_once(&prepared, Some(spec), strict, options)?;
480                output.push_str(&format!("== {} ==\n", spec.name));
481                output.push_str(&outcome.output);
482                if !outcome.output.ends_with('\n') {
483                    output.push('\n');
484                }
485                if outcome.exit_code != 0 {
486                    failed += 1;
487                }
488                sim_ms = sim_ms.max(outcome.sim_ms);
489                tests.push(TestOutcome {
490                    name: spec.name.clone(),
491                    passed: outcome.exit_code == 0,
492                    exit_code: outcome.exit_code,
493                    output: outcome.output,
494                    sim_ms: outcome.sim_ms,
495                });
496            }
497            Ok(Outcome {
498                exit_code: if failed == 0 { 0 } else { 1 },
499                output: format!(
500                    "{output}{}/{} tests passed\n",
501                    specs.len() - failed,
502                    specs.len()
503                ),
504                sim_ms,
505                tests,
506            })
507        }
508        Mode::Check => unreachable!(),
509    }
510}
511
512/// Boot a project for bounded simulated time, capturing everything.
513///
514/// This is `run` without the terminal: the serial stream is returned rather
515/// than printed, and the part states are read back when the time limit is
516/// reached. A normal bounded run still exits 42, matching the CLI.
517pub fn execute_capture(
518    dir: &Path,
519    timeout: Option<&str>,
520    strict: bool,
521    update_lock: bool,
522    options: &Options,
523) -> Result<CaptureOutcome, String> {
524    let config = Config::load_project(dir)?;
525    let mut registry = Registry::builtin();
526    for sub in ["parts", "boards"] {
527        let path = dir.join(sub);
528        if path.is_dir() {
529            registry.load_dir(&path).map_err(|e| e.to_string())?;
530        }
531    }
532
533    let diagram_path = dir.join(config.project.diagram());
534    let text = std::fs::read_to_string(&diagram_path)
535        .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
536    let circuit =
537        Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
538
539    let diagnostics = circuit.validate(&registry);
540    if blocks(&diagnostics, strict) {
541        return Ok(CaptureOutcome {
542            exit_code: 1,
543            output: render(&diagnostics),
544            sim_ms: 0,
545            part_states: BTreeMap::new(),
546            faults: Vec::new(),
547        });
548    }
549
550    let prepared = prepare(config, dir, registry, circuit)?;
551    enforce_lock(&prepared, update_lock)?;
552    run_capture(&prepared, timeout, options)
553}
554
555/// Run a scenario (`--scenario`) instead of the `[[test]]` entries.
556///
557/// The steps share the boot path with a test and differ only in who decides
558/// when to look at the output: a test polls for its own expectations, a
559/// scenario says what it is waiting for.
560pub fn execute_scenario(
561    dir: &Path,
562    file: &Path,
563    strict: bool,
564    update_lock: bool,
565) -> Result<Outcome, String> {
566    execute_scenario_with(dir, file, strict, update_lock, &Options::default())
567}
568
569/// `execute_scenario` with recording options.
570pub fn execute_scenario_with(
571    dir: &Path,
572    file: &Path,
573    strict: bool,
574    update_lock: bool,
575    options: &Options,
576) -> Result<Outcome, String> {
577    let config = Config::load_project(dir)?;
578    let mut registry = Registry::builtin();
579    for sub in ["parts", "boards"] {
580        let path = dir.join(sub);
581        if path.is_dir() {
582            registry.load_dir(&path).map_err(|e| e.to_string())?;
583        }
584    }
585    let diagram_path = dir.join(config.project.diagram());
586    let text = std::fs::read_to_string(&diagram_path)
587        .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
588    let circuit =
589        Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
590
591    let diagnostics = circuit.validate(&registry);
592    if blocks(&diagnostics, strict) {
593        return Ok(Outcome {
594            exit_code: 1,
595            output: render(&diagnostics),
596            sim_ms: 0,
597            tests: Vec::new(),
598        });
599    }
600
601    let prepared = prepare(config, dir, registry, circuit)?;
602    enforce_lock(&prepared, update_lock)?;
603    let scenario = Scenario::load(file)?;
604    run_scenario(&prepared, &scenario, options)
605}
606
607/// How long `wait-serial` waits when the scenario does not say.
608const DEFAULT_WAIT: u64 = 10_000_000_000;
609
610fn run_scenario(
611    prepared: &Prepared,
612    scenario: &Scenario,
613    options: &Options,
614) -> Result<Outcome, String> {
615    let Booted {
616        fleet: mut mcu,
617        board,
618        capture,
619        ..
620    } = boot(prepared, options)?;
621    start_recording(&mut mcu, options, prepared);
622    let mut heap = HeapLog::from_options(
623        options,
624        prepared
625            .boards
626            .first()
627            .map(|plan| plan.id.clone())
628            .unwrap_or_else(|| "esp".into()),
629    )?;
630    let mut serial = String::new();
631    let mut notes = Vec::new();
632    let mut failed = false;
633    // A tap with `wait: false` releases in the background, so the next step
634    // does not jump the simulated clock by the hold time.
635    let mut last_touch: Vec<Option<(u16, u16)>> = vec![None; prepared.boards.len()];
636    let mut pending_touch: Option<(u64, u16, u16, Option<usize>)> = None;
637
638    // A scenario observes the same console a test does, so MicroPython starts
639    // the same way: wait for the prompt, then paste. A scenario has no
640    // `[[test]]` timeout, so the default wait bounds the boot.
641    for (index, plan) in prepared.boards.iter().enumerate() {
642        if !pastes_script(plan) {
643            continue;
644        }
645        // CircuitPython runs `code.py` on boot, so its console is busy until
646        // Ctrl-C reaches it; MicroPython has nothing to interrupt.
647        if !plan.python.interrupt_sequence().is_empty() {
648            mcu.write_console_on(index, plan.python.interrupt_sequence());
649            advance(&mut mcu, &mut serial);
650        }
651        let deadline = now_ns(&mcu).saturating_add(DEFAULT_WAIT);
652        while !mcu.console_text(index).contains(REPL_PROMPT) {
653            if now_ns(&mcu) >= deadline || !advance(&mut mcu, &mut serial) {
654                break;
655            }
656        }
657        if !mcu.console_text(index).contains(REPL_PROMPT) {
658            return Err(format!(
659                "board {:?}: MicroPython REPL prompt did not appear within {DEFAULT_WAIT} ns of \
660                 simulated time; check that its firmware is a MicroPython or CircuitPython build",
661                plan.id
662            ));
663        }
664        paste_script(&mut mcu, index, &plan.scripts, plan.python);
665    }
666
667    for (index, step) in scenario.steps.iter().enumerate() {
668        let number = index + 1;
669        {
670            let now = now_ns(&mcu);
671            service_touch_release(&mut mcu, &mut pending_touch, now);
672        }
673        match step {
674            Step::Delay { ns } => {
675                let target = now_ns(&mcu).saturating_add(*ns);
676                while now_ns(&mcu) < target && advance(&mut mcu, &mut serial) {
677                    {
678                        let now = now_ns(&mcu);
679                        service_touch_release(&mut mcu, &mut pending_touch, now);
680                    }
681                    if let Some(log) = &mut heap {
682                        {
683                            let now = now_ns(&mcu);
684                            log.sample(&mut mcu, now);
685                        }
686                        if log.failed() {
687                            break;
688                        }
689                    }
690                }
691            }
692            Step::WaitSerial { text, timeout } => {
693                let deadline = now_ns(&mcu).saturating_add(timeout.unwrap_or(DEFAULT_WAIT));
694                while !serial.contains(text.as_str()) {
695                    if now_ns(&mcu) >= deadline {
696                        failed = true;
697                        notes.push(format!("step {number}: never saw {text:?}"));
698                        break;
699                    }
700                    if !advance(&mut mcu, &mut serial) {
701                        break;
702                    }
703                    {
704                        let now = now_ns(&mcu);
705                        service_touch_release(&mut mcu, &mut pending_touch, now);
706                    }
707                    if let Some(log) = &mut heap {
708                        {
709                            let now = now_ns(&mcu);
710                            log.sample(&mut mcu, now);
711                        }
712                        if log.failed() {
713                            break;
714                        }
715                    }
716                }
717            }
718            Step::WriteSerial { text } => {
719                // `write-serial` sends the text as written; it is the
720                // author's job to include the newline the firmware expects.
721                mcu.write_console_on(0, text.as_bytes());
722                advance(&mut mcu, &mut serial);
723            }
724            Step::WaitPin {
725                part,
726                pin,
727                value,
728                timeout,
729            } => {
730                let deadline = now_ns(&mcu).saturating_add(timeout.unwrap_or(DEFAULT_WAIT));
731                loop {
732                    let level = pin_level(prepared, &mcu, part, pin.as_deref());
733                    if level.is_some_and(|level| (level == Level::High) == *value) {
734                        break;
735                    }
736                    if now_ns(&mcu) >= deadline {
737                        failed = true;
738                        notes.push(format!(
739                            "step {number}: {part} never reached {} within {} ns",
740                            if *value { "high" } else { "low" },
741                            timeout.unwrap_or(DEFAULT_WAIT)
742                        ));
743                        break;
744                    }
745                    if !advance(&mut mcu, &mut serial) {
746                        break;
747                    }
748                    {
749                        let now = now_ns(&mcu);
750                        service_touch_release(&mut mcu, &mut pending_touch, now);
751                    }
752                }
753            }
754            Step::ExpectPin { part, pin, value } => {
755                match pin_level(prepared, &mcu, part, pin.as_deref()) {
756                    Some(level) => {
757                        let high = level == Level::High;
758                        if high != *value {
759                            failed = true;
760                            notes.push(format!(
761                                "step {number}: {part} is {} but the scenario expects {}",
762                                if high { "high" } else { "low" },
763                                if *value { "high" } else { "low" }
764                            ));
765                        }
766                    }
767                    None => {
768                        failed = true;
769                        notes.push(format!(
770                            "step {number}: no part {part:?} is wired to a chip pin"
771                        ));
772                    }
773                }
774            }
775            Step::SetControl {
776                part,
777                control,
778                value,
779            } => {
780                if mcu.set_named_control(part, control, value) {
781                    // The part understood the control's own name and unit.
782                } else {
783                    match control.as_str() {
784                        // The potentiometer's control is named `value` and
785                        // measured in percent of travel.
786                        "value" | "position" => match value.trim().parse::<f64>() {
787                            Ok(percent) if (0.0..=100.0).contains(&percent) => {
788                                let permille = (percent * 10.0).round() as u16;
789                                if !mcu.set_control(part, permille) {
790                                    failed = true;
791                                    notes.push(format!(
792                                        "step {number}: part {part:?} has no continuous control"
793                                    ));
794                                }
795                            }
796                            _ => {
797                                failed = true;
798                                notes.push(format!(
799                                "step {number}: set-control value {value:?} is not 0 through 100"
800                            ));
801                            }
802                        },
803                        other => {
804                            failed = true;
805                            notes.push(format!(
806                                "step {number}: part {part:?} has no control {other:?}"
807                            ));
808                        }
809                    }
810                }
811            }
812            Step::TakeScreenshot {
813                part,
814                path,
815                board: which,
816                expected,
817                tolerance,
818            } => {
819                let index = match which {
820                    Some(id) => Some(find_board(&prepared.boards, id, "take-screenshot")?),
821                    None => None,
822                };
823                // A capture with only `compare-with` still needs a file to
824                // write; it lands beside the reference so a failing CI job can
825                // show both pictures.
826                let path = match (path, expected) {
827                    (Some(path), _) => path.clone(),
828                    (None, Some(expected)) => expected.with_extension("actual.png"),
829                    (None, None) => unreachable!("the parser requires one of them"),
830                };
831                let capture = match part {
832                    Some(part) if prepared.boards.iter().any(|plan| plan.id == *part) => {
833                        let board = find_board(&prepared.boards, part, "take-screenshot")?;
834                        mcu.save_display(Some(board), &path)
835                    }
836                    Some(part) => mcu.save_part_display(part, &path),
837                    None => mcu.save_display(index, &path),
838                };
839                match capture {
840                    Ok(()) => {
841                        if let Some(expected) = expected {
842                            match compare_images(&path, expected, *tolerance) {
843                                Ok(()) => {}
844                                Err(error) => {
845                                    failed = true;
846                                    notes.push(format!("step {number}: {error}"));
847                                }
848                            }
849                        }
850                    }
851                    Err(error) => {
852                        failed = true;
853                        notes.push(format!("step {number}: {error}"));
854                    }
855                }
856            }
857            Step::Touch {
858                x,
859                y,
860                down,
861                board: which,
862                part,
863            } => {
864                let index = touch_board(prepared, which, part, "touch")?;
865                if let Err(error) = mcu.touch(index, *x, *y, *down) {
866                    failed = true;
867                    notes.push(format!("step {number}: {error}"));
868                } else if *down {
869                    let slot = index.unwrap_or(0);
870                    if let Some(slot) = last_touch.get_mut(slot) {
871                        *slot = Some((*x, *y));
872                    }
873                }
874            }
875            Step::TouchMove {
876                x,
877                y,
878                board: which,
879                part,
880            } => {
881                let index = touch_board(prepared, which, part, "touch-move")?;
882                if let Err(error) = mcu.touch(index, *x, *y, true) {
883                    failed = true;
884                    notes.push(format!("step {number}: {error}"));
885                } else {
886                    let slot = index.unwrap_or(0);
887                    if let Some(slot) = last_touch.get_mut(slot) {
888                        *slot = Some((*x, *y));
889                    }
890                }
891            }
892            Step::TouchTap {
893                x,
894                y,
895                duration,
896                wait,
897                board: which,
898                part,
899            } => {
900                let index = touch_board(prepared, which, part, "touch")?;
901                if let Err(error) = mcu.touch(index, *x, *y, true) {
902                    failed = true;
903                    notes.push(format!("step {number}: {error}"));
904                } else {
905                    let slot = index.unwrap_or(0);
906                    if let Some(slot) = last_touch.get_mut(slot) {
907                        *slot = Some((*x, *y));
908                    }
909                    let release_at = now_ns(&mcu).saturating_add(*duration);
910                    if *wait {
911                        while now_ns(&mcu) < release_at && advance(&mut mcu, &mut serial) {
912                            {
913                                let now = now_ns(&mcu);
914                                service_touch_release(&mut mcu, &mut pending_touch, now);
915                            }
916                        }
917                        let _ = mcu.touch(index, *x, *y, false);
918                    } else {
919                        pending_touch = Some((release_at, *x, *y, index));
920                    }
921                }
922            }
923            Step::TouchRelease {
924                x,
925                y,
926                board: which,
927                part,
928            } => {
929                let index = touch_board(prepared, which, part, "touch-release")?;
930                let previous = last_touch.get(index.unwrap_or(0)).copied().flatten();
931                let (x, y) = match (x, y) {
932                    (Some(x), Some(y)) => (*x, *y),
933                    _ => previous.unwrap_or((0, 0)),
934                };
935                pending_touch = None;
936                if let Err(error) = mcu.touch(index, x, y, false) {
937                    failed = true;
938                    notes.push(format!("step {number}: {error}"));
939                }
940            }
941        }
942        if let Some(log) = &mut heap {
943            {
944                let now = now_ns(&mcu);
945                log.sample(&mut mcu, now);
946            }
947        }
948        let conflicts = mcu.conflicts();
949        if !conflicts.is_empty() {
950            for conflict in &conflicts {
951                notes.push(format!(
952                    "electrical fault on net {}: {}",
953                    conflict.net, conflict.detail
954                ));
955            }
956            failed = true;
957            break;
958        }
959    }
960
961    let mut output = serial;
962    if !output.ends_with('\n') && !output.is_empty() {
963        output.push('\n');
964    }
965    for note in notes {
966        output.push_str(&format!("litz: {note}\n"));
967    }
968    for line in probe_report(&board) {
969        output.push_str(&format!("litz: {line}\n"));
970    }
971    for line in decode_report(&board, prepared, options)? {
972        output.push_str(&format!("litz: {line}\n"));
973    }
974    finish_recording(&mcu, &board, options, capture.as_ref())?;
975    if let Some(log) = heap {
976        let end = now_ns(&mcu);
977        let (lines, failure) = log.finish(&mut mcu, end);
978        for line in lines {
979            output.push_str(&format!("litz: {line}\n"));
980        }
981        if let Some(failure) = failure {
982            failed = true;
983            output.push_str(&format!("litz: heap: {failure}\n"));
984        }
985    }
986    Ok(Outcome {
987        exit_code: if failed { 1 } else { 0 },
988        output,
989        sim_ms: (mcu.seconds() * 1000.0) as u32,
990        tests: Vec::new(),
991    })
992}
993
994/// A scenario's pin reference, resolved to a level: `part-id` naming a
995/// development board with a GPIO number (`esp`/`2`), an explicit pin name
996/// (`name`), `part:pin` in the part id, or the chip pin the part is on.
997fn pin_level(prepared: &Prepared, mcu: &Fleet, target: &str, pin: Option<&str>) -> Option<Level> {
998    if let Some(index) = prepared.boards.iter().position(|plan| plan.id == target)
999        && let Some(gpio) = pin.and_then(parse_gpio)
1000    {
1001        return mcu.gpio_level(index, gpio);
1002    }
1003    match (target.split_once(':'), pin) {
1004        (Some((part, pin)), _) => mcu.part_pin_level(part, Some(pin)),
1005        (None, Some(pin)) => mcu.part_pin_level(target, Some(pin)),
1006        (None, None) => mcu.part_pin_level(target, None),
1007    }
1008}
1009
1010/// `2`, `GPIO2` or `D2` as a chip pad number.
1011fn parse_gpio(text: &str) -> Option<u8> {
1012    let text = text.trim();
1013    let text = text
1014        .strip_prefix("GPIO")
1015        .or_else(|| text.strip_prefix("gpio"))
1016        .or_else(|| text.strip_prefix('D'))
1017        .or_else(|| text.strip_prefix('d'))
1018        .unwrap_or(text);
1019    text.parse().ok()
1020}
1021
1022fn now_ns(fleet: &Fleet) -> u64 {
1023    fleet.frontier_ns()
1024}
1025
1026/// Release a tap whose hold time has elapsed, so `wait: false` does not stop
1027/// the scenario for the duration of the touch.
1028fn service_touch_release(
1029    mcu: &mut Fleet,
1030    pending: &mut Option<(u64, u16, u16, Option<usize>)>,
1031    now_ns: u64,
1032) {
1033    if let Some((at, x, y, index)) = *pending
1034        && now_ns >= at
1035    {
1036        let _ = mcu.touch(index, x, y, false);
1037        *pending = None;
1038    }
1039}
1040
1041/// Compare a captured image with a golden one, per pixel, so a report names a
1042/// coordinate rather than a byte offset inside a compressed stream. The
1043/// tolerance is per colour channel: 0 demands the same pixels exactly.
1044fn compare_images(actual: &Path, expected: &Path, tolerance: u8) -> Result<(), String> {
1045    let actual_image = decode_png(actual)?;
1046    let expected_image = decode_png(expected)?;
1047    if actual_image.0 != expected_image.0 || actual_image.1 != expected_image.1 {
1048        return Err(format!(
1049            "screenshot {} is {}x{} but {} is {}x{}",
1050            actual.display(),
1051            actual_image.0,
1052            actual_image.1,
1053            expected.display(),
1054            expected_image.0,
1055            expected_image.1
1056        ));
1057    }
1058    let (width, _, actual_pixels) = actual_image;
1059    let (_, _, expected_pixels) = expected_image;
1060    let mut mismatched = 0usize;
1061    let mut first = None;
1062    for (index, (a, b)) in actual_pixels.iter().zip(&expected_pixels).enumerate() {
1063        let differs = a.iter().zip(b).any(|(a, b)| a.abs_diff(*b) > tolerance);
1064        if differs {
1065            mismatched += 1;
1066            first.get_or_insert(index);
1067        }
1068    }
1069    if let Some(index) = first {
1070        let x = index as u32 % width;
1071        let y = index as u32 / width;
1072        return Err(format!(
1073            "screenshot {} differs from {} at ({x}, {y}) in {width}x{} pixels; \
1074             {mismatched} pixels differ",
1075            actual.display(),
1076            expected.display(),
1077            actual_pixels.len() as u32 / width.max(1)
1078        ));
1079    }
1080    Ok(())
1081}
1082
1083/// Decode a PNG to RGBA8. A reference image may use any colour type; the
1084/// comparison runs on the same pixels a display would show.
1085fn decode_png(path: &Path) -> Result<(u32, u32, Vec<[u8; 4]>), String> {
1086    let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
1087    let mut decoder = png::Decoder::new(std::io::BufReader::new(file));
1088    decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
1089    let mut reader = decoder
1090        .read_info()
1091        .map_err(|e| format!("{}: {e}", path.display()))?;
1092    let size = reader
1093        .output_buffer_size()
1094        .ok_or_else(|| format!("{}: the image is too large to decode", path.display()))?;
1095    let mut buffer = vec![0; size];
1096    let info = reader
1097        .next_frame(&mut buffer)
1098        .map_err(|e| format!("{}: {e}", path.display()))?;
1099    let pixels = match info.color_type {
1100        png::ColorType::Rgba => buffer.as_chunks::<4>().0.to_vec(),
1101        png::ColorType::Rgb => buffer
1102            .as_chunks::<3>()
1103            .0
1104            .iter()
1105            .map(|p| [p[0], p[1], p[2], 255])
1106            .collect(),
1107        png::ColorType::GrayscaleAlpha => buffer
1108            .as_chunks::<2>()
1109            .0
1110            .iter()
1111            .map(|p| [p[0], p[0], p[0], p[1]])
1112            .collect(),
1113        png::ColorType::Grayscale => buffer.iter().map(|p| [*p, *p, *p, 255]).collect(),
1114        png::ColorType::Indexed => {
1115            return Err(format!(
1116                "{}: an indexed PNG did not expand to RGB",
1117                path.display()
1118            ));
1119        }
1120    };
1121    Ok((info.width, info.height, pixels))
1122}
1123
1124/// Arm the breakpoint and the waveform before the first instruction runs, so
1125/// time 0 of the trace is the board as the chip first sees it.
1126fn start_recording(mcu: &mut Fleet, options: &Options, prepared: &Prepared) {
1127    if let Some(pc) = options.break_at {
1128        mcu.break_at(pc);
1129    }
1130    // A probe's record is the net trace, so asking for one starts the same
1131    // recording a VCD does.
1132    let wants_trace = options.vcd.is_some()
1133        || options.scope.is_some()
1134        || !prepared.config.probes.is_empty()
1135        || !prepared.config.decodes.is_empty()
1136        || !options.probes.is_empty()
1137        || !options.decodes.is_empty();
1138    if wants_trace {
1139        mcu.start_trace();
1140    }
1141}
1142
1143fn finish_recording(
1144    mcu: &Fleet,
1145    board: &std::rc::Rc<std::cell::RefCell<Board>>,
1146    options: &Options,
1147    capture: Option<&std::rc::Rc<std::cell::RefCell<litz_net::capture::Capture>>>,
1148) -> Result<(), String> {
1149    if let (Some(path), Some(capture)) = (&options.pcap, capture) {
1150        std::fs::write(path, capture.borrow().to_pcap())
1151            .map_err(|e| format!("{}: {e}", path.display()))?;
1152    }
1153    if let Some(path) = &options.vcd {
1154        std::fs::write(path, mcu.vcd()).map_err(|e| format!("{}: {e}", path.display()))?;
1155    }
1156    if let Some(path) = &options.sd_export {
1157        board.borrow_mut().save_sd_images(path)?;
1158    }
1159    if let Some(path) = &options.scope {
1160        let channels = board.borrow().scope();
1161        let csv = match &options.trigger {
1162            Some(trigger) => {
1163                let clipped = probe::triggered(&channels, trigger)?;
1164                probe::to_csv(&clipped)
1165            }
1166            None => probe::to_csv(&channels),
1167        };
1168        std::fs::write(path, csv).map_err(|e| format!("{}: {e}", path.display()))?;
1169    }
1170    Ok(())
1171}
1172
1173/// One summary line per probe, for a run that wants to say what the wires did.
1174fn probe_report(board: &std::rc::Rc<std::cell::RefCell<Board>>) -> Vec<String> {
1175    board.borrow().scope().iter().map(probe::summary).collect()
1176}
1177
1178/// One line per frame of every configured decoder, project entries first.
1179fn decode_report(
1180    board: &std::rc::Rc<std::cell::RefCell<Board>>,
1181    prepared: &Prepared,
1182    options: &Options,
1183) -> Result<Vec<String>, String> {
1184    let channels = board.borrow().scope();
1185    crate::decode::report(
1186        prepared.config.decodes.iter().chain(options.decodes.iter()),
1187        &channels,
1188    )
1189}
1190
1191/// One chunk of simulated time. False when the board reported a fault.
1192fn advance(mcu: &mut Fleet, serial: &mut String) -> bool {
1193    let _ = mcu.run(1_000_000);
1194    let chunk = mcu.take_console();
1195    if !chunk.is_empty() {
1196        serial.push_str(&String::from_utf8_lossy(&chunk));
1197    }
1198    mcu.conflicts().is_empty()
1199}
1200
1201/// Whether the project asks for a script to be pasted into a Python REPL.
1202/// `runtime = "micropython"` with no `script` still means "run this firmware",
1203/// just without the handshake.
1204fn pastes_script(plan: &BoardPlan) -> bool {
1205    matches!(plan.runtime, Runtime::Micropython | Runtime::CircuitPython)
1206        && !plan.scripts.is_empty()
1207}
1208
1209/// Read one project file as a Python source to stage.
1210fn read_staged(dir: &Path, rel: &str) -> Result<StagedScript, String> {
1211    let path = dir.join(rel);
1212    let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1213    if bytes.len() > MAX_SCRIPT {
1214        return Err(format!(
1215            "{} is {} bytes; a MicroPython raw paste is limited to {MAX_SCRIPT} bytes",
1216            path.display(),
1217            bytes.len()
1218        ));
1219    }
1220    Ok(StagedScript {
1221        name: staged_name(rel)?,
1222        bytes,
1223    })
1224}
1225
1226/// A stage path must stay inside the REPL's working directory, so a project
1227/// file cannot write over `/boot.py` or escape with `..`.
1228fn staged_name(name: &str) -> Result<String, String> {
1229    let name = name.trim().replace('\\', "/");
1230    let invalid = name.is_empty()
1231        || name.starts_with('/')
1232        || name
1233            .split('/')
1234            .any(|part| part.is_empty() || part == "." || part == "..");
1235    if invalid {
1236        return Err(format!(
1237            "staged script {name:?} must be a relative path inside the project, \
1238             like \"main.py\" or \"lib/util.py\""
1239        ));
1240    }
1241    Ok(name)
1242}
1243
1244/// Interrupt whatever is running, then send MicroPython's raw-paste sequence:
1245/// Ctrl-C (0x03), Ctrl-A (0x01) to enter the raw REPL, the script bytes, and
1246/// Ctrl-D (0x04) to compile and run them. The chip queues the bytes and paces
1247/// them at the UART's line rate, so the interpreter sees them in this order
1248/// however small its receive FIFO is.
1249fn paste_script(
1250    mcu: &mut Fleet,
1251    index: usize,
1252    scripts: &[StagedScript],
1253    python: crate::python::PythonRuntime,
1254) {
1255    // One file is the script itself, exactly as before; several become a
1256    // bootstrap that writes each file and then executes the entry.
1257    let body = if scripts.len() == 1 {
1258        scripts[0].bytes.clone()
1259    } else {
1260        let pairs: Vec<(&str, &[u8])> = scripts
1261            .iter()
1262            .map(|script| (script.name.as_str(), script.bytes.as_slice()))
1263            .collect();
1264        crate::python::stage_program(&scripts[0].name, &pairs).into_bytes()
1265    };
1266    let mut bytes = Vec::with_capacity(body.len() + 4);
1267    // Ctrl-C stops whatever CircuitPython started on boot; MicroPython lands
1268    // at a prompt already, but the byte is harmless there.
1269    let interrupt = python.interrupt_sequence();
1270    if interrupt.is_empty() {
1271        bytes.push(0x03);
1272    } else {
1273        bytes.extend_from_slice(interrupt);
1274    }
1275    bytes.extend_from_slice(python.raw_paste_begin());
1276    bytes.extend_from_slice(&body);
1277    bytes.extend_from_slice(python.raw_paste_end());
1278    // The host side of the UART is a queue; a classic ESP32 with a small
1279    // receive FIFO drops a burst that is written all at once. Feeding it in
1280    // small slices and letting the chip run between them keeps the byte
1281    // stream intact without a wall-clock sleep.
1282    for chunk in bytes.chunks(16) {
1283        mcu.write_console_to(index, chunk);
1284        mcu.run_one(index, 1_000_000);
1285    }
1286}
1287
1288fn prepare(
1289    config: Config,
1290    dir: &Path,
1291    registry: Registry,
1292    circuit: Circuit,
1293) -> Result<Prepared, String> {
1294    // Every development board on the diagram is its own chip with its own
1295    // image; the diagram is what says how many there are.
1296    let instances: Vec<litz_diagram::PartInstance> = circuit
1297        .parts
1298        .iter()
1299        .filter(|part| {
1300            registry
1301                .get(&part.type_key)
1302                .and_then(|manifest| manifest.board.as_ref())
1303                .is_some()
1304        })
1305        .cloned()
1306        .collect();
1307    if instances.is_empty() {
1308        return Err("the diagram has no development board".into());
1309    }
1310
1311    // `[[board]]` names each instance. A project with one board keeps using
1312    // `[sim]`; the moment a second board appears there is no sensible default
1313    // for which image goes where, so both boards must be named.
1314    let sections: Vec<BoardSection> = if config.boards.is_empty() {
1315        if instances.len() != 1 {
1316            return Err(format!(
1317                "the diagram has {} development boards; give each one a [[board]] entry with its id and firmware",
1318                instances.len()
1319            ));
1320        }
1321        vec![BoardSection {
1322            id: instances[0].id.clone(),
1323            firmware: config.sim.firmware.clone(),
1324            bootloader: config.sim.bootloader.clone(),
1325            partition_table: config.sim.partition_table.clone(),
1326            rom: config.sim.rom.clone(),
1327            elf: config.sim.elf.clone(),
1328            runtime: Some(config.sim.runtime),
1329            script: config.sim.script.clone(),
1330            scripts: config.sim.scripts.clone(),
1331            flash_size: config.sim.flash_size.clone(),
1332            mac: config.sim.mac.clone(),
1333        }]
1334    } else {
1335        if config.sim.firmware.is_some() {
1336            return Err(
1337                "a project with [[board]] entries names firmware per board; remove [sim] firmware"
1338                    .into(),
1339            );
1340        }
1341        let mut sections = Vec::with_capacity(instances.len());
1342        for instance in &instances {
1343            let mut found: Vec<&BoardSection> = config
1344                .boards
1345                .iter()
1346                .filter(|section| section.id == instance.id)
1347                .collect();
1348            match found.len() {
1349                1 => sections.push(found.remove(0).clone()),
1350                0 => {
1351                    return Err(format!(
1352                        "board {:?} in diagram.json has no [[board]] entry; add `id = {:?}` to one",
1353                        instance.id, instance.id
1354                    ));
1355                }
1356                _ => {
1357                    return Err(format!("[[board]] names {:?} more than once", instance.id));
1358                }
1359            }
1360        }
1361        if let Some(unknown) = config
1362            .boards
1363            .iter()
1364            .find(|section| !instances.iter().any(|instance| instance.id == section.id))
1365        {
1366            return Err(format!(
1367                "[[board]] id {:?} is not a development board in diagram.json",
1368                unknown.id
1369            ));
1370        }
1371        sections
1372    };
1373
1374    let mut boards = Vec::with_capacity(sections.len());
1375    for (section, instance) in sections.iter().zip(&instances) {
1376        boards.push(prepare_board(&config, dir, &registry, instance, section)?);
1377    }
1378    Ok(Prepared {
1379        config,
1380        dir: dir.to_path_buf(),
1381        registry,
1382        circuit,
1383        boards,
1384    })
1385}
1386
1387/// Read one board's images and work out how they boot.
1388fn prepare_board(
1389    config: &Config,
1390    dir: &Path,
1391    registry: &Registry,
1392    instance: &litz_diagram::PartInstance,
1393    section: &BoardSection,
1394) -> Result<BoardPlan, String> {
1395    let manifest = registry
1396        .get(&instance.type_key)
1397        .expect("the caller filtered on boards")
1398        .clone();
1399    let info = manifest
1400        .board
1401        .as_ref()
1402        .expect("the caller filtered on boards");
1403    let chip = info.chip.as_deref();
1404    // A builtin chip is one the adapters carry; anything else must be a
1405    // `[board.simulator]` module, which brings its own boot code.
1406    if let Some(name) = chip
1407        && !is_builtin_chip(name)
1408    {
1409        return Err(format!(
1410            "board {:?}: chip {name:?} is not built in; name a wasm component under \
1411             [board.simulator] instead",
1412            instance.id
1413        ));
1414    }
1415
1416    let flash_size = section
1417        .flash_size
1418        .as_deref()
1419        .or(config.sim.flash_size.as_deref())
1420        .map(parse_size)
1421        .transpose()?
1422        .or_else(|| info.flash_size.as_deref().and_then(|s| parse_size(s).ok()))
1423        .unwrap_or(4 * 1024 * 1024);
1424
1425    // A wasm simulator carries its own boot code and may ship a program in
1426    // flash, so a project can run it with no firmware at all. A built-in chip
1427    // needs an image: there is nothing in the adapter to execute otherwise.
1428    let (firmware, layout) = match section.firmware.as_deref() {
1429        Some(rel) => {
1430            let path = dir.join(rel);
1431            let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1432            let layout = image::detect(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
1433            (bytes, layout)
1434        }
1435        None if info.simulator.is_some() => (Vec::new(), FirmwareLayout::Application),
1436        None => {
1437            return Err(format!(
1438                "board {:?} has no firmware; give it `firmware = \"...\"`",
1439                instance.id
1440            ));
1441        }
1442    };
1443
1444    let bootloader_rel = section
1445        .bootloader
1446        .as_deref()
1447        .or(config.sim.bootloader.as_deref());
1448    let ptable_rel = section
1449        .partition_table
1450        .as_deref()
1451        .or(config.sim.partition_table.as_deref());
1452    // A merged image already carries the bootloader and partition table; the
1453    // separate files would be written a second time, at different offsets.
1454    if layout == FirmwareLayout::Merged && (bootloader_rel.is_some() || ptable_rel.is_some()) {
1455        return Err(format!(
1456            "board {:?}: the firmware is a merged image (bootloader at 0x0, \
1457             partition table at 0x8000, application at 0x10000); remove \
1458             `bootloader` and `partition_table`",
1459            instance.id
1460        ));
1461    }
1462    let bootloader = read_optional(dir, bootloader_rel)?;
1463    let partition_table = read_optional(dir, ptable_rel)?;
1464
1465    let elf_rel = section.elf.as_deref().or(config.sim.elf.as_deref());
1466    let elf = match elf_rel {
1467        Some(rel) => {
1468            let path = dir.join(rel);
1469            Some(std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?)
1470        }
1471        None => None,
1472    };
1473
1474    let runtime = section.runtime.unwrap_or(config.sim.runtime);
1475    let script_rel = section.script.as_deref().or(config.sim.script.as_deref());
1476    let staged = if section.scripts.is_empty() {
1477        &config.sim.scripts
1478    } else {
1479        &section.scripts
1480    };
1481    let scripts = match runtime {
1482        Runtime::Micropython | Runtime::CircuitPython => {
1483            let mut scripts = Vec::new();
1484            if let Some(rel) = script_rel {
1485                scripts.push(read_staged(dir, rel)?);
1486            }
1487            for spec in staged {
1488                // `name = path` stages a project file under a different name;
1489                // a bare path keeps its own relative path on the device.
1490                let (name, rel) = match spec.split_once('=') {
1491                    Some((name, path)) => (name.trim(), path.trim()),
1492                    None => (spec.trim(), spec.trim()),
1493                };
1494                if scripts.iter().any(|script| script.name == name) {
1495                    return Err(format!(
1496                        "board {:?}: two scripts would be staged as {name:?}",
1497                        instance.id
1498                    ));
1499                }
1500                let mut script = read_staged(dir, rel)?;
1501                script.name = staged_name(name)?;
1502                scripts.push(script);
1503            }
1504            let total: usize = scripts.iter().map(|script| script.bytes.len()).sum();
1505            if total > MAX_SCRIPT {
1506                return Err(format!(
1507                    "board {:?}: the staged scripts total {total} bytes; a Python raw \
1508                     paste is limited to {MAX_SCRIPT} bytes",
1509                    instance.id
1510                ));
1511            }
1512            // CircuitPython boots `code.py` (or `main.py`); whichever the
1513            // project staged as its entry runs first, whatever order it was
1514            // written in.
1515            if runtime == Runtime::CircuitPython {
1516                if let Some(entry) = scripts
1517                    .iter()
1518                    .position(|script| matches!(script.name.as_str(), "code.py" | "main.py"))
1519                {
1520                    let entry = scripts.remove(entry);
1521                    scripts.insert(0, entry);
1522                } else {
1523                    return Err(format!(
1524                        "board {:?}: CircuitPython needs code.py or main.py among its scripts",
1525                        instance.id
1526                    ));
1527                }
1528            }
1529            scripts
1530        }
1531        Runtime::Native => {
1532            if script_rel.is_some() || !staged.is_empty() {
1533                return Err(format!(
1534                    "board {:?}: script/scripts need runtime = \"micropython\" or \
1535                     \"circuitpython\"; a native firmware has no REPL to paste them into",
1536                    instance.id
1537                ));
1538            }
1539            Vec::new()
1540        }
1541    };
1542
1543    // A plain application image boots from a direct jump and never touches the
1544    // mask ROM. A merged image does: its first bytes are the bootloader, which
1545    // only the ROM knows how to start.
1546    let needs_rom = layout == FirmwareLayout::Merged || bootloader.is_some();
1547    let rom_rel = section.rom.as_deref().or(config.sim.rom.as_deref());
1548    let rom_path = rom_rel.map(PathBuf::from).or_else(|| {
1549        chip.and_then(rom_name)
1550            .and_then(|file| std::env::var_os("LITZ_ROM_DIR").map(|d| PathBuf::from(d).join(file)))
1551    });
1552    let rom = match rom_path {
1553        Some(path) => std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?,
1554        None if needs_rom => {
1555            return Err(format!(
1556                "board {:?}: {}; set `rom` in its [[board]] entry or in [sim], or LITZ_ROM_DIR",
1557                instance.id,
1558                if layout == FirmwareLayout::Merged {
1559                    "a merged image runs from the mask ROM"
1560                } else {
1561                    "a bootloader needs the mask ROM"
1562                }
1563            ));
1564        }
1565        None => Vec::new(),
1566    };
1567
1568    // The image name is the cheapest hint; a stock image whose file is named
1569    // generically still announces itself in its banner bytes.
1570    let python = crate::python::detect(runtime, section.firmware.as_deref().unwrap_or(""));
1571    let python = if python == crate::python::PythonRuntime::MicroPython {
1572        crate::python::detect_bytes(runtime, &firmware)
1573    } else {
1574        python
1575    };
1576    Ok(BoardPlan {
1577        id: instance.id.clone(),
1578        manifest,
1579        flash_size,
1580        rom,
1581        firmware,
1582        elf,
1583        layout,
1584        bootloader,
1585        partition_table,
1586        runtime,
1587        python,
1588        scripts,
1589        mac: parse_mac(section.mac.as_deref().or(config.sim.mac.as_deref())),
1590    })
1591}
1592
1593/// Check `litz.lock` against what this run would use, or write it when there
1594/// is none yet. A changed catalog or firmware is refused: the whole point is
1595/// that a green run can be repeated, and silently running a different
1596/// simulation would make the record a lie.
1597fn enforce_lock(prepared: &Prepared, update: bool) -> Result<(), String> {
1598    // One board records the same four hashes as before. Several boards have no
1599    // single `[firmware]` to describe them, so their images are folded into the
1600    // firmware hash in board order, each with its id and length; the run is
1601    // still repeatable when every byte that booted is in that hash.
1602    let (firmware, rom, bootloader, ptable) = if prepared.boards.len() == 1 {
1603        let plan = &prepared.boards[0];
1604        (
1605            Some(plan.firmware.clone()),
1606            (!plan.rom.is_empty()).then(|| plan.rom.clone()),
1607            plan.bootloader.clone(),
1608            plan.partition_table.clone(),
1609        )
1610    } else {
1611        let mut folded = Vec::new();
1612        for plan in &prepared.boards {
1613            folded.extend_from_slice(plan.id.as_bytes());
1614            folded.push(0);
1615            for image in [&plan.firmware, &plan.rom] {
1616                folded.extend_from_slice(&(image.len() as u64).to_le_bytes());
1617                folded.extend_from_slice(image);
1618            }
1619        }
1620        (Some(folded), None, None, None)
1621    };
1622    // Only the manifests this diagram actually expands go in the lock: an
1623    // entry the circuit never names cannot change the result, and hashing it
1624    // would rewrite every lock in the world when an unrelated part is added.
1625    let flat =
1626        FlatBoard::build(&prepared.circuit, &prepared.registry).map_err(|e| e.to_string())?;
1627    // The board itself is consumed by expansion, so its own manifest has to
1628    // come from the diagram rather than from the flattened part list.
1629    let used: std::collections::BTreeSet<&str> = prepared
1630        .circuit
1631        .parts
1632        .iter()
1633        .map(|part| part.type_key.as_str())
1634        .chain(flat.parts.iter().map(|part| part.type_key.as_str()))
1635        .collect();
1636    let manifests: Vec<_> = prepared
1637        .registry
1638        .manifest_texts()
1639        .into_iter()
1640        .filter(|(key, _, _)| used.contains(key.as_str()))
1641        .collect();
1642    let actual = Lock::from_run(
1643        &manifests,
1644        firmware.as_deref(),
1645        rom.as_deref(),
1646        bootloader.as_deref(),
1647        ptable.as_deref(),
1648    );
1649    let path = prepared.dir.join("litz.lock");
1650    if update || !path.exists() {
1651        actual.write(&path)?;
1652        eprintln!("litz: wrote {}", path.display());
1653        return Ok(());
1654    }
1655    let installed = Lock::load(&path)?;
1656    installed.check(&actual)
1657}
1658
1659/// The ROM ELF esp32sim expects for a builtin chip; `None` when the name is
1660/// not one of the adapters this build carries.
1661/// Chips an in-tree adapter can build, whether or not they need a mask ROM.
1662pub(crate) fn is_builtin_chip(chip: &str) -> bool {
1663    matches!(
1664        chip,
1665        "esp32"
1666            | "esp32c3"
1667            | "esp32c6"
1668            | "esp32s3"
1669            | "esp32p4"
1670            | "esp32s31"
1671            | "atmega328p"
1672            | "rp2040"
1673    )
1674}
1675
1676fn rom_name(chip: &str) -> Option<&'static str> {
1677    Some(match chip {
1678        "esp32" => "esp32_rev300_rom.elf",
1679        "esp32c3" => "esp32c3_rev3_rom.elf",
1680        "esp32c6" => "esp32c6_rev0_rom.elf",
1681        "esp32s3" => "esp32s3_rev0_rom.elf",
1682        "esp32p4" => "esp32p4_rev0_rom.elf",
1683        "esp32s31" => "esp32s31_rev0_rom.elf",
1684        _ => return None,
1685    })
1686}
1687
1688/// The radio network for this run: `--wifi` wins over `[sim.wifi]`, and a
1689/// project with neither gets no network at all.
1690///
1691/// The router's default services are HTTP on port 80 and a TCP echo on 7, so a
1692/// firmware that joins the access point has something to talk to without any
1693/// further configuration; a project that lists `[[sim.wifi.service]]` entries
1694/// replaces the defaults, and `[sim.wifi] services = false` leaves a router
1695/// that refuses every connection.
1696fn network_config(options: &Options, config: &Config) -> Result<Option<NetworkConfig>, String> {
1697    let spec = match (&options.wifi, &config.sim.wifi) {
1698        (Some(spec), _) => WifiSpec::Spec(spec.clone()),
1699        (None, Some(spec)) => spec.clone(),
1700        (None, None) => return Ok(None),
1701    };
1702
1703    let mut network = match &spec {
1704        WifiSpec::Spec(raw) => NetworkConfig {
1705            access_points: vec![access_point_from_spec(raw)?],
1706            ..NetworkConfig::default()
1707        },
1708        WifiSpec::Table(table) => {
1709            let mut network = NetworkConfig {
1710                access_points: vec![access_point(
1711                    &table.ssid,
1712                    table.psk.as_deref(),
1713                    table.channel,
1714                    table.bssid.as_deref().map(parse_bssid).transpose()?,
1715                    table.epoch,
1716                )],
1717                nearby: table
1718                    .nearby
1719                    .iter()
1720                    .map(|nearby| nearby_from_spec(nearby))
1721                    .collect::<Result<Vec<_>, String>>()?,
1722                resolve_unknown: table.resolve_unknown,
1723                ..NetworkConfig::default()
1724            };
1725            for extra in &table.extra_aps {
1726                network.access_points.push(access_point(
1727                    &extra.ssid,
1728                    extra.psk.as_deref(),
1729                    extra.channel,
1730                    extra.bssid.as_deref().map(parse_bssid).transpose()?,
1731                    extra.epoch,
1732                ));
1733            }
1734            for (name, address) in &table.names {
1735                let address: std::net::Ipv4Addr = address.parse().map_err(|_| {
1736                    format!("[sim.wifi] names.{name}: {address:?} is not an IPv4 address")
1737                })?;
1738                network.names.insert(name.clone(), address.octets());
1739            }
1740            network
1741        }
1742    };
1743
1744    match &spec {
1745        WifiSpec::Spec(_) => {
1746            network = network.with_default_services();
1747        }
1748        WifiSpec::Table(table) if table.services.is_empty() => {
1749            if table.services_default {
1750                network = network.with_default_services();
1751            }
1752        }
1753        WifiSpec::Table(table) => {
1754            for service in &table.services {
1755                let inner = if service.mqtt {
1756                    Service::mqtt(service.port)
1757                } else if service.websocket {
1758                    Service::websocket(service.port)
1759                } else if service.echo {
1760                    if service.udp {
1761                        Service::UdpEcho { port: service.port }
1762                    } else {
1763                        Service::TcpEcho { port: service.port }
1764                    }
1765                } else {
1766                    let reply = service.reply.as_ref().ok_or_else(|| {
1767                        format!(
1768                            "[sim.wifi.service] port {}: give `reply = \"...\"`, `echo = true`, \
1769                             `websocket = true` or `mqtt = true`",
1770                            service.port
1771                        )
1772                    })?;
1773                    Service::Tcp {
1774                        port: service.port,
1775                        reply: reply.as_bytes().to_vec(),
1776                        after_request: service.wait,
1777                    }
1778                };
1779                network = network.with_service(if service.tls {
1780                    Service::tls(service.port, inner)
1781                } else {
1782                    inner
1783                });
1784            }
1785        }
1786    }
1787    Ok(Some(network))
1788}
1789
1790fn access_point(
1791    ssid: &str,
1792    psk: Option<&str>,
1793    channel: Option<u8>,
1794    bssid: Option<[u8; 6]>,
1795    epoch: Option<u64>,
1796) -> AccessPoint {
1797    AccessPoint {
1798        ssid: ssid.to_string(),
1799        psk: psk.map(str::to_string),
1800        channel: channel.unwrap_or(6),
1801        bssid,
1802        epoch_s: epoch,
1803    }
1804}
1805
1806/// An access point in the short `--wifi` syntax: `ssid=NAME[,psk=PASS]
1807/// [,channel=N][,bssid=..][,epoch=S]`.
1808fn access_point_from_spec(spec: &str) -> Result<AccessPoint, String> {
1809    let mut ssid = None;
1810    let mut psk = None;
1811    let mut channel = None;
1812    let mut bssid = None;
1813    let mut epoch = None;
1814    for entry in spec.split(',').filter(|entry| !entry.is_empty()) {
1815        let (key, value) = entry
1816            .split_once('=')
1817            .ok_or_else(|| format!("invalid Wi-Fi option {entry:?}: expected key=value"))?;
1818        match key {
1819            "ssid" => ssid = Some(value.to_string()),
1820            "psk" | "password" | "pass" => psk = Some(value.to_string()),
1821            "channel" | "chan" | "ch" => {
1822                channel = Some(value.parse::<u8>().map_err(|_| {
1823                    format!("invalid Wi-Fi channel {value:?}: expected 1 through 14")
1824                })?)
1825            }
1826            "bssid" => bssid = Some(parse_bssid(value)?),
1827            "epoch" => {
1828                epoch = Some(value.parse::<u64>().map_err(|_| {
1829                    format!("invalid Wi-Fi epoch {value:?}: expected seconds since 1970")
1830                })?)
1831            }
1832            other => return Err(format!("unknown Wi-Fi option {other:?}")),
1833        }
1834    }
1835    let ssid = ssid.ok_or_else(|| format!("invalid Wi-Fi network {spec:?}: no ssid"))?;
1836    Ok(access_point(&ssid, psk.as_deref(), channel, bssid, epoch))
1837}
1838
1839fn nearby_from_spec(spec: &str) -> Result<NearbyNetwork, String> {
1840    let mut network = NearbyNetwork::new("");
1841    for entry in spec.split(',').filter(|entry| !entry.is_empty()) {
1842        let (key, value) = entry.split_once('=').ok_or_else(|| {
1843            format!("invalid nearby-network option {entry:?}: expected key=value")
1844        })?;
1845        match key {
1846            "ssid" => network.ssid = value.to_string(),
1847            "channel" | "chan" | "ch" => {
1848                network.channel = value.parse().map_err(|_| {
1849                    format!("invalid nearby-network channel {value:?}: expected 1 through 14")
1850                })?
1851            }
1852            "rssi" => {
1853                network.rssi = value.parse().map_err(|_| {
1854                    format!("invalid nearby-network rssi {value:?}: expected -128 through 127 dBm")
1855                })?
1856            }
1857            "secure" => {
1858                network.secure = match value {
1859                    "1" | "true" | "yes" => true,
1860                    "0" | "false" | "no" => false,
1861                    _ => {
1862                        return Err(format!(
1863                            "invalid nearby-network secure {value:?}: expected 0 or 1"
1864                        ));
1865                    }
1866                }
1867            }
1868            other => return Err(format!("unknown nearby-network option {other:?}")),
1869        }
1870    }
1871    if network.ssid.is_empty() {
1872        return Err(format!("invalid nearby network {spec:?}: no ssid"));
1873    }
1874    Ok(network)
1875}
1876
1877fn parse_bssid(text: &str) -> Result<[u8; 6], String> {
1878    let octets: Vec<u8> = text
1879        .split(':')
1880        .map(|octet| {
1881            u8::from_str_radix(octet, 16)
1882                .map_err(|_| format!("invalid BSSID {text:?}: expected six hex octets"))
1883        })
1884        .collect::<Result<_, _>>()?;
1885    octets
1886        .try_into()
1887        .map_err(|_| format!("invalid BSSID {text:?}: expected six hex octets"))
1888}
1889
1890/// Build the boards, load each image and start every chip. A test and a
1891/// scenario differ only in what they do once it is running.
1892///
1893/// The backend is chosen by each board's manifest: a builtin `chip` is an
1894/// adapter this build carries, a `[board.simulator]` module is a wasm
1895/// component. Everything after this point is written against [`Fleet`], so the
1896/// backends are interchangeable and a diagram may run more than one.
1897fn boot(prepared: &Prepared, options: &Options) -> Result<Booted, String> {
1898    let flat =
1899        FlatBoard::build(&prepared.circuit, &prepared.registry).map_err(|e| e.to_string())?;
1900    let parts: Vec<String> = flat.parts.iter().map(|p| p.id.clone()).collect();
1901    let mut board = Board::new(flat)
1902        .map_err(|e| e.to_string())?
1903        .with_analog(options.analog || prepared.config.sim.analog);
1904    // Probes are resolved before any time passes: a point that is not in the
1905    // diagram is a configuration error, not a channel that silently stays
1906    // empty. The project lists them, and a run may add more.
1907    for probe in &prepared.config.probes {
1908        let name = probe.name.as_deref().unwrap_or(probe.point.as_str());
1909        board.add_probe(name, &probe.point)?;
1910    }
1911    for spec in &options.probes {
1912        // `--probe sck=esp:GPIO2` names the channel and the point; a bare
1913        // point keeps its own name, as the project's probe entries do.
1914        let (name, point) = match spec.split_once('=') {
1915            Some((name, point)) => (name.trim(), point.trim()),
1916            None => (spec.as_str(), spec.as_str()),
1917        };
1918        board.add_probe(name, point)?;
1919    }
1920    // A decoder reads channels, so every name it mentions must already be a
1921    // probe. Checking here keeps a typo from producing an empty report after
1922    // a full run.
1923    for spec in prepared.config.decodes.iter().chain(options.decodes.iter()) {
1924        crate::decode::check(spec, board.probes())?;
1925    }
1926    // A `litz-wifi-router` part and a `litz-ble-beacon` part belong to the
1927    // board, so every chip on it hears the same network and the same
1928    // advertisers; `[sim.wifi]` or `--wifi` replaces the network for one run.
1929    let mut network =
1930        network_config(options, &prepared.config)?.or_else(|| board.network().cloned());
1931    let capture = if options.pcap.is_some() {
1932        let Some(config) = network.as_mut() else {
1933            return Err(
1934                "--pcap needs a simulated network: add a `litz-wifi-router` part or [sim.wifi]"
1935                    .into(),
1936            );
1937        };
1938        let capture = std::rc::Rc::new(std::cell::RefCell::new(litz_net::capture::Capture::new([
1939            10, 0, 2, 15,
1940        ])));
1941        config.capture = Some(std::rc::Rc::clone(&capture));
1942        Some(capture)
1943    } else {
1944        None
1945    };
1946    if let Some(config) = &network {
1947        board.set_network(config.clone());
1948    }
1949    let bluetooth = board.bluetooth().cloned();
1950    let shared = std::rc::Rc::new(std::cell::RefCell::new(board));
1951
1952    let mut chips = Vec::with_capacity(prepared.boards.len());
1953    for (index, plan) in prepared.boards.iter().enumerate() {
1954        let chip = build_chip(
1955            prepared,
1956            plan,
1957            std::rc::Rc::clone(&shared),
1958            index as u16,
1959            network.as_ref(),
1960            bluetooth.as_ref(),
1961        )?;
1962        chips.push(boot_chip(chip, plan)?);
1963    }
1964
1965    // The radio seams belong to the station, so they are asked of the first
1966    // board; a diagram with several Wi-Fi chips records the first one.
1967    if let Some(path) = &options.pcap_air
1968        && let Some(chip) = chips.first_mut()
1969    {
1970        chip.start_air_capture(path)?;
1971    }
1972    if let Some(path) = &options.pcap_eth
1973        && let Some(chip) = chips.first_mut()
1974    {
1975        chip.start_ethernet_capture(path)?;
1976    }
1977    if options.host_network || !options.host_forwards.is_empty() {
1978        let chip = chips
1979            .first_mut()
1980            .ok_or_else(|| "--net needs a board".to_string())?;
1981        chip.attach_host_gateway(&options.host_forwards)?;
1982    }
1983
1984    // A debugger attaches to a booted chip, so flash and symbols are already
1985    // in place when it reads memory or sets a breakpoint. A session owns its
1986    // chip's clock until the client disconnects, so one board is served; the
1987    // request says which, or names the first board that has a debug target.
1988    if let Some(request) = &options.gdb {
1989        let index = match &request.board {
1990            Some(id) => find_board(&prepared.boards, id, "--gdb")?,
1991            None => chips
1992                .iter_mut()
1993                .position(|chip| chip.debug().is_some())
1994                .ok_or_else(|| {
1995                    "--gdb needs a backend with a GDB target; a wasm MCU and the AVR core have none"
1996                        .to_string()
1997                })?,
1998        };
1999        let plan = &prepared.boards[index];
2000        let chip = &mut chips[index];
2001        let debug = chip.debug().ok_or_else(|| {
2002            format!(
2003                "--gdb: board {:?} has no GDB target; a wasm MCU and the AVR core have none",
2004                plan.id
2005            )
2006        })?;
2007        eprintln!("litz: gdb serves board {:?}", plan.id);
2008        debug.serve(request.port)?;
2009    }
2010    Ok(Booted {
2011        fleet: Fleet::new(chips),
2012        parts,
2013        board: shared,
2014        capture,
2015    })
2016}
2017
2018/// A booted circuit: the chips that run it, the part ids a report names, and
2019/// the board they all share. The board handle is what answers probe questions
2020/// once the chips own the run loop.
2021struct Booted {
2022    fleet: Fleet,
2023    parts: Vec<String>,
2024    board: std::rc::Rc<std::cell::RefCell<Board>>,
2025    /// The packet capture the run filled, when `--pcap` asked for one.
2026    capture: Option<std::rc::Rc<std::cell::RefCell<litz_net::capture::Capture>>>,
2027}
2028
2029/// The board a flag names, by its `diagram.json` instance id. The error lists
2030/// the ids that exist so a typo is answered in the same line it is reported.
2031fn find_board(boards: &[BoardPlan], id: &str, flag: &str) -> Result<usize, String> {
2032    boards.iter().position(|plan| plan.id == id).ok_or_else(|| {
2033        format!(
2034            "{flag} names board {id:?}; diagram.json has {}",
2035            boards
2036                .iter()
2037                .map(|plan| plan.id.as_str())
2038                .collect::<Vec<_>>()
2039                .join(", ")
2040        )
2041    })
2042}
2043
2044/// Which board a touch targets. Wokwi names the board in `part-id`; the older
2045/// `board` key still wins when both are present. A part id that is not a board
2046/// is ignored, so a single-board project can write either.
2047fn touch_board(
2048    prepared: &Prepared,
2049    board: &Option<String>,
2050    part: &Option<String>,
2051    flag: &str,
2052) -> Result<Option<usize>, String> {
2053    if let Some(id) = board {
2054        return find_board(&prepared.boards, id, flag).map(Some);
2055    }
2056    if let Some(part) = part
2057        && let Some(index) = prepared.boards.iter().position(|plan| plan.id == *part)
2058    {
2059        return Ok(Some(index));
2060    }
2061    Ok(None)
2062}
2063
2064/// One board's chip, attached to the shared board at its own index.
2065fn build_chip(
2066    prepared: &Prepared,
2067    plan: &BoardPlan,
2068    board: std::rc::Rc<std::cell::RefCell<Board>>,
2069    index: u16,
2070    network: Option<&NetworkConfig>,
2071    bluetooth: Option<&litz_ble::BleConfig>,
2072) -> Result<Box<dyn Chip>, String> {
2073    let info = plan
2074        .manifest
2075        .board
2076        .as_ref()
2077        .expect("prepare checked it is a board");
2078    #[cfg(not(target_family = "wasm"))]
2079    if let Some(simulator) = &info.simulator {
2080        let module = module_bytes(prepared, &plan.manifest, &simulator.module)?;
2081        return Ok(Box::new(
2082            WasmChip::from_bytes_with_abi(&module, &simulator.module, &simulator.abi)?
2083                .with_shared_board(board, index),
2084        ));
2085    }
2086    #[cfg(target_family = "wasm")]
2087    if info.simulator.is_some() {
2088        let _ = prepared;
2089        return Err(
2090            "a wasm guest chip cannot run inside the browser build; only the builtin chips \
2091             are compiled there"
2092                .into(),
2093        );
2094    }
2095    let name = info.chip.as_deref().unwrap_or("esp32c3");
2096    let mut chip = builtin_chip(
2097        name,
2098        plan.mac,
2099        plan.flash_size,
2100        board,
2101        index,
2102        Attachments {
2103            network,
2104            bluetooth,
2105            elf: plan.elf.as_deref(),
2106            ble_controller: plan.python == crate::python::PythonRuntime::CircuitPython,
2107        },
2108    )?;
2109    // A board whose manifest declares PSRAM gets the amount the chip's own
2110    // SocBus supports; the flag is the board's, the size is the chip's.
2111    if info.psram {
2112        chip.set_psram_size(4 << 20)?;
2113    }
2114    Ok(chip)
2115}
2116
2117/// Load the plan's images and start the chip.
2118fn boot_chip(mut mcu: Box<dyn Chip>, plan: &BoardPlan) -> Result<Box<dyn Chip>, String> {
2119    if !plan.rom.is_empty() {
2120        mcu.load_image(ImageKind::Rom, 0, &plan.rom)?;
2121    }
2122    if plan.firmware.is_empty() && plan.bootloader.is_none() {
2123        // A board with no image boots whatever its own simulator carries.
2124        mcu.boot()?;
2125        return Ok(mcu);
2126    }
2127    let flash = mcu.info().flash;
2128    match plan.layout {
2129        // The whole file goes in at the bootloader offset and `Chip::boot`
2130        // lets the ROM start it; the bootloader then finds the partition table
2131        // and application inside the same bytes. `flash.bootloader` is 0 on
2132        // the RISC-V parts whose official images use this layout.
2133        FirmwareLayout::Merged => {
2134            mcu.load_image(ImageKind::Bootloader, flash.bootloader, &plan.firmware)?;
2135        }
2136        FirmwareLayout::Application => match (&plan.bootloader, &plan.partition_table) {
2137            (Some(bootloader), Some(ptable)) => {
2138                mcu.load_image(ImageKind::Bootloader, flash.bootloader, bootloader)?;
2139                mcu.load_image(ImageKind::PartitionTable, flash.partition_table, ptable)?;
2140                mcu.load_image(ImageKind::Firmware, flash.app, &plan.firmware)?;
2141            }
2142            (None, None) => {
2143                mcu.load_image(ImageKind::Firmware, flash.app, &plan.firmware)?;
2144            }
2145            // A bootloader finds the application through the partition table,
2146            // so one without the other is a manifest mistake, not a fallback.
2147            _ => {
2148                return Err(format!(
2149                    "board {:?}: bootloader and partition_table go together; give both or neither",
2150                    plan.id
2151                ));
2152            }
2153        },
2154    }
2155    mcu.boot()?;
2156    Ok(mcu)
2157}
2158
2159/// The chips one diagram runs, in board order.
2160///
2161/// A single-board project is a fleet of one, so the run loop has one shape.
2162/// Board-wide questions — part state, conflicts, a pressed part — are answered
2163/// by the first chip, which sees the same board as the rest. Chip questions —
2164/// run, console, time — are asked of every chip, and their consoles are merged
2165/// in board order at each chunk boundary.
2166struct Fleet {
2167    chips: Vec<Box<dyn Chip>>,
2168    /// Each chip's console since the run began, so a MicroPython prompt can be
2169    /// found on the board that printed it.
2170    console: Vec<String>,
2171    /// How far each console has been handed out.
2172    read: Vec<usize>,
2173    /// How each chip last stopped, which is what tells a finished board from a
2174    /// slow one when the frontier is computed.
2175    stops: Vec<Stop>,
2176}
2177
2178impl Fleet {
2179    fn new(chips: Vec<Box<dyn Chip>>) -> Self {
2180        let count = chips.len();
2181        Self {
2182            chips,
2183            console: vec![String::new(); count],
2184            read: vec![0; count],
2185            stops: vec![Stop::Budget; count],
2186        }
2187    }
2188
2189    /// Advance every chip by one scheduling batch. The returned stop is the
2190    /// most significant one any chip reported, so a trap on either board ends
2191    /// the run.
2192    fn run(&mut self, steps: u64) -> litz_board::chip::RunResult {
2193        let mut cycles = 0;
2194        let mut stop = Stop::Budget;
2195        for (index, chip) in self.chips.iter_mut().enumerate() {
2196            let result = chip.run(steps);
2197            cycles = cycles.max(result.cycles);
2198            self.stops[index] = result.stop;
2199            let chunk = chip.take_console();
2200            if !chunk.is_empty() {
2201                self.console[index].push_str(&String::from_utf8_lossy(&chunk));
2202            }
2203            if stop_rank(result.stop) > stop_rank(stop) {
2204                stop = result.stop;
2205            }
2206        }
2207        litz_board::chip::RunResult { cycles, stop }
2208    }
2209
2210    /// One chip's next batch, for the paste handshake, which talks to the
2211    /// board whose REPL is ready and lets the others keep their own pace.
2212    fn run_one(&mut self, index: usize, steps: u64) {
2213        let result = self.chips[index].run(steps);
2214        self.stops[index] = result.stop;
2215        let chunk = self.chips[index].take_console();
2216        if !chunk.is_empty() {
2217            self.console[index].push_str(&String::from_utf8_lossy(&chunk));
2218        }
2219    }
2220
2221    /// Console bytes produced since the last call, merged in board order.
2222    /// Deliver a touch to one board (or the first), through its controller.
2223    fn touch(&mut self, board: Option<usize>, x: u16, y: u16, down: bool) -> Result<(), String> {
2224        let index = board.unwrap_or(0);
2225        match self.chips.get_mut(index) {
2226            Some(chip) => chip.touch(x, y, down),
2227            None => Err(format!("the diagram has no board {index}")),
2228        }
2229    }
2230
2231    /// Ask the first chip for the firmware's free heap.
2232    fn sample_heap(&mut self) -> Result<u32, String> {
2233        match self.chips.first_mut() {
2234            Some(chip) => chip.sample_heap(),
2235            None => Err("the diagram has no chip to sample".into()),
2236        }
2237    }
2238
2239    fn take_console(&mut self) -> Vec<u8> {
2240        let mut out = Vec::new();
2241        for (index, text) in self.console.iter().enumerate() {
2242            if self.read[index] < text.len() {
2243                out.extend_from_slice(&text.as_bytes()[self.read[index]..]);
2244                self.read[index] = text.len();
2245            }
2246        }
2247        out
2248    }
2249
2250    /// One board's console so far.
2251    fn console_text(&self, index: usize) -> &str {
2252        &self.console[index]
2253    }
2254
2255    fn write_console_to(&mut self, index: usize, bytes: &[u8]) {
2256        self.chips[index].write_console(bytes);
2257    }
2258
2259    /// The time every running chip has reached. A board that halted or
2260    /// trapped is finished and does not hold the others back.
2261    /// Whether every board has stopped for good. A halted core makes no more
2262    /// simulated time, so waiting for the timeout after this would wait for
2263    /// ever on a clock that never moves.
2264    fn finished(&self) -> bool {
2265        self.stops
2266            .iter()
2267            .all(|stop| matches!(stop, Stop::Halted | Stop::Reset | Stop::Trap))
2268    }
2269
2270    fn frontier_ns(&self) -> u64 {
2271        let mut frontier: Option<u64> = None;
2272        let mut latest = 0;
2273        for (index, chip) in self.chips.iter().enumerate() {
2274            let now = (chip.seconds() * 1e9) as u64;
2275            latest = latest.max(now);
2276            if matches!(self.stops[index], Stop::Halted | Stop::Reset | Stop::Trap) {
2277                continue;
2278            }
2279            frontier = Some(frontier.map_or(now, |front| front.min(now)));
2280        }
2281        frontier.unwrap_or(latest)
2282    }
2283
2284    fn seconds(&self) -> f64 {
2285        self.chips
2286            .iter()
2287            .map(|chip| chip.seconds())
2288            .fold(0.0, f64::max)
2289    }
2290
2291    /// Queue host actions on one board's chip. `board` is the index in
2292    /// [`Prepared::boards`], the same order the chips were built in.
2293    fn schedule(&mut self, board: usize, inputs: Vec<Input>) -> Result<(), String> {
2294        match self.chips.get_mut(board) {
2295            Some(chip) => chip.schedule(inputs),
2296            None => Err(format!("there is no board {board} to schedule input on")),
2297        }
2298    }
2299
2300    fn state(&self, part: &str) -> Option<PartState> {
2301        self.chips.first()?.state(part)
2302    }
2303
2304    fn press(&mut self, part: &str, pressed: bool) -> bool {
2305        self.chips
2306            .first_mut()
2307            .is_some_and(|chip| chip.press(part, pressed))
2308    }
2309
2310    fn set_control(&mut self, part: &str, value: u16) -> bool {
2311        self.chips
2312            .first_mut()
2313            .is_some_and(|chip| chip.set_control(part, value))
2314    }
2315
2316    fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2317        self.chips
2318            .first_mut()
2319            .is_some_and(|chip| chip.set_named_control(part, name, value))
2320    }
2321
2322    fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2323        self.chips.first()?.part_pin_level(part, pin)
2324    }
2325
2326    fn gpio_level(&self, board: usize, gpio: u8) -> Option<Level> {
2327        self.chips.get(board)?.gpio_level(gpio)
2328    }
2329
2330    fn conflicts(&self) -> Vec<litz_board::Conflict> {
2331        self.chips
2332            .first()
2333            .map(|chip| chip.conflicts())
2334            .unwrap_or_default()
2335    }
2336
2337    fn fault(&self) -> Option<String> {
2338        self.chips.iter().find_map(|chip| chip.fault())
2339    }
2340
2341    /// Host bytes into one board's console. Board 0 when no board was asked
2342    /// for.
2343    fn write_console_on(&mut self, board: usize, bytes: &[u8]) {
2344        if let Some(chip) = self.chips.get_mut(board) {
2345            chip.write_console(bytes);
2346        }
2347    }
2348
2349    /// Capture `board`'s display, or — when `board` is `None` — the first
2350    /// board that has one. A chip without a framebuffer says so, and the
2351    /// search moves on rather than failing a run because the first board has
2352    /// no panel.
2353    fn save_display(&mut self, board: Option<usize>, path: &Path) -> Result<(), String> {
2354        let Some(board) = board else {
2355            let mut refusal = None;
2356            for chip in &mut self.chips {
2357                match chip.save_display(path) {
2358                    Ok(()) => return Ok(()),
2359                    Err(e) => refusal.get_or_insert(e),
2360                };
2361            }
2362            return Err(refusal.unwrap_or_else(|| "the diagram has no chip to capture".into()));
2363        };
2364        match self.chips.get_mut(board) {
2365            Some(chip) => chip.save_display(path),
2366            None => Err(format!("there is no board {board} to capture")),
2367        }
2368    }
2369
2370    /// Capture one display part by id. The first chip that knows the part
2371    /// wins, which is the board the diagram wired it to.
2372    fn save_part_display(&mut self, part: &str, path: &Path) -> Result<(), String> {
2373        let mut refusal = None;
2374        for chip in &mut self.chips {
2375            match chip.save_part_display(part, path) {
2376                Ok(()) => return Ok(()),
2377                Err(error) => refusal.get_or_insert(error),
2378            };
2379        }
2380        Err(refusal.unwrap_or_else(|| format!("no part {part:?} has a framebuffer")))
2381    }
2382
2383    fn report(&mut self) -> Vec<String> {
2384        self.chips
2385            .iter_mut()
2386            .flat_map(|chip| chip.report())
2387            .collect()
2388    }
2389
2390    fn enable_coverage(&mut self) {
2391        for chip in &mut self.chips {
2392            chip.enable_coverage();
2393        }
2394    }
2395
2396    fn start_trace(&mut self) {
2397        if let Some(chip) = self.chips.first_mut() {
2398            chip.start_trace();
2399        }
2400    }
2401
2402    fn break_at(&mut self, pc: u32) {
2403        for chip in &mut self.chips {
2404            chip.break_at(pc);
2405        }
2406    }
2407
2408    fn vcd(&self) -> String {
2409        self.chips
2410            .first()
2411            .map(|chip| chip.vcd())
2412            .unwrap_or_default()
2413    }
2414}
2415
2416/// How decisive a stop is when several chips report in one batch.
2417fn stop_rank(stop: Stop) -> u8 {
2418    match stop {
2419        Stop::Trap => 5,
2420        Stop::Breakpoint(_) => 4,
2421        Stop::Reset => 3,
2422        Stop::Halted => 2,
2423        Stop::Idle => 1,
2424        Stop::Budget => 0,
2425    }
2426}
2427
2428/// The chip module a board names, from the binary for a builtin board or from
2429/// disk next to the manifest for one loaded from a directory.
2430#[cfg(not(target_family = "wasm"))]
2431fn module_bytes(
2432    prepared: &Prepared,
2433    manifest: &litz_catalog::PartManifest,
2434    module: &str,
2435) -> Result<Vec<u8>, String> {
2436    if let Some(bytes) = prepared.registry.builtin_module(&manifest.id) {
2437        return Ok(bytes.to_vec());
2438    }
2439    let base = manifest
2440        .source
2441        .as_deref()
2442        .and_then(|path| path.parent())
2443        .ok_or_else(|| {
2444            format!(
2445                "board {:?} names a module but has no directory",
2446                manifest.id
2447            )
2448        })?;
2449    let path = base.join(module);
2450    std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
2451}
2452
2453fn run_once(
2454    prepared: &Prepared,
2455    spec: Option<&TestSpec>,
2456    _strict: bool,
2457    options: &Options,
2458) -> Result<Outcome, String> {
2459    let data = run_inner(prepared, spec, spec.is_none(), false, None, options)?;
2460    Ok(Outcome {
2461        exit_code: data.exit_code,
2462        output: data.output,
2463        sim_ms: data.sim_ms,
2464        tests: Vec::new(),
2465    })
2466}
2467
2468fn run_capture(
2469    prepared: &Prepared,
2470    timeout: Option<&str>,
2471    options: &Options,
2472) -> Result<CaptureOutcome, String> {
2473    let data = run_inner(prepared, None, false, true, timeout, options)?;
2474    Ok(CaptureOutcome {
2475        exit_code: data.exit_code,
2476        output: data.output,
2477        sim_ms: data.sim_ms,
2478        part_states: data.part_states,
2479        faults: data.faults,
2480    })
2481}
2482
2483/// Everything a run produces, before it is shaped for a terminal or a host.
2484struct RunData {
2485    exit_code: i32,
2486    output: String,
2487    sim_ms: u32,
2488    part_states: BTreeMap<String, PartState>,
2489    faults: Vec<String>,
2490}
2491
2492fn run_inner(
2493    prepared: &Prepared,
2494    spec: Option<&TestSpec>,
2495    stream: bool,
2496    capture_states: bool,
2497    timeout_override: Option<&str>,
2498    options: &Options,
2499) -> Result<RunData, String> {
2500    let Booted {
2501        fleet: mut mcu,
2502        parts,
2503        board,
2504        capture,
2505    } = boot(prepared, options)?;
2506    start_recording(&mut mcu, options, prepared);
2507    if options.coverage {
2508        mcu.enable_coverage();
2509    }
2510    // Which chip the terminal and the screenshot address is settled before any
2511    // time passes: a board name that is not in the diagram is a configuration
2512    // error, not a note at the end of a run.
2513    let console_board = match options
2514        .interactive
2515        .as_ref()
2516        .and_then(|i| i.board.as_deref())
2517    {
2518        Some(id) => find_board(&prepared.boards, id, "--interactive")?,
2519        None => 0,
2520    };
2521    let capture_board = match options
2522        .screenshot
2523        .as_ref()
2524        .and_then(|capture| capture.board.as_deref())
2525    {
2526        Some(id) => Some(find_board(&prepared.boards, id, "--screenshot")?),
2527        None => None,
2528    };
2529    // `[[test.input]] pin` is a part id when the diagram has such a part and a
2530    // pin number otherwise. Finding out before the machine exists keeps the
2531    // two meanings from colliding at run time.
2532    let presses = spec.map(|s| press_schedule(s, &parts)).unwrap_or_default();
2533
2534    let inputs = spec
2535        .map(|s| inputs_for(s, &parts, &prepared.boards))
2536        .transpose()?
2537        .unwrap_or_default();
2538    for (board, inputs) in inputs {
2539        mcu.schedule(board, inputs)?;
2540    }
2541
2542    let timeout = match timeout_override {
2543        Some(text) => parse_duration(text)?,
2544        None => spec
2545            .and_then(|s| s.timeout.as_deref())
2546            .map(parse_duration)
2547            .transpose()?
2548            .unwrap_or_else(|| parse_duration(DEFAULT_TIMEOUT).expect("default timeout")),
2549    };
2550    let expects = spec
2551        .map(|s| consoled(s.expect(), &prepared.boards))
2552        .unwrap_or_default();
2553    let fails = spec
2554        .map(|s| consoled(s.fail(), &prepared.boards))
2555        .unwrap_or_default();
2556    let mut states: Vec<Wanted> = spec
2557        .map(TestSpec::expect_state)
2558        .unwrap_or_default()
2559        .into_iter()
2560        .map(wanted)
2561        .collect::<Result<_, _>>()?;
2562    let state_at = spec
2563        .and_then(|s| s.state_at.as_deref())
2564        .map(parse_duration)
2565        .transpose()?;
2566    let state_stays = spec
2567        .and_then(|s| s.state_stays.as_deref())
2568        .map(parse_duration)
2569        .transpose()?;
2570    for want in &mut states {
2571        want.at = state_at;
2572        want.stays = state_stays;
2573        if mcu.state(&want.part).is_none() {
2574            let known: Vec<&str> = diagram_part_ids(prepared).collect();
2575            return Err(format!(
2576                "no part named {:?} in diagram.json ({}); a part inside a board is \
2577                 reached as <board>/<id>",
2578                want.part,
2579                known.join(", ")
2580            ));
2581        }
2582    }
2583
2584    let mut heap = HeapLog::from_options(
2585        options,
2586        prepared
2587            .boards
2588            .first()
2589            .map(|plan| plan.id.clone())
2590            .unwrap_or_else(|| "esp".into()),
2591    )?;
2592    // CircuitPython starts `code.py` itself; the interrupt is queued before
2593    // the first chunk so the prompt can appear.
2594    for (index, plan) in prepared.boards.iter().enumerate() {
2595        if pastes_script(plan) && !plan.python.interrupt_sequence().is_empty() {
2596            mcu.write_console_on(index, plan.python.interrupt_sequence());
2597        }
2598    }
2599    let mut serial = String::new();
2600    let mut timed_out = false;
2601    let mut due = 0;
2602    let mut saw_fail = None;
2603    // Interactive input arrives on a thread because the run loop owns the
2604    // simulated clock: blocking on a terminal read would stop time. A line is
2605    // forwarded at the next chunk boundary, which is where every other host
2606    // input lands too.
2607    let (stdin_tx, stdin_rx) = std::sync::mpsc::channel::<Vec<u8>>();
2608    if options.interactive.is_some() {
2609        std::thread::spawn(move || {
2610            use std::io::BufRead;
2611            let stdin = std::io::stdin();
2612            let mut lock = stdin.lock();
2613            let mut line = String::new();
2614            loop {
2615                line.clear();
2616                match lock.read_line(&mut line) {
2617                    Ok(0) | Err(_) => break,
2618                    Ok(_) if stdin_tx.send(line.as_bytes().to_vec()).is_err() => break,
2619                    Ok(_) => {}
2620                }
2621            }
2622        });
2623    }
2624    let mut saw_trap: Option<String> = None;
2625    // A MicroPython run is not ready for its expectations until the prompt has
2626    // appeared and the script has been pasted. `pasted` gates both the
2627    // handshake and the "expectations met" exit.
2628    let mut pasted: Vec<bool> = prepared
2629        .boards
2630        .iter()
2631        .map(|plan| !pastes_script(plan))
2632        .collect();
2633    let mut pasted_at = vec![0u64; prepared.boards.len()];
2634    // When the host last nudged a CircuitPython board: it runs `code.py` by
2635    // itself and then waits in "Press any key to enter the REPL", so the
2636    // friendly prompt only appears after a key arrives. `pasted` still gates
2637    // the handshake; this only decides when to knock.
2638    let mut nudged_at = vec![0u64; prepared.boards.len()];
2639    loop {
2640        // A fault present before the chip runs (two rails meeting on a net, a
2641        // pin tied to ground while the board is already driving) is reported
2642        // without spending a chunk of simulated time on a doomed boot.
2643        if !mcu.conflicts().is_empty() {
2644            break;
2645        }
2646        // Host input lands at chunk boundaries, so it is applied within one
2647        // million-step chunk of the time it asked for — far below the
2648        // resolution any assertion can see.
2649        let now_ns = mcu.frontier_ns();
2650        while due < presses.len() && presses[due].0 <= now_ns {
2651            let (_, part, pressed) = &presses[due];
2652            mcu.press(part, *pressed);
2653            due += 1;
2654        }
2655        while let Ok(bytes) = stdin_rx.try_recv() {
2656            mcu.write_console_on(console_board, &bytes);
2657        }
2658        let step = mcu.run(1_000_000);
2659        // A trap is a real stop, not a slow boot: without this the run would
2660        // keep spinning a dead core until the timeout and report only a
2661        // missing expectation. `fault()` carries the backend's detail when it
2662        // has one.
2663        if step.stop == Stop::Trap {
2664            saw_trap = Some(mcu.fault().unwrap_or_else(|| "the core trapped".into()));
2665            break;
2666        }
2667        let chunk = mcu.take_console();
2668        if !chunk.is_empty() {
2669            let text = String::from_utf8_lossy(&chunk);
2670            if stream {
2671                print!("{text}");
2672                let _ = std::io::stdout().flush();
2673            }
2674            serial.push_str(&text);
2675        }
2676        if !mcu.conflicts().is_empty() {
2677            break;
2678        }
2679        if let Some(log) = &mut heap {
2680            let now = mcu.frontier_ns();
2681            log.sample(&mut mcu, now);
2682            if log.failed() {
2683                break;
2684            }
2685        }
2686        if mcu.finished() {
2687            break;
2688        }
2689        if let Some(hit) = fails.iter().find(|f| seen(&mcu, &serial, f)) {
2690            saw_fail = Some(hit.clone());
2691            break;
2692        }
2693        // Each board keeps its own handshake: two boards boot at their own
2694        // pace, and the prompt belongs to the console that printed it.
2695        let now = mcu.frontier_ns();
2696        for (index, plan) in prepared.boards.iter().enumerate() {
2697            if pasted[index] {
2698                continue;
2699            }
2700            if mcu.console_text(index).contains(REPL_PROMPT) {
2701                paste_script(&mut mcu, index, &plan.scripts, plan.python);
2702                pasted[index] = true;
2703                pasted_at[index] = now;
2704            } else if plan.python == crate::python::PythonRuntime::CircuitPython
2705                && !mcu.console_text(index).is_empty()
2706                && now.saturating_sub(nudged_at[index]) >= CIRCUITPYTHON_NUDGE
2707            {
2708                // Ctrl-C: it interrupts a running code.py, and at the
2709                // "press any key" idle it is the key that opens the REPL.
2710                mcu.write_console_on(index, plan.python.interrupt_sequence());
2711                nudged_at[index] = now;
2712            } else if now >= timeout {
2713                return Err(format!(
2714                    "board {:?}: MicroPython REPL prompt never appeared within {timeout} ns of \
2715                     simulated time; check that its firmware is a MicroPython or CircuitPython build",
2716                    plan.id
2717                ));
2718            }
2719        }
2720        for want in &mut states {
2721            if let Some(actual) = mcu.state(&want.part) {
2722                observe(want, actual, now);
2723            }
2724        }
2725        let paste_settled = prepared.boards.iter().enumerate().all(|(index, plan)| {
2726            !pastes_script(plan)
2727                || (pasted[index] && now >= pasted_at[index].saturating_add(PASTE_GRACE_NS))
2728        });
2729        let satisfied = pasted.iter().all(|pasted| *pasted)
2730            && paste_settled
2731            && expects.iter().all(|e| seen(&mcu, &serial, e))
2732            && states.iter().all(|w| w.seen);
2733        if satisfied && (!expects.is_empty() || !states.is_empty()) {
2734            timed_out = false;
2735            break;
2736        }
2737        if mcu.frontier_ns() >= timeout {
2738            timed_out = true;
2739            break;
2740        }
2741    }
2742
2743    let conflicts = mcu.conflicts();
2744    let missing: Vec<&Consoled> = expects.iter().filter(|e| !seen(&mcu, &serial, e)).collect();
2745    let missing_states: Vec<&Wanted> = states.iter().filter(|w| !w.seen).collect();
2746    let passed = conflicts.is_empty()
2747        && saw_fail.is_none()
2748        && saw_trap.is_none()
2749        && missing.is_empty()
2750        && missing_states.is_empty();
2751
2752    let mut notes = Vec::new();
2753    for conflict in &conflicts {
2754        notes.push(format!(
2755            "electrical fault on net {}: {}",
2756            conflict.net, conflict.detail
2757        ));
2758    }
2759    if let Some(hit) = &saw_fail {
2760        let text = hit.text;
2761        match hit.board.and_then(|index| prepared.boards.get(index)) {
2762            Some(plan) => notes.push(format!(
2763                "found failure text {text:?} on board {:?}",
2764                plan.id
2765            )),
2766            None => notes.push(format!("found failure text {text:?}")),
2767        }
2768    }
2769    if let Some(detail) = &saw_trap {
2770        notes.push(format!("the core trapped: {detail}"));
2771    }
2772    for miss in &missing {
2773        match miss.board.and_then(|index| prepared.boards.get(index)) {
2774            Some(plan) => notes.push(format!("never saw {:?} on board {:?}", miss.text, plan.id)),
2775            None => notes.push(format!("never saw {:?}", miss.text)),
2776        }
2777    }
2778    for want in missing_states {
2779        if want.broken {
2780            let stays = want.stays.map(seconds).unwrap_or_default();
2781            notes.push(format!(
2782                "{} {} did not hold for {stays}",
2783                want.part, want.state
2784            ));
2785        } else if let Some(at) = want.at {
2786            notes.push(format!(
2787                "{} was not {} at {}",
2788                want.part,
2789                want.state,
2790                seconds(at)
2791            ));
2792        } else {
2793            notes.push(format!("never saw {} {}", want.part, want.state));
2794        }
2795    }
2796    if timed_out && spec.is_some() {
2797        notes.push(format!("timed out after {timeout} ns of simulated time"));
2798    }
2799
2800    let mut exit_code = if spec.is_none() {
2801        if !conflicts.is_empty() || saw_trap.is_some() {
2802            1
2803        } else if !timed_out && mcu.finished() {
2804            // Every core halted on its own before the clock ran out: the
2805            // program finished rather than the run being cut short.
2806            0
2807        } else {
2808            EXIT_TIMEOUT
2809        }
2810    } else if passed {
2811        0
2812    } else {
2813        1
2814    };
2815
2816    let mut part_states = BTreeMap::new();
2817    if capture_states {
2818        for part in &parts {
2819            if let Some(state) = mcu.state(part)
2820                && state != PartState::None
2821            {
2822                part_states.insert(part.clone(), state);
2823            }
2824        }
2825    }
2826    let faults: Vec<String> = conflicts
2827        .iter()
2828        .map(|conflict| format!("net {}: {}", conflict.net, conflict.detail))
2829        .collect();
2830
2831    let mut output = if stream { String::new() } else { serial };
2832    if !output.ends_with('\n') && !output.is_empty() {
2833        output.push('\n');
2834    }
2835    for note in notes {
2836        output.push_str(&format!("litz: {note}\n"));
2837    }
2838    for line in probe_report(&board) {
2839        output.push_str(&format!("litz: {line}\n"));
2840    }
2841    for line in decode_report(&board, prepared, options)? {
2842        output.push_str(&format!("litz: {line}\n"));
2843    }
2844    // Coverage is a report, not an assertion: it never changes the exit code,
2845    // so a CI step can collect it without turning a pass into a failure.
2846    for line in mcu.report() {
2847        output.push_str(&line);
2848        if !line.ends_with('\n') {
2849            output.push('\n');
2850        }
2851    }
2852    let sim_ms = (mcu.seconds() * 1000.0) as u32;
2853    finish_recording(&mcu, &board, options, capture.as_ref())?;
2854    // A failing test is the moment a picture of the display earns its keep; a
2855    // plain `run` captures unconditionally because the caller asked for it.
2856    // A capture that cannot be taken is a note, not a failure: a board with no
2857    // display should not turn a green run red.
2858    if let Some(capture) = &options.screenshot
2859        && (spec.is_none() || exit_code != 0)
2860        && let Err(e) = mcu.save_display(capture_board, &capture.path)
2861    {
2862        eprintln!("litz: {e}");
2863    }
2864    if let Some(log) = heap {
2865        let end = mcu.frontier_ns();
2866        let (lines, failure) = log.finish(&mut mcu, end);
2867        for line in lines {
2868            output.push_str(&format!("litz: {line}\n"));
2869        }
2870        if let Some(failure) = failure {
2871            exit_code = 1;
2872            output.push_str(&format!("litz: heap: {failure}\n"));
2873        }
2874    }
2875    Ok(RunData {
2876        exit_code,
2877        output,
2878        sim_ms,
2879        part_states,
2880        faults,
2881    })
2882}
2883
2884/// A file named in `litz.toml`, read relative to the project directory.
2885fn read_optional(dir: &Path, rel: Option<&str>) -> Result<Option<Vec<u8>>, String> {
2886    rel.map(|rel| {
2887        let path = dir.join(rel);
2888        std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
2889    })
2890    .transpose()
2891}
2892
2893/// One `expect_state` entry: a part, the state it must reach, and whether it
2894/// has been seen there yet.
2895///
2896/// The wanted state stays text until it is compared, because one word can mean
2897/// the same thing for several parts — `on` is an LED being lit, a switch being
2898/// thrown and a buzzer sounding — and the part decides which reading applies.
2899struct Wanted {
2900    part: String,
2901    state: String,
2902    seen: bool,
2903    /// Sample the state at this simulated time instead of "at some point".
2904    at: Option<u64>,
2905    /// Once it matches, it must keep matching this long.
2906    stays: Option<u64>,
2907    /// The sample at `at` has been taken.
2908    sampled: bool,
2909    /// A held state started matching.
2910    started: bool,
2911    /// Simulated time the hold started.
2912    since: u64,
2913    /// The hold was broken before it completed.
2914    broken: bool,
2915}
2916
2917/// `<part>:<state>`, the inverse of what this prints in the failure note.
2918fn wanted(text: &str) -> Result<Wanted, String> {
2919    let (part, state) = text
2920        .split_once(':')
2921        .ok_or_else(|| format!("{text:?} is not <part>:<state>"))?;
2922    let known = matches!(state, "on" | "off" | "down" | "pressed" | "up" | "released")
2923        || state.parse::<u16>().is_ok()
2924        || state
2925            .strip_prefix("0x")
2926            .is_some_and(|hex| u8::from_str_radix(hex, 16).is_ok());
2927    if !known {
2928        return Err(format!(
2929            "{state:?} is not a state; write on, off, down, up, a servo angle in degrees, \
2930             or a segment mask as 0x7f"
2931        ));
2932    }
2933    Ok(Wanted {
2934        part: part.to_string(),
2935        state: state.to_string(),
2936        seen: false,
2937        at: None,
2938        stays: None,
2939        sampled: false,
2940        started: false,
2941        since: 0,
2942        broken: false,
2943    })
2944}
2945
2946/// Fold one observation of a part's state into what the test still needs.
2947///
2948/// Without modifiers this is "was ever seen". `state_at` samples instead of
2949/// accumulating, so a state that was true earlier and false at the requested
2950/// instant does not pass. `state_stays` extends a match into an interval: the
2951/// part must keep matching for the whole duration, and a single false
2952/// observation breaks it.
2953fn observe(want: &mut Wanted, actual: PartState, now: u64) {
2954    let matches = state_matches(actual, &want.state);
2955    match (want.at, want.stays) {
2956        (None, None) => {
2957            if matches {
2958                want.seen = true;
2959            }
2960        }
2961        (Some(at), None) => {
2962            if !want.sampled && now >= at {
2963                want.sampled = true;
2964                want.seen = matches;
2965            }
2966        }
2967        (None, Some(stays)) => {
2968            if want.broken || want.seen {
2969                return;
2970            }
2971            if matches {
2972                if !want.started {
2973                    want.started = true;
2974                    want.since = now;
2975                }
2976                if now.saturating_sub(want.since) >= stays {
2977                    want.seen = true;
2978                }
2979            } else if want.started {
2980                want.broken = true;
2981            }
2982        }
2983        (Some(at), Some(stays)) => {
2984            if want.broken || want.seen || now < at {
2985                return;
2986            }
2987            if !want.started {
2988                want.started = true;
2989                want.since = now;
2990            }
2991            if !matches {
2992                want.broken = true;
2993            } else if now.saturating_sub(want.since) >= stays {
2994                want.seen = true;
2995            }
2996        }
2997    }
2998}
2999
3000/// `1.5s` for a note, without trailing zeros.
3001fn seconds(ns: u64) -> String {
3002    format!("{}s", ns as f64 / 1e9)
3003}
3004
3005/// Whether a part's state is the one the test asked for.
3006fn state_matches(actual: PartState, want: &str) -> bool {
3007    match want {
3008        "on" => matches!(
3009            actual,
3010            PartState::Led { lit: true }
3011                | PartState::Switch { on: true }
3012                | PartState::Tone { sounding: true, .. }
3013        ),
3014        "off" => matches!(
3015            actual,
3016            PartState::Led { lit: false }
3017                | PartState::Switch { on: false }
3018                | PartState::Tone {
3019                    sounding: false,
3020                    ..
3021                }
3022        ),
3023        "down" | "pressed" => actual == PartState::Button { pressed: true },
3024        "up" | "released" => actual == PartState::Button { pressed: false },
3025        digits => {
3026            if let Some(hex) = digits.strip_prefix("0x") {
3027                let Ok(mask) = u8::from_str_radix(hex, 16) else {
3028                    return false;
3029                };
3030                return actual == PartState::Segments { mask };
3031            }
3032            match (digits.parse::<u16>(), actual) {
3033                (Ok(degrees), PartState::Servo { degrees: actual }) => degrees == actual,
3034                // A knob is written in percent, the unit `set-control`
3035                // and the diagram's `value` attribute use.
3036                (Ok(percent), PartState::Knob { permille }) => percent * 10 == permille,
3037                _ => false,
3038            }
3039        }
3040    }
3041}
3042
3043fn diagram_part_ids(prepared: &Prepared) -> impl Iterator<Item = &str> {
3044    prepared.circuit.parts.iter().map(|p| p.id.as_str())
3045}
3046
3047/// Presses of named parts, in the order they must happen.
3048fn press_schedule(spec: &TestSpec, parts: &[String]) -> Vec<(u64, String, bool)> {
3049    let mut presses: Vec<(u64, String, bool)> = Vec::new();
3050    for input in &spec.input {
3051        let Some(pin) = &input.pin else { continue };
3052        if !parts.iter().any(|id| id == pin) {
3053            continue;
3054        }
3055        let Ok(at) = parse_duration(&input.at) else {
3056            continue;
3057        };
3058        // A button wired to ground is pulled down while it is held, which is
3059        // the level a test writes: 0 presses, 1 releases.
3060        presses.push((at, pin.clone(), input.level.unwrap_or(1) == 0));
3061    }
3062    presses.sort_by_key(|(at, _, _)| *at);
3063    presses
3064}
3065
3066/// Test inputs as backend-independent scheduled events, grouped by board.
3067///
3068/// A part id in `pin` is pressed through the board rather than asserted onto a
3069/// chip pin, so it is left to `press_schedule`; only bare pin numbers become
3070/// GPIO events. Each group is scheduled on the chip of the board it names; the
3071/// returned order is board order, so a run queues them deterministically.
3072fn inputs_for(
3073    spec: &TestSpec,
3074    parts: &[String],
3075    boards: &[BoardPlan],
3076) -> Result<Vec<(usize, Vec<Input>)>, String> {
3077    let mut by_board: BTreeMap<usize, Vec<Input>> = BTreeMap::new();
3078    for input in &spec.input {
3079        let at_ns = parse_duration(&input.at)?;
3080        let board = input_board(spec, input, boards)?;
3081        if let Some(serial) = &input.serial {
3082            if serial.contains('\n') {
3083                return Err(format!(
3084                    "test {:?}: serial input must be one line",
3085                    spec.name
3086                ));
3087            }
3088            by_board.entry(board).or_default().push(Input::Uart {
3089                at_ns,
3090                bytes: format!("{serial}\n").into_bytes(),
3091            });
3092        }
3093        if let Some(pin) = &input.pin {
3094            if parts.iter().any(|id| id == pin) {
3095                continue;
3096            }
3097            let Ok(number) = pin.parse::<u8>() else {
3098                return Err(format!(
3099                    "test {:?}: {pin:?} is neither a part in the diagram nor a GPIO number",
3100                    spec.name
3101                ));
3102            };
3103            let level = if input.level.unwrap_or(1) == 0 {
3104                Level::Low
3105            } else {
3106                Level::High
3107            };
3108            by_board.entry(board).or_default().push(Input::Gpio {
3109                at_ns,
3110                pin: number,
3111                level,
3112            });
3113        }
3114    }
3115    let mut groups: Vec<(usize, Vec<Input>)> = by_board.into_iter().collect();
3116    for (_, inputs) in &mut groups {
3117        inputs.sort_by_key(|input| match input {
3118            Input::Gpio { at_ns, .. } | Input::Uart { at_ns, .. } => *at_ns,
3119        });
3120    }
3121    Ok(groups)
3122}
3123
3124/// The board an input lands on. One board needs no name; a diagram with more
3125/// than one cannot guess, because the same GPIO number exists on each.
3126fn input_board(
3127    spec: &TestSpec,
3128    input: &crate::config::Input,
3129    boards: &[BoardPlan],
3130) -> Result<usize, String> {
3131    match &input.board {
3132        Some(id) => boards
3133            .iter()
3134            .position(|plan| &plan.id == id)
3135            .ok_or_else(|| {
3136                format!(
3137                    "test {:?}: board {id:?} is not a development board in diagram.json ({})",
3138                    spec.name,
3139                    boards
3140                        .iter()
3141                        .map(|plan| plan.id.as_str())
3142                        .collect::<Vec<_>>()
3143                        .join(", ")
3144                )
3145            }),
3146        None if boards.len() == 1 => Ok(0),
3147        None => Err(format!(
3148            "test {:?}: the input at {} needs `board = \"...\"`; this diagram has {} boards ({})",
3149            spec.name,
3150            input.at,
3151            boards.len(),
3152            boards
3153                .iter()
3154                .map(|plan| plan.id.as_str())
3155                .collect::<Vec<_>>()
3156                .join(", ")
3157        )),
3158    }
3159}
3160
3161/// One `expect` or `fail` entry: the text, and the board whose console must
3162/// show it.
3163///
3164/// A leading `<board>@` narrows the match to that board's console. The prefix
3165/// is only read as a board when it names one, so any other text — `@`
3166/// included — is matched against the merged console of every board.
3167#[derive(Clone)]
3168struct Consoled<'a> {
3169    board: Option<usize>,
3170    text: &'a str,
3171}
3172
3173fn consoled<'a>(entries: Vec<&'a str>, boards: &[BoardPlan]) -> Vec<Consoled<'a>> {
3174    entries
3175        .into_iter()
3176        .map(|entry| match entry.split_once('@') {
3177            Some((prefix, rest)) => match boards.iter().position(|plan| plan.id == prefix) {
3178                Some(board) => Consoled {
3179                    board: Some(board),
3180                    text: rest,
3181                },
3182                None => Consoled {
3183                    board: None,
3184                    text: entry,
3185                },
3186            },
3187            None => Consoled {
3188                board: None,
3189                text: entry,
3190            },
3191        })
3192        .collect()
3193}
3194
3195/// Whether the console this entry names has shown its text. An entry without
3196/// a board reads the merged stream, exactly as a single-board project always
3197/// did.
3198fn seen(fleet: &Fleet, merged: &str, entry: &Consoled) -> bool {
3199    match entry.board {
3200        Some(index) => fleet.console_text(index).contains(entry.text),
3201        None => merged.contains(entry.text),
3202    }
3203}
3204
3205fn parse_mac(text: Option<&str>) -> [u8; 6] {
3206    let Some(text) = text else {
3207        return DEFAULT_MAC;
3208    };
3209    let bytes: Vec<u8> = text
3210        .split([':', '-'])
3211        .filter_map(|b| u8::from_str_radix(b, 16).ok())
3212        .collect();
3213    if bytes.len() == 6 {
3214        [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]]
3215    } else {
3216        DEFAULT_MAC
3217    }
3218}
3219
3220fn blocks(diagnostics: &[Diagnostic], strict: bool) -> bool {
3221    diagnostics
3222        .iter()
3223        .any(|d| d.severity == Severity::Error || (strict && d.severity == Severity::Warning))
3224}
3225
3226fn render(diagnostics: &[Diagnostic]) -> String {
3227    diagnostics
3228        .iter()
3229        .map(|d| {
3230            format!(
3231                "{}[{}]: {}\n",
3232                if d.severity == Severity::Error {
3233                    "error"
3234                } else {
3235                    "warning"
3236                },
3237                d.code,
3238                d.message
3239            )
3240        })
3241        .collect()
3242}
3243
3244/// `--trigger CHANNEL=high|low[,pre=DURATION][,post=DURATION]`. Durations use
3245/// the same syntax as a scenario delay (`250us`, `2ms`); with no `post`, the
3246/// window runs to the end of the record.
3247pub fn parse_trigger(spec: &str) -> Result<litz_board::probe::Trigger, String> {
3248    use litz_core::Level;
3249    let (channel, rest) = spec
3250        .split_once('=')
3251        .ok_or_else(|| format!("trigger {spec:?} needs CHANNEL=high|low"))?;
3252    let mut parts = rest.split(',');
3253    let level = match parts.next().unwrap_or("").trim() {
3254        "high" | "1" => Level::High,
3255        "low" | "0" => Level::Low,
3256        other => {
3257            return Err(format!("trigger level {other:?} is not high or low"));
3258        }
3259    };
3260    let mut pre = 0;
3261    let mut post = 0;
3262    for option in parts {
3263        let (key, value) = option
3264            .split_once('=')
3265            .ok_or_else(|| format!("trigger option {option:?} needs key=value"))?;
3266        match key.trim() {
3267            "pre" => pre = crate::config::parse_duration(value.trim())?,
3268            "post" => post = crate::config::parse_duration(value.trim())?,
3269            other => {
3270                return Err(format!("trigger option {other:?} is not pre or post"));
3271            }
3272        }
3273    }
3274    let channel = channel.trim();
3275    if channel.is_empty() {
3276        return Err("trigger needs a probe name".into());
3277    }
3278    Ok(litz_board::probe::Trigger {
3279        channel: channel.to_string(),
3280        level,
3281        pre_ticks: pre,
3282        post_ticks: post,
3283    })
3284}
3285
3286#[cfg(test)]
3287mod tests {
3288    use super::*;
3289
3290    fn staged(name: &str, source: &str) -> StagedScript {
3291        StagedScript {
3292            name: name.into(),
3293            bytes: source.as_bytes().to_vec(),
3294        }
3295    }
3296
3297    #[test]
3298    fn a_multi_file_paste_writes_every_module_then_runs_the_entry() {
3299        let scripts = [
3300            staged("main.py", "import util\nprint(util.N)\n"),
3301            staged("lib/util.py", "N = 42\n"),
3302        ];
3303        let pairs: Vec<(&str, &[u8])> = scripts
3304            .iter()
3305            .map(|script| (script.name.as_str(), script.bytes.as_slice()))
3306            .collect();
3307        let text = crate::python::stage_program("main.py", &pairs);
3308        assert!(text.contains("_litz_stage('main.py', (b'import util\\nprint(util.N)\\n'))"));
3309        assert!(text.contains("_litz_stage('lib/util.py', (b'N = 42\\n'))"));
3310        assert!(text.ends_with("exec(open('main.py').read())\n"));
3311        assert!(text.contains("os.mkdir(cur)"), "directories are created");
3312    }
3313
3314    #[test]
3315    fn a_staged_path_may_not_escape_the_device_directory() {
3316        assert_eq!(staged_name("lib/util.py").unwrap(), "lib/util.py");
3317        for bad in ["/boot.py", "../main.py", "lib//x.py", "", "lib/./x.py"] {
3318            assert!(staged_name(bad).is_err(), "{bad:?} should be refused");
3319        }
3320    }
3321
3322    #[test]
3323    fn a_trigger_spec_names_a_channel_a_level_and_a_window() {
3324        let trigger = parse_trigger("sck=high,pre=250us,post=2ms").unwrap();
3325        assert_eq!(trigger.channel, "sck");
3326        assert_eq!(trigger.level, litz_core::Level::High);
3327        assert_eq!(trigger.pre_ticks, 250_000);
3328        assert_eq!(trigger.post_ticks, 2_000_000);
3329        let plain = parse_trigger("tx=low").unwrap();
3330        assert_eq!(plain.level, litz_core::Level::Low);
3331        assert_eq!((plain.pre_ticks, plain.post_ticks), (0, 0));
3332        assert!(parse_trigger("sck").is_err());
3333        assert!(parse_trigger("sck=sideways").is_err());
3334        assert!(parse_trigger("sck=high,speed=1").is_err());
3335    }
3336}