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 if !self.open {
1302 self.written.clear();
1303 self.received.clear();
1304 self.open = true;
1305 self.started_at = self.board.borrow().now();
1306 }
1307 self.reading = read;
1308 let mut board = self.board.borrow_mut();
1309 let Some(bus) = board
1310 .buses_mut()
1311 .i2c
1312 .get_mut(&(self.board_index, self.controller))
1313 else {
1314 return false;
1315 };
1316 let Some(device) = bus.device_mut(self.address) else {
1317 return false;
1318 };
1319 device.connect(read);
1320 true
1321 }
1322
1323 fn write(&mut self, byte: u8) -> bool {
1324 if !self.reading {
1325 self.written.push(byte);
1326 }
1327 let mut board = self.board.borrow_mut();
1328 let Some(bus) = board
1329 .buses_mut()
1330 .i2c
1331 .get_mut(&(self.board_index, self.controller))
1332 else {
1333 return false;
1334 };
1335 let Some(device) = bus.device_mut(self.address) else {
1336 return false;
1337 };
1338 device.write(byte)
1339 }
1340
1341 fn read(&mut self) -> u8 {
1342 let byte = {
1343 let mut board = self.board.borrow_mut();
1344 let Some(bus) = board
1345 .buses_mut()
1346 .i2c
1347 .get_mut(&(self.board_index, self.controller))
1348 else {
1349 return 0xff;
1350 };
1351 let Some(device) = bus.device_mut(self.address) else {
1352 return 0xff;
1353 };
1354 device.read()
1355 };
1356 self.received.push(byte);
1357 byte
1358 }
1359
1360 fn stop(&mut self) {
1361 {
1362 let mut board = self.board.borrow_mut();
1363 let Some(bus) = board
1364 .buses_mut()
1365 .i2c
1366 .get_mut(&(self.board_index, self.controller))
1367 else {
1368 return;
1369 };
1370 if let Some(device) = bus.device_mut(self.address) {
1371 device.stop();
1372 }
1373 }
1374 if self.open {
1375 let mut board = self.board.borrow_mut();
1376 let end = board.now();
1377 let at = self.started_at.max(self.last_at);
1378 let phases = 1
1379 + self.written.len()
1380 + if self.received.is_empty() {
1381 0
1382 } else {
1383 1 + self.received.len()
1384 };
1385 let elapsed = end.saturating_sub(self.started_at);
1390 let hz = if elapsed > 0 {
1391 (phases as u128 * 9 * 1_000_000_000 / u128::from(elapsed))
1392 .clamp(1_000, 5_000_000) as u32
1393 } else {
1394 board.i2c_hz(self.board_index, self.controller)
1395 };
1396 board.set_i2c_hz(self.board_index, self.controller, hz);
1397 board.observe_i2c(
1398 self.board_index,
1399 self.controller,
1400 self.address,
1401 &self.written,
1402 &self.received,
1403 at,
1404 );
1405 let period = 1_000_000_000 / u64::from(hz);
1406 self.last_at = (at + phases as u64 * 9 * period).max(end);
1407 }
1408 self.open = false;
1409 self.reading = false;
1410 }
1411 }
1412
1413 #[derive(Clone, Copy)]
1420 struct SpiClockSpec {
1421 ports: [(u32, u32, u32); 2],
1423 }
1424
1425 #[cfg(feature = "esp32")]
1426 const ESP32_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1427 ports: [(0x3ff6_4018, 18, 0x1fff), (0x3ff6_5018, 18, 0x1fff)],
1428 };
1429
1430 #[cfg(feature = "esp32s3")]
1431 const S3_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1432 ports: [(0x6002_400c, 18, 0xf), (0x6002_500c, 18, 0xf)],
1433 };
1434
1435 struct SpiClockObserver {
1442 rates: Rc<Cell<[u32; 2]>>,
1443 spec: SpiClockSpec,
1444 }
1445
1446 impl<S: Soc> esp_soc::Observer<S> for SpiClockObserver {
1447 fn name(&self) -> &'static str {
1448 "litz-spi-clock"
1449 }
1450
1451 fn wants(&self) -> esp_soc::Wants {
1452 esp_soc::Wants::MMIO
1453 }
1454
1455 fn on_mmio(&mut self, _cx: &esp_soc::Ctx, _pc: u32, addr: u32, value: u32, write: bool) {
1456 if !write {
1457 return;
1458 }
1459 let Some(slot) = self.spec.ports.iter().position(|&(reg, ..)| reg == addr) else {
1460 return;
1461 };
1462 let (_, shift, mask) = self.spec.ports[slot];
1463 let divider = if value & (1 << 31) != 0 {
1466 1
1467 } else {
1468 (((value >> shift) & mask) + 1) * (((value >> 12) & 0x3f) + 1)
1469 };
1470 let mut rates = self.rates.get();
1471 rates[slot] = (esp_periph::APB_HZ / u64::from(divider)) as u32;
1472 self.rates.set(rates);
1473 }
1474 }
1475
1476 struct LitzModel {
1482 board: Rc<RefCell<LitzBoard>>,
1483 index: u16,
1485 enabled: u64,
1486 output: u64,
1487 cycle: u64,
1488 releases: Vec<u8>,
1489 cpu_hz: u64,
1492 uart_routes: BTreeMap<u8, (u8, u32)>,
1496 spi_rates: Rc<Cell<[u32; 2]>>,
1499 }
1500
1501 impl LitzModel {
1502 fn new(
1503 board: Rc<RefCell<LitzBoard>>,
1504 cpu_hz: u64,
1505 index: u16,
1506 spi_rates: Rc<Cell<[u32; 2]>>,
1507 ) -> Self {
1508 Self {
1509 board,
1510 index,
1511 enabled: 0,
1512 output: 0,
1513 cycle: 0,
1514 releases: Vec::new(),
1515 cpu_hz,
1516 uart_routes: BTreeMap::new(),
1517 spi_rates,
1518 }
1519 }
1520
1521 fn spi_rate(&self, host: u8) -> Option<u32> {
1523 let slot = usize::from(host.checked_sub(2)?);
1524 let hz = *self.spi_rates.get().get(slot)?;
1525 (hz > 0).then_some(hz)
1526 }
1527
1528 fn ns(&self, cycle: u64) -> u64 {
1529 (u128::from(cycle) * 1_000_000_000 / u128::from(self.cpu_hz)) as u64
1530 }
1531
1532 fn cycles_for(&self, ns: u64) -> u64 {
1535 let cycles = u128::from(ns) * u128::from(self.cpu_hz);
1536 (cycles.div_ceil(1_000_000_000)) as u64
1537 }
1538 }
1539
1540 fn expand_monochrome(bytes: &[u8], width: u32, height: u32) -> Vec<u16> {
1543 let mut pixels = vec![0u16; (width * height) as usize];
1544 for page in 0..height.div_ceil(8) {
1545 for column in 0..width {
1546 let Some(byte) = bytes.get((page * width + column) as usize) else {
1547 continue;
1548 };
1549 for bit in 0..8u32 {
1550 let y = page * 8 + bit;
1551 if y >= height {
1552 break;
1553 }
1554 if byte & (1 << bit) != 0 {
1555 pixels[(y * width + column) as usize] = 0xffff;
1556 }
1557 }
1558 }
1559 }
1560 pixels
1561 }
1562
1563 fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1566 let mut data = [0u8; litz_board::bus::CAN_MAX_DATA];
1568 let len = usize::from(frame.len).min(frame.data.len());
1569 data[..len].copy_from_slice(&frame.data[..len]);
1570 litz_board::bus::CanFrame {
1571 id: frame.id,
1572 extended: frame.extended,
1573 rtr: frame.rtr,
1574 len: frame.len,
1575 data,
1576 kind: if frame.rtr {
1577 litz_board::bus::CanFrameKind::Remote
1578 } else {
1579 litz_board::bus::CanFrameKind::Classic
1580 },
1581 }
1582 }
1583
1584 impl BoardModel for LitzModel {
1585 fn name(&self) -> &'static str {
1586 "litz"
1587 }
1588
1589 fn gpio_output_at(
1590 &mut self,
1591 cycle: u64,
1592 changes: &[(u8, bool)],
1593 enabled: u64,
1594 output: u64,
1595 ) {
1596 self.cycle = self.cycle.max(cycle);
1600 let now = self.ns(self.cycle);
1601 if std::env::var("LITZ_TRACE_DEBUG").is_ok() {
1602 eprintln!("DBG cycle={} now={}", self.cycle, now);
1603 }
1604 let mut mask = (enabled ^ self.enabled) | (output ^ self.output);
1607 for &(pin, _) in changes {
1608 mask |= 1u64 << pin;
1609 }
1610 let mut board = self.board.borrow_mut();
1611 while mask != 0 {
1612 let pin = mask.trailing_zeros() as u8;
1613 mask &= mask - 1;
1614 let bit = 1u64 << pin;
1615 let drive = if enabled & bit != 0 {
1616 if output & bit != 0 {
1617 Drive::strong(Level::High)
1618 } else {
1619 Drive::strong(Level::Low)
1620 }
1621 } else {
1622 Drive::HIGH_Z
1623 };
1624 board.set_chip_output_on(self.index, pin, drive, now);
1625 }
1626 self.enabled = enabled;
1627 self.output = output;
1628 }
1629
1630 fn display(&self) -> Option<(u32, u32, Vec<u16>, u64)> {
1635 let board = self.board.borrow();
1636 let buses = board.buses();
1637 for (&(owner, _), i2c) in &buses.i2c {
1638 if owner != self.index {
1639 continue;
1640 }
1641 for address in i2c.addresses() {
1642 if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1643 let (bytes, width, height) = oled.framebuffer();
1644 return Some((
1645 width,
1646 height,
1647 expand_monochrome(bytes, width, height),
1648 oled.frame_version(),
1649 ));
1650 }
1651 }
1652 }
1653 for (&(owner, _), spi) in &buses.spi {
1654 if owner != self.index {
1655 continue;
1656 }
1657 for select in spi.chip_selects() {
1658 if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1659 let (pixels, width, height) = tft.framebuffer();
1660 return Some((width, height, pixels.to_vec(), tft.frame_version()));
1661 }
1662 }
1663 }
1664 None
1665 }
1666
1667 fn touch(&mut self, x: u16, y: u16, down: bool) {
1671 let _ = self.board.borrow_mut().touch_panel(x, y, down);
1672 }
1673
1674 fn display_version(&self) -> u64 {
1675 let board = self.board.borrow();
1676 let buses = board.buses();
1677 for (&(owner, _), i2c) in &buses.i2c {
1678 if owner != self.index {
1679 continue;
1680 }
1681 for address in i2c.addresses() {
1682 if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1683 return oled.frame_version();
1684 }
1685 }
1686 }
1687 for (&(owner, _), spi) in &buses.spi {
1688 if owner != self.index {
1689 continue;
1690 }
1691 for select in spi.chip_selects() {
1692 if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1693 return tft.frame_version();
1694 }
1695 }
1696 }
1697 0
1698 }
1699
1700 fn advance_to(&mut self, cycle: u64) {
1701 self.cycle = cycle;
1702 let now = self.ns(cycle);
1707 self.board.borrow_mut().advance_to(now);
1708 }
1709
1710 fn next_deadline(&self) -> Option<u64> {
1711 let board = self.board.borrow();
1714 let now = board.has_pending_inputs_on(self.index).then_some(0);
1715 let event = board.next_event().map(|at| self.cycles_for(at));
1716 match (now, event) {
1717 (Some(a), Some(b)) => Some(a.min(b)),
1718 (a, b) => a.or(b),
1719 }
1720 }
1721
1722 fn take_edges(&mut self) -> Vec<BoardEdge> {
1723 let cycle = self.cycle;
1724 let drained = self.board.borrow_mut().take_chip_inputs_on(self.index);
1725 let mut levels: BTreeMap<u8, Level> = BTreeMap::new();
1731 for (pin, level) in drained {
1732 levels.insert(pin, level);
1733 }
1734 let mut edges = Vec::new();
1735 for (pin, level) in levels {
1736 match level {
1737 Level::High => edges.push(BoardEdge {
1738 cycle,
1739 pin,
1740 level: true,
1741 }),
1742 Level::Low => edges.push(BoardEdge {
1743 cycle,
1744 pin,
1745 level: false,
1746 }),
1747 Level::HighZ => self.releases.push(pin),
1748 }
1749 }
1750 edges
1751 }
1752
1753 fn released_inputs(&mut self) -> Vec<u8> {
1754 core::mem::take(&mut self.releases)
1755 }
1756
1757 fn input_levels(&self) -> Vec<(u8, bool)> {
1758 self.board
1759 .borrow()
1760 .input_levels_on(self.index)
1761 .into_iter()
1762 .filter_map(|(pin, level)| match level {
1763 Level::High => Some((pin, true)),
1764 Level::Low => Some((pin, false)),
1765 Level::HighZ => None,
1766 })
1767 .collect()
1768 }
1769
1770 fn named_pin(&self, name: &str) -> Option<u8> {
1771 let board = self.board.borrow();
1772 let (index, pin) = board.named_pin_on(name)?;
1773 (index == self.index).then_some(pin)
1774 }
1775
1776 fn i2c_devices(&mut self) -> Vec<(u8, u8, Box<dyn EspI2cDevice>)> {
1781 let board = self.board.borrow();
1782 let mut devices: Vec<(u8, u8)> = Vec::new();
1783 for (&(owner, controller), bus) in &board.buses().i2c {
1784 if owner != self.index {
1785 continue;
1786 }
1787 for address in bus.addresses() {
1788 devices.push((controller, address));
1789 }
1790 }
1791 drop(board);
1792 devices
1793 .into_iter()
1794 .map(|(controller, address)| {
1795 let device: Box<dyn EspI2cDevice> = Box::new(BoardI2cDevice {
1796 board: Rc::clone(&self.board),
1797 board_index: self.index,
1798 controller,
1799 address,
1800 written: Vec::new(),
1801 received: Vec::new(),
1802 reading: false,
1803 open: false,
1804 last_at: 0,
1805 started_at: 0,
1806 });
1807 (controller, address, device)
1808 })
1809 .collect()
1810 }
1811
1812 fn uses_spi_pins(&self) -> bool {
1813 self.board
1814 .borrow()
1815 .buses()
1816 .spi
1817 .keys()
1818 .any(|&(owner, _)| owner == self.index)
1819 }
1820
1821 fn spi_transfer(&mut self, host: u8, tx: &[u8], rx_len: usize) -> Vec<u8> {
1826 let rate = self.spi_rate(host);
1827 let mut board = self.board.borrow_mut();
1828 let selected = board
1829 .buses()
1830 .spi_sole(self.index, host)
1831 .or_else(|| board.buses().spi_only_device(self.index));
1832 match selected {
1833 Some((controller, chip_select)) => {
1834 if let Some(hz) = rate {
1837 board.set_spi_hz(self.index, controller, hz);
1838 }
1839 board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1840 }
1841 None => vec![0xff; rx_len],
1842 }
1843 }
1844
1845 fn spi_transfer_pins(
1848 &mut self,
1849 host: u8,
1850 pins: SpiPins,
1851 tx: &[u8],
1852 rx_len: usize,
1853 ) -> Vec<u8> {
1854 let rate = self.spi_rate(host);
1855 let mut board = self.board.borrow_mut();
1856 match board.buses().spi_selected(self.index, pins.cs) {
1857 Some((controller, chip_select)) => {
1858 if let Some(hz) = rate {
1859 board.set_spi_hz(self.index, controller, hz);
1860 }
1861 board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1862 }
1863 None => vec![0xff; rx_len],
1864 }
1865 }
1866
1867 fn uses_uart_pins(&self) -> bool {
1868 let board = self.board.borrow();
1869 if board
1870 .buses()
1871 .uart
1872 .keys()
1873 .any(|&(owner, _)| owner == self.index)
1874 {
1875 return true;
1876 }
1877 board.flat().has_chip_to_chip_wire(self.index)
1880 }
1881
1882 fn uart_tx(&mut self, cycle: u64, route: UartRoute, byte: u8) {
1885 let now = self.ns(cycle);
1886 let port = route.port as u8;
1887 let baud = route
1888 .baud
1889 .unwrap_or(litz_board::runtime::OBSERVED_UART_BAUD);
1890 let mut board = self.board.borrow_mut();
1891 board.set_uart_baud(self.index, port, baud);
1892 board.set_uart_pins(self.index, port, route.tx_pins, route.rx_pin);
1894 board.uart_receive(self.index, port, now, &[byte]);
1895 drop(board);
1896 if let Some(pin) = route.rx_pin {
1897 self.uart_routes
1898 .insert(port, (pin, route.baud.unwrap_or(115_200)));
1899 }
1900 }
1901
1902 fn uart_rx(&mut self, cycle: u64) -> Vec<UartInput> {
1907 let now = self.ns(cycle);
1908 let mut board = self.board.borrow_mut();
1909 for (&port, &(_, baud)) in &self.uart_routes {
1910 board.set_uart_baud(self.index, port, baud);
1911 }
1912 let mut ports: BTreeMap<u8, Option<(u8, u32)>> = self
1915 .uart_routes
1916 .iter()
1917 .map(|(&port, &route)| (port, Some(route)))
1918 .collect();
1919 for &(owner, port) in board.buses().uart.keys() {
1920 if owner != self.index {
1921 continue;
1922 }
1923 ports.entry(port).or_insert_with(|| {
1924 board
1925 .flat()
1926 .buses
1927 .uart
1928 .get(&(self.index, port))
1929 .map(|bus| (bus.chip_rx, 115_200))
1930 });
1931 }
1932 let mut inputs = Vec::new();
1933 for (port, route) in ports {
1934 let Some((pin, baud)) = route else { continue };
1935 let data = board.uart_poll(self.index, port, now);
1936 if !data.is_empty() {
1937 inputs.push(UartInput::new(pin, baud, data));
1938 }
1939 }
1940 inputs
1941 }
1942
1943 fn can_tx(&mut self, _host: u8, frame: &[u8]) {
1946 let Some(frame) = esp_soc::board::CanFrame::decode(frame) else {
1947 return;
1948 };
1949 let mut board = self.board.borrow_mut();
1950 let can = board.buses_mut().can_mut();
1951 can.attach(self.index);
1952 let _ = can.transmit(self.index, board_can_frame(&frame));
1953 }
1954
1955 fn can_take(&mut self, _host: u8) -> Option<Vec<u8>> {
1959 let mut board = self.board.borrow_mut();
1960 let can = board.buses_mut().can_mut();
1961 can.attach(self.index);
1962 let frame = can.take(self.index)?;
1963 let mut data = [0u8; esp_soc::board::CAN_MAX_DATA];
1965 let len = usize::from(frame.len).min(data.len());
1966 data[..len].copy_from_slice(&frame.data[..len]);
1967 Some(
1968 esp_soc::board::CanFrame {
1969 id: frame.id,
1970 extended: frame.extended,
1971 rtr: frame.rtr || frame.kind == litz_board::bus::CanFrameKind::Remote,
1972 len: frame.len,
1973 data,
1974 }
1975 .encode()
1976 .to_vec(),
1977 )
1978 }
1979 }
1980
1981 impl<S: Soc> litz_board::Chip for EspChip<S> {
1984 fn info(&self) -> litz_board::ChipInfo {
1985 litz_board::ChipInfo {
1986 name: S::NAME.into(),
1987 cpu_hz: S::CPU_HZ,
1988 flash: litz_board::FlashLayout {
1989 size: self.flash as u64,
1990 bootloader: S::BOOTLOADER_OFFSET as u64,
1991 partition_table: 0x8000,
1992 app: 0x1_0000,
1993 },
1994 }
1995 }
1996
1997 fn load_image(
1998 &mut self,
1999 kind: litz_board::ImageKind,
2000 offset: u64,
2001 bytes: &[u8],
2002 ) -> Result<(), String> {
2003 match kind {
2004 litz_board::ImageKind::Rom => self.load_rom(bytes),
2005 litz_board::ImageKind::Bootloader => {
2006 self.bootloader_loaded = true;
2007 self.write_flash(offset as usize, bytes)
2008 }
2009 _ => self.write_flash(offset as usize, bytes),
2010 }
2011 }
2012
2013 fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
2014 EspChip::set_psram_size(self, bytes)
2015 }
2016
2017 fn flash_image(&self) -> Option<Vec<u8>> {
2018 EspChip::flash_image(self).map(<[u8]>::to_vec)
2019 }
2020
2021 fn boot(&mut self) -> Result<u32, String> {
2022 self.powered = self.board_power();
2023 if !self.powered {
2024 return Ok(0);
2027 }
2028 if self.bootloader_loaded {
2029 return Ok(0);
2032 }
2033 let app = self.info().flash.app as usize;
2034 self.boot_app(app)
2035 }
2036
2037 fn schedule(&mut self, inputs: Vec<litz_board::Input>) -> Result<(), String> {
2038 let mut text = String::new();
2039 for input in inputs {
2040 match input {
2041 litz_board::Input::Gpio { at_ns, pin, level } => {
2042 let seconds = at_ns as f64 / 1e9;
2043 let bit = u8::from(level == Level::High);
2044 text.push_str(&format!("{seconds:.6} gpio {pin} {bit}\n"));
2045 }
2046 litz_board::Input::Uart { at_ns, bytes } => {
2047 let seconds = at_ns as f64 / 1e9;
2048 let text_in = String::from_utf8_lossy(&bytes);
2049 text.push_str(&format!(
2051 "{seconds:.6} uart0 {}\n",
2052 text_in.trim_end_matches('\n')
2053 ));
2054 }
2055 }
2056 }
2057 if text.is_empty() {
2058 Ok(())
2059 } else {
2060 self.load_script(&text)
2061 }
2062 }
2063
2064 fn run(&mut self, budget_cycles: u64) -> litz_board::RunResult {
2065 if !EspChip::board_power(self) {
2066 if self.powered {
2067 self.power_off();
2068 }
2069 let cycles = u128::from(budget_cycles) * 1_000_000_000;
2072 let cpu_hz = u128::from(litz_board::Chip::info(self).cpu_hz.max(1));
2073 self.off_ns = self.off_ns.saturating_add((cycles / cpu_hz) as u64);
2074 return litz_board::RunResult {
2075 cycles: budget_cycles,
2076 stop: litz_board::Stop::Idle,
2077 };
2078 }
2079 if !self.powered {
2080 if self.boot_after_power().is_err() {
2082 return litz_board::RunResult {
2083 cycles: 0,
2084 stop: litz_board::Stop::Trap,
2085 };
2086 }
2087 self.powered = true;
2088 }
2089 let stop = match EspChip::run(self, budget_cycles) {
2090 esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2091 esp_soc::Stop::Halted => litz_board::Stop::Halted,
2092 esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2093 esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2094 _ => litz_board::Stop::Idle,
2095 };
2096 self.publish_pwm();
2097 litz_board::RunResult {
2098 cycles: budget_cycles,
2099 stop,
2100 }
2101 }
2102
2103 fn seconds(&self) -> f64 {
2104 EspChip::seconds(self)
2105 }
2106
2107 fn write_console(&mut self, bytes: &[u8]) {
2108 self.write_serial(bytes);
2112 }
2113
2114 fn take_console(&mut self) -> Vec<u8> {
2115 let mut bytes = self.take_uart0();
2116 let usb = core::mem::take(&mut self.machine.console.usb);
2122 if usb != bytes {
2123 bytes.extend(usb);
2124 }
2125 bytes
2126 }
2127
2128 fn state(&self, part: &str) -> Option<PartState> {
2129 EspChip::state(self, part)
2130 }
2131
2132 fn press(&mut self, part: &str, pressed: bool) -> bool {
2133 EspChip::press(self, part, pressed)
2134 }
2135
2136 fn set_control(&mut self, part: &str, value: u16) -> bool {
2137 EspChip::set_control(self, part, value)
2138 }
2139
2140 fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2141 EspChip::set_named_control(self, part, name, value)
2142 }
2143
2144 fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2145 EspChip::part_pin_level(self, part, pin)
2146 }
2147
2148 fn gpio_level(&self, gpio: u8) -> Option<Level> {
2149 EspChip::gpio_level(self, gpio)
2150 }
2151
2152 fn conflicts(&self) -> Vec<Conflict> {
2153 EspChip::conflicts(self)
2154 }
2155
2156 fn start_trace(&mut self) {
2157 if let Some(board) = self.board.as_ref() {
2158 board.borrow_mut().start_trace();
2159 }
2160 }
2161
2162 fn vcd(&self) -> String {
2163 self.board
2164 .as_ref()
2165 .map(|board| board.borrow().vcd())
2166 .unwrap_or_default()
2167 }
2168
2169 fn break_at(&mut self, pc: u32) {
2170 EspChip::break_at(self, pc);
2171 }
2172
2173 fn registers(&self) -> String {
2174 self.machine.dump_regs()
2175 }
2176
2177 fn report(&mut self) -> Vec<String> {
2178 EspChip::reports(self)
2179 }
2180
2181 fn enable_coverage(&mut self) {
2182 EspChip::enable_coverage(self);
2183 }
2184
2185 fn display(&mut self) -> Option<(u32, u32, Vec<u16>, u64)> {
2186 self.machine.bus.board().display()
2187 }
2188
2189 fn display_version(&mut self) -> u64 {
2190 self.machine.bus.board().display_version()
2191 }
2192
2193 fn save_display(&mut self, path: &std::path::Path) -> Result<(), String> {
2194 crate::screenshot::capture(self, path)
2195 }
2196
2197 fn save_part_display(&mut self, part: &str, path: &std::path::Path) -> Result<(), String> {
2198 let Some(board) = &self.board else {
2199 return Err("this chip is not attached to a board".into());
2200 };
2201 let image = board
2202 .borrow()
2203 .part_framebuffer(part)
2204 .ok_or_else(|| format!("part {part:?} is not a display with a framebuffer"))?;
2205 std::fs::write(path, image.to_png()).map_err(|e| format!("{}: {e}", path.display()))
2206 }
2207
2208 fn sample_heap(&mut self) -> Result<u32, String> {
2209 EspChip::sample_heap(self)
2210 }
2211
2212 fn touch(&mut self, x: u16, y: u16, down: bool) -> Result<(), String> {
2213 let Some(board) = &self.board else {
2214 return Err("this chip is not attached to a board".into());
2215 };
2216 board.borrow_mut().touch_panel(x, y, down)
2217 }
2218
2219 fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2220 EspChip::start_air_capture(self, path)
2221 }
2222
2223 fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2224 EspChip::start_ethernet_capture(self, path)
2225 }
2226
2227 fn attach_host_gateway(&mut self, forwards: &[String]) -> Result<Vec<String>, String> {
2228 #[cfg(not(target_arch = "wasm32"))]
2229 {
2230 if forwards.is_empty() {
2231 EspChip::attach_host_nat(self, false).map(|()| Vec::new())
2232 } else {
2233 EspChip::attach_host_forwards(self, forwards, false)
2234 }
2235 }
2236 #[cfg(target_arch = "wasm32")]
2237 {
2238 let _ = forwards;
2239 Err("the browser build has no host sockets".into())
2240 }
2241 }
2242
2243 fn debug_available(&self) -> bool {
2244 use emu_core::Core;
2245 self.machine_ref()
2246 .cores
2247 .first()
2248 .map(|core| {
2249 let mut names = Vec::new();
2250 core.regs(&mut names);
2251 names.iter().any(|(name, _)| *name == "ra")
2252 && names.iter().any(|(name, _)| *name == "sp")
2253 })
2254 .unwrap_or(false)
2255 }
2256
2257 fn debug_pc(&self) -> Option<u32> {
2258 use emu_core::Core;
2259 self.machine_ref().cores.first().map(|core| core.pc())
2260 }
2261
2262 fn debug_register_file(&self) -> Option<[u32; 33]> {
2263 use emu_core::Core;
2264 let core = self.machine_ref().cores.first()?;
2265 let mut names = Vec::new();
2266 core.regs(&mut names);
2267 if !names.iter().any(|(name, _)| *name == "ra") {
2268 return None;
2269 }
2270 const RV: [&str; 32] = [
2271 "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2",
2272 "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
2273 "s10", "s11", "t3", "t4", "t5", "t6",
2274 ];
2275 let mut file = [0u32; 33];
2276 for (index, want) in RV.iter().enumerate() {
2277 if let Some((_, value)) = names.iter().find(|(name, _)| name == want) {
2278 file[index] = *value;
2279 }
2280 }
2281 file[32] = core.pc();
2282 Some(file)
2283 }
2284
2285 fn debug_read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
2286 if len == 0 {
2287 return Vec::new();
2288 }
2289 let start = addr & !3;
2290 let skip = (addr - start) as usize;
2291 let words = (skip + len).div_ceil(4);
2292 let text = self.machine_mut().peek(start, words);
2293 let mut bytes = Vec::with_capacity(words * 4);
2294 for line in text.lines() {
2295 let Some((_, word)) = line.split_once(": ") else {
2296 break;
2297 };
2298 let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
2299 break;
2300 };
2301 bytes.extend_from_slice(&word.to_le_bytes());
2302 }
2303 if bytes.len() < skip {
2304 return Vec::new();
2305 }
2306 let end = (skip + len).min(bytes.len());
2307 bytes[skip..end].to_vec()
2308 }
2309
2310 fn debug_disassemble(&mut self, addr: u32, count: usize) -> String {
2311 self.disassemble(addr, count)
2312 }
2313
2314 fn debug_set_breakpoints(&mut self, pcs: &[u32]) {
2315 self.machine_mut().set_breakpoints(pcs.to_vec());
2316 }
2317
2318 fn debug_step(&mut self) -> Option<litz_board::Stop> {
2319 Some(match self.machine_mut().step_one() {
2320 esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2321 esp_soc::Stop::Halted => litz_board::Stop::Halted,
2322 esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2323 esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2324 _ => litz_board::Stop::Idle,
2325 })
2326 }
2327
2328 fn debug(&mut self) -> Option<&mut dyn litz_board::ChipDebug> {
2329 Some(self)
2330 }
2331 }
2332
2333 impl<S: Soc> litz_board::ChipDebug for EspChip<S> {
2334 fn serve(&mut self, port: u16) -> Result<(), String> {
2335 self.gdb_serve(port)
2336 }
2337
2338 fn report(&mut self) -> String {
2339 self.machine.dump_regs()
2340 }
2341 }
2342
2343 #[cfg(all(test, feature = "esp32c3"))]
2344 mod ble_peers {
2345 use super::*;
2346
2347 fn beacon() -> litz_ble::Beacon {
2348 litz_ble::Beacon {
2349 name: Some("late".into()),
2350 services: Vec::new(),
2351 address: [0x04, 0x03, 0x02, 0x01, 0xaa, 0xc4],
2352 rssi: -42,
2353 adv: vec![2, 1, 6, 6, 9, b'l', b'a', b't', b'e'],
2354 scan_response: Vec::new(),
2355 gatt: Vec::new(),
2356 }
2357 }
2358
2359 #[test]
2363 fn a_peer_added_at_runtime_reaches_a_live_scan() {
2364 let mut chip = C3::new([0x24, 0x0a, 0xc4, 0x00, 0x01, 0x10], 4 << 20);
2365 assert_eq!(
2366 chip.add_ble_peer(&beacon()).unwrap_err(),
2367 "BLE is not enabled on this chip"
2368 );
2369 chip.machine_mut().bus.ble.hooks.push(0);
2370 chip.machine_mut().bus.ble.lines.keep();
2371 chip.ble_attached = true;
2372
2373 chip.machine_mut()
2375 .bus
2376 .ble
2377 .session
2378 .send(&[1, 0x0c, 0x20, 2, 1, 0]);
2379 chip.machine_mut().bus.ble.session.drain_log();
2380
2381 chip.add_ble_peer(&beacon())
2382 .expect("the scan accepts the list");
2383 assert_eq!(chip.ble_peers.len(), 1);
2384 let line = chip.ble_log().expect("the controller logged a report");
2385 assert!(line.contains("scan report"), "{line}");
2386 assert!(line.contains("c4:aa:01:02:03:04"), "{line}");
2387 }
2388 }
2389}
2390
2391const PLIC_AND_RV_MAP: [MemoryRegion; 6] = [
2392 MemoryRegion::new("irom", 0x4200_0000, 0x0040_0000),
2393 MemoryRegion::new("drom", 0x3C00_0000, 0x0040_0000),
2394 MemoryRegion::new("dram", 0x3FC8_0000, 0x0004_0000),
2395 MemoryRegion::new("irom-dram", 0x4037_C000, 0x0000_8000),
2396 MemoryRegion::new("peripherals", 0x6000_0000, 0x0010_0000),
2397 MemoryRegion::new("rtc", 0x5000_0000, 0x0001_0000),
2398];