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) bluetooth: Option<&'a litz_ble::BleConfig>,
124 pub(crate) elf: Option<&'a [u8]>,
125 pub(crate) ble_controller: bool,
128}
129
130pub(crate) fn builtin_chip(
132 name: &str,
133 mac: [u8; 6],
134 flash: usize,
135 board: Rc<RefCell<litz_board::Board>>,
136 index: u16,
137 attachments: Attachments<'_>,
138) -> Result<Box<dyn Chip>, String> {
139 let Attachments {
140 network,
141 bluetooth,
142 elf,
143 ble_controller,
144 } = attachments;
145 macro_rules! esp {
148 ($chip:expr) => {{
149 let mut chip = $chip;
150 if let Some(bytes) = elf {
151 chip = chip.with_elf(bytes)?;
152 }
153 if let Some(config) = network {
154 chip.attach_network(config)?;
155 }
156 if let Some(config) = bluetooth {
157 chip.attach_ble(config)?;
158 }
159 if ble_controller {
165 chip.enable_full_ble(false)?;
166 }
167 Box::new(chip)
168 }};
169 }
170 Ok(match name {
171 "esp32" => {
172 #[cfg(not(target_family = "wasm"))]
173 {
174 esp!(Esp32::new(mac, flash).with_shared_board(Rc::clone(&board), index))
175 }
176 #[cfg(target_family = "wasm")]
177 {
178 let _ = (mac, flash, &board, index);
179 return Err(xtensa_unavailable("esp32"));
180 }
181 }
182 "esp32c3" => esp!(C3::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
183 "esp32c6" => esp!(C6::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
184 "esp32s3" => {
185 #[cfg(not(target_family = "wasm"))]
186 {
187 esp!(S3::new(mac, flash).with_shared_board(Rc::clone(&board), index))
188 }
189 #[cfg(target_family = "wasm")]
190 {
191 let _ = (mac, flash, &board, index);
192 return Err(xtensa_unavailable("esp32s3"));
193 }
194 }
195 "esp32p4" => esp!(P4::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
196 "esp32s31" => {
197 esp!(S31::new(mac, flash).with_shared_board(Rc::clone(&board), index))
198 }
199 "atmega328p" => {
200 if network.is_some() {
201 return Err("atmega328p has no Wi-Fi radio; remove [sim] wifi".into());
202 }
203 if bluetooth.is_some() {
204 return Err("atmega328p has no Bluetooth radio; remove the beacon".into());
205 }
206 Box::new(litz_avr::Atmega328p::new().with_shared_board(board, index))
207 }
208 "rp2040" => {
209 if network.is_some() {
210 return Err("rp2040 has no radio; remove [sim] wifi".into());
211 }
212 if bluetooth.is_some() {
213 return Err("rp2040 has no Bluetooth radio; remove the beacon".into());
214 }
215 Box::new(litz_rp::Rp2040::new().with_shared_board(board, index))
216 }
217 other => return Err(format!("chip {other:?} is not built in")),
218 })
219}
220
221#[cfg(target_family = "wasm")]
223fn xtensa_unavailable(name: &str) -> String {
224 format!(
225 "{name} runs on the Xtensa core, which executes guest blocks through a host JIT; \
226 the browser module has no imports, so use the RISC-V ESP parts, the ATmega328P or \
227 the RP2040, or run this diagram with the CLI"
228 )
229}
230
231fn find_board<'a>(
233 circuit: &Circuit,
234 registry: &'a Registry,
235) -> Result<&'a litz_catalog::BoardInfo, String> {
236 let mut found: Vec<(&str, &litz_catalog::BoardInfo)> = Vec::new();
237 for part in &circuit.parts {
238 let Some(manifest) = registry.get(&part.type_key) else {
239 continue;
240 };
241 if let Some(info) = manifest.board.as_ref() {
242 found.push((part.id.as_str(), info));
243 }
244 }
245 match found.as_slice() {
246 [] => Err("the diagram has no development board".into()),
247 [(_, info)] => Ok(info),
248 [first, rest @ ..] => {
249 let mut ids = vec![first.0];
250 ids.extend(rest.iter().map(|(id, _)| *id));
251 Err(format!(
252 "the diagram has {} boards ({}); an in-memory session runs one",
253 ids.len(),
254 ids.join(", ")
255 ))
256 }
257 }
258}
259
260pub fn boot(diagram: &str, images: Images<'_>, options: &BootOptions) -> Result<Booted, String> {
267 let images = images.owned();
268 if images.app.is_empty() {
269 return Err("no application image: app_len is 0".into());
270 }
271
272 let mut registry = Registry::builtin();
273 for manifest in &options.manifests {
274 let id = registry
275 .insert_text(&manifest.toml)
276 .map_err(|error| format!("catalog manifest: {error}"))?;
277 if let Some(schematic) = &manifest.schematic {
278 registry.set_schematic(&id, schematic.as_str());
279 }
280 }
281 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
282 let info = find_board(&circuit, ®istry)?;
283 let simulator = info.simulator.clone();
284 let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
285 let flash_size = options
286 .flash_size
287 .or_else(|| {
288 info.flash_size
289 .as_deref()
290 .and_then(|text| parse_size(text).ok())
291 })
292 .unwrap_or(4 * 1024 * 1024);
293
294 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
295 let mut board = Board::new(flat)
296 .map_err(|e| e.to_string())?
297 .with_analog(options.analog);
298 let network = board.network().cloned();
301 let bluetooth = board.bluetooth().cloned();
302 if let Some(config) = network.clone() {
303 board.set_network(config);
304 }
305 let shared = Rc::new(RefCell::new(board));
306
307 let mut chip: Box<dyn Chip> = if let Some(simulator) = &simulator {
308 #[cfg(target_arch = "wasm32")]
309 {
310 Box::new(litz_board::host::HostChip::open(
311 &simulator.module,
312 Rc::clone(&shared),
313 0,
314 )?)
315 }
316 #[cfg(not(target_arch = "wasm32"))]
317 {
318 let _ = simulator;
319 return Err(
320 "this board runs a wasm guest chip, which an in-memory session does not host; \
321 install the board and run it from a project instead"
322 .into(),
323 );
324 }
325 } else {
326 let python = detect_bytes(Runtime::Native, &images.app);
327 let mut chip = builtin_chip(
328 &name,
329 options.mac,
330 flash_size,
331 Rc::clone(&shared),
332 0,
333 Attachments {
334 network: network.as_ref(),
335 bluetooth: bluetooth.as_ref(),
336 elf: None,
337 ble_controller: python == PythonRuntime::CircuitPython,
338 },
339 )?;
340 if info.psram {
341 chip.set_psram_size(4 << 20)?;
342 }
343 chip
344 };
345
346 if !images.rom.is_empty() {
347 chip.load_image(ImageKind::Rom, 0, &images.rom)?;
348 }
349 let flash = chip.info().flash;
350 match (
351 images.bootloader.is_empty(),
352 images.partition_table.is_empty(),
353 ) {
354 (false, false) => {
355 chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.bootloader)?;
356 chip.load_image(
357 ImageKind::PartitionTable,
358 flash.partition_table,
359 &images.partition_table,
360 )?;
361 chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
362 }
363 (true, true) => {
364 let merged = flash.app > 0
367 && detect_layout(&images.app).unwrap_or(FirmwareLayout::Application)
368 == FirmwareLayout::Merged;
369 if merged {
370 chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.app)?;
371 } else {
372 chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
373 }
374 }
375 _ => {
376 return Err("bootloader and partition table must be supplied together".into());
377 }
378 }
379 chip.boot()?;
380
381 Ok(Booted {
382 chip,
383 board: shared,
384 circuit,
385 })
386}
387
388pub fn boot_c3(
393 diagram: &str,
394 images: Images<'_>,
395 flash_size: usize,
396 mac: [u8; 6],
397) -> Result<(C3, Circuit), String> {
398 if images.app.is_empty() {
399 return Err("no application image: app_len is 0".into());
400 }
401
402 let registry = Registry::builtin();
403 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
404 require_c3(&circuit, ®istry)?;
405 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
406 let board = Board::new(flat).map_err(|e| e.to_string())?;
407
408 let mut mcu = C3::new(mac, flash_size).with_board(board);
409 if !images.rom.is_empty() {
410 mcu.load_rom(images.rom)?;
411 }
412
413 match (
414 images.bootloader.is_empty(),
415 images.partition_table.is_empty(),
416 ) {
417 (true, true) => {
418 mcu.write_flash(APP_OFFSET, images.app)?;
420 mcu.boot_app(APP_OFFSET)?;
421 }
422 (false, false) => {
423 mcu.write_flash(BOOTLOADER_OFFSET, images.bootloader)?;
424 mcu.write_flash(PTABLE_OFFSET, images.partition_table)?;
425 mcu.write_flash(APP_OFFSET, images.app)?;
426 }
427 _ => {
428 return Err("bootloader and partition table must be supplied together".into());
429 }
430 }
431
432 Ok((mcu, circuit))
433}
434
435fn require_c3(circuit: &Circuit, registry: &Registry) -> Result<(), String> {
437 let board = circuit
438 .parts
439 .iter()
440 .find(|p| {
441 registry
442 .get(&p.type_key)
443 .and_then(|m| m.board.as_ref())
444 .is_some()
445 })
446 .ok_or("the diagram has no development board")?;
447 let info = registry
448 .get(&board.type_key)
449 .and_then(|m| m.board.as_ref())
450 .expect("filtered above");
451 let chip = info.chip.as_deref().unwrap_or("");
452 if chip != "esp32c3" {
453 return Err(format!(
454 "chip {chip:?} is not built by this boot path; only esp32c3 is supported"
455 ));
456 }
457 Ok(())
458}
459
460pub struct BoardImage<'a> {
464 pub id: Option<&'a str>,
466 pub app: &'a [u8],
467 pub rom: &'a [u8],
468 pub bootloader: &'a [u8],
469 pub partition_table: &'a [u8],
470 pub flash_size: Option<usize>,
471 pub mac: Option<[u8; 6]>,
472}
473
474pub struct BootedFleet {
477 pub chips: Vec<Box<dyn Chip>>,
478 pub board: Rc<RefCell<Board>>,
479 pub circuit: Circuit,
480 pub ids: Vec<String>,
481}
482
483fn find_boards<'a>(
485 circuit: &'a Circuit,
486 registry: &'a Registry,
487) -> Result<Vec<(&'a str, &'a litz_catalog::BoardInfo)>, String> {
488 let mut found = Vec::new();
489 for part in &circuit.parts {
490 let Some(manifest) = registry.get(&part.type_key) else {
491 continue;
492 };
493 if let Some(info) = manifest.board.as_ref() {
494 found.push((part.id.as_str(), info));
495 }
496 }
497 if found.is_empty() {
498 return Err("the diagram has no development board".into());
499 }
500 Ok(found)
501}
502
503pub fn boot_fleet(
509 diagram: &str,
510 images: &[BoardImage<'_>],
511 options: &BootOptions,
512) -> Result<BootedFleet, String> {
513 let mut registry = Registry::builtin();
514 for manifest in &options.manifests {
515 let id = registry
516 .insert_text(&manifest.toml)
517 .map_err(|error| format!("catalog manifest: {error}"))?;
518 if let Some(schematic) = &manifest.schematic {
519 registry.set_schematic(&id, schematic.as_str());
520 }
521 }
522 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
523 let boards = find_boards(&circuit, ®istry)?;
524 if images.is_empty() {
525 return Err("no application image: app_len is 0".into());
526 }
527 if images.len() != boards.len() {
528 return Err(format!(
529 "the diagram has {} development boards but {} images were supplied",
530 boards.len(),
531 images.len()
532 ));
533 }
534 let named = images.iter().any(|image| image.id.is_some());
535 if named && images.iter().any(|image| image.id.is_none()) {
536 return Err("boot images must either all name a board id or all omit it".into());
537 }
538 if named {
539 for (id, _) in &boards {
540 if !images.iter().any(|image| image.id == Some(*id)) {
541 return Err(format!("board {id:?} has no boot image"));
542 }
543 }
544 }
545
546 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
547 let mut board = Board::new(flat)
548 .map_err(|e| e.to_string())?
549 .with_analog(options.analog);
550 let network = board.network().cloned();
551 let bluetooth = board.bluetooth().cloned();
552 if let Some(config) = network.clone() {
553 board.set_network(config);
554 }
555 let shared = Rc::new(RefCell::new(board));
556
557 let mut chips: Vec<Box<dyn Chip>> = Vec::with_capacity(boards.len());
558 for (index, (id, info)) in boards.iter().enumerate() {
559 let image = if named {
560 images
561 .iter()
562 .find(|image| image.id == Some(*id))
563 .expect("checked above")
564 } else {
565 &images[index]
566 };
567 let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
568 let flash_size = image
569 .flash_size
570 .or_else(|| {
571 info.flash_size
572 .as_deref()
573 .and_then(|text| parse_size(text).ok())
574 })
575 .unwrap_or(4 * 1024 * 1024);
576 let mut chip: Box<dyn Chip> = if let Some(simulator) = &info.simulator {
577 #[cfg(target_arch = "wasm32")]
578 {
579 Box::new(litz_board::host::HostChip::open(
580 &simulator.module,
581 Rc::clone(&shared),
582 index as u16,
583 )?)
584 }
585 #[cfg(not(target_arch = "wasm32"))]
586 {
587 let _ = simulator;
588 return Err(
589 "this board runs a wasm guest chip, which an in-memory session does not host; \
590 install the board and run it from a project instead"
591 .into(),
592 );
593 }
594 } else {
595 let python = detect_bytes(Runtime::Native, image.app);
600 let mut chip = builtin_chip(
601 &name,
602 image.mac.unwrap_or(options.mac),
603 flash_size,
604 Rc::clone(&shared),
605 index as u16,
606 Attachments {
607 network: network.as_ref(),
608 bluetooth: bluetooth.as_ref(),
609 elf: None,
610 ble_controller: python == PythonRuntime::CircuitPython,
611 },
612 )?;
613 if info.psram {
614 chip.set_psram_size(4 << 20)?;
615 }
616 chip
617 };
618
619 if !image.rom.is_empty() {
620 chip.load_image(ImageKind::Rom, 0, image.rom)?;
621 }
622 let flash = chip.info().flash;
623 match (
624 image.bootloader.is_empty(),
625 image.partition_table.is_empty(),
626 ) {
627 (false, false) => {
628 chip.load_image(ImageKind::Bootloader, flash.bootloader, image.bootloader)?;
629 chip.load_image(
630 ImageKind::PartitionTable,
631 flash.partition_table,
632 image.partition_table,
633 )?;
634 chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
635 }
636 (true, true) => {
637 if image.app.is_empty() {
638 chip.boot()?;
640 } else {
641 let merged = flash.app > 0
642 && detect_layout(image.app).unwrap_or(FirmwareLayout::Application)
643 == FirmwareLayout::Merged;
644 if merged {
645 chip.load_image(ImageKind::Bootloader, flash.bootloader, image.app)?;
646 } else {
647 chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
648 }
649 chip.boot()?;
650 }
651 }
652 _ => {
653 return Err("bootloader and partition table must be supplied together".into());
654 }
655 }
656 chips.push(chip);
657 }
658
659 let ids = boards.iter().map(|(id, _)| (*id).to_string()).collect();
660 Ok(BootedFleet {
661 chips,
662 board: shared,
663 circuit,
664 ids,
665 })
666}