feat(input-server): add InputServer<D: InputDevice> with protocol, mock + UART adapters, and tests
This commit is contained in:
38
crates/servers/input-server/src/adapters/mock.rs
Normal file
38
crates/servers/input-server/src/adapters/mock.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use crate::input_device::InputDevice;
|
||||
use crate::protocol::InputEvent;
|
||||
|
||||
pub struct MockInputDevice {
|
||||
events: [Option<InputEvent>; 16],
|
||||
head: usize,
|
||||
tail: usize,
|
||||
}
|
||||
|
||||
impl MockInputDevice {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
events: [None; 16],
|
||||
head: 0,
|
||||
tail: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_event(&mut self, event: InputEvent) {
|
||||
self.events[self.tail] = Some(event);
|
||||
self.tail = (self.tail + 1) % self.events.len();
|
||||
}
|
||||
}
|
||||
|
||||
impl InputDevice for MockInputDevice {
|
||||
fn poll(&mut self) -> Option<InputEvent> {
|
||||
if self.head == self.tail {
|
||||
return None;
|
||||
}
|
||||
let event = self.events[self.head].take();
|
||||
self.head = (self.head + 1) % self.events.len();
|
||||
event
|
||||
}
|
||||
|
||||
fn has_event(&self) -> bool {
|
||||
self.head != self.tail
|
||||
}
|
||||
}
|
||||
2
crates/servers/input-server/src/adapters/mod.rs
Normal file
2
crates/servers/input-server/src/adapters/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod mock;
|
||||
pub mod qemu_uart;
|
||||
48
crates/servers/input-server/src/adapters/qemu_uart.rs
Normal file
48
crates/servers/input-server/src/adapters/qemu_uart.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use crate::input_device::InputDevice;
|
||||
use crate::protocol::{InputEvent, Key};
|
||||
|
||||
const UART_BASE: usize = 0x10000000;
|
||||
const UART_LSR: usize = 5;
|
||||
|
||||
pub struct UartInputDevice {
|
||||
base: usize,
|
||||
}
|
||||
|
||||
impl UartInputDevice {
|
||||
pub fn new() -> Self {
|
||||
Self { base: UART_BASE }
|
||||
}
|
||||
|
||||
fn read_byte(&self) -> Option<u8> {
|
||||
let lsr = unsafe { core::ptr::read_volatile((self.base + UART_LSR) as *const u8) };
|
||||
if lsr & 1 != 0 {
|
||||
Some(unsafe { core::ptr::read_volatile(self.base as *const u8) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn byte_to_key(byte: u8) -> Key {
|
||||
match byte {
|
||||
b'w' | b'W' => Key::Up,
|
||||
b's' | b'S' => Key::Down,
|
||||
b'a' | b'A' => Key::Left,
|
||||
b'd' | b'D' => Key::Right,
|
||||
b'\r' | b'\n' => Key::Enter,
|
||||
0x1B => Key::Escape,
|
||||
c => Key::Char(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InputDevice for UartInputDevice {
|
||||
fn poll(&mut self) -> Option<InputEvent> {
|
||||
let byte = self.read_byte()?;
|
||||
Some(InputEvent::KeyDown(Self::byte_to_key(byte)))
|
||||
}
|
||||
|
||||
fn has_event(&self) -> bool {
|
||||
let lsr = unsafe { core::ptr::read_volatile((self.base + UART_LSR) as *const u8) };
|
||||
lsr & 1 != 0
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user