diff --git a/services/cram-hal-service/Cargo.toml b/services/cram-hal-service/Cargo.toml index 7c149d73e..2ff1207ee 100644 --- a/services/cram-hal-service/Cargo.toml +++ b/services/cram-hal-service/Cargo.toml @@ -19,6 +19,10 @@ cramium-hal = { path = "../../libs/cramium-hal", features = [ "derive-rkyv", "std", ] } +cramium-api = { path = "../../libs/cramium-api", features = [ + "derive-rkyv", + "std", +] } xous-pl230 = { path = "../../libs/xous-pl230", features = ["cramium-soc"] } # xous-pio = { path = "../../libs/xous-pio", default-features = false, features = [ # "cramium-soc", diff --git a/services/cram-hal-service/src/api.rs b/services/cram-hal-service/src/api.rs index 11a4f543a..c6a1fd3a9 100644 --- a/services/cram-hal-service/src/api.rs +++ b/services/cram-hal-service/src/api.rs @@ -1,7 +1,3 @@ -pub mod keyboard; -use cramium_hal::iox::{self, IoxPort, IoxValue}; -pub use keyboard::*; - /// The Opcode numbers here should not be changed. You can add new ones, /// but do not re-use old numbers or repurpose them. This is because the /// numbers are hard-coded in other libraries in order to break circular @@ -103,58 +99,3 @@ pub enum MemoryLcdOpcode { /// Sets a callback address as SID + opcode for pingbacks when the blit is done. SetCallbackServer = 3, } - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct IoxConfigMessage { - pub port: iox::IoxPort, - pub pin: u8, - pub direction: Option, - pub function: Option, - pub schmitt_trigger: Option, - pub pullup: Option, - pub slow_slew: Option, - pub strength: Option, -} - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, PartialEq, Eq)] -pub enum I2cTransactionType { - Write, - Read, - ReadRepeatedStart, -} - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub enum I2cResult { - /// For the outbound message holder - Pending, - /// Returns # of bytes read or written if successful - Ack(usize), - /// An error occurred. - Nack, -} - -#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct I2cTransaction { - pub i2c_type: I2cTransactionType, - pub device: u8, - pub address: u8, - pub data: Vec, - pub result: I2cResult, -} - -#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct I2cTransactions { - pub transactions: Vec, -} -impl From> for I2cTransactions { - fn from(value: Vec) -> Self { Self { transactions: value } } -} - -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct IoxIrqRegistration { - pub server: String, - pub opcode: usize, - pub port: IoxPort, - pub pin: u8, - pub active: IoxValue, -} diff --git a/services/cram-hal-service/src/api/keyboard.rs b/services/cram-hal-service/src/api/keyboard.rs deleted file mode 100644 index 9c08e99cc..000000000 --- a/services/cram-hal-service/src/api/keyboard.rs +++ /dev/null @@ -1,115 +0,0 @@ -use std::fmt::Display; - -pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; - -#[derive(Debug, Default, Copy, Clone)] -#[allow(dead_code)] -pub struct ScanCode { - /// base key value - pub key: Option, - /// tap blue shift key, then key - pub shift: Option, - /// hold blue shift key, then key - pub hold: Option, - /// hold orange shift key, then key - pub alt: Option, -} - -/// Maintainer note: there is a "BackupKeyboardLayout" serializer inside -/// root-keys/api.rs that needs to be updated when this changes. -#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub enum KeyMap { - Qwerty, - Azerty, - Qwertz, - Dvorak, - Braille, - Undefined, -} -impl From for KeyMap { - fn from(code: usize) -> Self { - match code { - 0 => KeyMap::Qwerty, - 1 => KeyMap::Azerty, - 2 => KeyMap::Qwertz, - 3 => KeyMap::Dvorak, - 4 => KeyMap::Braille, - _ => KeyMap::Qwerty, - } - } -} -impl From for usize { - fn from(map: KeyMap) -> usize { - match map { - // note: these indicese correspond to the position on the keyboard menu - KeyMap::Qwerty => 0, - KeyMap::Azerty => 1, - KeyMap::Qwertz => 2, - KeyMap::Dvorak => 3, - KeyMap::Braille => 4, - KeyMap::Undefined => 255, - } - } -} - -impl Display for KeyMap { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - Self::Azerty => write!(f, "AZERTY"), - Self::Qwerty => write!(f, "QWERTY"), - Self::Qwertz => write!(f, "QWERTZ"), - Self::Dvorak => write!(f, "Dvorak"), - Self::Braille => write!(f, "Braille"), - Self::Undefined => write!(f, "Undefined"), - } - } -} - -// Opcodes are pinned down to allow for unsafe FFI extraction of key hits -#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] -pub(crate) enum KeyboardOpcode { - /// set which keyboard mapping is present - SelectKeyMap = 0, //(KeyMap), - GetKeyMap = 1, - - /// request for ScanCodes - RegisterListener = 2, - - /// request for updates for *when* keyboard is pressed - RegisterKeyObserver = 12, - - /// set repeat delay, rate; both in ms - SetRepeat = 4, //(u32, u32), - - /// set chording interval (how long to wait for all keydowns to happen before interpreting as a chord), - /// in ms (for braille keyboards) - SetChordInterval = 5, //(u32), - - /// used by host mode emulation and debug UART to inject keys - InjectKey = 6, //(char), - - /// used by the interrupt handler to transfer results to the main loop - HandlerTrigger = 7, - - /// a blocking key listener - blocks until a key is hit - BlockingKeyListener = 9, -} - -// this structure is used to register a keyboard listener. Currently, we only accept -// one trusted listener (enforced by name server and structurally in the code), -// which is the GAM. -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Clone)] -pub(crate) struct KeyboardRegistration { - pub server_name: String, - pub listener_op_id: usize, -} - -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)] -pub struct RowCol { - pub r: u8, - pub c: u8, -} -impl RowCol { - #[allow(dead_code)] - pub fn new(r: u8, c: u8) -> RowCol { RowCol { r, c } } -} diff --git a/services/cram-hal-service/src/hw/keyboard.rs b/services/cram-hal-service/src/hw/keyboard.rs index 84083283a..901e7a52e 100644 --- a/services/cram-hal-service/src/hw/keyboard.rs +++ b/services/cram-hal-service/src/hw/keyboard.rs @@ -1,10 +1,8 @@ +use cramium_api::keyboard::*; use num_traits::*; use xous::{CID, MessageSender, msg_blocking_scalar_unpack, msg_scalar_unpack}; use xous_ipc::Buffer; -use crate::api; -pub use crate::api::keyboard::*; - pub fn start_keyboard_service() { std::thread::spawn(move || { keyboard_service(); @@ -20,7 +18,7 @@ fn keyboard_bouncer() { let sid = xous::create_server_with_address(b"keyboard_bouncer") .expect("couldn't create keyboard log bounce server"); let xns = xous_names::XousNames::new().unwrap(); - let kbd = cram_hal_service::keyboard::Keyboard::new(&xns).unwrap(); + let kbd = cramium_api::keyboard::Keyboard::new(&xns).unwrap(); let mut msg_opt = None; loop { xous::reply_and_receive_next(sid, &mut msg_opt).unwrap(); @@ -39,7 +37,7 @@ fn keyboard_bouncer() { fn keyboard_service() { let xns = xous_names::XousNames::new().unwrap(); - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, None).expect("can't register server"); + let kbd_sid = xns.register_name(cramium_api::SERVER_NAME_KBD, None).expect("can't register server"); let mut listener_conn: Option = None; let mut listener_op: Option = None; diff --git a/services/cram-hal-service/src/i2c_lib.rs b/services/cram-hal-service/src/i2c_lib.rs index dd20cade6..f33d0297f 100644 --- a/services/cram-hal-service/src/i2c_lib.rs +++ b/services/cram-hal-service/src/i2c_lib.rs @@ -1,9 +1,9 @@ use core::sync::atomic::{AtomicU32, Ordering}; -use cramium_hal::udma::I2cApi; +use cramium_api::*; use xous_ipc::Buffer; -use crate::api::{I2cResult, I2cTransaction, I2cTransactionType, I2cTransactions, Opcode}; +use crate::api::Opcode; pub struct I2c { conn: xous::CID, diff --git a/services/cram-hal-service/src/iox_lib.rs b/services/cram-hal-service/src/iox_lib.rs deleted file mode 100644 index 48389e289..000000000 --- a/services/cram-hal-service/src/iox_lib.rs +++ /dev/null @@ -1,189 +0,0 @@ -use core::sync::atomic::Ordering; - -use cramium_hal::iox::{ - IoGpio, IoIrq, IoSetup, IoxDir, IoxDriveStrength, IoxEnable, IoxFunction, IoxPort, IoxValue, -}; -use num_traits::*; - -use crate::{ - Opcode, SERVER_NAME_CRAM_HAL, - api::{IoxConfigMessage, IoxIrqRegistration}, -}; - -pub struct IoxHal { - conn: xous::CID, -} - -impl IoxHal { - pub fn new() -> Self { - crate::REFCOUNT.fetch_add(1, Ordering::Relaxed); - let xns = xous_names::XousNames::new().unwrap(); - let conn = - xns.request_connection(SERVER_NAME_CRAM_HAL).expect("Couldn't connect to Cramium HAL server"); - IoxHal { conn } - } - - pub fn set_gpio_pin_value(&self, port: IoxPort, pin: u8, value: IoxValue) { - xous::send_message( - self.conn, - xous::Message::new_blocking_scalar( - Opcode::SetGpioBank.to_usize().unwrap(), - port as usize, - // values to set - (value as usize) << (pin as usize), - // which pin, as a bitmask - 1 << pin as usize, - 0, - ), - ) - .expect("Couldn't set GPIO pin value"); - } - - pub fn set_gpio_bank_value(&self, port: IoxPort, value: u16, bitmask: u16) { - xous::send_message( - self.conn, - xous::Message::new_blocking_scalar( - Opcode::SetGpioBank.to_usize().unwrap(), - port as usize, - // values to set - value as usize, - // mask of valid bits - bitmask as usize, - 0, - ), - ) - .expect("Couldn't set GPIO pin value"); - } - - pub fn get_gpio_pin_value(&self, port: IoxPort, pin: u8) -> IoxValue { - match xous::send_message( - self.conn, - xous::Message::new_blocking_scalar( - Opcode::GetGpioBank.to_usize().unwrap(), - port as usize, - 0, - 0, - 0, - ), - ) { - Ok(xous::Result::Scalar5(_, value, _, _, _)) => { - if value & (1 << pin as usize) != 0 { - IoxValue::High - } else { - IoxValue::Low - } - } - _ => panic!("Internal Error: Couldn't get GPIO pin value"), - } - } - - pub fn get_gpio_bank_value(&self, port: IoxPort) -> u32 { - match xous::send_message( - self.conn, - xous::Message::new_blocking_scalar( - Opcode::GetGpioBank.to_usize().unwrap(), - port as usize, - 0, - 0, - 0, - ), - ) { - Ok(xous::Result::Scalar5(_, value, _, _, _)) => value as u32, - _ => panic!("Internal Error: Couldn't get GPIO pin value"), - } - } - - /// This function takes a 32-bit bitmask, corresponding to PIO 31 through 0, where - /// a `1` indicates to map that PIO to a GPIO. - /// - /// This function will automatically remap the AF and PIO settings for the PIO pins - /// specified in the bitmask, corresponding to the PIO GPIO pin number. If a `0` is - /// present in a bit position, it will turn off the PIO mux, but not change the AF setting. - /// - /// VERY IMPORTANT: Note that the PIO GPIO number is *not* consistent with the - /// numbering order of the GPIO ports: in fact, it is reverse-order for PORT B and in-order with skips for - /// PORT C. Also, bits 22, 27, 30 and 31 are not mappable for the PIO. - /// - /// Returns: a 32-entry array which records which GPIO bank and pin number was affected - /// by the mapping request. The index of the array corresponds to the bit position in - /// the bitmask. You may use this to pass as arguments to further functions - /// that do things like control slew rate or apply pull-ups. - pub fn set_ports_from_pio_bitmask(&self, _enable_bitmask: u32) -> [Option<(IoxPort, u8)>; 32] { - todo!("Do this when we get around to filling in the PIO drivers") - } - - /// Returns the PIO bit that was enabled based on the port and pin specifier given; - /// returns `None` if the proposed mapping is invalid. - pub fn set_pio_bit_from_port_and_pin(&self, _port: IoxPort, _pin: u8) -> Option { - todo!("Do this when we get around to filling in the PIO drivers") - } - - /// Returns the PIO bit that was disabled based on the port and pin specifier given; - /// returns `None` if the proposed mapping is invalid. Does not change the AF mapping, - /// simply disables the bit in the PIO mux register. - pub fn unset_pio_bit_from_port_and_pin(&self, _port: IoxPort, _pin: u8) -> Option { - todo!("Do this when we get around to filling in the PIO drivers") - } -} - -impl IoSetup for IoxHal { - fn setup_pin( - &self, - port: IoxPort, - pin: u8, - direction: Option, - function: Option, - schmitt_trigger: Option, - pullup: Option, - slow_slew: Option, - strength: Option, - ) { - let msg = - IoxConfigMessage { port, pin, direction, function, schmitt_trigger, pullup, slow_slew, strength }; - let buf = xous_ipc::Buffer::into_buf(msg).unwrap(); - buf.lend(self.conn, Opcode::ConfigureIox.to_u32().unwrap()).expect("Couldn't set up IO"); - } -} - -impl IoGpio for IoxHal { - fn get_gpio_pin_value(&self, port: IoxPort, pin: u8) -> IoxValue { self.get_gpio_pin_value(port, pin) } - - fn set_gpio_pin_dir(&self, port: IoxPort, pin: u8, dir: IoxDir) { - let msg = IoxConfigMessage { - port, - pin, - direction: Some(dir), - function: None, - schmitt_trigger: None, - pullup: None, - slow_slew: None, - strength: None, - }; - let buf = xous_ipc::Buffer::into_buf(msg).unwrap(); - buf.lend(self.conn, Opcode::ConfigureIox.to_u32().unwrap()).expect("Couldn't set up IO"); - } - - fn set_gpio_pin_value(&self, port: IoxPort, pin: u8, value: IoxValue) { - self.set_gpio_pin_value(port, pin, value); - } -} - -impl Drop for IoxHal { - fn drop(&mut self) { - // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the - // connection. - if crate::REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { - unsafe { - xous::disconnect(self.conn).unwrap(); - } - } - } -} - -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 }; - let buf = xous_ipc::Buffer::into_buf(msg).unwrap(); - buf.lend(self.conn, Opcode::ConfigureIoxIrq.to_u32().unwrap()).expect("Couldn't set up IRQ"); - } -} diff --git a/services/cram-hal-service/src/keyboard.rs b/services/cram-hal-service/src/keyboard.rs deleted file mode 100644 index 593268a7e..000000000 --- a/services/cram-hal-service/src/keyboard.rs +++ /dev/null @@ -1,108 +0,0 @@ -use num_traits::*; -use xous::{Message, send_message}; -use xous_ipc::Buffer; - -use crate::api::keyboard::*; - -#[derive(Debug)] -pub struct Keyboard { - conn: xous::CID, -} -impl Keyboard { - pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.fetch_add(1, Ordering::Relaxed); - let conn = - xns.request_connection_blocking(crate::api::SERVER_NAME_KBD).expect("Can't connect to KBD"); - Ok(Keyboard { conn }) - } - - /// Listeners get passed the full content of the key press on each key hit. - pub fn register_listener(&self, server_name: &str, action_opcode: usize) { - let kr = - KeyboardRegistration { server_name: String::from(server_name), listener_op_id: action_opcode }; - let buf = Buffer::into_buf(kr).unwrap(); - buf.lend(self.conn, KeyboardOpcode::RegisterListener.to_u32().unwrap()) - .expect("couldn't register listener"); - } - - /// Observers get notified if a key is hit, but the actual keypress is always null. - /// This is useful for hardware services that need to do e.g. screen wakeup on key hit - /// but has no need to know the user's actually keystroke contents. - pub fn register_observer(&self, server_name: &str, action_opcode: usize) { - let kr = - KeyboardRegistration { server_name: String::from(server_name), listener_op_id: action_opcode }; - let buf = Buffer::into_buf(kr).unwrap(); - buf.lend(self.conn, KeyboardOpcode::RegisterKeyObserver.to_u32().unwrap()) - .expect("couldn't register listener"); - } - - pub fn set_vibe(&self, _enable: bool) -> Result<(), xous::Error> { - // no vibe on cramium target, ignore API call - Ok(()) - } - - pub fn set_keymap(&self, map: KeyMap) -> Result<(), xous::Error> { - send_message( - self.conn, - Message::new_scalar(KeyboardOpcode::SelectKeyMap.to_usize().unwrap(), map.into(), 0, 0, 0), - ) - .map(|_| ()) - } - - pub fn get_keymap(&self) -> Result { - match send_message( - self.conn, - Message::new_blocking_scalar(KeyboardOpcode::GetKeyMap.to_usize().unwrap(), 0, 0, 0, 0), - ) { - Ok(xous::Result::Scalar1(code)) => Ok(code.into()), - _ => Err(xous::Error::InternalError), - } - } - - /// Blocks until a key is hit. Does not block the keyboard server, just the caller. - /// Returns a `Vec::`, as the user can press more than one key at a time. - /// The specific order of a simultaneous key hit event is not defined. - pub fn get_keys_blocking(&self) -> Vec { - match send_message( - self.conn, - Message::new_blocking_scalar(KeyboardOpcode::BlockingKeyListener.to_usize().unwrap(), 0, 0, 0, 0), - ) { - Ok(xous::Result::Scalar2(k1, k2)) => { - let mut ret = Vec::::new(); - if let Some(c) = core::char::from_u32(k1 as u32) { - ret.push(c) - } - if let Some(c) = core::char::from_u32(k2 as u32) { - ret.push(c) - } - ret - } - Ok(_) | Err(_) => panic!("internal error: Incorrect return type"), - } - } - - pub fn inject_key(&self, c: char) { - send_message( - self.conn, - Message::new_scalar(KeyboardOpcode::InjectKey.to_usize().unwrap(), c as u32 as usize, 0, 0, 0), - ) - .unwrap(); - } - - /// Reveal the connection ID for use with unsafe FFI calls - pub fn conn(&self) -> xous::CID { self.conn } -} - -use core::sync::atomic::{AtomicU32, Ordering}; -static REFCOUNT: AtomicU32 = AtomicU32::new(0); -impl Drop for Keyboard { - fn drop(&mut self) { - // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using - // the connection. - if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { - unsafe { - xous::disconnect(self.conn).unwrap(); - } - } - } -} diff --git a/services/cram-hal-service/src/lib.rs b/services/cram-hal-service/src/lib.rs index 814d1f2a4..5ad152cba 100644 --- a/services/cram-hal-service/src/lib.rs +++ b/services/cram-hal-service/src/lib.rs @@ -1,21 +1,13 @@ pub mod api; pub mod i2c_lib; -pub mod iox_lib; -pub mod keyboard; pub mod trng; -use api::Opcode; -use cramium_hal::udma::{EventChannel, PeriphEventType, PeriphId, UdmaGlobalConfig}; -pub use i2c_lib::*; -pub use iox_lib::*; -use num_traits::*; - -/// Do not change this constant, it is hard-coded into libraries in order to break -/// circular dependencies on the IFRAM block. -pub const SERVER_NAME_CRAM_HAL: &str = "_Cramium-SoC HAL_"; -pub const PERCLK: u32 = 100_000_000; - use core::sync::atomic::{AtomicU32, Ordering}; + +use api::Opcode; +use cramium_api::*; +pub use i2c_lib::*; +use num_traits::*; static REFCOUNT: AtomicU32 = AtomicU32::new(0); pub struct UdmaGlobal { diff --git a/services/cram-hal-service/src/main.rs b/services/cram-hal-service/src/main.rs index f62a02365..35d8c0232 100644 --- a/services/cram-hal-service/src/main.rs +++ b/services/cram-hal-service/src/main.rs @@ -3,10 +3,8 @@ mod hw; use api::*; use bitfield::*; -use cramium_hal::{ - iox::{self, IoxPort, IoxValue}, - udma::{EventChannel, GlobalConfig, I2cApi, PeriphId}, -}; +use cramium_api::*; +use cramium_hal::{iox::Iox, udma::GlobalConfig}; use num_traits::*; use utralib::CSR; #[cfg(feature = "quantum-timer")] @@ -147,7 +145,7 @@ fn main() { log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let sid = xns.register_name(cram_hal_service::SERVER_NAME_CRAM_HAL, None).expect("can't register server"); + let sid = xns.register_name(cramium_api::SERVER_NAME_CRAM_HAL, None).expect("can't register server"); let self_cid = xous::connect(sid).expect("couldn't create self-connection"); let mut ifram_allocs = [Vec::new(), Vec::new()]; @@ -186,7 +184,7 @@ fn main() { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("couldn't claim the IOX hardware page"); - let iox = iox::Iox::new(iox_page.as_ptr() as *mut u32); + let iox = Iox::new(iox_page.as_ptr() as *mut u32); let udma_global_csr = xous::syscall::map_memory( xous::MemoryAddress::new(utralib::generated::HW_UDMA_CTRL_BASE), @@ -225,7 +223,7 @@ fn main() { cramium_hal::udma::I2c::new_with_ifram( i2c_channel, 400_000, - cram_hal_service::PERCLK, + cramium_api::PERCLK, i2c_ifram, &udma_global, ) @@ -501,8 +499,7 @@ fn main() { } Opcode::SetGpioBank => { if let Some(scalar) = msg.body.scalar_message() { - let port: cramium_hal::iox::IoxPort = - num_traits::FromPrimitive::from_usize(scalar.arg1).unwrap(); + let port: IoxPort = num_traits::FromPrimitive::from_usize(scalar.arg1).unwrap(); let value = scalar.arg2 as u16; let bitmask = scalar.arg3 as u16; iox.set_gpio_bank(port, value, bitmask); @@ -510,8 +507,7 @@ fn main() { } Opcode::GetGpioBank => { if let Some(scalar) = msg.body.scalar_message_mut() { - let port: cramium_hal::iox::IoxPort = - num_traits::FromPrimitive::from_usize(scalar.arg1).unwrap(); + let port: IoxPort = num_traits::FromPrimitive::from_usize(scalar.arg1).unwrap(); scalar.arg1 = iox.get_gpio_bank(port) as usize; } }