mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
add keyboard userland abstractions
This commit is contained in:
parent
40c94b5abc
commit
601d2763e8
3 changed files with 280 additions and 12 deletions
|
|
@ -31,6 +31,10 @@ rand = "0.8.5"
|
|||
rand_core = "0.6.4"
|
||||
rand_chacha = "0.3.1"
|
||||
bitfield = "0.13.2"
|
||||
# TOODO: migrate from bitfield to bitbybit
|
||||
bitbybit = "1.4.0"
|
||||
arbitrary-int = "1.2"
|
||||
bytemuck = "1.24.0"
|
||||
|
||||
num-derive = { version = "0.4.2", default-features = false }
|
||||
num-traits = { version = "0.2.14", default-features = false }
|
||||
|
|
@ -40,6 +44,7 @@ rkyv = { version = "0.8.8", default-features = false, features = [
|
|||
] }
|
||||
|
||||
[features]
|
||||
keyboard-testing = []
|
||||
app-uart = []
|
||||
rawserial = []
|
||||
pinger = []
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
mod api;
|
||||
mod kpc_aoint;
|
||||
mod servers;
|
||||
#[cfg(feature = "board-baosec")]
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use bao1x_api::*;
|
||||
use arbitrary_int::{Number, u4};
|
||||
use bao1x_api::{keyboard::KeyboardOpcode, *};
|
||||
use bao1x_hal::{iox::Iox, udma::GlobalConfig};
|
||||
use bitfield::*;
|
||||
use num_traits::*;
|
||||
|
|
@ -256,8 +258,61 @@ fn main() {
|
|||
// The index of the array corresponds to the slot.
|
||||
let mut irq_table: [Option<IrqLocalRegistration>; 8] = [None; 8];
|
||||
|
||||
// "own" the KPC & Always-on registers
|
||||
let mut kpc_aoint = bao1x_hal::kpc_aoint::KpcAoInt::new(Some(crate::kpc_aoint::handler));
|
||||
kpc_aoint.ao.wo(utra::ao_sysctrl::SFR_IOX, 1); // connect PF directly to KP unit, overrides IO mux even???
|
||||
kpc_aoint.ao.wo(utra::ao_sysctrl::CR_WKUPMASK, 0x3F);
|
||||
|
||||
// KPOPO0 defines drive state in phase 0 - here we set it to high
|
||||
// KPOPO1 defines drive state in phase 1 - here we set it to low
|
||||
// KPOE0 defines OE state in phase 0 - here we set it to drive
|
||||
// KPOE1 defines OE state in phase 1 - here we set it to drive
|
||||
let cfg0 = kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOPO0, 1)
|
||||
// | kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOPO1, 1)
|
||||
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOOE0, 1)
|
||||
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_KPOOE1, 1)
|
||||
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG0_DKPCEN, 1);
|
||||
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG0, cfg0);
|
||||
let cfg1 = kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG1_CFG_STEP, 2)
|
||||
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG1_CFG_FILTER, 2)
|
||||
| kpc_aoint.kpc.ms(utra::dkpc::SFR_CFG1_CFG_CNT1MS, 4);
|
||||
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG1, cfg1);
|
||||
// CFG2 has format of interval kpo | stop drive kpo | sample point kpi | start drive kpo, each 8 bits wide
|
||||
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG2, 0x40_05_03_01); // sets ~24ms scanning rate
|
||||
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG3, 0xFFFF_0000); // fall[15:0] | rise[15:0] detection
|
||||
// this is the deep sleep interval for debouncing the keyboard array
|
||||
kpc_aoint.kpc.wo(utra::dkpc::SFR_CFG4, 256);
|
||||
// drain any pending events
|
||||
while kpc_aoint.kpc.r(utra::dkpc::SFR_SR1) != 0 {
|
||||
// this register didn't get mapped in register extraction because its type
|
||||
// is `apb_buf2`: FIXME - adjust the register extraction script to capture this type.
|
||||
// this register drains the pending interrupts from the wakeup/keyboard queue
|
||||
let _ = unsafe { kpc_aoint.kpc.base().add(8).read_volatile() };
|
||||
}
|
||||
|
||||
// safety: cloning the KPC hardware register is only safe because the KPC register is accessed
|
||||
// in two mutually exclusive contexts: the interrupt handler, and userland service. This server
|
||||
// guarantees we won't try to access it in any other contexts.
|
||||
servers::keyboard::start_keyboard_service(
|
||||
unsafe { kpc_aoint.kpc.base() } as usize,
|
||||
unsafe { kpc_aoint.irq.base() } as usize,
|
||||
unsafe { kpc_aoint.ao.base() } as usize,
|
||||
);
|
||||
// start keyboard emulator service
|
||||
servers::keyboard::start_keyboard_service();
|
||||
let kbd_conn = xns.request_connection_blocking(bao1x_api::SERVER_NAME_KBD).unwrap();
|
||||
|
||||
let kpc_int = u4::new(bao1x_hal::kpc_aoint::IrqMapping::AoInt as u8);
|
||||
kpc_aoint.add_irq_notifier(IrqNotification {
|
||||
bit: kpc_int,
|
||||
conn: kbd_conn,
|
||||
opcode: KeyboardOpcode::HandlerTrigger.to_usize().unwrap(),
|
||||
args: [0, 0, 0, 0],
|
||||
});
|
||||
// feels like a bit of an abstraction violation, but I don't know how much the other interrupts
|
||||
// require edge-triggered handling
|
||||
kpc_aoint.irq.wo(utra::irqarray2::EV_EDGE_TRIGGERED, 1 << kpc_int.as_u32());
|
||||
kpc_aoint.irq.wo(utra::irqarray2::EV_POLARITY, 1 << kpc_int.as_u32());
|
||||
kpc_aoint.modify_irq_ena(kpc_int, true);
|
||||
|
||||
// claim BIO
|
||||
#[cfg(feature = "board-baosec")]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,99 @@
|
|||
use bao1x_api::keyboard::*;
|
||||
use bao1x_hal::board::KeyPress;
|
||||
use bao1x_hal::kpc_aoint::AoIntStatus;
|
||||
use num_traits::*;
|
||||
use utralib::*;
|
||||
use xous::{CID, MessageSender, msg_blocking_scalar_unpack, msg_scalar_unpack};
|
||||
use xous_ipc::Buffer;
|
||||
|
||||
pub fn start_keyboard_service() {
|
||||
const KEYUP_DELAY_MS: u64 = 50;
|
||||
|
||||
struct KeypressTimestamp {
|
||||
pub kp: KeyPress,
|
||||
pub next_repeat_time: u64,
|
||||
}
|
||||
struct KeyTracker {
|
||||
pub rate_ms: usize,
|
||||
pub delay_ms: usize,
|
||||
pub keys: Vec<KeypressTimestamp>,
|
||||
}
|
||||
impl KeyTracker {
|
||||
pub fn new() -> Self { KeyTracker { rate_ms: KEYUP_DELAY_MS as usize, delay_ms: 500, keys: Vec::new() } }
|
||||
|
||||
pub fn register_key_down(&mut self, key: KeyPress, ts: u64) {
|
||||
if let Some(entry) = self.keys.iter_mut().find(|e| e.kp == key) {
|
||||
// update the existing entry if it exists
|
||||
entry.next_repeat_time = ts + self.delay_ms as u64;
|
||||
} else {
|
||||
self.keys.push(KeypressTimestamp { kp: key, next_repeat_time: ts + self.delay_ms as u64 });
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes the current keys pressed, at the current time stamp
|
||||
pub fn update_key_down(&mut self, keys: &[KeyPress], now: u64) {
|
||||
// Handle the case that key A is held down, then key B is held down simultaneously,
|
||||
// then key A is released while B continues to hold down
|
||||
// then key A is pressed again all while key B is held down
|
||||
//
|
||||
// The behavior in this case is that A should emit a keydown immediately and will also
|
||||
// immediately repeat without going through the repeat delay. This is consistent with a
|
||||
// "video gaming" mode of operation.
|
||||
//
|
||||
// Search for keys that are pressed, but not currently in the pressed array
|
||||
// trigger an effective key report by setting its timestamp to now minus the repeat delay
|
||||
for key in keys {
|
||||
// search for key not in keys vector; create a new entry with next repeat equal
|
||||
// to now, so it gets emitted immediately
|
||||
if !self.keys.iter().any(|e| e.kp == *key) {
|
||||
self.keys.push(KeypressTimestamp { kp: *key, next_repeat_time: now });
|
||||
}
|
||||
}
|
||||
|
||||
// Handle the case that key A is held down, then key B is held down simultaneously.
|
||||
// Then, key A is released.
|
||||
//
|
||||
// This is done after all current keys are registered above.
|
||||
//
|
||||
// Each key currently pressed should be present in `self.keys` vector.
|
||||
// If a currently pressed key is not in the `keys` input slice,
|
||||
// delete it from the `self.keys` vector. This will prevent it from continuing to generate
|
||||
// key presses on get_repeats()
|
||||
self.keys.retain(|entry| keys.iter().any(|key| key == &entry.kp));
|
||||
}
|
||||
|
||||
/// Returns any keys that should have repeat key-press events generated
|
||||
pub fn get_repeats(&mut self, now: u64) -> Vec<char> {
|
||||
let mut kps = Vec::new();
|
||||
for key in self.keys.iter_mut() {
|
||||
if now >= key.next_repeat_time {
|
||||
kps.push(map_keypress(key.kp));
|
||||
// rebasing off of now prevents keys from "lagging on" in case of UI delay
|
||||
key.next_repeat_time = now + self.rate_ms as u64;
|
||||
}
|
||||
}
|
||||
kps
|
||||
}
|
||||
|
||||
pub fn keys_pressed(&self) -> usize { self.keys.len() }
|
||||
|
||||
pub fn clear_keys(&mut self) { self.keys.clear(); }
|
||||
}
|
||||
|
||||
fn map_keypress(kp: KeyPress) -> char {
|
||||
match kp {
|
||||
KeyPress::Down => '↓',
|
||||
KeyPress::Up => '↑',
|
||||
KeyPress::Left => '←',
|
||||
KeyPress::Right => '→',
|
||||
KeyPress::Select => '∴',
|
||||
KeyPress::Center => '\r',
|
||||
_ => '\u{0000}',
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_keyboard_service(dkpc_ptr: usize, irq_ptr: usize, ao_ptr: usize) {
|
||||
std::thread::spawn(move || {
|
||||
keyboard_service();
|
||||
keyboard_service(dkpc_ptr, irq_ptr, ao_ptr);
|
||||
});
|
||||
std::thread::spawn(move || {
|
||||
keyboard_bouncer();
|
||||
|
|
@ -35,9 +123,14 @@ fn keyboard_bouncer() {
|
|||
}
|
||||
}
|
||||
|
||||
fn keyboard_service() {
|
||||
fn keyboard_service(dkpc_ptr: usize, irq_ptr: usize, ao_ptr: usize) {
|
||||
let dkpc = CSR::new(dkpc_ptr as *mut u32);
|
||||
let mut ao = CSR::new(ao_ptr as *mut u32);
|
||||
let _irq = CSR::new(irq_ptr as *mut u32);
|
||||
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
let kbd_sid = xns.register_name(bao1x_api::SERVER_NAME_KBD, None).expect("can't register server");
|
||||
let tt = ticktimer::Ticktimer::new().unwrap();
|
||||
|
||||
let mut listeners: Vec<(CID, usize)> = Vec::new();
|
||||
let mut observer_conn: Option<CID> = None;
|
||||
|
|
@ -48,6 +141,37 @@ fn keyboard_service() {
|
|||
// storage for any blocking listeners
|
||||
let mut blocking_listener = Vec::<MessageSender>::new();
|
||||
|
||||
let iox = crate::iox::IoxHal::new();
|
||||
let (_row, _col) = bao1x_hal::board::setup_kpc_pins(&iox);
|
||||
|
||||
#[cfg(feature = "keyboard-testing")]
|
||||
// this routine is useful for mapping out raw keys on new hardware builds
|
||||
std::thread::spawn(move || {
|
||||
let dkpc = CSR::new(dkpc_ptr as *mut u32);
|
||||
let mut irq = CSR::new(irq_ptr as *mut u32);
|
||||
let mut ao = CSR::new(ao_ptr as *mut u32);
|
||||
let tt = ticktimer::Ticktimer::new().unwrap();
|
||||
loop {
|
||||
tt.sleep_ms(1000);
|
||||
for i in (0..6).chain(12..13).chain(8..9) {
|
||||
log::info!("{:x}: {:x} ", i * 4, unsafe { dkpc.base().add(i).read_volatile() });
|
||||
}
|
||||
let fr = AoIntStatus::new_with_raw_value(ao.r(utra::ao_sysctrl::SFR_AOFR));
|
||||
let pending = irq.r(utralib::utra::irqarray2::EV_PENDING);
|
||||
log::info!(
|
||||
"int: {:x}/{:x}/{:x}/{:x?}",
|
||||
irq.r(utralib::utra::irqarray2::EV_ENABLE),
|
||||
pending,
|
||||
irq.r(utralib::utra::irqarray2::EV_STATUS),
|
||||
fr,
|
||||
);
|
||||
ao.wo(utra::ao_sysctrl::SFR_AOFR, fr.raw_value());
|
||||
irq.wo(utra::irqarray2::EV_PENDING, pending);
|
||||
}
|
||||
});
|
||||
|
||||
let mut key_tracker = KeyTracker::new();
|
||||
let mut last_key_event = 0u64;
|
||||
loop {
|
||||
let msg = xous::receive_message(kbd_sid).unwrap(); // this blocks until we get a message
|
||||
let op = FromPrimitive::from_usize(msg.body.id());
|
||||
|
|
@ -86,17 +210,22 @@ fn keyboard_service() {
|
|||
}
|
||||
}
|
||||
Some(KeyboardOpcode::SelectKeyMap) => {
|
||||
todo!();
|
||||
// only one key map for the input keyboard. Key mapping for translation of
|
||||
// key presess to USB key codes should be set in the USB stack, not here.
|
||||
unimplemented!()
|
||||
}
|
||||
Some(KeyboardOpcode::GetKeyMap) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
|
||||
log::warn!("Defaulting to DVORAK map");
|
||||
xous::return_scalar(msg.sender, KeyMap::Dvorak.into()).expect("can't retrieve keymap");
|
||||
}),
|
||||
Some(KeyboardOpcode::SetRepeat) => msg_scalar_unpack!(msg, _rate, _delay, _, _, {
|
||||
todo!();
|
||||
Some(KeyboardOpcode::SetRepeat) => msg_scalar_unpack!(msg, rate, delay, _, _, {
|
||||
key_tracker.rate_ms = rate;
|
||||
key_tracker.delay_ms = delay;
|
||||
}),
|
||||
Some(KeyboardOpcode::SetChordInterval) => msg_scalar_unpack!(msg, _delay, _, _, _, {
|
||||
todo!();
|
||||
// chording allows us to interpret multiple key hits as a whole new separate key.
|
||||
// for now we don't implement this feature.
|
||||
unimplemented!()
|
||||
}),
|
||||
Some(KeyboardOpcode::InjectKey) => msg_scalar_unpack!(msg, k, _, _, _, {
|
||||
// key substitutions to help things work better
|
||||
|
|
@ -188,9 +317,88 @@ fn keyboard_service() {
|
|||
xous::return_scalar2(listener, key as u32 as usize, 0).unwrap();
|
||||
}
|
||||
}),
|
||||
Some(KeyboardOpcode::HandlerTrigger) => {
|
||||
todo!("Write this once we have an IRQ handler for keyboard interrupts");
|
||||
}
|
||||
Some(KeyboardOpcode::HandlerTrigger) => msg_scalar_unpack!(msg, pending, _, _, _, {
|
||||
if pending & (1 << bao1x_hal::kpc_aoint::IrqMapping::AoInt as usize) != 0 {
|
||||
let mut kc: Vec<char> = Vec::new();
|
||||
let now = tt.elapsed_ms();
|
||||
if now - last_key_event > KEYUP_DELAY_MS {
|
||||
key_tracker.clear_keys();
|
||||
}
|
||||
last_key_event = now;
|
||||
|
||||
// key downs come from this register
|
||||
if dkpc.r(utra::dkpc::SFR_SR1) != 0 {
|
||||
let sr1 = unsafe { dkpc.base().add(8).read_volatile() };
|
||||
let key_down = bao1x_hal::board::kpc_sr1_to_key(sr1);
|
||||
key_tracker.register_key_down(key_down, now);
|
||||
if key_down != KeyPress::Invalid {
|
||||
kc.push(map_keypress(key_down))
|
||||
}
|
||||
}
|
||||
// the keys_pressed() check is necessary because the interrupt will fire *before* a key
|
||||
// press is effectively registered. This is because the interrupt fires as soon as any
|
||||
// noise is detected on the keyboard, *before* the hardware debounce
|
||||
// happens!
|
||||
if key_tracker.keys_pressed() > 0 {
|
||||
let sr0 = dkpc.r(utra::dkpc::SFR_SR0);
|
||||
let keys_down = bao1x_hal::board::kpc_sr0_to_key(sr0);
|
||||
key_tracker.update_key_down(&keys_down, now);
|
||||
}
|
||||
|
||||
// clear the FR bits
|
||||
let fr = AoIntStatus::new_with_raw_value(ao.r(utra::ao_sysctrl::SFR_AOFR));
|
||||
ao.wo(utra::ao_sysctrl::SFR_AOFR, fr.raw_value());
|
||||
|
||||
// add any repeat keys to the key response array
|
||||
kc.extend_from_slice(&key_tracker.get_repeats(now));
|
||||
|
||||
// strip out any null entries that were generated
|
||||
kc.retain(|&c| c != '\u{0000}');
|
||||
|
||||
// send keys, if any
|
||||
// handle the blocking listeners
|
||||
if kc.len() > 0 {
|
||||
for listener in blocking_listener.drain(..) {
|
||||
xous::return_scalar2(
|
||||
listener,
|
||||
if kc.len() >= 1 { kc[0] as u32 as usize } else { 0 },
|
||||
if kc.len() >= 2 { kc[1] as u32 as usize } else { 0 },
|
||||
)
|
||||
.unwrap();
|
||||
if kc.len() > 2 {
|
||||
log::warn!(
|
||||
"Extra keys in multi-hit event went unreported: only 2 of {} total keys reported out of {:?}",
|
||||
kc.len(),
|
||||
&kc,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// handle the true async listeners
|
||||
for kv in kc.chunks(4) {
|
||||
let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}'];
|
||||
for i in 0..kv.len() {
|
||||
keys[i] = kv[i];
|
||||
}
|
||||
log::trace!("sending keys {:?}", keys);
|
||||
for &(listener_conn, listener_op) in listeners.iter() {
|
||||
xous::try_send_message(
|
||||
listener_conn,
|
||||
xous::Message::new_scalar(
|
||||
listener_op,
|
||||
keys[0] as u32 as usize,
|
||||
keys[1] as u32 as usize,
|
||||
keys[2] as u32 as usize,
|
||||
keys[3] as u32 as usize,
|
||||
),
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::warn!("Unhandled interrupt: {:x}", pending);
|
||||
}
|
||||
}),
|
||||
None => {
|
||||
log::error!("couldn't convert KeyboardOpcode");
|
||||
break;
|
||||
|
|
|
|||
Loading…
Reference in a new issue