mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
initial cut of a major refactor of the keyboard server
- debounce is now in hardware (requires latest version of betrusted-soc) - key events originate from an interrupt context and propagate through to the listeners as messages - attempt to reduce the use of heapless::Vec; there is an awkward interposer step still between the array methodology and the Vec methodology I'm not sure if trying to eliminate the Vec is a good idea, because...I'm finding that we're just re-implementing Vec, but much worse. However, for the purpose of movement of data across IPC boundaries, it's more robust to use primitive types, because serializing Vec is not possible without either forking the heapless crate to derive the rkyv traits; or, we'd have to do some probably quite dangerous conversion of the Vec to a raw slice which also doesn't feel nice.
This commit is contained in:
parent
aa04241aa4
commit
bd54b48f8f
9 changed files with 548 additions and 491 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -626,6 +626,8 @@ dependencies = [
|
|||
"heapless",
|
||||
"log",
|
||||
"log-server",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"rkyv 0.4.3",
|
||||
"ticktimer-server",
|
||||
"utralib",
|
||||
|
|
|
|||
|
|
@ -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<fn(BattStats)> = None;
|
||||
static mut MYSERVER_CB: Option<fn(BattStats)> = 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<CID>; 32]) {
|
||||
fn do_callback(cb_conns: &mut [Option<CID>; 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();}
|
||||
}
|
||||
}
|
||||
|
|
@ -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"}
|
||||
|
|
|
|||
|
|
@ -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<char>,
|
||||
}
|
||||
|
||||
#[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<RowCol>; 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<RowCol> {
|
||||
if i < MAX_KEYS {
|
||||
self.storage[i]
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn set(&mut self, i: usize, data: Option<RowCol>) {
|
||||
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<bool, xous::Error> {
|
||||
// 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<RowCol, U16>,
|
||||
pub keyups: Vec<RowCol, U16>,
|
||||
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::<KeyRawStates>())
|
||||
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::<KeyRawStates>())
|
||||
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<S: rkyv::ser::Serializer + ?Sized> rkyv::Serialize<S> for KeyRawStates {
|
||||
fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
|
||||
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<usize> 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<Self, Self::Error> {
|
||||
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<Message> 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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<xous::Result, xous::Error> {
|
||||
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<fn([char; 4])> = None;
|
||||
static mut KBD_RAW_CB: Option<fn(KeyRawStates)> = None;
|
||||
|
||||
pub struct Keyboard {
|
||||
conn: xous::CID,
|
||||
event_cb_sid: Option<xous::SID>,
|
||||
raw_cb_sid: Option<xous::SID>,
|
||||
}
|
||||
impl Keyboard {
|
||||
pub fn new(xns: xous_names::XousNames) -> Result<Self, xous::Error> {
|
||||
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<xous::Result, xous::Error> {
|
||||
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::<KeyRawStates, _>().unwrap();
|
||||
unsafe {
|
||||
if let Some(cb) = KBD_RAW_CB {
|
||||
cb(krs)
|
||||
}
|
||||
}
|
||||
},
|
||||
None => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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<u32>,
|
||||
/// 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<Vec<RowCol, U16>>,
|
||||
/// 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<Vec<RowCol, U16>> {
|
||||
let mut keys: Vec<RowCol, U16> = 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<RowColVec> {
|
||||
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<Vec<RowCol, U16>>, Option<Vec<RowCol, U16>> ) {
|
||||
let mut downs: [[bool; KBD_COLS]; KBD_ROWS] = [[false; KBD_COLS]; KBD_ROWS];
|
||||
let mut keydowns: Vec<RowCol, U16> = Vec::new();
|
||||
let mut keyups: Vec<RowCol, U16> = 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<Vec<RowCol, U16>>;
|
||||
if keydowns.len() > 0 {
|
||||
retdowns = Some(keydowns);
|
||||
} else {
|
||||
retdowns = None;
|
||||
}
|
||||
|
||||
let retups: Option<Vec<RowCol, U16>>;
|
||||
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<CID>; 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<xous::CID, U64> = Vec::new();
|
||||
let mut raw_conns: Vec<xous::CID, U64> = Vec::new();
|
||||
let mut normal_conns: [Option<CID>; 16] = [None; 16];
|
||||
let mut raw_conns: [Option<CID>; 16] = [None; 16];
|
||||
|
||||
info!("KBD: starting main loop");
|
||||
log::trace!("starting main loop");
|
||||
#[cfg(not(target_os = "none"))]
|
||||
let mut injected_keys: Queue<char, U64, _> = 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::<api::Opcode>(&bytes, m.id as usize)
|
||||
};
|
||||
match &*value {
|
||||
rkyv::Archived::<api::Opcode>::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::<api::Opcode>::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::<KeyRawStates, _>().unwrap();
|
||||
|
||||
// interpret scan codes
|
||||
// the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state
|
||||
let kc: Vec<char, U4> = 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<RowCol, U16> = Vec::new();
|
||||
let mut keydowns_core: Vec<RowCol, U16> = 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<char, U4> = 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();}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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_";
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ fn try_main() -> Result<(), DynError> {
|
|||
"log-server",
|
||||
"com",
|
||||
"xous-names",
|
||||
//"keyboard",
|
||||
"keyboard",
|
||||
"trng",
|
||||
|
||||
"llio", // still to convert
|
||||
|
|
|
|||
Loading…
Reference in a new issue