From 3e84e0e597274e0e109b51d1c96ef507a82e2ad1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 6 Jun 2022 04:33:10 +0800 Subject: [PATCH] add some example code to FFI-test for implementing a getchar-like facility --- Cargo.lock | 1 + services/ffi-test/Cargo.toml | 1 + services/ffi-test/src/bindings.rs | 54 +++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 34126a0e7..04841cf94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1157,6 +1157,7 @@ name = "ffi-test" version = "0.1.0" dependencies = [ "ffi-sys", + "keyboard", "log", "log-server", "num-derive", diff --git a/services/ffi-test/Cargo.toml b/services/ffi-test/Cargo.toml index 4695c0589..5f6a7e332 100644 --- a/services/ffi-test/Cargo.toml +++ b/services/ffi-test/Cargo.toml @@ -16,6 +16,7 @@ num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} susres = {path = "../susres"} ffi-sys = {path = "sys"} +keyboard = {path = "../keyboard"} [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} diff --git a/services/ffi-test/src/bindings.rs b/services/ffi-test/src/bindings.rs index 062ca59ed..7bfb0183a 100644 --- a/services/ffi-test/src/bindings.rs +++ b/services/ffi-test/src/bindings.rs @@ -16,6 +16,60 @@ pub type c_float = f32; pub type c_double = f64; pub type c_void = core::ffi::c_void; +use xous::{send_message, Message}; +static mut KBD: Option = None; +fn get_keys_blocking() -> Vec { + if unsafe{KBD.is_none()} { + let xns = xous_names::XousNames::new().unwrap(); + let kbd = keyboard::Keyboard::new(&xns).unwrap(); + unsafe{KBD = Some(kbd)}; + } + match send_message(unsafe{KBD.as_ref().unwrap().conn()}, + Message::new_blocking_scalar( + 9, // BlockingKeyboardListener + 0, 0, 0, 0 + ) + ) { + Ok(xous::Result::Scalar2(k1, k2)) => { + let mut ret = Vec::::new(); + if let Some(c) = core::char::from_u32(k1 as u32) { + ret.push(c) + } + if let Some(c) = core::char::from_u32(k2 as u32) { + ret.push(c) + } + ret + } + Ok(_) | Err(_) => panic!("internal error: Incorrect return type") + } +} + + +#[export_name = "rust_getchar"] +pub unsafe extern "C" fn rust_getchar() -> c_char { + log::info!("rust_getchar called"); + let mut chr = 0 as c_char; + let kbhit = get_keys_blocking(); + for k in kbhit { + log::info!("got key character: {}", k); + chr = k as i8; + return chr; + //break; + } + log::info!("libc_getchar cleanup FIXME"); + //kbd.drop(); ????? + return chr; +} + +/* +/// Call this from your Rust init routine, before using get_keys_blocking() +pub fn init_kbd() { + let xns = xous_names::XousNames::new().unwrap(); + let kbd = keyboard::Keyboard::new(&xns).unwrap(); + KBD_CONN.store(kbd.conn(), Ordering::SeqCst); + unsafe{KBD = Some(kbd)}; +}*/ + extern "C" { pub fn add_one(a: i32) -> i32; }