use std::cell::RefCell;
use std::rc::Rc;
use litz_board::{Board, Chip, FlatBoard, ImageKind};
use litz_catalog::Registry;
use litz_diagram::Circuit;
use litz_esp::backend::{C3, C6, P4, S31};
#[cfg(not(target_family = "wasm"))]
use litz_esp::backend::{Esp32, S3};
use crate::config::{Runtime, parse_size};
use crate::image::{FirmwareLayout, detect as detect_layout};
use crate::python::{PythonRuntime, detect_bytes};
const BOOTLOADER_OFFSET: usize = 0x0;
const PTABLE_OFFSET: usize = 0x8000;
const APP_OFFSET: usize = 0x1_0000;
pub const DEFAULT_MAC: [u8; 6] = [0x24, 0x0a, 0xc4, 0x12, 0x34, 0x56];
pub struct Images<'a> {
pub rom: &'a [u8],
pub bootloader: &'a [u8],
pub partition_table: &'a [u8],
pub app: &'a [u8],
}
impl Images<'_> {
fn owned(&self) -> OwnedImages {
OwnedImages {
rom: self.rom.to_vec(),
bootloader: self.bootloader.to_vec(),
partition_table: self.partition_table.to_vec(),
app: self.app.to_vec(),
}
}
}
#[derive(Clone, Debug)]
pub struct BootOptions {
pub flash_size: Option<usize>,
pub mac: [u8; 6],
pub analog: bool,
pub manifests: Vec<ManifestText>,
}
#[derive(Clone, Debug, Default)]
pub struct ManifestText {
pub toml: String,
pub schematic: Option<String>,
}
impl Default for BootOptions {
fn default() -> Self {
Self {
flash_size: None,
mac: DEFAULT_MAC,
analog: false,
manifests: Vec::new(),
}
}
}
pub struct Booted {
pub chip: Box<dyn Chip>,
pub board: Rc<RefCell<Board>>,
pub circuit: Circuit,
}
struct OwnedImages {
rom: Vec<u8>,
bootloader: Vec<u8>,
partition_table: Vec<u8>,
app: Vec<u8>,
}
pub(crate) struct Attachments<'a> {
pub(crate) network: Option<&'a litz_net::NetworkConfig>,
pub(crate) bluetooth: Option<&'a litz_ble::BleConfig>,
pub(crate) elf: Option<&'a [u8]>,
pub(crate) ble_controller: bool,
}
pub(crate) fn builtin_chip(
name: &str,
mac: [u8; 6],
flash: usize,
board: Rc<RefCell<litz_board::Board>>,
index: u16,
attachments: Attachments<'_>,
) -> Result<Box<dyn Chip>, String> {
let Attachments {
network,
bluetooth,
elf,
ble_controller,
} = attachments;
macro_rules! esp {
($chip:expr) => {{
let mut chip = $chip;
if let Some(bytes) = elf {
chip = chip.with_elf(bytes)?;
}
if let Some(config) = network {
chip.attach_network(config)?;
}
if let Some(config) = bluetooth {
chip.attach_ble(config)?;
}
if ble_controller {
chip.enable_full_ble(false)?;
}
Box::new(chip)
}};
}
Ok(match name {
"esp32" => {
#[cfg(not(target_family = "wasm"))]
{
esp!(Esp32::new(mac, flash).with_shared_board(Rc::clone(&board), index))
}
#[cfg(target_family = "wasm")]
{
let _ = (mac, flash, &board, index);
return Err(xtensa_unavailable("esp32"));
}
}
"esp32c3" => esp!(C3::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
"esp32c6" => esp!(C6::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
"esp32s3" => {
#[cfg(not(target_family = "wasm"))]
{
esp!(S3::new(mac, flash).with_shared_board(Rc::clone(&board), index))
}
#[cfg(target_family = "wasm")]
{
let _ = (mac, flash, &board, index);
return Err(xtensa_unavailable("esp32s3"));
}
}
"esp32p4" => esp!(P4::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
"esp32s31" => {
esp!(S31::new(mac, flash).with_shared_board(Rc::clone(&board), index))
}
"atmega328p" => {
if network.is_some() {
return Err("atmega328p has no Wi-Fi radio; remove [sim] wifi".into());
}
if bluetooth.is_some() {
return Err("atmega328p has no Bluetooth radio; remove the beacon".into());
}
Box::new(litz_avr::Atmega328p::new().with_shared_board(board, index))
}
"rp2040" => {
if network.is_some() {
return Err("rp2040 has no radio; remove [sim] wifi".into());
}
if bluetooth.is_some() {
return Err("rp2040 has no Bluetooth radio; remove the beacon".into());
}
Box::new(litz_rp::Rp2040::new().with_shared_board(board, index))
}
other => return Err(format!("chip {other:?} is not built in")),
})
}
#[cfg(target_family = "wasm")]
fn xtensa_unavailable(name: &str) -> String {
format!(
"{name} runs on the Xtensa core, which executes guest blocks through a host JIT; \
the browser module has no imports, so use the RISC-V ESP parts, the ATmega328P or \
the RP2040, or run this diagram with the CLI"
)
}
fn find_board<'a>(
circuit: &Circuit,
registry: &'a Registry,
) -> Result<&'a litz_catalog::BoardInfo, String> {
let mut found: Vec<(&str, &litz_catalog::BoardInfo)> = Vec::new();
for part in &circuit.parts {
let Some(manifest) = registry.get(&part.type_key) else {
continue;
};
if let Some(info) = manifest.board.as_ref() {
found.push((part.id.as_str(), info));
}
}
match found.as_slice() {
[] => Err("the diagram has no development board".into()),
[(_, info)] => Ok(info),
[first, rest @ ..] => {
let mut ids = vec![first.0];
ids.extend(rest.iter().map(|(id, _)| *id));
Err(format!(
"the diagram has {} boards ({}); an in-memory session runs one",
ids.len(),
ids.join(", ")
))
}
}
}
pub fn boot(diagram: &str, images: Images<'_>, options: &BootOptions) -> Result<Booted, String> {
let images = images.owned();
if images.app.is_empty() {
return Err("no application image: app_len is 0".into());
}
let mut registry = Registry::builtin();
for manifest in &options.manifests {
let id = registry
.insert_text(&manifest.toml)
.map_err(|error| format!("catalog manifest: {error}"))?;
if let Some(schematic) = &manifest.schematic {
registry.set_schematic(&id, schematic.as_str());
}
}
let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
let info = find_board(&circuit, ®istry)?;
let simulator = info.simulator.clone();
let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
let flash_size = options
.flash_size
.or_else(|| {
info.flash_size
.as_deref()
.and_then(|text| parse_size(text).ok())
})
.unwrap_or(4 * 1024 * 1024);
let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
let mut board = Board::new(flat)
.map_err(|e| e.to_string())?
.with_analog(options.analog);
let network = board.network().cloned();
let bluetooth = board.bluetooth().cloned();
if let Some(config) = network.clone() {
board.set_network(config);
}
let shared = Rc::new(RefCell::new(board));
let mut chip: Box<dyn Chip> = if let Some(simulator) = &simulator {
#[cfg(target_arch = "wasm32")]
{
Box::new(litz_board::host::HostChip::open(
&simulator.module,
Rc::clone(&shared),
0,
)?)
}
#[cfg(not(target_arch = "wasm32"))]
{
let _ = simulator;
return Err(
"this board runs a wasm guest chip, which an in-memory session does not host; \
install the board and run it from a project instead"
.into(),
);
}
} else {
let python = detect_bytes(Runtime::Native, &images.app);
let mut chip = builtin_chip(
&name,
options.mac,
flash_size,
Rc::clone(&shared),
0,
Attachments {
network: network.as_ref(),
bluetooth: bluetooth.as_ref(),
elf: None,
ble_controller: python == PythonRuntime::CircuitPython,
},
)?;
if info.psram {
chip.set_psram_size(4 << 20)?;
}
chip
};
if !images.rom.is_empty() {
chip.load_image(ImageKind::Rom, 0, &images.rom)?;
}
let flash = chip.info().flash;
match (
images.bootloader.is_empty(),
images.partition_table.is_empty(),
) {
(false, false) => {
chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.bootloader)?;
chip.load_image(
ImageKind::PartitionTable,
flash.partition_table,
&images.partition_table,
)?;
chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
}
(true, true) => {
let merged = flash.app > 0
&& detect_layout(&images.app).unwrap_or(FirmwareLayout::Application)
== FirmwareLayout::Merged;
if merged {
chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.app)?;
} else {
chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
}
}
_ => {
return Err("bootloader and partition table must be supplied together".into());
}
}
chip.boot()?;
Ok(Booted {
chip,
board: shared,
circuit,
})
}
pub fn boot_c3(
diagram: &str,
images: Images<'_>,
flash_size: usize,
mac: [u8; 6],
) -> Result<(C3, Circuit), String> {
if images.app.is_empty() {
return Err("no application image: app_len is 0".into());
}
let registry = Registry::builtin();
let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
require_c3(&circuit, ®istry)?;
let flat = FlatBoard::build(&circuit, ®istry).map_err(|e| e.to_string())?;
let board = Board::new(flat).map_err(|e| e.to_string())?;
let mut mcu = C3::new(mac, flash_size).with_board(board);
if !images.rom.is_empty() {
mcu.load_rom(images.rom)?;
}
match (
images.bootloader.is_empty(),
images.partition_table.is_empty(),
) {
(true, true) => {
mcu.write_flash(APP_OFFSET, images.app)?;
mcu.boot_app(APP_OFFSET)?;
}
(false, false) => {
mcu.write_flash(BOOTLOADER_OFFSET, images.bootloader)?;
mcu.write_flash(PTABLE_OFFSET, images.partition_table)?;
mcu.write_flash(APP_OFFSET, images.app)?;
}
_ => {
return Err("bootloader and partition table must be supplied together".into());
}
}
Ok((mcu, circuit))
}
fn require_c3(circuit: &Circuit, registry: &Registry) -> Result<(), String> {
let board = circuit
.parts
.iter()
.find(|p| {
registry
.get(&p.type_key)
.and_then(|m| m.board.as_ref())
.is_some()
})
.ok_or("the diagram has no development board")?;
let info = registry
.get(&board.type_key)
.and_then(|m| m.board.as_ref())
.expect("filtered above");
let chip = info.chip.as_deref().unwrap_or("");
if chip != "esp32c3" {
return Err(format!(
"chip {chip:?} is not built by this boot path; only esp32c3 is supported"
));
}
Ok(())
}