//! Connection to the launcher's command socket: global `home`, remote status //! and standby. The launcher answers every command with its standby state //! (`standby off|screen|suspend `), which we cache here. use std::io::{BufRead, BufReader, Write}; use std::os::unix::net::UnixStream; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::watch; /// Remote states the launcher understands. pub mod state { /// No Bluetooth controller present. pub const NO_ADAPTER: &str = "no-adapter"; /// No paired remote: scanning for one in pairing mode. pub const SEARCHING: &str = "searching"; /// A remote in pairing mode was found; pairing in progress. pub const PAIRING: &str = "pairing"; /// Paired but not connected (asleep). pub const PAIRED: &str = "paired"; pub const CONNECTED: &str = "connected"; } /// The launcher's standby state. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Standby { #[default] Off, /// Screen off, machine running. Screen, /// The launcher wants the machine suspended; the number changes with /// every request (also when it asks again after a stray wake-up). Suspend(u64), } impl Standby { pub fn parse(line: &str) -> Option { let mut w = line.split_whitespace(); if w.next()? != "standby" { return None; } match w.next()? { "off" => Some(Standby::Off), "screen" => Some(Standby::Screen), "suspend" => Some(Standby::Suspend(w.next().and_then(|n| n.parse().ok()).unwrap_or(0))), _ => None, } } pub fn active(self) -> bool { self != Standby::Off } } #[derive(Clone)] pub struct Link { socket: Option, status: Arc>, standby: Arc>, } impl Link { pub fn new(socket: Option) -> Self { Self { socket, status: Arc::default(), standby: Arc::new(watch::Sender::new(Standby::Off)) } } /// Sends one command and reads the launcher's standby reply. fn send(&self, line: &str) -> bool { let Some(path) = &self.socket else { return false }; let result = UnixStream::connect(path).and_then(|mut s| { s.set_read_timeout(Some(Duration::from_millis(500)))?; s.write_all(format!("{line}\n").as_bytes())?; let mut reply = String::new(); // An older launcher doesn't answer; the timeout covers that. let _ = BufReader::new(&s).read_line(&mut reply); Ok(reply) }); match result { Ok(reply) => { if let Some(state) = Standby::parse(&reply) { self.standby.send_if_modified(|cur| { let changed = *cur != state; if changed { log::info!("standby: {state:?}"); *cur = state; } changed }); } true } Err(e) => { log::trace!("launcher socket {}: {e}", path.display()); false } } } /// Asks the launcher to come to the front. False if it isn't listening. pub fn home(&self) -> bool { self.send("home") } /// Power button: the launcher toggles standby. pub fn power(&self) -> Standby { self.send("power"); self.standby() } /// Leave standby. pub fn wake(&self) { self.send("wake"); } /// Last known standby state (refreshed with every command, at least every 3 s). pub fn standby(&self) -> Standby { *self.standby.borrow() } pub fn watch_standby(&self) -> watch::Receiver { self.standby.subscribe() } pub fn status(&self, s: &str) { let changed = { let mut cur = self.status.lock().unwrap(); let changed = *cur != s; *cur = s.to_string(); changed }; if changed { log::info!("remote status: {s}"); } self.send(&format!("remote {s}")); } /// Re-sends the last status (the launcher may have restarted). pub fn resend(&self) { let s = self.status.lock().unwrap().clone(); if !s.is_empty() { self.send(&format!("remote {s}")); } } } #[cfg(test)] mod tests { use super::*; #[test] fn parses_standby_reply() { assert_eq!(Standby::parse("standby off\n"), Some(Standby::Off)); assert_eq!(Standby::parse("standby screen"), Some(Standby::Screen)); assert_eq!(Standby::parse("standby suspend 7"), Some(Standby::Suspend(7))); assert_eq!(Standby::parse(""), None); assert!(Standby::Screen.active() && !Standby::Off.active()); } }