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}