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