From 9d5851bd9852774e6df11032c4bd0536549224be Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 25 Jan 2026 18:32:24 +0800 Subject: [PATCH 01/28] adjust attack threshold trip for recording attack in practice we're seeing multiple trips to the glitch detector when power down discharge is slow. --- libs/bao1x-hal/src/hardening.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libs/bao1x-hal/src/hardening.rs b/libs/bao1x-hal/src/hardening.rs index 889a8c6bf..82e1bbf1c 100644 --- a/libs/bao1x-hal/src/hardening.rs +++ b/libs/bao1x-hal/src/hardening.rs @@ -19,7 +19,9 @@ pub const WIPE_THRESHOLD: u32 = 127; /// This number is empirically tuned. The main issue is we don't want to notch up the /// counter during "slow shutdowns" where the power supply falls gradually enough that /// the glitch detector can fire. -const DISTURB_THRESHOLD: u32 = 2; +/// Empirically, during a shutdown, this reaches a value of around 10 on some boards. +/// Margin it up to 16, to avoid false alarms. +const DISTURB_THRESHOLD: u32 = 16; /// This is the range of delays we will pick from whenever we attempt a random delay, /// expressed as a number of bits. @@ -434,7 +436,7 @@ pub fn glitch_handler(attacks_since_boot: u32) { // even output something on the DUART - this could be used as a trigger to prevent shutdown // but at this point diagnostics are useful for seeing why the system shut down unexpectedly. #[cfg(feature = "debug-countermeasures")] - crate::println!("Attack thresh"); + crate::println!("Attack thresh trip: {}", attacks_since_boot); crate::sigcheck::die_no_std(); } From 026ba8654a9f85c2e30555a323d328da7d463399 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 25 Jan 2026 18:33:14 +0800 Subject: [PATCH 02/28] remember debug-countermeasures option as a comment --- bao1x-boot/boot1/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/bao1x-boot/boot1/Cargo.toml b/bao1x-boot/boot1/Cargo.toml index dd6b4922b..84d72a01a 100644 --- a/bao1x-boot/boot1/Cargo.toml +++ b/bao1x-boot/boot1/Cargo.toml @@ -36,6 +36,7 @@ bao1x = [ "bao1x-hal/loader-baosec", "bao1x-hal/security", # "bao1x-hal/debug-print-duart", + # "bao1x-hal/debug-countermeasures", "bao1x-api", # needed for the boot logo "ux-api/loader-baosec", From 955c85b22e5bd18dba1814270bb184086cccfb7d Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 25 Jan 2026 18:34:43 +0800 Subject: [PATCH 03/28] move statics initialization to top, adjust oled power-on timing - statics need to be initialized before IRQs are turned on. - oled power-on sequence is adjusted to clean up display on "rough" power-on transients --- bao1x-boot/boot1/src/platform/bao1x/bao1x.rs | 83 ++++++++++---------- 1 file changed, 43 insertions(+), 40 deletions(-) diff --git a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs index 852c32957..e15171fd1 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs @@ -151,6 +151,36 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa // does, but we leave this commented out for non-debug situations because it's a weak guarantee. // crate::debug::USE_CONSOLE.store(true, core::sync::atomic::Ordering::SeqCst); + // ======= setup .data section ======== + // this has to happen "up top" before any IRQs happen because IRQs rely on static variables for + // correctness. So: + // - ASSUME: basic clocks are sane because boot0 set those up. + // - ASSUME: SRAM trim wait states are set up correctly (sram0 has 1 wait state) + + // Now that SRAM trims are setup, initialize all the statics by writing to memory. + // For baremetal, the statics structure is just at the flash base. + const STATICS_LOC: usize = bao1x_api::BOOT1_START + SIGBLOCK_LEN; + + // safety: this data structure is pre-loaded by the image loader and is guaranteed to + // only have representable, valid values that are aligned according to the repr(C) spec + let statics_in_rom: &bao1x_api::StaticsInRom = + unsafe { (STATICS_LOC as *const bao1x_api::StaticsInRom).as_ref().unwrap() }; + assert!(statics_in_rom.version == bao1x_api::STATICS_IN_ROM_VERSION, "Can't find valid statics table"); + + // Clear .data, .bss, .stack, .heap regions & setup .data values + // Safety: only safe if the values computed by the loader are correct. + unsafe { + let data_ptr = statics_in_rom.data_origin as *mut u32; + for i in 0..statics_in_rom.data_size_bytes as usize / size_of::() { + data_ptr.add(i).write_volatile(0); + } + for &(offset, data) in &statics_in_rom.poke_table[..statics_in_rom.valid_pokes as usize] { + let offset = u16::from_le_bytes(offset) as usize; + let data = u32::from_le_bytes(data); + data_ptr.add(offset / size_of::()).write_volatile(data); + } + } + irq_setup(); // all sensors & IRQs setup already by boot0, but it doesn't hurt to re-write these registers // in case they were defeated somehow previously @@ -208,17 +238,17 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa iox.set_gpio_pin(se0_port, se0_pin, IoxValue::Low); // put the USB port into SE0 while we initialize things // setup display - turn on its power, reset the framebuffer - bao1x_hal::board::setup_display_pins(&iox); - // power on - let (oled_on_port, oled_on_pin) = bao1x_hal::board::setup_oled_power_pin(&iox); - iox.set_gpio_pin_value(oled_on_port, oled_on_pin, IoxValue::High); - // reset enable - note inversion compared to baosec (at least as of this board rev of baosec) bao1x_hal::board::setup_periph_reset_pin(&iox); + bao1x_hal::board::assert_periph_reset(&iox, true); - // delay for reset assert - delay(1); + // delay while reset assert - setup display pins at this time + bao1x_hal::board::setup_display_pins(&iox); + let (oled_on_port, oled_on_pin) = bao1x_hal::board::setup_oled_power_pin(&iox); bao1x_hal::board::assert_periph_reset(&iox, false); + + // power on + iox.set_gpio_pin_value(oled_on_port, oled_on_pin, IoxValue::High); } #[cfg(not(feature = "oem"))] BoardTypeCoding::Oem => { @@ -353,49 +383,22 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa iox.set_gpio_pin(se0_port, se0_pin, IoxValue::Low); // put the USB port into SE0 while we initialize things // setup display - turn on its power, reset the framebuffer - bao1x_hal::board::setup_display_pins(&iox); - // power on - let (oled_on_port, oled_on_pin) = bao1x_hal::board::setup_oled_power_pin(&iox); - iox.set_gpio_pin_value(oled_on_port, oled_on_pin, IoxValue::High); // reset enable let (peri_rst_port, peri_reset_pin) = bao1x_hal::board::setup_periph_reset_pin(&iox); iox.set_gpio_pin_value(peri_rst_port, peri_reset_pin, IoxValue::Low); - // delay for reset assert - delay(1); + // delay for reset assert - setup display pins during this time + bao1x_hal::board::setup_display_pins(&iox); + let (oled_on_port, oled_on_pin) = bao1x_hal::board::setup_oled_power_pin(&iox); iox.set_gpio_pin_value(peri_rst_port, peri_reset_pin, IoxValue::High); + // power on + iox.set_gpio_pin_value(oled_on_port, oled_on_pin, IoxValue::High); + // keyboard can setup at keyboard read time } } } - // ASSUME: basic clocks are sane because boot0 set those up. - // ASSUME: SRAM trim wait states are set up correctly (sram0 has 1 wait state) - - // Now that SRAM trims are setup, initialize all the statics by writing to memory. - // For baremetal, the statics structure is just at the flash base. - const STATICS_LOC: usize = bao1x_api::BOOT1_START + SIGBLOCK_LEN; - - // safety: this data structure is pre-loaded by the image loader and is guaranteed to - // only have representable, valid values that are aligned according to the repr(C) spec - let statics_in_rom: &bao1x_api::StaticsInRom = - unsafe { (STATICS_LOC as *const bao1x_api::StaticsInRom).as_ref().unwrap() }; - assert!(statics_in_rom.version == bao1x_api::STATICS_IN_ROM_VERSION, "Can't find valid statics table"); - - // Clear .data, .bss, .stack, .heap regions & setup .data values - // Safety: only safe if the values computed by the loader are correct. - unsafe { - let data_ptr = statics_in_rom.data_origin as *mut u32; - for i in 0..statics_in_rom.data_size_bytes as usize / size_of::() { - data_ptr.add(i).write_volatile(0); - } - for &(offset, data) in &statics_in_rom.poke_table[..statics_in_rom.valid_pokes as usize] { - let offset = u16::from_le_bytes(offset) as usize; - let data = u32::from_le_bytes(data); - data_ptr.add(offset / size_of::()).write_volatile(data); - } - } - // set the clock let fclk_freq = match board_type { BoardTypeCoding::Baosec => bao1x_api::offsets::baosec::DEFAULT_FCLK_FREQUENCY, From d6a5c636bb9b9ceccd19747510c701c4385e670b Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 17:33:22 +0800 Subject: [PATCH 04/28] "best" config with current lens --- libs/bao1x-hal/src/gc2145/gc2145.rs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/libs/bao1x-hal/src/gc2145/gc2145.rs b/libs/bao1x-hal/src/gc2145/gc2145.rs index e2065b840..1a3bdce2a 100644 --- a/libs/bao1x-hal/src/gc2145/gc2145.rs +++ b/libs/bao1x-hal/src/gc2145/gc2145.rs @@ -150,8 +150,8 @@ impl Gc2145 { // let c_ratio = 4u16; // let r_ratio = 4u16; // 320x240 base scaling - let c_ratio = 3u16; - let r_ratio = 3u16; + let c_ratio = 2u16; + let r_ratio = 2u16; // 640x480 base scaling // let c_ratio = 2u16; // let r_ratio = 2u16; @@ -165,6 +165,16 @@ impl Gc2145 { let win_y = (UXGA_VSIZE - win_h) / 2; /* Set readout window first. */ + /* + self.gc2145_set_window( + i2c, + GC2145_REG_BLANK_WINDOW_BASE, + win_x / 2, + win_y / 2, + (win_w + 16) * 2, + (win_h + 8) * 2, + ); + */ self.gc2145_set_window(i2c, GC2145_REG_BLANK_WINDOW_BASE, win_x, win_y, win_w + 16, win_h + 8); /* Set cropping window next. */ @@ -177,15 +187,13 @@ impl Gc2145 { /* Set Sub-sampling ratio and mode */ self.poke(i2c, GC2145_REG_SUBSAMPLE, ((r_ratio << 4) | c_ratio) as u8); - self.poke(i2c, GC2145_REG_SUBSAMPLE_MODE, GC2145_SUBSAMPLE_MODE_SMOOTH); + self.poke(i2c, GC2145_REG_SUBSAMPLE_MODE, 0x32); self.delay(30); - // divide the clock down, so that the system can keep up. - // self.poke(i2c, 0xFA, 0x32); // this offers a higher frame rate, but a greater bus congestion - - // maybe available on bao1x - // self.poke(i2c, 0xFA, 0x63); // this is necessary for MPW due to SPI backpressure bug - self.poke(i2c, 0xFA, 0x52); // this is necessary for MPW due to SPI backpressure bug + self.poke(i2c, 0xFA, 0x19); + + // now at 35Hz frame rate } #[inline(never)] From e8219cda583e93d3735e5c9b778fcb15cd697bc6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 21:38:19 +0800 Subject: [PATCH 05/28] adjust boot delays to make screen-up a bit faster --- bao1x-boot/boot1/src/main.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bao1x-boot/boot1/src/main.rs b/bao1x-boot/boot1/src/main.rs index 5f6dbb38f..563f9fa9a 100644 --- a/bao1x-boot/boot1/src/main.rs +++ b/bao1x-boot/boot1/src/main.rs @@ -203,23 +203,23 @@ pub unsafe extern "C" fn rust_entry() -> ! { let se0_dabao = crate::platform::setup_dabao_se0_pin(&iox); iox.set_gpio_pin(se0_baosec.0, se0_baosec.1, bao1x_api::IoxValue::Low); iox.set_gpio_pin(se0_dabao.0, se0_dabao.1, bao1x_api::IoxValue::Low); - delay(100); // use the USB disconnect time to initialize the display - at least 100ms is // needed after reset for the display to initialize if let Some(ref mut sh1107) = oled { // show the boot logo sh1107.init(); - sh1107.buffer_mut().fill(0xFFFF_FFFF); + delay(100); sh1107.blit_screen(&ux_api::bitmaps::baochip128x128::BITMAP); sh1107.draw(); + delay(150); + } else { + delay(250); } - delay(400); + delay(250); // setup the USB port let (mut last_usb_state, mut portsc) = glue::setup(); - - // remainder of the 1-second total wait target time for USB disconnect - delay(500); + delay(150); // release SE0 iox.set_gpio_pin(se0_baosec.0, se0_baosec.1, bao1x_api::IoxValue::High); From 1cb23dd4a26be294e13300902fce0c0ce8aef49d Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 21:51:50 +0800 Subject: [PATCH 06/28] change power-on order of display and add unchecked variant of put pixel - remove bounds checking for accelerating blits that are already checked - fix the command ordering for display power-on to remove "noise" during power-on of the display. --- libs/bao1x-hal/src/sh1107.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/libs/bao1x-hal/src/sh1107.rs b/libs/bao1x-hal/src/sh1107.rs index 7a5bd628f..ddfb0d4ef 100644 --- a/libs/bao1x-hal/src/sh1107.rs +++ b/libs/bao1x-hal/src/sh1107.rs @@ -465,7 +465,7 @@ impl<'a> Oled128x128<'a> { SetDCDCSettings(0x0), SetStartLine(0), SetDisplayOffset(0), - SetContrastControl(0x2f), // was 0x4f, was a bit too bright + SetContrastControl(0x3f), // was 0x4f, was a bit too bright SetAddressMode(AddressMode::Column), SetSegmentReMap(false), SetCOMScanDirection(Direction::Inverted), @@ -476,13 +476,21 @@ impl<'a> Oled128x128<'a> { SetPageAddress(0), ForceEntireDisplay(false), SetDisplayMode(DisplayMode::WhiteOnBlack), - DisplayOnOff(DisplayState::On), ]; for command in init_sequence { let bytes = command.encode(); self.send_command(bytes); } + // clear the frame buffer + self.buffer_mut().fill(0xFFFF_FFFF); + self.draw(); + + let display_on = [DisplayOnOff(DisplayState::On)]; + for command in display_on { + let bytes = command.encode(); + self.send_command(bytes); + } } pub fn powerdown(&mut self) { @@ -556,6 +564,18 @@ impl<'a> FrameBuffer for Oled128x128<'a> { } } + #[inline(always)] + unsafe fn put_pixel_unchecked(&mut self, p: Point, on: ColorNative) { + let bitnum = (p.x + p.y * COLUMN) as usize; + let word_idx = bitnum >> 5; // bitnum / 32 + let bit_idx = bitnum & 0x1F; // bitnum % 32 + if on.0 != 0 { + self.buffer[word_idx] |= 1 << bit_idx; + } else { + self.buffer[word_idx] &= !(1 << bit_idx); + } + } + fn dimensions(&self) -> Point { Point::new(COLUMN, ROW) } fn get_pixel(&self, p: Point) -> Option { From ac20b43aaadf3e4dddbd1232788e9032f5d8026d Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:02:24 +0800 Subject: [PATCH 07/28] update gc2145 comments --- libs/bao1x-hal/src/gc2145/gc2145.rs | 28 +++++----------------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/libs/bao1x-hal/src/gc2145/gc2145.rs b/libs/bao1x-hal/src/gc2145/gc2145.rs index 1a3bdce2a..8440e4143 100644 --- a/libs/bao1x-hal/src/gc2145/gc2145.rs +++ b/libs/bao1x-hal/src/gc2145/gc2145.rs @@ -143,18 +143,10 @@ impl Gc2145 { } fn set_resolution(&self, i2c: &mut dyn I2cApi, w: u16, h: u16) { - // TODO: figure out what this parameter even means in the context of an...unconstrained variable - // resolution? Maybe? It's not even clear to me that was the original intent from the C driver. - - // 160x120 base scaling - // let c_ratio = 4u16; - // let r_ratio = 4u16; - // 320x240 base scaling + // these define the scaling of the image. If "digital zoom" is required, increase + // these numbers to get a higher magnification. let c_ratio = 2u16; let r_ratio = 2u16; - // 640x480 base scaling - // let c_ratio = 2u16; - // let r_ratio = 2u16; /* Calculates the window boundaries to obtain the desired resolution */ let win_w = w * c_ratio; @@ -165,16 +157,6 @@ impl Gc2145 { let win_y = (UXGA_VSIZE - win_h) / 2; /* Set readout window first. */ - /* - self.gc2145_set_window( - i2c, - GC2145_REG_BLANK_WINDOW_BASE, - win_x / 2, - win_y / 2, - (win_w + 16) * 2, - (win_h + 8) * 2, - ); - */ self.gc2145_set_window(i2c, GC2145_REG_BLANK_WINDOW_BASE, win_x, win_y, win_w + 16, win_h + 8); /* Set cropping window next. */ @@ -182,18 +164,18 @@ impl Gc2145 { /* Enable crop */ self.poke(i2c, GC2145_REG_CROP_ENABLE, GC2145_CROP_SET_ENABLE); - // self.poke(i2c, GC2145_REG_CROP_ENABLE, 0); /* Set Sub-sampling ratio and mode */ self.poke(i2c, GC2145_REG_SUBSAMPLE, ((r_ratio << 4) | c_ratio) as u8); + // set to nearest-neighbor averaging plus "use" mode self.poke(i2c, GC2145_REG_SUBSAMPLE_MODE, 0x32); self.delay(30); - self.poke(i2c, 0xFA, 0x19); - + // faster clock enables a faster frame rate // now at 35Hz frame rate + self.poke(i2c, 0xFA, 0x19); } #[inline(never)] From f7c00eb985d94ce60578dd5234bfbd9bb067f47a Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:04:51 +0800 Subject: [PATCH 08/28] fix some rendering artifacts and add todo's on the QR code rendering --- libs/ux-api/src/minigfx/handlers.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libs/ux-api/src/minigfx/handlers.rs b/libs/ux-api/src/minigfx/handlers.rs index c8c3d6845..99836533b 100644 --- a/libs/ux-api/src/minigfx/handlers.rs +++ b/libs/ux-api/src/minigfx/handlers.rs @@ -441,9 +441,11 @@ pub fn render_qr( op::rectangle(display, r, screen_clip.into(), false); // now raster in the modules + // TODO: on dense codes, the dark colors are over-sized by a pixel. Figure this out. + // TODO: on smaller than optimal codes, align the QR code into the center of the screen. let mut line_top_left = Point::new(left_edge + module_width * QUIET_MODULES, tl.y + module_width * QUIET_MODULES); - let dark = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1); + let dark = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 0); for line in qr_render.modules.chunks(qr_render.width) { for (i, &module) in line.iter().enumerate() { if module { From 5a3319ae578921b920c4aa887cc912449eb741b9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:06:18 +0800 Subject: [PATCH 09/28] optimize camera frame rate it's now around 30Hz. --- services/bao-video/src/main.rs | 88 ++++++++++++++++++++++++++-------- 1 file changed, 68 insertions(+), 20 deletions(-) diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 0514aa336..7d5c252cd 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -85,6 +85,7 @@ fn encode_base64(input: &[u8]) -> String { general_purpose::STANDARD.encode(inpu /// This converts a frame of `[u8]` grayscale pixels that may be larger than the native /// frame buffer resolution into a black and white bitmap. +#[cfg(not(feature = "oem-baosec-lite"))] pub fn blit_to_display(display: &mut Oled128x128, frame: &[u8], display_cleared: bool, bw_thresh: &mut u8) { let mut sum: u32 = 0; let mut count: u32 = 0; @@ -122,6 +123,52 @@ pub fn blit_to_display(display: &mut Oled128x128, frame: &[u8], display_cleared: *bw_thresh = (sum / count) as u8; } +#[cfg(feature = "oem-baosec-lite")] +pub fn blit_to_display(display: &mut Oled128x128, frame: &[u8], display_cleared: bool, bw_thresh: &mut u8) { + let mut sum: u32 = 0; + let mut count: u32 = 0; + let frame_height = frame.len() / IMAGE_WIDTH; + let thresh = *bw_thresh; // Dereference once + + let max_display_x = display.dimensions().x as isize; + let max_display_y = display.dimensions().y as isize - (gfx::CHAR_HEIGHT as isize + 1); + + for y in (0..frame_height).step_by(2) { + // Skip every other line directly + let row = &frame[y * IMAGE_WIDTH..(y + 1) * IMAGE_WIDTH]; + let display_y = (frame_height - y - 1) as isize / 2; + + if display_y < 0 || display_y >= max_display_y { + continue; + } + + for x in (0..IMAGE_WIDTH).step_by(2) { + // Skip every other pixel directly + let display_x = x as isize / 2; + + if display_x >= max_display_x { + break; + } + + let luminance = row[x] & 0xff; + sum += luminance as u32; + count += 1; + + if luminance > thresh { + unsafe { + display.put_pixel_unchecked(Point::new(display_x, display_y), Mono::White.into()); + } + } else if !display_cleared { + unsafe { + display.put_pixel_unchecked(Point::new(display_x, display_y), Mono::Black.into()); + } + } + // else: display already cleared, skip writing black pixels + } + } + *bw_thresh = (sum / count) as u8; +} + #[repr(align(32))] #[cfg(not(feature = "hosted-baosec"))] struct CamIrq { @@ -230,6 +277,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { tt.sleep_ms(1000).ok(); // setup camera power + #[cfg(not(feature = "oem-baosec-lite"))] match bao1x_hal::axp2101::Axp2101::new(&mut i2c) { Ok(mut pmic) => { pmic.set_dcdc(&mut i2c, Some((1.8, false)), bao1x_hal::axp2101::WhichDcDc::Dcdc5).unwrap(); @@ -493,6 +541,26 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { } } GfxOpcode::CamIrq => { + // copy the camera data to our FB + let fb: &[u32] = cam.rx_buf(); + // fb is an array of IMAGE_WIDTH x IMAGE_HEIGHT x u16 + // frame is an array of IMAGE_WIDTH x IMAGE_HEIGHT x u8 + // Take only the "Y" channel out of the fb array and write it to frame, but do it + // such that we are fetching a u32 each read from fb as this matches the native + // width of the bus (because fb is non-cacheable reading u16 ends up fetching the + // same word twice, then masking it at the CPU side in hardware). Also, the fb + // is slow to access relative to main memory. + // + // Also, commit the data to `frame` in inverse line order, e.g. flip the image + // vertically. + for (y_src, line) in fb.chunks(IMAGE_WIDTH / 2).enumerate() { + for (x_src, &u32src) in line.iter().enumerate() { + frame[y_src * IMAGE_WIDTH + 2 * x_src] = ((u32src >> 8) & 0xff) as u8; + frame[y_src * IMAGE_WIDTH + 2 * x_src + 1] = ((u32src >> 24) & 0xff) as u8; + } + } + frames += 1; + if qr_request.is_some() { cam.capture_async(); } else { @@ -518,26 +586,6 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { } } - // copy the camera data to our FB - let fb: &[u32] = cam.rx_buf(); - // fb is an array of IMAGE_WIDTH x IMAGE_HEIGHT x u16 - // frame is an array of IMAGE_WIDTH x IMAGE_HEIGHT x u8 - // Take only the "Y" channel out of the fb array and write it to frame, but do it - // such that we are fetching a u32 each read from fb as this matches the native - // width of the bus (because fb is non-cacheable reading u16 ends up fetching the - // same word twice, then masking it at the CPU side in hardware). Also, the fb - // is slow to access relative to main memory. - // - // Also, commit the data to `frame` in inverse line order, e.g. flip the image - // vertically. - for (y_src, line) in fb.chunks(IMAGE_WIDTH / 2).enumerate() { - for (x_src, &u32src) in line.iter().enumerate() { - frame[y_src * IMAGE_WIDTH + 2 * x_src] = ((u32src >> 8) & 0xff) as u8; - frame[y_src * IMAGE_WIDTH + 2 * x_src + 1] = ((u32src >> 24) & 0xff) as u8; - } - } - frames += 1; - let mut candidates = Vec::::new(); log::debug!("------------- SEARCH {} -----------", frames); let _finder_width = From 385c3568016d9f10c8a5b4259ed9cfd6bee1dd1a Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:07:07 +0800 Subject: [PATCH 10/28] refactor clock computations & add routine to determine fd this is a prelude to clock tuning the internal bus networks for bandwidth. The "trivial" thing of just cranking the speed up to the edge and letting the dividers didn't seem to help performance much, though; this could be due to the clock synchronizers beating against each other. --- libs/bao1x-hal/src/clocks.rs | 53 +++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/libs/bao1x-hal/src/clocks.rs b/libs/bao1x-hal/src/clocks.rs index 1020f99f9..6c08a1d20 100644 --- a/libs/bao1x-hal/src/clocks.rs +++ b/libs/bao1x-hal/src/clocks.rs @@ -17,6 +17,10 @@ const MHZ: u32 = 1_000_000; /// perclk is returned by the clock setting routines. pub const PERCLK_HZ: u32 = 100_000_000; +pub const HCLK_HZ: u32 = 200_000_000; +pub const ICLK_HZ: u32 = 100_000_000; +pub const PCLK_HZ: u32 = 50_000_000; + #[bitfield(u32)] #[derive(PartialEq, Eq, Debug)] pub struct PmuControl { @@ -243,6 +247,29 @@ fn check_pll_std(cgu: &mut CSR) { } } +/// maximum value representable in the fd counter +const FD_MAX: u32 = 256; + +pub fn fd_from_frequency(desired_freq_hz: u32, in_freq_hz: u32) -> u32 { + // Shift by 1_000 to prevent overflow + let desired_freq_khz = desired_freq_hz / 1_000; + let in_freq_khz = in_freq_hz / 1_000; + + // Calculate (fd + 1) with rounding for accuracy + let fd_plus_1 = (desired_freq_khz * FD_MAX + in_freq_khz / 2) / in_freq_khz; + + // Subtract 1 to get fd, handling underflow and clamping to valid range + if fd_plus_1 == 0 { 0 } else { (fd_plus_1 - 1).min(FD_MAX - 1) } +} + +pub fn divide_by_fd(fd: u32, in_freq_hz: u32) -> u32 { + // shift by 1_000 to prevent overflow + let in_freq_khz = in_freq_hz / 1_000; + let out_freq_khz = (in_freq_khz * (fd + 1)) / FD_MAX; + // restore to Hz + out_freq_khz * 1_000 +} + #[cfg(feature = "std")] pub struct ClockManager { pub vco_freq: u32, @@ -266,10 +293,6 @@ pub struct ClockManager { pmic: Axp2101, } -/// maximum value representable in the fd counter -#[cfg(feature = "std")] -const FD_MAX: u32 = 256; - #[cfg(feature = "std")] impl ClockManager { pub fn new() -> Result { @@ -310,16 +333,16 @@ impl ClockManager { let iclk_fd = sysctrl.r(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_3) & 0xFF; let pclk_fd = sysctrl.r(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_4) & 0xFF; - let fclk = ClockManager::divide_by_fd(fclk_fd, pll0_freq); - let aclk = ClockManager::divide_by_fd(aclk_fd, pll0_freq); - let hclk = ClockManager::divide_by_fd(hclk_fd, pll0_freq); - let iclk = ClockManager::divide_by_fd(iclk_fd, pll0_freq); - let pclk = ClockManager::divide_by_fd(pclk_fd, pll0_freq); + let fclk = divide_by_fd(fclk_fd, pll0_freq); + let aclk = divide_by_fd(aclk_fd, pll0_freq); + let hclk = divide_by_fd(hclk_fd, pll0_freq); + let iclk = divide_by_fd(iclk_fd, pll0_freq); + let pclk = divide_by_fd(pclk_fd, pll0_freq); log::info!("fracen: {:?}", fracen); // perclk has an extra /2 applied to it log::info!("perclk: {:x}, pll0_freq {}", sysctrl.r(utra::sysctrl::SFR_CGUFDPER), pll0_freq); let perclk_fd = sysctrl.r(utra::sysctrl::SFR_CGUFDPER) & 0xFF; - let perclk = ClockManager::divide_by_fd(perclk_fd, pll0_freq) / 2; + let perclk = divide_by_fd(perclk_fd, pll0_freq) / 2; /* log::info!("m: {} n: {} q1: {} q0: {} frac: {}, fracen: {:?}", m, n, q1, q0, frac, fracen); @@ -364,14 +387,6 @@ impl ClockManager { /// using the susres block. pub unsafe fn susres_base(&self) -> usize { self.susres.base() as usize } - pub fn divide_by_fd(fd: u32, in_freq_hz: u32) -> u32 { - // shift by 1_000 to prevent overflow - let in_freq_khz = in_freq_hz / 1_000; - let out_freq_khz = (in_freq_khz * (fd + 1)) / FD_MAX; - // restore to Hz - out_freq_khz * 1_000 - } - pub fn measured_freqs(&self) -> Vec<(String, u32)> { let mut readings = Vec::new(); let clk_desc: [(&'static str, u32, usize); 8] = [ @@ -410,7 +425,7 @@ impl ClockManager { |ms: usize, freq_hz: u32| { let freq_khz = (freq_hz / 1_000).max(1); let aclk_fd = self.sysctrl.r(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_1) & 0xFF; - let aclk_khz = ClockManager::divide_by_fd(aclk_fd, freq_hz) / 1_000; + let aclk_khz = divide_by_fd(aclk_fd, freq_hz) / 1_000; fn get_hw_time(hw: &CSR) -> u64 { hw.r(utra::susres::TIME0) as u64 | ((hw.r(utra::susres::TIME1) as u64) << 32) From b34f4a4c6f5e82c7aed783cc6ded0112e30b5c61 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:08:28 +0800 Subject: [PATCH 11/28] remove failure case in Drop implementation this is some technical debt - Drop doesn't coordinate across all instances of an object and so the disconnect isn't able to know exactly when to disconnect. This will require some guru meditation later on to correct this in a "proper" fashion. --- libs/bao1x-api/src/iox.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/bao1x-api/src/iox.rs b/libs/bao1x-api/src/iox.rs index 45f6dbb97..bce11974e 100644 --- a/libs/bao1x-api/src/iox.rs +++ b/libs/bao1x-api/src/iox.rs @@ -336,7 +336,7 @@ impl Drop for IoxHal { // connection. if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe { - xous::disconnect(self.conn).unwrap(); + xous::disconnect(self.conn).ok(); } } } From 1db717a63f2a3a7a07c39ad7ffb9d0717521ec8c Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:09:37 +0800 Subject: [PATCH 12/28] add put_pixel_unchecked() trait in API this is for implementing checked, higher-performance loops like blits. --- libs/ux-api/src/minigfx/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libs/ux-api/src/minigfx/mod.rs b/libs/ux-api/src/minigfx/mod.rs index 008c6c310..e742b58f0 100644 --- a/libs/ux-api/src/minigfx/mod.rs +++ b/libs/ux-api/src/minigfx/mod.rs @@ -38,6 +38,8 @@ use crate::platform; pub trait FrameBuffer { /// Puts a pixel of ColorNative at x, y. (0, 0) is defined as the lower left corner. fn put_pixel(&mut self, p: Point, color: ColorNative); + /// For higher-performance loops that have guaranteed bounds checking in the point location. + unsafe fn put_pixel_unchecked(&mut self, p: Point, on: ColorNative); /// Retrieves a pixel value from the frame buffer; returns None if the point is out of bounds. fn get_pixel(&self, p: Point) -> Option; /// XORs a pixel to what is in the existing frame buffer. The exact definition of "XOR" is somewhat From f288a180409a878d6791af9d138b6f5e4cddba75 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:10:14 +0800 Subject: [PATCH 13/28] add a first whack at an lis2dh12 accelerometer driver This is a ball of Claude-generated code which was guided by the datasheets, some trait APIs and other prompt info. The prompt used to generate the code is appended to this file. The result is structurally pretty similar to the accelerometer driver templates I've seen provided by the vendor, except in Rust and with Xous idioms, so I think this is a pretty reasonable whack at reducing boilerplate. There's way more features in these accelerometers than I have time to write getters/setters for. The few functions I have used look good insofar as getter/setters, but there are some oddly specific defaults in the file that should probably be corrected, probably due to over-prompting of the code generator. I'll work through these over time. --- libs/bao1x-hal/src/lis2dh12.rs | 1781 ++++++++++++++++++++++++++++++++ 1 file changed, 1781 insertions(+) create mode 100644 libs/bao1x-hal/src/lis2dh12.rs diff --git a/libs/bao1x-hal/src/lis2dh12.rs b/libs/bao1x-hal/src/lis2dh12.rs new file mode 100644 index 000000000..e7eeb830b --- /dev/null +++ b/libs/bao1x-hal/src/lis2dh12.rs @@ -0,0 +1,1781 @@ +//! LIS2DH12 3-axis accelerometer driver for Xous +//! +//! This driver provides an interface to the ST LIS2DH12TR ultra-low-power +//! high-performance 3-axis accelerometer over I2C. +//! +//! # Features +//! - Orientation detection (face up/down) +//! - Motion/tap interrupt configuration +//! - Configurable full-scale range (±2g to ±16g) +//! - Multiple operating modes (low-power, normal, high-resolution) + +use std::thread; +use std::time::Duration; + +use bao1x_api::{I2cApi, I2cResult}; + +/// I2C device address with SA0 tied high (0b0011001) +pub const LIS2DH12_ADDR: u8 = 0x19; + +/// Expected WHO_AM_I register value +pub const WHO_AM_I_VALUE: u8 = 0x33; + +// ============================================================================= +// I2C Result Extension Trait +// ============================================================================= + +/// Extension trait for clean I2C result handling with the `?` operator +pub trait I2cResultExt { + /// Convert I2C result to a simple Result, discarding the byte count on success + fn check(self) -> Result<(), xous::Error>; +} + +impl I2cResultExt for Result { + fn check(self) -> Result<(), xous::Error> { + match self? { + I2cResult::Ack(_) => Ok(()), + I2cResult::Nack | I2cResult::Pending => Err(xous::Error::Timeout), + I2cResult::InternalError => Err(xous::Error::InternalError), + } + } +} + +// ============================================================================= +// Register Addresses +// ============================================================================= + +/// Register addresses for LIS2DH12 +#[allow(dead_code)] +pub mod regs { + pub const STATUS_REG_AUX: u8 = 0x07; + pub const OUT_TEMP_L: u8 = 0x0C; + pub const OUT_TEMP_H: u8 = 0x0D; + pub const WHO_AM_I: u8 = 0x0F; + pub const CTRL_REG0: u8 = 0x1E; + pub const TEMP_CFG_REG: u8 = 0x1F; + pub const CTRL_REG1: u8 = 0x20; + pub const CTRL_REG2: u8 = 0x21; + pub const CTRL_REG3: u8 = 0x22; + pub const CTRL_REG4: u8 = 0x23; + pub const CTRL_REG5: u8 = 0x24; + pub const CTRL_REG6: u8 = 0x25; + pub const REFERENCE: u8 = 0x26; + pub const STATUS_REG: u8 = 0x27; + pub const OUT_X_L: u8 = 0x28; + pub const OUT_X_H: u8 = 0x29; + pub const OUT_Y_L: u8 = 0x2A; + pub const OUT_Y_H: u8 = 0x2B; + pub const OUT_Z_L: u8 = 0x2C; + pub const OUT_Z_H: u8 = 0x2D; + pub const FIFO_CTRL_REG: u8 = 0x2E; + pub const FIFO_SRC_REG: u8 = 0x2F; + pub const INT1_CFG: u8 = 0x30; + pub const INT1_SRC: u8 = 0x31; + pub const INT1_THS: u8 = 0x32; + pub const INT1_DURATION: u8 = 0x33; + pub const INT2_CFG: u8 = 0x34; + pub const INT2_SRC: u8 = 0x35; + pub const INT2_THS: u8 = 0x36; + pub const INT2_DURATION: u8 = 0x37; + pub const CLICK_CFG: u8 = 0x38; + pub const CLICK_SRC: u8 = 0x39; + pub const CLICK_THS: u8 = 0x3A; + pub const TIME_LIMIT: u8 = 0x3B; + pub const TIME_LATENCY: u8 = 0x3C; + pub const TIME_WINDOW: u8 = 0x3D; + pub const ACT_THS: u8 = 0x3E; + pub const ACT_DUR: u8 = 0x3F; + + /// Flag to set MSB for auto-increment in multi-byte reads + pub const AUTO_INCREMENT: u8 = 0x80; +} + +// ============================================================================= +// Configuration Enums +// ============================================================================= + +/// Output data rate selection +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum DataRate { + /// Power-down mode + #[default] + PowerDown = 0b0000, + /// 1 Hz + Hz1 = 0b0001, + /// 10 Hz + Hz10 = 0b0010, + /// 25 Hz + Hz25 = 0b0011, + /// 50 Hz + Hz50 = 0b0100, + /// 100 Hz + Hz100 = 0b0101, + /// 200 Hz + Hz200 = 0b0110, + /// 400 Hz + Hz400 = 0b0111, + /// 1.620 kHz (low-power mode only) + Hz1620LowPower = 0b1000, + /// 1.344 kHz (HR/Normal) or 5.376 kHz (low-power) + Hz1344OrHz5376 = 0b1001, +} + +impl From for u8 { + fn from(dr: DataRate) -> u8 { dr as u8 } +} + +impl TryFrom for DataRate { + type Error = xous::Error; + + fn try_from(value: u8) -> Result { + match value & 0x0F { + 0b0000 => Ok(DataRate::PowerDown), + 0b0001 => Ok(DataRate::Hz1), + 0b0010 => Ok(DataRate::Hz10), + 0b0011 => Ok(DataRate::Hz25), + 0b0100 => Ok(DataRate::Hz50), + 0b0101 => Ok(DataRate::Hz100), + 0b0110 => Ok(DataRate::Hz200), + 0b0111 => Ok(DataRate::Hz400), + 0b1000 => Ok(DataRate::Hz1620LowPower), + 0b1001 => Ok(DataRate::Hz1344OrHz5376), + _ => Err(xous::Error::InvalidCoding), + } + } +} + +/// Full-scale selection +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum FullScale { + /// ±2g + #[default] + G2 = 0b00, + /// ±4g + G4 = 0b01, + /// ±8g + G8 = 0b10, + /// ±16g + G16 = 0b11, +} + +impl From for u8 { + fn from(fs: FullScale) -> u8 { fs as u8 } +} + +impl TryFrom for FullScale { + type Error = xous::Error; + + fn try_from(value: u8) -> Result { + match value & 0x03 { + 0b00 => Ok(FullScale::G2), + 0b01 => Ok(FullScale::G4), + 0b10 => Ok(FullScale::G8), + 0b11 => Ok(FullScale::G16), + _ => Err(xous::Error::InvalidCoding), + } + } +} + +impl FullScale { + /// Get the sensitivity in mg per digit for the given operating mode + pub fn sensitivity_mg(&self, mode: OperatingMode) -> u16 { + match (self, mode) { + (FullScale::G2, OperatingMode::HighResolution) => 1, + (FullScale::G2, OperatingMode::Normal) => 4, + (FullScale::G2, OperatingMode::LowPower) => 16, + (FullScale::G4, OperatingMode::HighResolution) => 2, + (FullScale::G4, OperatingMode::Normal) => 8, + (FullScale::G4, OperatingMode::LowPower) => 32, + (FullScale::G8, OperatingMode::HighResolution) => 4, + (FullScale::G8, OperatingMode::Normal) => 16, + (FullScale::G8, OperatingMode::LowPower) => 64, + (FullScale::G16, OperatingMode::HighResolution) => 12, + (FullScale::G16, OperatingMode::Normal) => 48, + (FullScale::G16, OperatingMode::LowPower) => 192, + } + } + + /// Get the threshold LSB value in mg for interrupt thresholds + pub fn threshold_mg_per_lsb(&self) -> u16 { + match self { + FullScale::G2 => 16, + FullScale::G4 => 32, + FullScale::G8 => 62, + FullScale::G16 => 186, + } + } +} + +/// Operating mode selection +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OperatingMode { + /// Low-power mode (8-bit data output) + LowPower, + /// Normal mode (10-bit data output) + #[default] + Normal, + /// High-resolution mode (12-bit data output) + HighResolution, +} + +impl OperatingMode { + /// Returns (LPen bit, HR bit) values for CTRL_REG1 and CTRL_REG4 + pub fn to_bits(self) -> (bool, bool) { + match self { + OperatingMode::LowPower => (true, false), + OperatingMode::Normal => (false, false), + OperatingMode::HighResolution => (false, true), + } + } + + /// Create from LPen and HR bit values + pub fn from_bits(lpen: bool, hr: bool) -> Option { + match (lpen, hr) { + (true, false) => Some(OperatingMode::LowPower), + (false, false) => Some(OperatingMode::Normal), + (false, true) => Some(OperatingMode::HighResolution), + (true, true) => None, // Invalid combination + } + } + + /// Number of valid bits in the acceleration data + pub fn data_bits(self) -> u8 { + match self { + OperatingMode::LowPower => 8, + OperatingMode::Normal => 10, + OperatingMode::HighResolution => 12, + } + } +} + +/// High-pass filter mode +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum HighPassFilterMode { + /// Normal mode (reset by reading REFERENCE register) + #[default] + NormalWithReset = 0b00, + /// Reference signal for filtering + Reference = 0b01, + /// Normal mode + Normal = 0b10, + /// Autoreset on interrupt event + AutoresetOnInterrupt = 0b11, +} + +impl From for u8 { + fn from(mode: HighPassFilterMode) -> u8 { mode as u8 } +} + +impl TryFrom for HighPassFilterMode { + type Error = xous::Error; + + fn try_from(value: u8) -> Result { + match value & 0x03 { + 0b00 => Ok(HighPassFilterMode::NormalWithReset), + 0b01 => Ok(HighPassFilterMode::Reference), + 0b10 => Ok(HighPassFilterMode::Normal), + 0b11 => Ok(HighPassFilterMode::AutoresetOnInterrupt), + _ => Err(xous::Error::InvalidCoding), + } + } +} + +/// FIFO mode selection +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum FifoMode { + /// Bypass mode (FIFO disabled) + #[default] + Bypass = 0b00, + /// FIFO mode + Fifo = 0b01, + /// Stream mode + Stream = 0b10, + /// Stream-to-FIFO mode + StreamToFifo = 0b11, +} + +impl From for u8 { + fn from(mode: FifoMode) -> u8 { mode as u8 } +} + +impl TryFrom for FifoMode { + type Error = xous::Error; + + fn try_from(value: u8) -> Result { + match value & 0x03 { + 0b00 => Ok(FifoMode::Bypass), + 0b01 => Ok(FifoMode::Fifo), + 0b10 => Ok(FifoMode::Stream), + 0b11 => Ok(FifoMode::StreamToFifo), + _ => Err(xous::Error::InvalidCoding), + } + } +} + +/// Interrupt mode for INT1/INT2 configuration +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum InterruptMode { + /// OR combination of interrupt events + #[default] + OrCombination, + /// 6-direction movement recognition + Movement6D, + /// AND combination of interrupt events + AndCombination, + /// 6-direction position recognition + Position6D, +} + +impl InterruptMode { + /// Returns (AOI bit, 6D bit) values + pub fn to_bits(self) -> (bool, bool) { + match self { + InterruptMode::OrCombination => (false, false), + InterruptMode::Movement6D => (false, true), + InterruptMode::AndCombination => (true, false), + InterruptMode::Position6D => (true, true), + } + } + + /// Create from AOI and 6D bit values + pub fn from_bits(aoi: bool, d6: bool) -> Self { + match (aoi, d6) { + (false, false) => InterruptMode::OrCombination, + (false, true) => InterruptMode::Movement6D, + (true, false) => InterruptMode::AndCombination, + (true, true) => InterruptMode::Position6D, + } + } +} + +/// Interrupt polarity +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum InterruptPolarity { + /// Active high + #[default] + ActiveHigh, + /// Active low + ActiveLow, +} + +/// Self-test mode +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum SelfTestMode { + /// Normal mode (self-test disabled) + #[default] + Disabled = 0b00, + /// Self-test 0 + SelfTest0 = 0b01, + /// Self-test 1 + SelfTest1 = 0b10, +} + +impl From for u8 { + fn from(mode: SelfTestMode) -> u8 { mode as u8 } +} + +impl TryFrom for SelfTestMode { + type Error = xous::Error; + + fn try_from(value: u8) -> Result { + match value & 0x03 { + 0b00 => Ok(SelfTestMode::Disabled), + 0b01 => Ok(SelfTestMode::SelfTest0), + 0b10 => Ok(SelfTestMode::SelfTest1), + _ => Err(xous::Error::InvalidCoding), + } + } +} + +/// Debug dump of interrupt-related registers +#[derive(Debug, Clone, Copy)] +pub struct IntDebugDump { + pub ctrl_reg1: u8, + pub ctrl_reg2: u8, + pub ctrl_reg3: u8, + pub ctrl_reg4: u8, + pub ctrl_reg5: u8, + pub ctrl_reg6: u8, + pub int1_cfg: u8, + pub int1_ths: u8, + pub int1_duration: u8, + pub int1_src: u8, + pub status_reg: u8, +} + +impl IntDebugDump { + /// Print a human-readable interpretation of the register values + pub fn interpret(&self) { + log::info!("=== LIS2DH12 Interrupt Debug Dump ==="); + + // CTRL_REG1: ODR, LPen, axis enables + let odr = (self.ctrl_reg1 >> 4) & 0x0F; + let lpen = (self.ctrl_reg1 & 0x08) != 0; + let zen = (self.ctrl_reg1 & 0x04) != 0; + let yen = (self.ctrl_reg1 & 0x02) != 0; + let xen = (self.ctrl_reg1 & 0x01) != 0; + log::info!( + "CTRL_REG1 (0x{:02X}): ODR={}, LPen={}, Z={}, Y={}, X={}", + self.ctrl_reg1, + odr, + lpen, + zen, + yen, + xen + ); + + // CTRL_REG2: High-pass filter settings + let hpm = (self.ctrl_reg2 >> 6) & 0x03; + let hpcf = (self.ctrl_reg2 >> 4) & 0x03; + let fds = (self.ctrl_reg2 & 0x08) != 0; + let hp_ia1 = (self.ctrl_reg2 & 0x01) != 0; + log::info!( + "CTRL_REG2 (0x{:02X}): HPM={}, HPCF={}, FDS={}, HP_IA1={}", + self.ctrl_reg2, + hpm, + hpcf, + fds, + hp_ia1 + ); + + // CTRL_REG3: Interrupt enables on INT1 + let i1_click = (self.ctrl_reg3 & 0x80) != 0; + let i1_ia1 = (self.ctrl_reg3 & 0x40) != 0; + let i1_ia2 = (self.ctrl_reg3 & 0x20) != 0; + let i1_zyxda = (self.ctrl_reg3 & 0x10) != 0; + log::info!( + "CTRL_REG3 (0x{:02X}): I1_CLICK={}, I1_IA1={}, I1_IA2={}, I1_ZYXDA={}", + self.ctrl_reg3, + i1_click, + i1_ia1, + i1_ia2, + i1_zyxda + ); + if !i1_ia1 { + log::info!(" WARNING: I1_IA1 not set - INT1 generator not routed to INT1 pin!"); + } + + // CTRL_REG4: BDU, FS, HR + let bdu = (self.ctrl_reg4 & 0x80) != 0; + let fs = (self.ctrl_reg4 >> 4) & 0x03; + let hr = (self.ctrl_reg4 & 0x08) != 0; + log::info!("CTRL_REG4 (0x{:02X}): BDU={}, FS={}, HR={}", self.ctrl_reg4, bdu, fs, hr); + + // CTRL_REG5: Latch settings + let lir_int1 = (self.ctrl_reg5 & 0x08) != 0; + let d4d_int1 = (self.ctrl_reg5 & 0x04) != 0; + log::info!("CTRL_REG5 (0x{:02X}): LIR_INT1={}, D4D_INT1={}", self.ctrl_reg5, lir_int1, d4d_int1); + + // CTRL_REG6: INT polarity + let int_polarity = (self.ctrl_reg6 & 0x02) != 0; + log::info!( + "CTRL_REG6 (0x{:02X}): INT_POLARITY={} ({})", + self.ctrl_reg6, + int_polarity, + if int_polarity { "active-low" } else { "active-high" } + ); + + // INT1_CFG: Interrupt configuration + let aoi = (self.int1_cfg & 0x80) != 0; + let d6 = (self.int1_cfg & 0x40) != 0; + let zhie = (self.int1_cfg & 0x20) != 0; + let zlie = (self.int1_cfg & 0x10) != 0; + let yhie = (self.int1_cfg & 0x08) != 0; + let ylie = (self.int1_cfg & 0x04) != 0; + let xhie = (self.int1_cfg & 0x02) != 0; + let xlie = (self.int1_cfg & 0x01) != 0; + log::info!( + "INT1_CFG (0x{:02X}): AOI={}, 6D={}, ZH={}, ZL={}, YH={}, YL={}, XH={}, XL={}", + self.int1_cfg, + aoi, + d6, + zhie, + zlie, + yhie, + ylie, + xhie, + xlie + ); + if self.int1_cfg == 0 { + log::info!(" WARNING: INT1_CFG is 0 - no interrupt events enabled!"); + } + + // INT1_THS: Threshold + let ths = self.int1_ths & 0x7F; + log::info!("INT1_THS (0x{:02X}): threshold={} ({}mg at ±2g)", self.int1_ths, ths, ths as u16 * 16); + + // INT1_DURATION + let dur = self.int1_duration & 0x7F; + log::info!("INT1_DURATION (0x{:02X}): duration={} samples", dur, dur); + + // INT1_SRC: Current interrupt status (reading this clears latched interrupt!) + let ia = (self.int1_src & 0x40) != 0; + let zh = (self.int1_src & 0x20) != 0; + let zl = (self.int1_src & 0x10) != 0; + let yh = (self.int1_src & 0x08) != 0; + let yl = (self.int1_src & 0x04) != 0; + let xh = (self.int1_src & 0x02) != 0; + let xl = (self.int1_src & 0x01) != 0; + log::info!( + "INT1_SRC (0x{:02X}): IA={}, ZH={}, ZL={}, YH={}, YL={}, XH={}, XL={}", + self.int1_src, + ia, + zh, + zl, + yh, + yl, + xh, + xl + ); + + // STATUS_REG + let zyxda = (self.status_reg & 0x08) != 0; + log::info!("STATUS_REG (0x{:02X}): ZYXDA={}", self.status_reg, zyxda); + + log::info!("====================================="); + } +} + +// ============================================================================= +// Data Structures +// ============================================================================= + +/// Raw acceleration data from all three axes +#[derive(Debug, Clone, Copy, Default)] +pub struct AccelData { + /// X-axis raw value (left-justified two's complement) + pub x: i16, + /// Y-axis raw value (left-justified two's complement) + pub y: i16, + /// Z-axis raw value (left-justified two's complement) + pub z: i16, +} + +impl AccelData { + /// Convert raw data to milli-g values based on full scale and operating mode + pub fn to_mg(&self, full_scale: FullScale, mode: OperatingMode) -> (i32, i32, i32) { + let sensitivity = full_scale.sensitivity_mg(mode) as i32; + let shift = 16 - mode.data_bits(); + + // Data is left-justified, so we need to shift right to get the actual value + let x = ((self.x >> shift) as i32) * sensitivity; + let y = ((self.y >> shift) as i32) * sensitivity; + let z = ((self.z >> shift) as i32) * sensitivity; + + (x, y, z) + } +} + +/// Device orientation based on acceleration readings +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Orientation { + /// Face up (Z positive, towards sky) + FaceUp, + /// Face down (Z negative, towards ground) + FaceDown, + /// Unknown or transitional orientation + Unknown, +} + +/// Interrupt source flags +#[derive(Debug, Clone, Copy, Default)] +pub struct InterruptSource { + /// Interrupt active + pub active: bool, + /// X high event occurred + pub x_high: bool, + /// X low event occurred + pub x_low: bool, + /// Y high event occurred + pub y_high: bool, + /// Y low event occurred + pub y_low: bool, + /// Z high event occurred + pub z_high: bool, + /// Z low event occurred + pub z_low: bool, +} + +impl From for InterruptSource { + fn from(value: u8) -> Self { + InterruptSource { + active: (value & 0x40) != 0, + z_high: (value & 0x20) != 0, + z_low: (value & 0x10) != 0, + y_high: (value & 0x08) != 0, + y_low: (value & 0x04) != 0, + x_high: (value & 0x02) != 0, + x_low: (value & 0x01) != 0, + } + } +} + +/// Click source flags +#[derive(Debug, Clone, Copy, Default)] +pub struct ClickSource { + /// Interrupt active + pub active: bool, + /// Double-click detected + pub double_click: bool, + /// Single-click detected + pub single_click: bool, + /// Click sign (true = negative) + pub negative: bool, + /// Z-axis click detected + pub z: bool, + /// Y-axis click detected + pub y: bool, + /// X-axis click detected + pub x: bool, +} + +impl From for ClickSource { + fn from(value: u8) -> Self { + ClickSource { + active: (value & 0x40) != 0, + double_click: (value & 0x20) != 0, + single_click: (value & 0x10) != 0, + negative: (value & 0x08) != 0, + z: (value & 0x04) != 0, + y: (value & 0x02) != 0, + x: (value & 0x01) != 0, + } + } +} + +/// Status register flags +#[derive(Debug, Clone, Copy, Default)] +pub struct Status { + /// X, Y, Z data overrun + pub xyz_overrun: bool, + /// Z data overrun + pub z_overrun: bool, + /// Y data overrun + pub y_overrun: bool, + /// X data overrun + pub x_overrun: bool, + /// X, Y, Z new data available + pub xyz_data_available: bool, + /// Z new data available + pub z_data_available: bool, + /// Y new data available + pub y_data_available: bool, + /// X new data available + pub x_data_available: bool, +} + +impl From for Status { + fn from(value: u8) -> Self { + Status { + xyz_overrun: (value & 0x80) != 0, + z_overrun: (value & 0x40) != 0, + y_overrun: (value & 0x20) != 0, + x_overrun: (value & 0x10) != 0, + xyz_data_available: (value & 0x08) != 0, + z_data_available: (value & 0x04) != 0, + y_data_available: (value & 0x02) != 0, + x_data_available: (value & 0x01) != 0, + } + } +} + +/// FIFO status +#[derive(Debug, Clone, Copy, Default)] +pub struct FifoStatus { + /// Watermark level exceeded + pub watermark: bool, + /// FIFO overrun + pub overrun: bool, + /// FIFO empty + pub empty: bool, + /// Number of unread samples (0-32) + pub samples: u8, +} + +impl From for FifoStatus { + fn from(value: u8) -> Self { + FifoStatus { + watermark: (value & 0x80) != 0, + overrun: (value & 0x40) != 0, + empty: (value & 0x20) != 0, + samples: value & 0x1F, + } + } +} + +// ============================================================================= +// Interrupt Configuration Builders +// ============================================================================= + +/// Configuration for interrupt thresholds and axes +#[derive(Debug, Clone, Copy, Default)] +pub struct InterruptConfig { + /// Interrupt mode (OR, AND, 6D movement, 6D position) + pub mode: InterruptMode, + /// Enable X high event + pub x_high: bool, + /// Enable X low event + pub x_low: bool, + /// Enable Y high event + pub y_high: bool, + /// Enable Y low event + pub y_low: bool, + /// Enable Z high event + pub z_high: bool, + /// Enable Z low event + pub z_low: bool, + /// Threshold value (7-bit, 0-127) + pub threshold: u8, + /// Duration value (7-bit, 0-127) in 1/ODR units + pub duration: u8, +} + +impl InterruptConfig { + /// Create a new interrupt configuration + pub fn new() -> Self { Self::default() } + + /// Configure for motion detection on any axis + pub fn motion_any_axis(threshold: u8, duration: u8) -> Self { + InterruptConfig { + mode: InterruptMode::Movement6D, + x_high: true, + x_low: true, + y_high: true, + y_low: true, + z_high: true, + z_low: true, + threshold: threshold & 0x7F, + duration: duration & 0x7F, + } + } + + /// Configure for 6D position detection + pub fn position_6d(threshold: u8) -> Self { + InterruptConfig { + mode: InterruptMode::Position6D, + x_high: true, + x_low: true, + y_high: true, + y_low: true, + z_high: true, + z_low: true, + threshold: threshold & 0x7F, + duration: 0, + } + } + + /// Convert to INT_CFG register value + pub fn to_cfg_byte(&self) -> u8 { + let (aoi, d6) = self.mode.to_bits(); + let mut value = 0u8; + if aoi { + value |= 0x80; + } + if d6 { + value |= 0x40; + } + if self.z_high { + value |= 0x20; + } + if self.z_low { + value |= 0x10; + } + if self.y_high { + value |= 0x08; + } + if self.y_low { + value |= 0x04; + } + if self.x_high { + value |= 0x02; + } + if self.x_low { + value |= 0x01; + } + value + } +} + +/// Click/tap detection configuration +#[derive(Debug, Clone, Copy, Default)] +pub struct ClickConfig { + /// Enable double-click on X axis + pub x_double: bool, + /// Enable single-click on X axis + pub x_single: bool, + /// Enable double-click on Y axis + pub y_double: bool, + /// Enable single-click on Y axis + pub y_single: bool, + /// Enable double-click on Z axis + pub z_double: bool, + /// Enable single-click on Z axis + pub z_single: bool, + /// Click threshold (7-bit) + pub threshold: u8, + /// Time limit (7-bit) - max time for click + pub time_limit: u8, + /// Time latency - time between clicks for double-click + pub time_latency: u8, + /// Time window - max time for second click in double-click + pub time_window: u8, + /// Latch interrupt until CLICK_SRC is read + pub latch: bool, +} + +impl ClickConfig { + /// Create a new click configuration + pub fn new() -> Self { Self::default() } + + /// Configure for single tap detection on any axis + pub fn single_tap_any(threshold: u8, time_limit: u8) -> Self { + ClickConfig { + x_single: true, + y_single: true, + z_single: true, + threshold: threshold & 0x7F, + time_limit: time_limit & 0x7F, + ..Default::default() + } + } + + /// Configure for double tap detection on any axis + pub fn double_tap_any(threshold: u8, time_limit: u8, latency: u8, window: u8) -> Self { + ClickConfig { + x_double: true, + y_double: true, + z_double: true, + threshold: threshold & 0x7F, + time_limit: time_limit & 0x7F, + time_latency: latency, + time_window: window, + latch: true, + ..Default::default() + } + } + + /// Convert to CLICK_CFG register value + pub fn to_cfg_byte(&self) -> u8 { + let mut value = 0u8; + if self.z_double { + value |= 0x20; + } + if self.z_single { + value |= 0x10; + } + if self.y_double { + value |= 0x08; + } + if self.y_single { + value |= 0x04; + } + if self.x_double { + value |= 0x02; + } + if self.x_single { + value |= 0x01; + } + value + } + + /// Convert to CLICK_THS register value (includes latch bit) + pub fn to_ths_byte(&self) -> u8 { + let mut value = self.threshold & 0x7F; + if self.latch { + value |= 0x80; + } + value + } +} + +// ============================================================================= +// Main Driver +// ============================================================================= + +/// LIS2DH12 accelerometer driver +pub struct Lis2dh12 { + /// Current full-scale setting (cached for conversion calculations) + full_scale: FullScale, + /// Current operating mode (cached for conversion calculations) + operating_mode: OperatingMode, +} + +impl Lis2dh12 { + /// Create a new LIS2DH12 driver and initialize the device + /// + /// This performs a basic initialization: + /// - Waits for boot completion (5ms) + /// - Verifies the WHO_AM_I register + /// - Sets default operating mode (Normal, 10 Hz, all axes enabled) + /// - Sets default full scale (±2g) + pub fn new(i2c: &mut dyn I2cApi) -> Result { + let mut driver = Lis2dh12 { full_scale: FullScale::G2, operating_mode: OperatingMode::Normal }; + + // Wait for boot procedure to complete (datasheet says 5ms max) + Self::delay_ms(5); + + // Verify device identity + let who_am_i = driver.read_who_am_i(i2c)?; + if who_am_i != WHO_AM_I_VALUE { + return Err(xous::Error::NotFound); + } + + // Initialize with safe defaults + driver.init_defaults(i2c)?; + + Ok(driver) + } + + /// Delay for the specified number of milliseconds + fn delay_ms(ms: u64) { thread::sleep(Duration::from_millis(ms)); } + + /// Initialize device with default settings + fn init_defaults(&mut self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + // CTRL_REG0: Keep default (SDO pull-up enabled) + // Note: bit 4 must be 1 for correct operation + self.write_register(i2c, regs::CTRL_REG0, 0x10)?; + + // CTRL_REG1: 200 Hz, normal mode, all axes enabled + self.write_register(i2c, regs::CTRL_REG1, 0x67)?; + + // CTRL_REG2: No high-pass filter + self.write_register(i2c, regs::CTRL_REG2, 0x00)?; + + // CTRL_REG3: No interrupts on INT1 initially + self.write_register(i2c, regs::CTRL_REG3, 0x00)?; + + // CTRL_REG4: ±2g, BDU enabled, high-resolution disabled + self.write_register(i2c, regs::CTRL_REG4, 0x80)?; + + // CTRL_REG5: No boot, no FIFO, no latch + self.write_register(i2c, regs::CTRL_REG5, 0x00)?; + + // CTRL_REG6: No interrupts on INT2, active-high + self.write_register(i2c, regs::CTRL_REG6, 0x00)?; + + Ok(()) + } + + // ========================================================================= + // Low-level register access + // ========================================================================= + + /// Read a single register + fn read_register(&self, i2c: &mut dyn I2cApi, reg: u8) -> Result { + let mut buf = [0u8; 1]; + i2c.i2c_read(LIS2DH12_ADDR, reg, &mut buf, true).check()?; + Ok(buf[0]) + } + + /// Write a single register + fn write_register(&self, i2c: &mut dyn I2cApi, reg: u8, value: u8) -> Result<(), xous::Error> { + i2c.i2c_write(LIS2DH12_ADDR, reg, &[value]).check() + } + + /// Read multiple consecutive registers + fn read_registers(&self, i2c: &mut dyn I2cApi, start_reg: u8, buf: &mut [u8]) -> Result<(), xous::Error> { + // Set MSB for auto-increment + i2c.i2c_read(LIS2DH12_ADDR, start_reg | regs::AUTO_INCREMENT, buf, true).check() + } + + /// Modify a register using read-modify-write + fn modify_register(&self, i2c: &mut dyn I2cApi, reg: u8, f: F) -> Result<(), xous::Error> + where + F: FnOnce(u8) -> u8, + { + let value = self.read_register(i2c, reg)?; + self.write_register(i2c, reg, f(value)) + } + + // ========================================================================= + // Device identification and status + // ========================================================================= + + /// Read WHO_AM_I register (should return 0x33) + pub fn read_who_am_i(&self, i2c: &mut dyn I2cApi) -> Result { + self.read_register(i2c, regs::WHO_AM_I) + } + + /// Read the status register + pub fn read_status(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(Status::from(self.read_register(i2c, regs::STATUS_REG)?)) + } + + /// Check if new data is available + pub fn data_available(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(self.read_status(i2c)?.xyz_data_available) + } + + // ========================================================================= + // Operating mode configuration + // ========================================================================= + + /// Set the output data rate + pub fn set_data_rate(&mut self, i2c: &mut dyn I2cApi, rate: DataRate) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG1, |v| (v & 0x0F) | (u8::from(rate) << 4)) + } + + /// Get the current output data rate + pub fn get_data_rate(&self, i2c: &mut dyn I2cApi) -> Result { + let reg = self.read_register(i2c, regs::CTRL_REG1)?; + DataRate::try_from(reg >> 4) + } + + /// Set the full-scale range + pub fn set_full_scale(&mut self, i2c: &mut dyn I2cApi, scale: FullScale) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG4, |v| (v & 0xCF) | (u8::from(scale) << 4))?; + self.full_scale = scale; + Ok(()) + } + + /// Get the current full-scale range + pub fn get_full_scale(&self, i2c: &mut dyn I2cApi) -> Result { + let reg = self.read_register(i2c, regs::CTRL_REG4)?; + FullScale::try_from((reg >> 4) & 0x03) + } + + /// Set the operating mode (low-power, normal, or high-resolution) + /// + /// Note: Mode transitions have turn-on times that depend on ODR. + /// This function adds a conservative delay to ensure the mode change is complete. + pub fn set_operating_mode( + &mut self, + i2c: &mut dyn I2cApi, + mode: OperatingMode, + ) -> Result<(), xous::Error> { + let (lpen, hr) = mode.to_bits(); + + // If switching from high-resolution to another mode, read REFERENCE first + // (per datasheet recommendation for proper filter block reset) + if self.operating_mode == OperatingMode::HighResolution && mode != OperatingMode::HighResolution { + let _ = self.read_register(i2c, regs::REFERENCE)?; + } + + // Set LPen bit in CTRL_REG1 + self.modify_register(i2c, regs::CTRL_REG1, |v| if lpen { v | 0x08 } else { v & !0x08 })?; + + // Set HR bit in CTRL_REG4 + self.modify_register(i2c, regs::CTRL_REG4, |v| if hr { v | 0x08 } else { v & !0x08 })?; + + // Delay for mode transition (7/ODR worst case; at 10Hz = 700ms, but we use + // a shorter delay assuming higher ODR or accepting some startup samples) + // Using 10ms as a reasonable compromise + Self::delay_ms(10); + + self.operating_mode = mode; + Ok(()) + } + + /// Get the current operating mode + pub fn get_operating_mode(&self, i2c: &mut dyn I2cApi) -> Result { + let reg1 = self.read_register(i2c, regs::CTRL_REG1)?; + let reg4 = self.read_register(i2c, regs::CTRL_REG4)?; + let lpen = (reg1 & 0x08) != 0; + let hr = (reg4 & 0x08) != 0; + OperatingMode::from_bits(lpen, hr).ok_or(xous::Error::InvalidCoding) + } + + /// Enable or disable specific axes + pub fn set_axes_enabled( + &self, + i2c: &mut dyn I2cApi, + x: bool, + y: bool, + z: bool, + ) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG1, |v| { + let mut new_val = v & 0xF8; + if z { + new_val |= 0x04; + } + if y { + new_val |= 0x02; + } + if x { + new_val |= 0x01; + } + new_val + }) + } + + /// Enable Block Data Update (BDU) + /// + /// When enabled, output registers are not updated until both MSB and LSB + /// have been read, preventing reading of partially-updated data. + /// This is enabled by default. + pub fn enable_bdu(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG4, |v| v | 0x80) + } + + /// Disable Block Data Update (BDU) + /// + /// When disabled, output registers are continuously updated. + /// This may be useful for debugging but risks reading inconsistent data. + pub fn disable_bdu(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG4, |v| v & !0x80) + } + + /// Enter power-down mode + pub fn power_down(&mut self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.set_data_rate(i2c, DataRate::PowerDown) + } + + // ========================================================================= + // Acceleration data reading + // ========================================================================= + + /// Read raw acceleration data from all three axes + pub fn read_accel_raw(&self, i2c: &mut dyn I2cApi) -> Result { + let mut buf = [0u8; 6]; + self.read_registers(i2c, regs::OUT_X_L, &mut buf)?; + + Ok(AccelData { + x: i16::from_le_bytes([buf[0], buf[1]]), + y: i16::from_le_bytes([buf[2], buf[3]]), + z: i16::from_le_bytes([buf[4], buf[5]]), + }) + } + + /// Read acceleration data in milli-g + pub fn read_accel_mg(&self, i2c: &mut dyn I2cApi) -> Result<(i32, i32, i32), xous::Error> { + let raw = self.read_accel_raw(i2c)?; + Ok(raw.to_mg(self.full_scale, self.operating_mode)) + } + + /// Determine the current orientation of the device + /// + /// This checks if the device is face-up or face-down based on the Z-axis reading. + /// For pivoting around Y-axis (X changes sign), use `get_x_orientation()`. + pub fn get_orientation(&self, i2c: &mut dyn I2cApi) -> Result { + let (x, _, _) = self.read_accel_mg(i2c)?; + + // At rest, gravity should read ~1000 mg on the axis pointing up + // Use a threshold of 500 mg to account for tilt + const THRESHOLD_MG: i32 = 500; + + if x > THRESHOLD_MG { + Ok(Orientation::FaceUp) + } else if x < -THRESHOLD_MG { + Ok(Orientation::FaceDown) + } else { + Ok(Orientation::Unknown) + } + } + + /// Check if device is face-up or face-down based on X-axis (pivoting around Y) + /// + /// Returns true if X is positive (one orientation), false if negative (flipped) + pub fn is_x_positive(&self, i2c: &mut dyn I2cApi) -> Result { + let (x, _, _) = self.read_accel_mg(i2c)?; + Ok(x > 0) + } + + // ========================================================================= + // Temperature sensor + // ========================================================================= + + /// Enable the temperature sensor + pub fn enable_temperature(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + // Enable temperature sensor (TEMP_EN = 11) + self.write_register(i2c, regs::TEMP_CFG_REG, 0xC0)?; + // Also need BDU bit set (should already be set from init) + self.modify_register(i2c, regs::CTRL_REG4, |v| v | 0x80) + } + + /// Disable the temperature sensor + pub fn disable_temperature(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.write_register(i2c, regs::TEMP_CFG_REG, 0x00) + } + + /// Read temperature data (relative, not absolute) + /// + /// The temperature sensor provides relative temperature change with 1°C/digit resolution. + /// This is NOT calibrated for absolute temperature measurement. + pub fn read_temperature_raw(&self, i2c: &mut dyn I2cApi) -> Result { + let mut buf = [0u8; 2]; + self.read_registers(i2c, regs::OUT_TEMP_L, &mut buf)?; + Ok(i16::from_le_bytes([buf[0], buf[1]])) + } + + // ========================================================================= + // Debug helpers + // ========================================================================= + + /// Dump all interrupt-related register values for debugging + /// + /// Returns a struct with all the relevant register values that can be printed. + /// NOTE: Reading INT1_SRC clears a latched interrupt, so this may affect interrupt state! + pub fn debug_dump_int_config(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(IntDebugDump { + ctrl_reg1: self.read_register(i2c, regs::CTRL_REG1)?, + ctrl_reg2: self.read_register(i2c, regs::CTRL_REG2)?, + ctrl_reg3: self.read_register(i2c, regs::CTRL_REG3)?, + ctrl_reg4: self.read_register(i2c, regs::CTRL_REG4)?, + ctrl_reg5: self.read_register(i2c, regs::CTRL_REG5)?, + ctrl_reg6: self.read_register(i2c, regs::CTRL_REG6)?, + int1_cfg: self.read_register(i2c, regs::INT1_CFG)?, + int1_ths: self.read_register(i2c, regs::INT1_THS)?, + int1_duration: self.read_register(i2c, regs::INT1_DURATION)?, + int1_src: self.read_register(i2c, regs::INT1_SRC)?, + status_reg: self.read_register(i2c, regs::STATUS_REG)?, + }) + } + + /// Poll INT1_SRC to check if interrupt condition is met (without relying on pin) + /// + /// This reads INT1_SRC which will also clear a latched interrupt. + /// Returns true if the IA (interrupt active) bit is set. + pub fn poll_int1_active(&self, i2c: &mut dyn I2cApi) -> Result { + let src = self.read_register(i2c, regs::INT1_SRC)?; + Ok((src & 0x40) != 0) + } + + /// Simple interrupt test: configure with very low threshold and check if it triggers + /// + /// This sets threshold to 1 LSB (16mg at ±2g) with no duration requirement. + /// Should trigger almost immediately if the device is experiencing any acceleration + /// (including gravity if not perfectly level). + /// + /// Returns Ok(true) if interrupt triggered, Ok(false) if not. + pub fn debug_test_int1_simple(&self, i2c: &mut dyn I2cApi) -> Result { + // Save current config + /* + let saved_cfg = self.read_register(i2c, regs::INT1_CFG)?; + let saved_ths = self.read_register(i2c, regs::INT1_THS)?; + let saved_dur = self.read_register(i2c, regs::INT1_DURATION)?; + */ + let saved_ctrl3 = self.read_register(i2c, regs::CTRL_REG3)?; + + self.write_register(i2c, regs::CTRL_REG5, 0x08)?; + + // Configure for very sensitive motion detection + // INT1_CFG: OR combination, all axes high/low enabled + self.write_register(i2c, regs::INT1_CFG, 0x7F)?; + // INT1_THS: threshold = 1 (16mg at ±2g) + self.write_register(i2c, regs::INT1_THS, 8)?; + // INT1_DURATION: 0 (no minimum duration) + self.write_register(i2c, regs::INT1_DURATION, 0)?; + // CTRL_REG3: Enable IA1 on INT1 pin + self.write_register(i2c, regs::CTRL_REG3, saved_ctrl3 | 0x40)?; + + self.write_register(i2c, regs::CTRL_REG2, 0b00_00_0001)?; + self.read_register(i2c, regs::REFERENCE)?; + + // Wait a bit for new samples + Self::delay_ms(150); + + // Clear any pending interrupt by reading INT1_SRC + let _ = self.read_register(i2c, regs::INT1_SRC)?; + + // Check if interrupt is active + let src = self.read_register(i2c, regs::INT1_SRC)?; + let triggered = (src & 0x40) != 0; + + log::info!("debug_test_int1_simple: INT1_SRC = 0x{:02X}, triggered = {}", src, triggered); + + // Restore original config + /* + self.write_register(i2c, regs::INT1_CFG, saved_cfg)?; + self.write_register(i2c, regs::INT1_THS, saved_ths)?; + self.write_register(i2c, regs::INT1_DURATION, saved_dur)?; + self.write_register(i2c, regs::CTRL_REG3, saved_ctrl3)?; + */ + + Ok(triggered) + } + + // ========================================================================= + // Interrupt configuration - INT1 + // + // INT1 is configured as push-pull, active-high by default. + // When an interrupt condition is met, INT1 drives high. + // ========================================================================= + + /* + INFO:bao_console::cmds::test: mg data: (252, 16, -980) (services/bao-console/src/cmds/test.rs:289) + INFO:bao1x_hal::lis2dh12: setup int1: 3f, 6, 2 (libs/bao1x-hal/src/lis2dh12.rs:1065) + INFO:bao_console::cmds::test: Motion detected! InterruptSource { active: true, x_high: true, x_low: false, y_high: false, y_low: true, z_high: true, z_low: false } (services/bao-console/src/cmds/test.rs:302) + INFO:bao_console::cmds::test: Motion detected! InterruptSource { active: true, x_high: true, x_low: false, y_high: false, y_low: true, z_high: true, z_low: false } (services/bao-console/src/cmds/test.rs:302) + */ + + /// Configure interrupt 1 for motion/threshold detection + pub fn configure_int1(&self, i2c: &mut dyn I2cApi, config: &InterruptConfig) -> Result<(), xous::Error> { + // Write configuration register + self.write_register(i2c, regs::INT1_CFG, config.to_cfg_byte())?; + + // Write threshold + self.write_register(i2c, regs::INT1_THS, config.threshold & 0x7F)?; + + // Write duration + self.write_register(i2c, regs::INT1_DURATION, config.duration & 0x7F)?; + + Ok(()) + } + + /// Enable INT1 interrupt output on the INT1 pin + pub fn enable_int1_pin(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG3, |v| v | 0x40) // I1_IA1 + } + + /// Disable INT1 interrupt output on the INT1 pin + pub fn disable_int1_pin(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG3, |v| v & !0x40) + } + + /// Latch INT1 interrupt (stays active until INT1_SRC is read) + pub fn set_int1_latch(&self, i2c: &mut dyn I2cApi, latch: bool) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG5, |v| if latch { v | 0x08 } else { v & !0x08 }) + } + + /// Read and clear INT1 source register + pub fn read_int1_source(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(InterruptSource::from(self.read_register(i2c, regs::INT1_SRC)?)) + } + + // ========================================================================= + // Interrupt configuration - INT2 + // ========================================================================= + + /// Configure interrupt 2 for motion/threshold detection + pub fn configure_int2(&self, i2c: &mut dyn I2cApi, config: &InterruptConfig) -> Result<(), xous::Error> { + self.write_register(i2c, regs::INT2_CFG, config.to_cfg_byte())?; + self.write_register(i2c, regs::INT2_THS, config.threshold & 0x7F)?; + self.write_register(i2c, regs::INT2_DURATION, config.duration & 0x7F)?; + Ok(()) + } + + /// Enable INT2 interrupt output on the INT2 pin + pub fn enable_int2_pin(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| v | 0x20) // I2_IA2 + } + + /// Disable INT2 interrupt output on the INT2 pin + pub fn disable_int2_pin(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| v & !0x20) + } + + /// Latch INT2 interrupt + pub fn set_int2_latch(&self, i2c: &mut dyn I2cApi, latch: bool) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG5, |v| if latch { v | 0x02 } else { v & !0x02 }) + } + + /// Read and clear INT2 source register + pub fn read_int2_source(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(InterruptSource::from(self.read_register(i2c, regs::INT2_SRC)?)) + } + + /// Set interrupt polarity for both INT1 and INT2 + /// + /// Default is active-high (push-pull). Both pins share the same polarity setting. + /// Note: If using INT1 to drive a transistor gate that pulls another signal low, + /// keep the default active-high setting. + pub fn set_interrupt_polarity( + &self, + i2c: &mut dyn I2cApi, + polarity: InterruptPolarity, + ) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| match polarity { + InterruptPolarity::ActiveHigh => v & !0x02, + InterruptPolarity::ActiveLow => v | 0x02, + }) + } + + // ========================================================================= + // Click/Tap detection + // ========================================================================= + + /// Configure click/tap detection + pub fn configure_click(&self, i2c: &mut dyn I2cApi, config: &ClickConfig) -> Result<(), xous::Error> { + self.write_register(i2c, regs::CLICK_CFG, config.to_cfg_byte())?; + self.write_register(i2c, regs::CLICK_THS, config.to_ths_byte())?; + self.write_register(i2c, regs::TIME_LIMIT, config.time_limit & 0x7F)?; + self.write_register(i2c, regs::TIME_LATENCY, config.time_latency)?; + self.write_register(i2c, regs::TIME_WINDOW, config.time_window)?; + Ok(()) + } + + /// Enable click interrupt on INT1 pin + pub fn enable_click_int1(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG3, |v| v | 0x80) + } + + /// Disable click interrupt on INT1 pin + pub fn disable_click_int1(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG3, |v| v & !0x80) + } + + /// Enable click interrupt on INT2 pin + pub fn enable_click_int2(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| v | 0x80) + } + + /// Disable click interrupt on INT2 pin + pub fn disable_click_int2(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| v & !0x80) + } + + /// Read and clear click source register + pub fn read_click_source(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(ClickSource::from(self.read_register(i2c, regs::CLICK_SRC)?)) + } + + // ========================================================================= + // Activity/Inactivity detection (Sleep-to-wake) + // ========================================================================= + + /// Configure sleep-to-wake / return-to-sleep function + /// + /// When acceleration falls below threshold, device switches to 10Hz low-power mode. + /// When acceleration rises above threshold, device returns to configured mode. + /// + /// - `threshold`: Activity threshold (7-bit, in LSB units dependent on full scale) + /// - `duration`: Duration before return-to-sleep (8-bit, in (8*LSB+1)/ODR units) + pub fn configure_activity_detection( + &self, + i2c: &mut dyn I2cApi, + threshold: u8, + duration: u8, + ) -> Result<(), xous::Error> { + self.write_register(i2c, regs::ACT_THS, threshold & 0x7F)?; + self.write_register(i2c, regs::ACT_DUR, duration)?; + Ok(()) + } + + /// Enable activity interrupt on INT2 pin + pub fn enable_activity_int2(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| v | 0x08) + } + + /// Disable activity interrupt on INT2 pin + pub fn disable_activity_int2(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG6, |v| v & !0x08) + } + + // ========================================================================= + // FIFO operations + // ========================================================================= + + /// Enable FIFO + pub fn enable_fifo(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG5, |v| v | 0x40) + } + + /// Disable FIFO + pub fn disable_fifo(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG5, |v| v & !0x40) + } + + /// Configure FIFO mode and watermark + /// + /// - `mode`: FIFO operating mode + /// - `watermark`: Watermark level (0-31) + /// - `trigger_int2`: If true, trigger on INT2 instead of INT1 + pub fn configure_fifo( + &self, + i2c: &mut dyn I2cApi, + mode: FifoMode, + watermark: u8, + trigger_int2: bool, + ) -> Result<(), xous::Error> { + let mut value = (u8::from(mode) << 6) | (watermark & 0x1F); + if trigger_int2 { + value |= 0x20; + } + self.write_register(i2c, regs::FIFO_CTRL_REG, value) + } + + /// Read FIFO status + pub fn read_fifo_status(&self, i2c: &mut dyn I2cApi) -> Result { + Ok(FifoStatus::from(self.read_register(i2c, regs::FIFO_SRC_REG)?)) + } + + /// Enable FIFO watermark interrupt on INT1 + pub fn enable_fifo_watermark_int1(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG3, |v| v | 0x04) + } + + /// Enable FIFO overrun interrupt on INT1 + pub fn enable_fifo_overrun_int1(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG3, |v| v | 0x02) + } + + // ========================================================================= + // High-pass filter configuration + // ========================================================================= + + /// Configure the high-pass filter + pub fn configure_highpass( + &self, + i2c: &mut dyn I2cApi, + mode: HighPassFilterMode, + cutoff: u8, + filter_data_output: bool, + ) -> Result<(), xous::Error> { + let mut value = (u8::from(mode) << 6) | ((cutoff & 0x03) << 4); + if filter_data_output { + value |= 0x08; + } + self.write_register(i2c, regs::CTRL_REG2, value) + } + + /// Enable high-pass filter for click detection + pub fn enable_highpass_click(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG2, |v| v | 0x04) + } + + /// Enable high-pass filter for INT1 (AOI function) + pub fn enable_highpass_int1(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG2, |v| v | 0x01) + } + + /// Enable high-pass filter for INT2 (AOI function) + pub fn enable_highpass_int2(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG2, |v| v | 0x02) + } + + /// Reset high-pass filter by reading the REFERENCE register + pub fn reset_highpass(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + let _ = self.read_register(i2c, regs::REFERENCE)?; + Ok(()) + } + + // ========================================================================= + // Self-test + // ========================================================================= + + /// Enable self-test mode + pub fn set_self_test(&self, i2c: &mut dyn I2cApi, mode: SelfTestMode) -> Result<(), xous::Error> { + self.modify_register(i2c, regs::CTRL_REG4, |v| (v & 0xF9) | (u8::from(mode) << 1)) + } + + // ========================================================================= + // Convenience methods for common use cases + // ========================================================================= + + /// Quick setup for motion detection interrupt + /// + /// Sets up the accelerometer to generate an interrupt when motion exceeds + /// the specified threshold in mg. Uses INT1 pin. + /// + /// - `threshold_mg`: Motion threshold in milli-g + /// - `duration_ms`: Minimum duration of motion (approximate, depends on ODR) + pub fn setup_motion_interrupt( + &mut self, + i2c: &mut dyn I2cApi, + threshold_mg: u16, + duration_samples: u8, + ) -> Result<(), xous::Error> { + // Convert mg threshold to register value + let lsb_mg = self.full_scale.threshold_mg_per_lsb(); + let threshold = ((threshold_mg as u32) / (lsb_mg as u32)).min(127) as u8; + + let config = InterruptConfig::motion_any_axis(threshold, duration_samples); + self.configure_int1(i2c, &config)?; + self.set_int1_latch(i2c, true)?; + self.enable_int1_pin(i2c)?; + + Ok(()) + } + + /// Quick setup for tap detection + /// + /// Sets up single-tap detection on all axes using INT1 pin. + pub fn setup_tap_interrupt( + &mut self, + i2c: &mut dyn I2cApi, + threshold_mg: u16, + ) -> Result<(), xous::Error> { + // Convert mg threshold to register value + let lsb_mg = self.full_scale.threshold_mg_per_lsb(); + let threshold = ((threshold_mg as u32) / (lsb_mg as u32)).min(127) as u8; + + // Time limit depends on ODR - using conservative values + let config = ClickConfig::single_tap_any(threshold, 10); + self.configure_click(i2c, &config)?; + self.enable_click_int1(i2c)?; + + Ok(()) + } + + /// Quick setup for orientation detection using 6D position recognition + pub fn setup_orientation_detection(&self, i2c: &mut dyn I2cApi) -> Result<(), xous::Error> { + // Use 6D position detection with ~0.5g threshold (32 * 16mg = 512mg) + let config = InterruptConfig::position_6d(32); + self.configure_int1(i2c, &config)?; + self.set_int1_latch(i2c, true)?; + self.enable_int1_pin(i2c)?; + + Ok(()) + } +} + +// ============================================================================= +// Unit tests (for development/verification) +// ============================================================================= + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_data_rate_conversion() { + assert_eq!(u8::from(DataRate::Hz10), 0b0010); + assert_eq!(DataRate::try_from(0b0010).unwrap(), DataRate::Hz10); + } + + #[test] + fn test_full_scale_sensitivity() { + assert_eq!(FullScale::G2.sensitivity_mg(OperatingMode::HighResolution), 1); + assert_eq!(FullScale::G2.sensitivity_mg(OperatingMode::Normal), 4); + assert_eq!(FullScale::G2.sensitivity_mg(OperatingMode::LowPower), 16); + } + + #[test] + fn test_interrupt_config() { + let config = InterruptConfig::motion_any_axis(32, 5); + assert_eq!(config.to_cfg_byte(), 0x3F); // All axes, OR mode + assert_eq!(config.threshold, 32); + assert_eq!(config.duration, 5); + } + + #[test] + fn test_accel_conversion() { + let raw = AccelData { + x: 0x1000, // 4096 in left-justified 12-bit = 256 in 12-bit value + y: 0, + z: 0, + }; + let (x, y, z) = raw.to_mg(FullScale::G2, OperatingMode::HighResolution); + // 256 * 1 mg/digit = 256 mg + assert_eq!(x, 256); + assert_eq!(y, 0); + assert_eq!(z, 0); + } +} + +/* +This file based on driver generated by Claude Opus 4.5 based on the following prompt: + +I'm looking to write a driver for the part in the attached PDF, the LIS2DH12TR. it's an accelerometer. [PDF is uploaded to the context buffer] + +The framework I'm using is Xous. I've also pasted in a simple example driver for a different I2C part that gives you a template for how the driver should look. Note that for the driver you're writing, you only need to do the `std` code, so you can skip the no_std/std flags in the example and just do std. Xous is unusual in that it is an embedded microcontroller OS that also has std and runs in Rust. I'd also like you to improve the error handling from the example to use the `?` idiom to remove the match error handling - in general, all the errors in the API should a xous::Error type. I'll go into that more after going through the functional API. +[the file referred to is bao1x-hal/src/bmp180.rs] + +Here's what the trait definition is for the I2C interface: + +pub trait I2cApi { + fn i2c_write(&mut self, dev: u8, adr: u8, data: &[u8]) -> Result; + /// initiate an i2c read. The read buffer is passed during the await. + fn i2c_read( + &mut self, + dev: u8, + adr: u8, + buf: &mut [u8], + repeated_start: bool, + ) -> Result; +} + +In the case of a write, the `dev` field is the device address; the `adr` is the address of the register; and `data` is a slice that contains the byte or bytes to be written consecutively starting at `adr`. The Result will generally be an Ack(usize) where the argument inside Ack is the number of bytes written. + +In the case of a read, the arguments have a similar format, except that the read passes a &mut [u8] that is storage for the return result, and you can specify a `repeated_start` for the read (I think for this chip you want that to be `true`, but check my assumption). + +The I2C write/read are non-atomic, but guaranteed to have the correct ordering. In other words, it's possible that another device will do something else in between the i2c write/read causing things to wait a bit. I will *not* have two drivers at once fighting for the acceleramoter, but for example a PMIC could take the I2C bus and do something in between a write and read to the accelerometer. I don't think this is an edge case of concern here but if you see any sequences in the accelerometer datasheet where you *must* have two operations complete with no interruption between them, flag it. There is a different API I have to force a bus-wide atomic, uninterruptable sequence of reads/writes. + +The main things I need to do with the part are: + +* determine the orientation of the product: the orientation determination is very coarse, I just need to know if it is placed face up or face down (in this case, pivoting around the Y axis so the X-reading would change sign) +* generate an interrupt when the product is being worn/moved. possibly fine to just use a "tap" detection mode but if it has a mode to detect movement greater than some threshold of acceleration, an API to configure that interrupt would be useful + +In terms of the interrupt handler itself, I'll add an extension that responds to the interrupts separately from this driver; it doesn't need to exist in the I2C framework because the interrupt gets routed to a GPIO. So please just focus on: + +* Extracting the register set with human-readable names +* Extracting getter/setters for various registers, using enums to define values with the appropriate from/into fields to make an ergonomic programming interface +* Note that this is configured with SA0 tied high, so you'll need to set the I2C address accordingly. + +For error handling, the I2CResult possibilities are: + +pub enum I2cResult { + /// For the outbound message holder + Pending, + /// Returns # of bytes read or written if successful + Ack(usize), + /// An error occurred. + Nack, + /// An unhandled error has occurred. + InternalError, +} + +Ack is actually the Ok case - it's not an error. The `usize` argument is, in practice, *always* correct (the underlying implementation just passes back the requested number) so no code is needed to check that. Just ignore that number to keep the code compact. + +I don't know if this is possible but I'd like a compact way to use the `?` idiom to convert the other I2cResult members into a xous::Error type. The xous error types are here: + +pub enum Error { + NoError = 0, + BadAlignment = 1, + BadAddress = 2, + OutOfMemory = 3, + MemoryInUse = 4, + InterruptNotFound = 5, + InterruptInUse = 6, + InvalidString = 7, + ServerExists = 8, + ServerNotFound = 9, + ProcessNotFound = 10, + ProcessNotChild = 11, + ProcessTerminated = 12, + Timeout = 13, + InternalError = 14, + ServerQueueFull = 15, + ThreadNotAvailable = 16, + UnhandledSyscall = 17, + InvalidSyscall = 18, + ShareViolation = 19, + InvalidThread = 20, + InvalidPID = 21, + UnknownError = 22, + AccessDenied = 23, + UseBeforeInit = 24, + DoubleFree = 25, + DebugInProgress = 26, + InvalidLimit = 27, + /// For lookups that result in not found (e.g., searching for keys, resources, names) + NotFound = 28, + /// Used when try_from/try_into can't map a number into a smaller number of options + InvalidCoding = 29, + /// Used for ECC errors, glitches, power failures, etc. + HardwareError = 30, + /// Used when buffers & messages fail to serialize or deserialize + SerializationError = 31, + /// Used when a call is correct but its arguments are out of bounds, invalid, or otherwise poorly + /// specified + InvalidArgument = 32, + /// Catch-all for networking related problems (unreachable network, etc.) + NetworkError = 33, + /// Catch-all for storage related problems (particularly write/read ECC errors) + StorageError = 34, + /// Catch-all for resources that are busy or already allocated + Unavailable = 35, + /// For failed parsing attempts + ParseError = 36, + /// Invalid core number on multi-core APIs + InvalidCore = 37, + /// Reports when verification/check steps fail. Thrown when correctly functioning algorithms determine + /// that an object is invalid. + VerificationError = 38, + /// Used to report higher-severity system security/integrity issues, such as glitch attacks, ECC errors, + /// memory violations, bad states for hardened bools. Note that bad passwords/credentials should use + /// "AccessDenied" + SecurityError = 39, +} + +Nack/Pending errors should map to xous::Error::Timeout; InternalError maps to InternalError; and Ack is the case that everything is OK, it's not an error so it doesn't map to an error type. + +Ideally there's some nice Rust idiom or wrapper we can use to make this translation cleaner than a match statement on every I2C transaction, since we're going to be using it all over this driver, and it will impact readability if we're using a multi-line match statement or multi-line .unwrap_or_x() handling idioms. i.e. a wrapper trait or some intermediate would be ideal. + +Alright, I think that should give you everything you need to know to do this work. If you get stuck, don't spin endlessly, ask questions. i have plenty of examples and what not I am just trying to keep your context buffer tidy so you can focus on the task at hand. Good luck. +*/ From ece9b9943ca295105a619f7a5f1364841ee4daaa Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Jan 2026 22:20:56 +0800 Subject: [PATCH 14/28] add module --- libs/bao1x-hal/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libs/bao1x-hal/src/lib.rs b/libs/bao1x-hal/src/lib.rs index c40215f41..5759ab440 100644 --- a/libs/bao1x-hal/src/lib.rs +++ b/libs/bao1x-hal/src/lib.rs @@ -48,6 +48,8 @@ pub mod hardening; pub mod i2c; #[cfg(all(not(feature = "hosted-baosec"), feature = "std"))] pub mod kpc_aoint; +#[cfg(feature = "sensor-lis2dh12")] +pub mod lis2dh12; #[cfg(not(feature = "hosted-baosec"))] pub mod mbox; #[cfg(not(feature = "hosted-baosec"))] From 45632385d5b3e908ee4abc6ca62fc0e3b11bfdd6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 00:36:05 +0800 Subject: [PATCH 15/28] downgrade susres to a common api doesn't make sense to push this to crates.io because it's not common across all platforms, I think. --- Cargo.toml | 4 ++-- api/xous-api-ticktimer/Cargo.toml | 1 - apps-baosec/vault2/Cargo.toml | 2 ++ apps/vault/Cargo.toml | 2 +- libs/bao1x-hal/Cargo.toml | 3 ++- services/bao-console/Cargo.toml | 6 +++++- services/codec/Cargo.toml | 2 +- services/com/Cargo.toml | 2 +- services/dns/Cargo.toml | 2 +- services/early_settings/Cargo.toml | 2 +- services/ffi-test/Cargo.toml | 2 +- services/gam/Cargo.toml | 2 +- services/graphics-server/Cargo.toml | 9 ++------- services/jtag/Cargo.toml | 2 +- services/keyboard/Cargo.toml | 2 +- services/llio/Cargo.toml | 2 +- services/net/Cargo.toml | 2 +- services/pddb/Cargo.toml | 2 +- services/root-keys/Cargo.toml | 2 +- services/shellchat/Cargo.toml | 2 +- services/skeleton/Cargo.toml | 2 +- services/spinor/Cargo.toml | 2 +- services/status/Cargo.toml | 2 +- services/ticktimer-test-client/Cargo.toml | 2 +- services/trng/Cargo.toml | 2 +- services/usb-device-xous/Cargo.toml | 2 +- services/usb-test/Cargo.toml | 2 +- services/xous-ticktimer/Cargo.toml | 2 +- 28 files changed, 35 insertions(+), 34 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8606c555c..f5d6d0795 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -217,8 +217,6 @@ path = "./svd2utra" # path = "./xous-ipc" # [patch.crates-io.xous-api-names] # path = "./api/xous-api-names" -# [patch.crates-io.xous-api-susres] -# path = "./api/xous-api-susres" # [patch.crates-io.xous-api-log] # path = "./api/xous-api-log" # [patch.crates-io.xous-api-ticktimer] @@ -226,3 +224,5 @@ path = "./svd2utra" # [patch.crates-io.xous-tts-backend] # path = "../tts-backend" +# [patch.crates-io.xous-api-susres] +# path = "./api/xous-api-susres" diff --git a/api/xous-api-ticktimer/Cargo.toml b/api/xous-api-ticktimer/Cargo.toml index 349a624bd..09f935d33 100644 --- a/api/xous-api-ticktimer/Cargo.toml +++ b/api/xous-api-ticktimer/Cargo.toml @@ -13,7 +13,6 @@ homepage = "https://betrusted.io/xous-book/" xous = "0.9.69" xous-ipc = "0.10.9" log-server = { package = "xous-api-log", version = "0.1.68" } -susres = { package = "xous-api-susres", version = "0.9.68" } xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" rkyv = { version = "0.8.8", default-features = false, features = [ diff --git a/apps-baosec/vault2/Cargo.toml b/apps-baosec/vault2/Cargo.toml index 5c3872317..a986a10f3 100644 --- a/apps-baosec/vault2/Cargo.toml +++ b/apps-baosec/vault2/Cargo.toml @@ -60,6 +60,8 @@ sntpc = { version = "0.3.1" } # net = { path = "../../services/net" } # com_rs = { git = "https://github.com/betrusted-io/com_rs", rev = "891bdd3ca8e41f81510d112483e178aea3e3a921" } +# QR code encoding +base45 = "3.1.0" [dev-dependencies] enum-iterator = "0.6.0" diff --git a/apps/vault/Cargo.toml b/apps/vault/Cargo.toml index 73f202f5b..aeba7d715 100644 --- a/apps/vault/Cargo.toml +++ b/apps/vault/Cargo.toml @@ -23,7 +23,7 @@ xous-usb-hid = { git = "https://github.com/betrusted-io/xous-usb-hid.git", branc pddb = { path = "../../services/pddb" } modals = { path = "../../services/modals" } trng = { path = "../../services/trng" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } ime-plugin-api = { path = "../../services/ime-plugin-api" } content-plugin-api = { path = "../../services/content-plugin-api" } # all content canvas providers must provide this API backup = { path = "libraries/backup" } diff --git a/libs/bao1x-hal/Cargo.toml b/libs/bao1x-hal/Cargo.toml index 298a8edc4..0177f5572 100644 --- a/libs/bao1x-hal/Cargo.toml +++ b/libs/bao1x-hal/Cargo.toml @@ -58,6 +58,7 @@ bytemuck = "1.24.0" camera-ov2640 = [] camera-gc2145 = [] display-sh1107 = [] +sensor-lis2dh12 = [] axp2101 = [] bmp180 = [] sigcheck = ["ed25519-dalek", "sha2-bao1x", "digest", "linked_list_allocator"] @@ -72,7 +73,7 @@ board-baosec = [ "ux-api/std", ] # USB form factor token # "lite" variant of baosec. Shares the same basic flags but some things remapped when this is added. -oem-baosec-lite = [] +oem-baosec-lite = ["sensor-lis2dh12"] loader-baosec = [ "utralib/bao1x", diff --git a/services/bao-console/Cargo.toml b/services/bao-console/Cargo.toml index 0e6d6b9f4..6f8d91737 100644 --- a/services/bao-console/Cargo.toml +++ b/services/bao-console/Cargo.toml @@ -24,9 +24,12 @@ ux-api = { path = "../../libs/ux-api", optional = true } pddb = { path = "../pddb", optional = true } xous-swapper = { path = "../xous-swapper", optional = true } bytemuck = "1.24.0" -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } keystore = { path = "../keystore" } +bio-lib = { path = "../../libs/bio-lib" } +arbitrary-int = "1.2" + # pddb testing rand = { version = "0.8.5", features = ["getrandom"], optional = true } rand_chacha = { version = "0.3.1", optional = true } @@ -57,6 +60,7 @@ board-baosec = [ "xous-swapper", "ux-api/board-baosec", ] +oem-baosec-lite = ["bao1x-hal/sensor-lis2dh12"] hosted-baosec = [ "modals/hosted-baosec", "usb-bao1x/hosted-baosec", diff --git a/services/codec/Cargo.toml b/services/codec/Cargo.toml index 9f3a49729..d9ad959a5 100644 --- a/services/codec/Cargo.toml +++ b/services/codec/Cargo.toml @@ -12,7 +12,7 @@ log-server = { package = "xous-api-log", version = "0.1.68" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } llio = { path = "../llio" } trng = { path = "../trng" } diff --git a/services/com/Cargo.toml b/services/com/Cargo.toml index 32c5bbed0..7502a5631 100644 --- a/services/com/Cargo.toml +++ b/services/com/Cargo.toml @@ -11,7 +11,7 @@ com_rs = { git = "https://github.com/betrusted-io/com_rs", rev = "891bdd3ca8e41f log = "0.4.14" log-server = { package = "xous-api-log", version = "0.1.68" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } typenum = "1.12" xous = "0.9.69" xous-ipc = "0.10.9" diff --git a/services/dns/Cargo.toml b/services/dns/Cargo.toml index cb679a064..3ba594370 100644 --- a/services/dns/Cargo.toml +++ b/services/dns/Cargo.toml @@ -31,7 +31,7 @@ chrono = { version = "0.4.33", default-features = false, features = ["std"] } sntpc = { version = "0.3.1" } #, features = ["log"] locales = { path = "../../locales" } gam = { path = "../gam" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } userprefs = { path = "../../libs/userprefs" } modals = { path = "../modals" } precursor-hal = { path = "../../libs/precursor-hal" } diff --git a/services/early_settings/Cargo.toml b/services/early_settings/Cargo.toml index 7740b24d7..10e178d68 100644 --- a/services/early_settings/Cargo.toml +++ b/services/early_settings/Cargo.toml @@ -16,7 +16,7 @@ ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } xous = "0.9.69" xous-ipc = "0.10.9" xous-names = { package = "xous-api-names", version = "0.9.70" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } spinor = { path = "../../services/spinor" } precursor-hal = { path = "../../libs/precursor-hal" } diff --git a/services/ffi-test/Cargo.toml b/services/ffi-test/Cargo.toml index a2d58d28f..9a2ab0f69 100644 --- a/services/ffi-test/Cargo.toml +++ b/services/ffi-test/Cargo.toml @@ -14,7 +14,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } ffi-sys = { path = "sys" } keyboard = { path = "../keyboard" } diff --git a/services/gam/Cargo.toml b/services/gam/Cargo.toml index a990c871e..f96ab6f8e 100644 --- a/services/gam/Cargo.toml +++ b/services/gam/Cargo.toml @@ -30,7 +30,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ "alloc", ] } -susres = { package = "xous-api-susres", version = "0.9.68", optional = true } # used for the sleep now menu item +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres", optional = true } # used for the sleep now menu item bao1x-hal-service = { path = "../bao1x-hal-service", optional = true, default-features = false } enum_dispatch = "0.3.7" # used for trait-based dispatch off of multiple layout objects. diff --git a/services/graphics-server/Cargo.toml b/services/graphics-server/Cargo.toml index dbe150126..364a0e53e 100644 --- a/services/graphics-server/Cargo.toml +++ b/services/graphics-server/Cargo.toml @@ -11,7 +11,7 @@ keyboard = { path = "../keyboard" } log = "0.4.14" log-server = { package = "xous-api-log", version = "0.1.68" } xous = "0.9.69" -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } locales = { path = "../../locales" } blitstr2 = { path = "../../libs/blitstr2" } @@ -39,12 +39,7 @@ bao1x-hal = { path = "../../libs/bao1x-hal", optional = true, features = [ minifb = "0.26.0" [features] -bao1x = [ - "utralib/bao1x", - "bao1x-hal-service", - "bao1x-hal", - "bao1x-hal/std", -] +bao1x = ["utralib/bao1x", "bao1x-hal-service", "bao1x-hal", "bao1x-hal/std"] board-baosor = ["bao1x-hal/board-baosor", "blitstr2/board-baosor"] precursor = [ diff --git a/services/jtag/Cargo.toml b/services/jtag/Cargo.toml index 8a90c6f17..8b2513de5 100644 --- a/services/jtag/Cargo.toml +++ b/services/jtag/Cargo.toml @@ -14,7 +14,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } xous-ipc = "0.10.9" rkyv = { version = "0.8.8", default-features = false, features = [ diff --git a/services/keyboard/Cargo.toml b/services/keyboard/Cargo.toml index 6d39e74c4..a3e0ed7da 100644 --- a/services/keyboard/Cargo.toml +++ b/services/keyboard/Cargo.toml @@ -17,7 +17,7 @@ xous = "0.9.69" xous-ipc = "0.10.9" xous-names = { package = "xous-api-names", version = "0.9.70" } llio = { path = "../llio" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } spinor = { path = "../spinor" } num-derive = { version = "0.4.2", default-features = false } diff --git a/services/llio/Cargo.toml b/services/llio/Cargo.toml index 52689b415..51f44c083 100644 --- a/services/llio/Cargo.toml +++ b/services/llio/Cargo.toml @@ -13,7 +13,7 @@ ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } xous = "0.9.69" xous-ipc = "0.10.9" xous-names = { package = "xous-api-names", version = "0.9.70" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } # RTC dependencies bitflags = "1.2.1" diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml index 7bfe0b852..1f620e816 100644 --- a/services/net/Cargo.toml +++ b/services/net/Cargo.toml @@ -15,7 +15,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } rkyv = { version = "0.8.8", default-features = false, features = [ "std", "alloc", diff --git a/services/pddb/Cargo.toml b/services/pddb/Cargo.toml index 3f33825d3..16bcebe9b 100644 --- a/services/pddb/Cargo.toml +++ b/services/pddb/Cargo.toml @@ -13,7 +13,7 @@ xous-ipc = "0.10.9" log-server = { package = "xous-api-log", version = "0.1.68" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } xous-names = { package = "xous-api-names", version = "0.9.70" } -susres = { package = "xous-api-susres", version = "0.9.68", optional = true } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres", optional = true } log = "0.4.14" num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } diff --git a/services/root-keys/Cargo.toml b/services/root-keys/Cargo.toml index 6393384a7..2432cd020 100644 --- a/services/root-keys/Cargo.toml +++ b/services/root-keys/Cargo.toml @@ -12,7 +12,7 @@ log-server = { package = "xous-api-log", version = "0.1.68" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } trng = { path = "../trng" } spinor = { path = "../spinor" } llio = { path = "../llio" } diff --git a/services/shellchat/Cargo.toml b/services/shellchat/Cargo.toml index 90af71d43..9caea0566 100644 --- a/services/shellchat/Cargo.toml +++ b/services/shellchat/Cargo.toml @@ -23,7 +23,7 @@ xous = "0.9.69" xous-ipc = "0.10.9" xous-names = { package = "xous-api-names", version = "0.9.70" } keyboard = { path = "../keyboard" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } codec = { path = "../codec" } sha2 = { version = "0.10.8" } digest = "0.10.7" diff --git a/services/skeleton/Cargo.toml b/services/skeleton/Cargo.toml index d7e6005f8..427425854 100644 --- a/services/skeleton/Cargo.toml +++ b/services/skeleton/Cargo.toml @@ -14,7 +14,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } utralib = { version = "0.1.26", optional = true, default-features = false } diff --git a/services/spinor/Cargo.toml b/services/spinor/Cargo.toml index a17b827c3..95812ae8f 100644 --- a/services/spinor/Cargo.toml +++ b/services/spinor/Cargo.toml @@ -12,7 +12,7 @@ log-server = { package = "xous-api-log", version = "0.1.68" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.68" } xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } trng = { path = "../trng" } com = { path = "../com" } llio = { path = "../llio" } diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index 342fd5a56..02be3f079 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -20,7 +20,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } ux-api = { path = "../../libs/ux-api" } gam = { path = "../gam" } locales = { path = "../../locales" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } root-keys = { path = "../root-keys" } keystore-api = { path = "../../libs/keystore-api", features = ["gen1"] } modals = { path = "../modals" } diff --git a/services/ticktimer-test-client/Cargo.toml b/services/ticktimer-test-client/Cargo.toml index 81f9cf0e4..423d20f0d 100644 --- a/services/ticktimer-test-client/Cargo.toml +++ b/services/ticktimer-test-client/Cargo.toml @@ -10,7 +10,7 @@ version = "0.1.0" xous = "0.9.69" log = "0.4.14" log-server = { package = "xous-api-log", version = "0.1.68" } -susres = { package = "xous-api-susres", version = "0.9.68", optional = true } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres", optional = true } xous-names = { package = "xous-api-names", version = "0.9.70", optional = true } [features] diff --git a/services/trng/Cargo.toml b/services/trng/Cargo.toml index 1a6def8d6..b5519dfd3 100644 --- a/services/trng/Cargo.toml +++ b/services/trng/Cargo.toml @@ -14,7 +14,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" num-derive = { version = "0.4.1", default-features = false } num-traits = { version = "0.2.14", default-features = false } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } rkyv = { version = "0.8.8", default-features = false, features = [ "std", "alloc", diff --git a/services/usb-device-xous/Cargo.toml b/services/usb-device-xous/Cargo.toml index 580c943a4..d9784415e 100644 --- a/services/usb-device-xous/Cargo.toml +++ b/services/usb-device-xous/Cargo.toml @@ -20,7 +20,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ "std", "alloc", ] } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } modals = { path = "../modals", optional = true } keyboard = { path = "../keyboard", features = ["inject-api"], optional = true } bitfield = "0.13.2" diff --git a/services/usb-test/Cargo.toml b/services/usb-test/Cargo.toml index ceb5ae996..3f44b4c9f 100644 --- a/services/usb-test/Cargo.toml +++ b/services/usb-test/Cargo.toml @@ -14,7 +14,7 @@ xous-names = { package = "xous-api-names", version = "0.9.70" } log = "0.4.14" num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } keyboard = { path = "../keyboard" } bitfield = "0.13.2" vcell = "0.1.3" diff --git a/services/xous-ticktimer/Cargo.toml b/services/xous-ticktimer/Cargo.toml index 8955a5cf4..b4c54fcde 100644 --- a/services/xous-ticktimer/Cargo.toml +++ b/services/xous-ticktimer/Cargo.toml @@ -15,7 +15,7 @@ xous = "0.9.69" xous-ipc = "0.10.9" xous-names = { package = "xous-api-names", version = "0.9.70" } log-server = { package = "xous-api-log", version = "0.1.68" } -susres = { package = "xous-api-susres", version = "0.9.68" } +susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } log = "0.4.14" rkyv = { version = "0.8.8", default-features = false, features = [ "std", From cc090eaff89eba29ba9738b242c19fee1e675730 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 00:36:41 +0800 Subject: [PATCH 16/28] remove susres from verifier and version bump --- publish.py | 2 +- xtask/src/verifier.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/publish.py b/publish.py index efe8ea89e..d0574e7a8 100644 --- a/publish.py +++ b/publish.py @@ -17,7 +17,7 @@ CRATES = [ ["xous-ipc", "xous-ipc"], ["xous-api-log", "api/xous-api-log"], ["xous-api-names", "api/xous-api-names"], - ["xous-api-susres", "api/xous-api-susres"], + # ["xous-api-susres", "api/xous-api-susres"], ["xous-api-ticktimer", "api/xous-api-ticktimer"], # ["xous-log", "services/xous-log"], # implementations, no longer published # ["xous-names", "services/xous-names"], diff --git a/xtask/src/verifier.rs b/xtask/src/verifier.rs index 97059f020..cbbd52755 100644 --- a/xtask/src/verifier.rs +++ b/xtask/src/verifier.rs @@ -16,7 +16,7 @@ pub fn check_project_consistency() -> Result<(), DynError> { "xous-ipc^0.10.9", "xous-api-log^0.1.68", "xous-api-names^0.9.70", - "xous-api-susres^0.9.68", + // "xous-api-susres^0.9.68", "xous-api-ticktimer^0.9.68", ]; // utra/svd2utra changes are downgraded to warnings because these now prefer to pull From a28df43d71433c8cd574d2c8ec9f6b61b73306ee Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 00:37:03 +0800 Subject: [PATCH 17/28] update dependencies --- Cargo.lock | 77 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c8f265c62..cb610921a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -356,11 +356,13 @@ name = "bao-console" version = "0.1.0" dependencies = [ "aes", + "arbitrary-int", "bao1x-api", "bao1x-emu", "bao1x-hal", "bao1x-hal-service", "base45", + "bio-lib", "bytemuck", "chrono", "keystore", @@ -378,7 +380,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-swapper", "xous-usb-hid", @@ -484,7 +486,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -542,7 +544,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1168,7 +1170,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1199,7 +1201,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", @@ -1990,7 +1992,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2016,7 +2018,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2376,7 +2378,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", ] @@ -2674,7 +2676,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2785,7 +2787,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3320,7 +3322,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3360,7 +3362,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3556,7 +3558,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", @@ -3926,7 +3928,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", @@ -4384,7 +4386,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-swapper", @@ -5219,7 +5221,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", @@ -5548,7 +5550,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -5654,7 +5656,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -5799,7 +5801,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -5883,7 +5885,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", @@ -6062,7 +6064,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-swapper", ] @@ -6129,7 +6131,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", ] [[package]] @@ -6402,7 +6404,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -6614,7 +6616,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", @@ -6639,7 +6641,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-usb-hid", ] @@ -6868,7 +6870,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-usb-hid", @@ -6885,6 +6887,7 @@ dependencies = [ "bao1x-hal", "bao1x-hal-service", "base32", + "base45", "blitstr2", "byteorder", "cbor-vault2", @@ -7511,6 +7514,21 @@ dependencies = [ "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "xous-api-susres" +version = "0.9.68" +dependencies = [ + "log", + "num-derive 0.4.2", + "num-traits", + "rkyv 0.8.8", + "utralib 0.1.26", + "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-log", + "xous-api-names", + "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "xous-api-susres" version = "0.9.68" @@ -7521,7 +7539,6 @@ dependencies = [ "num-derive 0.4.2", "num-traits", "rkyv 0.8.8", - "utralib 0.1.26", "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", @@ -7541,7 +7558,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", ] @@ -7693,7 +7710,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -7732,7 +7749,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", From 6ae6b22ff33f0aab095ffab85437d3da4f356e7b Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:03:40 +0800 Subject: [PATCH 18/28] more cleanup from susres localization --- services/test-swapper/Cargo.toml | 2 +- services/xous-susres/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/test-swapper/Cargo.toml b/services/test-swapper/Cargo.toml index 642908d84..0db57e0c6 100644 --- a/services/test-swapper/Cargo.toml +++ b/services/test-swapper/Cargo.toml @@ -10,7 +10,7 @@ homepage = "https://betrusted.io/xous-book/" # Dependency versions enforced by Cargo.lock. [dependencies] -xous-api-susres = "0.9.68" +xous-api-susres = { path = "../../api/xous-api-susres" } xous-names = { package = "xous-api-names", version = "0.9.70" } log-server = { package = "xous-api-log", version = "0.1.68" } xous = "0.9.69" diff --git a/services/xous-susres/Cargo.toml b/services/xous-susres/Cargo.toml index 64e6350fa..1519b3c4c 100644 --- a/services/xous-susres/Cargo.toml +++ b/services/xous-susres/Cargo.toml @@ -10,7 +10,7 @@ homepage = "https://betrusted.io/xous-book/" # Dependency versions enforced by Cargo.lock. [dependencies] -xous-api-susres = "0.9.68" +xous-api-susres = { path = "../../api/xous-api-susres" } xous-names = { package = "xous-api-names", version = "0.9.70" } log-server = { package = "xous-api-log", version = "0.1.68" } xous = "0.9.69" From 75f75ebffae3ba3a11261d126b160fab2d5b446b Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:04:06 +0800 Subject: [PATCH 19/28] add hooks for oem-baosec-lite in the clock and power management --- libs/bao1x-hal/src/clocks.rs | 46 ++++++++++++++++++++++-------------- libs/bao1x-hal/src/lib.rs | 2 +- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/libs/bao1x-hal/src/clocks.rs b/libs/bao1x-hal/src/clocks.rs index 6c08a1d20..e04e78617 100644 --- a/libs/bao1x-hal/src/clocks.rs +++ b/libs/bao1x-hal/src/clocks.rs @@ -4,9 +4,9 @@ use bao1x_api::{IoxHal, IoxPort}; use bitbybit::bitfield; use utralib::*; -#[cfg(feature = "board-baosec")] +#[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] use crate::axp2101::Axp2101; -#[cfg(all(feature = "std", feature = "board-baosec"))] +#[cfg(all(feature = "std", feature = "board-baosec", not(feature = "oem-baosec-lite")))] use crate::i2c::I2c; #[cfg(feature = "std")] @@ -271,7 +271,7 @@ pub fn divide_by_fd(fd: u32, in_freq_hz: u32) -> u32 { } #[cfg(feature = "std")] -pub struct ClockManager { +pub struct ClockManagerImpl { pub vco_freq: u32, pub fclk: u32, pub aclk: u32, @@ -283,18 +283,20 @@ pub struct ClockManager { // this is a clone of what's in the kpc_aoint ao_sysctrl: CSR, susres: CSR, - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] i2c: I2c, #[cfg(feature = "board-baosec")] iox: IoxHal, - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] dcdc2_io: (IoxPort, u8), - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", feature = "oem-baosec-lite"))] + core_on: (IoxPort, u8), + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] pmic: Axp2101, } #[cfg(feature = "std")] -impl ClockManager { +impl ClockManagerImpl { pub fn new() -> Result { let sysctrl_mem = xous::map_memory( xous::MemoryAddress::new(utra::sysctrl::HW_SYSCTRL_BASE), @@ -351,13 +353,15 @@ impl ClockManager { } */ - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec"))] let iox = IoxHal::new(); - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] let (port, pin) = crate::board::setup_dcdc2_pin(&iox); - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", feature = "oem-baosec-lite"))] + let (port, pin) = crate::board::get_power_off_pin(); + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] let mut i2c = I2c::new(); - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] let pmic = crate::axp2101::Axp2101::new(&mut i2c).unwrap(); Ok(Self { @@ -371,13 +375,15 @@ impl ClockManager { sysctrl, ao_sysctrl: CSR::new(ao_mem.as_ptr() as *mut u32), susres: CSR::new(susres.as_ptr() as *mut u32), - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] i2c, #[cfg(feature = "board-baosec")] iox, - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] dcdc2_io: (port, pin), - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", feature = "oem-baosec-lite"))] + core_on: (port, pin), + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] pmic, }) } @@ -471,7 +477,7 @@ impl ClockManager { self.sysctrl.wo(utra::sysctrl::SFR_CGUSET, 0x32); wfi_debug("internal osc"); - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] { wfi_debug("disconnect dcdc2"); self.iox.set_gpio_pin_value(self.dcdc2_io.0, self.dcdc2_io.1, bao1x_api::IoxValue::High); @@ -491,6 +497,10 @@ impl ClockManager { // wfi_debug("DCDC4 off"); } + // set CoreOff to high + #[cfg(all(feature = "board-baosec", feature = "oem-baosec-lite"))] + self.iox.set_gpio_pin_value(self.core_on.0, self.core_on.1, bao1x_api::IoxValue::High); + // enter PD mode - cuts VDDCORE power - requires full reset to come out of this // only RTC & backup regsiters are kept. ~1.2mA @ 4.2V consumption in this mode. @@ -507,7 +517,7 @@ impl ClockManager { pub fn wfi(&mut self) { wfi_debug("entering wfi"); - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] { self.pmic.set_dcdc(&mut self.i2c, Some((0.7, true)), crate::axp2101::WhichDcDc::Dcdc2).unwrap(); wfi_debug("DCDC2 to low voltage"); @@ -593,7 +603,7 @@ impl ClockManager { // high disconnects DCDC2 from the chip - the idea is to prevent DCDC2 shutdown due to VLDO going // above DCDC2 value - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] { wfi_debug("disconnect dcdc2"); self.iox.set_gpio_pin_value(self.dcdc2_io.0, self.dcdc2_io.1, bao1x_api::IoxValue::High); @@ -606,7 +616,7 @@ impl ClockManager { .ok(); wfi_debug("back to 350MHz"); - #[cfg(feature = "board-baosec")] + #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] { wfi_debug("setting DCDC"); diff --git a/libs/bao1x-hal/src/lib.rs b/libs/bao1x-hal/src/lib.rs index 5759ab440..790bc306d 100644 --- a/libs/bao1x-hal/src/lib.rs +++ b/libs/bao1x-hal/src/lib.rs @@ -48,7 +48,7 @@ pub mod hardening; pub mod i2c; #[cfg(all(not(feature = "hosted-baosec"), feature = "std"))] pub mod kpc_aoint; -#[cfg(feature = "sensor-lis2dh12")] +#[cfg(all(feature = "sensor-lis2dh12", feature = "std"))] pub mod lis2dh12; #[cfg(not(feature = "hosted-baosec"))] pub mod mbox; From 3e4cbe441fc20ec8ce67a52b1608d90c9cfeda47 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:07:22 +0800 Subject: [PATCH 20/28] add apis to access clock state via the susres manager this requires a PlatformSpecific extension to the susres API. In addition to that, a DeepSleep op is added so we're no longer overloading the meaning of the SuspendRequest operation. --- services/bao1x-hal-service/Cargo.toml | 4 +- services/bao1x-hal-service/src/api.rs | 12 ++ services/bao1x-hal-service/src/lib.rs | 129 ++++++++++++++++++ services/bao1x-hal-service/src/main.rs | 4 +- .../bao1x-hal-service/src/servers/susres.rs | 47 +++++-- 5 files changed, 184 insertions(+), 12 deletions(-) diff --git a/services/bao1x-hal-service/Cargo.toml b/services/bao1x-hal-service/Cargo.toml index fd1e59103..f0e5f5f1b 100644 --- a/services/bao1x-hal-service/Cargo.toml +++ b/services/bao1x-hal-service/Cargo.toml @@ -15,7 +15,7 @@ xous = { version = "0.9.69", features = ["raw-trng"] } xous-ipc = "0.10.9" log-server = { package = "xous-api-log", version = "0.1.68" } log = "0.4.14" -xous-api-susres = "0.9.68" +xous-api-susres = { path = "../../api/xous-api-susres" } bao1x-hal = { path = "../../libs/bao1x-hal", default-features = false } bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] } bio-lib = { path = "../../libs/bio-lib" } @@ -48,7 +48,7 @@ swap = [] mpw = ["bao1x-hal/mpw"] bmp180 = ["bao1x-hal/bmp180"] board-baosec = ["bao1x-hal/board-baosec"] -oem-baosec-lite = [] +oem-baosec-lite = ["bao1x-hal/oem-baosec-lite"] board-baosor = ["bao1x-hal/board-baosor"] board-dabao = ["bao1x-hal/board-dabao"] diff --git a/services/bao1x-hal-service/src/api.rs b/services/bao1x-hal-service/src/api.rs index e611317f2..8ae1aa918 100644 --- a/services/bao1x-hal-service/src/api.rs +++ b/services/bao1x-hal-service/src/api.rs @@ -20,3 +20,15 @@ pub enum TimeOp { /// Serialize the internal state for storage across reboots GetState = 1024, } + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub enum ClockOp { + GetVco, + GetFclk, + GetAclk, + GetHclk, + GetIclk, + GetPclk, + GetPer, + DeepSleep, +} diff --git a/services/bao1x-hal-service/src/lib.rs b/services/bao1x-hal-service/src/lib.rs index a7e542506..094017777 100644 --- a/services/bao1x-hal-service/src/lib.rs +++ b/services/bao1x-hal-service/src/lib.rs @@ -5,6 +5,10 @@ use core::sync::atomic::{AtomicU32, Ordering}; use bao1x_api::*; use num_traits::*; +use xous::{Message, send_message}; +use xous_api_susres::api::Opcode as SusresOp; + +use crate::api::ClockOp; static REFCOUNT: AtomicU32 = AtomicU32::new(0); pub struct UdmaGlobal { @@ -128,3 +132,128 @@ impl UdmaGlobalConfig for UdmaGlobal { } } } + +pub struct ClockManager { + conn: xous::CID, +} +impl ClockManager { + pub fn new() -> Self { + let xns = xous_names::XousNames::new().unwrap(); + let conn = xns + .request_connection_blocking(xous_api_susres::api::SERVER_NAME_SUSRES) + .expect("Couldn't connect to susres server"); + ClockManager { conn } + } + + pub fn get_fclk(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetFclk.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } + + pub fn get_aclk(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetAclk.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } + + pub fn get_hclk(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetHclk.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } + + pub fn get_iclk(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetIclk.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } + + pub fn get_pclk(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetPclk.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } + + pub fn get_per(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetPer.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } + + pub fn get_vco(&self) -> u32 { + match send_message( + self.conn, + Message::new_blocking_scalar( + SusresOp::PlatformSpecific.to_usize().unwrap(), + ClockOp::GetVco.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(clk)) => clk as u32, + _ => unimplemented!(), + } + } +} diff --git a/services/bao1x-hal-service/src/main.rs b/services/bao1x-hal-service/src/main.rs index 09e3e5654..09d3f0c78 100644 --- a/services/bao1x-hal-service/src/main.rs +++ b/services/bao1x-hal-service/src/main.rs @@ -273,8 +273,8 @@ fn main() { servers::susres::start_susres_service(); - // TODO: implement a method to fetch the clock setting from susres and put it into here! - servers::bio::start_bio_service(bao1x_hal::board::DEFAULT_FCLK_FREQUENCY); + let clk_mgr = bao1x_hal_service::ClockManager::new(); + servers::bio::start_bio_service(clk_mgr.get_fclk()); // claim BIO, based on the platform servers::trng::start_trng_service(); diff --git a/services/bao1x-hal-service/src/servers/susres.rs b/services/bao1x-hal-service/src/servers/susres.rs index f3b91b67c..89147e7d1 100644 --- a/services/bao1x-hal-service/src/servers/susres.rs +++ b/services/bao1x-hal-service/src/servers/susres.rs @@ -1,11 +1,14 @@ use core::sync::atomic::{AtomicU32, Ordering}; +use bao1x_hal_service::api::ClockOp; use num_traits::*; use utralib::*; use xous::{CID, Message, msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, sender::Sender}; use xous_api_susres::*; use xous_ipc::Buffer; +use crate::api::ClockOp; + static TIMEOUT_TIME: AtomicU32 = AtomicU32::new(5000); #[derive(Copy, Clone, Debug)] @@ -31,7 +34,7 @@ fn susres_service() { let susres_sid = xns.register_name(api::SERVER_NAME_SUSRES, None).expect("can't register server"); let susres_conn = xous::connect(susres_sid).unwrap(); - let mut clk_mgr = bao1x_hal::clocks::ClockManager::new().unwrap(); + let mut clk_mgr = bao1x_hal::clocks::ClockManagerImpl::new().unwrap(); let measured = clk_mgr.measured_freqs(); log::info!("computed frequencies:"); log::info!(" vco: {}", clk_mgr.vco_freq); @@ -220,13 +223,6 @@ fn susres_service() { } }), Some(Opcode::SuspendRequest) => msg_blocking_scalar_unpack!(msg, deepsleep, 0, 0, 0, { - // catch the case of deepsleep request - if deepsleep == 1 { - log::info!("entering deep sleep"); - clk_mgr.deep_sleep(); - xous::return_scalar(msg.sender, 1).ok(); - // system is shut down after this point, no code runs - } log::info!("registered suspend listeners:"); for sub in suspend_subscribers.iter() { log::info!("{:?}", sub); @@ -340,6 +336,41 @@ fn susres_service() { } }), Some(Opcode::Quit) => break, + Some(Opcode::PlatformSpecific) => { + msg_blocking_scalar_unpack!(msg, op, _arg2, _arg3, _arg4, { + let platform_op = FromPrimitive::from_usize(op); + match platform_op { + Some(ClockOp::GetVco) => { + xous::return_scalar(msg.sender, clk_mgr.vco_freq as usize).unwrap() + } + Some(ClockOp::GetFclk) => { + xous::return_scalar(msg.sender, clk_mgr.fclk as usize).unwrap() + } + Some(ClockOp::GetAclk) => { + xous::return_scalar(msg.sender, clk_mgr.aclk as usize).unwrap() + } + Some(ClockOp::GetHclk) => { + xous::return_scalar(msg.sender, clk_mgr.hclk as usize).unwrap() + } + Some(ClockOp::GetIclk) => { + xous::return_scalar(msg.sender, clk_mgr.iclk as usize).unwrap() + } + Some(ClockOp::GetPclk) => { + xous::return_scalar(msg.sender, clk_mgr.pclk as usize).unwrap() + } + Some(ClockOp::GetPer) => { + xous::return_scalar(msg.sender, clk_mgr.perclk as usize).unwrap() + } + Some(ClockOp::DeepSleep) => { + log::info!("entering deep sleep"); + clk_mgr.deep_sleep(); + xous::return_scalar(msg.sender, 1).ok(); + // system is shut down after this point, no code runs + } + _ => panic!("Incorrect PlatformOp"), + } + }) + } None => { log::error!("couldn't convert opcode"); } From 61ac848e710953b80530fc03e8a427a621f3c46c Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:08:30 +0800 Subject: [PATCH 21/28] add PlatformSpecific op extension to susres --- api/xous-api-susres/src/api.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/api/xous-api-susres/src/api.rs b/api/xous-api-susres/src/api.rs index 35daeed78..cda517f19 100644 --- a/api/xous-api-susres/src/api.rs +++ b/api/xous-api-susres/src/api.rs @@ -69,6 +69,10 @@ pub enum Opcode { /// exit the server Quit, + + /// Platform specific + #[cfg(feature = "bao1x")] + PlatformSpecific, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] From 22c8ce43084dc49ccb7710cf17d86aea423eb6fd Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:09:08 +0800 Subject: [PATCH 22/28] fix dangling susres api migration --- services/bao1x-emu/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/bao1x-emu/Cargo.toml b/services/bao1x-emu/Cargo.toml index 8e6ef27f6..9a24d600a 100644 --- a/services/bao1x-emu/Cargo.toml +++ b/services/bao1x-emu/Cargo.toml @@ -20,7 +20,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [ "alloc", ] } bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] } -xous-api-susres = "0.9.68" +xous-api-susres = { path = "../../api/xous-api-susres" } [target.'cfg(any(windows,unix))'.dependencies] minifb = "0.26.0" From 3b0edbb44214847f46a18dabfd0c15a63e5bdfe5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:09:52 +0800 Subject: [PATCH 23/28] add some more test routines - some of these will be culled shortly --- services/bao-console/src/cmds/test.rs | 80 ++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/services/bao-console/src/cmds/test.rs b/services/bao-console/src/cmds/test.rs index e39137623..f63e62697 100644 --- a/services/bao-console/src/cmds/test.rs +++ b/services/bao-console/src/cmds/test.rs @@ -1,3 +1,5 @@ +use std::time::Duration; + use String; use crate::{CommonEnv, ShellCmdApi}; @@ -134,8 +136,8 @@ impl<'a> ShellCmdApi<'a> for Test { match xous::send_message( conn, xous::Message::new_blocking_scalar( - susres::api::Opcode::SuspendRequest.to_usize().unwrap(), - 1, // this is a monkeypatch + susres::api::Opcode::PlatformSpecific.to_usize().unwrap(), + bao1x_hal_service::api::ClockOp::DeepSleep.to_usize().unwrap(), 0, 0, 0, @@ -250,6 +252,80 @@ impl<'a> ShellCmdApi<'a> for Test { } } } + "cam" => { + use bao1x_api::I2cApi; + let mut i2c = bao1x_hal::i2c::I2c::new(); + if args.len() < 1 { + write!(ret, "cam [poke adr data]").ok(); + return Ok(Some(ret)); + } + if args[0] == "poke" { + if args.len() != 3 { + write!(ret, "cam poke adr(hex) data(hex)").ok(); + return Ok(Some(ret)); + } + let adr = u8::from_str_radix(&args[1], 16).map_err(|_| xous::Error::InvalidArgument)?; + let data = u8::from_str_radix(&args[2], 16).map_err(|_| xous::Error::InvalidArgument)?; + i2c.i2c_write(0x3C, adr, &[data]).expect("write failed"); + write!(ret, "Wrote {:x} into {:x}", data, adr).ok(); + } + } + "accel" => { + use std::time::Instant; + + use bao1x_hal::i2c::I2c; + use bao1x_hal::lis2dh12::{Lis2dh12, Orientation}; + + let mut i2c = I2c::new(); + // Initialize + let mut accel = Lis2dh12::new(&mut i2c).unwrap(); + + // Check orientation + let duration = Duration::from_secs(2); + let start_time = Instant::now(); + while Instant::now().duration_since(start_time).lt(&duration) { + let orientation = accel.get_orientation(&mut i2c).unwrap(); + match orientation { + Orientation::FaceUp => println!("Face up"), + Orientation::FaceDown => println!("Face down"), + Orientation::Unknown => println!("Tilted/transitioning"), + } + let raw_data = accel.read_accel_mg(&mut i2c).unwrap(); + log::info!("mg data: {:?}", raw_data); + _env.ticktimer.sleep_ms(50).ok(); + } + + // Set up motion interrupt (200mg threshold, 5 samples duration) + // accel.set_int1_latch(&mut i2c, true)?; + // accel.setup_motion_interrupt(&mut i2c, 100, 2)?; + log::info!("result: {:?}", accel.debug_test_int1_simple(&mut i2c)?); + + let debug = accel.debug_dump_int_config(&mut i2c)?; + debug.interpret(); + log::info!("debug: {:?}", debug); + + // Later, when INT1 fires, read and clear the interrupt source + let duration = Duration::from_secs(30); + let start_time = Instant::now(); + while Instant::now().duration_since(start_time).lt(&duration) { + let source = accel.read_int1_source(&mut i2c)?; + if source.active { + log::info!( + "Motion detected! {:?} {:?}", + source, + accel.read_accel_mg(&mut i2c).unwrap() + ); + accel.reset_highpass(&mut i2c)?; + } + _env.ticktimer.sleep_ms(150).ok(); + /* + if accel.poll_int1_active(&mut i2c)? { + log::info!("int active"); + let raw_data = accel.read_accel_mg(&mut i2c).unwrap(); + log::info!("mg data: {:?}", raw_data); + }*/ + } + } /* // leave this around in case we have more swap bugs to debug // needs to have `swaptest1`` & `swaptest2` added to the image for this to work. "swap" => { From b84ff3d35140f610b47d37e0659ca782e18df3a0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:10:15 +0800 Subject: [PATCH 24/28] add a menu item to show a test QR code this is useful for testing inter-device QR code scanning. --- apps-baosec/vault2/src/actions.rs | 4 ++++ apps-baosec/vault2/src/main.rs | 10 ++++++++++ apps-baosec/vault2/src/submenu.rs | 7 +++++++ apps-baosec/vault2/src/vault_api.rs | 2 ++ 4 files changed, 23 insertions(+) diff --git a/apps-baosec/vault2/src/actions.rs b/apps-baosec/vault2/src/actions.rs index 7e8ccc271..7ebbc1252 100644 --- a/apps-baosec/vault2/src/actions.rs +++ b/apps-baosec/vault2/src/actions.rs @@ -1444,6 +1444,10 @@ impl ActionManager { .ok(); } } + } else { + let mut qr_str = String::from(t!("vault.error.qr", locales::LANG)); + qr_str.push_str(&format!(": {}", &qr_uri)); + self.modals.show_notification(&qr_str, None).ok(); } } } diff --git a/apps-baosec/vault2/src/main.rs b/apps-baosec/vault2/src/main.rs index bbf278467..0476ee969 100644 --- a/apps-baosec/vault2/src/main.rs +++ b/apps-baosec/vault2/src/main.rs @@ -536,6 +536,16 @@ fn main() -> ! { ) .ok(); } + Some(VaultOp::ShowQr) => { + let previous = allow_totp_rendering.load(Ordering::SeqCst); + allow_totp_rendering.store(false, Ordering::SeqCst); + let mut test_data = [0u8; 40]; + let mut trng = bao1x_hal_service::trng::Trng::new(&xns).unwrap(); + trng.fill_bytes_via_next(&mut test_data); + let encoded = base45::encode(&test_data); + modals.show_notification("", Some(&encoded)).ok(); + allow_totp_rendering.store(previous, Ordering::SeqCst); + } _ => { log::error!("Got unknown message: {:?}", msg); } diff --git a/apps-baosec/vault2/src/submenu.rs b/apps-baosec/vault2/src/submenu.rs index 219afe2bc..a4d58433f 100644 --- a/apps-baosec/vault2/src/submenu.rs +++ b/apps-baosec/vault2/src/submenu.rs @@ -52,6 +52,13 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); + menu_items.push(MenuItem { + name: String::from("Test QR code"), + action_conn: Some(vault_conn), + action_opcode: VaultOp::ShowQr.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); menu_items.push(MenuItem { name: String::from(t!("vault.menu_close", locales::LANG)), action_conn: Some(actions_conn), diff --git a/apps-baosec/vault2/src/vault_api.rs b/apps-baosec/vault2/src/vault_api.rs index f6299805b..82b840896 100644 --- a/apps-baosec/vault2/src/vault_api.rs +++ b/apps-baosec/vault2/src/vault_api.rs @@ -42,6 +42,8 @@ pub(crate) enum VaultOp { MenuPwMode, BasisChange, + + ShowQr, } pub fn atime_to_str(req_atime: u64) -> String { From a76222bda335f3f83d9b693dadd6004a718b23e2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:10:38 +0800 Subject: [PATCH 25/28] more dependency cleanup --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb610921a..ca84f5160 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -486,7 +486,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-susres 0.9.68", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -544,7 +544,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-susres 0.9.68", "xous-api-ticktimer", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -6064,7 +6064,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-susres 0.9.68", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", "xous-swapper", ] @@ -7710,7 +7710,7 @@ dependencies = [ "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", - "xous-api-susres 0.9.68 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-susres 0.9.68", "xous-ipc 0.10.9 (registry+https://github.com/rust-lang/crates.io-index)", ] From c2640458f5f002d668727e086b53804de95a440a Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:21:39 +0800 Subject: [PATCH 26/28] fix hosted mode and warnings --- apps-baosec/vault2/src/main.rs | 3 +++ services/bao-console/Cargo.toml | 3 ++- services/bao-console/src/cmds/test.rs | 6 +++--- services/bao-video/src/main.rs | 2 +- services/bao1x-emu/src/display.rs | 9 +++++++++ services/bao1x-hal-service/src/servers/susres.rs | 3 +-- 6 files changed, 19 insertions(+), 7 deletions(-) diff --git a/apps-baosec/vault2/src/main.rs b/apps-baosec/vault2/src/main.rs index 0476ee969..6df8541e1 100644 --- a/apps-baosec/vault2/src/main.rs +++ b/apps-baosec/vault2/src/main.rs @@ -540,6 +540,9 @@ fn main() -> ! { let previous = allow_totp_rendering.load(Ordering::SeqCst); allow_totp_rendering.store(false, Ordering::SeqCst); let mut test_data = [0u8; 40]; + #[cfg(feature = "hosted-baosec")] + let mut trng = bao1x_emu::trng::Trng::new(&xns).unwrap(); + #[cfg(not(feature = "hosted-baosec"))] let mut trng = bao1x_hal_service::trng::Trng::new(&xns).unwrap(); trng.fill_bytes_via_next(&mut test_data); let encoded = base45::encode(&test_data); diff --git a/services/bao-console/Cargo.toml b/services/bao-console/Cargo.toml index 6f8d91737..d603cb5a1 100644 --- a/services/bao-console/Cargo.toml +++ b/services/bao-console/Cargo.toml @@ -27,7 +27,7 @@ bytemuck = "1.24.0" susres = { path = "../../api/xous-api-susres", package = "xous-api-susres" } keystore = { path = "../keystore" } -bio-lib = { path = "../../libs/bio-lib" } +bio-lib = { path = "../../libs/bio-lib", optional = true } arbitrary-int = "1.2" # pddb testing @@ -59,6 +59,7 @@ board-baosec = [ "pddb/board-baosec", "xous-swapper", "ux-api/board-baosec", + "bio-lib", ] oem-baosec-lite = ["bao1x-hal/sensor-lis2dh12"] hosted-baosec = [ diff --git a/services/bao-console/src/cmds/test.rs b/services/bao-console/src/cmds/test.rs index f63e62697..06f9bb20b 100644 --- a/services/bao-console/src/cmds/test.rs +++ b/services/bao-console/src/cmds/test.rs @@ -1,5 +1,3 @@ -use std::time::Duration; - use String; use crate::{CommonEnv, ShellCmdApi}; @@ -252,6 +250,7 @@ impl<'a> ShellCmdApi<'a> for Test { } } } + #[cfg(not(feature = "hosted-baosec"))] "cam" => { use bao1x_api::I2cApi; let mut i2c = bao1x_hal::i2c::I2c::new(); @@ -270,8 +269,9 @@ impl<'a> ShellCmdApi<'a> for Test { write!(ret, "Wrote {:x} into {:x}", data, adr).ok(); } } + #[cfg(all(not(feature = "hosted-baosec"), feature = "oem-baosec-lite"))] "accel" => { - use std::time::Instant; + use std::time::{Duration, Instant}; use bao1x_hal::i2c::I2c; use bao1x_hal::lis2dh12::{Lis2dh12, Orientation}; diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 7d5c252cd..e5c864251 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -266,7 +266,7 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { udma_global.udma_clock_config(PeriphId::Cam, true); // ---- camera initialization - #[cfg(not(feature = "oem-baosec-lite"))] + #[cfg(all(not(feature = "oem-baosec-lite"), not(feature = "hosted-baosec")))] let cam_clk = (IoxPort::PA, 0); #[cfg(feature = "oem-baosec-lite")] let cam_clk = (IoxPort::PA, 3); diff --git a/services/bao1x-emu/src/display.rs b/services/bao1x-emu/src/display.rs index 9893f9b4d..b0bc7e92a 100644 --- a/services/bao1x-emu/src/display.rs +++ b/services/bao1x-emu/src/display.rs @@ -172,6 +172,15 @@ impl FrameBuffer for Oled128x128 { } } + unsafe fn put_pixel_unchecked(&mut self, p: Point, on: ColorNative) { + let bitnum = (p.x + p.y * COLUMN) as usize; + if on.0 != 0 { + self.buffer[bitnum / 32] |= 1 << (bitnum % 32); + } else { + self.buffer[bitnum / 32] &= !(1 << (bitnum % 32)); + } + } + fn dimensions(&self) -> Point { Point::new(COLUMN, ROW) } fn get_pixel(&self, p: Point) -> Option { diff --git a/services/bao1x-hal-service/src/servers/susres.rs b/services/bao1x-hal-service/src/servers/susres.rs index 89147e7d1..778a22aeb 100644 --- a/services/bao1x-hal-service/src/servers/susres.rs +++ b/services/bao1x-hal-service/src/servers/susres.rs @@ -1,6 +1,5 @@ use core::sync::atomic::{AtomicU32, Ordering}; -use bao1x_hal_service::api::ClockOp; use num_traits::*; use utralib::*; use xous::{CID, Message, msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, sender::Sender}; @@ -222,7 +221,7 @@ fn susres_service() { log::trace!("still waiting on callbacks, returning to main loop"); } }), - Some(Opcode::SuspendRequest) => msg_blocking_scalar_unpack!(msg, deepsleep, 0, 0, 0, { + Some(Opcode::SuspendRequest) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { log::info!("registered suspend listeners:"); for sub in suspend_subscribers.iter() { log::info!("{:?}", sub); From 3bc1c234255af85bac170ed3813dd7892422f5b4 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:31:22 +0800 Subject: [PATCH 27/28] add missing feature flag --- services/bao1x-hal-service/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/bao1x-hal-service/Cargo.toml b/services/bao1x-hal-service/Cargo.toml index f0e5f5f1b..3974a1d24 100644 --- a/services/bao1x-hal-service/Cargo.toml +++ b/services/bao1x-hal-service/Cargo.toml @@ -15,7 +15,7 @@ xous = { version = "0.9.69", features = ["raw-trng"] } xous-ipc = "0.10.9" log-server = { package = "xous-api-log", version = "0.1.68" } log = "0.4.14" -xous-api-susres = { path = "../../api/xous-api-susres" } +xous-api-susres = { path = "../../api/xous-api-susres", features = ["bao1x"] } bao1x-hal = { path = "../../libs/bao1x-hal", default-features = false } bao1x-api = { path = "../../libs/bao1x-api", features = ["derive-rkyv", "std"] } bio-lib = { path = "../../libs/bio-lib" } From dc56fc7a09913504e10c8a8c85b833913d5d47d6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 28 Jan 2026 15:44:18 +0800 Subject: [PATCH 28/28] fix precursor builds --- Cargo.lock | 3 ++- services/graphics-server/src/backend/betrusted.rs | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index ca84f5160..cd82f5801 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5535,7 +5535,7 @@ dependencies = [ [[package]] name = "sha2" version = "0.10.8" -source = "git+https://github.com/betrusted-io/hashes.git?branch=sha2-v0.10.8-xous#ef15aee3576eda5429b361bdee51eae3379ba8ff" +source = "git+https://github.com/betrusted-io/hashes.git?branch=sha2-v0.10.8-xous#c190327961172f8160db39f178ca6232fda8c8bf" dependencies = [ "cfg-if", "cpufeatures", @@ -7539,6 +7539,7 @@ dependencies = [ "num-derive 0.4.2", "num-traits", "rkyv 0.8.8", + "utralib 0.1.26", "xous 0.9.69 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", diff --git a/services/graphics-server/src/backend/betrusted.rs b/services/graphics-server/src/backend/betrusted.rs index 3b873ffcc..47250b03b 100644 --- a/services/graphics-server/src/backend/betrusted.rs +++ b/services/graphics-server/src/backend/betrusted.rs @@ -310,6 +310,11 @@ impl FrameBuffer for XousDisplay { fb[clip_y * LCD_WORDS_PER_LINE + (LCD_WORDS_PER_LINE - 1)] |= 0x1_0000; } + unsafe fn put_pixel_unchecked(&mut self, p: Point, color: ColorNative) { + // compatibility shim for other builds + self.put_pixel(p, color); + } + /// Retrieves a pixel value from the frame buffer; returns None if the point is out of bounds. /// /// Note: this has not be carefully tested as this API is not used by the legacy code base.