Skip to main content

litz_engine/
machine.rs

1//! Booting a diagram and a set of flash images, with no project directory.
2//!
3//! [`runner`](crate::runner) reads a project's files; a host that already has
4//! the diagram and the images in memory — the browser simulator is one — wants
5//! the same construction without the file system in the way. The sequence is
6//! shared so the two cannot drift: validate the diagram against the builtin
7//! catalog, flatten it into a board, attach the board to the chip, place the
8//! images in flash and either let the second-stage bootloader run or jump
9//! straight to the application.
10//!
11//! [`boot`] chooses the backend from the board's manifest, exactly as the
12//! runner does, so every builtin chip is reachable from an in-memory host.
13//! [`boot_c3`] is the older ESP32-C3-only entry point kept for callers that
14//! named the chip themselves.
15
16use 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
30/// The second-stage bootloader's offset in flash.
31const BOOTLOADER_OFFSET: usize = 0x0;
32/// The partition table's offset in flash.
33const PTABLE_OFFSET: usize = 0x8000;
34/// The factory application's offset in flash.
35const APP_OFFSET: usize = 0x1_0000;
36
37/// Espressif's example MAC. Nothing in the simulation is MAC-specific, so a
38/// fixed value keeps two runs byte-identical.
39pub const DEFAULT_MAC: [u8; 6] = [0x24, 0x0a, 0xc4, 0x12, 0x34, 0x56];
40
41/// The images a boot needs. ROM and the bootloader/partition-table pair are
42/// optional; the pair goes together or not at all, because the bootloader
43/// looks the application up through the table.
44pub struct Images<'a> {
45    /// The mask ROM, or an empty slice to let the chip use its own.
46    pub rom: &'a [u8],
47    /// The second-stage bootloader, when the application is not booted bare.
48    pub bootloader: &'a [u8],
49    /// The partition table that names the application's partition.
50    pub partition_table: &'a [u8],
51    /// The application image; required.
52    pub app: &'a [u8],
53}
54
55impl Images<'_> {
56    /// Every image as an owned slice, so a caller can hand the boot code
57    /// borrowed input and still construct the session from its own copies.
58    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/// What a host can choose about a boot before the diagram is read.
69#[derive(Clone, Debug)]
70pub struct BootOptions {
71    /// Flash size in bytes. `None` uses the board manifest's, then 4 MiB.
72    pub flash_size: Option<usize>,
73    /// The MAC the station reports. The default is stable so runs match.
74    pub mac: [u8; 6],
75    /// Solve the analog network instead of treating every net as digital.
76    pub analog: bool,
77    /// Catalog manifests the host supplies. A browser has no directory to
78    /// load them from, so a custom part or board arrives here.
79    pub manifests: Vec<ManifestText>,
80}
81
82/// One manifest the host supplies, with the board's internal schematic when
83/// the manifest names one and has no directory to resolve it against.
84#[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
101/// A booted circuit: the chip that runs it and the board it drives.
102pub struct Booted {
103    pub chip: Box<dyn Chip>,
104    /// The same board the chip was given, kept so a host can ask about parts,
105    /// probes and the display without reaching through the backend.
106    pub board: Rc<RefCell<Board>>,
107    /// The parsed diagram, kept so part enumeration reports the ids the host
108    /// wrote rather than the prefixed ids a board expansion invents.
109    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
119/// What a chip is given besides its own pins: the circuit's network, its
120/// advertisers, and the firmware's symbol table.
121pub(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    /// Bring the Bluetooth controller up even when the project asks for no
126    /// beacons: a CircuitPython build initialises it on every boot.
127    pub(crate) ble_controller: bool,
128}
129
130/// The builtin backend a board's `chip` name selects, with the board attached.
131pub(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    // A radio is part of the ESP32-family adapters, not of `Chip`; the macro
146    // attaches it before the machine is boxed and erased.
147    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            // A CircuitPython build ships with Bluetooth and brings the
160            // controller up on every boot. With no controller behind the
161            // registers the ROM's init asserts and the interpreter never
162            // reaches its own main loop, so the runtime choice carries the
163            // radio with it. `attach_ble` above still decides what is on air.
164            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/// Why an Xtensa board cannot boot in the zero-import browser build.
222#[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
231/// The board instance a diagram boots, with its manifest.
232fn 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
260/// Boot whatever chip the diagram's board names.
261///
262/// The images are copied before this returns, so the caller keeps ownership of
263/// its buffers. A merged ESP image is recognised and written at the
264/// bootloader offset, the way the runner does it; a bare application goes at
265/// the chip's own application offset.
266pub 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, &registry)?;
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, &registry).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    // Radios belong to the circuit's parts, so the chip is attached to the
299    // network and the beacons the diagram already describes.
300    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            // A chip whose application is not at an ESP-IDF offset has no
365            // merged form to detect: the whole file is the application.
366            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
388/// Build a board and an ESP32-C3 wired to it, then place `images` in flash.
389///
390/// Kept for callers that know the chip is a C3; [`boot`] is the entry point
391/// that reads the chip from the diagram.
392pub 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, &registry)?;
405    let flat = FlatBoard::build(&circuit, &registry).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            // No bootloader: start the app the way one would.
419            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
435/// Reject a diagram whose board is not the chip this boot path builds.
436fn 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}