use alloc::collections::VecDeque;
use conquer_once::spin::OnceCell;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures_util::stream::Stream;
use futures_util::task::AtomicWaker;
use spin::Mutex;
static SCANCODE_QUEUE: OnceCell<Mutex<VecDeque<u8>>> = OnceCell::uninit();
static WAKER: AtomicWaker = AtomicWaker::new();
pub(crate) fn add_scancode(scancode: u8) {
if let Ok(queue) = SCANCODE_QUEUE.try_get() {
queue.lock().push_back(scancode);
WAKER.wake(); }
}
pub struct ScancodeStream {
_private: (),
}
impl ScancodeStream {
pub fn new() -> Self {
let _ = SCANCODE_QUEUE.try_init_once(|| Mutex::new(VecDeque::new()));
ScancodeStream { _private: () }
}
}
impl Default for ScancodeStream {
fn default() -> Self {
Self::new()
}
}
impl Stream for ScancodeStream {
type Item = u8;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<u8>> {
let queue = SCANCODE_QUEUE
.try_get()
.expect("scancode queue not initialized");
if let Some(scancode) = queue.lock().pop_front() {
return Poll::Ready(Some(scancode));
}
WAKER.register(cx.waker());
match queue.lock().pop_front() {
Some(scancode) => {
WAKER.take();
Poll::Ready(Some(scancode))
}
None => Poll::Pending,
}
}
}
fn sbi_console_getchar() -> Option<u8> {
let ret: isize;
unsafe {
core::arch::asm!(
"li a7, 2", "ecall",
"mv {}, a0", out(reg) ret,
options(nostack)
);
}
if ret >= 0 {
Some(ret as u8)
} else {
None
}
}
pub fn try_pop_char() -> Option<u8> {
if let Ok(queue) = SCANCODE_QUEUE.try_get() {
queue.lock().pop_front()
} else {
None
}
}
pub fn poll_keyboard() {
const MAX_READS_PER_POLL: usize = 10;
for _ in 0..MAX_READS_PER_POLL {
if let Some(ch) = sbi_console_getchar() {
add_scancode(ch);
} else {
break;
}
}
}
pub async fn print_keypresses() {
use futures_util::stream::StreamExt;
crate::serial_println!("[KEYBOARD] Keyboard input task started (SBI console)");
crate::println!("[KEYBOARD] Press keys to test...");
let mut scancodes = ScancodeStream::new();
while let Some(scancode) = scancodes.next().await {
match scancode {
b'\r' | b'\n' => {
crate::println!();
}
0x08 | 0x7f => {
crate::print!("\x08 \x08");
}
0x20..=0x7e => {
crate::print!("{}", scancode as char);
}
_ => {
crate::print!("[{:02x}]", scancode);
}
}
}
}
pub fn keyboard_interrupt_handler() {
poll_keyboard();
}