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