From 445ea9db44bbddee9aefb5bec777004de0710e47 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 00:34:24 +0800 Subject: [PATCH 1/6] expand iox api to allow for switching of interrupt levels this allows us to trigger on both rising and falling edges alternately --- libs/bao1x-api/src/iox.rs | 63 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/libs/bao1x-api/src/iox.rs b/libs/bao1x-api/src/iox.rs index 62c0217f0..ad952bf3f 100644 --- a/libs/bao1x-api/src/iox.rs +++ b/libs/bao1x-api/src/iox.rs @@ -1,3 +1,6 @@ +#[cfg(feature = "std")] +use std::ops::Not; + #[cfg(feature = "std")] use num_traits::ToPrimitive; @@ -64,6 +67,18 @@ impl From for IoxValue { fn from(value: u32) -> Self { if value == 0 { IoxValue::Low } else { IoxValue::High } } } +#[cfg(feature = "std")] +impl Not for IoxValue { + type Output = IoxValue; + + fn not(self) -> Self::Output { + match self { + IoxValue::Low => IoxValue::High, + IoxValue::High => IoxValue::Low, + } + } +} + /// Use a trait that will allow us to share code between both `std` and `no-std` implementations pub trait IoSetup { fn setup_pin( @@ -93,7 +108,21 @@ pub trait IoIrq { /// with `server` and the opcode number `usize` when an IRQ is detected on the port/pin. /// The active state of the IRQ is defined by `active`; the transition edge from inactive /// to active is when the event is generated. - fn set_irq_pin(&self, port: IoxPort, pin: u8, active: IoxValue, server: &str, opcode: usize); + /// + /// Returns Some(index) which is required for future API calls to modify IRQ pin parameters. + /// If `None` is returned, the IRQ is unavailable (due a resource conflict, or exhausting of + /// interrupt routing slots - there are only 8 available in the hardware). + fn set_irq_pin( + &self, + port: IoxPort, + pin: u8, + active: IoxValue, + server: &str, + opcode: usize, + ) -> Option; + + /// `index` is the returned value from `set_irq_pin()` + fn update_irq_pin(&self, server: &str, index: usize, active: Option, opcode: Option); } #[cfg_attr(feature = "derive-rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] @@ -118,6 +147,17 @@ pub struct IoxIrqRegistration { pub port: IoxPort, pub pin: u8, pub active: IoxValue, + pub index: Option, +} + +#[cfg_attr(feature = "derive-rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +#[derive(Debug)] +#[cfg(feature = "std")] +pub struct IoxIrqUpdate { + pub server: String, + pub opcode: Option, + pub active: Option, + pub index: usize, } #[cfg(feature = "std")] @@ -325,9 +365,24 @@ impl IoGpio for IoxHal { #[cfg(feature = "std")] impl IoIrq for IoxHal { - fn set_irq_pin(&self, port: IoxPort, pin: u8, active: IoxValue, server: &str, opcode: usize) { - let msg = IoxIrqRegistration { server: server.to_owned(), opcode, port, pin, active }; + fn set_irq_pin( + &self, + port: IoxPort, + pin: u8, + active: IoxValue, + server: &str, + opcode: usize, + ) -> Option { + let msg = IoxIrqRegistration { server: server.to_owned(), opcode, port, pin, active, index: None }; + let mut buf = xous_ipc::Buffer::into_buf(msg).unwrap(); + buf.lend_mut(self.conn, HalOpcode::ConfigureIoxIrq as u32).expect("Couldn't set up IRQ"); + let ret: IoxIrqRegistration = buf.to_original().unwrap(); + ret.index + } + + fn update_irq_pin(&self, server: &str, index: usize, active: Option, opcode: Option) { + let msg = IoxIrqUpdate { server: server.to_owned(), opcode, active, index }; let buf = xous_ipc::Buffer::into_buf(msg).unwrap(); - buf.lend(self.conn, HalOpcode::ConfigureIoxIrq as u32).expect("Couldn't set up IRQ"); + buf.lend(self.conn, HalOpcode::UpdateIoxIrq as u32).expect("Couldn't update IRQ"); } } From 245040cfb95326e71182f61e6592b49812d718e4 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 00:34:59 +0800 Subject: [PATCH 2/6] add opcode for irq config update --- libs/bao1x-api/src/api.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/libs/bao1x-api/src/api.rs b/libs/bao1x-api/src/api.rs index a305c58eb..693266a34 100644 --- a/libs/bao1x-api/src/api.rs +++ b/libs/bao1x-api/src/api.rs @@ -52,6 +52,7 @@ pub enum HalOpcode { /// Configure Iox IRQ ConfigureIoxIrq = 11, IrqLocalHandler = 12, + UpdateIoxIrq = 13, /// Manipulate the OS timer SetPreemptionState = 64, From 6b0972a551d4d16a1a4cf1d73d00cea42aad1302 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 00:35:34 +0800 Subject: [PATCH 3/6] add code to implement irq trigger edge updating also improve comments so I can remember how this actually works. --- services/bao1x-hal-service/src/main.rs | 65 ++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/services/bao1x-hal-service/src/main.rs b/services/bao1x-hal-service/src/main.rs index 2b8eefd47..9ce92a038 100644 --- a/services/bao1x-hal-service/src/main.rs +++ b/services/bao1x-hal-service/src/main.rs @@ -34,7 +34,7 @@ bitfield! { fn irq_select_from_port(port: IoxPort, pin: u8) -> u32 { (port as u32) * 16 + pin as u32 } fn find_first_none(arr: &[Option]) -> Option { arr.iter().position(|item| item.is_none()) } -#[derive(Debug, Copy, Clone)] +#[derive(Debug)] #[allow(dead_code)] struct IrqLocalRegistration { pub cid: xous::CID, @@ -42,6 +42,7 @@ struct IrqLocalRegistration { pub port: IoxPort, pub pin: u8, pub active: IoxValue, + pub server: String, } struct IrqHandler { @@ -274,9 +275,12 @@ fn main() { .expect("couldn't claim Iox interrupt"); irq.irq_csr.wo(utralib::utra::irqarray10::EV_PENDING, 0xFFFF_FFFF); irq.irq_csr.wfo(utralib::utra::irqarray10::EV_ENABLE_IOXIRQ, 1); - // Up to 8 slots where we can populate interrupt mappings in the hardware - // The index of the array corresponds to the slot. - let mut irq_table: [Option; 8] = [None; 8]; + // This is an [Option; 8] instead of a Vec because in hardware we have only + // 8 slots where we can populate interrupt mappings in the hardware. Each slot's + // index maps 1:1 to a hardware register offset. Thus as interrupts are de-allocated, + // we don't want the indices to change - in this case, Vec is not the right object, + // we want a static array defined like this. + let mut irq_table: [Option; 8] = [const { None }; 8]; let mut msg_opt = None; log::debug!("Starting main loop"); @@ -399,12 +403,12 @@ fn main() { } } HalOpcode::ConfigureIoxIrq => { - let buf = unsafe { + let mut buf = unsafe { xous_ipc::Buffer::from_memory_message( - msg_opt.as_mut().unwrap().body.memory_message().unwrap(), + msg_opt.as_mut().unwrap().body.memory_message_mut().unwrap(), ) }; - let registration = buf.to_original::().unwrap(); + let mut registration = buf.to_original::().unwrap(); log::info!("Got registration request: {:?}", registration); if let Some(index) = find_first_none(&irq_table) { // create the reverse-lookup registration @@ -417,6 +421,7 @@ fn main() { port: registration.port, pin: registration.pin, active: registration.active, + server: registration.server.to_owned(), }; irq_table[index] = Some(local_reg); @@ -429,6 +434,7 @@ fn main() { IoxValue::High => int_cr.set_mode(IntMode::RisingEdge as u32), } int_cr.set_enable(true); + int_cr.set_wakeup(true); // safety: the index and offset are mapped to the intended range because the index is // bounded by the size of irq_table, and the offset comes from the generated header // file. @@ -448,10 +454,53 @@ fn main() { .add(index) .write_volatile(int_cr.0); } + registration.index = Some(index); + + buf.replace(registration).unwrap(); } else { panic!("Ran out of Iox interrupt slots: maximum 8 available"); } } + HalOpcode::UpdateIoxIrq => { + let buf = unsafe { + xous_ipc::Buffer::from_memory_message( + msg_opt.as_ref().unwrap().body.memory_message().unwrap(), + ) + }; + let update = buf.to_original::().unwrap(); + log::debug!("Got IRQ update request: {:?}", update); + if let Some(Some(reg)) = irq_table.get_mut(update.index) { + if reg.server == update.server { + if let Some(active) = update.active { + reg.active = active; + // fetch the interrupt control register value + let mut int_cr = IntCr(unsafe { + iox.csr + .base() + .add(utralib::utra::iox::SFR_INTCR_CRINT0.offset()) + .add(update.index) + .read_volatile() + }); + // update the edge option + match active { + IoxValue::Low => int_cr.set_mode(IntMode::FallingEdge as u32), + IoxValue::High => int_cr.set_mode(IntMode::RisingEdge as u32), + } + // commit + unsafe { + iox.csr + .base() + .add(utralib::utra::iox::SFR_INTCR_CRINT0.offset()) + .add(update.index) + .write_volatile(int_cr.0); + } + } + if let Some(opcode) = update.opcode { + reg.opcode = opcode; + } + } + } + } HalOpcode::IrqLocalHandler => { if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message() { // Figure out which port(s) caused the IRQ @@ -462,7 +511,7 @@ fn main() { for bitpos in 0..8 { // the bit position is flipped versus register order in memory if ((irq_flag << (bitpos as u32)) & 0x80) != 0 { - if let Some(local_reg) = irq_table[bitpos] { + if let Some(local_reg) = &irq_table[bitpos] { found = true; // interrupts are "Best effort" and can gracefully fail if the receiver // has been overwhelmed by too many From 1ce29e80fa45e788f39ce510a812cd9aebc14bb2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 00:36:39 +0800 Subject: [PATCH 4/6] add ability to flip rendering of sh1107 screen this allows a device to be flipped upside-down and have the screen track orientation --- libs/bao1x-hal/src/sh1107.rs | 16 ++++++++++++++++ libs/ux-api/src/service/api.rs | 2 ++ libs/ux-api/src/service/gfx.rs | 15 +++++++++++++++ services/bao-video/src/main.rs | 8 ++++++++ 4 files changed, 41 insertions(+) diff --git a/libs/bao1x-hal/src/sh1107.rs b/libs/bao1x-hal/src/sh1107.rs index 46d20a3bb..d940ef124 100644 --- a/libs/bao1x-hal/src/sh1107.rs +++ b/libs/bao1x-hal/src/sh1107.rs @@ -514,6 +514,22 @@ impl<'a> Oled128x128<'a> { Ok(()) } + pub fn flip_vertical(&mut self, flip: bool) -> Result<(), xous::Error> { + use Command::*; + let cmds = if flip { + // flipped + [SetSegmentReMap(true), SetCOMScanDirection(Direction::Normal)] + } else { + // normal + [SetSegmentReMap(false), SetCOMScanDirection(Direction::Inverted)] + }; + for c in cmds { + let bytes = c.encode(); + self.send_command(bytes)?; + } + Ok(()) + } + pub fn powerdown(&mut self) { self.powerdown = true; // assert reset diff --git a/libs/ux-api/src/service/api.rs b/libs/ux-api/src/service/api.rs index 05eb265f6..236439f5f 100644 --- a/libs/ux-api/src/service/api.rs +++ b/libs/ux-api/src/service/api.rs @@ -112,6 +112,8 @@ pub enum GfxOpcode { BaosecBitmap, #[cfg(feature = "board-baosec")] Brightness, + #[cfg(feature = "board-baosec")] + FlipScreen, /// Gutter for invalid calls InvalidCall, diff --git a/libs/ux-api/src/service/gfx.rs b/libs/ux-api/src/service/gfx.rs index 112905735..07f1b730c 100644 --- a/libs/ux-api/src/service/gfx.rs +++ b/libs/ux-api/src/service/gfx.rs @@ -801,6 +801,21 @@ impl Gfx { .map(|_| ()) } + #[cfg(feature = "board-baosec")] + pub fn flip_screen(&self, flip: bool) -> Result<(), xous::Error> { + send_message( + self.conn, + Message::new_blocking_scalar( + GfxOpcode::FlipScreen.to_usize().unwrap(), + if flip { 1 } else { 0 }, + 0, + 0, + 0, + ), + ) + .map(|_| ()) + } + #[cfg(feature = "hosted-baosec")] pub fn acquire_qr(&self) -> Result { let dummy = "otpauth://totp/ACME%20Co:john.doe@email.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30".to_string(); diff --git a/services/bao-video/src/main.rs b/services/bao-video/src/main.rs index 96632db9e..fbd9b795a 100644 --- a/services/bao-video/src/main.rs +++ b/services/bao-video/src/main.rs @@ -902,6 +902,14 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! { .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)); } } + #[cfg(feature = "board-baosec")] + GfxOpcode::FlipScreen => { + if let Some(scalar) = msg.body.scalar_message_mut() { + display + .flip_vertical(scalar.arg1 != 0) + .unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display)) + } + } GfxOpcode::Quit => break, _ => { // This is perfectly normal because not all opcodes are handled by all platforms. From 70543731d1ccd0293e6880e829f33d5ad20db224 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 00:37:15 +0800 Subject: [PATCH 5/6] add keyboard remapping that also tracks screen flipping --- libs/bao1x-api/src/keyboard.rs | 18 ++++ .../bao1x-hal-service/src/servers/keyboard.rs | 86 ++++++++++++++----- 2 files changed, 81 insertions(+), 23 deletions(-) diff --git a/libs/bao1x-api/src/keyboard.rs b/libs/bao1x-api/src/keyboard.rs index b83b69495..bfaeacf35 100644 --- a/libs/bao1x-api/src/keyboard.rs +++ b/libs/bao1x-api/src/keyboard.rs @@ -91,6 +91,10 @@ pub enum KeyboardOpcode { /// a blocking key listener - blocks until a key is hit BlockingKeyListener = 9, + + /// change orientation, and thus key mapping of directional keys. Behavior + /// depends on the hardware type selected. + SetOrientation = 128, } // this structure is used to register a keyboard listener. @@ -201,6 +205,20 @@ impl Keyboard { .unwrap(); } + pub fn flip_orientation(&self, flipped: bool) { + send_message( + self.conn, + Message::new_scalar( + KeyboardOpcode::SetOrientation.to_usize().unwrap(), + if flipped { 1 } else { 0 }, + 0, + 0, + 0, + ), + ) + .unwrap(); + } + /// Reveal the connection ID for use with unsafe FFI calls pub fn conn(&self) -> xous::CID { self.conn } } diff --git a/services/bao1x-hal-service/src/servers/keyboard.rs b/services/bao1x-hal-service/src/servers/keyboard.rs index 7d1a2158b..03b963c23 100644 --- a/services/bao1x-hal-service/src/servers/keyboard.rs +++ b/services/bao1x-hal-service/src/servers/keyboard.rs @@ -62,10 +62,18 @@ struct KeyTracker { pub rate_ms: usize, pub delay_ms: usize, pub keys: Vec, + pub orientation_flipped: bool, } #[cfg(feature = "board-baosec")] impl KeyTracker { - pub fn new() -> Self { KeyTracker { rate_ms: KEYUP_DELAY_MS as usize, delay_ms: 1000, keys: Vec::new() } } + pub fn new() -> Self { + KeyTracker { + rate_ms: KEYUP_DELAY_MS as usize, + delay_ms: 1000, + keys: Vec::new(), + orientation_flipped: false, + } + } pub fn register_key_down(&mut self, key: KeyPress, ts: u64) { if let Some(entry) = self.keys.iter_mut().find(|e| e.kp == key) { @@ -113,11 +121,13 @@ impl KeyTracker { /// Returns any keys that should have repeat key-press events generated pub fn get_repeats(&mut self, now: u64) -> Vec { let mut kps = Vec::new(); - for key in self.keys.iter_mut() { - if now >= key.next_repeat_time { - kps.push(map_keypress(key.kp)); + // use index-based iteration to avoid borrow checker issue on map_keypress() call + for i in 0..self.keys.len() { + if now >= self.keys[i].next_repeat_time { + let kp = self.keys[i].kp; + kps.push(self.map_keypress(kp)); // rebasing off of now prevents keys from "lagging on" in case of UI delay - key.next_repeat_time = now + self.rate_ms as u64; + self.keys[i].next_repeat_time = now + self.rate_ms as u64; } } kps @@ -126,23 +136,47 @@ impl KeyTracker { pub fn keys_pressed(&self) -> usize { self.keys.len() } pub fn clear_keys(&mut self) { self.keys.clear(); } -} -#[cfg(feature = "board-baosec")] -fn map_keypress(kp: KeyPress) -> char { - match kp { - KeyPress::Down => '↓', - KeyPress::Up => '↑', - KeyPress::Left => '←', - KeyPress::Right => '→', - KeyPress::Select => '∴', - // "Fire" is used as the mapping for the center instead of carriage return ('\r' (0xd)) - // because carriage return is reserved for the shell to indicate the end of line. Thus - // by mapping "fire" to the center key, we get a UI-specific action key without invoking - // shell commands in the background unintentionally. - KeyPress::Center => '🔥', - #[cfg(feature = "accel-kbd")] - KeyPress::Accel => '⏯', - _ => '\u{0000}', + + pub fn map_keypress(&self, kp: KeyPress) -> char { + match kp { + KeyPress::Down => { + if self.orientation_flipped { + '↑' + } else { + '↓' + } + } + KeyPress::Up => { + if self.orientation_flipped { + '↓' + } else { + '↑' + } + } + KeyPress::Left => { + if self.orientation_flipped { + '→' + } else { + '←' + } + } + KeyPress::Right => { + if self.orientation_flipped { + '←' + } else { + '→' + } + } + KeyPress::Select => '∴', + // "Fire" is used as the mapping for the center instead of carriage return ('\r' (0xd)) + // because carriage return is reserved for the shell to indicate the end of line. Thus + // by mapping "fire" to the center key, we get a UI-specific action key without invoking + // shell commands in the background unintentionally. + KeyPress::Center => '🔥', + #[cfg(feature = "accel-kbd")] + KeyPress::Accel => '⏯', + _ => '\u{0000}', + } } } @@ -475,7 +509,7 @@ fn keyboard_service() { log::debug!("{:?}", key_down); if key_down != KeyPress::Invalid && key_down != KeyPress::None { key_tracker.register_key_down(key_down, now); - kc.push(map_keypress(key_down)) + kc.push(key_tracker.map_keypress(key_down)) } } // the keys_pressed() check is necessary because the interrupt will fire *before* a key @@ -542,6 +576,12 @@ fn keyboard_service() { log::warn!("Unhandled interrupt: {:x}", pending); } }), + Some(KeyboardOpcode::SetOrientation) => msg_scalar_unpack!(msg, _flipped, _, _, _, { + #[cfg(feature = "board-baosec")] + { + key_tracker.orientation_flipped = _flipped != 0; + } + }), None => { log::error!("couldn't convert KeyboardOpcode"); break; From 4637fc703732e562a0b8e104abeca2d7b5485a65 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 00:56:57 +0800 Subject: [PATCH 6/6] fix hosted mode --- services/bao1x-emu/src/keyboard.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/bao1x-emu/src/keyboard.rs b/services/bao1x-emu/src/keyboard.rs index 8272a2045..ca95f122d 100644 --- a/services/bao1x-emu/src/keyboard.rs +++ b/services/bao1x-emu/src/keyboard.rs @@ -190,6 +190,9 @@ fn keyboard_service() { Some(KeyboardOpcode::HandlerTrigger) => { todo!("Write this once we have an IRQ handler for keyboard interrupts"); } + Some(KeyboardOpcode::SetOrientation) => { + // nop - doesn't do anything on emulation + } None => { log::error!("couldn't convert KeyboardOpcode"); break;