Skip to main content

litz_esp/
lib.rs

1//! ESP32-family chips.
2//!
3//! The adapter is generic over esp32sim's `Soc`: one `EspChip<S>` drives any chip
4//! that crate family models, so adding a chip is a type alias, a bus factory and
5//! a board manifest rather than a second copy of this file. ESP32-C3 is wired
6//! today; the Xtensa parts (ESP32, S3) and the remaining RISC-V parts (C6, P4,
7//! S31) follow the same shape.
8//!
9//! The mask ROM is not vendored here. Espressif publishes the ROM ELFs under
10//! Apache-2.0 at `espressif/esp-rom-elfs`; a chip loads one at runtime from a
11//! path or from an embedded blob the caller supplies, so the crate stays free
12//! of binaries and the licence question stays where Espressif put it.
13// The esp32sim backend is a `std` crate, so the no_std promise only holds
14// when that backend is off.
15#![cfg_attr(
16    not(any(
17        feature = "esp32",
18        feature = "esp32c3",
19        feature = "esp32c6",
20        feature = "esp32s3",
21        feature = "esp32p4",
22        feature = "esp32s31"
23    )),
24    no_std
25)]
26#![forbid(unsafe_code)]
27
28extern crate alloc;
29
30use litz_mcu::MemoryRegion;
31
32/// The simulated network behind an access point: DHCP/DNS/ICMP from esp32sim,
33/// TCP and UDP from Litz's own service table.
34#[cfg(any(
35    feature = "esp32",
36    feature = "esp32c3",
37    feature = "esp32c6",
38    feature = "esp32s3",
39    feature = "esp32p4",
40    feature = "esp32s31"
41))]
42pub mod router;
43
44// The debug surface, the display capture and the GDB stub are siblings of
45// `backend`: each needs the machine, which only the backend may hold, and each
46// gates itself on the chips it can serve.
47pub mod debug;
48pub mod gdb;
49pub mod screenshot;
50
51#[cfg(any(
52    feature = "esp32",
53    feature = "esp32c3",
54    feature = "esp32c6",
55    feature = "esp32s3",
56    feature = "esp32p4",
57    feature = "esp32s31"
58))]
59pub use litz_net::{NetworkConfig, Service};
60#[cfg(any(
61    feature = "esp32",
62    feature = "esp32c3",
63    feature = "esp32c6",
64    feature = "esp32s3",
65    feature = "esp32p4",
66    feature = "esp32s31"
67))]
68pub use router::EspRouter;
69
70/// Which chip a [`Config`] describes.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Chip {
73    /// RV32IMC, 160 MHz, PLIC, no atomics.
74    Esp32C3,
75    /// RV32IMAC, 160 MHz, PLIC.
76    Esp32C6,
77    /// RV32IMAC, 96 MHz, PLIC, no radio.
78    Esp32H2,
79}
80
81/// External flash layout, in the order the ROM expects to find images.
82#[derive(Clone, Copy, Debug)]
83pub struct FlashLayout {
84    pub size: u32,
85    /// Offset of the second-stage bootloader.
86    pub bootloader_offset: u32,
87    /// Offset of the partition table.
88    pub partition_table_offset: u32,
89    /// Offset of the application image.
90    pub app_offset: u32,
91}
92
93impl Chip {
94    pub const fn memory_map(self) -> &'static [MemoryRegion] {
95        // Addresses are from the ESP32-C3/C6 technical reference manuals.
96        match self {
97            Chip::Esp32C3 | Chip::Esp32C6 | Chip::Esp32H2 => &PLIC_AND_RV_MAP,
98        }
99    }
100
101    pub const fn flash_layout(self) -> FlashLayout {
102        FlashLayout {
103            size: 4 * 1024 * 1024,
104            bootloader_offset: 0x0,
105            partition_table_offset: 0x8000,
106            app_offset: 0x1_0000,
107        }
108    }
109}
110
111/// Adapter over `esp32sim`'s ESP32-family machines.
112///
113/// This exists to answer one question with a build rather than an opinion:
114/// can a mature, MIT-licensed ESP32 emulator be driven as a library from
115/// outside its own repo? Everything above this module — diagrams, parts, the
116/// CI runner — only needs the [`litz_board::Chip`] calls, so the backend can be
117/// swapped for a vendored copy or an in-tree core later without touching them.
118#[cfg(any(
119    feature = "esp32",
120    feature = "esp32c3",
121    feature = "esp32c6",
122    feature = "esp32s3",
123    feature = "esp32p4",
124    feature = "esp32s31"
125))]
126pub mod backend {
127    use alloc::vec::Vec;
128    use core::cell::RefCell;
129    use std::cell::Cell;
130    use std::collections::BTreeMap;
131    use std::rc::Rc;
132
133    use esp_periph::i2c::I2cDevice as EspI2cDevice;
134    use esp_soc::ble::peer::Nearby;
135    use esp_soc::board::{BoardEdge, BoardModel, SpiPins};
136    use esp_soc::uart::{UartInput, UartRoute};
137    use esp_soc::{Machine, Soc, SocBus};
138    use litz_board::{Board as LitzBoard, Conflict};
139    use litz_core::{Drive, Level, PartState};
140
141    /// Builds a chip's bus with the Litz board already on it.
142    ///
143    /// Each esp32sim crate has its own `SocBus::new` signature — the S3 takes a
144    /// PSRAM size, the P4 a wafer revision, the S31 nothing — so the factory is
145    /// the one per-chip detail, and everything above it is generic. The cell
146    /// carries the GP-SPI clock the guest programmed, from an MMIO observer to
147    /// the board model that reconstructs the wires.
148    pub type BusFactory<S> = fn(
149        [u8; 6],
150        usize,
151        Option<Rc<RefCell<LitzBoard>>>,
152        u16,
153        Rc<Cell<[u32; 2]>>,
154    ) -> <S as Soc>::Bus;
155
156    /// An esp32sim machine attached to a Litz board.
157    pub struct EspChip<S: Soc> {
158        machine: Machine<S>,
159        board: Option<Rc<RefCell<LitzBoard>>>,
160        /// Kept so `with_board` can rebuild the machine; the bus owns the board
161        /// model and esp32sim has no setter after construction.
162        mac: [u8; 6],
163        flash: usize,
164        bus_for: BusFactory<S>,
165        /// A bootloader image was placed, so the machine starts from it
166        /// rather than from a direct `boot_app`.
167        bootloader_loaded: bool,
168        /// The analog values last written to the pads, so a run that changes
169        /// nothing does not reprogram the ADC every step.
170        analog: Vec<(u8, f32)>,
171        /// The firmware's ELF, when the project supplies one. esp32sim's HCI
172        /// Bluetooth controller is started by patching the guest's controller
173        /// task, so it needs the symbol table; the same symbols name addresses
174        /// in logs, disassembly and the debugger.
175        elf: Option<Vec<u8>>,
176        /// Serves a GDB client, when this chip's core is one the stub can
177        /// describe. The per-chip constructor installs it; the Xtensa parts
178        /// leave it empty, because their windowed register file needs a
179        /// different target description rather than a made-up one.
180        gdb: Option<GdbServeFn<S>>,
181        /// Calls a guest function on a core this adapter can drive, installed
182        /// by that chip's constructor: the flat RV32 register file, or a
183        /// windowed Xtensa `call8` with a saved core around it.
184        guest_call: Option<GuestCall<S>>,
185        /// Which development-board instance on the diagram these pads belong
186        /// to. A diagram with one board is board 0.
187        board_index: u16,
188        /// The chip's simulated time, shared with the network adapter so a
189        /// packet capture can timestamp the frames it records.
190        net_clock: Rc<Cell<u64>>,
191        /// The controller is on and its scan list came from the board, so a
192        /// runtime advertiser has to be mirrored on the next step.
193        ble_attached: bool,
194        /// The board's BLE generation the controller's scan list reflects.
195        ble_seen: u64,
196        /// The controller's scan list as this adapter last gave it, so a peer
197        /// added while the simulation runs can be appended to it.
198        ble_peers: Vec<litz_ble::Beacon>,
199        /// Reads and writes the USB Serial/JTAG console on chips that have one.
200        /// A firmware built for USB CDC (CircuitPython, TinyUSB, HWCDC) prints
201        /// there and not on UART0, so the console has to follow both.
202        /// The GP-SPI clock registers a firmware write feeds to the board model.
203        spi_clock: Option<SpiClockSpec>,
204        /// The latest programmed rate per GP-SPI host (2 and 3), written by an
205        /// MMIO observer and read when a transfer reaches the board.
206        spi_rates: Rc<Cell<[u32; 2]>>,
207    }
208
209    /// Starts a GDB session over one chip.
210    pub type GdbServeFn<S> = fn(&mut EspChip<S>, u16) -> Result<(), String>;
211
212    /// Calls a guest function with no arguments and returns its result: `a0` on
213    /// RV32, and the windowed callee's `a2` on Xtensa (the caller's `a10` once
214    /// `retw` restores the register base).
215    pub type GuestCall<S> = fn(&mut EspChip<S>, u32) -> Result<u32, String>;
216
217    /// The entry a RISC-V chip's constructor installs. The stub is only compiled for the
218    /// RISC-V parts, so an Xtensa-only feature set must not reference it.
219    #[cfg(any(
220        feature = "esp32c3",
221        feature = "esp32c6",
222        feature = "esp32p4",
223        feature = "esp32s31"
224    ))]
225    fn serve_gdb<S: crate::debug::Rv32Chip>(
226        chip: &mut EspChip<S>,
227        port: u16,
228    ) -> Result<(), String> {
229        crate::gdb::serve(chip, port)
230    }
231
232    impl<S: Soc> EspChip<S> {
233        /// A chip with no board on it. Public to the crate's own constructors;
234        /// callers use the per-chip `new`.
235        fn bare(mac: [u8; 6], flash: usize, bus_for: BusFactory<S>) -> Self {
236            let spi_rates = Rc::new(Cell::new([0; 2]));
237            let machine = Self::build(mac, flash, bus_for, None, 0, Rc::clone(&spi_rates));
238            Self {
239                machine,
240                board: None,
241                mac,
242                flash,
243                bus_for,
244                bootloader_loaded: false,
245                analog: Vec::new(),
246                elf: None,
247                gdb: None,
248                guest_call: None,
249                board_index: 0,
250                net_clock: Rc::new(Cell::new(0)),
251                ble_attached: false,
252                ble_seen: 0,
253                ble_peers: Vec::new(),
254                spi_clock: None,
255                spi_rates,
256            }
257        }
258
259        fn build(
260            mac: [u8; 6],
261            flash: usize,
262            bus_for: BusFactory<S>,
263            board: Option<Rc<RefCell<LitzBoard>>>,
264            index: u16,
265            spi_rates: Rc<Cell<[u32; 2]>>,
266        ) -> Machine<S> {
267            let mut machine = Machine::new(mac, bus_for(mac, flash, board, index, spi_rates));
268            // The scheduling batching knobs default from `ESP32SIM_VQ` /
269            // `ESP32SIM_BB` at construction; pin them to the plain one-quantum
270            // schedule, which is the bit-exact reference the batching is
271            // defined against. A simulator whose behaviour depends on the CI
272            // runner's environment cannot be a test gate, so the machine is
273            // built directly rather than through `esp32c3::machine`.
274            machine.vq_max = 1;
275            machine.bb_max = 1;
276            // The console prints to stdout unless captured; a library caller
277            // wants the bytes, not the side effect.
278            machine.console.capture = true;
279            machine
280        }
281
282        /// Attach a flattened board. Rebuilds the machine, so it must be called
283        /// before images are loaded (which is how every caller uses it).
284        pub fn with_board(self, board: LitzBoard) -> Self {
285            let shared = Rc::new(RefCell::new(board));
286            self.with_shared_board(shared, 0)
287        }
288
289        /// Attach a board another chip already shares, and say which board
290        /// instance these pads belong to.
291        ///
292        /// A diagram with more than one MCU has one [`LitzBoard`] and one chip
293        /// per development-board instance; the board is the same object, and
294        /// the index keeps two boards' GPIO 4 apart. The machine is rebuilt
295        /// here, which is why images are loaded after this call.
296        pub fn with_shared_board(mut self, board: Rc<RefCell<LitzBoard>>, index: u16) -> Self {
297            self.machine = Self::build(
298                self.mac,
299                self.flash,
300                self.bus_for,
301                Some(Rc::clone(&board)),
302                index,
303                Rc::clone(&self.spi_rates),
304            );
305            self.board = Some(board);
306            self.board_index = index;
307            // The rebuild replaces the machine, so the symbols and the clock
308            // observer go back on it. The bytes parsed when they were accepted,
309            // and parsing is pure.
310            if let Some(bytes) = &self.elf {
311                let _ = self.machine.add_symbols(bytes);
312            }
313            self.install_spi_observer();
314            self
315        }
316
317        /// Watch the GP-SPI clock registers, when this chip has them and a
318        /// board is attached.
319        ///
320        /// A firmware write is seen by an MMIO observer and stored in
321        /// `spi_rates`; the board model reports it at the transfer itself, so
322        /// the reconstructed wires use the divider the driver programmed
323        /// rather than the board's default. A chip with no board reconstructs
324        /// nothing, so it does not pay for an MMIO log. Installing twice is a
325        /// no-op.
326        fn install_spi_observer(&mut self) {
327            if self.board.is_none() {
328                return;
329            }
330            let Some(spec) = self.spi_clock else {
331                return;
332            };
333            if self.machine.has_observer("litz-spi-clock") {
334                return;
335            }
336            self.machine.add_observer(Box::new(SpiClockObserver {
337                rates: Rc::clone(&self.spi_rates),
338                spec,
339            }));
340        }
341
342        /// The machine, for the sibling modules that capture a display or
343        /// answer a debugger. Every esp32sim type still stays in this crate.
344        pub(crate) fn machine_ref(&self) -> &Machine<S> {
345            &self.machine
346        }
347
348        pub(crate) fn machine_mut(&mut self) -> &mut Machine<S> {
349            &mut self.machine
350        }
351
352        /// Serve one GDB client on `127.0.0.1:port`, returning when it
353        /// disconnects.
354        pub fn gdb_serve(&mut self, port: u16) -> Result<(), String> {
355            match self.gdb {
356                Some(serve) => serve(self, port),
357                None => Err(format!(
358                    "{} has no GDB target: only the RISC-V chips describe a register file",
359                    S::NAME
360                )),
361            }
362        }
363
364        /// Give the machine the firmware's symbol table.
365        ///
366        /// A project that has the ELF next to its image should always pass it:
367        /// the Bluetooth controller esp32sim runs is installed by patching the
368        /// guest's own controller task, which is only reachable by symbol, and
369        /// every log line, disassembly and breakpoint address benefits from
370        /// names. Call it after [`EspChip::with_board`], which rebuilds the
371        /// machine and would otherwise drop the symbols.
372        pub fn with_elf(mut self, bytes: &[u8]) -> Result<Self, String> {
373            self.machine.add_symbols(bytes)?;
374            self.elf = Some(bytes.to_vec());
375            Ok(self)
376        }
377
378        /// Whether a second-stage bootloader was loaded. With one, the boot
379        /// sequence is the bootloader's job and `boot` has nothing to start.
380        pub fn has_bootloader(&self) -> bool {
381            self.bootloader_loaded
382        }
383
384        pub fn board(&self) -> Option<&Rc<RefCell<LitzBoard>>> {
385            self.board.as_ref()
386        }
387
388        /// The esp32sim board callbacks, which route pins, SPI, UART and I2C
389        /// to the Litz board. A test can call the same entry points the chip
390        /// does without hand-programming a peripheral.
391        pub fn board_model(&mut self) -> &mut dyn BoardModel {
392            self.machine.bus.board()
393        }
394
395        pub fn state(&self, part: &str) -> Option<PartState> {
396            self.board.as_ref()?.borrow().state(part)
397        }
398
399        /// Press or release a named part. The board resolves it, so a LED
400        /// wired through the switch lights up as well; the chip only sees the
401        /// pin move if the circuit routes the switch to one.
402        pub fn press(&mut self, part: &str, pressed: bool) -> bool {
403            let Some(board) = self.board.as_ref() else {
404                return false;
405            };
406            let now = (self.machine.seconds() * 1e9) as u64;
407            board.borrow_mut().press(part, pressed, now)
408        }
409
410        /// Move a continuous control (a potentiometer's travel, in permille). The
411        /// board recomputes the wiper voltage; the pad is reprogrammed on the next
412        /// run, which is the first moment the firmware could read it anyway.
413        /// Make external PSRAM visible to the chip, in bytes.
414        pub fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
415            self.machine.bus.set_psram_size(bytes)
416        }
417
418        pub fn set_control(&mut self, part: &str, permille: u16) -> bool {
419            let Some(board) = self.board.as_ref() else {
420                return false;
421            };
422            let now = (self.machine.seconds() * 1e9) as u64;
423            board.borrow_mut().set_control(part, permille, now)
424        }
425
426        /// Set a named control on a part, in the unit the scenario wrote.
427        pub fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
428            let Some(board) = self.board.as_ref() else {
429                return false;
430            };
431            let now = (self.machine.seconds() * 1e9) as u64;
432            board.borrow_mut().set_named_control(part, name, value, now)
433        }
434
435        /// Bytes from the host into UART0's receive FIFO, as a terminal on the
436        /// chip's RX pin would send them.
437        pub fn write_serial(&mut self, bytes: &[u8]) {
438            self.machine.bus.uart_input(0, bytes);
439            *self.machine.bus.irq_dirty() = true;
440        }
441
442        /// Analog voltages the board holds on chip pins, for tests and a UI.
443        pub fn analog_inputs(&self) -> Vec<(u8, f32)> {
444            self.board
445                .as_ref()
446                .map(|b| b.borrow().analog_inputs_on(self.board_index))
447                .unwrap_or_default()
448        }
449
450        /// Push the board's analog levels to the pads that changed since the
451        /// last push.
452        ///
453        /// `Board::analog_inputs` is the one preference point: when the board's
454        /// analog co-simulation is on it returns the solved node voltage for an
455        /// analog pin, and when it is off it returns the part's static
456        /// `Part::analog` value exactly as before. The adapter therefore has no
457        /// second, chip-specific path to keep in sync.
458        fn publish_analog(&mut self) {
459            let Some(board) = self.board.as_ref() else {
460                return;
461            };
462            let now = board.borrow().analog_inputs();
463            for &(gpio, volts) in &now {
464                let unchanged = self
465                    .analog
466                    .iter()
467                    .any(|&(pin, v)| pin == gpio && v == volts);
468                if !unchanged {
469                    self.machine
470                        .bus
471                        .analog_set(gpio, esp_periph::AnalogSource::Const(volts));
472                }
473            }
474            self.analog = now;
475        }
476
477        /// The level on one pin of a named part. With no pin name, the level
478        /// the chip sees on the pin the part is wired to.
479        pub fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
480            let board = self.board.as_ref()?.borrow();
481            match pin {
482                Some(pin) => board.part_pin_level(part, pin),
483                None => board.chip_pin_level_on(self.board_index, part),
484            }
485        }
486
487        /// The level on one of this chip's own pads, by GPIO number.
488        pub fn gpio_level(&self, gpio: u8) -> Option<Level> {
489            let board = self.board.as_ref()?.borrow();
490            board.chip_level_on(self.board_index, gpio)
491        }
492
493        pub fn conflicts(&self) -> Vec<Conflict> {
494            self.board
495                .as_ref()
496                .map(|b| b.borrow().conflicts().to_vec())
497                .unwrap_or_default()
498        }
499
500        /// Load the mask ROM ELF (Apache-2.0, from `espressif/esp-rom-elfs`).
501        pub fn load_rom(&mut self, rom_elf: &[u8]) -> Result<(), String> {
502            self.machine.load_rom(rom_elf)
503        }
504
505        /// Write bytes at a flash offset (bootloader at 0x0, partition table at
506        /// 0x8000, application at 0x10000, matching the ESP-IDF layout).
507        pub fn write_flash(&mut self, offset: usize, data: &[u8]) -> Result<(), String> {
508            self.machine.write_flash(offset, data)
509        }
510
511        /// Start the application at `app_off` the way the second-stage
512        /// bootloader would, for images that ship without a bootloader.
513        pub fn boot_app(&mut self, app_off: usize) -> Result<u32, String> {
514            self.machine.boot_app(app_off)
515        }
516
517        /// Schedule host actions (pressing a named pin, writing to a UART) at
518        /// simulated times. Times are seconds; the format is esp32sim's.
519        pub fn load_script(&mut self, text: &str) -> Result<(), String> {
520            self.machine.load_script(text)
521        }
522
523        /// Load an ELF's symbols so a fault or a trace names a function instead of
524        /// an address. The ROM ELF and the firmware ELF both work.
525        pub fn add_symbols(&mut self, elf: &[u8]) -> Result<(), String> {
526            self.machine.add_symbols(elf)
527        }
528
529        /// Stop the next run when the program counter reaches `pc`.
530        pub fn break_at(&mut self, pc: u32) {
531            self.machine
532                .add_observer(Box::new(esp_soc::observers::Breakpoints { pcs: vec![pc] }));
533        }
534
535        /// Registers of every core, as the debugger prints them.
536        pub fn registers(&self) -> String {
537            self.machine.dump_regs()
538        }
539
540        /// Record which code blocks execute, so a test can show what it
541        /// actually covered. Enabling twice is a no-op.
542        pub fn enable_coverage(&mut self) {
543            if !self.machine.has_observer("coverage") {
544                self.machine
545                    .add_observer(Box::new(esp_soc::observers::Coverage::new(None)));
546            }
547        }
548
549        /// The enabled observers' end-of-run reports, one line each.
550        pub fn reports(&mut self) -> Vec<String> {
551            self.machine.reports().lines().map(str::to_string).collect()
552        }
553
554        /// Disassemble `count` instructions at `addr`.
555        /// The address the firmware's symbol table gives `name`, when the
556        /// project supplied an ELF.
557        pub fn symbol_addr(&self, name: &str) -> Option<u32> {
558            self.machine.sym_addr(name)
559        }
560
561        /// Call a guest function with no arguments and return its result: `a0`
562        /// on RV32, and the windowed callee's `a2` on Xtensa (read from the
563        /// caller's `a10` after `retw` rotates the register window back).
564        ///
565        /// The call is transparent to the firmware: the core state and program
566        /// counter are saved and restored, and the function returns to the
567        /// instruction that was about to execute. The call is bounded, so a
568        /// function that never returns comes back as an error instead of hanging
569        /// the run.
570        pub fn call_guest(&mut self, address: u32) -> Result<u32, String> {
571            match self.guest_call {
572                Some(call) => call(self, address),
573                None => Err(format!(
574                    "{} does not install a guest-call trampoline",
575                    S::NAME
576                )),
577            }
578        }
579
580        /// The free heap the running firmware reports, by calling its own
581        /// `esp_get_free_heap_size` (or another IDF getter).
582        ///
583        /// This is a real sample: the function reads the guest's allocator.
584        /// It needs the ELF's symbols and a stopped or idle core.
585        pub fn sample_heap(&mut self) -> Result<u32, String> {
586            let names = [
587                "esp_get_free_heap_size",
588                "heap_caps_get_free_size",
589                "xPortGetFreeHeapSize",
590            ];
591            let (name, address) = names
592                .iter()
593                .find_map(|name| self.symbol_addr(name).map(|address| (*name, address)))
594                .ok_or_else(|| {
595                    "no heap getter symbol in the ELF (esp_get_free_heap_size, \
596                     heap_caps_get_free_size or xPortGetFreeHeapSize); supply `elf` in the project"
597                        .to_string()
598                })?;
599            self.call_guest(address)
600                .map_err(|error| format!("{name}: {error}"))
601        }
602
603        pub fn disassemble(&mut self, addr: u32, count: usize) -> String {
604            self.machine.disasm(addr, count)
605        }
606
607        /// Put a virtual access point on the air the chip's radio hears.
608        ///
609        /// `spec` is esp32sim's AP syntax (`ssid=...,psk=...,channel=...`). The
610        /// network behind it is the deterministic virtual one (DHCP, ARP, DNS,
611        /// NTP); no host socket is involved, so a test that uses Wi-Fi stays
612        /// repeatable. NAT to the host is deliberately not wired here.
613        pub fn attach_wifi(&mut self, spec: &str) -> Result<(), String> {
614            let ap = esp_soc::wifi::ApConfig::parse(spec)?;
615            self.machine.bus.attach_wifi(ap, None)
616        }
617
618        /// Put a whole simulated network on the air: the joinable access points,
619        /// the networks a scan should see, and a router that answers TCP and UDP
620        /// without a host socket.
621        ///
622        /// The router is installed as esp32sim's NAT transport, so the guest's
623        /// DHCP lease, gateway, DNS server and default route are the ones a real
624        /// access point hands out; only the far side of the gateway is Litz's,
625        /// and that side is `litz-net`, not anything ESP-specific.
626        pub fn attach_network(&mut self, config: &crate::NetworkConfig) -> Result<(), String> {
627            let specs: Vec<String> = config.access_points.iter().map(ap_spec).collect();
628            let aps = esp_soc::wifi::ApConfig::parse_all(&specs)?;
629            let nat = esp_soc::nat::Nat::with_transport(
630                false,
631                Box::new(crate::EspRouter::with_clock(
632                    config,
633                    Rc::clone(&self.net_clock),
634                )),
635            );
636            self.machine.bus.attach_wifi(aps[0].clone(), Some(nat))?;
637            for ap in &aps[1..] {
638                self.machine.bus.add_wifi_ap(ap.clone())?;
639            }
640            if !config.nearby.is_empty() {
641                let specs: Vec<String> = config.nearby.iter().map(nearby_spec).collect();
642                let beacons = esp_soc::wifi::BeaconAp::parse_all(&specs)?;
643                let left_out = self.machine.bus.wifi_nearby(beacons)?;
644                if let Some((beacon, why)) = left_out.first() {
645                    return Err(format!(
646                        "the network '{}' cannot be beside the access point: it shares {why}",
647                        beacon.ssid
648                    ));
649                }
650            }
651            Ok(())
652        }
653
654        /// Replace the simulated far side of the Wi-Fi gateway with host
655        /// sockets, so the guest reaches the real internet through the host.
656        ///
657        /// The access point and the DHCP lease stay the simulated ones; only
658        /// what is behind the gateway changes. This is opt-in and has no
659        /// deterministic bytes: a run that uses it depends on the host network.
660        #[cfg(not(target_arch = "wasm32"))]
661        pub fn attach_host_nat(&mut self, local_ntp: bool) -> Result<(), String> {
662            self.machine
663                .bus
664                .attach_nat(Some(esp_soc::nat::Nat::new(false)), local_ntp)
665        }
666
667        /// Put host sockets behind the gateway and forward these host ports
668        /// into the guest: `tcp:[host:]port-[guest:]port`, the same syntax
669        /// esp32sim uses. Returns one line per forward describing where it
670        /// listens.
671        #[cfg(not(target_arch = "wasm32"))]
672        pub fn attach_host_forwards(
673            &mut self,
674            forwards: &[String],
675            local_ntp: bool,
676        ) -> Result<Vec<String>, String> {
677            let mut transport = esp_soc::nat::StdTransport::new();
678            let mut lines = Vec::new();
679            for spec in forwards {
680                let forward = esp_soc::nat::HostFwdSpec::parse(spec)?;
681                let at = transport
682                    .listen(&forward)
683                    .map_err(|e| format!("host forward {spec:?}: {e}"))?;
684                lines.push(format!("{spec} -> {at}"));
685            }
686            let mut nat = esp_soc::nat::Nat::with_transport(false, Box::new(transport));
687            nat.hostfwd = forwards.len() as u64;
688            self.machine.bus.attach_nat(Some(nat), local_ntp)?;
689            Ok(lines)
690        }
691
692        /// Record the Ethernet frames the station's MAC carries, both ways,
693        /// for a pcap. Independent of the virtual network's own capture.
694        pub fn set_net_tap(&mut self, tap: esp_soc::netcap::NetTap) -> Result<(), String> {
695            self.machine.bus.set_net_tap(tap)
696        }
697
698        /// Record every 802.11 frame the air carries into a pcap with link
699        /// type 105, written as the run goes.
700        pub fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
701            let file =
702                std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
703            let capture =
704                std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::AirCapture::default()));
705            capture
706                .lock()
707                .map_err(|_| "the air capture lock is poisoned".to_string())?
708                .set_pcap(Box::new(file))
709                .map_err(|e| format!("{}: {e}", path.display()))?;
710            self.machine
711                .bus
712                .set_air_tap(Some(capture))
713                .map_err(|e| format!("802.11 capture: {e}"))
714        }
715
716        /// Record the Ethernet frames the station's MAC actually carried into
717        /// a pcap with link type 1, written as the run goes.
718        pub fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
719            let file =
720                std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
721            let capture =
722                std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::NetCapture::default()));
723            capture
724                .lock()
725                .map_err(|_| "the Ethernet capture lock is poisoned".to_string())?
726                .set_pcap(Box::new(file))
727                .map_err(|e| format!("{}: {e}", path.display()))?;
728            self.machine
729                .bus
730                .set_net_tap(capture)
731                .map_err(|e| format!("Ethernet capture: {e}"))
732        }
733
734        /// Replace the simulated network with a raw Ethernet seam: the guest's
735        /// frames come out of [`take_ethernet_frames`](Self::take_ethernet_frames)
736        /// and the host's go back in through
737        /// [`receive_ethernet_frame`](Self::receive_ethernet_frame).
738        pub fn set_ethernet_relay(&mut self, enabled: bool) -> Result<(), String> {
739            self.machine.bus.set_ethernet_relay(enabled)
740        }
741
742        /// Complete Ethernet frames (no FCS) in transmit order since the last
743        /// call. Empty outside relay mode.
744        pub fn take_ethernet_frames(&mut self) -> Vec<Vec<u8>> {
745            self.machine.bus.take_ethernet_frames()
746        }
747
748        /// Queue one 14..=1518-byte Ethernet frame (no FCS) for the guest.
749        pub fn receive_ethernet_frame(&mut self, frame: &[u8]) -> Result<(), String> {
750            self.machine.bus.receive_ethernet_frame(frame)
751        }
752
753        /// Put the circuit's Bluetooth advertisers on the air the chip's LE
754        /// controller hears.
755        ///
756        /// The ESP32-C3's link controller is derived from its mask ROM, so it
757        /// needs no ELF and can be installed here with `enable_ble_full(false)`.
758        /// The S3, C6 and classic ESP32 controllers are package images carried
759        /// inside the firmware ELF; Litz has no ELF plumbing for them, so those
760        /// chips answer with an error naming themselves rather than start a
761        /// controller that cannot scan.
762        ///
763        /// The beacons are translated straight into esp32sim's `Nearby` structs:
764        /// the part attributes have already been validated by the board, so the
765        /// string syntax `--ble-nearby` uses would only parse them a second time.
766        pub fn attach_ble(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
767            if config.is_empty() {
768                return Ok(());
769            }
770            // The list the controller hears is the circuit's, and it is not
771            // fixed for the run: a runtime advertiser changes it. Remember the
772            // generation the controller was given so a step can notice.
773            self.ble_seen = self
774                .board
775                .as_ref()
776                .map(|board| board.borrow().ble_generation())
777                .unwrap_or(0);
778            self.ble_attached = false;
779            // The advertisers reach a scanning guest through esp32sim's HCI
780            // controller, which is started by patching the guest's own
781            // controller task — an entry the machine can only find by symbol.
782            // The ROM-derived controller (`enable_ble_full`) is a different
783            // object and deliberately refuses the connection: sending the
784            // beacons to it would look like success and put nothing on the
785            // air, so the missing ELF is reported instead.
786            let Some(bytes) = self.elf.clone() else {
787                return Err(format!(
788                    "{} needs the firmware ELF to scan for a beacon: set [sim] elf, \
789                     because the Bluetooth controller is started through the guest's \
790                     symbol table",
791                    S::NAME
792                ));
793            };
794            let elf = esp_soc::elf::parse(&bytes)?;
795            self.machine
796                .bus
797                .enable_ble(&elf)
798                .map_err(|why| format!("{} cannot carry BLE beacons: {why}", S::NAME))?;
799            let beacons = nearby_list(&config.beacons);
800            self.machine.bus.ble_nearby(beacons)?;
801            self.ble_peers = config.beacons.clone();
802            self.ble_attached = true;
803            Ok(())
804        }
805
806        /// Replace the devices the controller's scan reports while it runs.
807        ///
808        /// esp32sim hands the list to the controller, and a scan in progress
809        /// hears the new one at once, so this is the runtime half of
810        /// [`EspChip::attach_ble`]. Litz calls it from `run` whenever a custom
811        /// chip starts or stops advertising, which is what makes a runtime
812        /// advertiser visible to a native ESP32 rather than only to another
813        /// wasm chip.
814        pub fn set_ble_nearby(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
815            if !self.ble_attached {
816                return Err("BLE is not enabled on this chip".into());
817            }
818            self.machine.bus.ble_nearby(nearby_list(&config.beacons))?;
819            self.ble_peers = config.beacons.clone();
820            self.ble_seen = self
821                .board
822                .as_ref()
823                .map(|board| board.borrow().ble_generation())
824                .unwrap_or(0);
825            Ok(())
826        }
827
828        /// Add one advertiser to the controller's scan list while it runs.
829        ///
830        /// esp32sim replaces its peer list wholesale, and a scan in progress
831        /// reports the new list at once, so the list this adapter was given is
832        /// the thing to append to. The method is inherent rather than on
833        /// [`litz_board::Chip`]: that trait is the runner's seam and has no
834        /// per-advertiser BLE entry point.
835        pub fn add_ble_peer(&mut self, beacon: &litz_ble::Beacon) -> Result<(), String> {
836            if !self.ble_attached {
837                return Err("BLE is not enabled on this chip".into());
838            }
839            self.ble_peers.push(beacon.clone());
840            let peers = nearby_list(&self.ble_peers);
841            if let Err(error) = self.machine.bus.ble_nearby(peers) {
842                self.ble_peers.pop();
843                return Err(error);
844            }
845            self.ble_seen = self
846                .board
847                .as_ref()
848                .map(|board| board.borrow().ble_generation())
849                .unwrap_or(0);
850            Ok(())
851        }
852
853        /// Drive the virtual central the controller's peer link exposes:
854        /// `connect`, `discover`, `read <handle>`, `write <handle> <hex>`,
855        /// `disconnect` or `central-stop`.
856        ///
857        /// The commands are the ones a phone would send to the guest's
858        /// peripheral, so a test can exercise the guest's GATT server and its
859        /// connection events without a second chip. The full link controller
860        /// (C3) models the 30 ms connection interval, channel hopping and ATT
861        /// transactions; the ROM-derived HCI controller answers with the
862        /// smaller command set and says so.
863        pub fn ble_command(&mut self, command: &str) -> Result<(), String> {
864            self.machine.bus.ble_command(command)
865        }
866
867        /// How many virtual-central commands have not completed yet.
868        pub fn ble_pending_commands(&self) -> usize {
869            self.machine.bus.ble_pending_commands()
870        }
871
872        /// The oldest kept `[ble]` line, without its prefix.
873        pub fn ble_log(&mut self) -> Option<String> {
874            self.machine.bus.ble_log_take()
875        }
876
877        /// Start the full C3 link controller, which models connection events,
878        /// the 30 ms interval and gap timing rather than only advertising and
879        /// scanning. `observe` keeps its `[ble-*]` lines for [`EspChip::ble_log`].
880        pub fn enable_full_ble(&mut self, observe: bool) -> Result<(), String> {
881            self.machine.bus.enable_ble_full(observe)
882        }
883
884        /// Simulated seconds since reset.
885        pub fn seconds(&self) -> f64 {
886            self.machine.seconds()
887        }
888
889        /// Run at most `steps` scheduling steps; the stop condition says why it ended.
890        pub fn run(&mut self, steps: u64) -> esp_soc::Stop {
891            // An ADC conversion inside the run must see the voltage the knob
892            // holds now, so the pads are refreshed before any instruction runs.
893            self.publish_analog();
894            // A capture timestamps network answers with the board's clock.
895            if let Some(board) = &self.board {
896                let now = board.borrow().now();
897                self.net_clock.set(now);
898                // A wasm chip on the same board may have started or stopped
899                // advertising since the last step. Mirror the air only when it
900                // changed: the list reaches a scan in progress at once.
901                if self.ble_attached {
902                    let (generation, air) = {
903                        let board = board.borrow();
904                        (board.ble_generation(), board.ble_air(self.board_index))
905                    };
906                    if generation != self.ble_seen {
907                        self.ble_seen = generation;
908                        let _ = self.machine.bus.ble_nearby(nearby_list(&air));
909                        self.ble_peers = air;
910                    }
911                }
912            }
913            self.machine.run(steps)
914        }
915
916        pub fn uart0(&self) -> &[u8] {
917            &self.machine.console.uart0
918        }
919
920        pub fn take_uart0(&mut self) -> Vec<u8> {
921            core::mem::take(&mut self.machine.console.uart0)
922        }
923    }
924
925    /// esp32sim's access-point syntax, built from the chip-independent
926    /// description so the parsing, validation and BSSID derivation stay in one
927    /// place (esp32sim's own).
928    fn ap_spec(ap: &litz_net::AccessPoint) -> String {
929        let mut spec = format!("ssid={},channel={}", ap.ssid, ap.channel);
930        if let Some(psk) = &ap.psk {
931            spec.push_str(&format!(",psk={psk}"));
932        }
933        if let Some(bssid) = ap.bssid {
934            spec.push_str(&format!(
935                ",bssid={}",
936                bssid
937                    .iter()
938                    .map(|b| format!("{b:02x}"))
939                    .collect::<Vec<_>>()
940                    .join(":")
941            ));
942        }
943        if let Some(epoch) = ap.epoch_s {
944            spec.push_str(&format!(",epoch={epoch}"));
945        }
946        spec
947    }
948
949    /// The controller's view of a set of advertisers, including the GATT
950    /// table a central discovers after connecting.
951    fn nearby_list(beacons: &[litz_ble::Beacon]) -> Vec<Nearby> {
952        beacons
953            .iter()
954            .map(|beacon| Nearby {
955                addr: beacon.address,
956                addr_type: beacon.address_type(),
957                rssi: beacon.rssi,
958                adv: beacon.adv.clone(),
959                scan_response: beacon.scan_response.clone(),
960                gatt: beacon
961                    .gatt
962                    .iter()
963                    .map(|service| esp_soc::ble::peer::GattService {
964                        uuid: service.uuid,
965                        characteristics: service
966                            .characteristics
967                            .iter()
968                            .map(|characteristic| esp_soc::ble::peer::GattCharacteristic {
969                                uuid: characteristic.uuid,
970                                flags: characteristic.flags,
971                                value: characteristic.value.clone(),
972                            })
973                            .collect(),
974                    })
975                    .collect(),
976            })
977            .collect()
978    }
979
980    fn nearby_spec(network: &litz_net::NearbyNetwork) -> String {
981        format!(
982            "ssid={},channel={},rssi={},secure={}",
983            network.ssid,
984            network.channel,
985            network.rssi,
986            u8::from(network.secure)
987        )
988    }
989
990    /// The ESP32-C3. Kept as a named alias so callers keep writing `C3`.
991    #[cfg(feature = "esp32c3")]
992    pub type C3 = EspChip<esp32c3::C3>;
993
994    #[cfg(feature = "esp32c3")]
995    impl EspChip<esp32c3::C3> {
996        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
997            let mut chip = Self::bare(mac, flash_size, c3_bus);
998            chip.gdb = Some(serve_gdb::<esp32c3::C3>);
999            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c3::C3>);
1000            chip
1001        }
1002    }
1003
1004    #[cfg(feature = "esp32c3")]
1005    fn c3_bus(
1006        mac: [u8; 6],
1007        flash: usize,
1008        board: Option<Rc<RefCell<LitzBoard>>>,
1009        index: u16,
1010        spi_rates: Rc<Cell<[u32; 2]>>,
1011    ) -> esp32c3::bus::SocBus {
1012        const CPU_HZ: u64 = esp32c3::periph::CPU_HZ;
1013        let mut bus = esp32c3::bus::SocBus::new(flash, mac);
1014        if let Some(board) = board {
1015            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1016            // The bus caches which callbacks the board wants and reconnects the
1017            // board's current input levels; both happen here.
1018            bus.attach_board_devices();
1019        }
1020        bus
1021    }
1022
1023    /// The ESP32-C6: the same adapter over the second RISC-V chip.
1024    #[cfg(feature = "esp32c6")]
1025    pub type C6 = EspChip<esp32c6::C6>;
1026
1027    #[cfg(feature = "esp32c6")]
1028    impl EspChip<esp32c6::C6> {
1029        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1030            let mut chip = Self::bare(mac, flash_size, c6_bus);
1031            chip.gdb = Some(serve_gdb::<esp32c6::C6>);
1032            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c6::C6>);
1033            chip
1034        }
1035    }
1036
1037    #[cfg(feature = "esp32c6")]
1038    fn c6_bus(
1039        mac: [u8; 6],
1040        flash: usize,
1041        board: Option<Rc<RefCell<LitzBoard>>>,
1042        index: u16,
1043        spi_rates: Rc<Cell<[u32; 2]>>,
1044    ) -> esp32c6::bus::SocBus {
1045        const CPU_HZ: u64 = esp32c6::periph::CPU_HZ;
1046        let mut bus = esp32c6::bus::SocBus::new(flash, mac);
1047        if let Some(board) = board {
1048            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1049            bus.attach_board_devices();
1050        }
1051        bus
1052    }
1053
1054    /// The classic ESP32 (Xtensa LX6, two cores).
1055    #[cfg(feature = "esp32")]
1056    pub type Esp32 = EspChip<esp32::Esp32>;
1057
1058    #[cfg(feature = "esp32")]
1059    impl EspChip<esp32::Esp32> {
1060        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1061            let mut chip = Self::bare(mac, flash_size, esp32_bus);
1062            chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1063            chip.spi_clock = Some(ESP32_SPI_CLOCKS);
1064            chip
1065        }
1066    }
1067
1068    #[cfg(feature = "esp32")]
1069    fn esp32_bus(
1070        mac: [u8; 6],
1071        flash: usize,
1072        board: Option<Rc<RefCell<LitzBoard>>>,
1073        index: u16,
1074        spi_rates: Rc<Cell<[u32; 2]>>,
1075    ) -> esp32::bus::SocBus {
1076        const CPU_HZ: u64 = esp32::periph::CPU_HZ;
1077        let mut bus = esp32::bus::SocBus::new(flash, mac);
1078        if let Some(board) = board {
1079            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1080            bus.attach_board_devices();
1081        }
1082        bus
1083    }
1084
1085    /// PSRAM the S3 adapter hands the bus. A board manifest does not carry a
1086    /// PSRAM size yet; the DevKitC-1 has 2 MiB and the chips tolerate more.
1087    #[cfg(feature = "esp32s3")]
1088    const S3_PSRAM: usize = 2 << 20;
1089
1090    /// The ESP32-S3 (Xtensa LX7).
1091    #[cfg(feature = "esp32s3")]
1092    pub type S3 = EspChip<esp32s3::S3>;
1093
1094    #[cfg(feature = "esp32s3")]
1095    impl EspChip<esp32s3::S3> {
1096        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1097            let mut chip = Self::bare(mac, flash_size, s3_bus);
1098            chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1099            chip.spi_clock = Some(S3_SPI_CLOCKS);
1100            chip
1101        }
1102    }
1103
1104    #[cfg(feature = "esp32s3")]
1105    fn s3_bus(
1106        mac: [u8; 6],
1107        flash: usize,
1108        board: Option<Rc<RefCell<LitzBoard>>>,
1109        index: u16,
1110        spi_rates: Rc<Cell<[u32; 2]>>,
1111    ) -> esp32s3::bus::SocBus {
1112        const CPU_HZ: u64 = esp32s3::periph::CPU_HZ;
1113        let mut bus = esp32s3::bus::SocBus::new(flash, S3_PSRAM, mac);
1114        if let Some(board) = board {
1115            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1116            bus.attach_board_devices();
1117        }
1118        bus
1119    }
1120
1121    /// The ESP32-P4 in its pre-rev-3 wafer, which is what `esp32p4::machine`
1122    /// builds. A rev-3 board can add a sibling alias over `P4Rev3`.
1123    #[cfg(feature = "esp32p4")]
1124    pub type P4 = EspChip<esp32p4::P4>;
1125
1126    #[cfg(feature = "esp32p4")]
1127    impl EspChip<esp32p4::P4> {
1128        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1129            let mut chip = Self::bare(mac, flash_size, p4_bus);
1130            chip.gdb = Some(serve_gdb::<esp32p4::P4>);
1131            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32p4::P4>);
1132            chip
1133        }
1134    }
1135
1136    #[cfg(feature = "esp32p4")]
1137    fn p4_bus(
1138        mac: [u8; 6],
1139        flash: usize,
1140        board: Option<Rc<RefCell<LitzBoard>>>,
1141        index: u16,
1142        spi_rates: Rc<Cell<[u32; 2]>>,
1143    ) -> esp32p4::bus::SocBus {
1144        const CPU_HZ: u64 = esp32p4::periph::CPU_HZ;
1145        let wafer = <esp32p4::RevLt3 as esp32p4::Revision>::WAFER;
1146        let mut bus = esp32p4::bus::SocBus::new(flash, mac, wafer);
1147        if let Some(board) = board {
1148            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1149            bus.attach_board_devices();
1150        }
1151        bus
1152    }
1153
1154    /// The ESP32-S31.
1155    #[cfg(feature = "esp32s31")]
1156    pub type S31 = EspChip<esp32s31::S31>;
1157
1158    #[cfg(feature = "esp32s31")]
1159    impl EspChip<esp32s31::S31> {
1160        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1161            let mut chip = Self::bare(mac, flash_size, s31_bus);
1162            chip.gdb = Some(serve_gdb::<esp32s31::S31>);
1163            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32s31::S31>);
1164            chip
1165        }
1166    }
1167
1168    #[cfg(feature = "esp32s31")]
1169    fn s31_bus(
1170        mac: [u8; 6],
1171        flash: usize,
1172        board: Option<Rc<RefCell<LitzBoard>>>,
1173        index: u16,
1174        spi_rates: Rc<Cell<[u32; 2]>>,
1175    ) -> esp32s31::SocBus {
1176        const CPU_HZ: u64 = esp32s31::periph::CPU_HZ;
1177        let mut bus = esp32s31::SocBus::new(flash, mac);
1178        if let Some(board) = board {
1179            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1180            bus.attach_board_devices();
1181        }
1182        bus
1183    }
1184
1185    /// One I2C target, as esp32sim's controller sees it.
1186    ///
1187    /// The device itself stays in `Board::buses`; this handle holds the shared
1188    /// board and an address, so handing it to esp32sim does not move the
1189    /// device out of the board and the board stays usable by tests and the
1190    /// host. Every callback borrows the board for the length of one byte.
1191    struct BoardI2cDevice {
1192        board: Rc<RefCell<LitzBoard>>,
1193        /// The board instance whose controller this is; two boards' `i2c0`
1194        /// are different buses.
1195        board_index: u16,
1196        controller: u8,
1197        address: u8,
1198        /// The phases of the transaction in flight, so the pins can be
1199        /// reconstructed when the STOP arrives. `esp32sim` reports one byte
1200        /// at a time and has no timestamp of its own.
1201        written: Vec<u8>,
1202        received: Vec<u8>,
1203        reading: bool,
1204        open: bool,
1205        /// Where the last observed transaction ended, so back-to-back
1206        /// transactions do not stack at one tick when the board never settled
1207        /// a pin between them.
1208        last_at: u64,
1209        /// When the firmware's controller started this transaction. The
1210        /// elapsed time is the configured SCL rate, which is what the
1211        /// reconstructed edges use.
1212        started_at: u64,
1213    }
1214
1215    impl EspI2cDevice for BoardI2cDevice {
1216        fn address(&self, _configured: u8) -> u8 {
1217            self.address
1218        }
1219
1220        fn start(&mut self, read: bool) -> bool {
1221            if !self.open {
1222                self.written.clear();
1223                self.received.clear();
1224                self.open = true;
1225                self.started_at = self.board.borrow().now();
1226            }
1227            self.reading = read;
1228            let mut board = self.board.borrow_mut();
1229            let Some(bus) = board
1230                .buses_mut()
1231                .i2c
1232                .get_mut(&(self.board_index, self.controller))
1233            else {
1234                return false;
1235            };
1236            let Some(device) = bus.device_mut(self.address) else {
1237                return false;
1238            };
1239            device.connect(read);
1240            true
1241        }
1242
1243        fn write(&mut self, byte: u8) -> bool {
1244            if !self.reading {
1245                self.written.push(byte);
1246            }
1247            let mut board = self.board.borrow_mut();
1248            let Some(bus) = board
1249                .buses_mut()
1250                .i2c
1251                .get_mut(&(self.board_index, self.controller))
1252            else {
1253                return false;
1254            };
1255            let Some(device) = bus.device_mut(self.address) else {
1256                return false;
1257            };
1258            device.write(byte)
1259        }
1260
1261        fn read(&mut self) -> u8 {
1262            let byte = {
1263                let mut board = self.board.borrow_mut();
1264                let Some(bus) = board
1265                    .buses_mut()
1266                    .i2c
1267                    .get_mut(&(self.board_index, self.controller))
1268                else {
1269                    return 0xff;
1270                };
1271                let Some(device) = bus.device_mut(self.address) else {
1272                    return 0xff;
1273                };
1274                device.read()
1275            };
1276            self.received.push(byte);
1277            byte
1278        }
1279
1280        fn stop(&mut self) {
1281            {
1282                let mut board = self.board.borrow_mut();
1283                let Some(bus) = board
1284                    .buses_mut()
1285                    .i2c
1286                    .get_mut(&(self.board_index, self.controller))
1287                else {
1288                    return;
1289                };
1290                if let Some(device) = bus.device_mut(self.address) {
1291                    device.stop();
1292                }
1293            }
1294            if self.open {
1295                let mut board = self.board.borrow_mut();
1296                let end = board.now();
1297                let at = self.started_at.max(self.last_at);
1298                let phases = 1
1299                    + self.written.len()
1300                    + if self.received.is_empty() {
1301                        0
1302                    } else {
1303                        1 + self.received.len()
1304                    };
1305                // The controller clocks each phase at the divider the firmware
1306                // programmed, so the transaction's own duration is the SCL
1307                // rate. Falling back to the last known rate keeps a
1308                // zero-duration model (a callback-only device) usable.
1309                let elapsed = end.saturating_sub(self.started_at);
1310                let hz = if elapsed > 0 {
1311                    (phases as u128 * 9 * 1_000_000_000 / u128::from(elapsed))
1312                        .clamp(1_000, 5_000_000) as u32
1313                } else {
1314                    board.i2c_hz(self.board_index, self.controller)
1315                };
1316                board.set_i2c_hz(self.board_index, self.controller, hz);
1317                board.observe_i2c(
1318                    self.board_index,
1319                    self.controller,
1320                    self.address,
1321                    &self.written,
1322                    &self.received,
1323                    at,
1324                );
1325                let period = 1_000_000_000 / u64::from(hz);
1326                self.last_at = (at + phases as u64 * 9 * period).max(end);
1327            }
1328            self.open = false;
1329            self.reading = false;
1330        }
1331    }
1332
1333    /// Where one chip keeps its GP-SPI clock dividers.
1334    ///
1335    /// The two Xtensa parts encode the same `APB / ((pre+1) * (n+1))` divider
1336    /// at the same bit positions, but the register offset and the width of the
1337    /// pre-divider differ: the classic ESP32 has 0x18 and 13 bits, the S3 0xC
1338    /// and 4 bits.
1339    #[derive(Clone, Copy)]
1340    struct SpiClockSpec {
1341        /// `(clock register, pre-divider shift, pre-divider mask)` for hosts 2 and 3.
1342        ports: [(u32, u32, u32); 2],
1343    }
1344
1345    #[cfg(feature = "esp32")]
1346    const ESP32_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1347        ports: [(0x3ff6_4018, 18, 0x1fff), (0x3ff6_5018, 18, 0x1fff)],
1348    };
1349
1350    #[cfg(feature = "esp32s3")]
1351    const S3_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1352        ports: [(0x6002_400c, 18, 0xf), (0x6002_500c, 18, 0xf)],
1353    };
1354
1355    /// Turns a firmware's GP-SPI clock-register write into the rate the board
1356    /// model reports for the next transfer.
1357    ///
1358    /// esp32sim's `spi_transfer` callback carries bytes, not a clock, so the
1359    /// programmed divider has to travel beside it. Watching MMIO is exact and
1360    /// cheap: only a register write ever changes the rate.
1361    struct SpiClockObserver {
1362        rates: Rc<Cell<[u32; 2]>>,
1363        spec: SpiClockSpec,
1364    }
1365
1366    impl<S: Soc> esp_soc::Observer<S> for SpiClockObserver {
1367        fn name(&self) -> &'static str {
1368            "litz-spi-clock"
1369        }
1370
1371        fn wants(&self) -> esp_soc::Wants {
1372            esp_soc::Wants::MMIO
1373        }
1374
1375        fn on_mmio(&mut self, _cx: &esp_soc::Ctx, _pc: u32, addr: u32, value: u32, write: bool) {
1376            if !write {
1377                return;
1378            }
1379            let Some(slot) = self.spec.ports.iter().position(|&(reg, ..)| reg == addr) else {
1380                return;
1381            };
1382            let (_, shift, mask) = self.spec.ports[slot];
1383            // SPI_CLK_EQU_SYSCLK bypasses both dividers; otherwise CLKCNT_N is
1384            // bits 17:12 and CLKDIV_PRE sits above it.
1385            let divider = if value & (1 << 31) != 0 {
1386                1
1387            } else {
1388                (((value >> shift) & mask) + 1) * (((value >> 12) & 0x3f) + 1)
1389            };
1390            let mut rates = self.rates.get();
1391            rates[slot] = (esp_periph::APB_HZ / u64::from(divider)) as u32;
1392            self.rates.set(rates);
1393        }
1394    }
1395
1396    /// `esp_soc::BoardModel` over a flattened Litz board.
1397    ///
1398    /// The bus reports the GPIO output latch and its enable mask; only enabled
1399    /// bits are strong drivers, everything else is high-impedance. Edges the
1400    /// board resolves back onto a chip pin leave through `take_edges`.
1401    struct LitzModel {
1402        board: Rc<RefCell<LitzBoard>>,
1403        /// The board instance whose pads this bus drives.
1404        index: u16,
1405        enabled: u64,
1406        output: u64,
1407        cycle: u64,
1408        releases: Vec<u8>,
1409        /// The chip's clock, to turn esp32sim's bus cycles into the nanoseconds
1410        /// the board's parts and the waveform measure time in.
1411        cpu_hz: u64,
1412        /// Each UART port's receive pin and baud, learned from the route on
1413        /// the chip's last transmitted byte. A board peer answers on the pin
1414        /// the chip listens to, and that is what an input has to name.
1415        uart_routes: BTreeMap<u8, (u8, u32)>,
1416        /// The GP-SPI rates the firmware programmed, shared with the MMIO
1417        /// observer. A chip without GP-SPI registers leaves it all zero.
1418        spi_rates: Rc<Cell<[u32; 2]>>,
1419    }
1420
1421    impl LitzModel {
1422        fn new(
1423            board: Rc<RefCell<LitzBoard>>,
1424            cpu_hz: u64,
1425            index: u16,
1426            spi_rates: Rc<Cell<[u32; 2]>>,
1427        ) -> Self {
1428            Self {
1429                board,
1430                index,
1431                enabled: 0,
1432                output: 0,
1433                cycle: 0,
1434                releases: Vec::new(),
1435                cpu_hz,
1436                uart_routes: BTreeMap::new(),
1437                spi_rates,
1438            }
1439        }
1440
1441        /// The rate the guest programmed for GP-SPI `host`, if it wrote one.
1442        fn spi_rate(&self, host: u8) -> Option<u32> {
1443            let slot = usize::from(host.checked_sub(2)?);
1444            let hz = *self.spi_rates.get().get(slot)?;
1445            (hz > 0).then_some(hz)
1446        }
1447
1448        fn ns(&self, cycle: u64) -> u64 {
1449            (u128::from(cycle) * 1_000_000_000 / u128::from(self.cpu_hz)) as u64
1450        }
1451
1452        /// The first bus cycle at or after `ns`, so a deadline is never
1453        /// rounded down into the past.
1454        fn cycles_for(&self, ns: u64) -> u64 {
1455            let cycles = u128::from(ns) * u128::from(self.cpu_hz);
1456            (cycles.div_ceil(1_000_000_000)) as u64
1457        }
1458    }
1459
1460    /// SSD1306 GDDRAM is page-major, LSB-first within a byte; a host PNG
1461    /// wants one RGB565 word per pixel.
1462    fn expand_monochrome(bytes: &[u8], width: u32, height: u32) -> Vec<u16> {
1463        let mut pixels = vec![0u16; (width * height) as usize];
1464        for page in 0..height.div_ceil(8) {
1465            for column in 0..width {
1466                let Some(byte) = bytes.get((page * width + column) as usize) else {
1467                    continue;
1468                };
1469                for bit in 0..8u32 {
1470                    let y = page * 8 + bit;
1471                    if y >= height {
1472                        break;
1473                    }
1474                    if byte & (1 << bit) != 0 {
1475                        pixels[(y * width + column) as usize] = 0xffff;
1476                    }
1477                }
1478            }
1479        }
1480        pixels
1481    }
1482
1483    /// The board fabric's frame type is the same data as the chip's wire frame, with the
1484    /// board's own fixed-size array and frame kind. Convert once at the boundary.
1485    fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1486        // The chip carries a classic CAN wire frame: eight data bytes at most.
1487        let mut data = [0u8; litz_board::bus::CAN_MAX_DATA];
1488        let len = usize::from(frame.len).min(frame.data.len());
1489        data[..len].copy_from_slice(&frame.data[..len]);
1490        litz_board::bus::CanFrame {
1491            id: frame.id,
1492            extended: frame.extended,
1493            rtr: frame.rtr,
1494            len: frame.len,
1495            data,
1496            kind: if frame.rtr {
1497                litz_board::bus::CanFrameKind::Remote
1498            } else {
1499                litz_board::bus::CanFrameKind::Classic
1500            },
1501        }
1502    }
1503
1504    impl BoardModel for LitzModel {
1505        fn name(&self) -> &'static str {
1506            "litz"
1507        }
1508
1509        fn gpio_output_at(
1510            &mut self,
1511            cycle: u64,
1512            changes: &[(u8, bool)],
1513            enabled: u64,
1514            output: u64,
1515        ) {
1516            // The callback's cycle is relative to the current quantum on some chips;
1517            // `advance_to` carries the absolute bus cycle. Take whichever is later
1518            // so a toggle is never dated before the run reached it.
1519            self.cycle = self.cycle.max(cycle);
1520            let now = self.ns(self.cycle);
1521            if std::env::var("LITZ_TRACE_DEBUG").is_ok() {
1522                eprintln!("DBG cycle={} now={}", self.cycle, now);
1523            }
1524            // An enable-only transition is not in `changes`, and it matters:
1525            // releasing an output must stop driving the net.
1526            let mut mask = (enabled ^ self.enabled) | (output ^ self.output);
1527            for &(pin, _) in changes {
1528                mask |= 1u64 << pin;
1529            }
1530            let mut board = self.board.borrow_mut();
1531            while mask != 0 {
1532                let pin = mask.trailing_zeros() as u8;
1533                mask &= mask - 1;
1534                let bit = 1u64 << pin;
1535                let drive = if enabled & bit != 0 {
1536                    if output & bit != 0 {
1537                        Drive::strong(Level::High)
1538                    } else {
1539                        Drive::strong(Level::Low)
1540                    }
1541                } else {
1542                    Drive::HIGH_Z
1543                };
1544                board.set_chip_output_on(self.index, pin, drive, now);
1545            }
1546            self.enabled = enabled;
1547            self.output = output;
1548        }
1549
1550        /// The first display on this board's buses, as RGB565. A colour TFT
1551        /// hands over its own buffer; a monochrome OLED is expanded one bit
1552        /// per pixel. The change counter comes from the panel, so a host can
1553        /// skip a frame that did not move.
1554        fn display(&self) -> Option<(u32, u32, Vec<u16>, u64)> {
1555            let board = self.board.borrow();
1556            let buses = board.buses();
1557            for (&(owner, _), i2c) in &buses.i2c {
1558                if owner != self.index {
1559                    continue;
1560                }
1561                for address in i2c.addresses() {
1562                    if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1563                        let (bytes, width, height) = oled.framebuffer();
1564                        return Some((
1565                            width,
1566                            height,
1567                            expand_monochrome(bytes, width, height),
1568                            oled.frame_version(),
1569                        ));
1570                    }
1571                }
1572            }
1573            for (&(owner, _), spi) in &buses.spi {
1574                if owner != self.index {
1575                    continue;
1576                }
1577                for select in spi.chip_selects() {
1578                    if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1579                        let (pixels, width, height) = tft.framebuffer();
1580                        return Some((width, height, pixels.to_vec(), tft.frame_version()));
1581                    }
1582                }
1583            }
1584            None
1585        }
1586
1587        /// Host touch from the browser or a scenario reaches the board's
1588        /// controller part; a board without one ignores it, exactly as a
1589        /// finger on a panel that is not there would.
1590        fn touch(&mut self, x: u16, y: u16, down: bool) {
1591            let _ = self.board.borrow_mut().touch_panel(x, y, down);
1592        }
1593
1594        fn display_version(&self) -> u64 {
1595            let board = self.board.borrow();
1596            let buses = board.buses();
1597            for (&(owner, _), i2c) in &buses.i2c {
1598                if owner != self.index {
1599                    continue;
1600                }
1601                for address in i2c.addresses() {
1602                    if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1603                        return oled.frame_version();
1604                    }
1605                }
1606            }
1607            for (&(owner, _), spi) in &buses.spi {
1608                if owner != self.index {
1609                    continue;
1610                }
1611                for select in spi.chip_selects() {
1612                    if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1613                        return tft.frame_version();
1614                    }
1615                }
1616            }
1617            0
1618        }
1619
1620        fn advance_to(&mut self, cycle: u64) {
1621            self.cycle = cycle;
1622            // A part that schedules its own edges (a rangefinder's ECHO, a
1623            // sensor's frame) has to be moved on the chip's clock, not the
1624            // board's wall clock. The board settles after every event, so the
1625            // edges this produces are already waiting in `take_edges`.
1626            let now = self.ns(cycle);
1627            self.board.borrow_mut().advance_to(now);
1628        }
1629
1630        fn next_deadline(&self) -> Option<u64> {
1631            // Pending inputs must reach the chip now, not at its next poll. A
1632            // part's next event is nanoseconds; the bus counts cycles.
1633            let board = self.board.borrow();
1634            let now = board.has_pending_inputs_on(self.index).then_some(0);
1635            let event = board.next_event().map(|at| self.cycles_for(at));
1636            match (now, event) {
1637                (Some(a), Some(b)) => Some(a.min(b)),
1638                (a, b) => a.or(b),
1639            }
1640        }
1641
1642        fn take_edges(&mut self) -> Vec<BoardEdge> {
1643            let cycle = self.cycle;
1644            let drained = self.board.borrow_mut().take_chip_inputs_on(self.index);
1645            // One board attach can queue a pin twice: the first settle leaves
1646            // it floating and the next drive, in the same batch, holds it. The
1647            // last level is the one the pad has, so a pin that ends driven is
1648            // not also released — releasing it after `set_input` would put the
1649            // pad back on its pull and lose the level that just arrived.
1650            let mut levels: BTreeMap<u8, Level> = BTreeMap::new();
1651            for (pin, level) in drained {
1652                levels.insert(pin, level);
1653            }
1654            let mut edges = Vec::new();
1655            for (pin, level) in levels {
1656                match level {
1657                    Level::High => edges.push(BoardEdge {
1658                        cycle,
1659                        pin,
1660                        level: true,
1661                    }),
1662                    Level::Low => edges.push(BoardEdge {
1663                        cycle,
1664                        pin,
1665                        level: false,
1666                    }),
1667                    Level::HighZ => self.releases.push(pin),
1668                }
1669            }
1670            edges
1671        }
1672
1673        fn released_inputs(&mut self) -> Vec<u8> {
1674            core::mem::take(&mut self.releases)
1675        }
1676
1677        fn input_levels(&self) -> Vec<(u8, bool)> {
1678            self.board
1679                .borrow()
1680                .input_levels_on(self.index)
1681                .into_iter()
1682                .filter_map(|(pin, level)| match level {
1683                    Level::High => Some((pin, true)),
1684                    Level::Low => Some((pin, false)),
1685                    Level::HighZ => None,
1686                })
1687                .collect()
1688        }
1689
1690        fn named_pin(&self, name: &str) -> Option<u8> {
1691            let board = self.board.borrow();
1692            let (index, pin) = board.named_pin_on(name)?;
1693            (index == self.index).then_some(pin)
1694        }
1695
1696        /// Every I2C target the board holds, as `(controller, address, device)`.
1697        ///
1698        /// The device boxes share the board rather than taking a device out of
1699        /// it, so `Board` remains the owner and stays usable after attach.
1700        fn i2c_devices(&mut self) -> Vec<(u8, u8, Box<dyn EspI2cDevice>)> {
1701            let board = self.board.borrow();
1702            let mut devices: Vec<(u8, u8)> = Vec::new();
1703            for (&(owner, controller), bus) in &board.buses().i2c {
1704                if owner != self.index {
1705                    continue;
1706                }
1707                for address in bus.addresses() {
1708                    devices.push((controller, address));
1709                }
1710            }
1711            drop(board);
1712            devices
1713                .into_iter()
1714                .map(|(controller, address)| {
1715                    let device: Box<dyn EspI2cDevice> = Box::new(BoardI2cDevice {
1716                        board: Rc::clone(&self.board),
1717                        board_index: self.index,
1718                        controller,
1719                        address,
1720                        written: Vec::new(),
1721                        received: Vec::new(),
1722                        reading: false,
1723                        open: false,
1724                        last_at: 0,
1725                        started_at: 0,
1726                    });
1727                    (controller, address, device)
1728                })
1729                .collect()
1730        }
1731
1732        fn uses_spi_pins(&self) -> bool {
1733            self.board
1734                .borrow()
1735                .buses()
1736                .spi
1737                .keys()
1738                .any(|&(owner, _)| owner == self.index)
1739        }
1740
1741        /// A transaction with no pin route: use the only device on the chip's
1742        /// controller, or the board's only device when the controller numbering
1743        /// differs between the board and the chip (a board names `spi0`, the
1744        /// C3 calls its GP-SPI host 2). No device or an ambiguous one floats.
1745        fn spi_transfer(&mut self, host: u8, tx: &[u8], rx_len: usize) -> Vec<u8> {
1746            let rate = self.spi_rate(host);
1747            let mut board = self.board.borrow_mut();
1748            let selected = board
1749                .buses()
1750                .spi_sole(self.index, host)
1751                .or_else(|| board.buses().spi_only_device(self.index));
1752            match selected {
1753                Some((controller, chip_select)) => {
1754                    // The waveform is reconstructed here, so the rate has to
1755                    // reach the board before the transaction does.
1756                    if let Some(hz) = rate {
1757                        board.set_spi_hz(self.index, controller, hz);
1758                    }
1759                    board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1760                }
1761                None => vec![0xff; rx_len],
1762            }
1763        }
1764
1765        /// A routed transaction: the asserted chip-select lines select the
1766        /// device, exactly as they do on the board.
1767        fn spi_transfer_pins(
1768            &mut self,
1769            host: u8,
1770            pins: SpiPins,
1771            tx: &[u8],
1772            rx_len: usize,
1773        ) -> Vec<u8> {
1774            let rate = self.spi_rate(host);
1775            let mut board = self.board.borrow_mut();
1776            match board.buses().spi_selected(self.index, pins.cs) {
1777                Some((controller, chip_select)) => {
1778                    if let Some(hz) = rate {
1779                        board.set_spi_hz(self.index, controller, hz);
1780                    }
1781                    board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1782                }
1783                None => vec![0xff; rx_len],
1784            }
1785        }
1786
1787        fn uses_uart_pins(&self) -> bool {
1788            self.board
1789                .borrow()
1790                .buses()
1791                .uart
1792                .keys()
1793                .any(|&(owner, _)| owner == self.index)
1794        }
1795
1796        /// A byte the chip transmitted reaches the peer on `route.port`. The
1797        /// route names the chip's receive pin, so remember it for `uart_rx`.
1798        fn uart_tx(&mut self, cycle: u64, route: UartRoute, byte: u8) {
1799            let now = self.ns(cycle);
1800            let port = route.port as u8;
1801            let baud = route
1802                .baud
1803                .unwrap_or(litz_board::runtime::OBSERVED_UART_BAUD);
1804            let mut board = self.board.borrow_mut();
1805            board.set_uart_baud(self.index, port, baud);
1806            board.uart_receive(self.index, port, now, &[byte]);
1807            drop(board);
1808            if let Some(pin) = route.rx_pin {
1809                self.uart_routes
1810                    .insert(port, (pin, route.baud.unwrap_or(115_200)));
1811            }
1812        }
1813
1814        /// Bytes the board's UART peers have ready, one input per port. The
1815        /// chip's last route supplies the pin and baud; before the chip has
1816        /// transmitted, the board's resolved wiring names the receive pin and
1817        /// the usual 115 200 baud is assumed. A port with neither is skipped.
1818        fn uart_rx(&mut self, cycle: u64) -> Vec<UartInput> {
1819            let now = self.ns(cycle);
1820            let mut board = self.board.borrow_mut();
1821            for (&port, &(_, baud)) in &self.uart_routes {
1822                board.set_uart_baud(self.index, port, baud);
1823            }
1824            let ports: Vec<(u8, Option<(u8, u32)>)> = board
1825                .buses()
1826                .uart
1827                .keys()
1828                .filter(|(owner, _)| *owner == self.index)
1829                .map(|&(_, port)| {
1830                    let wired = board
1831                        .flat()
1832                        .buses
1833                        .uart
1834                        .get(&(self.index, port))
1835                        .map(|bus| (bus.chip_rx, 115_200));
1836                    (port, self.uart_routes.get(&port).copied().or(wired))
1837                })
1838                .collect();
1839            let mut inputs = Vec::new();
1840            for (port, route) in ports {
1841                let Some((pin, baud)) = route else { continue };
1842                let data = board.uart_poll(self.index, port, now);
1843                if !data.is_empty() {
1844                    inputs.push(UartInput::new(pin, baud, data));
1845                }
1846            }
1847            inputs
1848        }
1849
1850        /// The chip completed a TWAI transmission: put it on the board's shared CAN wire.
1851        /// The node is the board index, so two MCUs on one diagram are distinct endpoints.
1852        fn can_tx(&mut self, _host: u8, frame: &[u8]) {
1853            let Some(frame) = esp_soc::board::CanFrame::decode(frame) else {
1854                return;
1855            };
1856            let mut board = self.board.borrow_mut();
1857            let can = board.buses_mut().can_mut();
1858            can.attach(self.index);
1859            let _ = can.transmit(self.index, board_can_frame(&frame));
1860        }
1861
1862        /// The chip's TWAI receive buffer is empty: hand it the next frame addressed to this
1863        /// board's node. Attaching lazily keeps a CAN-free diagram unchanged; nothing is
1864        /// queued for a board that never drives TWAI.
1865        fn can_take(&mut self, _host: u8) -> Option<Vec<u8>> {
1866            let mut board = self.board.borrow_mut();
1867            let can = board.buses_mut().can_mut();
1868            can.attach(self.index);
1869            let frame = can.take(self.index)?;
1870            // The chip's wire frame holds only the eight classic CAN bytes.
1871            let mut data = [0u8; esp_soc::board::CAN_MAX_DATA];
1872            let len = usize::from(frame.len).min(data.len());
1873            data[..len].copy_from_slice(&frame.data[..len]);
1874            Some(
1875                esp_soc::board::CanFrame {
1876                    id: frame.id,
1877                    extended: frame.extended,
1878                    rtr: frame.rtr || frame.kind == litz_board::bus::CanFrameKind::Remote,
1879                    len: frame.len,
1880                    data,
1881                }
1882                .encode()
1883                .to_vec(),
1884            )
1885        }
1886    }
1887
1888    /// The [`litz_board::Chip`] view of this adapter: what a runner needs, with
1889    /// nothing esp32sim-specific in the signature.
1890    impl<S: Soc> litz_board::Chip for EspChip<S> {
1891        fn info(&self) -> litz_board::ChipInfo {
1892            litz_board::ChipInfo {
1893                name: S::NAME.into(),
1894                cpu_hz: S::CPU_HZ,
1895                flash: litz_board::FlashLayout {
1896                    size: self.flash as u64,
1897                    bootloader: S::BOOTLOADER_OFFSET as u64,
1898                    partition_table: 0x8000,
1899                    app: 0x1_0000,
1900                },
1901            }
1902        }
1903
1904        fn load_image(
1905            &mut self,
1906            kind: litz_board::ImageKind,
1907            offset: u64,
1908            bytes: &[u8],
1909        ) -> Result<(), String> {
1910            match kind {
1911                litz_board::ImageKind::Rom => self.load_rom(bytes),
1912                litz_board::ImageKind::Bootloader => {
1913                    self.bootloader_loaded = true;
1914                    self.write_flash(offset as usize, bytes)
1915                }
1916                _ => self.write_flash(offset as usize, bytes),
1917            }
1918        }
1919
1920        fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
1921            EspChip::set_psram_size(self, bytes)
1922        }
1923
1924        fn boot(&mut self) -> Result<u32, String> {
1925            if self.bootloader_loaded {
1926                // The bootloader finds the application itself; starting the app
1927                // directly would skip it.
1928                return Ok(0);
1929            }
1930            let app = self.info().flash.app as usize;
1931            self.boot_app(app)
1932        }
1933
1934        fn schedule(&mut self, inputs: Vec<litz_board::Input>) -> Result<(), String> {
1935            let mut text = String::new();
1936            for input in inputs {
1937                match input {
1938                    litz_board::Input::Gpio { at_ns, pin, level } => {
1939                        let seconds = at_ns as f64 / 1e9;
1940                        let bit = u8::from(level == Level::High);
1941                        text.push_str(&format!("{seconds:.6} gpio {pin} {bit}\n"));
1942                    }
1943                    litz_board::Input::Uart { at_ns, bytes } => {
1944                        let seconds = at_ns as f64 / 1e9;
1945                        let text_in = String::from_utf8_lossy(&bytes);
1946                        // The script format appends the newline itself.
1947                        text.push_str(&format!(
1948                            "{seconds:.6} uart0 {}\n",
1949                            text_in.trim_end_matches('\n')
1950                        ));
1951                    }
1952                }
1953            }
1954            if text.is_empty() {
1955                Ok(())
1956            } else {
1957                self.load_script(&text)
1958            }
1959        }
1960
1961        fn run(&mut self, budget_cycles: u64) -> litz_board::RunResult {
1962            let stop = match EspChip::run(self, budget_cycles) {
1963                esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
1964                esp_soc::Stop::Halted => litz_board::Stop::Halted,
1965                esp_soc::Stop::SwReset => litz_board::Stop::Reset,
1966                esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
1967                _ => litz_board::Stop::Idle,
1968            };
1969            litz_board::RunResult {
1970                cycles: budget_cycles,
1971                stop,
1972            }
1973        }
1974
1975        fn seconds(&self) -> f64 {
1976            EspChip::seconds(self)
1977        }
1978
1979        fn write_console(&mut self, bytes: &[u8]) {
1980            // Both interpreters the runner speaks to read their console from
1981            // UART0. Mirroring the bytes onto the USB block as well splits one
1982            // paste across two input paths and the guest sees it twice.
1983            self.write_serial(bytes);
1984        }
1985
1986        fn take_console(&mut self) -> Vec<u8> {
1987            let mut bytes = self.take_uart0();
1988            // The machine's own drain already moved USB output into this
1989            // backlog; a chip without a USB peripheral leaves it empty. A
1990            // build that logs to both consoles sends the same bytes down each,
1991            // so an identical copy is the same console message, not a second
1992            // one.
1993            let usb = core::mem::take(&mut self.machine.console.usb);
1994            if usb != bytes {
1995                bytes.extend(usb);
1996            }
1997            bytes
1998        }
1999
2000        fn state(&self, part: &str) -> Option<PartState> {
2001            EspChip::state(self, part)
2002        }
2003
2004        fn press(&mut self, part: &str, pressed: bool) -> bool {
2005            EspChip::press(self, part, pressed)
2006        }
2007
2008        fn set_control(&mut self, part: &str, value: u16) -> bool {
2009            EspChip::set_control(self, part, value)
2010        }
2011
2012        fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2013            EspChip::set_named_control(self, part, name, value)
2014        }
2015
2016        fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2017            EspChip::part_pin_level(self, part, pin)
2018        }
2019
2020        fn gpio_level(&self, gpio: u8) -> Option<Level> {
2021            EspChip::gpio_level(self, gpio)
2022        }
2023
2024        fn conflicts(&self) -> Vec<Conflict> {
2025            EspChip::conflicts(self)
2026        }
2027
2028        fn start_trace(&mut self) {
2029            if let Some(board) = self.board.as_ref() {
2030                board.borrow_mut().start_trace();
2031            }
2032        }
2033
2034        fn vcd(&self) -> String {
2035            self.board
2036                .as_ref()
2037                .map(|board| board.borrow().vcd())
2038                .unwrap_or_default()
2039        }
2040
2041        fn break_at(&mut self, pc: u32) {
2042            EspChip::break_at(self, pc);
2043        }
2044
2045        fn registers(&self) -> String {
2046            self.machine.dump_regs()
2047        }
2048
2049        fn report(&mut self) -> Vec<String> {
2050            EspChip::reports(self)
2051        }
2052
2053        fn enable_coverage(&mut self) {
2054            EspChip::enable_coverage(self);
2055        }
2056
2057        fn display(&mut self) -> Option<(u32, u32, Vec<u16>, u64)> {
2058            self.machine.bus.board().display()
2059        }
2060
2061        fn display_version(&mut self) -> u64 {
2062            self.machine.bus.board().display_version()
2063        }
2064
2065        fn save_display(&mut self, path: &std::path::Path) -> Result<(), String> {
2066            crate::screenshot::capture(self, path)
2067        }
2068
2069        fn save_part_display(&mut self, part: &str, path: &std::path::Path) -> Result<(), String> {
2070            let Some(board) = &self.board else {
2071                return Err("this chip is not attached to a board".into());
2072            };
2073            let image = board
2074                .borrow()
2075                .part_framebuffer(part)
2076                .ok_or_else(|| format!("part {part:?} is not a display with a framebuffer"))?;
2077            std::fs::write(path, image.to_png()).map_err(|e| format!("{}: {e}", path.display()))
2078        }
2079
2080        fn sample_heap(&mut self) -> Result<u32, String> {
2081            EspChip::sample_heap(self)
2082        }
2083
2084        fn touch(&mut self, x: u16, y: u16, down: bool) -> Result<(), String> {
2085            let Some(board) = &self.board else {
2086                return Err("this chip is not attached to a board".into());
2087            };
2088            board.borrow_mut().touch_panel(x, y, down)
2089        }
2090
2091        fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2092            EspChip::start_air_capture(self, path)
2093        }
2094
2095        fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2096            EspChip::start_ethernet_capture(self, path)
2097        }
2098
2099        fn attach_host_gateway(&mut self, forwards: &[String]) -> Result<Vec<String>, String> {
2100            #[cfg(not(target_arch = "wasm32"))]
2101            {
2102                if forwards.is_empty() {
2103                    EspChip::attach_host_nat(self, false).map(|()| Vec::new())
2104                } else {
2105                    EspChip::attach_host_forwards(self, forwards, false)
2106                }
2107            }
2108            #[cfg(target_arch = "wasm32")]
2109            {
2110                let _ = forwards;
2111                Err("the browser build has no host sockets".into())
2112            }
2113        }
2114
2115        fn debug_available(&self) -> bool {
2116            use emu_core::Core;
2117            self.machine_ref()
2118                .cores
2119                .first()
2120                .map(|core| {
2121                    let mut names = Vec::new();
2122                    core.regs(&mut names);
2123                    names.iter().any(|(name, _)| *name == "ra")
2124                        && names.iter().any(|(name, _)| *name == "sp")
2125                })
2126                .unwrap_or(false)
2127        }
2128
2129        fn debug_pc(&self) -> Option<u32> {
2130            use emu_core::Core;
2131            self.machine_ref().cores.first().map(|core| core.pc())
2132        }
2133
2134        fn debug_register_file(&self) -> Option<[u32; 33]> {
2135            use emu_core::Core;
2136            let core = self.machine_ref().cores.first()?;
2137            let mut names = Vec::new();
2138            core.regs(&mut names);
2139            if !names.iter().any(|(name, _)| *name == "ra") {
2140                return None;
2141            }
2142            const RV: [&str; 32] = [
2143                "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2",
2144                "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
2145                "s10", "s11", "t3", "t4", "t5", "t6",
2146            ];
2147            let mut file = [0u32; 33];
2148            for (index, want) in RV.iter().enumerate() {
2149                if let Some((_, value)) = names.iter().find(|(name, _)| name == want) {
2150                    file[index] = *value;
2151                }
2152            }
2153            file[32] = core.pc();
2154            Some(file)
2155        }
2156
2157        fn debug_read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
2158            if len == 0 {
2159                return Vec::new();
2160            }
2161            let start = addr & !3;
2162            let skip = (addr - start) as usize;
2163            let words = (skip + len).div_ceil(4);
2164            let text = self.machine_mut().peek(start, words);
2165            let mut bytes = Vec::with_capacity(words * 4);
2166            for line in text.lines() {
2167                let Some((_, word)) = line.split_once(": ") else {
2168                    break;
2169                };
2170                let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
2171                    break;
2172                };
2173                bytes.extend_from_slice(&word.to_le_bytes());
2174            }
2175            if bytes.len() < skip {
2176                return Vec::new();
2177            }
2178            let end = (skip + len).min(bytes.len());
2179            bytes[skip..end].to_vec()
2180        }
2181
2182        fn debug_disassemble(&mut self, addr: u32, count: usize) -> String {
2183            self.disassemble(addr, count)
2184        }
2185
2186        fn debug_set_breakpoints(&mut self, pcs: &[u32]) {
2187            self.machine_mut().set_breakpoints(pcs.to_vec());
2188        }
2189
2190        fn debug_step(&mut self) -> Option<litz_board::Stop> {
2191            Some(match self.machine_mut().step_one() {
2192                esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2193                esp_soc::Stop::Halted => litz_board::Stop::Halted,
2194                esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2195                esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2196                _ => litz_board::Stop::Idle,
2197            })
2198        }
2199
2200        fn debug(&mut self) -> Option<&mut dyn litz_board::ChipDebug> {
2201            Some(self)
2202        }
2203    }
2204
2205    impl<S: Soc> litz_board::ChipDebug for EspChip<S> {
2206        fn serve(&mut self, port: u16) -> Result<(), String> {
2207            self.gdb_serve(port)
2208        }
2209
2210        fn report(&mut self) -> String {
2211            self.machine.dump_regs()
2212        }
2213    }
2214
2215    #[cfg(all(test, feature = "esp32c3"))]
2216    mod ble_peers {
2217        use super::*;
2218
2219        fn beacon() -> litz_ble::Beacon {
2220            litz_ble::Beacon {
2221                name: Some("late".into()),
2222                services: Vec::new(),
2223                address: [0x04, 0x03, 0x02, 0x01, 0xaa, 0xc4],
2224                rssi: -42,
2225                adv: vec![2, 1, 6, 6, 9, b'l', b'a', b't', b'e'],
2226                scan_response: Vec::new(),
2227                gatt: Vec::new(),
2228            }
2229        }
2230
2231        /// A scan enabled before the peer arrives hears it on the next report.
2232        /// The controller is stood up just far enough for `ble_nearby` to
2233        /// accept a list: firmware assets are not needed to test the list.
2234        #[test]
2235        fn a_peer_added_at_runtime_reaches_a_live_scan() {
2236            let mut chip = C3::new([0x24, 0x0a, 0xc4, 0x00, 0x01, 0x10], 4 << 20);
2237            assert_eq!(
2238                chip.add_ble_peer(&beacon()).unwrap_err(),
2239                "BLE is not enabled on this chip"
2240            );
2241            chip.machine_mut().bus.ble.hooks.push(0);
2242            chip.machine_mut().bus.ble.lines.keep();
2243            chip.ble_attached = true;
2244
2245            // LE Set Scan Enable: enabled, passive.
2246            chip.machine_mut()
2247                .bus
2248                .ble
2249                .session
2250                .send(&[1, 0x0c, 0x20, 2, 1, 0]);
2251            chip.machine_mut().bus.ble.session.drain_log();
2252
2253            chip.add_ble_peer(&beacon())
2254                .expect("the scan accepts the list");
2255            assert_eq!(chip.ble_peers.len(), 1);
2256            let line = chip.ble_log().expect("the controller logged a report");
2257            assert!(line.contains("scan report"), "{line}");
2258            assert!(line.contains("c4:aa:01:02:03:04"), "{line}");
2259        }
2260    }
2261}
2262
2263const PLIC_AND_RV_MAP: [MemoryRegion; 6] = [
2264    MemoryRegion::new("irom", 0x4200_0000, 0x0040_0000),
2265    MemoryRegion::new("drom", 0x3C00_0000, 0x0040_0000),
2266    MemoryRegion::new("dram", 0x3FC8_0000, 0x0004_0000),
2267    MemoryRegion::new("irom-dram", 0x4037_C000, 0x0000_8000),
2268    MemoryRegion::new("peripherals", 0x6000_0000, 0x0010_0000),
2269    MemoryRegion::new("rtc", 0x5000_0000, 0x0001_0000),
2270];