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" | "atmega2560" | "atmega32u4" | "attiny85" => {
200 if network.is_some() {
201 return Err(format!("{name} has no Wi-Fi radio; remove [sim] wifi"));
202 }
203 if bluetooth.is_some() {
204 return Err(format!("{name} has no Bluetooth radio; remove the beacon"));
205 }
206 match name {
207 "atmega328p" => {
208 Box::new(litz_avr::Atmega328p::new().with_shared_board(board, index))
209 }
210 "atmega2560" => {
211 Box::new(litz_avr::Atmega2560::new().with_shared_board(board, index))
212 }
213 "atmega32u4" => {
214 Box::new(litz_avr::Atmega32u4::new().with_shared_board(board, index))
215 }
216 _ => Box::new(litz_avr::Attiny85::new().with_shared_board(board, index)),
217 }
218 }
219 "rp2040" => {
220 if network.is_some() {
221 return Err("rp2040 has no radio; remove [sim] wifi".into());
222 }
223 if bluetooth.is_some() {
224 return Err("rp2040 has no Bluetooth radio; remove the beacon".into());
225 }
226 Box::new(litz_rp::Rp2040::new().with_shared_board(board, index))
227 }
228 "rp2350" => {
229 if network.is_some() {
230 return Err("rp2350 has no radio; remove [sim] wifi".into());
231 }
232 if bluetooth.is_some() {
233 return Err("rp2350 has no Bluetooth radio; remove the beacon".into());
234 }
235 Box::new(litz_rp2350::Rp2350::new().with_shared_board(board, index))
236 }
237 "stc89c52" => {
238 if network.is_some() {
239 return Err("stc89c52 has no radio; remove [sim] wifi".into());
240 }
241 if bluetooth.is_some() {
242 return Err("stc89c52 has no Bluetooth radio; remove the beacon".into());
243 }
244 Box::new(litz_8051::Stc89c52::new().with_shared_board(board, index))
245 }
246 "ch32v003" => {
247 if network.is_some() {
248 return Err("ch32v003 has no radio; remove [sim] wifi".into());
249 }
250 if bluetooth.is_some() {
251 return Err("ch32v003 has no Bluetooth radio; remove the beacon".into());
252 }
253 Box::new(litz_ch32v003::Ch32v003::new().with_shared_board(board, index))
254 }
255 other => return Err(format!("chip {other:?} is not built in")),
256 })
257}
258
259#[cfg(target_family = "wasm")]
261fn xtensa_unavailable(name: &str) -> String {
262 format!(
263 "{name} runs on the Xtensa core, which executes guest blocks through a host JIT; \
264 the browser module has no imports, so use a RISC-V or 8/16-bit part or \
265 run this diagram with the CLI"
266 )
267}
268
269fn find_board<'a>(
271 circuit: &Circuit,
272 registry: &'a Registry,
273) -> Result<&'a litz_catalog::BoardInfo, String> {
274 let mut found: Vec<(&str, &litz_catalog::BoardInfo)> = Vec::new();
275 for part in &circuit.parts {
276 let Some(manifest) = registry.get(&part.type_key) else {
277 continue;
278 };
279 if let Some(info) = manifest.board.as_ref() {
280 found.push((part.id.as_str(), info));
281 }
282 }
283 match found.as_slice() {
284 [] => Err("the diagram has no development board".into()),
285 [(_, info)] => Ok(info),
286 [first, rest @ ..] => {
287 let mut ids = vec![first.0];
288 ids.extend(rest.iter().map(|(id, _)| *id));
289 Err(format!(
290 "the diagram has {} boards ({}); an in-memory session runs one",
291 ids.len(),
292 ids.join(", ")
293 ))
294 }
295 }
296}
297
298pub fn boot(diagram: &str, images: Images<'_>, options: &BootOptions) -> Result<Booted, String> {
305 let images = images.owned();
306 if images.app.is_empty() {
307 return Err("no application image: app_len is 0".into());
308 }
309
310 let mut registry = Registry::builtin();
311 for manifest in &options.manifests {
312 let id = registry
313 .insert_text(&manifest.toml)
314 .map_err(|error| format!("catalog manifest: {error}"))?;
315 if let Some(schematic) = &manifest.schematic {
316 registry.set_schematic(&id, schematic.as_str());
317 }
318 }
319 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
320 let info = find_board(&circuit, ®istry)?;
321 let simulator = info.simulator.clone();
322 let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
323 let flash_size = options
324 .flash_size
325 .or_else(|| {
326 info.flash_size
327 .as_deref()
328 .and_then(|text| parse_size(text).ok())
329 })
330 .unwrap_or(4 * 1024 * 1024);
331
332 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
333 let mut board = Board::new(flat)
334 .map_err(|e| e.to_string())?
335 .with_analog(options.analog);
336 let network = board.network().cloned();
339 let bluetooth = board.bluetooth().cloned();
340 if let Some(config) = network.clone() {
341 board.set_network(config);
342 }
343 let shared = Rc::new(RefCell::new(board));
344
345 let mut chip: Box<dyn Chip> = if let Some(simulator) = &simulator {
346 #[cfg(target_arch = "wasm32")]
347 {
348 Box::new(litz_board::host::HostChip::open(
349 &simulator.module,
350 Rc::clone(&shared),
351 0,
352 )?)
353 }
354 #[cfg(not(target_arch = "wasm32"))]
355 {
356 let _ = simulator;
357 return Err(
358 "this board runs a wasm guest chip, which an in-memory session does not host; \
359 install the board and run it from a project instead"
360 .into(),
361 );
362 }
363 } else {
364 let python = detect_bytes(Runtime::Native, &images.app);
365 let mut chip = builtin_chip(
366 &name,
367 options.mac,
368 flash_size,
369 Rc::clone(&shared),
370 0,
371 Attachments {
372 network: network.as_ref(),
373 bluetooth: bluetooth.as_ref(),
374 elf: None,
375 ble_controller: python == PythonRuntime::CircuitPython,
376 },
377 )?;
378 if info.psram {
379 chip.set_psram_size(4 << 20)?;
380 }
381 chip
382 };
383
384 if !images.rom.is_empty() {
385 chip.load_image(ImageKind::Rom, 0, &images.rom)?;
386 }
387 let flash = chip.info().flash;
388 match (
389 images.bootloader.is_empty(),
390 images.partition_table.is_empty(),
391 ) {
392 (false, false) => {
393 chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.bootloader)?;
394 chip.load_image(
395 ImageKind::PartitionTable,
396 flash.partition_table,
397 &images.partition_table,
398 )?;
399 chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
400 }
401 (true, true) => {
402 let merged = flash.app > 0
405 && detect_layout(&images.app).unwrap_or(FirmwareLayout::Application)
406 == FirmwareLayout::Merged;
407 if merged {
408 chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.app)?;
409 } else {
410 chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
411 }
412 }
413 _ => {
414 return Err("bootloader and partition table must be supplied together".into());
415 }
416 }
417 chip.boot()?;
418
419 Ok(Booted {
420 chip,
421 board: shared,
422 circuit,
423 })
424}
425
426pub fn boot_c3(
431 diagram: &str,
432 images: Images<'_>,
433 flash_size: usize,
434 mac: [u8; 6],
435) -> Result<(C3, Circuit), String> {
436 if images.app.is_empty() {
437 return Err("no application image: app_len is 0".into());
438 }
439
440 let registry = Registry::builtin();
441 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
442 require_c3(&circuit, ®istry)?;
443 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
444 let board = Board::new(flat).map_err(|e| e.to_string())?;
445
446 let mut mcu = C3::new(mac, flash_size).with_board(board);
447 if !images.rom.is_empty() {
448 mcu.load_rom(images.rom)?;
449 }
450
451 match (
452 images.bootloader.is_empty(),
453 images.partition_table.is_empty(),
454 ) {
455 (true, true) => {
456 mcu.write_flash(APP_OFFSET, images.app)?;
458 mcu.boot_app(APP_OFFSET)?;
459 }
460 (false, false) => {
461 mcu.write_flash(BOOTLOADER_OFFSET, images.bootloader)?;
462 mcu.write_flash(PTABLE_OFFSET, images.partition_table)?;
463 mcu.write_flash(APP_OFFSET, images.app)?;
464 }
465 _ => {
466 return Err("bootloader and partition table must be supplied together".into());
467 }
468 }
469
470 Ok((mcu, circuit))
471}
472
473fn require_c3(circuit: &Circuit, registry: &Registry) -> Result<(), String> {
475 let board = circuit
476 .parts
477 .iter()
478 .find(|p| {
479 registry
480 .get(&p.type_key)
481 .and_then(|m| m.board.as_ref())
482 .is_some()
483 })
484 .ok_or("the diagram has no development board")?;
485 let info = registry
486 .get(&board.type_key)
487 .and_then(|m| m.board.as_ref())
488 .expect("filtered above");
489 let chip = info.chip.as_deref().unwrap_or("");
490 if chip != "esp32c3" {
491 return Err(format!(
492 "chip {chip:?} is not built by this boot path; only esp32c3 is supported"
493 ));
494 }
495 Ok(())
496}
497
498pub struct BoardImage<'a> {
502 pub id: Option<&'a str>,
504 pub app: &'a [u8],
505 pub rom: &'a [u8],
506 pub bootloader: &'a [u8],
507 pub partition_table: &'a [u8],
508 pub flash_size: Option<usize>,
509 pub mac: Option<[u8; 6]>,
510}
511
512pub struct BootedFleet {
515 pub chips: Vec<Box<dyn Chip>>,
516 pub board: Rc<RefCell<Board>>,
517 pub circuit: Circuit,
518 pub ids: Vec<String>,
519}
520
521fn find_boards<'a>(
523 circuit: &'a Circuit,
524 registry: &'a Registry,
525) -> Result<Vec<(&'a str, &'a litz_catalog::BoardInfo)>, String> {
526 let mut found = Vec::new();
527 for part in &circuit.parts {
528 let Some(manifest) = registry.get(&part.type_key) else {
529 continue;
530 };
531 if let Some(info) = manifest.board.as_ref() {
532 found.push((part.id.as_str(), info));
533 }
534 }
535 if found.is_empty() {
536 return Err("the diagram has no development board".into());
537 }
538 Ok(found)
539}
540
541pub fn boot_fleet(
547 diagram: &str,
548 images: &[BoardImage<'_>],
549 options: &BootOptions,
550) -> Result<BootedFleet, String> {
551 let mut registry = Registry::builtin();
552 for manifest in &options.manifests {
553 let id = registry
554 .insert_text(&manifest.toml)
555 .map_err(|error| format!("catalog manifest: {error}"))?;
556 if let Some(schematic) = &manifest.schematic {
557 registry.set_schematic(&id, schematic.as_str());
558 }
559 }
560 let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
561 let boards = find_boards(&circuit, ®istry)?;
562 if images.is_empty() {
563 return Err("no application image: app_len is 0".into());
564 }
565 if images.len() != boards.len() {
566 return Err(format!(
567 "the diagram has {} development boards but {} images were supplied",
568 boards.len(),
569 images.len()
570 ));
571 }
572 let named = images.iter().any(|image| image.id.is_some());
573 if named && images.iter().any(|image| image.id.is_none()) {
574 return Err("boot images must either all name a board id or all omit it".into());
575 }
576 if named {
577 for (id, _) in &boards {
578 if !images.iter().any(|image| image.id == Some(*id)) {
579 return Err(format!("board {id:?} has no boot image"));
580 }
581 }
582 }
583
584 let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
585 let mut board = Board::new(flat)
586 .map_err(|e| e.to_string())?
587 .with_analog(options.analog);
588 let network = board.network().cloned();
589 let bluetooth = board.bluetooth().cloned();
590 if let Some(config) = network.clone() {
591 board.set_network(config);
592 }
593 let shared = Rc::new(RefCell::new(board));
594
595 let mut chips: Vec<Box<dyn Chip>> = Vec::with_capacity(boards.len());
596 for (index, (id, info)) in boards.iter().enumerate() {
597 let image = if named {
598 images
599 .iter()
600 .find(|image| image.id == Some(*id))
601 .expect("checked above")
602 } else {
603 &images[index]
604 };
605 let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
606 let flash_size = image
607 .flash_size
608 .or_else(|| {
609 info.flash_size
610 .as_deref()
611 .and_then(|text| parse_size(text).ok())
612 })
613 .unwrap_or(4 * 1024 * 1024);
614 let mut chip: Box<dyn Chip> = if let Some(simulator) = &info.simulator {
615 #[cfg(target_arch = "wasm32")]
616 {
617 Box::new(litz_board::host::HostChip::open(
618 &simulator.module,
619 Rc::clone(&shared),
620 index as u16,
621 )?)
622 }
623 #[cfg(not(target_arch = "wasm32"))]
624 {
625 let _ = simulator;
626 return Err(
627 "this board runs a wasm guest chip, which an in-memory session does not host; \
628 install the board and run it from a project instead"
629 .into(),
630 );
631 }
632 } else {
633 let python = detect_bytes(Runtime::Native, image.app);
638 let mut chip = builtin_chip(
639 &name,
640 image.mac.unwrap_or(options.mac),
641 flash_size,
642 Rc::clone(&shared),
643 index as u16,
644 Attachments {
645 network: network.as_ref(),
646 bluetooth: bluetooth.as_ref(),
647 elf: None,
648 ble_controller: python == PythonRuntime::CircuitPython,
649 },
650 )?;
651 if info.psram {
652 chip.set_psram_size(4 << 20)?;
653 }
654 chip
655 };
656
657 if !image.rom.is_empty() {
658 chip.load_image(ImageKind::Rom, 0, image.rom)?;
659 }
660 let flash = chip.info().flash;
661 match (
662 image.bootloader.is_empty(),
663 image.partition_table.is_empty(),
664 ) {
665 (false, false) => {
666 chip.load_image(ImageKind::Bootloader, flash.bootloader, image.bootloader)?;
667 chip.load_image(
668 ImageKind::PartitionTable,
669 flash.partition_table,
670 image.partition_table,
671 )?;
672 chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
673 }
674 (true, true) => {
675 if image.app.is_empty() {
676 chip.boot()?;
678 } else {
679 let merged = flash.app > 0
680 && detect_layout(image.app).unwrap_or(FirmwareLayout::Application)
681 == FirmwareLayout::Merged;
682 if merged {
683 chip.load_image(ImageKind::Bootloader, flash.bootloader, image.app)?;
684 } else {
685 chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
686 }
687 chip.boot()?;
688 }
689 }
690 _ => {
691 return Err("bootloader and partition table must be supplied together".into());
692 }
693 }
694 chips.push(chip);
695 }
696
697 let ids = boards.iter().map(|(id, _)| (*id).to_string()).collect();
698 Ok(BootedFleet {
699 chips,
700 board: shared,
701 circuit,
702 ids,
703 })
704}