1use alloc::collections::VecDeque;
15use conquer_once::spin::OnceCell;
16use core::pin::Pin;
17use core::task::{Context, Poll};
18use futures_util::stream::Stream;
19use futures_util::task::AtomicWaker;
20use spin::Mutex;
21
22static SCANCODE_QUEUE: OnceCell<Mutex<VecDeque<u8>>> = OnceCell::uninit();
24
25static WAKER: AtomicWaker = AtomicWaker::new();
27
28pub(crate) fn add_scancode(scancode: u8) {
34 if let Ok(queue) = SCANCODE_QUEUE.try_get() {
35 queue.lock().push_back(scancode);
36 WAKER.wake(); }
38 }
40
41pub struct ScancodeStream {
43 _private: (),
44}
45
46impl ScancodeStream {
47 pub fn new() -> Self {
49 let _ = SCANCODE_QUEUE.try_init_once(|| Mutex::new(VecDeque::new()));
51 ScancodeStream { _private: () }
52 }
53}
54
55impl Default for ScancodeStream {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61impl Stream for ScancodeStream {
62 type Item = u8;
63
64 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<u8>> {
65 let queue = SCANCODE_QUEUE
66 .try_get()
67 .expect("scancode queue not initialized");
68
69 if let Some(scancode) = queue.lock().pop_front() {
71 return Poll::Ready(Some(scancode));
72 }
73
74 WAKER.register(cx.waker());
76
77 match queue.lock().pop_front() {
79 Some(scancode) => {
80 WAKER.take();
81 Poll::Ready(Some(scancode))
82 }
83 None => Poll::Pending,
84 }
85 }
86}
87
88fn sbi_console_getchar() -> Option<u8> {
94 let ret: isize;
95 unsafe {
96 core::arch::asm!(
97 "li a7, 2", "ecall",
99 "mv {}, a0", out(reg) ret,
101 options(nostack)
102 );
103 }
104
105 if ret >= 0 {
106 Some(ret as u8)
107 } else {
108 None
109 }
110}
111
112pub fn try_pop_char() -> Option<u8> {
115 if let Ok(queue) = SCANCODE_QUEUE.try_get() {
116 queue.lock().pop_front()
117 } else {
118 None
119 }
120}
121
122pub fn poll_keyboard() {
129 const MAX_READS_PER_POLL: usize = 10;
131
132 for _ in 0..MAX_READS_PER_POLL {
133 if let Some(ch) = sbi_console_getchar() {
134 add_scancode(ch);
135 } else {
136 break;
138 }
139 }
140}
141
142pub async fn print_keypresses() {
147 use futures_util::stream::StreamExt;
148
149 crate::serial_println!("[KEYBOARD] Keyboard input task started (SBI console)");
150 crate::println!("[KEYBOARD] Press keys to test...");
151
152 let mut scancodes = ScancodeStream::new();
153
154 while let Some(scancode) = scancodes.next().await {
155 match scancode {
157 b'\r' | b'\n' => {
158 crate::println!();
159 }
160 0x08 | 0x7f => {
161 crate::print!("\x08 \x08");
163 }
164 0x20..=0x7e => {
165 crate::print!("{}", scancode as char);
167 }
168 _ => {
169 crate::print!("[{:02x}]", scancode);
171 }
172 }
173 }
174}
175
176pub fn keyboard_interrupt_handler() {
182 poll_keyboard();
183}