1#![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#[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
44pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Chip {
73 Esp32C3,
75 Esp32C6,
77 Esp32H2,
79}
80
81#[derive(Clone, Copy, Debug)]
83pub struct FlashLayout {
84 pub size: u32,
85 pub bootloader_offset: u32,
87 pub partition_table_offset: u32,
89 pub app_offset: u32,
91}
92
93impl Chip {
94 pub const fn memory_map(self) -> &'static [MemoryRegion] {
95 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#[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 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 pub struct EspChip<S: Soc> {
158 machine: Machine<S>,
159 board: Option<Rc<RefCell<LitzBoard>>>,
160 mac: [u8; 6],
163 flash: usize,
164 bus_for: BusFactory<S>,
165 bootloader_loaded: bool,
168 analog: Vec<(u8, f32)>,
171 elf: Option<Vec<u8>>,
176 gdb: Option<GdbServeFn<S>>,
181 guest_call: Option<GuestCall<S>>,
185 board_index: u16,
188 net_clock: Rc<Cell<u64>>,
191 ble_attached: bool,
194 ble_seen: u64,
196 ble_peers: Vec<litz_ble::Beacon>,
199 spi_clock: Option<SpiClockSpec>,
204 spi_rates: Rc<Cell<[u32; 2]>>,
207 }
208
209 pub type GdbServeFn<S> = fn(&mut EspChip<S>, u16) -> Result<(), String>;
211
212 pub type GuestCall<S> = fn(&mut EspChip<S>, u32) -> Result<u32, String>;
216
217 #[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 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 machine.vq_max = 1;
275 machine.bb_max = 1;
276 machine.console.capture = true;
279 machine
280 }
281
282 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 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 if let Some(bytes) = &self.elf {
311 let _ = self.machine.add_symbols(bytes);
312 }
313 self.install_spi_observer();
314 self
315 }
316
317 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn load_rom(&mut self, rom_elf: &[u8]) -> Result<(), String> {
502 self.machine.load_rom(rom_elf)
503 }
504
505 pub fn write_flash(&mut self, offset: usize, data: &[u8]) -> Result<(), String> {
508 self.machine.write_flash(offset, data)
509 }
510
511 pub fn boot_app(&mut self, app_off: usize) -> Result<u32, String> {
514 self.machine.boot_app(app_off)
515 }
516
517 pub fn load_script(&mut self, text: &str) -> Result<(), String> {
520 self.machine.load_script(text)
521 }
522
523 pub fn add_symbols(&mut self, elf: &[u8]) -> Result<(), String> {
526 self.machine.add_symbols(elf)
527 }
528
529 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 pub fn registers(&self) -> String {
537 self.machine.dump_regs()
538 }
539
540 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 pub fn reports(&mut self) -> Vec<String> {
551 self.machine.reports().lines().map(str::to_string).collect()
552 }
553
554 pub fn symbol_addr(&self, name: &str) -> Option<u32> {
558 self.machine.sym_addr(name)
559 }
560
561 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 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 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 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 #[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 #[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 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 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 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 pub fn set_ethernet_relay(&mut self, enabled: bool) -> Result<(), String> {
739 self.machine.bus.set_ethernet_relay(enabled)
740 }
741
742 pub fn take_ethernet_frames(&mut self) -> Vec<Vec<u8>> {
745 self.machine.bus.take_ethernet_frames()
746 }
747
748 pub fn receive_ethernet_frame(&mut self, frame: &[u8]) -> Result<(), String> {
750 self.machine.bus.receive_ethernet_frame(frame)
751 }
752
753 pub fn attach_ble(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
767 if config.is_empty() {
768 return Ok(());
769 }
770 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 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 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 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 pub fn ble_command(&mut self, command: &str) -> Result<(), String> {
864 self.machine.bus.ble_command(command)
865 }
866
867 pub fn ble_pending_commands(&self) -> usize {
869 self.machine.bus.ble_pending_commands()
870 }
871
872 pub fn ble_log(&mut self) -> Option<String> {
874 self.machine.bus.ble_log_take()
875 }
876
877 pub fn enable_full_ble(&mut self, observe: bool) -> Result<(), String> {
881 self.machine.bus.enable_ble_full(observe)
882 }
883
884 pub fn seconds(&self) -> f64 {
886 self.machine.seconds()
887 }
888
889 pub fn run(&mut self, steps: u64) -> esp_soc::Stop {
891 self.publish_analog();
894 if let Some(board) = &self.board {
896 let now = board.borrow().now();
897 self.net_clock.set(now);
898 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 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 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 #[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 bus.attach_board_devices();
1019 }
1020 bus
1021 }
1022
1023 #[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 #[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 #[cfg(feature = "esp32s3")]
1088 const S3_PSRAM: usize = 2 << 20;
1089
1090 #[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 #[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 #[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 struct BoardI2cDevice {
1192 board: Rc<RefCell<LitzBoard>>,
1193 board_index: u16,
1196 controller: u8,
1197 address: u8,
1198 written: Vec<u8>,
1202 received: Vec<u8>,
1203 reading: bool,
1204 open: bool,
1205 last_at: u64,
1209 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 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 #[derive(Clone, Copy)]
1340 struct SpiClockSpec {
1341 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 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 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 struct LitzModel {
1402 board: Rc<RefCell<LitzBoard>>,
1403 index: u16,
1405 enabled: u64,
1406 output: u64,
1407 cycle: u64,
1408 releases: Vec<u8>,
1409 cpu_hz: u64,
1412 uart_routes: BTreeMap<u8, (u8, u32)>,
1416 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 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 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 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 fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1486 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 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 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 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 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 let now = self.ns(cycle);
1627 self.board.borrow_mut().advance_to(now);
1628 }
1629
1630 fn next_deadline(&self) -> Option<u64> {
1631 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.write_serial(bytes);
1984 }
1985
1986 fn take_console(&mut self) -> Vec<u8> {
1987 let mut bytes = self.take_uart0();
1988 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 #[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 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];