From cb2a3b442d511e5169c7a627be3f67114ca5c0d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Sat, 14 May 2022 11:17:26 +0200 Subject: [PATCH 01/11] intermediate commit --- Cargo.lock | 20 +++++++++++ Cargo.toml | 2 ++ services/keyboard-backlight/Cargo.toml | 26 ++++++++++++++ services/keyboard-backlight/src/main.rs | 48 +++++++++++++++++++++++++ services/keyboard/src/api.rs | 3 ++ services/keyboard/src/lib.rs | 10 ++++++ services/keyboard/src/main.rs | 31 +++++++++++++++- 7 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 services/keyboard-backlight/Cargo.toml create mode 100644 services/keyboard-backlight/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 597a2b327..4d2097e0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1491,6 +1491,26 @@ dependencies = [ "xous-names", ] +[[package]] +name = "keyboard-backlight" +version = "0.1.0" +dependencies = [ + "com", + "keyboard", + "log", + "log-server", + "net", + "num-derive", + "num-traits", + "rkyv", + "ticktimer-server", + "trng", + "utralib", + "xous", + "xous-ipc 0.9.7", + "xous-names", +] + [[package]] name = "lazy_static" version = "1.4.0" diff --git a/Cargo.toml b/Cargo.toml index 5c885f4a0..d3435a022 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ default-members = [ "services/ticktimer-server", "services/xous-names", "services/keyboard", + "services/keyboard-backlight", "services/com", "services/trng", "services/gam", @@ -44,6 +45,7 @@ members = [ "xous-rs", "tools", "macros", + "services/keyboard-backlight", "services/aes-test", "services/graphics-server", "services/log-server", diff --git a/services/keyboard-backlight/Cargo.toml b/services/keyboard-backlight/Cargo.toml new file mode 100644 index 000000000..19a196100 --- /dev/null +++ b/services/keyboard-backlight/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "keyboard-backlight" +version = "0.1.0" +edition = "2021" + +# Dependency policy: fully specify dependencies to the minor version number +[dependencies] +xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4.14" +num-derive = {version = "0.3.3", default-features = false} +num-traits = {version = "0.2.14", default-features = false} +net = {path = "../net"} +xous-ipc = {path="../../xous-ipc"} +rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} +trng = {path = "../trng"} +keyboard = {path = "../keyboard"} +com = {path = "../com"} + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +default = [] \ No newline at end of file diff --git a/services/keyboard-backlight/src/main.rs b/services/keyboard-backlight/src/main.rs new file mode 100644 index 000000000..59e0ee5f6 --- /dev/null +++ b/services/keyboard-backlight/src/main.rs @@ -0,0 +1,48 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +use num_traits::*; + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +enum KbbOps { + Keypress, + TurnLightsOff, +} + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + log::info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + let kbb_sid = xns + .register_name("_Keyboard backlight_", Some(1)) + .expect("can't register server"); + + // connect to com + let com = com::Com::new(&xns).expect("cannot connect to com"); + + // connect to keyboard + let keyboard = keyboard::Keyboard::new(&xns).expect("cannot connect to keyboard server"); + keyboard.register_observer("_Keyboard backlight_", KbbOps::Keypress.to_u32().unwrap() as usize); + + //let backlight_period_on = + + loop { + let mut msg = xous::receive_message(kbb_sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(KbbOps::Keypress) => {}, + Some(KbbOps::TurnLightsOff) => { + com.set_backlight(0, 0).expect("cannot set backlight off"); + }, + _ => {}, + } + } +} + +fn turn_lights_on(com: &com::Com) { + com.set_backlight(255, 128).expect("cannot set backlight on"); + std::thread::sleep(std::time::Duration::from_secs(7)); + com.set_backlight(0, 0).expect("cannot set backlight off"); +} \ No newline at end of file diff --git a/services/keyboard/src/api.rs b/services/keyboard/src/api.rs index a37140911..58b5b5c50 100644 --- a/services/keyboard/src/api.rs +++ b/services/keyboard/src/api.rs @@ -59,6 +59,9 @@ pub(crate) enum Opcode { /// request for raw keyups/downs RegisterRawListener, + /// request for updates for *when* keyboard is pressed + RegisterKeyObserver, + /// set repeat delay, rate; both in ms SetRepeat, //(u32, u32), diff --git a/services/keyboard/src/lib.rs b/services/keyboard/src/lib.rs index de17d8ba3..bab739437 100644 --- a/services/keyboard/src/lib.rs +++ b/services/keyboard/src/lib.rs @@ -41,6 +41,16 @@ impl Keyboard { .expect("couldn't register listener"); } + pub fn register_observer(&self, server_name: &str, action_opcode: usize) { + let kr = KeyboardRegistration { + server_name: String::<64>::from_str(server_name), + listener_op_id: action_opcode + }; + let buf = Buffer::into_buf(kr).unwrap(); + buf.lend(self.conn, Opcode::RegisterKeyObserver.to_u32().unwrap()) + .expect("couldn't register listener"); + } + pub fn set_vibe(&self, enable: bool) -> Result<(), xous::Error> { let ena = if enable { 1 } diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 26620d01c..a4051f4bb 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -735,8 +735,9 @@ fn xmain() -> ! { // - graphics (if building for hosted mode) // - oqc (for factory test) // - status sub system (for setting the layout) + // - keyboard-backlight (to start backlight when a key is pressed) #[cfg(any(target_os = "none", target_os = "xous"))] - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(3)).expect("can't register server"); + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server"); #[cfg(not(any(target_os = "none", target_os = "xous")))] let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server"); log::trace!("registered with NS -- {:?}", kbd_sid); @@ -755,6 +756,8 @@ fn xmain() -> ! { let mut listener_op: Option = None; let mut raw_listener_conn: Option = None; let mut raw_listener_op: Option = None; + let mut observer_conn: Option = None; + let mut observer_op: Option = None; let mut vibe = false; let llio = llio::Llio::new(&xns); @@ -809,6 +812,21 @@ fn xmain() -> ! { } } }, + Some(Opcode::RegisterKeyObserver) => { + let buffer = unsafe{Buffer::from_memory_message(msg.body.memory_message().unwrap())}; + let kr = buffer.as_flat::().unwrap(); + match xns.request_connection_blocking(kr.server_name.as_str()) { + Ok(cid) => { + observer_conn = Some(cid); + observer_op = Some(kr.listener_op_id as usize); + } + Err(e) => { + log::error!("couldn't connect to observer: {:?}", e); + observer_conn = None; + observer_op = None; + } + } + }, Some(Opcode::SelectKeyMap) => msg_scalar_unpack!(msg, km, _, _, _, { kbd.set_map(KeyMap::from(km)) }), @@ -946,6 +964,17 @@ fn xmain() -> ! { keys[3] as u32 as usize, ) ).expect("couldn't send key codes to listener"); + + log::trace!("sending observer key"); + xous::send_message(observer_conn.unwrap(), + xous::Message::new_scalar( + observer_op.unwrap(), + 0, + 0, + 0, + 0, + ) + ).expect("couldn't send key codes to listener"); } } // as long as we have a keydown, keep pinging the loop at a high rate. this consumes more power, but keydowns are relatively rare. From 9b58fc6bf8cc98ac37f887fbd0bdcb820b702982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 20 May 2022 12:40:32 +0200 Subject: [PATCH 02/11] first somewhat working code --- .cargo/config | 3 + Cargo.lock | 31 +++++++- services/keyboard-backlight/Cargo.toml | 3 +- services/keyboard-backlight/src/main.rs | 99 +++++++++++++++++++++---- services/keyboard/src/main.rs | 41 ++++++---- xtask/src/main.rs | 1 + 6 files changed, 146 insertions(+), 32 deletions(-) diff --git a/.cargo/config b/.cargo/config index 67000f6e8..df2b29411 100644 --- a/.cargo/config +++ b/.cargo/config @@ -3,3 +3,6 @@ xtask = "run --package xtask --" # [net] # offline = true # do not access the network + +[build] +rustflags = ["--cfg", "crossbeam_no_atomic_64"] \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 4d2097e0f..410fd0d22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -568,10 +568,24 @@ dependencies = [ ] [[package]] -name = "crossbeam-channel" -version = "0.5.2" +name = "crossbeam" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e54ea8bc3fb1ee042f5aace6e3c6e025d3874866da222930f70ce62aceba0bfa" +checksum = "4ae5588f6b3c3cb05239e90bd110f257254aecd01e4635400391aeae07497845" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" dependencies = [ "cfg-if 1.0.0", "crossbeam-utils", @@ -602,6 +616,16 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f25d8400f4a7a5778f0e4e52384a48cbd9b5c495d110786187fc750075277a2" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.6" @@ -1496,6 +1520,7 @@ name = "keyboard-backlight" version = "0.1.0" dependencies = [ "com", + "crossbeam", "keyboard", "log", "log-server", diff --git a/services/keyboard-backlight/Cargo.toml b/services/keyboard-backlight/Cargo.toml index 19a196100..f20d8dddb 100644 --- a/services/keyboard-backlight/Cargo.toml +++ b/services/keyboard-backlight/Cargo.toml @@ -18,9 +18,10 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics trng = {path = "../trng"} keyboard = {path = "../keyboard"} com = {path = "../com"} +crossbeam = "0.8.1" [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} [features] -default = [] \ No newline at end of file +default = [] diff --git a/services/keyboard-backlight/src/main.rs b/services/keyboard-backlight/src/main.rs index 59e0ee5f6..820813f7e 100644 --- a/services/keyboard-backlight/src/main.rs +++ b/services/keyboard-backlight/src/main.rs @@ -1,48 +1,117 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] +use crossbeam::channel::{at, select, unbounded, Receiver, Sender}; use num_traits::*; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::RwLock; #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] enum KbbOps { Keypress, TurnLightsOff, + TurnLightsOn, + EnableAutomaticBacklight, + DisableAutomaticBacklight, +} + +enum ThreadOps { + Renew, } #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Info); + log::set_max_level(log::LevelFilter::Trace); log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); let kbb_sid = xns - .register_name("_Keyboard backlight_", Some(1)) + .register_name("_Keyboard backlight_", Some(2)) .expect("can't register server"); // connect to com let com = com::Com::new(&xns).expect("cannot connect to com"); - - // connect to keyboard - let keyboard = keyboard::Keyboard::new(&xns).expect("cannot connect to keyboard server"); - keyboard.register_observer("_Keyboard backlight_", KbbOps::Keypress.to_u32().unwrap() as usize); - //let backlight_period_on = + let keyboard = keyboard::Keyboard::new(&xns).expect("cannot connect to keyboard server"); + keyboard.register_observer( + "_Keyboard backlight_", + KbbOps::Keypress.to_u32().unwrap() as usize, + ); + + // TODO: wire this to a real activation routine + let enabled = Arc::new(RwLock::new(true)); + let (tx, rx): (Sender, Receiver) = unbounded(); + + let rx = Box::new(rx); + + let thread_already_running = Arc::new(Mutex::new(false)); + let thread_conn = xous::connect(kbb_sid).unwrap(); loop { - let mut msg = xous::receive_message(kbb_sid).unwrap(); + let msg = xous::receive_message(kbb_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { - Some(KbbOps::Keypress) => {}, + Some(KbbOps::Keypress) => { + if !*enabled.read().unwrap() { + continue + } + let mut run_lock = thread_already_running.lock().unwrap(); + match *run_lock { + true => { + log::trace!("renewing backlight timer"); + tx.send(ThreadOps::Renew).unwrap(); + continue + }, + false => { + *run_lock = true; + com.set_backlight(255, 128).expect("cannot set backlight on"); + std::thread::spawn({ + let rx = rx.clone(); + move || turn_lights_on(rx, thread_conn) + }); + }, + } + } + Some(KbbOps::TurnLightsOn) => { + log::trace!("turning lights on"); + com.set_backlight(255, 128).expect("cannot set backlight on"); + }, Some(KbbOps::TurnLightsOff) => { + log::trace!("turning lights off"); + let mut run_lock = thread_already_running.lock().unwrap(); + *run_lock = false; com.set_backlight(0, 0).expect("cannot set backlight off"); }, - _ => {}, + Some(KbbOps::EnableAutomaticBacklight) => { + *enabled.write().unwrap() = true; + } + Some(KbbOps::DisableAutomaticBacklight) => { + *enabled.write().unwrap() = false; + } + _ => {} } } } -fn turn_lights_on(com: &com::Com) { - com.set_backlight(255, 128).expect("cannot set backlight on"); - std::thread::sleep(std::time::Duration::from_secs(7)); - com.set_backlight(0, 0).expect("cannot set backlight off"); -} \ No newline at end of file +fn turn_lights_on(rx: Box>, cid: xous::CID) { + let standard_duration = std::time::Duration::from_secs(10); + + let mut timeout = std::time::Instant::now() + standard_duration; + + let mut total_waited = 0; + + loop { + select! { + recv(rx) -> _ => { + timeout = std::time::Instant::now() + standard_duration; + total_waited += 1 + }, + recv(at(timeout)) -> _ => { + log::trace!("timeout finished, total re-waited {}, returning!", total_waited); + xous::send_message(cid, xous::Message::new_scalar(KbbOps::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap(); + break; + } + }; + } +} diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index a4051f4bb..937e3fc01 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -737,9 +737,9 @@ fn xmain() -> ! { // - status sub system (for setting the layout) // - keyboard-backlight (to start backlight when a key is pressed) #[cfg(any(target_os = "none", target_os = "xous"))] - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server"); + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(5)).expect("can't register server"); #[cfg(not(any(target_os = "none", target_os = "xous")))] - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server"); + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(5)).expect("can't register server"); log::trace!("registered with NS -- {:?}", kbd_sid); // Create a new kbd object @@ -911,6 +911,19 @@ fn xmain() -> ! { ).unwrap(); } } + + if observer_conn.is_some() && observer_op.is_some() { + log::trace!("sending observer key"); + xous::send_message(observer_conn.unwrap(), + xous::Message::new_scalar( + observer_op.unwrap(), + 0, + 0, + 0, + 0, + ) + ).expect("couldn't send key codes to listener"); + } }), Some(Opcode::HandlerTrigger) => { let rawstates = kbd.update(); @@ -933,6 +946,19 @@ fn xmain() -> ! { buf.lend(raw_listener_conn.unwrap(), raw_listener_op.unwrap()).expect("couldn't send raw scancodes"); } + if observer_conn.is_some() && observer_op.is_some() { + log::trace!("sending observer key"); + xous::send_message(observer_conn.unwrap(), + xous::Message::new_scalar( + observer_op.unwrap(), + 0, + 0, + 0, + 0, + ) + ).expect("couldn't send key codes to listener"); + } + // interpret scancodes // the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state let kc: Vec = match kbd.get_map() { @@ -964,17 +990,6 @@ fn xmain() -> ! { keys[3] as u32 as usize, ) ).expect("couldn't send key codes to listener"); - - log::trace!("sending observer key"); - xous::send_message(observer_conn.unwrap(), - xous::Message::new_scalar( - observer_op.unwrap(), - 0, - 0, - 0, - 0, - ) - ).expect("couldn't send key codes to listener"); } } // as long as we have a keydown, keep pinging the loop at a high rate. this consumes more power, but keydowns are relatively rare. diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 86519a171..96dffe613 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -58,6 +58,7 @@ fn main() -> Result<(), Box> { "com", "xous-names", "keyboard", + "keyboard-backlight", "trng", "llio", "susres", From 4931e00d60d9f18b0413c621357ae92f2a144196 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 21 May 2022 01:34:35 +0800 Subject: [PATCH 03/11] advance timer state by +1 ms on suspend to avoid double-interrupts on resume Issue #159 may be caused by queueing a connection to respond to when the timer expires, but if the timer expires twice then it tries to respond to a null connection id. And if it goes to suspend in the same millisecond as it services the condvar, then it'll reissue the interrupt when it comes back from suspend. --- services/susres/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs index 7b9e32a8a..10a0074e7 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -243,7 +243,7 @@ mod implementation { self.stored_time = Some( (self.csr.r(utra::susres::TIME0) as u64 | (self.csr.r(utra::susres::TIME1) as u64) << 32) - + 0 // a placeholder in case we need to advance time on save + + 1 // a placeholder in case we need to advance time on save ); #[cfg(feature = "debugprint")] println!("Stored time: {}", self.stored_time.unwrap()); From d2a3b252f07943fe3d77a6522ed0ba333fb20f54 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 May 2022 17:27:05 +0800 Subject: [PATCH 04/11] potential fix for #162 see issue for discussion --- services/ticktimer-server/src/main.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index 358ce703b..e41d68ade 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -625,16 +625,15 @@ fn xmain() -> ! { let sender = args.arg1; let request_kind = args.arg2; let condvar = args.arg3; - let sender_pid = msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32; + let sender_pid = xous::MessageSender::from_usize(sender).pid(); // If we're being asked to recalculate due to a timeout expiring, drop the sent // message from the `entries` list. - if sender_pid == xous::process::id() - && (request_kind == RequestKind::Timeout as usize) + if (request_kind == RequestKind::Timeout as usize) && (sender > 0) { let entries = notify_hash - .entry(msg.sender.pid()) + .entry(sender_pid) .or_default() .entry(condvar) .or_default(); @@ -648,6 +647,7 @@ fn xmain() -> ! { if let Some(idx) = idx { entries.remove(idx); } + // log::trace!("new entries for PID {:?}/condvar {:08x}: {:?}", sender_pid, condvar, notify_hash.get(&sender_pid).unwrap().get(&condvar)); } } recalculate_sleep(&mut ticktimer, &mut sleep_heap, None); @@ -771,6 +771,7 @@ fn xmain() -> ! { .or_default() .push_back(msg.sender); + // log::trace!("New waiting senders: {:?}", notify_hash.get(&pid).unwrap().get(&condvar)); continue; } else { info!( From 9af6c7257d8443e22d7e7260bcdaea85f1663665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 27 May 2022 09:35:10 +0000 Subject: [PATCH 05/11] middle commit --- services/keyboard-backlight/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/keyboard-backlight/src/main.rs b/services/keyboard-backlight/src/main.rs index 820813f7e..727393d1d 100644 --- a/services/keyboard-backlight/src/main.rs +++ b/services/keyboard-backlight/src/main.rs @@ -39,7 +39,7 @@ fn xmain() -> ! { "_Keyboard backlight_", KbbOps::Keypress.to_u32().unwrap() as usize, ); - + // TODO: wire this to a real activation routine let enabled = Arc::new(RwLock::new(true)); let (tx, rx): (Sender, Receiver) = unbounded(); From 7985ad9a95e0265dc941453f2f7129162bac2043 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Wed, 8 Jun 2022 12:08:49 +0200 Subject: [PATCH 06/11] make the thing compile --- Cargo.toml | 1 - services/keyboard-backlight/src/main.rs | 3 +-- services/keyboard/src/api.rs | 16 ++++++++-------- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4751b19b0..70612ceb6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,6 @@ members = [ "xous-ipc", "xous-rs", "tools", - "macros", "services/keyboard-backlight", "services/aes-test", "services/graphics-server", diff --git a/services/keyboard-backlight/src/main.rs b/services/keyboard-backlight/src/main.rs index 727393d1d..807f20514 100644 --- a/services/keyboard-backlight/src/main.rs +++ b/services/keyboard-backlight/src/main.rs @@ -20,8 +20,7 @@ enum ThreadOps { Renew, } -#[xous::xous_main] -fn xmain() -> ! { +fn main() -> ! { log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Trace); log::info!("my PID is {}", xous::process::id()); diff --git a/services/keyboard/src/api.rs b/services/keyboard/src/api.rs index a88a13f36..37fa41a4e 100644 --- a/services/keyboard/src/api.rs +++ b/services/keyboard/src/api.rs @@ -61,28 +61,28 @@ pub(crate) enum Opcode { RegisterRawListener = 3, /// request for updates for *when* keyboard is pressed - RegisterKeyObserver, + RegisterKeyObserver = 4, /// set repeat delay, rate; both in ms - SetRepeat = 4, //(u32, u32), + SetRepeat = 5, //(u32, u32), /// set chording interval (how long to wait for all keydowns to happen before interpreting as a chord), in ms (for braille keyboards) - SetChordInterval = 5, //(u32), + SetChordInterval = 6, //(u32), /// used by host mode emulation and debug UART to inject keys - InjectKey = 6, //(char), + InjectKey = 7, //(char), /// used by the interrupt handler to transfer results to the main loop - HandlerTrigger = 7, + HandlerTrigger = 8, /// used to turn keyboard vibrate on and off - Vibe = 8, + Vibe = 9, /// a blocking key listener - blocks until a key is hit - BlockingKeyListener = 9, + BlockingKeyListener = 10, /// Suspend/resume callback - SuspendResume = 10, + SuspendResume = 11, } // this structure is used to register a keyboard listener. Currently, we only accept From 4115c9b2cd05d1bcec606ab0c5f40be512ba21f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 10 Jun 2022 14:33:33 +0200 Subject: [PATCH 07/11] feat: wire keyboard-backlight to status menu --- Cargo.lock | 1 + services/keyboard-backlight/src/api.rs | 11 ++++++ services/keyboard-backlight/src/lib.rs | 44 ++++++++++++++++++++++++ services/keyboard-backlight/src/main.rs | 45 ++++++++++++++----------- services/status/Cargo.toml | 1 + services/status/locales/i18n.json | 8 +++++ services/status/src/main.rs | 4 ++- services/status/src/mainmenu.rs | 21 +++++++++++- 8 files changed, 114 insertions(+), 21 deletions(-) create mode 100644 services/keyboard-backlight/src/api.rs create mode 100644 services/keyboard-backlight/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 2d9f48e9f..c77b2fd35 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3262,6 +3262,7 @@ dependencies = [ "gam", "graphics-server", "keyboard", + "keyboard-backlight", "llio", "locales", "log", diff --git a/services/keyboard-backlight/src/api.rs b/services/keyboard-backlight/src/api.rs new file mode 100644 index 000000000..d8b9789df --- /dev/null +++ b/services/keyboard-backlight/src/api.rs @@ -0,0 +1,11 @@ +pub const KBB_SERVER_NAME: &str = "_Keyboard backlight_"; + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub enum KbbOps { + Keypress, + TurnLightsOff, + TurnLightsOn, + EnableAutomaticBacklight, + DisableAutomaticBacklight, + Status, +} \ No newline at end of file diff --git a/services/keyboard-backlight/src/lib.rs b/services/keyboard-backlight/src/lib.rs new file mode 100644 index 000000000..263d2f6ae --- /dev/null +++ b/services/keyboard-backlight/src/lib.rs @@ -0,0 +1,44 @@ +pub mod api; +use api::*; + +use num_traits::*; + + +#[derive(Debug)] +pub struct KeyboardBacklight { + conn: xous::CID, +} +impl KeyboardBacklight { + pub fn new(xns: &xous_names::XousNames) -> Result { + let conn = xns.request_connection_blocking(api::KBB_SERVER_NAME).expect("Can't connect to KBD"); + Ok(KeyboardBacklight { + conn, + }) + } + + pub fn cid(&self) -> xous::CID { + self.conn + } + + pub fn enabled(&self) -> Result { + match xous::send_message(self.conn, + xous::Message::new_blocking_scalar(KbbOps::Status.to_usize().unwrap(), + 0, + 0, + 0, + 0 + ) + ) { + Ok(xous::Result::Scalar1(last_state)) => { + if last_state == 1 { + Ok(true) + } else { + Ok(false) + } + } + _ => { + Err(xous::Error::InternalError) + } + } + } +} \ No newline at end of file diff --git a/services/keyboard-backlight/src/main.rs b/services/keyboard-backlight/src/main.rs index 807f20514..9e128050d 100644 --- a/services/keyboard-backlight/src/main.rs +++ b/services/keyboard-backlight/src/main.rs @@ -1,23 +1,17 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] +mod api; +use api::*; + use crossbeam::channel::{at, select, unbounded, Receiver, Sender}; use num_traits::*; use std::sync::Arc; use std::sync::Mutex; -use std::sync::RwLock; - -#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -enum KbbOps { - Keypress, - TurnLightsOff, - TurnLightsOn, - EnableAutomaticBacklight, - DisableAutomaticBacklight, -} enum ThreadOps { Renew, + Stop, } fn main() -> ! { @@ -27,7 +21,7 @@ fn main() -> ! { let xns = xous_names::XousNames::new().unwrap(); let kbb_sid = xns - .register_name("_Keyboard backlight_", Some(2)) + .register_name(api::KBB_SERVER_NAME, Some(2)) .expect("can't register server"); // connect to com @@ -39,8 +33,7 @@ fn main() -> ! { KbbOps::Keypress.to_u32().unwrap() as usize, ); - // TODO: wire this to a real activation routine - let enabled = Arc::new(RwLock::new(true)); + let enabled = Arc::new(Mutex::new(false)); let (tx, rx): (Sender, Receiver) = unbounded(); let rx = Box::new(rx); @@ -52,7 +45,8 @@ fn main() -> ! { let msg = xous::receive_message(kbb_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { Some(KbbOps::Keypress) => { - if !*enabled.read().unwrap() { + if !*enabled.lock().unwrap() { + log::trace!("ignoring keypress, automatic backlight is disabled"); continue } let mut run_lock = thread_already_running.lock().unwrap(); @@ -83,11 +77,16 @@ fn main() -> ! { com.set_backlight(0, 0).expect("cannot set backlight off"); }, Some(KbbOps::EnableAutomaticBacklight) => { - *enabled.write().unwrap() = true; + *enabled.lock().unwrap() = true; } Some(KbbOps::DisableAutomaticBacklight) => { - *enabled.write().unwrap() = false; + *enabled.lock().unwrap() = false; + tx.send(ThreadOps::Stop).unwrap(); } + Some(KbbOps::Status) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { + let status = *enabled.lock().unwrap(); + xous::return_scalar(msg.sender, status.into()).unwrap(); + }), _ => {} } } @@ -102,9 +101,17 @@ fn turn_lights_on(rx: Box>, cid: xous::CID) { loop { select! { - recv(rx) -> _ => { - timeout = std::time::Instant::now() + standard_duration; - total_waited += 1 + recv(rx) -> op => { + match op.unwrap() { + ThreadOps::Renew => { + timeout = std::time::Instant::now() + standard_duration; + total_waited += 1; + }, + ThreadOps::Stop => { + log::trace!("received Stop op, killing background backlight thread"); + return; + }, + } }, recv(at(timeout)) -> _ => { log::trace!("timeout finished, total re-waited {}, returning!", total_waited); diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index 92aefdb7e..bf841d444 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -27,6 +27,7 @@ pddb = {path = "../pddb"} net = {path = "../net"} keyboard = {path = "../keyboard"} usb-device-xous = {path="../usb-device-xous"} +keyboard-backlight = {path = "../keyboard-backlight"} num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 915c5a702..e0325ce54 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -90,6 +90,14 @@ "zh": "背光关闭", "en-tts": "🔇" }, + "mainmenu.autobacklighton": { + "en": "Automatic backlight on", + "en-tts": "🔇" + }, + "mainmenu.autobacklightoff": { + "en": "Automatic backlight off", + "en-tts": "🔇" + }, "mainmenu.init_keys": { "en": "Initialize root keys", "ja": "ルートキーの初期化", diff --git a/services/status/src/main.rs b/services/status/src/main.rs index bf042c287..c37920975 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -332,8 +332,10 @@ fn main() -> ! { // used to show notifications, e.g. can't sleep while power is engaged. let modals = modals::Modals::new(&xns).unwrap(); + let keyboard_backlight = keyboard_backlight::KeyboardBacklight::new(&xns).unwrap(); + log::debug!("starting main menu thread"); - create_main_menu(keys.clone(), xous::connect(status_sid).unwrap(), &com, time_cid); + create_main_menu(keys.clone(), xous::connect(status_sid).unwrap(), &com, time_cid, &keyboard_backlight); create_app_menu(xous::connect(status_sid).unwrap()); let kbd_mgr = xous::create_server().unwrap(); let kbd_menumatic = create_kbd_menu(xous::connect(status_sid).unwrap(), kbd_mgr); diff --git a/services/status/src/mainmenu.rs b/services/status/src/mainmenu.rs index e53719d30..0111e4cfe 100644 --- a/services/status/src/mainmenu.rs +++ b/services/status/src/mainmenu.rs @@ -4,11 +4,12 @@ use root_keys::RootKeys; use std::sync::{Arc, Mutex}; use xous_ipc::String; use num_traits::*; +use keyboard_backlight::api::*; use crate::StatusOpcode; #[allow(unused_variables)] // quiets a warning about unused com that is emitted in tts config. Would be nice to make this more targeted... -pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: &com::Com, time_ux_conn: xous::CID) { +pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: &com::Com, time_ux_conn: xous::CID, kbb: &keyboard_backlight::KeyboardBacklight) { let key_conn = keys.lock().unwrap().conn(); let mut menuitems = Vec::::new(); @@ -32,6 +33,24 @@ pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: close_on_select: true, }); + #[cfg(not(feature="tts"))] + menuitems.push(MenuItem { + name: String::from_str(t!("mainmenu.autobacklighton", xous::LANG)), + action_conn: Some(kbb.cid()), + action_opcode: KbbOps::EnableAutomaticBacklight.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + + #[cfg(not(feature="tts"))] + menuitems.push(MenuItem { + name: String::from_str(t!("mainmenu.autobacklightoff", xous::LANG)), + action_conn: Some(kbb.cid()), + action_opcode: KbbOps::DisableAutomaticBacklight.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + menuitems.push(MenuItem { name: String::from_str(t!("mainmenu.sleep", xous::LANG)), action_conn: Some(status_conn), From 1ebf3316e7909b9358dddee3f549cb1bf393face Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 10 Jun 2022 17:14:38 +0200 Subject: [PATCH 08/11] feat: wire keyboard backlight controls to main menu --- services/keyboard-backlight/src/lib.rs | 22 +++++++++ services/status/src/main.rs | 63 +++++++++++++++++++++++++- services/status/src/mainmenu.rs | 25 +++++----- 3 files changed, 96 insertions(+), 14 deletions(-) diff --git a/services/keyboard-backlight/src/lib.rs b/services/keyboard-backlight/src/lib.rs index 263d2f6ae..0703279da 100644 --- a/services/keyboard-backlight/src/lib.rs +++ b/services/keyboard-backlight/src/lib.rs @@ -19,6 +19,28 @@ impl KeyboardBacklight { pub fn cid(&self) -> xous::CID { self.conn } + + pub fn enable(&self) { + xous::send_message(self.conn, + xous::Message::new_scalar(KbbOps::EnableAutomaticBacklight.to_usize().unwrap(), + 0, + 0, + 0, + 0 + ) + ).map(|_|()).unwrap(); + } + + pub fn disable(&self) { + xous::send_message(self.conn, + xous::Message::new_scalar(KbbOps::DisableAutomaticBacklight.to_usize().unwrap(), + 0, + 0, + 0, + 0 + ) + ).map(|_|()).unwrap(); + } pub fn enabled(&self) -> Result { match xous::send_message(self.conn, diff --git a/services/status/src/main.rs b/services/status/src/main.rs index c37920975..cf84aefbf 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -56,6 +56,12 @@ pub(crate) enum StatusOpcode { /// Set the keyboard map SetKeyboard, + /// Sets automatic backlight on + EnableAutomaticBacklight, + + /// Sets automatic backlight off + DisableAutomaticBacklight, + /// Suspend handler from the main menu TrySuspend, /// Ship mode handler for the main menu @@ -335,7 +341,9 @@ fn main() -> ! { let keyboard_backlight = keyboard_backlight::KeyboardBacklight::new(&xns).unwrap(); log::debug!("starting main menu thread"); - create_main_menu(keys.clone(), xous::connect(status_sid).unwrap(), &com, time_cid, &keyboard_backlight); + let main_menu_sid = xous::create_server().unwrap(); + let status_cid = xous::connect(status_sid).unwrap(); + let menu_manager = create_main_menu(keys.clone(), main_menu_sid, status_cid, &com, time_cid); create_app_menu(xous::connect(status_sid).unwrap()); let kbd_mgr = xous::create_server().unwrap(); let kbd_menumatic = create_kbd_menu(xous::connect(status_sid).unwrap(), kbd_mgr); @@ -366,6 +374,59 @@ fn main() -> ! { let msg = xous::receive_message(status_sid).unwrap(); log::trace!("|status: Message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { + // TODO: handle tts + Some(StatusOpcode::EnableAutomaticBacklight) => { + // first: enable automatic backlight. + keyboard_backlight.enable(); + + // second: delete the first three elements off the menu + menu_manager.delete_item(t!("mainmenu.backlighton", xous::LANG)); + menu_manager.delete_item(t!("mainmenu.backlightoff", xous::LANG)); + menu_manager.delete_item(t!("mainmenu.autobacklighton", xous::LANG)); + + // third: add a "disable automatic backlight element" + menu_manager.insert_item(gam::MenuItem { + name: xous_ipc::String::from_str(t!("mainmenu.autobacklightoff", xous::LANG)), + action_conn: Some(status_cid), + action_opcode: StatusOpcode::DisableAutomaticBacklight.to_u32().unwrap(), + action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }, 0); + } + Some(StatusOpcode::DisableAutomaticBacklight) => { + // first: disable automatic backlight. + keyboard_backlight.disable(); + + // second: delete the first element off the menu. + menu_manager.delete_item(t!("mainmenu.autobacklightoff", xous::LANG)); + + // third: construct an array of the new elements to add to the menu. + let new_elems = [ + gam::MenuItem { + name: xous_ipc::String::from_str(t!("mainmenu.backlighton", xous::LANG)), + action_conn: Some(com.conn()), + action_opcode: com.getop_backlight(), + action_payload: gam::MenuPayload::Scalar([191 >> 3, 191 >> 3, 0, 0]), + close_on_select: true, + }, + gam::MenuItem { + name: xous_ipc::String::from_str(t!("mainmenu.backlightoff", xous::LANG)), + action_conn: Some(com.conn()), + action_opcode: com.getop_backlight(), + action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }, + gam::MenuItem { + name: xous_ipc::String::from_str(t!("mainmenu.autobacklighton", xous::LANG)), + action_conn: Some(status_cid), + action_opcode: StatusOpcode::EnableAutomaticBacklight.to_u32().unwrap(), + action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + } + ]; + + new_elems.iter().enumerate().for_each(|(index, element)| {let _ = menu_manager.insert_item(*element, index);}); + } Some(StatusOpcode::BattStats) => msg_scalar_unpack!(msg, lo, hi, _, _, { stats = [lo, hi].into(); battstats_tv.clear_str(); diff --git a/services/status/src/mainmenu.rs b/services/status/src/mainmenu.rs index 0111e4cfe..30d96c1c3 100644 --- a/services/status/src/mainmenu.rs +++ b/services/status/src/mainmenu.rs @@ -4,12 +4,11 @@ use root_keys::RootKeys; use std::sync::{Arc, Mutex}; use xous_ipc::String; use num_traits::*; -use keyboard_backlight::api::*; use crate::StatusOpcode; #[allow(unused_variables)] // quiets a warning about unused com that is emitted in tts config. Would be nice to make this more targeted... -pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: &com::Com, time_ux_conn: xous::CID, kbb: &keyboard_backlight::KeyboardBacklight) { +pub fn create_main_menu(keys: Arc>, menu_management_sid: xous::SID, status_conn: xous::CID, com: &com::Com, time_ux_conn: xous::CID) -> MenuMatic { let key_conn = keys.lock().unwrap().conn(); let mut menuitems = Vec::::new(); @@ -36,20 +35,20 @@ pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: #[cfg(not(feature="tts"))] menuitems.push(MenuItem { name: String::from_str(t!("mainmenu.autobacklighton", xous::LANG)), - action_conn: Some(kbb.cid()), - action_opcode: KbbOps::EnableAutomaticBacklight.to_u32().unwrap(), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::EnableAutomaticBacklight.to_u32().unwrap(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); - #[cfg(not(feature="tts"))] - menuitems.push(MenuItem { - name: String::from_str(t!("mainmenu.autobacklightoff", xous::LANG)), - action_conn: Some(kbb.cid()), - action_opcode: KbbOps::DisableAutomaticBacklight.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([0, 0, 0, 0]), - close_on_select: true, - }); + // #[cfg(not(feature="tts"))] + // menuitems.push(MenuItem { + // name: String::from_str(t!("mainmenu.autobacklightoff", xous::LANG)), + // action_conn: Some(kbb.cid()), + // action_opcode: KbbOps::DisableAutomaticBacklight.to_u32().unwrap(), + // action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + // close_on_select: true, + // }); menuitems.push(MenuItem { name: String::from_str(t!("mainmenu.sleep", xous::LANG)), @@ -147,5 +146,5 @@ pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: close_on_select: true, }); - menu_matic(menuitems, MAIN_MENU_NAME, None); + menu_matic(menuitems, MAIN_MENU_NAME, Some(menu_management_sid)).unwrap() } From d7eb53664ef96baee93a18d47a65c238a53c5221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Mon, 13 Jun 2022 16:33:44 +0200 Subject: [PATCH 09/11] chore: move automatic backlight in status crate Let's not use a precious process just for some a backlight effect :-) --- Cargo.lock | 23 +---- Cargo.toml | 2 - services/keyboard-backlight/Cargo.toml | 27 ------ services/keyboard-backlight/src/api.rs | 11 --- services/keyboard-backlight/src/lib.rs | 66 ------------- services/keyboard-backlight/src/main.rs | 123 ------------------------ services/status/Cargo.toml | 2 +- services/status/src/main.rs | 113 +++++++++++++++++++--- xtask/src/main.rs | 1 - 9 files changed, 104 insertions(+), 264 deletions(-) delete mode 100644 services/keyboard-backlight/Cargo.toml delete mode 100644 services/keyboard-backlight/src/api.rs delete mode 100644 services/keyboard-backlight/src/lib.rs delete mode 100644 services/keyboard-backlight/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index bdbae79aa..425e47e25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1813,27 +1813,6 @@ dependencies = [ "xous-names", ] -[[package]] -name = "keyboard-backlight" -version = "0.1.0" -dependencies = [ - "com", - "crossbeam", - "keyboard", - "log", - "log-server", - "net", - "num-derive", - "num-traits", - "rkyv", - "ticktimer-server", - "trng", - "utralib", - "xous", - "xous-ipc 0.9.7", - "xous-names", -] - [[package]] name = "lazy_static" version = "1.4.0" @@ -3270,10 +3249,10 @@ dependencies = [ "chrono", "com", "content-plugin-api", + "crossbeam", "gam", "graphics-server", "keyboard", - "keyboard-backlight", "llio", "locales", "log", diff --git a/Cargo.toml b/Cargo.toml index 70612ceb6..6424ce93c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,6 @@ default-members = [ "services/ticktimer-server", "services/xous-names", "services/keyboard", - "services/keyboard-backlight", "services/com", "services/trng", "services/gam", @@ -35,7 +34,6 @@ members = [ "xous-ipc", "xous-rs", "tools", - "services/keyboard-backlight", "services/aes-test", "services/graphics-server", "services/log-server", diff --git a/services/keyboard-backlight/Cargo.toml b/services/keyboard-backlight/Cargo.toml deleted file mode 100644 index f20d8dddb..000000000 --- a/services/keyboard-backlight/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "keyboard-backlight" -version = "0.1.0" -edition = "2021" - -# Dependency policy: fully specify dependencies to the minor version number -[dependencies] -xous = { path = "../../xous-rs" } -log-server = { path = "../log-server" } -ticktimer-server = { path = "../ticktimer-server" } -xous-names = { path = "../xous-names" } -log = "0.4.14" -num-derive = {version = "0.3.3", default-features = false} -num-traits = {version = "0.2.14", default-features = false} -net = {path = "../net"} -xous-ipc = {path="../../xous-ipc"} -rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} -trng = {path = "../trng"} -keyboard = {path = "../keyboard"} -com = {path = "../com"} -crossbeam = "0.8.1" - -[target.'cfg(not(any(windows,unix)))'.dependencies] -utralib = { path = "../../utralib"} - -[features] -default = [] diff --git a/services/keyboard-backlight/src/api.rs b/services/keyboard-backlight/src/api.rs deleted file mode 100644 index d8b9789df..000000000 --- a/services/keyboard-backlight/src/api.rs +++ /dev/null @@ -1,11 +0,0 @@ -pub const KBB_SERVER_NAME: &str = "_Keyboard backlight_"; - -#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -pub enum KbbOps { - Keypress, - TurnLightsOff, - TurnLightsOn, - EnableAutomaticBacklight, - DisableAutomaticBacklight, - Status, -} \ No newline at end of file diff --git a/services/keyboard-backlight/src/lib.rs b/services/keyboard-backlight/src/lib.rs deleted file mode 100644 index 0703279da..000000000 --- a/services/keyboard-backlight/src/lib.rs +++ /dev/null @@ -1,66 +0,0 @@ -pub mod api; -use api::*; - -use num_traits::*; - - -#[derive(Debug)] -pub struct KeyboardBacklight { - conn: xous::CID, -} -impl KeyboardBacklight { - pub fn new(xns: &xous_names::XousNames) -> Result { - let conn = xns.request_connection_blocking(api::KBB_SERVER_NAME).expect("Can't connect to KBD"); - Ok(KeyboardBacklight { - conn, - }) - } - - pub fn cid(&self) -> xous::CID { - self.conn - } - - pub fn enable(&self) { - xous::send_message(self.conn, - xous::Message::new_scalar(KbbOps::EnableAutomaticBacklight.to_usize().unwrap(), - 0, - 0, - 0, - 0 - ) - ).map(|_|()).unwrap(); - } - - pub fn disable(&self) { - xous::send_message(self.conn, - xous::Message::new_scalar(KbbOps::DisableAutomaticBacklight.to_usize().unwrap(), - 0, - 0, - 0, - 0 - ) - ).map(|_|()).unwrap(); - } - - pub fn enabled(&self) -> Result { - match xous::send_message(self.conn, - xous::Message::new_blocking_scalar(KbbOps::Status.to_usize().unwrap(), - 0, - 0, - 0, - 0 - ) - ) { - Ok(xous::Result::Scalar1(last_state)) => { - if last_state == 1 { - Ok(true) - } else { - Ok(false) - } - } - _ => { - Err(xous::Error::InternalError) - } - } - } -} \ No newline at end of file diff --git a/services/keyboard-backlight/src/main.rs b/services/keyboard-backlight/src/main.rs deleted file mode 100644 index 9e128050d..000000000 --- a/services/keyboard-backlight/src/main.rs +++ /dev/null @@ -1,123 +0,0 @@ -#![cfg_attr(target_os = "none", no_std)] -#![cfg_attr(target_os = "none", no_main)] - -mod api; -use api::*; - -use crossbeam::channel::{at, select, unbounded, Receiver, Sender}; -use num_traits::*; -use std::sync::Arc; -use std::sync::Mutex; - -enum ThreadOps { - Renew, - Stop, -} - -fn main() -> ! { - log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Trace); - log::info!("my PID is {}", xous::process::id()); - - let xns = xous_names::XousNames::new().unwrap(); - let kbb_sid = xns - .register_name(api::KBB_SERVER_NAME, Some(2)) - .expect("can't register server"); - - // connect to com - let com = com::Com::new(&xns).expect("cannot connect to com"); - - let keyboard = keyboard::Keyboard::new(&xns).expect("cannot connect to keyboard server"); - keyboard.register_observer( - "_Keyboard backlight_", - KbbOps::Keypress.to_u32().unwrap() as usize, - ); - - let enabled = Arc::new(Mutex::new(false)); - let (tx, rx): (Sender, Receiver) = unbounded(); - - let rx = Box::new(rx); - - let thread_already_running = Arc::new(Mutex::new(false)); - let thread_conn = xous::connect(kbb_sid).unwrap(); - - loop { - let msg = xous::receive_message(kbb_sid).unwrap(); - match FromPrimitive::from_usize(msg.body.id()) { - Some(KbbOps::Keypress) => { - if !*enabled.lock().unwrap() { - log::trace!("ignoring keypress, automatic backlight is disabled"); - continue - } - let mut run_lock = thread_already_running.lock().unwrap(); - match *run_lock { - true => { - log::trace!("renewing backlight timer"); - tx.send(ThreadOps::Renew).unwrap(); - continue - }, - false => { - *run_lock = true; - com.set_backlight(255, 128).expect("cannot set backlight on"); - std::thread::spawn({ - let rx = rx.clone(); - move || turn_lights_on(rx, thread_conn) - }); - }, - } - } - Some(KbbOps::TurnLightsOn) => { - log::trace!("turning lights on"); - com.set_backlight(255, 128).expect("cannot set backlight on"); - }, - Some(KbbOps::TurnLightsOff) => { - log::trace!("turning lights off"); - let mut run_lock = thread_already_running.lock().unwrap(); - *run_lock = false; - com.set_backlight(0, 0).expect("cannot set backlight off"); - }, - Some(KbbOps::EnableAutomaticBacklight) => { - *enabled.lock().unwrap() = true; - } - Some(KbbOps::DisableAutomaticBacklight) => { - *enabled.lock().unwrap() = false; - tx.send(ThreadOps::Stop).unwrap(); - } - Some(KbbOps::Status) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { - let status = *enabled.lock().unwrap(); - xous::return_scalar(msg.sender, status.into()).unwrap(); - }), - _ => {} - } - } -} - -fn turn_lights_on(rx: Box>, cid: xous::CID) { - let standard_duration = std::time::Duration::from_secs(10); - - let mut timeout = std::time::Instant::now() + standard_duration; - - let mut total_waited = 0; - - loop { - select! { - recv(rx) -> op => { - match op.unwrap() { - ThreadOps::Renew => { - timeout = std::time::Instant::now() + standard_duration; - total_waited += 1; - }, - ThreadOps::Stop => { - log::trace!("received Stop op, killing background backlight thread"); - return; - }, - } - }, - recv(at(timeout)) -> _ => { - log::trace!("timeout finished, total re-waited {}, returning!", total_waited); - xous::send_message(cid, xous::Message::new_scalar(KbbOps::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap(); - break; - } - }; - } -} diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index ff56824d7..1148ce353 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -27,7 +27,6 @@ pddb = {path = "../pddb"} net = {path = "../net"} keyboard = {path = "../keyboard"} usb-device-xous = {path="../usb-device-xous"} -keyboard-backlight = {path = "../keyboard-backlight"} num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} @@ -35,6 +34,7 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics chrono = {version = "0.4.19", default-features = false, features = ["std"]} sntpc = {version = "0.3.1"} #, features = ["log"] +crossbeam = "0.8.1" [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} diff --git a/services/status/src/main.rs b/services/status/src/main.rs index cf84aefbf..84cdbf65d 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -19,6 +19,7 @@ use graphics_server::api::GlyphStyle; use locales::t; use gam::{GamObjectList, GamObjectType}; use chrono::prelude::*; +use crossbeam::channel::{at, select, unbounded, Receiver, Sender}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -31,6 +32,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_"; +const SERVER_NAME_STATUS: &str = "_Status_"; #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum StatusOpcode { @@ -56,10 +58,15 @@ pub(crate) enum StatusOpcode { /// Set the keyboard map SetKeyboard, - /// Sets automatic backlight on + /// Tells keyboard watching thread that a new keypress happened. + Keypress, + /// Turns backlight off. + TurnLightsOff, + /// Turns backlight on. + TurnLightsOn, + /// Enables automatic backlight handling. EnableAutomaticBacklight, - - /// Sets automatic backlight off + /// Disables automatic backlight handling. DisableAutomaticBacklight, /// Suspend handler from the main menu @@ -143,7 +150,8 @@ fn main() -> ! { log::debug!("|status: registering GAM|status thread"); - let status_sid = xous::create_server().unwrap(); // completely private to this crate + // allow only one connection, from keyboard to us. + let status_sid = xns.register_name(SERVER_NAME_STATUS, Some(1)).unwrap(); // create a connection for callback hooks let cb_cid = xous::connect(status_sid).unwrap(); unsafe { CB_TO_MAIN_CONN = Some(cb_cid) }; @@ -338,8 +346,6 @@ fn main() -> ! { // used to show notifications, e.g. can't sleep while power is engaged. let modals = modals::Modals::new(&xns).unwrap(); - let keyboard_backlight = keyboard_backlight::KeyboardBacklight::new(&xns).unwrap(); - log::debug!("starting main menu thread"); let main_menu_sid = xous::create_server().unwrap(); let status_cid = xous::connect(status_sid).unwrap(); @@ -369,15 +375,28 @@ fn main() -> ! { #[cfg(any(target_os = "none", target_os = "xous"))] llio.clear_wakeup_alarm().unwrap(); // this is here to clear any wake-up alarms that were set by a prior coldboot command + // Automatic backlight-related variables. + kbd.register_observer( + SERVER_NAME_STATUS, + StatusOpcode::Keypress.to_u32().unwrap() as usize, + ); + + let enabled = Arc::new(Mutex::new(false)); + let (tx, rx): (Sender, Receiver) = unbounded(); + + let rx = Box::new(rx); + + let thread_already_running = Arc::new(Mutex::new(false)); + let thread_conn = xous::connect(status_sid).unwrap(); + pump_run.store(true, Ordering::Relaxed); // start status thread updating loop { let msg = xous::receive_message(status_sid).unwrap(); log::trace!("|status: Message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { // TODO: handle tts - Some(StatusOpcode::EnableAutomaticBacklight) => { - // first: enable automatic backlight. - keyboard_backlight.enable(); + Some(StatusOpcode::EnableAutomaticBacklight) => { + *enabled.lock().unwrap() = true; // second: delete the first three elements off the menu menu_manager.delete_item(t!("mainmenu.backlighton", xous::LANG)); @@ -394,8 +413,8 @@ fn main() -> ! { }, 0); } Some(StatusOpcode::DisableAutomaticBacklight) => { - // first: disable automatic backlight. - keyboard_backlight.disable(); + *enabled.lock().unwrap() = false; + tx.send(BacklightThreadOps::Stop).unwrap(); // second: delete the first element off the menu. menu_manager.delete_item(t!("mainmenu.autobacklightoff", xous::LANG)); @@ -719,6 +738,40 @@ fn main() -> ! { com.power_off_soc().unwrap(); } }, + + Some(StatusOpcode::Keypress) => { + if !*enabled.lock().unwrap() { + log::trace!("ignoring keypress, automatic backlight is disabled"); + continue + } + let mut run_lock = thread_already_running.lock().unwrap(); + match *run_lock { + true => { + log::trace!("renewing backlight timer"); + tx.send(BacklightThreadOps::Renew).unwrap(); + continue + }, + false => { + *run_lock = true; + com.set_backlight(255, 128).expect("cannot set backlight on"); + std::thread::spawn({ + let rx = rx.clone(); + move || turn_lights_on(rx, thread_conn) + }); + }, + } + } + Some(StatusOpcode::TurnLightsOn) => { + log::trace!("turning lights on"); + com.set_backlight(255, 128).expect("cannot set backlight on"); + }, + Some(StatusOpcode::TurnLightsOff) => { + log::trace!("turning lights off"); + let mut run_lock = thread_already_running.lock().unwrap(); + *run_lock = false; + com.set_backlight(0, 0).expect("cannot set backlight off"); + }, + Some(StatusOpcode::Quit) => { break; } @@ -742,3 +795,41 @@ fn main() -> ! { xous::terminate_process(0) } +enum BacklightThreadOps { + /// Renew renews the backlight timer for another instance of standard_duration. + Renew, + + /// Stop stops the background backlight thread. + Stop, +} + +fn turn_lights_on(rx: Box>, cid: xous::CID) { + let standard_duration = std::time::Duration::from_secs(10); + + let mut timeout = std::time::Instant::now() + standard_duration; + + let mut total_waited = 0; + + loop { + select! { + recv(rx) -> op => { + match op.unwrap() { + BacklightThreadOps::Renew => { + timeout = std::time::Instant::now() + standard_duration; + total_waited += 1; + }, + BacklightThreadOps::Stop => { + log::trace!("received Stop op, killing background backlight thread"); + xous::send_message(cid, xous::Message::new_scalar(StatusOpcode::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap(); + return; + }, + } + }, + recv(at(timeout)) -> _ => { + log::trace!("timeout finished, total re-waited {}, returning!", total_waited); + xous::send_message(cid, xous::Message::new_scalar(StatusOpcode::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap(); + break; + } + }; + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ded24294f..d8699ab85 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -58,7 +58,6 @@ fn main() -> Result<(), Box> { "com", "xous-names", "keyboard", - "keyboard-backlight", "trng", "llio", "susres", From 97609109918614c2adbac5779514eada551bfca9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 14 Jun 2022 01:23:48 +0800 Subject: [PATCH 10/11] do not renumber explicitly numbered enums In general, if an enum has been explicitly numbered, it means that there are crates that depend on the actual number assigned, and changing them will break other crates. This is done to allow for cross-compatibility reasons, for example, going to a C FFI or to the standard library, where we can't simply refer to a Rust crate to import the symbolic enums and have the compiler figure out a consistent numbering method. Thus even though it's a bit "ugly", please assign only unused numbers to new enums, and when old enums are retired, do not re-use the number. --- services/keyboard/src/api.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/services/keyboard/src/api.rs b/services/keyboard/src/api.rs index 37fa41a4e..087f3e058 100644 --- a/services/keyboard/src/api.rs +++ b/services/keyboard/src/api.rs @@ -61,28 +61,28 @@ pub(crate) enum Opcode { RegisterRawListener = 3, /// request for updates for *when* keyboard is pressed - RegisterKeyObserver = 4, + RegisterKeyObserver = 12, /// set repeat delay, rate; both in ms - SetRepeat = 5, //(u32, u32), + SetRepeat = 4, //(u32, u32), /// set chording interval (how long to wait for all keydowns to happen before interpreting as a chord), in ms (for braille keyboards) - SetChordInterval = 6, //(u32), + SetChordInterval = 5, //(u32), /// used by host mode emulation and debug UART to inject keys - InjectKey = 7, //(char), + InjectKey = 6, //(char), /// used by the interrupt handler to transfer results to the main loop - HandlerTrigger = 8, + HandlerTrigger = 7, /// used to turn keyboard vibrate on and off - Vibe = 9, + Vibe = 8, /// a blocking key listener - blocks until a key is hit - BlockingKeyListener = 10, + BlockingKeyListener = 9, /// Suspend/resume callback - SuspendResume = 11, + SuspendResume = 10, } // this structure is used to register a keyboard listener. Currently, we only accept From 6a583a5f0ca093c8d1b64cc4c81481b66f36da0b Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 14 Jun 2022 01:25:41 +0800 Subject: [PATCH 11/11] the system as writ does not actually allocate an extra connection Adjust the connection number back to 4. There isn't a connection made for a keyboard backlight server anymore. This is necessary for root key initialization to proceed. --- services/keyboard/src/main.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 6178a2b92..c3f3f5aad 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -739,10 +739,9 @@ fn main() -> ! { // - graphics (if building for hosted mode) // - oqc (for factory test) // - status sub system (for setting the layout) - // - keyboard-backlight (to start backlight when a key is pressed) // - USB (for getting layout) #[cfg(any(target_os = "none", target_os = "xous"))] - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(6)).expect("can't register server"); + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server"); #[cfg(not(any(target_os = "none", target_os = "xous")))] let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(5)).expect("can't register server"); log::trace!("registered with NS -- {:?}", kbd_sid);