1use std::cell::RefCell;
17use std::rc::Rc;
18
19use litz_board::{Board, Chip, FlatBoard, ImageKind};
20use litz_catalog::Registry;
21use litz_diagram::Circuit;
22use litz_esp::backend::{C3, C6, P4, S31};
23#[cfg(not(target_family = "wasm"))]
24use litz_esp::backend::{Esp32, S3};
25
26use crate::config::{Runtime, parse_size};
27use crate::image::{FirmwareLayout, detect as detect_layout};
28use crate::python::{PythonRuntime, detect_bytes};
29
30const BOOTLOADER_OFFSET: usize = 0x0;
32const PTABLE_OFFSET: usize = 0x8000;
34const APP_OFFSET: usize = 0x1_0000;
36
37pub const DEFAULT_MAC: [u8; 6] = [0x24, 0x0a, 0xc4, 0x12, 0x34, 0x56];
40
41pub struct Images<'a> {
45 pub rom: &'a [u8],
47 pub bootloader: &'a [u8],
49 pub partition_table: &'a [u8],
51 pub app: &'a [u8],
53}
54
55impl Images<'_> {
56 fn owned(&self) -> OwnedImages {
59 OwnedImages {
60 rom: self.rom.to_vec(),
61 bootloader: self.bootloader.to_vec(),
62 partition_table: self.partition_table.to_vec(),
63 app: self.app.to_vec(),
64 }
65 }
66}
67
68#[derive(Clone, Debug)]
70pub struct BootOptions {
71 pub flash_size: Option<usize>,
73 pub mac: [u8; 6],
75 pub analog: bool,
77 pub manifests: Vec<ManifestText>,
80}
81
82#[derive(Clone, Debug, Default)]
85pub struct ManifestText {
86 pub toml: String,
87 pub schematic: Option<String>,
88}
89
90impl Default for BootOptions {
91 fn default() -> Self {
92 Self {
93 flash_size: None,
94 mac: DEFAULT_MAC,
95 analog: false,
96 manifests: Vec::new(),
97 }
98 }
99}
100
101pub struct Booted {
103 pub chip: Box<dyn Chip>,
104 pub board: Rc<RefCell<Board>>,
107 pub circuit: Circuit,
110}
111
112struct OwnedImages {
113 rom: Vec<u8>,
114 bootloader: Vec<u8>,
115 partition_table: Vec<u8>,
116 app: Vec<u8>,
117}
118
119pub(crate) struct Attachments<'a> {
122 pub(crate) network: Option<&'a litz_net::NetworkConfig>,
123 pub(crate) station: Option<&'a str>,
126 pub(crate) bluetooth: Option<&'a litz_ble::BleConfig>,
127 pub(crate) elf: Option<&'a [u8]>,
128 pub(crate) ble_controller: bool,
131}
132
133pub(crate) fn builtin_chip(
135 name: &str,
136 mac: [u8; 6],
137 flash: usize,
138 board: Rc<RefCell<litz_board::Board>>,
139 index: u16,
140 attachments: Attachments<'_>,
141) -> Result<Box<dyn Chip>, String> {
142 let Attachments {
143 network,
144 station,
145 bluetooth,
146 elf,
147 ble_controller,
148 } = attachments;
149 if station.is_some()
152 && !matches!(
153 name,
154 "esp32" | "esp32c3" | "esp32c6" | "esp32s3" | "esp32s31"
155 )
156 {
157 return Err(format!(
158 "{name} has no Wi-Fi radio; remove [sim] wifi_sta / --wifi-sta"
159 ));
160 }
161 macro_rules! esp {
164 ($chip:expr) => {{
165 let mut chip = $chip;
166 if let Some(bytes) = elf {
167 chip = chip.with_elf(bytes)?;
168 }
169 if let Some(config) = network {
170 chip.attach_network(config)?;
171 }
172 if let Some(spec) = station {
173 chip.attach_station(spec)?;
174 }
175 if let Some(config) = bluetooth {
176 chip.attach_ble(config)?;
177 }
178 if ble_controller {
184 chip.enable_full_ble(false)?;
185 }
186 Box::new(chip)
187 }};
188 }
189 Ok(match name {
190 "esp32" => {
191 #[cfg(not(target_family = "wasm"))]
192 {
193 esp!(Esp32::new(mac, flash).with_shared_board(Rc::clone(&board), index))
194 }
195 #[cfg(target_family = "wasm")]
196 {
197 let _ = (mac, flash, &board, index);
198 return Err(xtensa_unavailable("esp32"));
199 }
200 }
201 "esp32c3" => esp!(C3::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
202 "esp32c6" => esp!(C6::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
203 "esp32s3" => {
204 #[cfg(not(target_family = "wasm"))]
205 {
206 esp!(S3::new(mac, flash).with_shared_board(Rc::clone(&board), index))
207 }
208 #[cfg(target_family = "wasm")]
209 {
210 let _ = (mac, flash, &board, index);
211 return Err(xtensa_unavailable("esp32s3"));
212 }
213 }
214 "esp32p4" => esp!(P4::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
215 "esp32s31" => {
216 esp!(S31::new(mac, flash).with_shared_board(Rc::clone(&board), index))
217 }
218 "atmega328p" | "atmega2560" | "atmega32u4" | "attiny85" => {
219 if network.is_some() {
220 return Err(format!("{name} has no Wi-Fi radio; remove [sim] wifi"));
221 }
222 if bluetooth.is_some() {
223 return Err(format!("{name} has no Bluetooth radio; remove the beacon"));
224 }
225 match name {
226 "atmega328p" => {
227 Box::new(litz_avr::Atmega328p::new().with_shared_board(board, index))
228 }
229 "atmega2560" => {
230 Box::new(litz_avr::Atmega2560::new().with_shared_board(board, index))
231 }
232 "atmega32u4" => {
233 Box::new(litz_avr::Atmega32u4::new().with_shared_board(board, index))
234 }
235 _ => Box::new(litz_avr::Attiny85::new().with_shared_board(board, index)),
236 }
237 }
238 "rp2040" => {
239 if network.is_some() {
240 return Err("rp2040 has no radio; remove [sim] wifi".into());
241 }
242 if bluetooth.is_some() {
243 return Err("rp2040 has no Bluetooth radio; remove the beacon".into());
244 }
245 Box::new(litz_rp::Rp2040::new().with_shared_board(board, index))
246 }
247 "rp2350" => {
248 if network.is_some() {
249 return Err("rp2350 has no radio; remove [sim] wifi".into());
250 }
251 if bluetooth.is_some() {
252 return Err("rp2350 has no Bluetooth radio; remove the beacon".into());
253 }
254 Box::new(litz_rp2350::Rp2350::new().with_shared_board(board, index))
255 }
256 "stc89c52" => {
257 if network.is_some() {
258 return Err("stc89c52 has no radio; remove [sim] wifi".into());
259 }
260 if bluetooth.is_some() {
261 return Err("stc89c52 has no Bluetooth radio; remove the beacon".into());
262 }
263 Box::new(litz_8051::Stc89c52::new().with_shared_board(board, index))
264 }
265 "ch32v003" => {
266 if network.is_some() {
267 return Err("ch32v003 has no radio; remove [sim] wifi".into());
268 }
269 if bluetooth.is_some() {
270 return Err("ch32v003 has no Bluetooth radio; remove the beacon".into());
271 }
272 Box::new(litz_ch32v003::Ch32v003::new().with_shared_board(board, index))
273 }
274 other => return Err(format!("chip {other:?} is not built in")),
275 })
276}
277
278#[cfg(target_family = "wasm")]
280fn xtensa_unavailable(name: &str) -> String {
281 format!(
282 "{name} runs on the Xtensa core, which executes guest blocks through a host JIT; \
283 the browser module has no imports, so use a RISC-V or 8/16-bit part or \
284 run this diagram with the CLI"
285 )
286}
287
288fn find_board<'a>(
290 circuit: &Circuit,
291 registry: &'a Registry,
292) -> Result<&'a litz_catalog::BoardInfo, String> {
293 let mut found: Vec<(&str, &litz_catalog::BoardInfo)> = Vec::new();
294 for part in &circuit.parts {
295 let Some(manifest) = registry.get(&part.type_key) else {
296 continue;
297 };
298 if let Some(info) = manifest.board.as_ref() {
299 found.push((part.id.as_str(), info));
300 }
301 }
302 match found.as_slice() {
303 [] => Err("the diagram has no development board".into()),
304 [(_, info)] => Ok(info),
305 [first, rest @ ..] => {
306 let mut ids = vec![first.0];
307 ids.extend(rest.iter().map(|(id, _)| *id));
308 Err(format!(
309 "the diagram has {} boards ({}); an in-memory session runs one",
310 ids.len(),
311 ids.join(", ")
312 ))
313 }
314 }
315}
316
317pub fn boot(diagram: &str, images: Images<'_>, options: &BootOptions) -> Result<Booted, String> {
324 let images = images.owned();
325 if images.app.is_empty() {
326 return Err("no application image: app_len is 0".into());
327 }
328
329 let mut registry = Registry::builtin();
330 for manifest in &options.manifests {
331 let id = registry
332 .insert_text(&manifest.toml)
333 .map_err(|error| format!("catalog manifest: {error}"))?;
334 if let Some(schematic) = &manifest.schematic {
335 registry.set_schematic(&id, schematic.as_str());
336 }
337 }
338 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
339 let info = find_board(&circuit, ®istry)?;
340 let simulator = info.simulator.clone();
341 let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
342 let flash_size = options
343 .flash_size
344 .or_else(|| {
345 info.flash_size
346 .as_deref()
347 .and_then(|text| parse_size(text).ok())
348 })
349 .unwrap_or(4 * 1024 * 1024);
350
351 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
352 let mut board = Board::new(flat)
353 .map_err(|e| e.to_string())?
354 .with_analog(options.analog);
355 let network = board.network().cloned();
358 let bluetooth = board.bluetooth().cloned();
359 if let Some(config) = network.clone() {
360 board.set_network(config);
361 }
362 let shared = Rc::new(RefCell::new(board));
363
364 let mut chip: Box<dyn Chip> = if let Some(simulator) = &simulator {
365 #[cfg(target_arch = "wasm32")]
366 {
367 Box::new(litz_board::host::HostChip::open(
368 &simulator.module,
369 Rc::clone(&shared),
370 0,
371 )?)
372 }
373 #[cfg(not(target_arch = "wasm32"))]
374 {
375 let _ = simulator;
376 return Err(
377 "this board runs a wasm guest chip, which an in-memory session does not host; \
378 install the board and run it from a project instead"
379 .into(),
380 );
381 }
382 } else {
383 let python = detect_bytes(Runtime::Native, &images.app);
384 let mut chip = builtin_chip(
385 &name,
386 options.mac,
387 flash_size,
388 Rc::clone(&shared),
389 0,
390 Attachments {
391 network: network.as_ref(),
392 station: None,
393 bluetooth: bluetooth.as_ref(),
394 elf: None,
395 ble_controller: python == PythonRuntime::CircuitPython,
396 },
397 )?;
398 if info.psram {
399 chip.set_psram_size(4 << 20)?;
400 }
401 chip
402 };
403
404 if !images.rom.is_empty() {
405 chip.load_image(ImageKind::Rom, 0, &images.rom)?;
406 }
407 let flash = chip.info().flash;
408 match (
409 images.bootloader.is_empty(),
410 images.partition_table.is_empty(),
411 ) {
412 (false, false) => {
413 chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.bootloader)?;
414 chip.load_image(
415 ImageKind::PartitionTable,
416 flash.partition_table,
417 &images.partition_table,
418 )?;
419 chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
420 }
421 (true, true) => {
422 let merged = flash.app > 0
425 && detect_layout(&images.app).unwrap_or(FirmwareLayout::Application)
426 == FirmwareLayout::Merged;
427 if merged {
428 chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.app)?;
429 } else {
430 chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
431 }
432 }
433 _ => {
434 return Err("bootloader and partition table must be supplied together".into());
435 }
436 }
437 chip.boot()?;
438
439 Ok(Booted {
440 chip,
441 board: shared,
442 circuit,
443 })
444}
445
446pub fn boot_c3(
451 diagram: &str,
452 images: Images<'_>,
453 flash_size: usize,
454 mac: [u8; 6],
455) -> Result<(C3, Circuit), String> {
456 if images.app.is_empty() {
457 return Err("no application image: app_len is 0".into());
458 }
459
460 let registry = Registry::builtin();
461 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
462 require_c3(&circuit, ®istry)?;
463 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
464 let board = Board::new(flat).map_err(|e| e.to_string())?;
465
466 let mut mcu = C3::new(mac, flash_size).with_board(board);
467 if !images.rom.is_empty() {
468 mcu.load_rom(images.rom)?;
469 }
470
471 match (
472 images.bootloader.is_empty(),
473 images.partition_table.is_empty(),
474 ) {
475 (true, true) => {
476 mcu.write_flash(APP_OFFSET, images.app)?;
478 mcu.boot_app(APP_OFFSET)?;
479 }
480 (false, false) => {
481 mcu.write_flash(BOOTLOADER_OFFSET, images.bootloader)?;
482 mcu.write_flash(PTABLE_OFFSET, images.partition_table)?;
483 mcu.write_flash(APP_OFFSET, images.app)?;
484 }
485 _ => {
486 return Err("bootloader and partition table must be supplied together".into());
487 }
488 }
489
490 Ok((mcu, circuit))
491}
492
493fn require_c3(circuit: &Circuit, registry: &Registry) -> Result<(), String> {
495 let board = circuit
496 .parts
497 .iter()
498 .find(|p| {
499 registry
500 .get(&p.type_key)
501 .and_then(|m| m.board.as_ref())
502 .is_some()
503 })
504 .ok_or("the diagram has no development board")?;
505 let info = registry
506 .get(&board.type_key)
507 .and_then(|m| m.board.as_ref())
508 .expect("filtered above");
509 let chip = info.chip.as_deref().unwrap_or("");
510 if chip != "esp32c3" {
511 return Err(format!(
512 "chip {chip:?} is not built by this boot path; only esp32c3 is supported"
513 ));
514 }
515 Ok(())
516}
517
518pub struct BoardImage<'a> {
522 pub id: Option<&'a str>,
524 pub app: &'a [u8],
525 pub rom: &'a [u8],
526 pub bootloader: &'a [u8],
527 pub partition_table: &'a [u8],
528 pub flash_size: Option<usize>,
529 pub mac: Option<[u8; 6]>,
530}
531
532pub struct BootedFleet {
535 pub chips: Vec<Box<dyn Chip>>,
536 pub board: Rc<RefCell<Board>>,
537 pub circuit: Circuit,
538 pub ids: Vec<String>,
539}
540
541fn find_boards<'a>(
543 circuit: &'a Circuit,
544 registry: &'a Registry,
545) -> Result<Vec<(&'a str, &'a litz_catalog::BoardInfo)>, String> {
546 let mut found = Vec::new();
547 for part in &circuit.parts {
548 let Some(manifest) = registry.get(&part.type_key) else {
549 continue;
550 };
551 if let Some(info) = manifest.board.as_ref() {
552 found.push((part.id.as_str(), info));
553 }
554 }
555 if found.is_empty() {
556 return Err("the diagram has no development board".into());
557 }
558 Ok(found)
559}
560
561pub fn boot_fleet(
567 diagram: &str,
568 images: &[BoardImage<'_>],
569 options: &BootOptions,
570) -> Result<BootedFleet, String> {
571 let mut registry = Registry::builtin();
572 for manifest in &options.manifests {
573 let id = registry
574 .insert_text(&manifest.toml)
575 .map_err(|error| format!("catalog manifest: {error}"))?;
576 if let Some(schematic) = &manifest.schematic {
577 registry.set_schematic(&id, schematic.as_str());
578 }
579 }
580 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
581 let boards = find_boards(&circuit, ®istry)?;
582 if images.is_empty() {
583 return Err("no application image: app_len is 0".into());
584 }
585 if images.len() != boards.len() {
586 return Err(format!(
587 "the diagram has {} development boards but {} images were supplied",
588 boards.len(),
589 images.len()
590 ));
591 }
592 let named = images.iter().any(|image| image.id.is_some());
593 if named && images.iter().any(|image| image.id.is_none()) {
594 return Err("boot images must either all name a board id or all omit it".into());
595 }
596 if named {
597 for (id, _) in &boards {
598 if !images.iter().any(|image| image.id == Some(*id)) {
599 return Err(format!("board {id:?} has no boot image"));
600 }
601 }
602 }
603
604 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
605 let mut board = Board::new(flat)
606 .map_err(|e| e.to_string())?
607 .with_analog(options.analog);
608 let network = board.network().cloned();
609 let bluetooth = board.bluetooth().cloned();
610 if let Some(config) = network.clone() {
611 board.set_network(config);
612 }
613 let shared = Rc::new(RefCell::new(board));
614
615 let mut chips: Vec<Box<dyn Chip>> = Vec::with_capacity(boards.len());
616 for (index, (id, info)) in boards.iter().enumerate() {
617 let image = if named {
618 images
619 .iter()
620 .find(|image| image.id == Some(*id))
621 .expect("checked above")
622 } else {
623 &images[index]
624 };
625 let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
626 let flash_size = image
627 .flash_size
628 .or_else(|| {
629 info.flash_size
630 .as_deref()
631 .and_then(|text| parse_size(text).ok())
632 })
633 .unwrap_or(4 * 1024 * 1024);
634 let mut chip: Box<dyn Chip> = if let Some(simulator) = &info.simulator {
635 #[cfg(target_arch = "wasm32")]
636 {
637 Box::new(litz_board::host::HostChip::open(
638 &simulator.module,
639 Rc::clone(&shared),
640 index as u16,
641 )?)
642 }
643 #[cfg(not(target_arch = "wasm32"))]
644 {
645 let _ = simulator;
646 return Err(
647 "this board runs a wasm guest chip, which an in-memory session does not host; \
648 install the board and run it from a project instead"
649 .into(),
650 );
651 }
652 } else {
653 let python = detect_bytes(Runtime::Native, image.app);
658 let mut chip = builtin_chip(
659 &name,
660 image.mac.unwrap_or(options.mac),
661 flash_size,
662 Rc::clone(&shared),
663 index as u16,
664 Attachments {
665 network: network.as_ref(),
666 station: None,
667 bluetooth: bluetooth.as_ref(),
668 elf: None,
669 ble_controller: python == PythonRuntime::CircuitPython,
670 },
671 )?;
672 if info.psram {
673 chip.set_psram_size(4 << 20)?;
674 }
675 chip
676 };
677
678 if !image.rom.is_empty() {
679 chip.load_image(ImageKind::Rom, 0, image.rom)?;
680 }
681 let flash = chip.info().flash;
682 match (
683 image.bootloader.is_empty(),
684 image.partition_table.is_empty(),
685 ) {
686 (false, false) => {
687 chip.load_image(ImageKind::Bootloader, flash.bootloader, image.bootloader)?;
688 chip.load_image(
689 ImageKind::PartitionTable,
690 flash.partition_table,
691 image.partition_table,
692 )?;
693 chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
694 }
695 (true, true) => {
696 if image.app.is_empty() {
697 chip.boot()?;
699 } else {
700 let merged = flash.app > 0
701 && detect_layout(image.app).unwrap_or(FirmwareLayout::Application)
702 == FirmwareLayout::Merged;
703 if merged {
704 chip.load_image(ImageKind::Bootloader, flash.bootloader, image.app)?;
705 } else {
706 chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
707 }
708 chip.boot()?;
709 }
710 }
711 _ => {
712 return Err("bootloader and partition table must be supplied together".into());
713 }
714 }
715 chips.push(chip);
716 }
717
718 let ids = boards.iter().map(|(id, _)| (*id).to_string()).collect();
719 Ok(BootedFleet {
720 chips,
721 board: shared,
722 circuit,
723 ids,
724 })
725}