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