diff --git a/Cargo.lock b/Cargo.lock index 38f12938b..046b237c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,6 +626,8 @@ dependencies = [ "heapless", "log", "log-server", + "num-derive", + "num-traits", "rkyv 0.4.3", "ticktimer-server", "utralib", diff --git a/RELEASE-v0.8.md b/RELEASE-v0.8.md index 4f5eef43f..c0a00c0b7 100644 --- a/RELEASE-v0.8.md +++ b/RELEASE-v0.8.md @@ -179,7 +179,7 @@ impl MyServer { use core::fmt::Write; write!(rich_struct.name, "{}", words).expect("words too long"); // now convert it into a Xous::Buffer, which can then be lent to the server - let buf = Buffer::into_buf(rich_struct).or(Err(xous::Error:InternalError))?; + let buf = Buffer::into_buf(rich_struct).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::ExampleMemory.to_u32().unwrap()).map(|_| ()) } @@ -191,7 +191,7 @@ impl MyServer { stuff, }; // now convert it into a Xous::Buffer, which can then be mutably lent to the server - let mut buf = Buffer::into_buf(rich_struct).or(Err(xous::Error:InternalError))?; + let mut buf = Buffer::into_buf(rich_struct).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::ExampleMemoryWithReturn.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; // note that to_original() creates a local copy on the stack of the returned buffer @@ -212,7 +212,7 @@ impl MyServer { } /// an example of registering for a callback - static mut MYSERVER_CB: Option = None; + static mut MYSERVER_CB: Option = None; // this actually goes outside the object decl pub fn hook_callback(&mut self, cb: fn(u32)) -> Result<(), xous::Error> { if unsafe{MYSERVER_CB}.is_some() { return Err(xous::Error::MemoryInUse) // can't hook it twice @@ -232,7 +232,7 @@ impl MyServer { } } -/// handles callback messages from the COM server, in the library user's process space. +/// handles callback messages from server, in the library user's process space. fn callback_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32); loop { @@ -370,18 +370,18 @@ fn xmain() -> ! { /// 1. Define a crate-local API to pass the messages /// 2. Use Atomic data types (only applicable if you have primitive data to send) /// 3. Do some static mut unsafe thing because we don't have a Mutex data type yet. -fn do_callback(&mut cb_conns: [Option; 32]) { +fn do_callback(cb_conns: &mut [Option; 32]) { let a = useful_computation(); for maybe_conn in cb_conns.iter_mut() { // this code is notional and probably doesn't work if let Some(conn) = maybe_conn { - match xous::send_message(conn, - xous:Message::new_scalar(api::Callback::Hello.to_usize().unwrap(), a, 0, 0, 0) + match xous::send_message(*conn, + xous::Message::new_scalar(api::Callback::Hello.to_usize().unwrap(), a, 0, 0, 0) ) { Err(xous::Error::ServerNotFound) => { - maybe_conn = None // automatically de-allocate callbacks for clients that have dropped + *maybe_conn = None // automatically de-allocate callbacks for clients that have dropped }, - Ok => {} - _ => panic!("unhandled error in callback processing"); + Ok(xous::Result::Ok) => {} + _ => panic!("unhandled error or result in callback processing"); } } } diff --git a/services/graphics-server/src/lib.rs b/services/graphics-server/src/lib.rs index 89b34945a..4e77c8195 100644 --- a/services/graphics-server/src/lib.rs +++ b/services/graphics-server/src/lib.rs @@ -132,3 +132,10 @@ impl Gfx { buf.lend(self.conn, Opcode::DrawClipObject.to_u32().unwrap()).map(|_| ()) } } + +impl Drop for Gfx { + fn drop(&mut self) { + // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. + unsafe{xous::disconnect(self.conn).unwrap();} + } +} \ No newline at end of file diff --git a/services/keyboard/Cargo.toml b/services/keyboard/Cargo.toml index af81df05f..45891490b 100644 --- a/services/keyboard/Cargo.toml +++ b/services/keyboard/Cargo.toml @@ -6,7 +6,6 @@ name = "keyboard" version = "0.1.0" [dependencies] -heapless = "0.5.6" log = "0.4" log-server = {path = "../log-server"} ticktimer-server = {path = "../ticktimer-server"} @@ -14,10 +13,11 @@ xous = {path = "../../xous-rs"} xous-ipc = {path = "../../xous-ipc"} xous-names = {path = "../xous-names"} -[dependencies.rkyv] -default-features = false -features = ["const_generics"] -version = "0.4.1" +heapless = "0.5.6" + +num-derive = {version = "0.3", default-features = false} +num-traits = {version = "0.2", default-features = false} +rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} diff --git a/services/keyboard/src/api.rs b/services/keyboard/src/api.rs index d186d6997..a8f979e6a 100644 --- a/services/keyboard/src/api.rs +++ b/services/keyboard/src/api.rs @@ -1,11 +1,8 @@ -use core::ops::Deref; - -use heapless::consts::*; -use heapless::Vec; use xous::{Message, ScalarMessage}; use xous_ipc::String; -use core::slice; -use core::ops::DerefMut; +use num_traits::{ToPrimitive, FromPrimitive}; + +pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; #[derive(Debug, Default, Copy, Clone)] pub struct ScanCode { @@ -19,110 +16,102 @@ pub struct ScanCode { pub alt: Option, } -#[derive(Debug, Default, Copy, Clone)] +// maximum number of key events to track simultaneously. +pub const MAX_KEYS: usize = 16; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default, Copy, Clone, PartialEq, Eq)] pub struct RowCol { pub r: u8, pub c: u8, } -#[repr(packed)] +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct RowColVec { + storage: [Option; MAX_KEYS], + iter: usize, +} +impl RowColVec { + pub fn new() -> Self { + RowColVec { + storage: [None; MAX_KEYS], + iter: 0 + } + } + pub fn len(&self) -> usize { + return MAX_KEYS + } + pub fn get(&self, i: usize) -> Option { + if i < MAX_KEYS { + self.storage[i] + } else { + None + } + } + pub fn set(&mut self, i: usize, data: Option) { + if i < MAX_KEYS { + self.storage[i]= data; + } + } + // returns True if key is unique and added; False if already exists in storage + pub fn add_rc(&mut self, key: RowCol) -> Result { + // first, check if the rc is in the array + for &s in self.storage.iter() { + if let Some(rc) = s { + if rc == key { + return Ok(false) + } + } + } + // if we got here, rc was not in the arary + let mut added = false; + for s in self.storage.iter_mut() { + if *s == None { + *s = Some(key); + added = true; + break; + } + } + if added { + Ok(true) + } else { + Err(xous::Error::OutOfMemory) + } + } + // returns True if the key was removed; false if the key did not exist already + pub fn remove_rc(&mut self, key: RowCol) -> bool { + for s in self.storage.iter_mut() { + if let Some(rc) = s { + if *rc == key { + *s = None; + return true + } + } + } + return false + } + pub fn contains(&self, key: RowCol) -> bool { + for s in self.storage.iter() { + if let Some(rc) = s { + if *rc == key { + return true + } + } + } + false + } +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct KeyRawStates { - pub keydowns: Vec, - pub keyups: Vec, + pub keydowns: RowColVec, + pub keyups: RowColVec, } impl KeyRawStates { pub fn new() -> Self { KeyRawStates { - keydowns: Vec::new(), - keyups: Vec::new(), + keydowns: RowColVec::new(), + keyups: RowColVec::new(), } } - - #[allow(dead_code)] - pub fn copy(&self) -> KeyRawStates { - let mut krs = KeyRawStates::new(); - unsafe { // because KeyRawStates is *packed* - for kd in self.keydowns.iter() { - krs.keydowns.push(*kd).unwrap(); - } - for ku in self.keyups.iter() { - krs.keyups.push(*ku).unwrap(); - } - } - krs - } -} -impl Clone for KeyRawStates { - fn clone(&self) -> KeyRawStates { - self.copy() - } -} -impl Deref for KeyRawStates { - type Target = [u8]; - fn deref(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self as *const KeyRawStates as *const u8, core::mem::size_of::()) - as &[u8] - } - } -} -impl DerefMut for KeyRawStates { - fn deref_mut(&mut self) -> &mut[u8] { - unsafe { - slice::from_raw_parts_mut(self as *mut KeyRawStates as *mut u8, core::mem::size_of::()) - as &mut [u8] - } - } -} - -// warning: this rkyv code is totallly untested -use rkyv::SerializeUnsized; -use rkyv::ArchiveUnsized; -pub struct ArchivedKeyRawStates { - myvec_ptr: rkyv::RelPtr<[u8]>, -} - -#[allow(dead_code)] -impl ArchivedKeyRawStates { - pub fn as_slice(&self) -> &[u8] { - unsafe { &*self.myvec_ptr.as_ptr() } - } -} - -pub struct KeyRawStatesResolver { - bytes_pos: usize, - _metadata_resolver: rkyv::MetadataResolver<[u8]>, -} - -impl rkyv::Serialize for KeyRawStates { - fn serialize(&self, serializer: &mut S) -> Result { - Ok(KeyRawStatesResolver { - bytes_pos: self.deref().serialize_unsized(serializer)?, - _metadata_resolver: self.deref().serialize_metadata(serializer)?, - }) - } -} - -impl rkyv::Archive for KeyRawStates -{ - type Archived = ArchivedKeyRawStates; - type Resolver = KeyRawStatesResolver; - fn resolve(&self, pos: usize, resolver: Self::Resolver) -> Self::Archived { - Self::Archived { - myvec_ptr: unsafe { - self.deref().resolve_unsized( - pos + rkyv::offset_of!(Self::Archived, myvec_ptr), - resolver.bytes_pos, - (), - ) - }, - } - } -} - -impl AsRef<[u8]> for ArchivedKeyRawStates { - fn as_ref(&self) -> &[u8] { - unsafe { &*self.myvec_ptr.as_ptr() } - } } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] @@ -159,114 +148,34 @@ impl Into for KeyMap { } } -#[allow(dead_code)] -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub enum Opcode { +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum Opcode { /// set which keyboard mapping is present - SelectKeyMap(KeyMap), + SelectKeyMap, //(KeyMap), /// request interpreted ScanCodes to be sent - RegisterListener(String::<64>), + RegisterListener, //(String::<64>), /// request raw keyup/keydown events to be sent - RegisterRawListener(String::<64>), + RegisterRawListener, //(String::<64>), /// set repeat delay, rate; both in ms - SetRepeat(u32, u32), + SetRepeat, //(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(u32), - - /// keyboard events (as sent to listeners) - KeyboardEvent([char; 4]), + SetChordInterval, //(u32), /// used by host mode emulation to inject keys - HostModeInjectKey(char), + HostModeInjectKey, //(char), + + /// used by the interrupt handler to transfer results to the main loop + HandlerRawStates, // KeyRawState } -impl core::convert::TryFrom<&Message> for Opcode { - type Error = &'static str; - fn try_from(message: &Message) -> Result { - match message { - Message::Scalar(m) => match m.id { - 0 => Ok(Opcode::SelectKeyMap(KeyMap::from(m.arg1))), - 1 => Ok(Opcode::SetRepeat(m.arg1 as u32, m.arg2 as u32)), - 2 => Ok(Opcode::SetChordInterval(m.arg1 as u32)), - xous::names::GID_KEYBOARD_KEYSTATE_EVENT => Ok(Opcode::KeyboardEvent([ - if let Some(a) = core::char::from_u32(m.arg1 as u32) { - a - } else { - '\u{0000}' - }, - if let Some(a) = core::char::from_u32(m.arg2 as u32) { - a - } else { - '\u{0000}' - }, - if let Some(a) = core::char::from_u32(m.arg3 as u32) { - a - } else { - '\u{0000}' - }, - if let Some(a) = core::char::from_u32(m.arg4 as u32) { - a - } else { - '\u{0000}' - }, - ])), - 3 => Ok(Opcode::HostModeInjectKey( - if let Some(a) = core::char::from_u32(m.arg1 as u32) { - a - } else { - '\u{0000}' - }, - )), - _ => Err("KBD api: unknown Scalar ID"), - }, - _ => Err("KBD api: unhandled message type"), - } - } +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum Callback { + KeyEvent, + KeyRawEvent, + Drop, } -impl Into for Opcode { - fn into(self) -> Message { - match self { - Opcode::SelectKeyMap(map) => Message::Scalar(ScalarMessage { - id: 0, - arg1: map.into(), - arg2: 0, - arg3: 0, - arg4: 0, - }), - Opcode::SetRepeat(delay, rate) => Message::Scalar(ScalarMessage { - id: 1, - arg1: delay as usize, - arg2: rate as usize, - arg3: 0, - arg4: 0, - }), - Opcode::SetChordInterval(period) => Message::Scalar(ScalarMessage { - id: 2, - arg1: period as usize, - arg2: 0, - arg3: 0, - arg4: 0, - }), - Opcode::KeyboardEvent(keys) => Message::Scalar(ScalarMessage { - id: xous::names::GID_KEYBOARD_KEYSTATE_EVENT, - arg1: keys[0] as u32 as usize, - arg2: keys[1] as u32 as usize, - arg3: keys[2] as u32 as usize, - arg4: keys[3] as u32 as usize, - }), - Opcode::HostModeInjectKey(key) => Message::Scalar(ScalarMessage { - id: 3, - arg1: key as u32 as usize, - arg2: 0, - arg3: 0, - arg4: 0, - }), - _ => panic!("KBD api: Opcode type not handled by Into(), refer to helper method"), - } - } -} diff --git a/services/keyboard/src/lib.rs b/services/keyboard/src/lib.rs index 9864d4e44..b52ef6244 100644 --- a/services/keyboard/src/lib.rs +++ b/services/keyboard/src/lib.rs @@ -1,33 +1,167 @@ #![cfg_attr(target_os = "none", no_std)] -use core::convert::TryInto; use xous_ipc::String; +use num_traits::{ToPrimitive, FromPrimitive}; pub mod api; -pub fn request_events(name: &str, kbd_conn: xous::CID) -> Result { - let s = String::<64>::from_str(name); - let request = api::Opcode::RegisterListener(s); - let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); - let pos = { - use rkyv::ser::Serializer; - writer.serialize_value(&request).expect("couldn't archive RegisterListener request") - }; - let xous_buffer = writer.into_inner(); +use api::{Opcode, Callback, KeyRawStates}; +use xous::{send_message, Message, msg_scalar_unpack}; +use xous_ipc::Buffer; - xous_buffer.lend(kbd_conn, pos.try_into().unwrap()) +static mut KBD_EVENT_CB: Option = None; +static mut KBD_RAW_CB: Option = None; + +pub struct Keyboard { + conn: xous::CID, + event_cb_sid: Option, + raw_cb_sid: Option, +} +impl Keyboard { + pub fn new(xns: xous_names::XousNames) -> Result { + let conn = xns.request_connection_blocking(api::SERVER_NAME_KBD).expect("Can't connect to KBD"); + Ok(Keyboard { + conn, + event_cb_sid: None, + raw_cb_sid: None, + }) + } + + pub fn hook_keyboard_events(&mut self, cb: fn([char; 4])) -> Result<(), xous::Error> { + if unsafe{KBD_EVENT_CB}.is_some() { + return Err(xous::Error::MemoryInUse) // can't hook it twice + } + unsafe{KBD_EVENT_CB = Some(cb)}; + if self.event_cb_sid.is_none() { + let sid = xous::create_server().unwrap(); + self.event_cb_sid = Some(sid); + let sid_tuple = sid.to_u32(); + xous::create_thread_4(event_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); + send_message(self.conn, + Message::new_scalar(Opcode::RegisterListener.to_usize().unwrap(), + sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize + )).unwrap(); + } + Ok(()) + } + + pub fn hook_raw_events(&mut self, cb: fn(KeyRawStates)) -> Result<(), xous::Error> { + if unsafe{KBD_RAW_CB}.is_some() { + return Err(xous::Error::MemoryInUse) // can't hook it twice + } + unsafe{KBD_RAW_CB = Some(cb)}; + if self.raw_cb_sid.is_none() { + let sid = xous::create_server().unwrap(); + self.raw_cb_sid = Some(sid); + let sid_tuple = sid.to_u32(); + xous::create_thread_4(raw_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); + send_message(self.conn, + Message::new_scalar(Opcode::RegisterRawListener.to_usize().unwrap(), + sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize + )).unwrap(); + } + Ok(()) + } } -pub fn request_raw_events(name: &str, kbd_conn: xous::CID) -> Result { - let s = String::<64>::from_str(name); - let request = api::Opcode::RegisterRawListener(s); - let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); - let pos = { - use rkyv::ser::Serializer; - writer.serialize_value(&request).expect("couldn't archive RegisterRawListener request") - }; - let xous_buffer = writer.into_inner(); +impl Drop for Keyboard { + fn drop(&mut self) { + // if we have callbacks, destroy the callback server + if let Some(sid) = self.event_cb_sid.take() { + // no need to tell the upstream server we're quitting: the next time a callback processes, + // it will automatically remove my entry as it will receive a ServerNotFound error. - xous_buffer.lend(kbd_conn, pos.try_into().unwrap()) + // tell my handler thread to quit + let cid = xous::connect(sid).unwrap(); + send_message(cid, + Message::new_blocking_scalar(api::Callback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); + unsafe{xous::disconnect(cid).unwrap();} + xous::destroy_server(sid).unwrap(); + } + if let Some(sid) = self.raw_cb_sid.take() { + // no need to tell the upstream server we're quitting: the next time a callback processes, + // it will automatically remove my entry as it will receive a ServerNotFound error. + + // tell my handler thread to quit + let cid = xous::connect(sid).unwrap(); + send_message(cid, + Message::new_blocking_scalar(api::Callback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); + unsafe{xous::disconnect(cid).unwrap();} + xous::destroy_server(sid).unwrap(); + } + + // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. + unsafe{xous::disconnect(self.conn).unwrap();} + } } + + +/// handles callback messages from the keyboard server, in the library user's process space. +fn event_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { + let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32); + loop { + let msg = xous::receive_message(sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Callback::KeyEvent) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { + let keys = [ + if let Some(a) = core::char::from_u32(k1 as u32) { + a + } else { + '\u{0000}' + }, + if let Some(a) = core::char::from_u32(k2 as u32) { + a + } else { + '\u{0000}' + }, + if let Some(a) = core::char::from_u32(k3 as u32) { + a + } else { + '\u{0000}' + }, + if let Some(a) = core::char::from_u32(k4 as u32) { + a + } else { + '\u{0000}' + }, + ]; + unsafe { + if let Some(cb) = KBD_EVENT_CB { + cb(keys) + } + } + }), + Some(Callback::Drop) => { + break; // this exits the loop and kills the thread + }, + Some(Callback::KeyRawEvent) => panic!("wrong callback type issued: want KeyEvent, got KeyRawEvent!"), + None => (), + } + } +} + + +/// handles callback messages from the keyboard server, in the library user's process space. +fn raw_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { + let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32); + loop { + let msg = xous::receive_message(sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Callback::KeyEvent) => panic!("wrong callback type issued: want KeyRawEvent, got KeyEvent!"), + Some(Callback::Drop) => { + break; // this exits the loop and kills the thread + }, + Some(Callback::KeyRawEvent) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let krs = buffer.to_original::().unwrap(); + unsafe { + if let Some(cb) = KBD_RAW_CB { + cb(krs) + } + } + }, + None => (), + } + } +} \ No newline at end of file diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 7554ce42a..eb2f92470 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -10,13 +10,12 @@ use heapless::consts::*; #[cfg(not(target_os = "none"))] use heapless::spsc::Queue; -use core::convert::TryFrom; - use log::{error, info}; -use core::pin::Pin; -use xous::buffer; -use rkyv::archived_value; +use num_traits::{FromPrimitive, ToPrimitive}; +use xous_ipc::Buffer; +use api::{Opcode, KeyRawStates}; +use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack}; /// Compute the dvorak key mapping of row/col to key tuples #[allow(dead_code)] @@ -168,27 +167,29 @@ fn map_qwerty(code: RowCol) -> ScanCode { #[cfg(target_os = "none")] mod implementation { - use heapless::Vec; - use heapless::consts::*; use utralib::generated::*; use crate::api::*; use crate::{map_dvorak, map_qwerty}; use log::{error, info}; + use ticktimer_server::Ticktimer; + use xous::CID; + use xous_ipc::Buffer; + use num_traits::{FromPrimitive, ToPrimitive}; + + use heapless::Vec; + use heapless::consts::*; /// note: the code is structured to use at most 16 rows or 16 cols const KBD_ROWS: usize = 9; const KBD_COLS: usize = 10; pub struct Keyboard { + conn: CID, csr: utralib::CSR, - /// debounce counter array - debounce: [[u8; KBD_COLS]; KBD_ROWS], - /// threshold (in ms) for considering an up or down event to be debounced, in loop interations. - threshold: u8, /// last timestamp (in ms) since last call timestamp: u64, - /// remember the last keycode since a change event - lastcode: Option>, + /// remember the last key states + last_state: RowColVec, /// connection to the timer for real-time events ticktimer: Ticktimer, /// mapping for ScanCode translation @@ -217,8 +218,14 @@ mod implementation { chord_active: bool, } + fn handle_kbd(_irq_no: usize, arg: *mut usize) { + let kbd = unsafe { &mut *(arg as *mut Keyboard) }; + kbd.update(); + kbd.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1); // clear the interrupt + } + impl Keyboard { - pub fn new() -> Keyboard { + pub fn new(sid: xous::SID) -> Keyboard { let csr = xous::syscall::map_memory( xous::MemoryAddress::new(utra::keyboard::HW_KEYBOARD_BASE), None, @@ -227,16 +234,15 @@ mod implementation { ) .expect("couldn't map Keyboard CSR range"); - let mut ticktimer = XousTickTimer::new(ticktimer_client).expect("KBD: couldn't connect to ticktimer"); - + let ticktimer = ticktimer_server::Ticktimer::new().expect("couldn't connect to ticktimer"); let timestamp = ticktimer.elapsed_ms(); - let kbd = Keyboard { + + let mut kbd = Keyboard { + conn: xous::connect(sid).unwrap(), csr: CSR::new(csr.as_mut_ptr() as *mut u32), - debounce: [[0; KBD_COLS]; KBD_ROWS], - threshold: 5, - timestamp: timestamp, - lastcode: None, - ticktimer: ticktimer_conn, + timestamp, + last_state: RowColVec::new(), + ticktimer, map: KeyMap::Qwerty, delay: 500, rate: 20, @@ -252,7 +258,14 @@ mod implementation { chord_active: false, }; - info!("KBD: hardware initialized"); // gratuitous info statement to keep clippy quiet about unused info import + xous::claim_interrupt( + utra::keyboard::KEYBOARD_IRQ, + handle_kbd, + (&mut kbd) as *mut Keyboard as *mut usize, + ) + .expect("couldn't claim irq"); + + log::trace!("hardware initialized"); kbd } @@ -289,124 +302,92 @@ mod implementation { } /// scan the entire key matrix and return the list of keys that are currently - /// pressed as key codes. Return format is an option-wrapped vector of u8, + /// pressed as key codes. Return format is an array of option-wrapped RowCol /// which is structured as (row : col), where each of row and col are a u8. /// Option "none" means no keys were pressed during this scan. - fn kbd_getcodes(&self) -> Option> { - let mut keys: Vec = Vec::new(); + /// This has O(N^2) time growth as number of keys are pressed; but, typically, + /// it's rare that more than two keys are pressed at once, and most of the time, none are pressed. + /// The 16-element limit is more allowing for an extremely likely worst case. On average, this will perform + /// as well as an O(N) heapless Vec, but comes with the benefit of getting rid of that dependency. + fn kbd_getcodes(&self) -> Option { + let mut keys = RowColVec::new(); + let mut totalfound = 0; for r in 0..KBD_ROWS { let cols: u16 = self.kbd_getrow(r as u8); for c in 0..KBD_COLS { if (cols & (1 << c)) != 0 { - keys.push( RowCol{r: r as _, c: c as _} ).unwrap(); + // note: we could implement a check to flag if more than 16 keys were pressed within a single + // debounce quanta (5ms) at once... + // this is an unlikely scenario, so we're just going to count on ample space being the solution + // to this problem + keys.add_rc(RowCol{r: r as _, c: c as _}).unwrap(); + totalfound += 1; } } } - if keys.len() > 0 { + if totalfound > 0 { Some(keys) } else { None } } - /// update() does a software-based debounce of the keyboard switches - /// update() is designed to be called at regular intervals (not based on keyboard interrupt) - /// it will automatically fetch new keycodes if a change event has happened, otherwise - /// the regular calls to update() are necessary to update the debouncer state - /// - /// returns a struct of (keydown, keyup) scan codes. - - pub fn update(&mut self) -> ( Option>, Option> ) { - let mut downs: [[bool; KBD_COLS]; KBD_ROWS] = [[false; KBD_COLS]; KBD_ROWS]; - let mut keydowns: Vec = Vec::new(); - let mut keyups: Vec = Vec::new(); + /// update() is called from an interrupt context + /// it will send messages to the main loop with the keyup/keydown codes that were pressed + pub fn update(&mut self) { + let mut keydowns = RowColVec::new(); + let mut keyups = RowColVec::new(); // EV_PENDING_KEYPRESSED effectively does an XOR of the previous keyboard state // to the current state, which is why update() does not repeatedly issue results // for keys that are pressed & held. - if self.csr.rf(utra::keyboard::EV_PENDING_KEYPRESSED) != 0 { - // only do the getcodes() call if we saw a change to key state - self.lastcode = self.kbd_getcodes(); - /* - info!("KBD: pending detected"); - if let Some(lc) = &self.lastcode { - for &code in lc.iter() { - info!("KBD: {:?}", code); - } - } else { - info!("KBD: lastcode is None"); - }*/ - // clear the pending bit - self.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1); - let elapsed = self.ticktimer.elapsed_ms() - self.timestamp; - if elapsed <= 1 { - // skip debounce processing if time elapsed is too short - (None, None) - } else { - self.timestamp = elapsed; - - // in case a lot of time has elapsed, saturate the debounce increment at the threshold so we don't - // overflow the debounce counter's u8 - let increment: u8; - if elapsed > self.threshold as u64 { - increment = self.threshold; - } else { - increment = elapsed as u8; - } - - // if there's keys pressed, continue to increment the debounce counter - if let Some(code) = &self.lastcode { - for &rc in code.iter() { - let row = rc.r as usize; let col = rc.c as usize; - if self.debounce[row][col] < self.threshold { - self.debounce[row][col] += increment; - // now check if we've passed the debounce threshold, and report a keydown - if self.debounce[row][col] >= self.threshold { - keydowns.push(RowCol{r: row as _, c: col as _}).expect("KBD hw: probably ran out of space to track keydowns"); - } - } - downs[row][col] = true; // record that we processed the key - } - } - - // now decrement debounce couter for all elements that don't have a press - for r in 0..KBD_ROWS { - for c in 0..KBD_COLS { - if !downs[r][c] && (self.debounce[r][c] > 0) { - if self.debounce[r][c] >= increment { - self.debounce[r][c] -= increment; - } else { - self.debounce[r][c] = 0; - } - - if self.debounce[r][c] == 0 { - keyups.push(RowCol{r: r as _, c: c as _}).expect("KBD hw: probably ran out of space to track keyups"); - } - } - } - } - - let retdowns: Option>; - if keydowns.len() > 0 { - retdowns = Some(keydowns); - } else { - retdowns = None; - } - - let retups: Option>; - if keyups.len() > 0 { - retups = Some(keyups); - } else { - retups = None; - } - - (retdowns, retups) + let maybe_codes = self.kbd_getcodes(); + /* + log::info!("pending detected"); + if let Some(lc) = &self.lastcode { + for &code in lc.iter() { + info!("{:?}", code); } } else { - (None, None) + info!("lastcode is None"); + }*/ + if let Some(new_codes) = maybe_codes { + // check to see if there are codes in the last state that aren't in the current codes + for i in 0..self.last_state.len() { + if let Some(lastcode) = self.last_state.get(i) { + if !new_codes.contains(lastcode) { + keyups.add_rc(lastcode); + self.last_state.set(i, None); + } + } + } + // check to see if the codes in the current set aren't already in the current codes + for i in 0..new_codes.len() { + if let Some(rc) = new_codes.get(i) { + match self.last_state.add_rc(rc) { + Ok(true) => { + keydowns.add_rc(rc).unwrap(); + }, + Ok(false) => { + // already in the array, don't report anything as it's not a change + }, + _ => log::error!("out of key storage state in keyboard update") + } + } + } + + let krs = KeyRawStates { + keydowns, + keyups, + }; + // now dispatch messages based on keyups and keydowns + let buf = Buffer::into_buf(krs).or(Err(xous::Error::InternalError)).unwrap(); + buf.send(self.conn, Opcode::HandlerRawStates.to_u32().unwrap()).unwrap(); + } else { + // skip } } @@ -568,10 +549,10 @@ mod implementation { if ((rc.r == 8) && (rc.c == 5)) || ((rc.r == 8) && (rc.c == 9)) { // if the shift key was tapped twice, remove the shift modifier if self.shift_up == false { - //info!("KBD: shift down true"); + //info!("shift down true"); self.shift_down = true; } else { - //info!("KBD: shift up false"); + //info!("shift up false"); self.shift_up = false; } } @@ -603,13 +584,13 @@ mod implementation { if ((rc.r == 8) && (rc.c == 5)) || ((rc.r == 8) && (rc.c == 9)) { // only set the shift-up if we didn't previously clear it with a double-tap of shift if self.shift_down { - //info!("KBD: shift up true"); + //info!("shift up true"); self.shift_up = true; } - //info!("KBD: shift down false"); + //info!("shift down false"); self.shift_down = false; } else { - //info!("KBD: adding non-shift entry {:?}", rc); + //info!("adding non-shift entry {:?}", rc); ku_ns.push(RowCol{r: rc.r as _, c: rc.c as _}).unwrap(); } } @@ -648,11 +629,11 @@ mod implementation { hold = false; } - fn report_ok(k: char) -> Result<(), ()> { error!("KBD: ran out of space saving char: {}", k); Ok(()) } + fn report_ok(k: char) -> Result<(), ()> { error!("ran out of space saving char: {}", k); Ok(()) } if let Some(kus) = &keyups_noshift { for &rc in kus.iter() { - // info!("KBD: interpreting keyups_noshift entry {:?}", rc); + // info!("interpreting keyups_noshift entry {:?}", rc); let code = match self.map { KeyMap::Qwerty => map_qwerty(rc), KeyMap::Dvorak => map_dvorak(rc), @@ -716,7 +697,7 @@ mod implementation { } } else { if let Some(keycode) = code.key { - // info!("KBD: appeding normal key '{}'", keycode); + // info!("appeding normal key '{}'", keycode); ks.push(keycode).or_else(report_ok).ok(); } } @@ -749,6 +730,7 @@ mod implementation { #[allow(dead_code)] pub struct Keyboard { + cid: xous::CID, map: KeyMap, rate: u32, delay: u32, @@ -756,8 +738,9 @@ mod implementation { } impl Keyboard { - pub fn new() -> Keyboard { + pub fn new(sid: xous::SID) -> Keyboard { Keyboard { + cid: xous::connect(sid).unwrap(), map: KeyMap::Qwerty, rate: 20, delay: 200, @@ -793,162 +776,185 @@ mod implementation { } } +fn send_rawstates(cb_conns: &mut [Option; 16], krs: &KeyRawStates) { + for maybe_conn in cb_conns.iter_mut() { + if let Some(conn) = maybe_conn { + let buf = Buffer::into_buf(*krs).unwrap(); + match buf.lend(*conn, Callback::KeyRawEvent.to_u32().unwrap()) { + Err(xous::Error::ServerNotFound) => { + *maybe_conn = None + }, + Ok(xous::Result::Ok) => {}, + _ => panic!("unhandled error or result in callback processing"), + } + } + } +} + #[xous::xous_main] fn xmain() -> ! { use crate::implementation::Keyboard; log_server::init_wait().unwrap(); - info!("KBD: my PID is {}", xous::process::id()); + info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let kbd_sid = xns.register_name(xous::names::SERVER_NAME_KBD).expect("KBD: can't register server"); - info!("KBD: registered with NS -- {:?}", kbd_sid); + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD).expect("can't register server"); + log::trace!("registered with NS -- {:?}", kbd_sid); // Create a new kbd object - let mut kbd = Keyboard::new(); + let mut kbd = Keyboard::new(kbd_sid); - let mut normal_conns: Vec = Vec::new(); - let mut raw_conns: Vec = Vec::new(); + let mut normal_conns: [Option; 16] = [None; 16]; + let mut raw_conns: [Option; 16] = [None; 16]; - info!("KBD: starting main loop"); + log::trace!("starting main loop"); #[cfg(not(target_os = "none"))] let mut injected_keys: Queue = Queue::u8(); #[cfg(not(target_os = "none"))] let (mut key_enqueue, mut key_dequeue) = injected_keys.split(); loop { - let maybe_env = xous::try_receive_message(kbd_sid).unwrap(); - match maybe_env { - Some(envelope) => { - info!("KBD: Message: {:?}", envelope); - if let xous::Message::Borrow(m) = &envelope.body { - let buf = unsafe { buffer::XousBuffer::from_memory_message(m) }; - let bytes = Pin::new(buf.as_ref()); - let value = unsafe { - archived_value::(&bytes, m.id as usize) - }; - match &*value { - rkyv::Archived::::RegisterListener(registration) => { - let cid = xns.request_connection_blocking(registration.as_str()).expect("KBD: can't connect to requested listener for reporting events"); - normal_conns.push(cid).expect("KBD: probably ran out of slots for keyboard event reporting"); - }, - rkyv::Archived::::RegisterRawListener(registration) => { - let cid = xns.request_connection_blocking(registration.as_str()).expect("KBD: can't connect to requested listener for reporting events"); - raw_conns.push(cid).expect("KBD: probably ran out of slots for raw keyboard event reporting"); - }, - _ => panic!("Invalid memory message response -- corruption occurred"), - }; - } else if let Ok(opcode) = Opcode::try_from(&envelope.body) { - match opcode { - Opcode::SelectKeyMap(map) => { - kbd.set_map(map); - }, - Opcode::SetRepeat(rate, delay) => { - kbd.set_repeat(rate, delay); - }, - Opcode::SetChordInterval(delay) => { - kbd.set_chord_interval(delay); - }, - Opcode::KeyboardEvent(_keys) => { - error!("KBD: somehow received an outgoing event code, this shouldn't happen!"); - }, - Opcode::HostModeInjectKey(key) => { - info!("KBD: injecting emulation key press '{}'", key); - #[cfg(not(target_os = "none"))] - key_enqueue.enqueue(key).unwrap(); - }, - _ => panic!("KBD: received unknown opcode") + let msg = xous::receive_message(kbd_sid).unwrap(); // this blocks until we get a message + log::trace!("Message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::RegisterListener) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, { + let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _); + let cid = Some(xous::connect(sid).unwrap()); + let mut found = false; + for entry in normal_conns.iter_mut() { + if *entry == None { + *entry = cid; + found = true; + break; } + } + if !found { + error!("RegisterListener ran out of space registering callback"); + } + }), + Some(Opcode::RegisterRawListener) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, { + let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _); + let cid = Some(xous::connect(sid).unwrap()); + let mut found = false; + for entry in raw_conns.iter_mut() { + if *entry == None { + *entry = cid; + found = true; + break; + } + } + if !found { + error!("RegisterListener ran out of space registering callback"); + } + }), + Some(Opcode::SelectKeyMap) => msg_scalar_unpack!(msg, km, _, _, _, { + kbd.set_map(KeyMap::from(km)) + }), + Some(Opcode::SetRepeat) => msg_scalar_unpack!(msg, rate, delay, _, _, { + kbd.set_repeat(rate as u32, delay as u32); + }), + Some(Opcode::SetChordInterval) => msg_scalar_unpack!(msg, delay, _, _, _, { + kbd.set_chord_interval(delay as u32); + }), + Some(Opcode::HostModeInjectKey) => msg_scalar_unpack!(msg, k, _, _, _, { + let key = if let Some(a) = core::char::from_u32(k as u32) { + a } else { - error!("KBD: couldn't convert opcode"); - } - } - _ => xous::yield_slice(), - } - - let (keydowns, keyups) = kbd.update(); - /* - if let Some(ku) = &keyups { - for &kus in ku.iter() { - info!("KBD: keyup r{} c{}", kus.r, kus.c); - } - } - if let Some(kd) = &keydowns { - for &kds in kd.iter() { - info!("KBD: keydown r{} c{}", kds.r, kds.c); - } - } - */ - - // this code is totally untested - if keyups.is_some() || keydowns.is_some() { - // send the raw codes - for conn in raw_conns.iter() { - let mut rs: KeyRawStates = KeyRawStates::new(); - if let Some(ku) = &keyups { - for &k in ku.iter() { - unsafe { // because rs is "repr packed" - rs.keyups.push(k).unwrap(); - } - } - } - if let Some(kd) = &keydowns { - for &k in kd.iter() { - unsafe { - rs.keydowns.push(k).unwrap(); - } - } - } - let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); - let pos = { - use rkyv::ser::Serializer; - writer.serialize_value(&rs).expect("KBD: couldn't archive request") + '\u{0000}' }; - let xous_buffer = writer.into_inner(); - xous_buffer.send(*conn, pos as u32).expect("KBD: can't send raw code"); - } - } + info!("injecting emulation key press '{}'", key); + #[cfg(not(target_os = "none"))] + key_enqueue.enqueue(key).unwrap(); + }), + Some(Opcode::HandlerRawStates) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let rawstates = buffer.to_original::().unwrap(); - // interpret scan codes - // the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state - let kc: Vec = match kbd.get_map() { - KeyMap::Braille => { - kbd.track_chord(keyups, keydowns) - }, - _ => { - kbd.track_keys(keyups, keydowns) - }, - }; + // send rawstates on to rawstate listeners + send_rawstates(&mut raw_conns, &rawstates); - // this is used for hosted mode emulation injection of keys - #[cfg(not(target_os = "none"))] - { - let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; - let mut i = 0; - while let Some(c) = key_dequeue.dequeue() { - keys[i] = c; - i = i + 1; - if i == 4 { break; } // see https://github.com/rust-lang/rfcs/pull/2497 for why this can't be at the top of the loop conditional - }; - if i != 0 { - for conn in normal_conns.iter() { - xous::send_message(*conn, api::Opcode::KeyboardEvent(keys).into()).map(|_| ()).expect("KBD: Couldn't send event to listener"); + // TODO: refactor this Vec usage into an array (the Vec is from a previous implementation) + // for now, just copy the array over, inefficiently + let mut keyups_core: Vec = Vec::new(); + let mut keydowns_core: Vec = Vec::new(); + for i in 0..rawstates.keyups.len() { + if let Some(rc) = rawstates.keyups.get(i) { + keyups_core.push(rc); + } } - } - } + for i in 0..rawstates.keydowns.len() { + if let Some(rc) = rawstates.keydowns.get(i) { + keydowns_core.push(rc); + } + } + let keyups = if keyups_core.len() > 0 { + Some(keyups_core) + } else { + None + }; + let keydowns = if keydowns_core.len() > 0 { + Some(keydowns_core) + } else { + None + }; - // send keys, if any - if kc.len() > 0 { - let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; - for i in 0..kc.len() { - // info!("KBD: sending key '{}'", kc[i]); - keys[i] = kc[i]; - } - for conn in normal_conns.iter() { - xous::send_message(*conn, api::Opcode::KeyboardEvent(keys).into()).map(|_| ()).expect("KBD: Couldn't send event to listener"); - } + // interpret scancodes + // the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state + let kc: Vec = match kbd.get_map() { + KeyMap::Braille => { + kbd.track_chord(keyups, keydowns) + }, + _ => { + kbd.track_keys(keyups, keydowns) + }, + }; + + // this is used for hosted mode emulation injection of keys + #[cfg(not(target_os = "none"))] + { + let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; + let mut i = 0; + while let Some(c) = key_dequeue.dequeue() { + keys[i] = c; + i = i + 1; + if i == 4 { break; } // see https://github.com/rust-lang/rfcs/pull/2497 for why this can't be at the top of the loop conditional + }; + if i != 0 { + for conn in normal_conns.iter() { + xous::send_message(*conn, api::Opcode::KeyboardEvent(keys).into()).map(|_| ()).expect("Couldn't send event to listener"); + } + } + } + + // send keys, if any + if kc.len() > 0 { + let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; + for i in 0..kc.len() { + // info!("sending key '{}'", kc[i]); + keys[i] = kc[i]; + } + + for maybe_conn in normal_conns.iter_mut() { + if let Some(conn) = maybe_conn { + match xous::send_message(*conn, + xous::Message::new_scalar(api::Callback::KeyEvent.to_usize().unwrap(), + keys[0] as u32 as usize, + keys[1] as u32 as usize, + keys[2] as u32 as usize, + keys[3] as u32 as usize, + )) { + Err(xous::Error::ServerNotFound) => { + *maybe_conn = None + }, + Ok(xous::Result::Ok) => {}, + _ => log::error!("unhandled error in key event sending") + } + } + } + } + }, + None => log::error!("couldn't convert opcode"), } } - // this shuts up the keyboard thread from polluting the kernel logs when panics happen elsewhere - //loop {xous::receive_message(kbd_sid).unwrap(); xous::yield_slice();} } diff --git a/xous-rs/src/names.rs b/xous-rs/src/names.rs index 5a8425de9..c5df4c476 100644 --- a/xous-rs/src/names.rs +++ b/xous-rs/src/names.rs @@ -7,7 +7,6 @@ for the core set of kernel services. pub const SERVER_NAME_LLIO: &str = "_Low Level I/O manager_"; pub const SERVER_NAME_SHELL: &str = "_Shell_"; -pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; pub const SERVER_NAME_GAM: &str = "_Graphical Abstraction Manager_"; pub const SERVER_NAME_STATUS: &str = "_Status bar manager_"; pub const SERVER_NAME_IME_FRONT: &str = "_IME front end_"; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 9f33fd1a0..0830b24a0 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -46,7 +46,7 @@ fn try_main() -> Result<(), DynError> { "log-server", "com", "xous-names", - //"keyboard", + "keyboard", "trng", "llio", // still to convert