1use 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#[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;
31const REPL_PROMPT: &str = ">>> ";
35const CIRCUITPYTHON_NUDGE: u64 = 200_000_000;
39const MAX_SCRIPT: usize = 64 * 1024;
43const 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#[derive(Clone, Default)]
58pub struct Options {
59 pub vcd: Option<PathBuf>,
61 pub break_at: Option<u32>,
63 pub analog: bool,
66 pub wifi: Option<String>,
68 pub coverage: bool,
71 pub interactive: Option<Interactive>,
74 pub screenshot: Option<Screenshot>,
77 pub probes: Vec<String>,
80 pub scope: Option<PathBuf>,
82 pub trigger: Option<litz_board::probe::Trigger>,
85 pub decodes: Vec<DecodeSection>,
88 pub gdb: Option<GdbRequest>,
90 pub pcap: Option<PathBuf>,
93 pub pcap_air: Option<PathBuf>,
96 pub pcap_eth: Option<PathBuf>,
99 pub host_network: bool,
102 pub host_forwards: Vec<String>,
103 pub heap_sample: bool,
106 pub heap_interval: Option<u64>,
109 pub heap_min_free: Option<u32>,
111 pub heap_csv: Option<PathBuf>,
113 pub sd_export: Option<PathBuf>,
116}
117
118#[derive(Clone, Debug, Default)]
120pub struct Interactive {
121 pub board: Option<String>,
123}
124
125#[derive(Clone, Debug)]
127pub struct Screenshot {
128 pub board: Option<String>,
131 pub path: PathBuf,
132}
133
134struct HeapLog {
141 label: String,
142 interval_ns: u64,
143 next_ns: u64,
144 limit: Option<u32>,
145 csv: Option<(PathBuf, std::io::BufWriter<std::fs::File>)>,
146 samples: Vec<(u64, u32)>,
147 lowest: Option<u32>,
148 failure: Option<String>,
149 last_error: Option<String>,
150}
151
152impl HeapLog {
153 fn from_options(options: &Options, label: String) -> Result<Option<Self>, String> {
154 let enabled = options.heap_sample
155 || options.heap_interval.is_some()
156 || options.heap_min_free.is_some()
157 || options.heap_csv.is_some();
158 if !enabled {
159 return Ok(None);
160 }
161 let interval_ns = options.heap_interval.unwrap_or(1_000_000_000).max(1);
162 let csv = options
163 .heap_csv
164 .as_ref()
165 .map(|path| {
166 let file =
167 std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
168 let mut writer = std::io::BufWriter::new(file);
169 writer
170 .write_all(b"part,time_s,free,min_free\n")
171 .map_err(|e| format!("{}: {e}", path.display()))?;
172 Ok::<(PathBuf, std::io::BufWriter<std::fs::File>), String>((path.clone(), writer))
173 })
174 .transpose()?;
175 Ok(Some(Self {
176 label,
177 interval_ns,
178 next_ns: 0,
179 limit: options.heap_min_free,
180 csv,
181 samples: Vec::new(),
182 lowest: None,
183 failure: None,
184 last_error: None,
185 }))
186 }
187
188 fn sample(&mut self, mcu: &mut Fleet, now_ns: u64) {
192 if now_ns < self.next_ns || self.failure.is_some() {
193 return;
194 }
195 while self.next_ns <= now_ns {
196 self.next_ns = self.next_ns.saturating_add(self.interval_ns);
197 }
198 self.record(mcu, now_ns);
199 }
200
201 fn record(&mut self, mcu: &mut Fleet, now_ns: u64) {
203 let free = match mcu.sample_heap() {
204 Ok(free) => free,
205 Err(error) => {
206 self.last_error = Some(error);
207 return;
208 }
209 };
210 self.samples.push((now_ns, free));
211 self.lowest = Some(self.lowest.map_or(free, |lowest| lowest.min(free)));
212 let lowest = self.lowest.unwrap_or(free);
213 if let Some((path, writer)) = &mut self.csv {
214 let line = format!(
215 "{},{:.3},{},{}\n",
216 csv_field(&self.label),
217 now_ns as f64 / 1e9,
218 free,
219 lowest
220 );
221 if let Err(error) = writer.write_all(line.as_bytes()) {
222 self.failure = Some(format!("{}: {error}", path.display()));
223 }
224 }
225 if let Some(limit) = self.limit
226 && free < limit
227 {
228 self.failure = Some(format!(
229 "free heap {free} dropped below {limit} bytes at {:.3}s",
230 now_ns as f64 / 1e9
231 ));
232 }
233 }
234
235 fn finish(mut self, mcu: &mut Fleet, now_ns: u64) -> (Vec<String>, Option<String>) {
238 if !self.samples.iter().any(|(at, _)| *at == now_ns) {
241 self.record(mcu, now_ns);
242 }
243 let mut lines = Vec::new();
244 if self.samples.is_empty() {
245 let why = self
246 .last_error
247 .unwrap_or_else(|| "the firmware never answered".into());
248 let message = format!("no samples: {why}");
249 return if self.limit.is_some() {
252 (Vec::new(), Some(message))
253 } else {
254 (vec![message], None)
255 };
256 }
257 let first = self.samples[0];
258 let last = *self.samples.last().expect("checked non-empty");
259 let mut last_free = None;
260 for (at, free) in &self.samples {
261 if last_free == Some(*free) {
262 continue;
263 }
264 last_free = Some(*free);
265 lines.push(format!(
266 "[heap {}] {:.3}s free={free} min={}",
267 self.label,
268 *at as f64 / 1e9,
269 self.lowest.unwrap_or(*free)
270 ));
271 }
272 let lost = first.1.saturating_sub(last.1);
273 let seconds = (last.0.saturating_sub(first.0)) as f64 / 1e9;
274 let rate = if seconds > 0.0 {
275 lost as f64 / seconds
276 } else {
277 0.0
278 };
279 lines.push(format!(
280 "Heap: {} samples, free {} -> {}, lowest {}, {:.0} bytes/s lost",
281 self.samples.len(),
282 first.1,
283 last.1,
284 self.lowest.unwrap_or(last.1),
285 rate
286 ));
287 (lines, self.failure)
288 }
289}
290
291fn csv_field(text: &str) -> String {
294 if text.contains([',', '"', '\n']) {
295 format!("\"{}\"", text.replace('"', "\"\""))
296 } else {
297 text.to_string()
298 }
299}
300
301impl HeapLog {
302 fn failed(&self) -> bool {
304 self.failure.is_some()
305 }
306}
307
308#[derive(Clone, Debug)]
314pub struct GdbRequest {
315 pub board: Option<String>,
316 pub port: u16,
317}
318
319pub struct Outcome {
320 pub exit_code: i32,
321 pub output: String,
322 pub sim_ms: u32,
325 pub tests: Vec<TestOutcome>,
327}
328
329pub struct TestOutcome {
330 pub name: String,
331 pub passed: bool,
332 pub exit_code: i32,
333 pub output: String,
334 pub sim_ms: u32,
335}
336
337pub struct CaptureOutcome {
344 pub exit_code: i32,
345 pub output: String,
346 pub sim_ms: u32,
347 pub part_states: BTreeMap<String, PartState>,
349 pub faults: Vec<String>,
351}
352
353struct Prepared {
354 config: Config,
355 dir: PathBuf,
356 registry: Registry,
357 circuit: Circuit,
358 boards: Vec<BoardPlan>,
361}
362
363struct BoardPlan {
365 id: String,
367 manifest: litz_catalog::PartManifest,
369 flash_size: usize,
370 rom: Vec<u8>,
371 firmware: Vec<u8>,
372 elf: Option<Vec<u8>>,
374 layout: FirmwareLayout,
376 bootloader: Option<Vec<u8>>,
377 partition_table: Option<Vec<u8>>,
378 runtime: Runtime,
382 python: crate::python::PythonRuntime,
385 scripts: Vec<StagedScript>,
386 mac: [u8; 6],
387}
388
389struct StagedScript {
391 name: String,
393 bytes: Vec<u8>,
394}
395
396pub fn execute(dir: &Path, mode: Mode, strict: bool, update_lock: bool) -> Result<Outcome, String> {
397 execute_with(dir, mode, strict, update_lock, &Options::default())
398}
399
400pub fn execute_with(
402 dir: &Path,
403 mode: Mode,
404 strict: bool,
405 update_lock: bool,
406 options: &Options,
407) -> Result<Outcome, String> {
408 let config = match Config::load_project(dir) {
409 Ok(config) => config,
410 Err(e) if mode == Mode::Check => {
411 let _ = e;
412 Config::default()
413 }
414 Err(e) => return Err(e),
415 };
416
417 let mut registry = Registry::builtin();
418 for sub in ["parts", "boards"] {
419 let path = dir.join(sub);
420 if path.is_dir() {
421 registry.load_dir(&path).map_err(|e| e.to_string())?;
422 }
423 }
424
425 let diagram_path = dir.join(config.project.diagram());
426 let text = std::fs::read_to_string(&diagram_path)
427 .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
428 let circuit =
429 Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
430
431 let diagnostics = circuit.validate(®istry);
432 if blocks(&diagnostics, strict) {
433 return Ok(Outcome {
434 exit_code: 1,
435 output: render(&diagnostics),
436 sim_ms: 0,
437 tests: Vec::new(),
438 });
439 }
440
441 if mode == Mode::Check {
442 let mut output = render(&diagnostics);
443 if output.is_empty() {
444 output.push_str("diagram is valid\n");
445 }
446 return Ok(Outcome {
447 exit_code: 0,
448 output,
449 sim_ms: 0,
450 tests: Vec::new(),
451 });
452 }
453
454 let prepared = prepare(config, dir, registry, circuit)?;
455 enforce_lock(&prepared, update_lock)?;
456
457 match mode {
458 Mode::Run => run_once(&prepared, None, strict, options),
459 Mode::Test => {
460 let specs = if prepared.config.test.is_empty() {
461 vec![TestSpec {
462 name: "run".into(),
463 timeout: None,
464 expect: None,
465 fail: None,
466 input: Vec::new(),
467 expect_state: None,
468 state_at: None,
469 state_stays: None,
470 }]
471 } else {
472 prepared.config.test.clone()
473 };
474 let mut output = String::new();
475 let mut tests = Vec::new();
476 let mut failed = 0;
477 let mut sim_ms = 0;
478 for spec in &specs {
479 let outcome = run_once(&prepared, Some(spec), strict, options)?;
480 output.push_str(&format!("== {} ==\n", spec.name));
481 output.push_str(&outcome.output);
482 if !outcome.output.ends_with('\n') {
483 output.push('\n');
484 }
485 if outcome.exit_code != 0 {
486 failed += 1;
487 }
488 sim_ms = sim_ms.max(outcome.sim_ms);
489 tests.push(TestOutcome {
490 name: spec.name.clone(),
491 passed: outcome.exit_code == 0,
492 exit_code: outcome.exit_code,
493 output: outcome.output,
494 sim_ms: outcome.sim_ms,
495 });
496 }
497 Ok(Outcome {
498 exit_code: if failed == 0 { 0 } else { 1 },
499 output: format!(
500 "{output}{}/{} tests passed\n",
501 specs.len() - failed,
502 specs.len()
503 ),
504 sim_ms,
505 tests,
506 })
507 }
508 Mode::Check => unreachable!(),
509 }
510}
511
512pub fn execute_capture(
518 dir: &Path,
519 timeout: Option<&str>,
520 strict: bool,
521 update_lock: bool,
522 options: &Options,
523) -> Result<CaptureOutcome, String> {
524 let config = Config::load_project(dir)?;
525 let mut registry = Registry::builtin();
526 for sub in ["parts", "boards"] {
527 let path = dir.join(sub);
528 if path.is_dir() {
529 registry.load_dir(&path).map_err(|e| e.to_string())?;
530 }
531 }
532
533 let diagram_path = dir.join(config.project.diagram());
534 let text = std::fs::read_to_string(&diagram_path)
535 .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
536 let circuit =
537 Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
538
539 let diagnostics = circuit.validate(®istry);
540 if blocks(&diagnostics, strict) {
541 return Ok(CaptureOutcome {
542 exit_code: 1,
543 output: render(&diagnostics),
544 sim_ms: 0,
545 part_states: BTreeMap::new(),
546 faults: Vec::new(),
547 });
548 }
549
550 let prepared = prepare(config, dir, registry, circuit)?;
551 enforce_lock(&prepared, update_lock)?;
552 run_capture(&prepared, timeout, options)
553}
554
555pub fn execute_scenario(
561 dir: &Path,
562 file: &Path,
563 strict: bool,
564 update_lock: bool,
565) -> Result<Outcome, String> {
566 execute_scenario_with(dir, file, strict, update_lock, &Options::default())
567}
568
569pub fn execute_scenario_with(
571 dir: &Path,
572 file: &Path,
573 strict: bool,
574 update_lock: bool,
575 options: &Options,
576) -> Result<Outcome, String> {
577 let config = Config::load_project(dir)?;
578 let mut registry = Registry::builtin();
579 for sub in ["parts", "boards"] {
580 let path = dir.join(sub);
581 if path.is_dir() {
582 registry.load_dir(&path).map_err(|e| e.to_string())?;
583 }
584 }
585 let diagram_path = dir.join(config.project.diagram());
586 let text = std::fs::read_to_string(&diagram_path)
587 .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
588 let circuit =
589 Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
590
591 let diagnostics = circuit.validate(®istry);
592 if blocks(&diagnostics, strict) {
593 return Ok(Outcome {
594 exit_code: 1,
595 output: render(&diagnostics),
596 sim_ms: 0,
597 tests: Vec::new(),
598 });
599 }
600
601 let prepared = prepare(config, dir, registry, circuit)?;
602 enforce_lock(&prepared, update_lock)?;
603 let scenario = Scenario::load(file)?;
604 run_scenario(&prepared, &scenario, options)
605}
606
607const DEFAULT_WAIT: u64 = 10_000_000_000;
609
610fn run_scenario(
611 prepared: &Prepared,
612 scenario: &Scenario,
613 options: &Options,
614) -> Result<Outcome, String> {
615 let Booted {
616 fleet: mut mcu,
617 board,
618 capture,
619 ..
620 } = boot(prepared, options)?;
621 start_recording(&mut mcu, options, prepared);
622 let mut heap = HeapLog::from_options(
623 options,
624 prepared
625 .boards
626 .first()
627 .map(|plan| plan.id.clone())
628 .unwrap_or_else(|| "esp".into()),
629 )?;
630 let mut serial = String::new();
631 let mut notes = Vec::new();
632 let mut failed = false;
633 let mut last_touch: Vec<Option<(u16, u16)>> = vec![None; prepared.boards.len()];
636 let mut pending_touch: Option<(u64, u16, u16, Option<usize>)> = None;
637
638 for (index, plan) in prepared.boards.iter().enumerate() {
642 if !pastes_script(plan) {
643 continue;
644 }
645 if !plan.python.interrupt_sequence().is_empty() {
648 mcu.write_console_on(index, plan.python.interrupt_sequence());
649 advance(&mut mcu, &mut serial);
650 }
651 let deadline = now_ns(&mcu).saturating_add(DEFAULT_WAIT);
652 while !mcu.console_text(index).contains(REPL_PROMPT) {
653 if now_ns(&mcu) >= deadline || !advance(&mut mcu, &mut serial) {
654 break;
655 }
656 }
657 if !mcu.console_text(index).contains(REPL_PROMPT) {
658 return Err(format!(
659 "board {:?}: MicroPython REPL prompt did not appear within {DEFAULT_WAIT} ns of \
660 simulated time; check that its firmware is a MicroPython or CircuitPython build",
661 plan.id
662 ));
663 }
664 paste_script(&mut mcu, index, &plan.scripts, plan.python);
665 }
666
667 for (index, step) in scenario.steps.iter().enumerate() {
668 let number = index + 1;
669 {
670 let now = now_ns(&mcu);
671 service_touch_release(&mut mcu, &mut pending_touch, now);
672 }
673 match step {
674 Step::Delay { ns } => {
675 let target = now_ns(&mcu).saturating_add(*ns);
676 while now_ns(&mcu) < target && advance(&mut mcu, &mut serial) {
677 {
678 let now = now_ns(&mcu);
679 service_touch_release(&mut mcu, &mut pending_touch, now);
680 }
681 if let Some(log) = &mut heap {
682 {
683 let now = now_ns(&mcu);
684 log.sample(&mut mcu, now);
685 }
686 if log.failed() {
687 break;
688 }
689 }
690 }
691 }
692 Step::WaitSerial { text, timeout } => {
693 let deadline = now_ns(&mcu).saturating_add(timeout.unwrap_or(DEFAULT_WAIT));
694 while !serial.contains(text.as_str()) {
695 if now_ns(&mcu) >= deadline {
696 failed = true;
697 notes.push(format!("step {number}: never saw {text:?}"));
698 break;
699 }
700 if !advance(&mut mcu, &mut serial) {
701 break;
702 }
703 {
704 let now = now_ns(&mcu);
705 service_touch_release(&mut mcu, &mut pending_touch, now);
706 }
707 if let Some(log) = &mut heap {
708 {
709 let now = now_ns(&mcu);
710 log.sample(&mut mcu, now);
711 }
712 if log.failed() {
713 break;
714 }
715 }
716 }
717 }
718 Step::WriteSerial { text } => {
719 mcu.write_console_on(0, text.as_bytes());
722 advance(&mut mcu, &mut serial);
723 }
724 Step::WaitPin {
725 part,
726 pin,
727 value,
728 timeout,
729 } => {
730 let deadline = now_ns(&mcu).saturating_add(timeout.unwrap_or(DEFAULT_WAIT));
731 loop {
732 let level = pin_level(prepared, &mcu, part, pin.as_deref());
733 if level.is_some_and(|level| (level == Level::High) == *value) {
734 break;
735 }
736 if now_ns(&mcu) >= deadline {
737 failed = true;
738 notes.push(format!(
739 "step {number}: {part} never reached {} within {} ns",
740 if *value { "high" } else { "low" },
741 timeout.unwrap_or(DEFAULT_WAIT)
742 ));
743 break;
744 }
745 if !advance(&mut mcu, &mut serial) {
746 break;
747 }
748 {
749 let now = now_ns(&mcu);
750 service_touch_release(&mut mcu, &mut pending_touch, now);
751 }
752 }
753 }
754 Step::ExpectPin { part, pin, value } => {
755 match pin_level(prepared, &mcu, part, pin.as_deref()) {
756 Some(level) => {
757 let high = level == Level::High;
758 if high != *value {
759 failed = true;
760 notes.push(format!(
761 "step {number}: {part} is {} but the scenario expects {}",
762 if high { "high" } else { "low" },
763 if *value { "high" } else { "low" }
764 ));
765 }
766 }
767 None => {
768 failed = true;
769 notes.push(format!(
770 "step {number}: no part {part:?} is wired to a chip pin"
771 ));
772 }
773 }
774 }
775 Step::SetControl {
776 part,
777 control,
778 value,
779 } => {
780 if mcu.set_named_control(part, control, value) {
781 } else {
783 match control.as_str() {
784 "value" | "position" => match value.trim().parse::<f64>() {
787 Ok(percent) if (0.0..=100.0).contains(&percent) => {
788 let permille = (percent * 10.0).round() as u16;
789 if !mcu.set_control(part, permille) {
790 failed = true;
791 notes.push(format!(
792 "step {number}: part {part:?} has no continuous control"
793 ));
794 }
795 }
796 _ => {
797 failed = true;
798 notes.push(format!(
799 "step {number}: set-control value {value:?} is not 0 through 100"
800 ));
801 }
802 },
803 other => {
804 failed = true;
805 notes.push(format!(
806 "step {number}: part {part:?} has no control {other:?}"
807 ));
808 }
809 }
810 }
811 }
812 Step::TakeScreenshot {
813 part,
814 path,
815 board: which,
816 expected,
817 tolerance,
818 } => {
819 let index = match which {
820 Some(id) => Some(find_board(&prepared.boards, id, "take-screenshot")?),
821 None => None,
822 };
823 let path = match (path, expected) {
827 (Some(path), _) => path.clone(),
828 (None, Some(expected)) => expected.with_extension("actual.png"),
829 (None, None) => unreachable!("the parser requires one of them"),
830 };
831 let capture = match part {
832 Some(part) if prepared.boards.iter().any(|plan| plan.id == *part) => {
833 let board = find_board(&prepared.boards, part, "take-screenshot")?;
834 mcu.save_display(Some(board), &path)
835 }
836 Some(part) => mcu.save_part_display(part, &path),
837 None => mcu.save_display(index, &path),
838 };
839 match capture {
840 Ok(()) => {
841 if let Some(expected) = expected {
842 match compare_images(&path, expected, *tolerance) {
843 Ok(()) => {}
844 Err(error) => {
845 failed = true;
846 notes.push(format!("step {number}: {error}"));
847 }
848 }
849 }
850 }
851 Err(error) => {
852 failed = true;
853 notes.push(format!("step {number}: {error}"));
854 }
855 }
856 }
857 Step::Touch {
858 x,
859 y,
860 down,
861 board: which,
862 part,
863 } => {
864 let index = touch_board(prepared, which, part, "touch")?;
865 if let Err(error) = mcu.touch(index, *x, *y, *down) {
866 failed = true;
867 notes.push(format!("step {number}: {error}"));
868 } else if *down {
869 let slot = index.unwrap_or(0);
870 if let Some(slot) = last_touch.get_mut(slot) {
871 *slot = Some((*x, *y));
872 }
873 }
874 }
875 Step::TouchMove {
876 x,
877 y,
878 board: which,
879 part,
880 } => {
881 let index = touch_board(prepared, which, part, "touch-move")?;
882 if let Err(error) = mcu.touch(index, *x, *y, true) {
883 failed = true;
884 notes.push(format!("step {number}: {error}"));
885 } else {
886 let slot = index.unwrap_or(0);
887 if let Some(slot) = last_touch.get_mut(slot) {
888 *slot = Some((*x, *y));
889 }
890 }
891 }
892 Step::TouchTap {
893 x,
894 y,
895 duration,
896 wait,
897 board: which,
898 part,
899 } => {
900 let index = touch_board(prepared, which, part, "touch")?;
901 if let Err(error) = mcu.touch(index, *x, *y, true) {
902 failed = true;
903 notes.push(format!("step {number}: {error}"));
904 } else {
905 let slot = index.unwrap_or(0);
906 if let Some(slot) = last_touch.get_mut(slot) {
907 *slot = Some((*x, *y));
908 }
909 let release_at = now_ns(&mcu).saturating_add(*duration);
910 if *wait {
911 while now_ns(&mcu) < release_at && advance(&mut mcu, &mut serial) {
912 {
913 let now = now_ns(&mcu);
914 service_touch_release(&mut mcu, &mut pending_touch, now);
915 }
916 }
917 let _ = mcu.touch(index, *x, *y, false);
918 } else {
919 pending_touch = Some((release_at, *x, *y, index));
920 }
921 }
922 }
923 Step::TouchRelease {
924 x,
925 y,
926 board: which,
927 part,
928 } => {
929 let index = touch_board(prepared, which, part, "touch-release")?;
930 let previous = last_touch.get(index.unwrap_or(0)).copied().flatten();
931 let (x, y) = match (x, y) {
932 (Some(x), Some(y)) => (*x, *y),
933 _ => previous.unwrap_or((0, 0)),
934 };
935 pending_touch = None;
936 if let Err(error) = mcu.touch(index, x, y, false) {
937 failed = true;
938 notes.push(format!("step {number}: {error}"));
939 }
940 }
941 }
942 if let Some(log) = &mut heap {
943 {
944 let now = now_ns(&mcu);
945 log.sample(&mut mcu, now);
946 }
947 }
948 let conflicts = mcu.conflicts();
949 if !conflicts.is_empty() {
950 for conflict in &conflicts {
951 notes.push(format!(
952 "electrical fault on net {}: {}",
953 conflict.net, conflict.detail
954 ));
955 }
956 failed = true;
957 break;
958 }
959 }
960
961 let mut output = serial;
962 if !output.ends_with('\n') && !output.is_empty() {
963 output.push('\n');
964 }
965 for note in notes {
966 output.push_str(&format!("litz: {note}\n"));
967 }
968 for line in probe_report(&board) {
969 output.push_str(&format!("litz: {line}\n"));
970 }
971 for line in decode_report(&board, prepared, options)? {
972 output.push_str(&format!("litz: {line}\n"));
973 }
974 finish_recording(&mcu, &board, options, capture.as_ref())?;
975 if let Some(log) = heap {
976 let end = now_ns(&mcu);
977 let (lines, failure) = log.finish(&mut mcu, end);
978 for line in lines {
979 output.push_str(&format!("litz: {line}\n"));
980 }
981 if let Some(failure) = failure {
982 failed = true;
983 output.push_str(&format!("litz: heap: {failure}\n"));
984 }
985 }
986 Ok(Outcome {
987 exit_code: if failed { 1 } else { 0 },
988 output,
989 sim_ms: (mcu.seconds() * 1000.0) as u32,
990 tests: Vec::new(),
991 })
992}
993
994fn pin_level(prepared: &Prepared, mcu: &Fleet, target: &str, pin: Option<&str>) -> Option<Level> {
998 if let Some(index) = prepared.boards.iter().position(|plan| plan.id == target)
999 && let Some(gpio) = pin.and_then(parse_gpio)
1000 {
1001 return mcu.gpio_level(index, gpio);
1002 }
1003 match (target.split_once(':'), pin) {
1004 (Some((part, pin)), _) => mcu.part_pin_level(part, Some(pin)),
1005 (None, Some(pin)) => mcu.part_pin_level(target, Some(pin)),
1006 (None, None) => mcu.part_pin_level(target, None),
1007 }
1008}
1009
1010fn parse_gpio(text: &str) -> Option<u8> {
1012 let text = text.trim();
1013 let text = text
1014 .strip_prefix("GPIO")
1015 .or_else(|| text.strip_prefix("gpio"))
1016 .or_else(|| text.strip_prefix('D'))
1017 .or_else(|| text.strip_prefix('d'))
1018 .unwrap_or(text);
1019 text.parse().ok()
1020}
1021
1022fn now_ns(fleet: &Fleet) -> u64 {
1023 fleet.frontier_ns()
1024}
1025
1026fn service_touch_release(
1029 mcu: &mut Fleet,
1030 pending: &mut Option<(u64, u16, u16, Option<usize>)>,
1031 now_ns: u64,
1032) {
1033 if let Some((at, x, y, index)) = *pending
1034 && now_ns >= at
1035 {
1036 let _ = mcu.touch(index, x, y, false);
1037 *pending = None;
1038 }
1039}
1040
1041fn compare_images(actual: &Path, expected: &Path, tolerance: u8) -> Result<(), String> {
1045 let actual_image = decode_png(actual)?;
1046 let expected_image = decode_png(expected)?;
1047 if actual_image.0 != expected_image.0 || actual_image.1 != expected_image.1 {
1048 return Err(format!(
1049 "screenshot {} is {}x{} but {} is {}x{}",
1050 actual.display(),
1051 actual_image.0,
1052 actual_image.1,
1053 expected.display(),
1054 expected_image.0,
1055 expected_image.1
1056 ));
1057 }
1058 let (width, _, actual_pixels) = actual_image;
1059 let (_, _, expected_pixels) = expected_image;
1060 let mut mismatched = 0usize;
1061 let mut first = None;
1062 for (index, (a, b)) in actual_pixels.iter().zip(&expected_pixels).enumerate() {
1063 let differs = a.iter().zip(b).any(|(a, b)| a.abs_diff(*b) > tolerance);
1064 if differs {
1065 mismatched += 1;
1066 first.get_or_insert(index);
1067 }
1068 }
1069 if let Some(index) = first {
1070 let x = index as u32 % width;
1071 let y = index as u32 / width;
1072 return Err(format!(
1073 "screenshot {} differs from {} at ({x}, {y}) in {width}x{} pixels; \
1074 {mismatched} pixels differ",
1075 actual.display(),
1076 expected.display(),
1077 actual_pixels.len() as u32 / width.max(1)
1078 ));
1079 }
1080 Ok(())
1081}
1082
1083fn decode_png(path: &Path) -> Result<(u32, u32, Vec<[u8; 4]>), String> {
1086 let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
1087 let mut decoder = png::Decoder::new(std::io::BufReader::new(file));
1088 decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
1089 let mut reader = decoder
1090 .read_info()
1091 .map_err(|e| format!("{}: {e}", path.display()))?;
1092 let size = reader
1093 .output_buffer_size()
1094 .ok_or_else(|| format!("{}: the image is too large to decode", path.display()))?;
1095 let mut buffer = vec![0; size];
1096 let info = reader
1097 .next_frame(&mut buffer)
1098 .map_err(|e| format!("{}: {e}", path.display()))?;
1099 let pixels = match info.color_type {
1100 png::ColorType::Rgba => buffer.as_chunks::<4>().0.to_vec(),
1101 png::ColorType::Rgb => buffer
1102 .as_chunks::<3>()
1103 .0
1104 .iter()
1105 .map(|p| [p[0], p[1], p[2], 255])
1106 .collect(),
1107 png::ColorType::GrayscaleAlpha => buffer
1108 .as_chunks::<2>()
1109 .0
1110 .iter()
1111 .map(|p| [p[0], p[0], p[0], p[1]])
1112 .collect(),
1113 png::ColorType::Grayscale => buffer.iter().map(|p| [*p, *p, *p, 255]).collect(),
1114 png::ColorType::Indexed => {
1115 return Err(format!(
1116 "{}: an indexed PNG did not expand to RGB",
1117 path.display()
1118 ));
1119 }
1120 };
1121 Ok((info.width, info.height, pixels))
1122}
1123
1124fn start_recording(mcu: &mut Fleet, options: &Options, prepared: &Prepared) {
1127 if let Some(pc) = options.break_at {
1128 mcu.break_at(pc);
1129 }
1130 let wants_trace = options.vcd.is_some()
1133 || options.scope.is_some()
1134 || !prepared.config.probes.is_empty()
1135 || !prepared.config.decodes.is_empty()
1136 || !options.probes.is_empty()
1137 || !options.decodes.is_empty();
1138 if wants_trace {
1139 mcu.start_trace();
1140 }
1141}
1142
1143fn finish_recording(
1144 mcu: &Fleet,
1145 board: &std::rc::Rc<std::cell::RefCell<Board>>,
1146 options: &Options,
1147 capture: Option<&std::rc::Rc<std::cell::RefCell<litz_net::capture::Capture>>>,
1148) -> Result<(), String> {
1149 if let (Some(path), Some(capture)) = (&options.pcap, capture) {
1150 std::fs::write(path, capture.borrow().to_pcap())
1151 .map_err(|e| format!("{}: {e}", path.display()))?;
1152 }
1153 if let Some(path) = &options.vcd {
1154 std::fs::write(path, mcu.vcd()).map_err(|e| format!("{}: {e}", path.display()))?;
1155 }
1156 if let Some(path) = &options.sd_export {
1157 board.borrow_mut().save_sd_images(path)?;
1158 }
1159 if let Some(path) = &options.scope {
1160 let channels = board.borrow().scope();
1161 let csv = match &options.trigger {
1162 Some(trigger) => {
1163 let clipped = probe::triggered(&channels, trigger)?;
1164 probe::to_csv(&clipped)
1165 }
1166 None => probe::to_csv(&channels),
1167 };
1168 std::fs::write(path, csv).map_err(|e| format!("{}: {e}", path.display()))?;
1169 }
1170 Ok(())
1171}
1172
1173fn probe_report(board: &std::rc::Rc<std::cell::RefCell<Board>>) -> Vec<String> {
1175 board.borrow().scope().iter().map(probe::summary).collect()
1176}
1177
1178fn decode_report(
1180 board: &std::rc::Rc<std::cell::RefCell<Board>>,
1181 prepared: &Prepared,
1182 options: &Options,
1183) -> Result<Vec<String>, String> {
1184 let channels = board.borrow().scope();
1185 crate::decode::report(
1186 prepared.config.decodes.iter().chain(options.decodes.iter()),
1187 &channels,
1188 )
1189}
1190
1191fn advance(mcu: &mut Fleet, serial: &mut String) -> bool {
1193 let _ = mcu.run(1_000_000);
1194 let chunk = mcu.take_console();
1195 if !chunk.is_empty() {
1196 serial.push_str(&String::from_utf8_lossy(&chunk));
1197 }
1198 mcu.conflicts().is_empty()
1199}
1200
1201fn pastes_script(plan: &BoardPlan) -> bool {
1205 matches!(plan.runtime, Runtime::Micropython | Runtime::CircuitPython)
1206 && !plan.scripts.is_empty()
1207}
1208
1209fn read_staged(dir: &Path, rel: &str) -> Result<StagedScript, String> {
1211 let path = dir.join(rel);
1212 let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1213 if bytes.len() > MAX_SCRIPT {
1214 return Err(format!(
1215 "{} is {} bytes; a MicroPython raw paste is limited to {MAX_SCRIPT} bytes",
1216 path.display(),
1217 bytes.len()
1218 ));
1219 }
1220 Ok(StagedScript {
1221 name: staged_name(rel)?,
1222 bytes,
1223 })
1224}
1225
1226fn staged_name(name: &str) -> Result<String, String> {
1229 let name = name.trim().replace('\\', "/");
1230 let invalid = name.is_empty()
1231 || name.starts_with('/')
1232 || name
1233 .split('/')
1234 .any(|part| part.is_empty() || part == "." || part == "..");
1235 if invalid {
1236 return Err(format!(
1237 "staged script {name:?} must be a relative path inside the project, \
1238 like \"main.py\" or \"lib/util.py\""
1239 ));
1240 }
1241 Ok(name)
1242}
1243
1244fn paste_script(
1250 mcu: &mut Fleet,
1251 index: usize,
1252 scripts: &[StagedScript],
1253 python: crate::python::PythonRuntime,
1254) {
1255 let body = if scripts.len() == 1 {
1258 scripts[0].bytes.clone()
1259 } else {
1260 let pairs: Vec<(&str, &[u8])> = scripts
1261 .iter()
1262 .map(|script| (script.name.as_str(), script.bytes.as_slice()))
1263 .collect();
1264 crate::python::stage_program(&scripts[0].name, &pairs).into_bytes()
1265 };
1266 let mut bytes = Vec::with_capacity(body.len() + 4);
1267 let interrupt = python.interrupt_sequence();
1270 if interrupt.is_empty() {
1271 bytes.push(0x03);
1272 } else {
1273 bytes.extend_from_slice(interrupt);
1274 }
1275 bytes.extend_from_slice(python.raw_paste_begin());
1276 bytes.extend_from_slice(&body);
1277 bytes.extend_from_slice(python.raw_paste_end());
1278 for chunk in bytes.chunks(16) {
1283 mcu.write_console_to(index, chunk);
1284 mcu.run_one(index, 1_000_000);
1285 }
1286}
1287
1288fn prepare(
1289 config: Config,
1290 dir: &Path,
1291 registry: Registry,
1292 circuit: Circuit,
1293) -> Result<Prepared, String> {
1294 let instances: Vec<litz_diagram::PartInstance> = circuit
1297 .parts
1298 .iter()
1299 .filter(|part| {
1300 registry
1301 .get(&part.type_key)
1302 .and_then(|manifest| manifest.board.as_ref())
1303 .is_some()
1304 })
1305 .cloned()
1306 .collect();
1307 if instances.is_empty() {
1308 return Err("the diagram has no development board".into());
1309 }
1310
1311 let sections: Vec<BoardSection> = if config.boards.is_empty() {
1315 if instances.len() != 1 {
1316 return Err(format!(
1317 "the diagram has {} development boards; give each one a [[board]] entry with its id and firmware",
1318 instances.len()
1319 ));
1320 }
1321 vec![BoardSection {
1322 id: instances[0].id.clone(),
1323 firmware: config.sim.firmware.clone(),
1324 bootloader: config.sim.bootloader.clone(),
1325 partition_table: config.sim.partition_table.clone(),
1326 rom: config.sim.rom.clone(),
1327 elf: config.sim.elf.clone(),
1328 runtime: Some(config.sim.runtime),
1329 script: config.sim.script.clone(),
1330 scripts: config.sim.scripts.clone(),
1331 flash_size: config.sim.flash_size.clone(),
1332 mac: config.sim.mac.clone(),
1333 }]
1334 } else {
1335 if config.sim.firmware.is_some() {
1336 return Err(
1337 "a project with [[board]] entries names firmware per board; remove [sim] firmware"
1338 .into(),
1339 );
1340 }
1341 let mut sections = Vec::with_capacity(instances.len());
1342 for instance in &instances {
1343 let mut found: Vec<&BoardSection> = config
1344 .boards
1345 .iter()
1346 .filter(|section| section.id == instance.id)
1347 .collect();
1348 match found.len() {
1349 1 => sections.push(found.remove(0).clone()),
1350 0 => {
1351 return Err(format!(
1352 "board {:?} in diagram.json has no [[board]] entry; add `id = {:?}` to one",
1353 instance.id, instance.id
1354 ));
1355 }
1356 _ => {
1357 return Err(format!("[[board]] names {:?} more than once", instance.id));
1358 }
1359 }
1360 }
1361 if let Some(unknown) = config
1362 .boards
1363 .iter()
1364 .find(|section| !instances.iter().any(|instance| instance.id == section.id))
1365 {
1366 return Err(format!(
1367 "[[board]] id {:?} is not a development board in diagram.json",
1368 unknown.id
1369 ));
1370 }
1371 sections
1372 };
1373
1374 let mut boards = Vec::with_capacity(sections.len());
1375 for (section, instance) in sections.iter().zip(&instances) {
1376 boards.push(prepare_board(&config, dir, ®istry, instance, section)?);
1377 }
1378 Ok(Prepared {
1379 config,
1380 dir: dir.to_path_buf(),
1381 registry,
1382 circuit,
1383 boards,
1384 })
1385}
1386
1387fn prepare_board(
1389 config: &Config,
1390 dir: &Path,
1391 registry: &Registry,
1392 instance: &litz_diagram::PartInstance,
1393 section: &BoardSection,
1394) -> Result<BoardPlan, String> {
1395 let manifest = registry
1396 .get(&instance.type_key)
1397 .expect("the caller filtered on boards")
1398 .clone();
1399 let info = manifest
1400 .board
1401 .as_ref()
1402 .expect("the caller filtered on boards");
1403 let chip = info.chip.as_deref();
1404 if let Some(name) = chip
1407 && !is_builtin_chip(name)
1408 {
1409 return Err(format!(
1410 "board {:?}: chip {name:?} is not built in; name a wasm component under \
1411 [board.simulator] instead",
1412 instance.id
1413 ));
1414 }
1415
1416 let flash_size = section
1417 .flash_size
1418 .as_deref()
1419 .or(config.sim.flash_size.as_deref())
1420 .map(parse_size)
1421 .transpose()?
1422 .or_else(|| info.flash_size.as_deref().and_then(|s| parse_size(s).ok()))
1423 .unwrap_or(4 * 1024 * 1024);
1424
1425 let (firmware, layout) = match section.firmware.as_deref() {
1429 Some(rel) => {
1430 let path = dir.join(rel);
1431 let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1432 let layout = image::detect(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
1433 (bytes, layout)
1434 }
1435 None if info.simulator.is_some() => (Vec::new(), FirmwareLayout::Application),
1436 None => {
1437 return Err(format!(
1438 "board {:?} has no firmware; give it `firmware = \"...\"`",
1439 instance.id
1440 ));
1441 }
1442 };
1443
1444 let bootloader_rel = section
1445 .bootloader
1446 .as_deref()
1447 .or(config.sim.bootloader.as_deref());
1448 let ptable_rel = section
1449 .partition_table
1450 .as_deref()
1451 .or(config.sim.partition_table.as_deref());
1452 if layout == FirmwareLayout::Merged && (bootloader_rel.is_some() || ptable_rel.is_some()) {
1455 return Err(format!(
1456 "board {:?}: the firmware is a merged image (bootloader at 0x0, \
1457 partition table at 0x8000, application at 0x10000); remove \
1458 `bootloader` and `partition_table`",
1459 instance.id
1460 ));
1461 }
1462 let bootloader = read_optional(dir, bootloader_rel)?;
1463 let partition_table = read_optional(dir, ptable_rel)?;
1464
1465 let elf_rel = section.elf.as_deref().or(config.sim.elf.as_deref());
1466 let elf = match elf_rel {
1467 Some(rel) => {
1468 let path = dir.join(rel);
1469 Some(std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?)
1470 }
1471 None => None,
1472 };
1473
1474 let runtime = section.runtime.unwrap_or(config.sim.runtime);
1475 let script_rel = section.script.as_deref().or(config.sim.script.as_deref());
1476 let staged = if section.scripts.is_empty() {
1477 &config.sim.scripts
1478 } else {
1479 §ion.scripts
1480 };
1481 let scripts = match runtime {
1482 Runtime::Micropython | Runtime::CircuitPython => {
1483 let mut scripts = Vec::new();
1484 if let Some(rel) = script_rel {
1485 scripts.push(read_staged(dir, rel)?);
1486 }
1487 for spec in staged {
1488 let (name, rel) = match spec.split_once('=') {
1491 Some((name, path)) => (name.trim(), path.trim()),
1492 None => (spec.trim(), spec.trim()),
1493 };
1494 if scripts.iter().any(|script| script.name == name) {
1495 return Err(format!(
1496 "board {:?}: two scripts would be staged as {name:?}",
1497 instance.id
1498 ));
1499 }
1500 let mut script = read_staged(dir, rel)?;
1501 script.name = staged_name(name)?;
1502 scripts.push(script);
1503 }
1504 let total: usize = scripts.iter().map(|script| script.bytes.len()).sum();
1505 if total > MAX_SCRIPT {
1506 return Err(format!(
1507 "board {:?}: the staged scripts total {total} bytes; a Python raw \
1508 paste is limited to {MAX_SCRIPT} bytes",
1509 instance.id
1510 ));
1511 }
1512 if runtime == Runtime::CircuitPython {
1516 if let Some(entry) = scripts
1517 .iter()
1518 .position(|script| matches!(script.name.as_str(), "code.py" | "main.py"))
1519 {
1520 let entry = scripts.remove(entry);
1521 scripts.insert(0, entry);
1522 } else {
1523 return Err(format!(
1524 "board {:?}: CircuitPython needs code.py or main.py among its scripts",
1525 instance.id
1526 ));
1527 }
1528 }
1529 scripts
1530 }
1531 Runtime::Native => {
1532 if script_rel.is_some() || !staged.is_empty() {
1533 return Err(format!(
1534 "board {:?}: script/scripts need runtime = \"micropython\" or \
1535 \"circuitpython\"; a native firmware has no REPL to paste them into",
1536 instance.id
1537 ));
1538 }
1539 Vec::new()
1540 }
1541 };
1542
1543 let needs_rom = layout == FirmwareLayout::Merged || bootloader.is_some();
1547 let rom_rel = section.rom.as_deref().or(config.sim.rom.as_deref());
1548 let rom_path = rom_rel.map(PathBuf::from).or_else(|| {
1549 chip.and_then(rom_name)
1550 .and_then(|file| std::env::var_os("LITZ_ROM_DIR").map(|d| PathBuf::from(d).join(file)))
1551 });
1552 let rom = match rom_path {
1553 Some(path) => std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?,
1554 None if needs_rom => {
1555 return Err(format!(
1556 "board {:?}: {}; set `rom` in its [[board]] entry or in [sim], or LITZ_ROM_DIR",
1557 instance.id,
1558 if layout == FirmwareLayout::Merged {
1559 "a merged image runs from the mask ROM"
1560 } else {
1561 "a bootloader needs the mask ROM"
1562 }
1563 ));
1564 }
1565 None => Vec::new(),
1566 };
1567
1568 let python = crate::python::detect(runtime, section.firmware.as_deref().unwrap_or(""));
1571 let python = if python == crate::python::PythonRuntime::MicroPython {
1572 crate::python::detect_bytes(runtime, &firmware)
1573 } else {
1574 python
1575 };
1576 Ok(BoardPlan {
1577 id: instance.id.clone(),
1578 manifest,
1579 flash_size,
1580 rom,
1581 firmware,
1582 elf,
1583 layout,
1584 bootloader,
1585 partition_table,
1586 runtime,
1587 python,
1588 scripts,
1589 mac: parse_mac(section.mac.as_deref().or(config.sim.mac.as_deref())),
1590 })
1591}
1592
1593fn enforce_lock(prepared: &Prepared, update: bool) -> Result<(), String> {
1598 let (firmware, rom, bootloader, ptable) = if prepared.boards.len() == 1 {
1603 let plan = &prepared.boards[0];
1604 (
1605 Some(plan.firmware.clone()),
1606 (!plan.rom.is_empty()).then(|| plan.rom.clone()),
1607 plan.bootloader.clone(),
1608 plan.partition_table.clone(),
1609 )
1610 } else {
1611 let mut folded = Vec::new();
1612 for plan in &prepared.boards {
1613 folded.extend_from_slice(plan.id.as_bytes());
1614 folded.push(0);
1615 for image in [&plan.firmware, &plan.rom] {
1616 folded.extend_from_slice(&(image.len() as u64).to_le_bytes());
1617 folded.extend_from_slice(image);
1618 }
1619 }
1620 (Some(folded), None, None, None)
1621 };
1622 let flat =
1626 FlatBoard::build(&prepared.circuit, &prepared.registry).map_err(|e| e.to_string())?;
1627 let used: std::collections::BTreeSet<&str> = prepared
1630 .circuit
1631 .parts
1632 .iter()
1633 .map(|part| part.type_key.as_str())
1634 .chain(flat.parts.iter().map(|part| part.type_key.as_str()))
1635 .collect();
1636 let manifests: Vec<_> = prepared
1637 .registry
1638 .manifest_texts()
1639 .into_iter()
1640 .filter(|(key, _, _)| used.contains(key.as_str()))
1641 .collect();
1642 let actual = Lock::from_run(
1643 &manifests,
1644 firmware.as_deref(),
1645 rom.as_deref(),
1646 bootloader.as_deref(),
1647 ptable.as_deref(),
1648 );
1649 let path = prepared.dir.join("litz.lock");
1650 if update || !path.exists() {
1651 actual.write(&path)?;
1652 eprintln!("litz: wrote {}", path.display());
1653 return Ok(());
1654 }
1655 let installed = Lock::load(&path)?;
1656 installed.check(&actual)
1657}
1658
1659pub(crate) fn is_builtin_chip(chip: &str) -> bool {
1663 matches!(
1664 chip,
1665 "esp32"
1666 | "esp32c3"
1667 | "esp32c6"
1668 | "esp32s3"
1669 | "esp32p4"
1670 | "esp32s31"
1671 | "atmega328p"
1672 | "rp2040"
1673 )
1674}
1675
1676fn rom_name(chip: &str) -> Option<&'static str> {
1677 Some(match chip {
1678 "esp32" => "esp32_rev300_rom.elf",
1679 "esp32c3" => "esp32c3_rev3_rom.elf",
1680 "esp32c6" => "esp32c6_rev0_rom.elf",
1681 "esp32s3" => "esp32s3_rev0_rom.elf",
1682 "esp32p4" => "esp32p4_rev0_rom.elf",
1683 "esp32s31" => "esp32s31_rev0_rom.elf",
1684 _ => return None,
1685 })
1686}
1687
1688fn network_config(options: &Options, config: &Config) -> Result<Option<NetworkConfig>, String> {
1697 let spec = match (&options.wifi, &config.sim.wifi) {
1698 (Some(spec), _) => WifiSpec::Spec(spec.clone()),
1699 (None, Some(spec)) => spec.clone(),
1700 (None, None) => return Ok(None),
1701 };
1702
1703 let mut network = match &spec {
1704 WifiSpec::Spec(raw) => NetworkConfig {
1705 access_points: vec![access_point_from_spec(raw)?],
1706 ..NetworkConfig::default()
1707 },
1708 WifiSpec::Table(table) => {
1709 let mut network = NetworkConfig {
1710 access_points: vec![access_point(
1711 &table.ssid,
1712 table.psk.as_deref(),
1713 table.channel,
1714 table.bssid.as_deref().map(parse_bssid).transpose()?,
1715 table.epoch,
1716 )],
1717 nearby: table
1718 .nearby
1719 .iter()
1720 .map(|nearby| nearby_from_spec(nearby))
1721 .collect::<Result<Vec<_>, String>>()?,
1722 resolve_unknown: table.resolve_unknown,
1723 ..NetworkConfig::default()
1724 };
1725 for extra in &table.extra_aps {
1726 network.access_points.push(access_point(
1727 &extra.ssid,
1728 extra.psk.as_deref(),
1729 extra.channel,
1730 extra.bssid.as_deref().map(parse_bssid).transpose()?,
1731 extra.epoch,
1732 ));
1733 }
1734 for (name, address) in &table.names {
1735 let address: std::net::Ipv4Addr = address.parse().map_err(|_| {
1736 format!("[sim.wifi] names.{name}: {address:?} is not an IPv4 address")
1737 })?;
1738 network.names.insert(name.clone(), address.octets());
1739 }
1740 network
1741 }
1742 };
1743
1744 match &spec {
1745 WifiSpec::Spec(_) => {
1746 network = network.with_default_services();
1747 }
1748 WifiSpec::Table(table) if table.services.is_empty() => {
1749 if table.services_default {
1750 network = network.with_default_services();
1751 }
1752 }
1753 WifiSpec::Table(table) => {
1754 for service in &table.services {
1755 let inner = if service.mqtt {
1756 Service::mqtt(service.port)
1757 } else if service.websocket {
1758 Service::websocket(service.port)
1759 } else if service.echo {
1760 if service.udp {
1761 Service::UdpEcho { port: service.port }
1762 } else {
1763 Service::TcpEcho { port: service.port }
1764 }
1765 } else {
1766 let reply = service.reply.as_ref().ok_or_else(|| {
1767 format!(
1768 "[sim.wifi.service] port {}: give `reply = \"...\"`, `echo = true`, \
1769 `websocket = true` or `mqtt = true`",
1770 service.port
1771 )
1772 })?;
1773 Service::Tcp {
1774 port: service.port,
1775 reply: reply.as_bytes().to_vec(),
1776 after_request: service.wait,
1777 }
1778 };
1779 network = network.with_service(if service.tls {
1780 Service::tls(service.port, inner)
1781 } else {
1782 inner
1783 });
1784 }
1785 }
1786 }
1787 Ok(Some(network))
1788}
1789
1790fn access_point(
1791 ssid: &str,
1792 psk: Option<&str>,
1793 channel: Option<u8>,
1794 bssid: Option<[u8; 6]>,
1795 epoch: Option<u64>,
1796) -> AccessPoint {
1797 AccessPoint {
1798 ssid: ssid.to_string(),
1799 psk: psk.map(str::to_string),
1800 channel: channel.unwrap_or(6),
1801 bssid,
1802 epoch_s: epoch,
1803 }
1804}
1805
1806fn access_point_from_spec(spec: &str) -> Result<AccessPoint, String> {
1809 let mut ssid = None;
1810 let mut psk = None;
1811 let mut channel = None;
1812 let mut bssid = None;
1813 let mut epoch = None;
1814 for entry in spec.split(',').filter(|entry| !entry.is_empty()) {
1815 let (key, value) = entry
1816 .split_once('=')
1817 .ok_or_else(|| format!("invalid Wi-Fi option {entry:?}: expected key=value"))?;
1818 match key {
1819 "ssid" => ssid = Some(value.to_string()),
1820 "psk" | "password" | "pass" => psk = Some(value.to_string()),
1821 "channel" | "chan" | "ch" => {
1822 channel = Some(value.parse::<u8>().map_err(|_| {
1823 format!("invalid Wi-Fi channel {value:?}: expected 1 through 14")
1824 })?)
1825 }
1826 "bssid" => bssid = Some(parse_bssid(value)?),
1827 "epoch" => {
1828 epoch = Some(value.parse::<u64>().map_err(|_| {
1829 format!("invalid Wi-Fi epoch {value:?}: expected seconds since 1970")
1830 })?)
1831 }
1832 other => return Err(format!("unknown Wi-Fi option {other:?}")),
1833 }
1834 }
1835 let ssid = ssid.ok_or_else(|| format!("invalid Wi-Fi network {spec:?}: no ssid"))?;
1836 Ok(access_point(&ssid, psk.as_deref(), channel, bssid, epoch))
1837}
1838
1839fn nearby_from_spec(spec: &str) -> Result<NearbyNetwork, String> {
1840 let mut network = NearbyNetwork::new("");
1841 for entry in spec.split(',').filter(|entry| !entry.is_empty()) {
1842 let (key, value) = entry.split_once('=').ok_or_else(|| {
1843 format!("invalid nearby-network option {entry:?}: expected key=value")
1844 })?;
1845 match key {
1846 "ssid" => network.ssid = value.to_string(),
1847 "channel" | "chan" | "ch" => {
1848 network.channel = value.parse().map_err(|_| {
1849 format!("invalid nearby-network channel {value:?}: expected 1 through 14")
1850 })?
1851 }
1852 "rssi" => {
1853 network.rssi = value.parse().map_err(|_| {
1854 format!("invalid nearby-network rssi {value:?}: expected -128 through 127 dBm")
1855 })?
1856 }
1857 "secure" => {
1858 network.secure = match value {
1859 "1" | "true" | "yes" => true,
1860 "0" | "false" | "no" => false,
1861 _ => {
1862 return Err(format!(
1863 "invalid nearby-network secure {value:?}: expected 0 or 1"
1864 ));
1865 }
1866 }
1867 }
1868 other => return Err(format!("unknown nearby-network option {other:?}")),
1869 }
1870 }
1871 if network.ssid.is_empty() {
1872 return Err(format!("invalid nearby network {spec:?}: no ssid"));
1873 }
1874 Ok(network)
1875}
1876
1877fn parse_bssid(text: &str) -> Result<[u8; 6], String> {
1878 let octets: Vec<u8> = text
1879 .split(':')
1880 .map(|octet| {
1881 u8::from_str_radix(octet, 16)
1882 .map_err(|_| format!("invalid BSSID {text:?}: expected six hex octets"))
1883 })
1884 .collect::<Result<_, _>>()?;
1885 octets
1886 .try_into()
1887 .map_err(|_| format!("invalid BSSID {text:?}: expected six hex octets"))
1888}
1889
1890fn boot(prepared: &Prepared, options: &Options) -> Result<Booted, String> {
1898 let flat =
1899 FlatBoard::build(&prepared.circuit, &prepared.registry).map_err(|e| e.to_string())?;
1900 let parts: Vec<String> = flat.parts.iter().map(|p| p.id.clone()).collect();
1901 let mut board = Board::new(flat)
1902 .map_err(|e| e.to_string())?
1903 .with_analog(options.analog || prepared.config.sim.analog);
1904 for probe in &prepared.config.probes {
1908 let name = probe.name.as_deref().unwrap_or(probe.point.as_str());
1909 board.add_probe(name, &probe.point)?;
1910 }
1911 for spec in &options.probes {
1912 let (name, point) = match spec.split_once('=') {
1915 Some((name, point)) => (name.trim(), point.trim()),
1916 None => (spec.as_str(), spec.as_str()),
1917 };
1918 board.add_probe(name, point)?;
1919 }
1920 for spec in prepared.config.decodes.iter().chain(options.decodes.iter()) {
1924 crate::decode::check(spec, board.probes())?;
1925 }
1926 let mut network =
1930 network_config(options, &prepared.config)?.or_else(|| board.network().cloned());
1931 let capture = if options.pcap.is_some() {
1932 let Some(config) = network.as_mut() else {
1933 return Err(
1934 "--pcap needs a simulated network: add a `litz-wifi-router` part or [sim.wifi]"
1935 .into(),
1936 );
1937 };
1938 let capture = std::rc::Rc::new(std::cell::RefCell::new(litz_net::capture::Capture::new([
1939 10, 0, 2, 15,
1940 ])));
1941 config.capture = Some(std::rc::Rc::clone(&capture));
1942 Some(capture)
1943 } else {
1944 None
1945 };
1946 if let Some(config) = &network {
1947 board.set_network(config.clone());
1948 }
1949 let bluetooth = board.bluetooth().cloned();
1950 let shared = std::rc::Rc::new(std::cell::RefCell::new(board));
1951
1952 let mut chips = Vec::with_capacity(prepared.boards.len());
1953 for (index, plan) in prepared.boards.iter().enumerate() {
1954 let chip = build_chip(
1955 prepared,
1956 plan,
1957 std::rc::Rc::clone(&shared),
1958 index as u16,
1959 network.as_ref(),
1960 bluetooth.as_ref(),
1961 )?;
1962 chips.push(boot_chip(chip, plan)?);
1963 }
1964
1965 if let Some(path) = &options.pcap_air
1968 && let Some(chip) = chips.first_mut()
1969 {
1970 chip.start_air_capture(path)?;
1971 }
1972 if let Some(path) = &options.pcap_eth
1973 && let Some(chip) = chips.first_mut()
1974 {
1975 chip.start_ethernet_capture(path)?;
1976 }
1977 if options.host_network || !options.host_forwards.is_empty() {
1978 let chip = chips
1979 .first_mut()
1980 .ok_or_else(|| "--net needs a board".to_string())?;
1981 chip.attach_host_gateway(&options.host_forwards)?;
1982 }
1983
1984 if let Some(request) = &options.gdb {
1989 let index = match &request.board {
1990 Some(id) => find_board(&prepared.boards, id, "--gdb")?,
1991 None => chips
1992 .iter_mut()
1993 .position(|chip| chip.debug().is_some())
1994 .ok_or_else(|| {
1995 "--gdb needs a backend with a GDB target; a wasm MCU and the AVR core have none"
1996 .to_string()
1997 })?,
1998 };
1999 let plan = &prepared.boards[index];
2000 let chip = &mut chips[index];
2001 let debug = chip.debug().ok_or_else(|| {
2002 format!(
2003 "--gdb: board {:?} has no GDB target; a wasm MCU and the AVR core have none",
2004 plan.id
2005 )
2006 })?;
2007 eprintln!("litz: gdb serves board {:?}", plan.id);
2008 debug.serve(request.port)?;
2009 }
2010 Ok(Booted {
2011 fleet: Fleet::new(chips),
2012 parts,
2013 board: shared,
2014 capture,
2015 })
2016}
2017
2018struct Booted {
2022 fleet: Fleet,
2023 parts: Vec<String>,
2024 board: std::rc::Rc<std::cell::RefCell<Board>>,
2025 capture: Option<std::rc::Rc<std::cell::RefCell<litz_net::capture::Capture>>>,
2027}
2028
2029fn find_board(boards: &[BoardPlan], id: &str, flag: &str) -> Result<usize, String> {
2032 boards.iter().position(|plan| plan.id == id).ok_or_else(|| {
2033 format!(
2034 "{flag} names board {id:?}; diagram.json has {}",
2035 boards
2036 .iter()
2037 .map(|plan| plan.id.as_str())
2038 .collect::<Vec<_>>()
2039 .join(", ")
2040 )
2041 })
2042}
2043
2044fn touch_board(
2048 prepared: &Prepared,
2049 board: &Option<String>,
2050 part: &Option<String>,
2051 flag: &str,
2052) -> Result<Option<usize>, String> {
2053 if let Some(id) = board {
2054 return find_board(&prepared.boards, id, flag).map(Some);
2055 }
2056 if let Some(part) = part
2057 && let Some(index) = prepared.boards.iter().position(|plan| plan.id == *part)
2058 {
2059 return Ok(Some(index));
2060 }
2061 Ok(None)
2062}
2063
2064fn build_chip(
2066 prepared: &Prepared,
2067 plan: &BoardPlan,
2068 board: std::rc::Rc<std::cell::RefCell<Board>>,
2069 index: u16,
2070 network: Option<&NetworkConfig>,
2071 bluetooth: Option<&litz_ble::BleConfig>,
2072) -> Result<Box<dyn Chip>, String> {
2073 let info = plan
2074 .manifest
2075 .board
2076 .as_ref()
2077 .expect("prepare checked it is a board");
2078 #[cfg(not(target_family = "wasm"))]
2079 if let Some(simulator) = &info.simulator {
2080 let module = module_bytes(prepared, &plan.manifest, &simulator.module)?;
2081 return Ok(Box::new(
2082 WasmChip::from_bytes_with_abi(&module, &simulator.module, &simulator.abi)?
2083 .with_shared_board(board, index),
2084 ));
2085 }
2086 #[cfg(target_family = "wasm")]
2087 if info.simulator.is_some() {
2088 let _ = prepared;
2089 return Err(
2090 "a wasm guest chip cannot run inside the browser build; only the builtin chips \
2091 are compiled there"
2092 .into(),
2093 );
2094 }
2095 let name = info.chip.as_deref().unwrap_or("esp32c3");
2096 let mut chip = builtin_chip(
2097 name,
2098 plan.mac,
2099 plan.flash_size,
2100 board,
2101 index,
2102 Attachments {
2103 network,
2104 bluetooth,
2105 elf: plan.elf.as_deref(),
2106 ble_controller: plan.python == crate::python::PythonRuntime::CircuitPython,
2107 },
2108 )?;
2109 if info.psram {
2112 chip.set_psram_size(4 << 20)?;
2113 }
2114 Ok(chip)
2115}
2116
2117fn boot_chip(mut mcu: Box<dyn Chip>, plan: &BoardPlan) -> Result<Box<dyn Chip>, String> {
2119 if !plan.rom.is_empty() {
2120 mcu.load_image(ImageKind::Rom, 0, &plan.rom)?;
2121 }
2122 if plan.firmware.is_empty() && plan.bootloader.is_none() {
2123 mcu.boot()?;
2125 return Ok(mcu);
2126 }
2127 let flash = mcu.info().flash;
2128 match plan.layout {
2129 FirmwareLayout::Merged => {
2134 mcu.load_image(ImageKind::Bootloader, flash.bootloader, &plan.firmware)?;
2135 }
2136 FirmwareLayout::Application => match (&plan.bootloader, &plan.partition_table) {
2137 (Some(bootloader), Some(ptable)) => {
2138 mcu.load_image(ImageKind::Bootloader, flash.bootloader, bootloader)?;
2139 mcu.load_image(ImageKind::PartitionTable, flash.partition_table, ptable)?;
2140 mcu.load_image(ImageKind::Firmware, flash.app, &plan.firmware)?;
2141 }
2142 (None, None) => {
2143 mcu.load_image(ImageKind::Firmware, flash.app, &plan.firmware)?;
2144 }
2145 _ => {
2148 return Err(format!(
2149 "board {:?}: bootloader and partition_table go together; give both or neither",
2150 plan.id
2151 ));
2152 }
2153 },
2154 }
2155 mcu.boot()?;
2156 Ok(mcu)
2157}
2158
2159struct Fleet {
2167 chips: Vec<Box<dyn Chip>>,
2168 console: Vec<String>,
2171 read: Vec<usize>,
2173 stops: Vec<Stop>,
2176}
2177
2178impl Fleet {
2179 fn new(chips: Vec<Box<dyn Chip>>) -> Self {
2180 let count = chips.len();
2181 Self {
2182 chips,
2183 console: vec![String::new(); count],
2184 read: vec![0; count],
2185 stops: vec![Stop::Budget; count],
2186 }
2187 }
2188
2189 fn run(&mut self, steps: u64) -> litz_board::chip::RunResult {
2193 let mut cycles = 0;
2194 let mut stop = Stop::Budget;
2195 for (index, chip) in self.chips.iter_mut().enumerate() {
2196 let result = chip.run(steps);
2197 cycles = cycles.max(result.cycles);
2198 self.stops[index] = result.stop;
2199 let chunk = chip.take_console();
2200 if !chunk.is_empty() {
2201 self.console[index].push_str(&String::from_utf8_lossy(&chunk));
2202 }
2203 if stop_rank(result.stop) > stop_rank(stop) {
2204 stop = result.stop;
2205 }
2206 }
2207 litz_board::chip::RunResult { cycles, stop }
2208 }
2209
2210 fn run_one(&mut self, index: usize, steps: u64) {
2213 let result = self.chips[index].run(steps);
2214 self.stops[index] = result.stop;
2215 let chunk = self.chips[index].take_console();
2216 if !chunk.is_empty() {
2217 self.console[index].push_str(&String::from_utf8_lossy(&chunk));
2218 }
2219 }
2220
2221 fn touch(&mut self, board: Option<usize>, x: u16, y: u16, down: bool) -> Result<(), String> {
2224 let index = board.unwrap_or(0);
2225 match self.chips.get_mut(index) {
2226 Some(chip) => chip.touch(x, y, down),
2227 None => Err(format!("the diagram has no board {index}")),
2228 }
2229 }
2230
2231 fn sample_heap(&mut self) -> Result<u32, String> {
2233 match self.chips.first_mut() {
2234 Some(chip) => chip.sample_heap(),
2235 None => Err("the diagram has no chip to sample".into()),
2236 }
2237 }
2238
2239 fn take_console(&mut self) -> Vec<u8> {
2240 let mut out = Vec::new();
2241 for (index, text) in self.console.iter().enumerate() {
2242 if self.read[index] < text.len() {
2243 out.extend_from_slice(&text.as_bytes()[self.read[index]..]);
2244 self.read[index] = text.len();
2245 }
2246 }
2247 out
2248 }
2249
2250 fn console_text(&self, index: usize) -> &str {
2252 &self.console[index]
2253 }
2254
2255 fn write_console_to(&mut self, index: usize, bytes: &[u8]) {
2256 self.chips[index].write_console(bytes);
2257 }
2258
2259 fn finished(&self) -> bool {
2265 self.stops
2266 .iter()
2267 .all(|stop| matches!(stop, Stop::Halted | Stop::Reset | Stop::Trap))
2268 }
2269
2270 fn frontier_ns(&self) -> u64 {
2271 let mut frontier: Option<u64> = None;
2272 let mut latest = 0;
2273 for (index, chip) in self.chips.iter().enumerate() {
2274 let now = (chip.seconds() * 1e9) as u64;
2275 latest = latest.max(now);
2276 if matches!(self.stops[index], Stop::Halted | Stop::Reset | Stop::Trap) {
2277 continue;
2278 }
2279 frontier = Some(frontier.map_or(now, |front| front.min(now)));
2280 }
2281 frontier.unwrap_or(latest)
2282 }
2283
2284 fn seconds(&self) -> f64 {
2285 self.chips
2286 .iter()
2287 .map(|chip| chip.seconds())
2288 .fold(0.0, f64::max)
2289 }
2290
2291 fn schedule(&mut self, board: usize, inputs: Vec<Input>) -> Result<(), String> {
2294 match self.chips.get_mut(board) {
2295 Some(chip) => chip.schedule(inputs),
2296 None => Err(format!("there is no board {board} to schedule input on")),
2297 }
2298 }
2299
2300 fn state(&self, part: &str) -> Option<PartState> {
2301 self.chips.first()?.state(part)
2302 }
2303
2304 fn press(&mut self, part: &str, pressed: bool) -> bool {
2305 self.chips
2306 .first_mut()
2307 .is_some_and(|chip| chip.press(part, pressed))
2308 }
2309
2310 fn set_control(&mut self, part: &str, value: u16) -> bool {
2311 self.chips
2312 .first_mut()
2313 .is_some_and(|chip| chip.set_control(part, value))
2314 }
2315
2316 fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2317 self.chips
2318 .first_mut()
2319 .is_some_and(|chip| chip.set_named_control(part, name, value))
2320 }
2321
2322 fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2323 self.chips.first()?.part_pin_level(part, pin)
2324 }
2325
2326 fn gpio_level(&self, board: usize, gpio: u8) -> Option<Level> {
2327 self.chips.get(board)?.gpio_level(gpio)
2328 }
2329
2330 fn conflicts(&self) -> Vec<litz_board::Conflict> {
2331 self.chips
2332 .first()
2333 .map(|chip| chip.conflicts())
2334 .unwrap_or_default()
2335 }
2336
2337 fn fault(&self) -> Option<String> {
2338 self.chips.iter().find_map(|chip| chip.fault())
2339 }
2340
2341 fn write_console_on(&mut self, board: usize, bytes: &[u8]) {
2344 if let Some(chip) = self.chips.get_mut(board) {
2345 chip.write_console(bytes);
2346 }
2347 }
2348
2349 fn save_display(&mut self, board: Option<usize>, path: &Path) -> Result<(), String> {
2354 let Some(board) = board else {
2355 let mut refusal = None;
2356 for chip in &mut self.chips {
2357 match chip.save_display(path) {
2358 Ok(()) => return Ok(()),
2359 Err(e) => refusal.get_or_insert(e),
2360 };
2361 }
2362 return Err(refusal.unwrap_or_else(|| "the diagram has no chip to capture".into()));
2363 };
2364 match self.chips.get_mut(board) {
2365 Some(chip) => chip.save_display(path),
2366 None => Err(format!("there is no board {board} to capture")),
2367 }
2368 }
2369
2370 fn save_part_display(&mut self, part: &str, path: &Path) -> Result<(), String> {
2373 let mut refusal = None;
2374 for chip in &mut self.chips {
2375 match chip.save_part_display(part, path) {
2376 Ok(()) => return Ok(()),
2377 Err(error) => refusal.get_or_insert(error),
2378 };
2379 }
2380 Err(refusal.unwrap_or_else(|| format!("no part {part:?} has a framebuffer")))
2381 }
2382
2383 fn report(&mut self) -> Vec<String> {
2384 self.chips
2385 .iter_mut()
2386 .flat_map(|chip| chip.report())
2387 .collect()
2388 }
2389
2390 fn enable_coverage(&mut self) {
2391 for chip in &mut self.chips {
2392 chip.enable_coverage();
2393 }
2394 }
2395
2396 fn start_trace(&mut self) {
2397 if let Some(chip) = self.chips.first_mut() {
2398 chip.start_trace();
2399 }
2400 }
2401
2402 fn break_at(&mut self, pc: u32) {
2403 for chip in &mut self.chips {
2404 chip.break_at(pc);
2405 }
2406 }
2407
2408 fn vcd(&self) -> String {
2409 self.chips
2410 .first()
2411 .map(|chip| chip.vcd())
2412 .unwrap_or_default()
2413 }
2414}
2415
2416fn stop_rank(stop: Stop) -> u8 {
2418 match stop {
2419 Stop::Trap => 5,
2420 Stop::Breakpoint(_) => 4,
2421 Stop::Reset => 3,
2422 Stop::Halted => 2,
2423 Stop::Idle => 1,
2424 Stop::Budget => 0,
2425 }
2426}
2427
2428#[cfg(not(target_family = "wasm"))]
2431fn module_bytes(
2432 prepared: &Prepared,
2433 manifest: &litz_catalog::PartManifest,
2434 module: &str,
2435) -> Result<Vec<u8>, String> {
2436 if let Some(bytes) = prepared.registry.builtin_module(&manifest.id) {
2437 return Ok(bytes.to_vec());
2438 }
2439 let base = manifest
2440 .source
2441 .as_deref()
2442 .and_then(|path| path.parent())
2443 .ok_or_else(|| {
2444 format!(
2445 "board {:?} names a module but has no directory",
2446 manifest.id
2447 )
2448 })?;
2449 let path = base.join(module);
2450 std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
2451}
2452
2453fn run_once(
2454 prepared: &Prepared,
2455 spec: Option<&TestSpec>,
2456 _strict: bool,
2457 options: &Options,
2458) -> Result<Outcome, String> {
2459 let data = run_inner(prepared, spec, spec.is_none(), false, None, options)?;
2460 Ok(Outcome {
2461 exit_code: data.exit_code,
2462 output: data.output,
2463 sim_ms: data.sim_ms,
2464 tests: Vec::new(),
2465 })
2466}
2467
2468fn run_capture(
2469 prepared: &Prepared,
2470 timeout: Option<&str>,
2471 options: &Options,
2472) -> Result<CaptureOutcome, String> {
2473 let data = run_inner(prepared, None, false, true, timeout, options)?;
2474 Ok(CaptureOutcome {
2475 exit_code: data.exit_code,
2476 output: data.output,
2477 sim_ms: data.sim_ms,
2478 part_states: data.part_states,
2479 faults: data.faults,
2480 })
2481}
2482
2483struct RunData {
2485 exit_code: i32,
2486 output: String,
2487 sim_ms: u32,
2488 part_states: BTreeMap<String, PartState>,
2489 faults: Vec<String>,
2490}
2491
2492fn run_inner(
2493 prepared: &Prepared,
2494 spec: Option<&TestSpec>,
2495 stream: bool,
2496 capture_states: bool,
2497 timeout_override: Option<&str>,
2498 options: &Options,
2499) -> Result<RunData, String> {
2500 let Booted {
2501 fleet: mut mcu,
2502 parts,
2503 board,
2504 capture,
2505 } = boot(prepared, options)?;
2506 start_recording(&mut mcu, options, prepared);
2507 if options.coverage {
2508 mcu.enable_coverage();
2509 }
2510 let console_board = match options
2514 .interactive
2515 .as_ref()
2516 .and_then(|i| i.board.as_deref())
2517 {
2518 Some(id) => find_board(&prepared.boards, id, "--interactive")?,
2519 None => 0,
2520 };
2521 let capture_board = match options
2522 .screenshot
2523 .as_ref()
2524 .and_then(|capture| capture.board.as_deref())
2525 {
2526 Some(id) => Some(find_board(&prepared.boards, id, "--screenshot")?),
2527 None => None,
2528 };
2529 let presses = spec.map(|s| press_schedule(s, &parts)).unwrap_or_default();
2533
2534 let inputs = spec
2535 .map(|s| inputs_for(s, &parts, &prepared.boards))
2536 .transpose()?
2537 .unwrap_or_default();
2538 for (board, inputs) in inputs {
2539 mcu.schedule(board, inputs)?;
2540 }
2541
2542 let timeout = match timeout_override {
2543 Some(text) => parse_duration(text)?,
2544 None => spec
2545 .and_then(|s| s.timeout.as_deref())
2546 .map(parse_duration)
2547 .transpose()?
2548 .unwrap_or_else(|| parse_duration(DEFAULT_TIMEOUT).expect("default timeout")),
2549 };
2550 let expects = spec
2551 .map(|s| consoled(s.expect(), &prepared.boards))
2552 .unwrap_or_default();
2553 let fails = spec
2554 .map(|s| consoled(s.fail(), &prepared.boards))
2555 .unwrap_or_default();
2556 let mut states: Vec<Wanted> = spec
2557 .map(TestSpec::expect_state)
2558 .unwrap_or_default()
2559 .into_iter()
2560 .map(wanted)
2561 .collect::<Result<_, _>>()?;
2562 let state_at = spec
2563 .and_then(|s| s.state_at.as_deref())
2564 .map(parse_duration)
2565 .transpose()?;
2566 let state_stays = spec
2567 .and_then(|s| s.state_stays.as_deref())
2568 .map(parse_duration)
2569 .transpose()?;
2570 for want in &mut states {
2571 want.at = state_at;
2572 want.stays = state_stays;
2573 if mcu.state(&want.part).is_none() {
2574 let known: Vec<&str> = diagram_part_ids(prepared).collect();
2575 return Err(format!(
2576 "no part named {:?} in diagram.json ({}); a part inside a board is \
2577 reached as <board>/<id>",
2578 want.part,
2579 known.join(", ")
2580 ));
2581 }
2582 }
2583
2584 let mut heap = HeapLog::from_options(
2585 options,
2586 prepared
2587 .boards
2588 .first()
2589 .map(|plan| plan.id.clone())
2590 .unwrap_or_else(|| "esp".into()),
2591 )?;
2592 for (index, plan) in prepared.boards.iter().enumerate() {
2595 if pastes_script(plan) && !plan.python.interrupt_sequence().is_empty() {
2596 mcu.write_console_on(index, plan.python.interrupt_sequence());
2597 }
2598 }
2599 let mut serial = String::new();
2600 let mut timed_out = false;
2601 let mut due = 0;
2602 let mut saw_fail = None;
2603 let (stdin_tx, stdin_rx) = std::sync::mpsc::channel::<Vec<u8>>();
2608 if options.interactive.is_some() {
2609 std::thread::spawn(move || {
2610 use std::io::BufRead;
2611 let stdin = std::io::stdin();
2612 let mut lock = stdin.lock();
2613 let mut line = String::new();
2614 loop {
2615 line.clear();
2616 match lock.read_line(&mut line) {
2617 Ok(0) | Err(_) => break,
2618 Ok(_) if stdin_tx.send(line.as_bytes().to_vec()).is_err() => break,
2619 Ok(_) => {}
2620 }
2621 }
2622 });
2623 }
2624 let mut saw_trap: Option<String> = None;
2625 let mut pasted: Vec<bool> = prepared
2629 .boards
2630 .iter()
2631 .map(|plan| !pastes_script(plan))
2632 .collect();
2633 let mut pasted_at = vec![0u64; prepared.boards.len()];
2634 let mut nudged_at = vec![0u64; prepared.boards.len()];
2639 loop {
2640 if !mcu.conflicts().is_empty() {
2644 break;
2645 }
2646 let now_ns = mcu.frontier_ns();
2650 while due < presses.len() && presses[due].0 <= now_ns {
2651 let (_, part, pressed) = &presses[due];
2652 mcu.press(part, *pressed);
2653 due += 1;
2654 }
2655 while let Ok(bytes) = stdin_rx.try_recv() {
2656 mcu.write_console_on(console_board, &bytes);
2657 }
2658 let step = mcu.run(1_000_000);
2659 if step.stop == Stop::Trap {
2664 saw_trap = Some(mcu.fault().unwrap_or_else(|| "the core trapped".into()));
2665 break;
2666 }
2667 let chunk = mcu.take_console();
2668 if !chunk.is_empty() {
2669 let text = String::from_utf8_lossy(&chunk);
2670 if stream {
2671 print!("{text}");
2672 let _ = std::io::stdout().flush();
2673 }
2674 serial.push_str(&text);
2675 }
2676 if !mcu.conflicts().is_empty() {
2677 break;
2678 }
2679 if let Some(log) = &mut heap {
2680 let now = mcu.frontier_ns();
2681 log.sample(&mut mcu, now);
2682 if log.failed() {
2683 break;
2684 }
2685 }
2686 if mcu.finished() {
2687 break;
2688 }
2689 if let Some(hit) = fails.iter().find(|f| seen(&mcu, &serial, f)) {
2690 saw_fail = Some(hit.clone());
2691 break;
2692 }
2693 let now = mcu.frontier_ns();
2696 for (index, plan) in prepared.boards.iter().enumerate() {
2697 if pasted[index] {
2698 continue;
2699 }
2700 if mcu.console_text(index).contains(REPL_PROMPT) {
2701 paste_script(&mut mcu, index, &plan.scripts, plan.python);
2702 pasted[index] = true;
2703 pasted_at[index] = now;
2704 } else if plan.python == crate::python::PythonRuntime::CircuitPython
2705 && !mcu.console_text(index).is_empty()
2706 && now.saturating_sub(nudged_at[index]) >= CIRCUITPYTHON_NUDGE
2707 {
2708 mcu.write_console_on(index, plan.python.interrupt_sequence());
2711 nudged_at[index] = now;
2712 } else if now >= timeout {
2713 return Err(format!(
2714 "board {:?}: MicroPython REPL prompt never appeared within {timeout} ns of \
2715 simulated time; check that its firmware is a MicroPython or CircuitPython build",
2716 plan.id
2717 ));
2718 }
2719 }
2720 for want in &mut states {
2721 if let Some(actual) = mcu.state(&want.part) {
2722 observe(want, actual, now);
2723 }
2724 }
2725 let paste_settled = prepared.boards.iter().enumerate().all(|(index, plan)| {
2726 !pastes_script(plan)
2727 || (pasted[index] && now >= pasted_at[index].saturating_add(PASTE_GRACE_NS))
2728 });
2729 let satisfied = pasted.iter().all(|pasted| *pasted)
2730 && paste_settled
2731 && expects.iter().all(|e| seen(&mcu, &serial, e))
2732 && states.iter().all(|w| w.seen);
2733 if satisfied && (!expects.is_empty() || !states.is_empty()) {
2734 timed_out = false;
2735 break;
2736 }
2737 if mcu.frontier_ns() >= timeout {
2738 timed_out = true;
2739 break;
2740 }
2741 }
2742
2743 let conflicts = mcu.conflicts();
2744 let missing: Vec<&Consoled> = expects.iter().filter(|e| !seen(&mcu, &serial, e)).collect();
2745 let missing_states: Vec<&Wanted> = states.iter().filter(|w| !w.seen).collect();
2746 let passed = conflicts.is_empty()
2747 && saw_fail.is_none()
2748 && saw_trap.is_none()
2749 && missing.is_empty()
2750 && missing_states.is_empty();
2751
2752 let mut notes = Vec::new();
2753 for conflict in &conflicts {
2754 notes.push(format!(
2755 "electrical fault on net {}: {}",
2756 conflict.net, conflict.detail
2757 ));
2758 }
2759 if let Some(hit) = &saw_fail {
2760 let text = hit.text;
2761 match hit.board.and_then(|index| prepared.boards.get(index)) {
2762 Some(plan) => notes.push(format!(
2763 "found failure text {text:?} on board {:?}",
2764 plan.id
2765 )),
2766 None => notes.push(format!("found failure text {text:?}")),
2767 }
2768 }
2769 if let Some(detail) = &saw_trap {
2770 notes.push(format!("the core trapped: {detail}"));
2771 }
2772 for miss in &missing {
2773 match miss.board.and_then(|index| prepared.boards.get(index)) {
2774 Some(plan) => notes.push(format!("never saw {:?} on board {:?}", miss.text, plan.id)),
2775 None => notes.push(format!("never saw {:?}", miss.text)),
2776 }
2777 }
2778 for want in missing_states {
2779 if want.broken {
2780 let stays = want.stays.map(seconds).unwrap_or_default();
2781 notes.push(format!(
2782 "{} {} did not hold for {stays}",
2783 want.part, want.state
2784 ));
2785 } else if let Some(at) = want.at {
2786 notes.push(format!(
2787 "{} was not {} at {}",
2788 want.part,
2789 want.state,
2790 seconds(at)
2791 ));
2792 } else {
2793 notes.push(format!("never saw {} {}", want.part, want.state));
2794 }
2795 }
2796 if timed_out && spec.is_some() {
2797 notes.push(format!("timed out after {timeout} ns of simulated time"));
2798 }
2799
2800 let mut exit_code = if spec.is_none() {
2801 if !conflicts.is_empty() || saw_trap.is_some() {
2802 1
2803 } else if !timed_out && mcu.finished() {
2804 0
2807 } else {
2808 EXIT_TIMEOUT
2809 }
2810 } else if passed {
2811 0
2812 } else {
2813 1
2814 };
2815
2816 let mut part_states = BTreeMap::new();
2817 if capture_states {
2818 for part in &parts {
2819 if let Some(state) = mcu.state(part)
2820 && state != PartState::None
2821 {
2822 part_states.insert(part.clone(), state);
2823 }
2824 }
2825 }
2826 let faults: Vec<String> = conflicts
2827 .iter()
2828 .map(|conflict| format!("net {}: {}", conflict.net, conflict.detail))
2829 .collect();
2830
2831 let mut output = if stream { String::new() } else { serial };
2832 if !output.ends_with('\n') && !output.is_empty() {
2833 output.push('\n');
2834 }
2835 for note in notes {
2836 output.push_str(&format!("litz: {note}\n"));
2837 }
2838 for line in probe_report(&board) {
2839 output.push_str(&format!("litz: {line}\n"));
2840 }
2841 for line in decode_report(&board, prepared, options)? {
2842 output.push_str(&format!("litz: {line}\n"));
2843 }
2844 for line in mcu.report() {
2847 output.push_str(&line);
2848 if !line.ends_with('\n') {
2849 output.push('\n');
2850 }
2851 }
2852 let sim_ms = (mcu.seconds() * 1000.0) as u32;
2853 finish_recording(&mcu, &board, options, capture.as_ref())?;
2854 if let Some(capture) = &options.screenshot
2859 && (spec.is_none() || exit_code != 0)
2860 && let Err(e) = mcu.save_display(capture_board, &capture.path)
2861 {
2862 eprintln!("litz: {e}");
2863 }
2864 if let Some(log) = heap {
2865 let end = mcu.frontier_ns();
2866 let (lines, failure) = log.finish(&mut mcu, end);
2867 for line in lines {
2868 output.push_str(&format!("litz: {line}\n"));
2869 }
2870 if let Some(failure) = failure {
2871 exit_code = 1;
2872 output.push_str(&format!("litz: heap: {failure}\n"));
2873 }
2874 }
2875 Ok(RunData {
2876 exit_code,
2877 output,
2878 sim_ms,
2879 part_states,
2880 faults,
2881 })
2882}
2883
2884fn read_optional(dir: &Path, rel: Option<&str>) -> Result<Option<Vec<u8>>, String> {
2886 rel.map(|rel| {
2887 let path = dir.join(rel);
2888 std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
2889 })
2890 .transpose()
2891}
2892
2893struct Wanted {
2900 part: String,
2901 state: String,
2902 seen: bool,
2903 at: Option<u64>,
2905 stays: Option<u64>,
2907 sampled: bool,
2909 started: bool,
2911 since: u64,
2913 broken: bool,
2915}
2916
2917fn wanted(text: &str) -> Result<Wanted, String> {
2919 let (part, state) = text
2920 .split_once(':')
2921 .ok_or_else(|| format!("{text:?} is not <part>:<state>"))?;
2922 let known = matches!(state, "on" | "off" | "down" | "pressed" | "up" | "released")
2923 || state.parse::<u16>().is_ok()
2924 || state
2925 .strip_prefix("0x")
2926 .is_some_and(|hex| u8::from_str_radix(hex, 16).is_ok());
2927 if !known {
2928 return Err(format!(
2929 "{state:?} is not a state; write on, off, down, up, a servo angle in degrees, \
2930 or a segment mask as 0x7f"
2931 ));
2932 }
2933 Ok(Wanted {
2934 part: part.to_string(),
2935 state: state.to_string(),
2936 seen: false,
2937 at: None,
2938 stays: None,
2939 sampled: false,
2940 started: false,
2941 since: 0,
2942 broken: false,
2943 })
2944}
2945
2946fn observe(want: &mut Wanted, actual: PartState, now: u64) {
2954 let matches = state_matches(actual, &want.state);
2955 match (want.at, want.stays) {
2956 (None, None) => {
2957 if matches {
2958 want.seen = true;
2959 }
2960 }
2961 (Some(at), None) => {
2962 if !want.sampled && now >= at {
2963 want.sampled = true;
2964 want.seen = matches;
2965 }
2966 }
2967 (None, Some(stays)) => {
2968 if want.broken || want.seen {
2969 return;
2970 }
2971 if matches {
2972 if !want.started {
2973 want.started = true;
2974 want.since = now;
2975 }
2976 if now.saturating_sub(want.since) >= stays {
2977 want.seen = true;
2978 }
2979 } else if want.started {
2980 want.broken = true;
2981 }
2982 }
2983 (Some(at), Some(stays)) => {
2984 if want.broken || want.seen || now < at {
2985 return;
2986 }
2987 if !want.started {
2988 want.started = true;
2989 want.since = now;
2990 }
2991 if !matches {
2992 want.broken = true;
2993 } else if now.saturating_sub(want.since) >= stays {
2994 want.seen = true;
2995 }
2996 }
2997 }
2998}
2999
3000fn seconds(ns: u64) -> String {
3002 format!("{}s", ns as f64 / 1e9)
3003}
3004
3005fn state_matches(actual: PartState, want: &str) -> bool {
3007 match want {
3008 "on" => matches!(
3009 actual,
3010 PartState::Led { lit: true }
3011 | PartState::Switch { on: true }
3012 | PartState::Tone { sounding: true, .. }
3013 ),
3014 "off" => matches!(
3015 actual,
3016 PartState::Led { lit: false }
3017 | PartState::Switch { on: false }
3018 | PartState::Tone {
3019 sounding: false,
3020 ..
3021 }
3022 ),
3023 "down" | "pressed" => actual == PartState::Button { pressed: true },
3024 "up" | "released" => actual == PartState::Button { pressed: false },
3025 digits => {
3026 if let Some(hex) = digits.strip_prefix("0x") {
3027 let Ok(mask) = u8::from_str_radix(hex, 16) else {
3028 return false;
3029 };
3030 return actual == PartState::Segments { mask };
3031 }
3032 match (digits.parse::<u16>(), actual) {
3033 (Ok(degrees), PartState::Servo { degrees: actual }) => degrees == actual,
3034 (Ok(percent), PartState::Knob { permille }) => percent * 10 == permille,
3037 _ => false,
3038 }
3039 }
3040 }
3041}
3042
3043fn diagram_part_ids(prepared: &Prepared) -> impl Iterator<Item = &str> {
3044 prepared.circuit.parts.iter().map(|p| p.id.as_str())
3045}
3046
3047fn press_schedule(spec: &TestSpec, parts: &[String]) -> Vec<(u64, String, bool)> {
3049 let mut presses: Vec<(u64, String, bool)> = Vec::new();
3050 for input in &spec.input {
3051 let Some(pin) = &input.pin else { continue };
3052 if !parts.iter().any(|id| id == pin) {
3053 continue;
3054 }
3055 let Ok(at) = parse_duration(&input.at) else {
3056 continue;
3057 };
3058 presses.push((at, pin.clone(), input.level.unwrap_or(1) == 0));
3061 }
3062 presses.sort_by_key(|(at, _, _)| *at);
3063 presses
3064}
3065
3066fn inputs_for(
3073 spec: &TestSpec,
3074 parts: &[String],
3075 boards: &[BoardPlan],
3076) -> Result<Vec<(usize, Vec<Input>)>, String> {
3077 let mut by_board: BTreeMap<usize, Vec<Input>> = BTreeMap::new();
3078 for input in &spec.input {
3079 let at_ns = parse_duration(&input.at)?;
3080 let board = input_board(spec, input, boards)?;
3081 if let Some(serial) = &input.serial {
3082 if serial.contains('\n') {
3083 return Err(format!(
3084 "test {:?}: serial input must be one line",
3085 spec.name
3086 ));
3087 }
3088 by_board.entry(board).or_default().push(Input::Uart {
3089 at_ns,
3090 bytes: format!("{serial}\n").into_bytes(),
3091 });
3092 }
3093 if let Some(pin) = &input.pin {
3094 if parts.iter().any(|id| id == pin) {
3095 continue;
3096 }
3097 let Ok(number) = pin.parse::<u8>() else {
3098 return Err(format!(
3099 "test {:?}: {pin:?} is neither a part in the diagram nor a GPIO number",
3100 spec.name
3101 ));
3102 };
3103 let level = if input.level.unwrap_or(1) == 0 {
3104 Level::Low
3105 } else {
3106 Level::High
3107 };
3108 by_board.entry(board).or_default().push(Input::Gpio {
3109 at_ns,
3110 pin: number,
3111 level,
3112 });
3113 }
3114 }
3115 let mut groups: Vec<(usize, Vec<Input>)> = by_board.into_iter().collect();
3116 for (_, inputs) in &mut groups {
3117 inputs.sort_by_key(|input| match input {
3118 Input::Gpio { at_ns, .. } | Input::Uart { at_ns, .. } => *at_ns,
3119 });
3120 }
3121 Ok(groups)
3122}
3123
3124fn input_board(
3127 spec: &TestSpec,
3128 input: &crate::config::Input,
3129 boards: &[BoardPlan],
3130) -> Result<usize, String> {
3131 match &input.board {
3132 Some(id) => boards
3133 .iter()
3134 .position(|plan| &plan.id == id)
3135 .ok_or_else(|| {
3136 format!(
3137 "test {:?}: board {id:?} is not a development board in diagram.json ({})",
3138 spec.name,
3139 boards
3140 .iter()
3141 .map(|plan| plan.id.as_str())
3142 .collect::<Vec<_>>()
3143 .join(", ")
3144 )
3145 }),
3146 None if boards.len() == 1 => Ok(0),
3147 None => Err(format!(
3148 "test {:?}: the input at {} needs `board = \"...\"`; this diagram has {} boards ({})",
3149 spec.name,
3150 input.at,
3151 boards.len(),
3152 boards
3153 .iter()
3154 .map(|plan| plan.id.as_str())
3155 .collect::<Vec<_>>()
3156 .join(", ")
3157 )),
3158 }
3159}
3160
3161#[derive(Clone)]
3168struct Consoled<'a> {
3169 board: Option<usize>,
3170 text: &'a str,
3171}
3172
3173fn consoled<'a>(entries: Vec<&'a str>, boards: &[BoardPlan]) -> Vec<Consoled<'a>> {
3174 entries
3175 .into_iter()
3176 .map(|entry| match entry.split_once('@') {
3177 Some((prefix, rest)) => match boards.iter().position(|plan| plan.id == prefix) {
3178 Some(board) => Consoled {
3179 board: Some(board),
3180 text: rest,
3181 },
3182 None => Consoled {
3183 board: None,
3184 text: entry,
3185 },
3186 },
3187 None => Consoled {
3188 board: None,
3189 text: entry,
3190 },
3191 })
3192 .collect()
3193}
3194
3195fn seen(fleet: &Fleet, merged: &str, entry: &Consoled) -> bool {
3199 match entry.board {
3200 Some(index) => fleet.console_text(index).contains(entry.text),
3201 None => merged.contains(entry.text),
3202 }
3203}
3204
3205fn parse_mac(text: Option<&str>) -> [u8; 6] {
3206 let Some(text) = text else {
3207 return DEFAULT_MAC;
3208 };
3209 let bytes: Vec<u8> = text
3210 .split([':', '-'])
3211 .filter_map(|b| u8::from_str_radix(b, 16).ok())
3212 .collect();
3213 if bytes.len() == 6 {
3214 [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]]
3215 } else {
3216 DEFAULT_MAC
3217 }
3218}
3219
3220fn blocks(diagnostics: &[Diagnostic], strict: bool) -> bool {
3221 diagnostics
3222 .iter()
3223 .any(|d| d.severity == Severity::Error || (strict && d.severity == Severity::Warning))
3224}
3225
3226fn render(diagnostics: &[Diagnostic]) -> String {
3227 diagnostics
3228 .iter()
3229 .map(|d| {
3230 format!(
3231 "{}[{}]: {}\n",
3232 if d.severity == Severity::Error {
3233 "error"
3234 } else {
3235 "warning"
3236 },
3237 d.code,
3238 d.message
3239 )
3240 })
3241 .collect()
3242}
3243
3244pub fn parse_trigger(spec: &str) -> Result<litz_board::probe::Trigger, String> {
3248 use litz_core::Level;
3249 let (channel, rest) = spec
3250 .split_once('=')
3251 .ok_or_else(|| format!("trigger {spec:?} needs CHANNEL=high|low"))?;
3252 let mut parts = rest.split(',');
3253 let level = match parts.next().unwrap_or("").trim() {
3254 "high" | "1" => Level::High,
3255 "low" | "0" => Level::Low,
3256 other => {
3257 return Err(format!("trigger level {other:?} is not high or low"));
3258 }
3259 };
3260 let mut pre = 0;
3261 let mut post = 0;
3262 for option in parts {
3263 let (key, value) = option
3264 .split_once('=')
3265 .ok_or_else(|| format!("trigger option {option:?} needs key=value"))?;
3266 match key.trim() {
3267 "pre" => pre = crate::config::parse_duration(value.trim())?,
3268 "post" => post = crate::config::parse_duration(value.trim())?,
3269 other => {
3270 return Err(format!("trigger option {other:?} is not pre or post"));
3271 }
3272 }
3273 }
3274 let channel = channel.trim();
3275 if channel.is_empty() {
3276 return Err("trigger needs a probe name".into());
3277 }
3278 Ok(litz_board::probe::Trigger {
3279 channel: channel.to_string(),
3280 level,
3281 pre_ticks: pre,
3282 post_ticks: post,
3283 })
3284}
3285
3286#[cfg(test)]
3287mod tests {
3288 use super::*;
3289
3290 fn staged(name: &str, source: &str) -> StagedScript {
3291 StagedScript {
3292 name: name.into(),
3293 bytes: source.as_bytes().to_vec(),
3294 }
3295 }
3296
3297 #[test]
3298 fn a_multi_file_paste_writes_every_module_then_runs_the_entry() {
3299 let scripts = [
3300 staged("main.py", "import util\nprint(util.N)\n"),
3301 staged("lib/util.py", "N = 42\n"),
3302 ];
3303 let pairs: Vec<(&str, &[u8])> = scripts
3304 .iter()
3305 .map(|script| (script.name.as_str(), script.bytes.as_slice()))
3306 .collect();
3307 let text = crate::python::stage_program("main.py", &pairs);
3308 assert!(text.contains("_litz_stage('main.py', (b'import util\\nprint(util.N)\\n'))"));
3309 assert!(text.contains("_litz_stage('lib/util.py', (b'N = 42\\n'))"));
3310 assert!(text.ends_with("exec(open('main.py').read())\n"));
3311 assert!(text.contains("os.mkdir(cur)"), "directories are created");
3312 }
3313
3314 #[test]
3315 fn a_staged_path_may_not_escape_the_device_directory() {
3316 assert_eq!(staged_name("lib/util.py").unwrap(), "lib/util.py");
3317 for bad in ["/boot.py", "../main.py", "lib//x.py", "", "lib/./x.py"] {
3318 assert!(staged_name(bad).is_err(), "{bad:?} should be refused");
3319 }
3320 }
3321
3322 #[test]
3323 fn a_trigger_spec_names_a_channel_a_level_and_a_window() {
3324 let trigger = parse_trigger("sck=high,pre=250us,post=2ms").unwrap();
3325 assert_eq!(trigger.channel, "sck");
3326 assert_eq!(trigger.level, litz_core::Level::High);
3327 assert_eq!(trigger.pre_ticks, 250_000);
3328 assert_eq!(trigger.post_ticks, 2_000_000);
3329 let plain = parse_trigger("tx=low").unwrap();
3330 assert_eq!(plain.level, litz_core::Level::Low);
3331 assert_eq!((plain.pre_ticks, plain.post_ticks), (0, 0));
3332 assert!(parse_trigger("sck").is_err());
3333 assert!(parse_trigger("sck=sideways").is_err());
3334 assert!(parse_trigger("sck=high,speed=1").is_err());
3335 }
3336}