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 pwm: BTreeMap<u8, f64>,
174 elf: Option<Vec<u8>>,
179 gdb: Option<GdbServeFn<S>>,
184 guest_call: Option<GuestCall<S>>,
188 board_index: u16,
191 net_clock: Rc<Cell<u64>>,
194 ble_attached: bool,
197 ble_seen: u64,
199 ble_peers: Vec<litz_ble::Beacon>,
202 powered: bool,
205 off_ns: u64,
209 spi_clock: Option<SpiClockSpec>,
214 spi_rates: Rc<Cell<[u32; 2]>>,
217 }
218
219 pub type GdbServeFn<S> = fn(&mut EspChip<S>, u16) -> Result<(), String>;
221
222 pub type GuestCall<S> = fn(&mut EspChip<S>, u32) -> Result<u32, String>;
226
227 #[cfg(any(
230 feature = "esp32c3",
231 feature = "esp32c6",
232 feature = "esp32p4",
233 feature = "esp32s31"
234 ))]
235 fn serve_gdb<S: crate::debug::Rv32Chip>(
236 chip: &mut EspChip<S>,
237 port: u16,
238 ) -> Result<(), String> {
239 crate::gdb::serve(chip, port)
240 }
241
242 impl<S: Soc> EspChip<S> {
243 fn bare(mac: [u8; 6], flash: usize, bus_for: BusFactory<S>) -> Self {
246 let spi_rates = Rc::new(Cell::new([0; 2]));
247 let machine = Self::build(mac, flash, bus_for, None, 0, Rc::clone(&spi_rates));
248 Self {
249 machine,
250 board: None,
251 mac,
252 flash,
253 bus_for,
254 bootloader_loaded: false,
255 analog: Vec::new(),
256 pwm: BTreeMap::new(),
257 elf: None,
258 gdb: None,
259 guest_call: None,
260 board_index: 0,
261 powered: true,
262 off_ns: 0,
263 net_clock: Rc::new(Cell::new(0)),
264 ble_attached: false,
265 ble_seen: 0,
266 ble_peers: Vec::new(),
267 spi_clock: None,
268 spi_rates,
269 }
270 }
271
272 fn build(
273 mac: [u8; 6],
274 flash: usize,
275 bus_for: BusFactory<S>,
276 board: Option<Rc<RefCell<LitzBoard>>>,
277 index: u16,
278 spi_rates: Rc<Cell<[u32; 2]>>,
279 ) -> Machine<S> {
280 let mut machine = Machine::new(mac, bus_for(mac, flash, board, index, spi_rates));
281 machine.vq_max = 1;
288 machine.bb_max = 1;
289 machine.console.capture = true;
292 machine
293 }
294
295 pub fn with_board(self, board: LitzBoard) -> Self {
298 let shared = Rc::new(RefCell::new(board));
299 self.with_shared_board(shared, 0)
300 }
301
302 pub fn with_shared_board(mut self, board: Rc<RefCell<LitzBoard>>, index: u16) -> Self {
310 self.machine = Self::build(
311 self.mac,
312 self.flash,
313 self.bus_for,
314 Some(Rc::clone(&board)),
315 index,
316 Rc::clone(&self.spi_rates),
317 );
318 self.board = Some(board);
319 self.board_index = index;
320 if let Some(bytes) = &self.elf {
324 let _ = self.machine.add_symbols(bytes);
325 }
326 self.install_spi_observer();
327 self
328 }
329
330 fn install_spi_observer(&mut self) {
340 if self.board.is_none() {
341 return;
342 }
343 let Some(spec) = self.spi_clock else {
344 return;
345 };
346 if self.machine.has_observer("litz-spi-clock") {
347 return;
348 }
349 self.machine.add_observer(Box::new(SpiClockObserver {
350 rates: Rc::clone(&self.spi_rates),
351 spec,
352 }));
353 }
354
355 pub(crate) fn machine_ref(&self) -> &Machine<S> {
358 &self.machine
359 }
360
361 pub(crate) fn machine_mut(&mut self) -> &mut Machine<S> {
362 &mut self.machine
363 }
364
365 pub fn gdb_serve(&mut self, port: u16) -> Result<(), String> {
368 match self.gdb {
369 Some(serve) => serve(self, port),
370 None => Err(format!(
371 "{} has no GDB target: only the RISC-V chips describe a register file",
372 S::NAME
373 )),
374 }
375 }
376
377 pub fn with_elf(mut self, bytes: &[u8]) -> Result<Self, String> {
386 self.machine.add_symbols(bytes)?;
387 self.elf = Some(bytes.to_vec());
388 Ok(self)
389 }
390
391 pub fn has_bootloader(&self) -> bool {
394 self.bootloader_loaded
395 }
396
397 pub fn board(&self) -> Option<&Rc<RefCell<LitzBoard>>> {
398 self.board.as_ref()
399 }
400
401 pub fn board_model(&mut self) -> &mut dyn BoardModel {
405 self.machine.bus.board()
406 }
407
408 pub fn state(&self, part: &str) -> Option<PartState> {
409 self.board.as_ref()?.borrow().state(part)
410 }
411
412 pub fn press(&mut self, part: &str, pressed: bool) -> bool {
416 let Some(board) = self.board.as_ref() else {
417 return false;
418 };
419 let now = (self.machine.seconds() * 1e9) as u64;
420 board.borrow_mut().press(part, pressed, now)
421 }
422
423 pub fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
428 self.machine.bus.set_psram_size(bytes)
429 }
430
431 pub fn set_control(&mut self, part: &str, permille: u16) -> bool {
432 let Some(board) = self.board.as_ref() else {
433 return false;
434 };
435 let now = (self.machine.seconds() * 1e9) as u64;
436 board.borrow_mut().set_control(part, permille, now)
437 }
438
439 pub fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
441 let Some(board) = self.board.as_ref() else {
442 return false;
443 };
444 let now = (self.machine.seconds() * 1e9) as u64;
445 board.borrow_mut().set_named_control(part, name, value, now)
446 }
447
448 pub fn write_serial(&mut self, bytes: &[u8]) {
451 self.machine.bus.uart_input(0, bytes);
452 *self.machine.bus.irq_dirty() = true;
453 }
454
455 pub fn analog_inputs(&self) -> Vec<(u8, f32)> {
457 self.board
458 .as_ref()
459 .map(|b| b.borrow().analog_inputs_on(self.board_index))
460 .unwrap_or_default()
461 }
462
463 fn publish_analog(&mut self) {
472 let Some(board) = self.board.as_ref() else {
473 return;
474 };
475 let now = board.borrow().analog_inputs();
476 for &(gpio, volts) in &now {
477 let unchanged = self
478 .analog
479 .iter()
480 .any(|&(pin, v)| pin == gpio && v == volts);
481 if !unchanged {
482 self.machine
483 .bus
484 .analog_set(gpio, esp_periph::AnalogSource::Const(volts));
485 }
486 }
487 self.analog = now;
488 }
489
490 fn publish_pwm(&mut self) {
494 let Some(board) = self.board.clone() else {
495 return;
496 };
497 let mut next = BTreeMap::new();
498 for pin in 0..=48u8 {
499 if let Some((_, count)) = self.machine.bus.pwm_output(pin) {
500 next.insert(pin, f64::from(count) / 65535.0);
501 }
502 }
503 if next == self.pwm {
504 return;
505 }
506 let now = (self.seconds() * 1e9) as u64;
507 let mut board = board.borrow_mut();
508 for &pin in self.pwm.keys() {
509 if !next.contains_key(&pin) {
510 board.set_chip_pwm_on(self.board_index, pin, None, now);
511 }
512 }
513 for (&pin, &duty) in &next {
514 board.set_chip_pwm_on(self.board_index, pin, Some(duty), now);
515 }
516 self.pwm = next;
517 }
518
519 pub fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
522 let board = self.board.as_ref()?.borrow();
523 match pin {
524 Some(pin) => board.part_pin_level(part, pin),
525 None => board.chip_pin_level_on(self.board_index, part),
526 }
527 }
528
529 pub fn gpio_level(&self, gpio: u8) -> Option<Level> {
531 let board = self.board.as_ref()?.borrow();
532 board.chip_level_on(self.board_index, gpio)
533 }
534
535 pub fn conflicts(&self) -> Vec<Conflict> {
536 self.board
537 .as_ref()
538 .map(|b| b.borrow().conflicts().to_vec())
539 .unwrap_or_default()
540 }
541
542 pub fn load_rom(&mut self, rom_elf: &[u8]) -> Result<(), String> {
544 self.machine.load_rom(rom_elf)
545 }
546
547 pub fn write_flash(&mut self, offset: usize, data: &[u8]) -> Result<(), String> {
550 self.machine.write_flash(offset, data)
551 }
552
553 pub fn flash_image(&self) -> Option<&[u8]> {
556 self.machine.bus.flash_image()
557 }
558
559 pub fn boot_app(&mut self, app_off: usize) -> Result<u32, String> {
562 self.machine.boot_app(app_off)
563 }
564
565 pub fn load_script(&mut self, text: &str) -> Result<(), String> {
568 self.machine.load_script(text)
569 }
570
571 pub fn add_symbols(&mut self, elf: &[u8]) -> Result<(), String> {
574 self.machine.add_symbols(elf)
575 }
576
577 pub fn break_at(&mut self, pc: u32) {
579 self.machine
580 .add_observer(Box::new(esp_soc::observers::Breakpoints { pcs: vec![pc] }));
581 }
582
583 pub fn registers(&self) -> String {
585 self.machine.dump_regs()
586 }
587
588 pub fn enable_coverage(&mut self) {
591 if !self.machine.has_observer("coverage") {
592 self.machine
593 .add_observer(Box::new(esp_soc::observers::Coverage::new(None)));
594 }
595 }
596
597 pub fn reports(&mut self) -> Vec<String> {
599 self.machine.reports().lines().map(str::to_string).collect()
600 }
601
602 pub fn symbol_addr(&self, name: &str) -> Option<u32> {
606 self.machine.sym_addr(name)
607 }
608
609 pub fn call_guest(&mut self, address: u32) -> Result<u32, String> {
619 match self.guest_call {
620 Some(call) => call(self, address),
621 None => Err(format!(
622 "{} does not install a guest-call trampoline",
623 S::NAME
624 )),
625 }
626 }
627
628 pub fn sample_heap(&mut self) -> Result<u32, String> {
634 let names = [
635 "esp_get_free_heap_size",
636 "heap_caps_get_free_size",
637 "xPortGetFreeHeapSize",
638 ];
639 let (name, address) = names
640 .iter()
641 .find_map(|name| self.symbol_addr(name).map(|address| (*name, address)))
642 .ok_or_else(|| {
643 "no heap getter symbol in the ELF (esp_get_free_heap_size, \
644 heap_caps_get_free_size or xPortGetFreeHeapSize); supply `elf` in the project"
645 .to_string()
646 })?;
647 self.call_guest(address)
648 .map_err(|error| format!("{name}: {error}"))
649 }
650
651 pub fn disassemble(&mut self, addr: u32, count: usize) -> String {
652 self.machine.disasm(addr, count)
653 }
654
655 pub fn attach_wifi(&mut self, spec: &str) -> Result<(), String> {
662 let ap = esp_soc::wifi::ApConfig::parse(spec)?;
663 self.machine.bus.attach_wifi(ap, None)
664 }
665
666 pub fn attach_network(&mut self, config: &crate::NetworkConfig) -> Result<(), String> {
675 let specs: Vec<String> = config.access_points.iter().map(ap_spec).collect();
676 let aps = esp_soc::wifi::ApConfig::parse_all(&specs)?;
677 let nat = esp_soc::nat::Nat::with_transport(
678 false,
679 Box::new(crate::EspRouter::with_clock(
680 config,
681 Rc::clone(&self.net_clock),
682 )),
683 );
684 self.machine.bus.attach_wifi(aps[0].clone(), Some(nat))?;
685 for ap in &aps[1..] {
686 self.machine.bus.add_wifi_ap(ap.clone())?;
687 }
688 if !config.nearby.is_empty() {
689 let specs: Vec<String> = config.nearby.iter().map(nearby_spec).collect();
690 let beacons = esp_soc::wifi::BeaconAp::parse_all(&specs)?;
691 let left_out = self.machine.bus.wifi_nearby(beacons)?;
692 if let Some((beacon, why)) = left_out.first() {
693 return Err(format!(
694 "the network '{}' cannot be beside the access point: it shares {why}",
695 beacon.ssid
696 ));
697 }
698 }
699 Ok(())
700 }
701
702 #[cfg(not(target_arch = "wasm32"))]
709 pub fn attach_host_nat(&mut self, local_ntp: bool) -> Result<(), String> {
710 self.machine
711 .bus
712 .attach_nat(Some(esp_soc::nat::Nat::new(false)), local_ntp)
713 }
714
715 #[cfg(not(target_arch = "wasm32"))]
720 pub fn attach_host_forwards(
721 &mut self,
722 forwards: &[String],
723 local_ntp: bool,
724 ) -> Result<Vec<String>, String> {
725 let mut transport = esp_soc::nat::StdTransport::new();
726 let mut lines = Vec::new();
727 for spec in forwards {
728 let forward = esp_soc::nat::HostFwdSpec::parse(spec)?;
729 let at = transport
730 .listen(&forward)
731 .map_err(|e| format!("host forward {spec:?}: {e}"))?;
732 lines.push(format!("{spec} -> {at}"));
733 }
734 let mut nat = esp_soc::nat::Nat::with_transport(false, Box::new(transport));
735 nat.hostfwd = forwards.len() as u64;
736 self.machine.bus.attach_nat(Some(nat), local_ntp)?;
737 Ok(lines)
738 }
739
740 pub fn set_net_tap(&mut self, tap: esp_soc::netcap::NetTap) -> Result<(), String> {
743 self.machine.bus.set_net_tap(tap)
744 }
745
746 pub fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
749 let file =
750 std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
751 let capture =
752 std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::AirCapture::default()));
753 capture
754 .lock()
755 .map_err(|_| "the air capture lock is poisoned".to_string())?
756 .set_pcap(Box::new(file))
757 .map_err(|e| format!("{}: {e}", path.display()))?;
758 self.machine
759 .bus
760 .set_air_tap(Some(capture))
761 .map_err(|e| format!("802.11 capture: {e}"))
762 }
763
764 pub fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
767 let file =
768 std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
769 let capture =
770 std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::NetCapture::default()));
771 capture
772 .lock()
773 .map_err(|_| "the Ethernet capture lock is poisoned".to_string())?
774 .set_pcap(Box::new(file))
775 .map_err(|e| format!("{}: {e}", path.display()))?;
776 self.machine
777 .bus
778 .set_net_tap(capture)
779 .map_err(|e| format!("Ethernet capture: {e}"))
780 }
781
782 pub fn set_ethernet_relay(&mut self, enabled: bool) -> Result<(), String> {
787 self.machine.bus.set_ethernet_relay(enabled)
788 }
789
790 pub fn take_ethernet_frames(&mut self) -> Vec<Vec<u8>> {
793 self.machine.bus.take_ethernet_frames()
794 }
795
796 pub fn receive_ethernet_frame(&mut self, frame: &[u8]) -> Result<(), String> {
798 self.machine.bus.receive_ethernet_frame(frame)
799 }
800
801 pub fn attach_ble(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
815 if config.is_empty() {
816 return Ok(());
817 }
818 self.ble_seen = self
822 .board
823 .as_ref()
824 .map(|board| board.borrow().ble_generation())
825 .unwrap_or(0);
826 self.ble_attached = false;
827 let Some(bytes) = self.elf.clone() else {
835 return Err(format!(
836 "{} needs the firmware ELF to scan for a beacon: set [sim] elf, \
837 because the Bluetooth controller is started through the guest's \
838 symbol table",
839 S::NAME
840 ));
841 };
842 let elf = esp_soc::elf::parse(&bytes)?;
843 self.machine
844 .bus
845 .enable_ble(&elf)
846 .map_err(|why| format!("{} cannot carry BLE beacons: {why}", S::NAME))?;
847 let beacons = nearby_list(&config.beacons);
848 self.machine.bus.ble_nearby(beacons)?;
849 self.ble_peers = config.beacons.clone();
850 self.ble_attached = true;
851 Ok(())
852 }
853
854 pub fn set_ble_nearby(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
863 if !self.ble_attached {
864 return Err("BLE is not enabled on this chip".into());
865 }
866 self.machine.bus.ble_nearby(nearby_list(&config.beacons))?;
867 self.ble_peers = config.beacons.clone();
868 self.ble_seen = self
869 .board
870 .as_ref()
871 .map(|board| board.borrow().ble_generation())
872 .unwrap_or(0);
873 Ok(())
874 }
875
876 pub fn add_ble_peer(&mut self, beacon: &litz_ble::Beacon) -> Result<(), String> {
884 if !self.ble_attached {
885 return Err("BLE is not enabled on this chip".into());
886 }
887 self.ble_peers.push(beacon.clone());
888 let peers = nearby_list(&self.ble_peers);
889 if let Err(error) = self.machine.bus.ble_nearby(peers) {
890 self.ble_peers.pop();
891 return Err(error);
892 }
893 self.ble_seen = self
894 .board
895 .as_ref()
896 .map(|board| board.borrow().ble_generation())
897 .unwrap_or(0);
898 Ok(())
899 }
900
901 pub fn ble_command(&mut self, command: &str) -> Result<(), String> {
912 self.machine.bus.ble_command(command)
913 }
914
915 pub fn ble_pending_commands(&self) -> usize {
917 self.machine.bus.ble_pending_commands()
918 }
919
920 pub fn ble_log(&mut self) -> Option<String> {
922 self.machine.bus.ble_log_take()
923 }
924
925 pub fn enable_full_ble(&mut self, observe: bool) -> Result<(), String> {
929 self.machine.bus.enable_ble_full(observe)
930 }
931
932 pub fn seconds(&self) -> f64 {
934 self.machine.seconds() + self.off_ns as f64 / 1e9
935 }
936
937 pub fn board_power(&self) -> bool {
939 match &self.board {
940 Some(board) => board.borrow().board_powered(self.board_index),
941 None => true,
942 }
943 }
944
945 fn boot_after_power(&mut self) -> Result<u32, String> {
948 if self.bootloader_loaded {
949 self.machine.reboot();
950 Ok(0)
951 } else {
952 let app = litz_board::Chip::info(self).flash.app as usize;
953 self.boot_app(app)
954 }
955 }
956
957 fn power_off(&mut self) {
959 self.powered = false;
960 self.pwm.clear();
961 if let Some(board) = &self.board {
962 let now = (self.seconds() * 1e9) as u64;
963 board
964 .borrow_mut()
965 .release_chip_outputs(self.board_index, now);
966 }
967 }
968
969 pub fn run(&mut self, steps: u64) -> esp_soc::Stop {
971 self.publish_analog();
974 if let Some(board) = &self.board {
976 let now = board.borrow().now();
977 self.net_clock.set(now);
978 if self.ble_attached {
982 let (generation, air) = {
983 let board = board.borrow();
984 (board.ble_generation(), board.ble_air(self.board_index))
985 };
986 if generation != self.ble_seen {
987 self.ble_seen = generation;
988 let _ = self.machine.bus.ble_nearby(nearby_list(&air));
989 self.ble_peers = air;
990 }
991 }
992 }
993 self.machine.run(steps)
994 }
995
996 pub fn uart0(&self) -> &[u8] {
997 &self.machine.console.uart0
998 }
999
1000 pub fn take_uart0(&mut self) -> Vec<u8> {
1001 core::mem::take(&mut self.machine.console.uart0)
1002 }
1003 }
1004
1005 fn ap_spec(ap: &litz_net::AccessPoint) -> String {
1009 let mut spec = format!("ssid={},channel={}", ap.ssid, ap.channel);
1010 if let Some(psk) = &ap.psk {
1011 spec.push_str(&format!(",psk={psk}"));
1012 }
1013 if let Some(bssid) = ap.bssid {
1014 spec.push_str(&format!(
1015 ",bssid={}",
1016 bssid
1017 .iter()
1018 .map(|b| format!("{b:02x}"))
1019 .collect::<Vec<_>>()
1020 .join(":")
1021 ));
1022 }
1023 if let Some(epoch) = ap.epoch_s {
1024 spec.push_str(&format!(",epoch={epoch}"));
1025 }
1026 spec
1027 }
1028
1029 fn nearby_list(beacons: &[litz_ble::Beacon]) -> Vec<Nearby> {
1032 beacons
1033 .iter()
1034 .map(|beacon| Nearby {
1035 addr: beacon.address,
1036 addr_type: beacon.address_type(),
1037 rssi: beacon.rssi,
1038 adv: beacon.adv.clone(),
1039 scan_response: beacon.scan_response.clone(),
1040 gatt: beacon
1041 .gatt
1042 .iter()
1043 .map(|service| esp_soc::ble::peer::GattService {
1044 uuid: service.uuid,
1045 characteristics: service
1046 .characteristics
1047 .iter()
1048 .map(|characteristic| esp_soc::ble::peer::GattCharacteristic {
1049 uuid: characteristic.uuid,
1050 flags: characteristic.flags,
1051 value: characteristic.value.clone(),
1052 })
1053 .collect(),
1054 })
1055 .collect(),
1056 })
1057 .collect()
1058 }
1059
1060 fn nearby_spec(network: &litz_net::NearbyNetwork) -> String {
1061 format!(
1062 "ssid={},channel={},rssi={},secure={}",
1063 network.ssid,
1064 network.channel,
1065 network.rssi,
1066 u8::from(network.secure)
1067 )
1068 }
1069
1070 #[cfg(feature = "esp32c3")]
1072 pub type C3 = EspChip<esp32c3::C3>;
1073
1074 #[cfg(feature = "esp32c3")]
1075 impl EspChip<esp32c3::C3> {
1076 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1077 let mut chip = Self::bare(mac, flash_size, c3_bus);
1078 chip.gdb = Some(serve_gdb::<esp32c3::C3>);
1079 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c3::C3>);
1080 chip
1081 }
1082 }
1083
1084 #[cfg(feature = "esp32c3")]
1085 fn c3_bus(
1086 mac: [u8; 6],
1087 flash: usize,
1088 board: Option<Rc<RefCell<LitzBoard>>>,
1089 index: u16,
1090 spi_rates: Rc<Cell<[u32; 2]>>,
1091 ) -> esp32c3::bus::SocBus {
1092 const CPU_HZ: u64 = esp32c3::periph::CPU_HZ;
1093 let mut bus = esp32c3::bus::SocBus::new(flash, mac);
1094 if let Some(board) = board {
1095 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1096 bus.attach_board_devices();
1099 }
1100 bus
1101 }
1102
1103 #[cfg(feature = "esp32c6")]
1105 pub type C6 = EspChip<esp32c6::C6>;
1106
1107 #[cfg(feature = "esp32c6")]
1108 impl EspChip<esp32c6::C6> {
1109 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1110 let mut chip = Self::bare(mac, flash_size, c6_bus);
1111 chip.gdb = Some(serve_gdb::<esp32c6::C6>);
1112 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c6::C6>);
1113 chip
1114 }
1115 }
1116
1117 #[cfg(feature = "esp32c6")]
1118 fn c6_bus(
1119 mac: [u8; 6],
1120 flash: usize,
1121 board: Option<Rc<RefCell<LitzBoard>>>,
1122 index: u16,
1123 spi_rates: Rc<Cell<[u32; 2]>>,
1124 ) -> esp32c6::bus::SocBus {
1125 const CPU_HZ: u64 = esp32c6::periph::CPU_HZ;
1126 let mut bus = esp32c6::bus::SocBus::new(flash, mac);
1127 if let Some(board) = board {
1128 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1129 bus.attach_board_devices();
1130 }
1131 bus
1132 }
1133
1134 #[cfg(feature = "esp32")]
1136 pub type Esp32 = EspChip<esp32::Esp32>;
1137
1138 #[cfg(feature = "esp32")]
1139 impl EspChip<esp32::Esp32> {
1140 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1141 let mut chip = Self::bare(mac, flash_size, esp32_bus);
1142 chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1143 chip.spi_clock = Some(ESP32_SPI_CLOCKS);
1144 chip
1145 }
1146 }
1147
1148 #[cfg(feature = "esp32")]
1149 fn esp32_bus(
1150 mac: [u8; 6],
1151 flash: usize,
1152 board: Option<Rc<RefCell<LitzBoard>>>,
1153 index: u16,
1154 spi_rates: Rc<Cell<[u32; 2]>>,
1155 ) -> esp32::bus::SocBus {
1156 const CPU_HZ: u64 = esp32::periph::CPU_HZ;
1157 let mut bus = esp32::bus::SocBus::new(flash, mac);
1158 if let Some(board) = board {
1159 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1160 bus.attach_board_devices();
1161 }
1162 bus
1163 }
1164
1165 #[cfg(feature = "esp32s3")]
1168 const S3_PSRAM: usize = 2 << 20;
1169
1170 #[cfg(feature = "esp32s3")]
1172 pub type S3 = EspChip<esp32s3::S3>;
1173
1174 #[cfg(feature = "esp32s3")]
1175 impl EspChip<esp32s3::S3> {
1176 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1177 let mut chip = Self::bare(mac, flash_size, s3_bus);
1178 chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1179 chip.spi_clock = Some(S3_SPI_CLOCKS);
1180 chip
1181 }
1182 }
1183
1184 #[cfg(feature = "esp32s3")]
1185 fn s3_bus(
1186 mac: [u8; 6],
1187 flash: usize,
1188 board: Option<Rc<RefCell<LitzBoard>>>,
1189 index: u16,
1190 spi_rates: Rc<Cell<[u32; 2]>>,
1191 ) -> esp32s3::bus::SocBus {
1192 const CPU_HZ: u64 = esp32s3::periph::CPU_HZ;
1193 let mut bus = esp32s3::bus::SocBus::new(flash, S3_PSRAM, mac);
1194 if let Some(board) = board {
1195 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1196 bus.attach_board_devices();
1197 }
1198 bus
1199 }
1200
1201 #[cfg(feature = "esp32p4")]
1204 pub type P4 = EspChip<esp32p4::P4>;
1205
1206 #[cfg(feature = "esp32p4")]
1207 impl EspChip<esp32p4::P4> {
1208 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1209 let mut chip = Self::bare(mac, flash_size, p4_bus);
1210 chip.gdb = Some(serve_gdb::<esp32p4::P4>);
1211 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32p4::P4>);
1212 chip
1213 }
1214 }
1215
1216 #[cfg(feature = "esp32p4")]
1217 fn p4_bus(
1218 mac: [u8; 6],
1219 flash: usize,
1220 board: Option<Rc<RefCell<LitzBoard>>>,
1221 index: u16,
1222 spi_rates: Rc<Cell<[u32; 2]>>,
1223 ) -> esp32p4::bus::SocBus {
1224 const CPU_HZ: u64 = esp32p4::periph::CPU_HZ;
1225 let wafer = <esp32p4::RevLt3 as esp32p4::Revision>::WAFER;
1226 let mut bus = esp32p4::bus::SocBus::new(flash, mac, wafer);
1227 if let Some(board) = board {
1228 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1229 bus.attach_board_devices();
1230 }
1231 bus
1232 }
1233
1234 #[cfg(feature = "esp32s31")]
1236 pub type S31 = EspChip<esp32s31::S31>;
1237
1238 #[cfg(feature = "esp32s31")]
1239 impl EspChip<esp32s31::S31> {
1240 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1241 let mut chip = Self::bare(mac, flash_size, s31_bus);
1242 chip.gdb = Some(serve_gdb::<esp32s31::S31>);
1243 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32s31::S31>);
1244 chip
1245 }
1246 }
1247
1248 #[cfg(feature = "esp32s31")]
1249 fn s31_bus(
1250 mac: [u8; 6],
1251 flash: usize,
1252 board: Option<Rc<RefCell<LitzBoard>>>,
1253 index: u16,
1254 spi_rates: Rc<Cell<[u32; 2]>>,
1255 ) -> esp32s31::SocBus {
1256 const CPU_HZ: u64 = esp32s31::periph::CPU_HZ;
1257 let mut bus = esp32s31::SocBus::new(flash, mac);
1258 if let Some(board) = board {
1259 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1260 bus.attach_board_devices();
1261 }
1262 bus
1263 }
1264
1265 struct BoardI2cDevice {
1272 board: Rc<RefCell<LitzBoard>>,
1273 board_index: u16,
1276 controller: u8,
1277 address: u8,
1278 written: Vec<u8>,
1282 received: Vec<u8>,
1283 reading: bool,
1284 open: bool,
1285 last_at: u64,
1289 started_at: u64,
1293 }
1294
1295 impl EspI2cDevice for BoardI2cDevice {
1296 fn address(&self, _configured: u8) -> u8 {
1297 self.address
1298 }
1299
1300 fn start(&mut self, read: bool) -> bool {
1301 let opening = !self.open;
1302 if opening {
1303 self.written.clear();
1304 self.received.clear();
1305 self.open = true;
1306 self.started_at = self.board.borrow().now();
1307 }
1308 self.reading = read;
1309 let mut board = self.board.borrow_mut();
1310 if opening {
1311 board.i2c_begin(self.board_index, self.controller, self.address);
1312 }
1313 let Some(bus) = board
1314 .buses_mut()
1315 .i2c
1316 .get_mut(&(self.board_index, self.controller))
1317 else {
1318 return false;
1319 };
1320 let Some(device) = bus.device_mut(self.address) else {
1321 return false;
1322 };
1323 device.connect(read);
1324 true
1325 }
1326
1327 fn write(&mut self, byte: u8) -> bool {
1328 if !self.reading {
1329 self.written.push(byte);
1330 }
1331 let mut board = self.board.borrow_mut();
1332 let Some(bus) = board
1333 .buses_mut()
1334 .i2c
1335 .get_mut(&(self.board_index, self.controller))
1336 else {
1337 return false;
1338 };
1339 let Some(device) = bus.device_mut(self.address) else {
1340 return false;
1341 };
1342 device.write(byte)
1343 }
1344
1345 fn read(&mut self) -> u8 {
1346 let byte = {
1347 let mut board = self.board.borrow_mut();
1348 let Some(bus) = board
1349 .buses_mut()
1350 .i2c
1351 .get_mut(&(self.board_index, self.controller))
1352 else {
1353 return 0xff;
1354 };
1355 let Some(device) = bus.device_mut(self.address) else {
1356 return 0xff;
1357 };
1358 device.read()
1359 };
1360 self.received.push(byte);
1361 byte
1362 }
1363
1364 fn stop(&mut self) {
1365 {
1366 let mut board = self.board.borrow_mut();
1367 let Some(bus) = board
1368 .buses_mut()
1369 .i2c
1370 .get_mut(&(self.board_index, self.controller))
1371 else {
1372 return;
1373 };
1374 if let Some(device) = bus.device_mut(self.address) {
1375 device.stop();
1376 }
1377 }
1378 if self.open {
1379 let mut board = self.board.borrow_mut();
1380 board.i2c_end(self.board_index, self.controller, self.address);
1381 let end = board.now();
1382 let at = self.started_at.max(self.last_at);
1383 let phases = 1
1384 + self.written.len()
1385 + if self.received.is_empty() {
1386 0
1387 } else {
1388 1 + self.received.len()
1389 };
1390 let elapsed = end.saturating_sub(self.started_at);
1395 let hz = if elapsed > 0 {
1396 (phases as u128 * 9 * 1_000_000_000 / u128::from(elapsed))
1397 .clamp(1_000, 5_000_000) as u32
1398 } else {
1399 board.i2c_hz(self.board_index, self.controller)
1400 };
1401 board.set_i2c_hz(self.board_index, self.controller, hz);
1402 board.observe_i2c(
1403 self.board_index,
1404 self.controller,
1405 self.address,
1406 &self.written,
1407 &self.received,
1408 at,
1409 );
1410 let period = 1_000_000_000 / u64::from(hz);
1411 self.last_at = (at + phases as u64 * 9 * period).max(end);
1412 }
1413 self.open = false;
1414 self.reading = false;
1415 }
1416 }
1417
1418 #[derive(Clone, Copy)]
1425 struct SpiClockSpec {
1426 ports: [(u32, u32, u32); 2],
1428 }
1429
1430 #[cfg(feature = "esp32")]
1431 const ESP32_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1432 ports: [(0x3ff6_4018, 18, 0x1fff), (0x3ff6_5018, 18, 0x1fff)],
1433 };
1434
1435 #[cfg(feature = "esp32s3")]
1436 const S3_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1437 ports: [(0x6002_400c, 18, 0xf), (0x6002_500c, 18, 0xf)],
1438 };
1439
1440 struct SpiClockObserver {
1447 rates: Rc<Cell<[u32; 2]>>,
1448 spec: SpiClockSpec,
1449 }
1450
1451 impl<S: Soc> esp_soc::Observer<S> for SpiClockObserver {
1452 fn name(&self) -> &'static str {
1453 "litz-spi-clock"
1454 }
1455
1456 fn wants(&self) -> esp_soc::Wants {
1457 esp_soc::Wants::MMIO
1458 }
1459
1460 fn on_mmio(&mut self, _cx: &esp_soc::Ctx, _pc: u32, addr: u32, value: u32, write: bool) {
1461 if !write {
1462 return;
1463 }
1464 let Some(slot) = self.spec.ports.iter().position(|&(reg, ..)| reg == addr) else {
1465 return;
1466 };
1467 let (_, shift, mask) = self.spec.ports[slot];
1468 let divider = if value & (1 << 31) != 0 {
1471 1
1472 } else {
1473 (((value >> shift) & mask) + 1) * (((value >> 12) & 0x3f) + 1)
1474 };
1475 let mut rates = self.rates.get();
1476 rates[slot] = (esp_periph::APB_HZ / u64::from(divider)) as u32;
1477 self.rates.set(rates);
1478 }
1479 }
1480
1481 struct LitzModel {
1487 board: Rc<RefCell<LitzBoard>>,
1488 index: u16,
1490 enabled: u64,
1491 output: u64,
1492 cycle: u64,
1493 releases: Vec<u8>,
1494 cpu_hz: u64,
1497 uart_routes: BTreeMap<u8, (u8, u32)>,
1501 spi_rates: Rc<Cell<[u32; 2]>>,
1504 }
1505
1506 impl LitzModel {
1507 fn new(
1508 board: Rc<RefCell<LitzBoard>>,
1509 cpu_hz: u64,
1510 index: u16,
1511 spi_rates: Rc<Cell<[u32; 2]>>,
1512 ) -> Self {
1513 Self {
1514 board,
1515 index,
1516 enabled: 0,
1517 output: 0,
1518 cycle: 0,
1519 releases: Vec::new(),
1520 cpu_hz,
1521 uart_routes: BTreeMap::new(),
1522 spi_rates,
1523 }
1524 }
1525
1526 fn spi_rate(&self, host: u8) -> Option<u32> {
1528 let slot = usize::from(host.checked_sub(2)?);
1529 let hz = *self.spi_rates.get().get(slot)?;
1530 (hz > 0).then_some(hz)
1531 }
1532
1533 fn ns(&self, cycle: u64) -> u64 {
1534 (u128::from(cycle) * 1_000_000_000 / u128::from(self.cpu_hz)) as u64
1535 }
1536
1537 fn cycles_for(&self, ns: u64) -> u64 {
1540 let cycles = u128::from(ns) * u128::from(self.cpu_hz);
1541 (cycles.div_ceil(1_000_000_000)) as u64
1542 }
1543 }
1544
1545 fn expand_monochrome(bytes: &[u8], width: u32, height: u32) -> Vec<u16> {
1548 let mut pixels = vec![0u16; (width * height) as usize];
1549 for page in 0..height.div_ceil(8) {
1550 for column in 0..width {
1551 let Some(byte) = bytes.get((page * width + column) as usize) else {
1552 continue;
1553 };
1554 for bit in 0..8u32 {
1555 let y = page * 8 + bit;
1556 if y >= height {
1557 break;
1558 }
1559 if byte & (1 << bit) != 0 {
1560 pixels[(y * width + column) as usize] = 0xffff;
1561 }
1562 }
1563 }
1564 }
1565 pixels
1566 }
1567
1568 fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1571 let mut data = [0u8; litz_board::bus::CAN_MAX_DATA];
1573 let len = usize::from(frame.len).min(frame.data.len());
1574 data[..len].copy_from_slice(&frame.data[..len]);
1575 litz_board::bus::CanFrame {
1576 id: frame.id,
1577 extended: frame.extended,
1578 rtr: frame.rtr,
1579 len: frame.len,
1580 data,
1581 kind: if frame.rtr {
1582 litz_board::bus::CanFrameKind::Remote
1583 } else {
1584 litz_board::bus::CanFrameKind::Classic
1585 },
1586 }
1587 }
1588
1589 impl BoardModel for LitzModel {
1590 fn name(&self) -> &'static str {
1591 "litz"
1592 }
1593
1594 fn gpio_output_at(
1595 &mut self,
1596 cycle: u64,
1597 changes: &[(u8, bool)],
1598 enabled: u64,
1599 output: u64,
1600 ) {
1601 self.cycle = self.cycle.max(cycle);
1605 let now = self.ns(self.cycle);
1606 if std::env::var("LITZ_TRACE_DEBUG").is_ok() {
1607 eprintln!("DBG cycle={} now={}", self.cycle, now);
1608 }
1609 let mut mask = (enabled ^ self.enabled) | (output ^ self.output);
1612 for &(pin, _) in changes {
1613 mask |= 1u64 << pin;
1614 }
1615 let mut board = self.board.borrow_mut();
1616 while mask != 0 {
1617 let pin = mask.trailing_zeros() as u8;
1618 mask &= mask - 1;
1619 let bit = 1u64 << pin;
1620 let drive = if enabled & bit != 0 {
1621 if output & bit != 0 {
1622 Drive::strong(Level::High)
1623 } else {
1624 Drive::strong(Level::Low)
1625 }
1626 } else {
1627 Drive::HIGH_Z
1628 };
1629 board.set_chip_output_on(self.index, pin, drive, now);
1630 }
1631 self.enabled = enabled;
1632 self.output = output;
1633 }
1634
1635 fn display(&self) -> Option<(u32, u32, Vec<u16>, u64)> {
1640 let board = self.board.borrow();
1641 let buses = board.buses();
1642 for (&(owner, _), i2c) in &buses.i2c {
1643 if owner != self.index {
1644 continue;
1645 }
1646 for address in i2c.addresses() {
1647 if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1648 let (bytes, width, height) = oled.framebuffer();
1649 return Some((
1650 width,
1651 height,
1652 expand_monochrome(bytes, width, height),
1653 oled.frame_version(),
1654 ));
1655 }
1656 }
1657 }
1658 for (&(owner, _), spi) in &buses.spi {
1659 if owner != self.index {
1660 continue;
1661 }
1662 for select in spi.chip_selects() {
1663 if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1664 let (pixels, width, height) = tft.framebuffer();
1665 return Some((width, height, pixels.to_vec(), tft.frame_version()));
1666 }
1667 }
1668 }
1669 None
1670 }
1671
1672 fn touch(&mut self, x: u16, y: u16, down: bool) {
1676 let _ = self.board.borrow_mut().touch_panel(x, y, down);
1677 }
1678
1679 fn display_version(&self) -> u64 {
1680 let board = self.board.borrow();
1681 let buses = board.buses();
1682 for (&(owner, _), i2c) in &buses.i2c {
1683 if owner != self.index {
1684 continue;
1685 }
1686 for address in i2c.addresses() {
1687 if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1688 return oled.frame_version();
1689 }
1690 }
1691 }
1692 for (&(owner, _), spi) in &buses.spi {
1693 if owner != self.index {
1694 continue;
1695 }
1696 for select in spi.chip_selects() {
1697 if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1698 return tft.frame_version();
1699 }
1700 }
1701 }
1702 0
1703 }
1704
1705 fn advance_to(&mut self, cycle: u64) {
1706 self.cycle = cycle;
1707 let now = self.ns(cycle);
1712 self.board.borrow_mut().advance_to(now);
1713 }
1714
1715 fn next_deadline(&self) -> Option<u64> {
1716 let board = self.board.borrow();
1719 let now = board.has_pending_inputs_on(self.index).then_some(0);
1720 let event = board.next_event().map(|at| self.cycles_for(at));
1721 match (now, event) {
1722 (Some(a), Some(b)) => Some(a.min(b)),
1723 (a, b) => a.or(b),
1724 }
1725 }
1726
1727 fn take_edges(&mut self) -> Vec<BoardEdge> {
1728 let cycle = self.cycle;
1729 let drained = self.board.borrow_mut().take_chip_inputs_on(self.index);
1730 let mut levels: BTreeMap<u8, Level> = BTreeMap::new();
1736 for (pin, level) in drained {
1737 levels.insert(pin, level);
1738 }
1739 let mut edges = Vec::new();
1740 for (pin, level) in levels {
1741 match level {
1742 Level::High => edges.push(BoardEdge {
1743 cycle,
1744 pin,
1745 level: true,
1746 }),
1747 Level::Low => edges.push(BoardEdge {
1748 cycle,
1749 pin,
1750 level: false,
1751 }),
1752 Level::HighZ => self.releases.push(pin),
1753 }
1754 }
1755 edges
1756 }
1757
1758 fn released_inputs(&mut self) -> Vec<u8> {
1759 core::mem::take(&mut self.releases)
1760 }
1761
1762 fn input_levels(&self) -> Vec<(u8, bool)> {
1763 self.board
1764 .borrow()
1765 .input_levels_on(self.index)
1766 .into_iter()
1767 .filter_map(|(pin, level)| match level {
1768 Level::High => Some((pin, true)),
1769 Level::Low => Some((pin, false)),
1770 Level::HighZ => None,
1771 })
1772 .collect()
1773 }
1774
1775 fn named_pin(&self, name: &str) -> Option<u8> {
1776 let board = self.board.borrow();
1777 let (index, pin) = board.named_pin_on(name)?;
1778 (index == self.index).then_some(pin)
1779 }
1780
1781 fn i2c_devices(&mut self) -> Vec<(u8, u8, Box<dyn EspI2cDevice>)> {
1786 let board = self.board.borrow();
1787 let mut devices: Vec<(u8, u8)> = Vec::new();
1788 for (&(owner, controller), bus) in &board.buses().i2c {
1789 if owner != self.index {
1790 continue;
1791 }
1792 for address in bus.addresses() {
1793 devices.push((controller, address));
1794 }
1795 }
1796 drop(board);
1797 devices
1798 .into_iter()
1799 .map(|(controller, address)| {
1800 let device: Box<dyn EspI2cDevice> = Box::new(BoardI2cDevice {
1801 board: Rc::clone(&self.board),
1802 board_index: self.index,
1803 controller,
1804 address,
1805 written: Vec::new(),
1806 received: Vec::new(),
1807 reading: false,
1808 open: false,
1809 last_at: 0,
1810 started_at: 0,
1811 });
1812 (controller, address, device)
1813 })
1814 .collect()
1815 }
1816
1817 fn uses_spi_pins(&self) -> bool {
1818 self.board
1819 .borrow()
1820 .buses()
1821 .spi
1822 .keys()
1823 .any(|&(owner, _)| owner == self.index)
1824 }
1825
1826 fn spi_transfer(&mut self, host: u8, tx: &[u8], rx_len: usize) -> Vec<u8> {
1831 let rate = self.spi_rate(host);
1832 let mut board = self.board.borrow_mut();
1833 let selected = board
1834 .buses()
1835 .spi_sole(self.index, host)
1836 .or_else(|| board.buses().spi_only_device(self.index));
1837 match selected {
1838 Some((controller, chip_select)) => {
1839 if let Some(hz) = rate {
1842 board.set_spi_hz(self.index, controller, hz);
1843 }
1844 board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1845 }
1846 None => vec![0xff; rx_len],
1847 }
1848 }
1849
1850 fn spi_transfer_pins(
1853 &mut self,
1854 host: u8,
1855 pins: SpiPins,
1856 tx: &[u8],
1857 rx_len: usize,
1858 ) -> Vec<u8> {
1859 let rate = self.spi_rate(host);
1860 let mut board = self.board.borrow_mut();
1861 match board.buses().spi_selected(self.index, pins.cs) {
1862 Some((controller, chip_select)) => {
1863 if let Some(hz) = rate {
1864 board.set_spi_hz(self.index, controller, hz);
1865 }
1866 board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1867 }
1868 None => vec![0xff; rx_len],
1869 }
1870 }
1871
1872 fn uses_uart_pins(&self) -> bool {
1873 let board = self.board.borrow();
1874 if board
1875 .buses()
1876 .uart
1877 .keys()
1878 .any(|&(owner, _)| owner == self.index)
1879 {
1880 return true;
1881 }
1882 board.flat().has_chip_to_chip_wire(self.index)
1885 }
1886
1887 fn uart_tx(&mut self, cycle: u64, route: UartRoute, byte: u8) {
1890 let now = self.ns(cycle);
1891 let port = route.port as u8;
1892 let baud = route
1893 .baud
1894 .unwrap_or(litz_board::runtime::OBSERVED_UART_BAUD);
1895 let mut board = self.board.borrow_mut();
1896 board.set_uart_baud(self.index, port, baud);
1897 board.set_uart_pins(self.index, port, route.tx_pins, route.rx_pin);
1899 board.uart_receive(self.index, port, now, &[byte]);
1900 drop(board);
1901 if let Some(pin) = route.rx_pin {
1902 self.uart_routes
1903 .insert(port, (pin, route.baud.unwrap_or(115_200)));
1904 }
1905 }
1906
1907 fn uart_rx(&mut self, cycle: u64) -> Vec<UartInput> {
1912 let now = self.ns(cycle);
1913 let mut board = self.board.borrow_mut();
1914 for (&port, &(_, baud)) in &self.uart_routes {
1915 board.set_uart_baud(self.index, port, baud);
1916 }
1917 let mut ports: BTreeMap<u8, Option<(u8, u32)>> = self
1920 .uart_routes
1921 .iter()
1922 .map(|(&port, &route)| (port, Some(route)))
1923 .collect();
1924 for &(owner, port) in board.buses().uart.keys() {
1925 if owner != self.index {
1926 continue;
1927 }
1928 ports.entry(port).or_insert_with(|| {
1929 board
1930 .flat()
1931 .buses
1932 .uart
1933 .get(&(self.index, port))
1934 .map(|bus| (bus.chip_rx, 115_200))
1935 });
1936 }
1937 let mut inputs = Vec::new();
1938 for (port, route) in ports {
1939 let Some((pin, baud)) = route else { continue };
1940 let data = board.uart_poll(self.index, port, now);
1941 if !data.is_empty() {
1942 inputs.push(UartInput::new(pin, baud, data));
1943 }
1944 }
1945 inputs
1946 }
1947
1948 fn can_tx(&mut self, _host: u8, frame: &[u8]) {
1951 let Some(frame) = esp_soc::board::CanFrame::decode(frame) else {
1952 return;
1953 };
1954 let mut board = self.board.borrow_mut();
1955 let can = board.buses_mut().can_mut();
1956 can.attach(self.index);
1957 let _ = can.transmit(self.index, board_can_frame(&frame));
1958 }
1959
1960 fn can_take(&mut self, _host: u8) -> Option<Vec<u8>> {
1964 let mut board = self.board.borrow_mut();
1965 let can = board.buses_mut().can_mut();
1966 can.attach(self.index);
1967 let frame = can.take(self.index)?;
1968 let mut data = [0u8; esp_soc::board::CAN_MAX_DATA];
1970 let len = usize::from(frame.len).min(data.len());
1971 data[..len].copy_from_slice(&frame.data[..len]);
1972 Some(
1973 esp_soc::board::CanFrame {
1974 id: frame.id,
1975 extended: frame.extended,
1976 rtr: frame.rtr || frame.kind == litz_board::bus::CanFrameKind::Remote,
1977 len: frame.len,
1978 data,
1979 }
1980 .encode()
1981 .to_vec(),
1982 )
1983 }
1984 }
1985
1986 impl<S: Soc> litz_board::Chip for EspChip<S> {
1989 fn info(&self) -> litz_board::ChipInfo {
1990 litz_board::ChipInfo {
1991 name: S::NAME.into(),
1992 cpu_hz: S::CPU_HZ,
1993 flash: litz_board::FlashLayout {
1994 size: self.flash as u64,
1995 bootloader: S::BOOTLOADER_OFFSET as u64,
1996 partition_table: 0x8000,
1997 app: 0x1_0000,
1998 },
1999 }
2000 }
2001
2002 fn load_image(
2003 &mut self,
2004 kind: litz_board::ImageKind,
2005 offset: u64,
2006 bytes: &[u8],
2007 ) -> Result<(), String> {
2008 match kind {
2009 litz_board::ImageKind::Rom => self.load_rom(bytes),
2010 litz_board::ImageKind::Bootloader => {
2011 self.bootloader_loaded = true;
2012 self.write_flash(offset as usize, bytes)
2013 }
2014 _ => self.write_flash(offset as usize, bytes),
2015 }
2016 }
2017
2018 fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
2019 EspChip::set_psram_size(self, bytes)
2020 }
2021
2022 fn flash_image(&self) -> Option<Vec<u8>> {
2023 EspChip::flash_image(self).map(<[u8]>::to_vec)
2024 }
2025
2026 fn boot(&mut self) -> Result<u32, String> {
2027 self.powered = self.board_power();
2028 if !self.powered {
2029 return Ok(0);
2032 }
2033 if self.bootloader_loaded {
2034 return Ok(0);
2037 }
2038 let app = self.info().flash.app as usize;
2039 self.boot_app(app)
2040 }
2041
2042 fn schedule(&mut self, inputs: Vec<litz_board::Input>) -> Result<(), String> {
2043 let mut text = String::new();
2044 for input in inputs {
2045 match input {
2046 litz_board::Input::Gpio { at_ns, pin, level } => {
2047 let seconds = at_ns as f64 / 1e9;
2048 let bit = u8::from(level == Level::High);
2049 text.push_str(&format!("{seconds:.6} gpio {pin} {bit}\n"));
2050 }
2051 litz_board::Input::Uart { at_ns, bytes } => {
2052 let seconds = at_ns as f64 / 1e9;
2053 let text_in = String::from_utf8_lossy(&bytes);
2054 text.push_str(&format!(
2056 "{seconds:.6} uart0 {}\n",
2057 text_in.trim_end_matches('\n')
2058 ));
2059 }
2060 }
2061 }
2062 if text.is_empty() {
2063 Ok(())
2064 } else {
2065 self.load_script(&text)
2066 }
2067 }
2068
2069 fn run(&mut self, budget_cycles: u64) -> litz_board::RunResult {
2070 if !EspChip::board_power(self) {
2071 if self.powered {
2072 self.power_off();
2073 }
2074 let cycles = u128::from(budget_cycles) * 1_000_000_000;
2077 let cpu_hz = u128::from(litz_board::Chip::info(self).cpu_hz.max(1));
2078 self.off_ns = self.off_ns.saturating_add((cycles / cpu_hz) as u64);
2079 return litz_board::RunResult {
2080 cycles: budget_cycles,
2081 stop: litz_board::Stop::Idle,
2082 };
2083 }
2084 if !self.powered {
2085 if self.boot_after_power().is_err() {
2087 return litz_board::RunResult {
2088 cycles: 0,
2089 stop: litz_board::Stop::Trap,
2090 };
2091 }
2092 self.powered = true;
2093 }
2094 let stop = match EspChip::run(self, budget_cycles) {
2095 esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2096 esp_soc::Stop::Halted => litz_board::Stop::Halted,
2097 esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2098 esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2099 _ => litz_board::Stop::Idle,
2100 };
2101 self.publish_pwm();
2102 litz_board::RunResult {
2103 cycles: budget_cycles,
2104 stop,
2105 }
2106 }
2107
2108 fn seconds(&self) -> f64 {
2109 EspChip::seconds(self)
2110 }
2111
2112 fn write_console(&mut self, bytes: &[u8]) {
2113 self.write_serial(bytes);
2117 }
2118
2119 fn take_console(&mut self) -> Vec<u8> {
2120 let mut bytes = self.take_uart0();
2121 let usb = core::mem::take(&mut self.machine.console.usb);
2127 if usb != bytes {
2128 bytes.extend(usb);
2129 }
2130 bytes
2131 }
2132
2133 fn state(&self, part: &str) -> Option<PartState> {
2134 EspChip::state(self, part)
2135 }
2136
2137 fn press(&mut self, part: &str, pressed: bool) -> bool {
2138 EspChip::press(self, part, pressed)
2139 }
2140
2141 fn set_control(&mut self, part: &str, value: u16) -> bool {
2142 EspChip::set_control(self, part, value)
2143 }
2144
2145 fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2146 EspChip::set_named_control(self, part, name, value)
2147 }
2148
2149 fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2150 EspChip::part_pin_level(self, part, pin)
2151 }
2152
2153 fn gpio_level(&self, gpio: u8) -> Option<Level> {
2154 EspChip::gpio_level(self, gpio)
2155 }
2156
2157 fn conflicts(&self) -> Vec<Conflict> {
2158 EspChip::conflicts(self)
2159 }
2160
2161 fn start_trace(&mut self) {
2162 if let Some(board) = self.board.as_ref() {
2163 board.borrow_mut().start_trace();
2164 }
2165 }
2166
2167 fn vcd(&self) -> String {
2168 self.board
2169 .as_ref()
2170 .map(|board| board.borrow().vcd())
2171 .unwrap_or_default()
2172 }
2173
2174 fn break_at(&mut self, pc: u32) {
2175 EspChip::break_at(self, pc);
2176 }
2177
2178 fn registers(&self) -> String {
2179 self.machine.dump_regs()
2180 }
2181
2182 fn report(&mut self) -> Vec<String> {
2183 EspChip::reports(self)
2184 }
2185
2186 fn enable_coverage(&mut self) {
2187 EspChip::enable_coverage(self);
2188 }
2189
2190 fn display(&mut self) -> Option<(u32, u32, Vec<u16>, u64)> {
2191 self.machine.bus.board().display()
2192 }
2193
2194 fn display_version(&mut self) -> u64 {
2195 self.machine.bus.board().display_version()
2196 }
2197
2198 fn save_display(&mut self, path: &std::path::Path) -> Result<(), String> {
2199 crate::screenshot::capture(self, path)
2200 }
2201
2202 fn save_part_display(&mut self, part: &str, path: &std::path::Path) -> Result<(), String> {
2203 let Some(board) = &self.board else {
2204 return Err("this chip is not attached to a board".into());
2205 };
2206 let image = board
2207 .borrow()
2208 .part_framebuffer(part)
2209 .ok_or_else(|| format!("part {part:?} is not a display with a framebuffer"))?;
2210 std::fs::write(path, image.to_png()).map_err(|e| format!("{}: {e}", path.display()))
2211 }
2212
2213 fn sample_heap(&mut self) -> Result<u32, String> {
2214 EspChip::sample_heap(self)
2215 }
2216
2217 fn touch(&mut self, x: u16, y: u16, down: bool) -> Result<(), String> {
2218 let Some(board) = &self.board else {
2219 return Err("this chip is not attached to a board".into());
2220 };
2221 board.borrow_mut().touch_panel(x, y, down)
2222 }
2223
2224 fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2225 EspChip::start_air_capture(self, path)
2226 }
2227
2228 fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2229 EspChip::start_ethernet_capture(self, path)
2230 }
2231
2232 fn attach_host_gateway(&mut self, forwards: &[String]) -> Result<Vec<String>, String> {
2233 #[cfg(not(target_arch = "wasm32"))]
2234 {
2235 if forwards.is_empty() {
2236 EspChip::attach_host_nat(self, false).map(|()| Vec::new())
2237 } else {
2238 EspChip::attach_host_forwards(self, forwards, false)
2239 }
2240 }
2241 #[cfg(target_arch = "wasm32")]
2242 {
2243 let _ = forwards;
2244 Err("the browser build has no host sockets".into())
2245 }
2246 }
2247
2248 fn debug_available(&self) -> bool {
2249 use emu_core::Core;
2250 self.machine_ref()
2251 .cores
2252 .first()
2253 .map(|core| {
2254 let mut names = Vec::new();
2255 core.regs(&mut names);
2256 names.iter().any(|(name, _)| *name == "ra")
2257 && names.iter().any(|(name, _)| *name == "sp")
2258 })
2259 .unwrap_or(false)
2260 }
2261
2262 fn debug_pc(&self) -> Option<u32> {
2263 use emu_core::Core;
2264 self.machine_ref().cores.first().map(|core| core.pc())
2265 }
2266
2267 fn debug_register_file(&self) -> Option<[u32; 33]> {
2268 use emu_core::Core;
2269 let core = self.machine_ref().cores.first()?;
2270 let mut names = Vec::new();
2271 core.regs(&mut names);
2272 if !names.iter().any(|(name, _)| *name == "ra") {
2273 return None;
2274 }
2275 const RV: [&str; 32] = [
2276 "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2",
2277 "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
2278 "s10", "s11", "t3", "t4", "t5", "t6",
2279 ];
2280 let mut file = [0u32; 33];
2281 for (index, want) in RV.iter().enumerate() {
2282 if let Some((_, value)) = names.iter().find(|(name, _)| name == want) {
2283 file[index] = *value;
2284 }
2285 }
2286 file[32] = core.pc();
2287 Some(file)
2288 }
2289
2290 fn debug_read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
2291 if len == 0 {
2292 return Vec::new();
2293 }
2294 let start = addr & !3;
2295 let skip = (addr - start) as usize;
2296 let words = (skip + len).div_ceil(4);
2297 let text = self.machine_mut().peek(start, words);
2298 let mut bytes = Vec::with_capacity(words * 4);
2299 for line in text.lines() {
2300 let Some((_, word)) = line.split_once(": ") else {
2301 break;
2302 };
2303 let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
2304 break;
2305 };
2306 bytes.extend_from_slice(&word.to_le_bytes());
2307 }
2308 if bytes.len() < skip {
2309 return Vec::new();
2310 }
2311 let end = (skip + len).min(bytes.len());
2312 bytes[skip..end].to_vec()
2313 }
2314
2315 fn debug_disassemble(&mut self, addr: u32, count: usize) -> String {
2316 self.disassemble(addr, count)
2317 }
2318
2319 fn debug_set_breakpoints(&mut self, pcs: &[u32]) {
2320 self.machine_mut().set_breakpoints(pcs.to_vec());
2321 }
2322
2323 fn debug_step(&mut self) -> Option<litz_board::Stop> {
2324 Some(match self.machine_mut().step_one() {
2325 esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2326 esp_soc::Stop::Halted => litz_board::Stop::Halted,
2327 esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2328 esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2329 _ => litz_board::Stop::Idle,
2330 })
2331 }
2332
2333 fn debug(&mut self) -> Option<&mut dyn litz_board::ChipDebug> {
2334 Some(self)
2335 }
2336 }
2337
2338 impl<S: Soc> litz_board::ChipDebug for EspChip<S> {
2339 fn serve(&mut self, port: u16) -> Result<(), String> {
2340 self.gdb_serve(port)
2341 }
2342
2343 fn report(&mut self) -> String {
2344 self.machine.dump_regs()
2345 }
2346 }
2347
2348 #[cfg(all(test, feature = "esp32c3"))]
2349 mod ble_peers {
2350 use super::*;
2351
2352 fn beacon() -> litz_ble::Beacon {
2353 litz_ble::Beacon {
2354 name: Some("late".into()),
2355 services: Vec::new(),
2356 address: [0x04, 0x03, 0x02, 0x01, 0xaa, 0xc4],
2357 rssi: -42,
2358 adv: vec![2, 1, 6, 6, 9, b'l', b'a', b't', b'e'],
2359 scan_response: Vec::new(),
2360 gatt: Vec::new(),
2361 }
2362 }
2363
2364 #[test]
2368 fn a_peer_added_at_runtime_reaches_a_live_scan() {
2369 let mut chip = C3::new([0x24, 0x0a, 0xc4, 0x00, 0x01, 0x10], 4 << 20);
2370 assert_eq!(
2371 chip.add_ble_peer(&beacon()).unwrap_err(),
2372 "BLE is not enabled on this chip"
2373 );
2374 chip.machine_mut().bus.ble.hooks.push(0);
2375 chip.machine_mut().bus.ble.lines.keep();
2376 chip.ble_attached = true;
2377
2378 chip.machine_mut()
2380 .bus
2381 .ble
2382 .session
2383 .send(&[1, 0x0c, 0x20, 2, 1, 0]);
2384 chip.machine_mut().bus.ble.session.drain_log();
2385
2386 chip.add_ble_peer(&beacon())
2387 .expect("the scan accepts the list");
2388 assert_eq!(chip.ble_peers.len(), 1);
2389 let line = chip.ble_log().expect("the controller logged a report");
2390 assert!(line.contains("scan report"), "{line}");
2391 assert!(line.contains("c4:aa:01:02:03:04"), "{line}");
2392 }
2393 }
2394}
2395
2396const PLIC_AND_RV_MAP: [MemoryRegion; 6] = [
2397 MemoryRegion::new("irom", 0x4200_0000, 0x0040_0000),
2398 MemoryRegion::new("drom", 0x3C00_0000, 0x0040_0000),
2399 MemoryRegion::new("dram", 0x3FC8_0000, 0x0004_0000),
2400 MemoryRegion::new("irom-dram", 0x4037_C000, 0x0000_8000),
2401 MemoryRegion::new("peripherals", 0x6000_0000, 0x0010_0000),
2402 MemoryRegion::new("rtc", 0x5000_0000, 0x0001_0000),
2403];