diff --git a/crates/secbird-tray/src/editor.html b/crates/secbird-tray/src/editor.html index 9b7c174..1c473b7 100644 --- a/crates/secbird-tray/src/editor.html +++ b/crates/secbird-tray/src/editor.html @@ -3554,6 +3554,20 @@

const startup = group('Startup and games', row('Start with Windows', 'Your settings go back on as soon as you sign in. Off means they only apply while Secretarybird is running.', ...traySwitch('autostart', 'Start with Windows')), row('Switch profiles with games', 'A profile tied to a program comes up while that program is in front, and goes back after.', ...traySwitch('auto_switch', 'Switch profiles with games')), + row('Re-sync Spectrum when either device wakes (experimental)', + 'When a device wakes (seen through Windows Raw Input, no HID polling), Spectrum restarts on it and on the other devices that are awake, so they cycle in step whichever wakes first. A device still asleep is left alone and synced when it wakes. Restart Secretarybird after turning this on.', + ...traySwitch('spectrum_wake_sync', 'Re-sync Spectrum when either device wakes')), + row('Re-sync Spectrum now', + 'Restart Spectrum cycling on all connected devices that already use the Spectrum effect. Other effects and colors are left untouched.', + el('button', { className: 'ghost', textContent: 'Re-sync now', onclick: async e => { + const button = e.currentTarget; button.disabled = true; + try { + const r = await api('/api/resync-spectrum', {}); + const missed = (r.failed || []).length ? ' (not answering: ' + r.failed.join(', ') + ')' : ''; + toast(r.zones ? 'Spectrum restarted on ' + r.zones + ' lighting zones' + missed : (r.reason || 'No device took the write' + missed), !r.zones || !!missed); + } catch (err) { toast(err.message, true); } + button.disabled = false; + } })), row('Lights when away', 'While the PC is locked or its screen is off, the lights dim to a quarter or turn off, and come back when you return. Nothing is saved on the devices.', seg('Lights when away', [['', 'Leave on'], ['dim', 'Dim'], ['off', 'Off']], a.away_lights || '', async v => { try { diff --git a/crates/secbird-tray/src/engine.rs b/crates/secbird-tray/src/engine.rs index abc4ff8..6c88997 100644 --- a/crates/secbird-tray/src/engine.rs +++ b/crates/secbird-tray/src/engine.rs @@ -1,6 +1,7 @@ //! Device and profile handling for the tray, kept free of Win32 code. -use secbird_core::{config_dir, discover, hidapi::HidApi, Db, Device, Dimming, Result, Store}; +use crate::wake_sync::Peer; +use secbird_core::{config_dir, discover, effects::Effect, hidapi::HidApi, Db, Device, Dimming, Result, Store}; use crate::studio::Studio; use std::cell::{RefCell, RefMut}; use std::collections::{HashMap, HashSet}; @@ -67,6 +68,32 @@ pub struct LightsRetry { pub gave_up: Vec, } +/// One zone written by [`Engine::restart_spectrum`]. +pub struct ZoneWrite { + pub pid: u16, + pub zone: String, + pub result: Result<()>, + pub took: Duration, +} + +/// For the log: `02C9 backlight ok (31 ms), 00EA underglow failed: ... (160 ms)`. +pub fn describe_writes(writes: &[ZoneWrite]) -> String { + if writes.is_empty() { + return "nothing written".into(); + } + let parts: Vec = writes + .iter() + .map(|w| { + let ms = w.took.as_millis(); + match &w.result { + Ok(()) => format!("{:04X} {} ok ({ms} ms)", w.pid, w.zone), + Err(e) => format!("{:04X} {} failed: {e} ({ms} ms)", w.pid, w.zone), + } + }) + .collect(); + parts.join(", ") +} + /// What happened when a device's active profile was sent to it. pub struct ApplyReport { pub device: String, @@ -126,6 +153,83 @@ impl Engine { .collect() } + /// Devices whose profile in use shows Spectrum on a lit zone, by product id. `Err` says + /// why none can be written now. + pub fn spectrum_pids(&self) -> std::result::Result, String> { + if self.away.is_some() { + return Err("lights are down while away".into()); + } + let mut store = Self::store().map_err(|e| format!("profiles.json: {e}"))?; + let mut pids = Vec::new(); + for dev in &self.devices { + if !pids.contains(&dev.pid) && !self.spectrum_zones(&mut store, dev).is_empty() { + pids.push(dev.pid); + } + } + Ok(pids) + } + + /// LED id and name of each zone of `dev` that shows Spectrum in its profile in use. + fn spectrum_zones(&self, store: &mut Store, dev: &Device) -> Vec<(u8, String)> { + let p = store.for_device(dev); + if p.lighting_off { + return Vec::new(); + } + let name = p.effective(self.foreground()).to_string(); + let (Some(profile), Some(spec)) = (p.profiles.get(&name), &dev.spec) else { return Vec::new() }; + spec.leds + .iter() + .filter(|led| { + profile.lighting.get(&led.name).is_some_and(|z| !z.off && z.effect.as_ref() == Some(&Effect::Spectrum)) + }) + .map(|led| (led.id, led.name.clone())) + .collect() + } + + /// Restart the hardware Spectrum of the devices in `order`, in that order, without + /// changing any profile. The first `strict` of them just woke: when one of those doesn't + /// take the write, stop, so the rest aren't restarted out of step with it. Returns + /// every write made. + pub fn restart_spectrum(&self, order: &[u16], strict: usize) -> Vec { + let Ok(mut store) = Self::store() else { return Vec::new() }; + let mut writes = Vec::new(); + for (i, &pid) in order.iter().enumerate() { + for dev in self.devices.iter().filter(|d| d.pid == pid) { + for (led, zone) in self.spectrum_zones(&mut store, dev) { + let start = Instant::now(); + let result = dev.set_effect(led, &Effect::Spectrum); + let stop = result.is_err() && i < strict; + writes.push(ZoneWrite { pid, zone, result, took: start.elapsed() }); + if stop { + return writes; + } + } + } + } + writes + } + + /// Devices whose Raw Input may wake a Spectrum sync: those found, with the sleep timer + /// their profile sets, and the known wireless ones plugged in but asleep. + pub fn wake_peers(&self) -> HashMap { + let mut store = Self::store().ok(); + let mut peers = HashMap::new(); + for dev in &self.devices { + let minutes = store.as_mut().and_then(|s| { + let p = s.for_device(dev); + let name = p.effective(self.foreground()).to_string(); + p.profiles.get(&name)?.sleep_minutes + }); + let sleep = minutes.filter(|m| *m > 0).map(|m| Duration::from_secs(u64::from(m) * 60)); + let wireless = dev.spec.as_ref().is_some_and(|s| s.wireless); + peers.insert(dev.pid, Peer { wireless, sleep }); + } + for asleep in self.unsupported.iter().filter(|u| u.reason == ASLEEP) { + peers.entry(asleep.pid).or_insert(Peer { wireless: true, sleep: None }); + } + peers + } + pub fn open_events(&self, path: &std::ffi::CStr) -> Option { self.api.open_path(path).ok() } diff --git a/crates/secbird-tray/src/input.rs b/crates/secbird-tray/src/input.rs index a7c35ae..5e4b587 100644 --- a/crates/secbird-tray/src/input.rs +++ b/crates/secbird-tray/src/input.rs @@ -27,11 +27,18 @@ pub struct Input { } impl Input { - /// Listen or stop listening. - pub fn want(&mut self, hwnd: HWND, on: bool) { + /// Listen or stop listening. `kept`: Raw Input stays registered for mouse and keyboard + /// anyway (the Spectrum wake sync), so only start or stop reading it: registering here + /// would drop that registration's flags, and `RIDEV_REMOVE` would end it. + pub fn want(&mut self, hwnd: HWND, on: bool, kept: bool) { if on == self.on { return; } + if kept { + self.on = on; + self.down.clear(); + return; + } let flags = if on { RIDEV_INPUTSINK } else { RIDEV_REMOVE }; let target = if on { hwnd } else { null_mut() }; let list = [ @@ -43,6 +50,11 @@ impl Input { self.down.clear(); } + /// Whether a scene wants key presses now. + pub fn is_on(&self) -> bool { + self.on + } + /// A `WM_INPUT`: the Razer device's product id and the key's names (empty for a click), /// when it is a press. pub fn read(&mut self, lparam: LPARAM) -> Option<(u16, &'static [&'static str])> { diff --git a/crates/secbird-tray/src/main.rs b/crates/secbird-tray/src/main.rs index 9ec5350..9d96382 100644 --- a/crates/secbird-tray/src/main.rs +++ b/crates/secbird-tray/src/main.rs @@ -21,6 +21,8 @@ mod settings; mod studio; #[cfg(windows)] mod win; +#[cfg(windows)] +mod wake_sync; #[cfg(windows)] fn main() { diff --git a/crates/secbird-tray/src/server.rs b/crates/secbird-tray/src/server.rs index b5c99b6..4fdba48 100644 --- a/crates/secbird-tray/src/server.rs +++ b/crates/secbird-tray/src/server.rs @@ -229,6 +229,7 @@ impl Server { ("GET", "/api/settings") => Ok(settings_json(&engine)), ("GET", "/api/export") => Store::load(&config_dir().join("profiles.json")) .and_then(|s| serde_json::to_value(&s).map_err(|e| Error::Db(e.to_string()))), + ("POST", "/api/resync-spectrum") => Ok(resync_spectrum(&engine)), ("POST", path) => post(&mut engine, path, &req.body), _ => return Response::text("404 Not Found", "Not found"), }; @@ -653,6 +654,20 @@ fn sync(engine: &mut Engine, color: &str, effect: &str) -> Result Ok(json!({ "zones": zones, "devices": pids.len(), "skipped": skipped, "failed": failed, "state": state(engine) })) } +/// "Re-sync now": restart Spectrum on every device showing it, whether or not it woke. +fn resync_spectrum(engine: &Engine) -> Value { + let pids = match engine.spectrum_pids() { + Ok(pids) if pids.len() >= 2 => pids, + Ok(_) => return json!({ "zones": 0, "reason": "Set Spectrum cycling on at least two devices first" }), + Err(reason) => return json!({ "zones": 0, "reason": reason }), + }; + let writes = engine.restart_spectrum(&pids, 0); + secbird_core::log::append(&format!("Spectrum re-sync now: {}", crate::engine::describe_writes(&writes))); + let zones = writes.iter().filter(|w| w.result.is_ok()).count(); + let failed: Vec = writes.iter().filter(|w| w.result.is_err()).map(|w| format!("{:04X} {}", w.pid, w.zone)).collect(); + json!({ "zones": zones, "failed": failed }) +} + /// The app's own settings, for the editor's Settings page. fn settings_json(engine: &Engine) -> Value { let s = crate::settings::TraySettings::load(); @@ -668,6 +683,7 @@ fn settings_json(engine: &Engine) -> Value { "battery_warning_at": s.low_battery(), "auto_switch": !s.auto_switch_off, "away_lights": s.away_lights.as_deref().unwrap_or(""), + "spectrum_wake_sync": s.spectrum_wake_sync, "synapse": engine.synapse(), }) } @@ -696,6 +712,7 @@ fn app_post(engine: &mut Engine, path: &str, b: &Body) -> Option s.auto_switch_off = !b.on, + "spectrum_wake_sync" => s.spectrum_wake_sync = b.on, // `data`: "dim", "off", or "" to leave the lights as they are. "away_lights" => { let want = b.data.as_str().unwrap_or_default(); diff --git a/crates/secbird-tray/src/settings.rs b/crates/secbird-tray/src/settings.rs index 3c56fbf..3c749e2 100644 --- a/crates/secbird-tray/src/settings.rs +++ b/crates/secbird-tray/src/settings.rs @@ -55,6 +55,11 @@ pub struct TraySettings { /// or left as they are when unset. #[serde(default, skip_serializing_if = "Option::is_none")] pub away_lights: Option, + /// Experimental: restart Spectrum on the devices together when one of them wakes, so + /// they cycle in step (see `wake_sync`). Wakes come from Windows Raw Input; no HID + /// polling. Off by default; read at start. + #[serde(default)] + pub spectrum_wake_sync: bool, } /// Choices for [`TraySettings::away_lights`], with the percent of the saved brightness. diff --git a/crates/secbird-tray/src/wake_sync.rs b/crates/secbird-tray/src/wake_sync.rs new file mode 100644 index 0000000..aa00618 --- /dev/null +++ b/crates/secbird-tray/src/wake_sync.rs @@ -0,0 +1,529 @@ +//! When to restart Spectrum on the keyboard and mouse together, so they cycle in step +//! again after one of them wakes. Driven by events only: Windows Raw Input (event headers, +//! no HID traffic), the tray sending a device its profile on its own, and the outcome of +//! each attempt. Nothing here talks to a device, so every decision is tested without one. +//! +//! A wireless device sleeps after a stretch without input, so its first input after a gap +//! that long is a wake. One whose last input is more recent than its sleep timer must still +//! be awake; one quiet for longer may be asleep and isn't written to: it restarts its own +//! lights when it wakes, and that wake syncs everything again. Whichever device wakes first, +//! the write happens once both are awake, however long apart they woke. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +/// Assumed while a device's own sleep timer is unknown: Razer timers start at one minute. +const DEFAULT_IDLE: Duration = Duration::from_secs(55); +/// Taken off a device's own sleep timer, which isn't kept to the second. +const SLEEP_MARGIN: Duration = Duration::from_secs(5); +/// Wait after a wake before writing, for the device to take commands again. +pub const SETTLE: Duration = Duration::from_millis(1_500); +/// Further attempts while a device that woke doesn't take the write; then wait for its next wake. +const RETRY_AFTER: [Duration; 2] = [Duration::from_secs(2), Duration::from_secs(4)]; + +/// What the tray knows about a device it may get input from, refreshed after each rescan. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Peer { + /// Wired devices never sleep: their input is never a wake and they always count as awake. + pub wireless: bool, + /// The sleep timer set in its profile, if any. + pub sleep: Option, +} + +impl Peer { + /// Quiet for longer than this, the device may be asleep. + fn idle_limit(&self) -> Duration { + match self.sleep { + Some(sleep) if sleep > SLEEP_MARGIN * 2 => sleep - SLEEP_MARGIN, + _ => DEFAULT_IDLE, + } + } +} + +/// A device's first input after a gap long enough to have slept. +#[derive(Debug, PartialEq, Eq)] +pub struct Wake { + pub pid: u16, + /// The gap; `None` for the first input seen from the device. + pub idle: Option, +} + +/// One attempt: the devices that woke (or got their profile again), and its number from 1. +#[derive(Debug, PartialEq, Eq)] +pub struct Job { + pub woke: Vec, + pub attempt: usize, +} + +/// What to do for a [`Job`], given the devices the tray has right now. +#[derive(Debug, PartialEq, Eq)] +pub enum Plan { + /// Write the Spectrum zones of these devices in this order. The first `strict` ones just + /// woke: if one of them doesn't take the write, stop there ([`Outcome::NotReady`]), so the + /// others aren't restarted out of step with it. + Write { order: Vec, strict: usize }, + /// Devices that woke but aren't in the tray's list (dropped while asleep): rescan first. + Missing(Vec), + /// Nothing to write now, and why. + Wait(String), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Outcome { + /// Written, or nothing to write: wait for the next wake. + Done, + /// A device that woke isn't taking commands yet, or isn't back in the list yet. + NotReady, +} + +#[derive(Default)] +pub struct WakeSync { + peers: HashMap, + last_input: HashMap, + /// Devices that woke or got their profile again since the last attempt finished, in order. + woke: Vec, + /// Attempts made for `woke`. + attempts: usize, +} + +impl WakeSync { + pub fn set_peers(&mut self, peers: HashMap) { + self.peers = peers; + } + + /// Input from device `pid`. `Some` when it is a wake: (re)arm the timer for [`SETTLE`] and + /// call [`WakeSync::start`] when it fires. Other input only moves a timestamp, so steady + /// input can't cause a stream of writes. + pub fn input(&mut self, pid: u16, now: Instant) -> Option { + let peer = *self.peers.get(&pid)?; + let idle = self.last_input.insert(pid, now).map(|last| now.saturating_duration_since(last)); + if !peer.wireless || idle.is_some_and(|idle| idle < peer.idle_limit()) { + return None; + } + if !self.woke.contains(&pid) { + self.woke.push(pid); + } + // A fresh wake gets every attempt again. + self.attempts = 0; + Some(Wake { pid, idle }) + } + + /// The tray sent these devices their profile by itself (they turned up again in a rescan, + /// or answered after the lights came back), which restarted their Spectrum alone. True + /// when that makes an attempt due: arm the timer for [`SETTLE`]. + pub fn applied(&mut self, pids: &[u16]) -> bool { + for pid in pids { + if !self.woke.contains(pid) { + self.woke.push(*pid); + } + } + !pids.is_empty() + } + + /// Whether `pid` must be awake now: wired, or input more recent than its sleep timer. + pub fn awake(&self, pid: u16, now: Instant) -> bool { + self.peers.get(&pid).is_some_and(|peer| { + !peer.wireless + || self.last_input.get(&pid).is_some_and(|last| now.saturating_duration_since(*last) < peer.idle_limit()) + }) + } + + /// The timer fired: the attempt to make, if one is due. + pub fn start(&mut self) -> Option { + if self.woke.is_empty() { + return None; + } + self.attempts += 1; + Some(Job { woke: self.woke.clone(), attempt: self.attempts }) + } + + /// What to write for `job`: the devices that woke, then the others on Spectrum that must + /// still be awake. `present` are the devices in the tray's list, `spectrum` those of them + /// whose profile in use shows Spectrum. + pub fn plan(&self, job: &Job, present: &[u16], spectrum: &[u16], now: Instant) -> Plan { + let missing: Vec = job.woke.iter().copied().filter(|pid| !present.contains(pid)).collect(); + if !missing.is_empty() { + return Plan::Missing(missing); + } + let mut order: Vec = job.woke.iter().copied().filter(|pid| spectrum.contains(pid)).collect(); + let strict = order.len(); + if strict == 0 { + return Plan::Wait(format!("{} doesn't show Spectrum", list(&job.woke))); + } + let mut asleep = Vec::new(); + for &pid in spectrum { + if order.contains(&pid) { + continue; + } + if self.awake(pid, now) { + order.push(pid); + } else { + asleep.push(pid); + } + } + if order.len() >= 2 { + return Plan::Write { order, strict }; + } + if !asleep.is_empty() { + return Plan::Wait(format!("waiting for {} to wake", list(&asleep))); + } + // A device dropped from the list while asleep can't be seen on Spectrum yet. + let mut absent: Vec = self.peers.keys().copied().filter(|pid| !present.contains(pid)).collect(); + absent.sort_unstable(); + if absent.is_empty() { + Plan::Wait("no other device shows Spectrum".into()) + } else { + Plan::Wait(format!("no other device shows Spectrum; {} not in the device list (asleep?)", list(&absent))) + } + } + + /// The attempt is over. `Some(delay)`: try again after it. `None`: done until the next wake. + pub fn finish(&mut self, outcome: Outcome) -> Option { + if outcome == Outcome::NotReady { + if let Some(delay) = self.attempts.checked_sub(1).and_then(|i| RETRY_AFTER.get(i)) { + return Some(*delay); + } + } + self.woke.clear(); + self.attempts = 0; + None + } + + /// For the log: how long each device has been quiet, and which may be asleep. + pub fn describe(&self, now: Instant) -> String { + let mut pids: Vec = self.peers.keys().copied().collect(); + pids.sort_unstable(); + let parts: Vec = pids + .iter() + .map(|&pid| { + let state = match (self.peers[&pid].wireless, self.last_input.get(&pid)) { + (false, _) => "wired".to_string(), + (true, None) => "no input yet".to_string(), + (true, Some(last)) => { + let quiet = now.saturating_duration_since(*last).as_secs(); + if self.awake(pid, now) { + format!("quiet {quiet} s") + } else { + format!("quiet {quiet} s, may be asleep") + } + } + }; + format!("{pid:04X} {state}") + }) + .collect(); + parts.join(", ") + } +} + +/// Product ids for the log: `02C9, 00EA`. +pub fn list(pids: &[u16]) -> String { + pids.iter().map(|pid| format!("{pid:04X}")).collect::>().join(", ") +} + +/// The Razer product id in a Raw Input or HID device path, such as +/// `\\?\HID#VID_1532&PID_02C9&MI_02&Col01#...`. The receiver's id for a wireless device. +pub fn razer_pid(path: &str) -> Option { + const PREFIX: &str = "VID_1532&PID_"; + let upper = path.to_ascii_uppercase(); + let at = upper.find(PREFIX)? + PREFIX.len(); + let hex = upper.get(at..at + 4)?; + if !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + u16::from_str_radix(hex, 16).ok() +} + +/// The interface and collection in a device path (`MI_02 COL01`): tells a receiver's +/// collections apart in the log without logging the whole path. +pub fn collection(path: &str) -> String { + let upper = path.to_ascii_uppercase(); + let parts: Vec<&str> = ["MI_", "COL"] + .into_iter() + .filter_map(|tag| { + let at = upper.find(tag)?; + upper.get(at..at + tag.len() + 2) + }) + .collect(); + parts.join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pair this was built for: BlackWidow V4 Low-Profile HyperSpeed and Basilisk V4 + /// HyperSpeed, each on its own receiver, both set to sleep after one minute. + const BLACKWIDOW: u16 = 0x02C9; + const BASILISK: u16 = 0x00EA; + const BOTH: [u16; 2] = [BLACKWIDOW, BASILISK]; + const ONE_MINUTE: Peer = Peer { wireless: true, sleep: Some(Duration::from_secs(60)) }; + + fn secs(s: u64) -> Duration { + Duration::from_secs(s) + } + + fn write(order: [u16; 2]) -> Plan { + Plan::Write { order: order.to_vec(), strict: 1 } + } + + /// Both used at `t0`, synced, in step from then on. + fn in_step(t0: Instant) -> WakeSync { + let mut t = WakeSync::default(); + t.set_peers(HashMap::from([(BLACKWIDOW, ONE_MINUTE), (BASILISK, ONE_MINUTE)])); + assert!(t.input(BLACKWIDOW, t0).is_some(), "first input seen counts as a wake"); + assert!(t.input(BASILISK, t0).is_some()); + assert_eq!(fire(&mut t, t0 + SETTLE, &BOTH), Plan::Write { order: BOTH.to_vec(), strict: 2 }); + t + } + + /// `pid` used every 10 s for `span` seconds after `from`, when it was last used. + fn keep_using(t: &mut WakeSync, pid: u16, from: Instant, span: u64) { + for s in (10..=span).step_by(10) { + assert_eq!(t.input(pid, from + secs(s)), None, "steady input is not a wake"); + } + } + + /// The timer firing with `present` in the list, all on Spectrum, and every write taking. + fn fire(t: &mut WakeSync, now: Instant, present: &[u16]) -> Plan { + let job = t.start().expect("an attempt is due"); + let plan = t.plan(&job, present, present, now); + assert_eq!(t.finish(Outcome::Done), None); + plan + } + + /// Both fell asleep. `first` wakes and is used for `used` seconds; `second` wakes `gap` + /// seconds after `first` did. Returns the plan made for the second wake. + fn both_slept(first: u16, second: u16, gap: u64, used: u64) -> (WakeSync, Instant, Plan) { + let t0 = Instant::now(); + let mut t = in_step(t0); + let woke = t0 + secs(300); + assert_eq!(t.input(first, woke), Some(Wake { pid: first, idle: Some(secs(300)) })); + // The other one still sleeps: nothing is written, not even to the one that woke. + let waiting = Plan::Wait(format!("waiting for {second:04X} to wake")); + assert_eq!(fire(&mut t, woke + SETTLE, &BOTH), waiting); + keep_using(&mut t, first, woke, used); + let second_at = woke + secs(gap); + assert_eq!(t.input(second, second_at), Some(Wake { pid: second, idle: Some(secs(300 + gap)) })); + let plan = fire(&mut t, second_at + SETTLE, &BOTH); + (t, second_at, plan) + } + + #[test] + fn both_slept_mouse_then_keyboard_soon_after() { + assert_eq!(both_slept(BASILISK, BLACKWIDOW, 10, 5).2, write([BLACKWIDOW, BASILISK])); + } + + #[test] + fn both_slept_keyboard_then_mouse_soon_after() { + assert_eq!(both_slept(BLACKWIDOW, BASILISK, 10, 5).2, write([BASILISK, BLACKWIDOW])); + } + + #[test] + fn both_slept_mouse_then_keyboard_90_s_later_while_the_mouse_is_in_use() { + assert_eq!(both_slept(BASILISK, BLACKWIDOW, 90, 85).2, write([BLACKWIDOW, BASILISK])); + } + + #[test] + fn both_slept_keyboard_then_mouse_90_s_later_while_typing() { + assert_eq!(both_slept(BLACKWIDOW, BASILISK, 90, 85).2, write([BASILISK, BLACKWIDOW])); + } + + /// The first device was left alone and went back to sleep before the second woke: the + /// sync waits for the first one's next wake instead of writing to a sleeping device. + fn first_slept_again(first: u16, second: u16) { + let (mut t, second_at, plan) = both_slept(first, second, 90, 20); + assert_eq!(plan, Plan::Wait(format!("waiting for {first:04X} to wake"))); + let back = second_at + secs(30); + assert!(t.input(first, back).is_some(), "100 s quiet: a wake"); + assert_eq!(fire(&mut t, back + SETTLE, &BOTH), write([first, second])); + } + + #[test] + fn both_slept_mouse_then_keyboard_after_the_mouse_slept_again() { + first_slept_again(BASILISK, BLACKWIDOW); + } + + #[test] + fn both_slept_keyboard_then_mouse_after_the_keyboard_slept_again() { + first_slept_again(BLACKWIDOW, BASILISK); + } + + /// The case that already worked on hardware: one sleeps while the other is in use. + fn one_slept(sleeper: u16, in_use: u16) { + let t0 = Instant::now(); + let mut t = in_step(t0); + keep_using(&mut t, in_use, t0, 300); + let woke = t0 + secs(305); + assert!(t.input(sleeper, woke).is_some()); + assert_eq!(fire(&mut t, woke + SETTLE, &BOTH), write([sleeper, in_use])); + } + + #[test] + fn mouse_slept_alone() { + one_slept(BASILISK, BLACKWIDOW); + } + + #[test] + fn keyboard_slept_alone() { + one_slept(BLACKWIDOW, BASILISK); + } + + /// Seen in the log of 2026-10-29: a rescan while the keyboard slept dropped it from the + /// list, so the old sync found one device, wrote nothing and forgot the wake. + #[test] + fn keyboard_dropped_from_the_list_while_asleep() { + let t0 = Instant::now(); + let mut t = in_step(t0); + let mouse_only = [BASILISK]; + assert!(t.input(BASILISK, t0 + secs(300)).is_some()); + let waiting = Plan::Wait("no other device shows Spectrum; 02C9 not in the device list (asleep?)".into()); + assert_eq!(fire(&mut t, t0 + secs(302), &mouse_only), waiting); + let woke = t0 + secs(312); + assert!(t.input(BLACKWIDOW, woke).is_some()); + let job = t.start().unwrap(); + let now = woke + SETTLE; + assert_eq!(t.plan(&job, &mouse_only, &mouse_only, now), Plan::Missing(vec![BLACKWIDOW])); + // After the rescan the tray finds it again. + assert_eq!(t.plan(&job, &BOTH, &BOTH, now), write([BLACKWIDOW, BASILISK])); + assert_eq!(t.finish(Outcome::Done), None); + } + + /// Seen on 2026-10-29: the timers went from 1 to 7 minutes in the editor; the attempt + /// reads them again, so a keyboard quiet for 99 s counts as awake. + #[test] + fn sleep_timers_changed_in_the_editor_count_at_the_next_attempt() { + let t0 = Instant::now(); + let mut t = in_step(t0); + assert!(t.input(BASILISK, t0 + secs(99)).is_some()); + let job = t.start().unwrap(); + let now = t0 + secs(100); + assert_eq!(t.plan(&job, &BOTH, &BOTH, now), Plan::Wait("waiting for 02C9 to wake".into())); + let seven = Peer { wireless: true, sleep: Some(secs(7 * 60)) }; + t.set_peers(HashMap::from([(BLACKWIDOW, seven), (BASILISK, ONE_MINUTE)])); + assert_eq!(t.plan(&job, &BOTH, &BOTH, now), write([BASILISK, BLACKWIDOW])); + } + + #[test] + fn a_device_that_doesnt_take_the_write_gets_two_more_tries_then_waits() { + let t0 = Instant::now(); + let mut t = in_step(t0); + keep_using(&mut t, BLACKWIDOW, t0, 300); + let woke = t0 + secs(305); + assert!(t.input(BASILISK, woke).is_some()); + for (attempt, retry) in [(1, Some(secs(2))), (2, Some(secs(4))), (3, None)] { + let job = t.start().unwrap(); + assert_eq!(job, Job { woke: vec![BASILISK], attempt }); + assert_eq!(t.finish(Outcome::NotReady), retry); + } + assert_eq!(t.start(), None, "given up until the next wake"); + assert_eq!(t.input(BASILISK, woke + secs(20)), None, "still the same wake"); + assert!(t.input(BASILISK, woke + secs(90)).is_some()); + assert_eq!(t.start().unwrap().attempt, 1); + } + + #[test] + fn a_new_wake_during_retries_starts_the_count_again() { + let t0 = Instant::now(); + let mut t = in_step(t0); + assert!(t.input(BASILISK, t0 + secs(300)).is_some()); + t.start(); + assert_eq!(t.finish(Outcome::NotReady), Some(secs(2))); + assert!(t.input(BLACKWIDOW, t0 + secs(301)).is_some()); + assert_eq!(t.start(), Some(Job { woke: vec![BASILISK, BLACKWIDOW], attempt: 1 })); + } + + #[test] + fn steady_input_never_writes_again() { + let t0 = Instant::now(); + let mut t = in_step(t0); + for tenth in 1..=6_000 { + let now = t0 + Duration::from_millis(100 * tenth); + assert_eq!(t.input(BLACKWIDOW, now), None); + assert_eq!(t.input(BASILISK, now), None); + } + assert_eq!(t.start(), None); + } + + #[test] + fn a_profile_sent_again_syncs_with_the_awake_device() { + let t0 = Instant::now(); + let mut t = in_step(t0); + keep_using(&mut t, BLACKWIDOW, t0, 250); + assert!(t.applied(&[BASILISK])); + assert_eq!(fire(&mut t, t0 + secs(256), &BOTH), write([BASILISK, BLACKWIDOW])); + assert!(!t.applied(&[])); + assert_eq!(t.start(), None); + } + + #[test] + fn wired_devices_never_wake_and_always_count_as_awake() { + const WIRED: u16 = 0x02CC; + let mut t = WakeSync::default(); + t.set_peers(HashMap::from([(BASILISK, ONE_MINUTE), (WIRED, Peer { wireless: false, sleep: None })])); + let t0 = Instant::now(); + assert_eq!(t.input(WIRED, t0), None); + assert_eq!(t.input(WIRED, t0 + secs(600)), None); + assert!(t.input(BASILISK, t0 + secs(900)).is_some()); + assert_eq!(fire(&mut t, t0 + secs(902), &[BASILISK, WIRED]), write([BASILISK, WIRED])); + } + + #[test] + fn the_sleep_timer_from_the_profile_sets_what_counts_as_a_wake() { + let mut t = WakeSync::default(); + t.set_peers(HashMap::from([(BASILISK, Peer { wireless: true, sleep: Some(secs(300)) })])); + let t0 = Instant::now(); + t.input(BASILISK, t0); + assert_eq!(t.input(BASILISK, t0 + secs(70)), None, "a pause, not a sleep"); + assert!(t.awake(BASILISK, t0 + secs(300))); + assert!(!t.awake(BASILISK, t0 + secs(370))); + assert!(t.input(BASILISK, t0 + secs(370)).is_some()); + let mut unknown = WakeSync::default(); + unknown.set_peers(HashMap::from([(BASILISK, Peer { wireless: true, sleep: None })])); + unknown.input(BASILISK, t0); + assert!(unknown.input(BASILISK, t0 + secs(55)).is_some(), "Razer timers start at one minute"); + } + + #[test] + fn devices_the_tray_doesnt_know_are_ignored() { + let mut t = WakeSync::default(); + let now = Instant::now(); + assert_eq!(t.input(BLACKWIDOW, now), None, "no device list yet"); + t.set_peers(HashMap::from([(BLACKWIDOW, ONE_MINUTE)])); + assert_eq!(t.input(0x1234, now), None); + assert_eq!(t.start(), None); + } + + #[test] + fn a_device_without_spectrum_writes_nothing() { + let t0 = Instant::now(); + let mut t = in_step(t0); + assert!(t.input(BASILISK, t0 + secs(300)).is_some()); + let job = t.start().unwrap(); + let plan = t.plan(&job, &BOTH, &[BLACKWIDOW], t0 + secs(302)); + assert_eq!(plan, Plan::Wait("00EA doesn't show Spectrum".into())); + } + + #[test] + fn the_log_line_says_who_may_be_asleep() { + let t0 = Instant::now(); + let mut t = in_step(t0); + assert_eq!(t.describe(t0 + secs(5)), "00EA quiet 5 s, 02C9 quiet 5 s"); + t.input(BASILISK, t0 + secs(100)); + assert_eq!(t.describe(t0 + secs(101)), "00EA quiet 1 s, 02C9 quiet 101 s, may be asleep"); + } + + #[test] + fn raw_input_paths_name_the_receiver() { + let keyboard = r"\\?\HID#VID_1532&PID_02C9&MI_02&Col01#8&2a1b3c4d&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91e6bf6}"; + assert_eq!(razer_pid(keyboard), Some(BLACKWIDOW)); + assert_eq!(collection(keyboard), "MI_02 COL01"); + let mouse = r"\\?\hid#vid_1532&pid_00ea&mi_00#7&1f2e3d4c&0&0000#{378de44c-56ef-11d1-bc8c-00a0c91e6bf6}"; + assert_eq!(razer_pid(mouse), Some(BASILISK)); + assert_eq!(collection(mouse), "MI_00"); + assert_eq!(razer_pid(r"\\?\HID#VID_046D&PID_C52B&MI_00#x"), None); + assert_eq!(razer_pid("VID_1532&PID_02"), None); + assert_eq!(razer_pid("VID_1532&PID_+2C9"), None); + assert_eq!(collection("VID_1532&PID_02C9"), ""); + assert_eq!(list(&BOTH), "02C9, 00EA"); + } +} diff --git a/crates/secbird-tray/src/win.rs b/crates/secbird-tray/src/win.rs index 04ad4b4..7157a32 100644 --- a/crates/secbird-tray/src/win.rs +++ b/crates/secbird-tray/src/win.rs @@ -1,4 +1,5 @@ -use crate::engine::{ApplyReport, Battery, Engine, LightsRetry, DIM_FOR, RELIGHT_FOR}; +use crate::engine::{describe_writes, ApplyReport, Battery, Engine, LightsRetry, DIM_FOR, RELIGHT_FOR}; +use crate::wake_sync::{self, Job, Outcome, Plan, WakeSync}; use secbird_core::log; use std::collections::{HashMap, HashSet}; use crate::settings::{autostart_enabled, open_config_folder, set_autostart, TraySettings}; @@ -12,7 +13,7 @@ use std::mem::{size_of, zeroed}; use std::ptr::{null, null_mut}; use std::sync::atomic::{AtomicPtr, AtomicU32, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; -use std::time::Duration; +use std::time::{Duration, Instant}; use windows_sys::core::GUID; use windows_sys::Win32::Foundation::*; use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; @@ -21,6 +22,7 @@ use windows_sys::Win32::System::RemoteDesktop::{WTSRegisterSessionNotification, use windows_sys::Win32::System::SystemServices::GUID_CONSOLE_DISPLAY_STATE; use windows_sys::Win32::System::Threading::CreateMutexW; use windows_sys::Win32::UI::Accessibility::{SetWinEventHook, HWINEVENTHOOK}; +use windows_sys::Win32::UI::Input::*; use windows_sys::Win32::UI::Shell::*; use windows_sys::Win32::UI::WindowsAndMessaging::*; @@ -80,6 +82,9 @@ const LIGHTS_MS: u32 = 3_000; const TIMER_STUDIO: usize = 8; const STUDIO_FRAME_MS: u32 = 1000 / secbird_core::studio::FPS; const STUDIO_IDLE_MS: u32 = 500; +/// Spectrum restarted on the devices together after one wakes (see `wake_sync`): armed by +/// each wake, each profile the tray sends by itself, and each retry. +const TIMER_SPECTRUM_WAKE: usize = 9; const ID_REAPPLY: u32 = 1; const ID_FOLDER: u32 = 2; @@ -141,6 +146,12 @@ struct App { /// The session is locked, or the screen is off: the lights go down if set (#48). locked: bool, screen_off: bool, + /// Spectrum re-sync on wake is on: set at start, once Raw Input is registered. + wake_sync_on: bool, + /// Raw Input hDevice -> Razer product id (`None`: not Razer), looked up once per handle + /// and forgotten when Windows says the device went away. + raw_devices: HashMap>, + wake_sync: WakeSync, /// Sound level and screen colour for the Audio and Screen effects, while used. sensors: crate::sensors::Sensors, /// Key presses for Reactive and Ripple, while used. @@ -328,12 +339,19 @@ pub fn run() { installs, locked: false, screen_off: false, + wake_sync_on: false, + raw_devices: HashMap::new(), + wake_sync: WakeSync::default(), sensors: Default::default(), input: Default::default(), studio_ms: STUDIO_IDLE_MS, }) }); log::append("tray started"); + // After the app exists, so the device arrivals Windows reports right away are seen. + if TraySettings::load().spectrum_wake_sync && register_wake_raw_input(hwnd) { + with_app(|app| app.wake_sync_on = true); + } with_app(|app| app.announce_updated()); with_app(|app| app.rescan()); start_retries(hwnd); @@ -379,6 +397,24 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: with_app(|app| app.device_events()); 0 } + WM_INPUT => { + // One registration serves the Spectrum wake sync and the Reactive and Ripple + // key presses (see `Input::want`). + with_app(|app| { + app.raw_input(lparam); + if app.input.is_on() { + if let Some((pid, names)) = app.input.read(lparam) { + app.engine().studio().press(pid, names); + } + } + }); + // Required for foreground raw input cleanup; harmless for INPUTSINK. + DefWindowProcW(hwnd, msg, wparam, lparam) + } + WM_INPUT_DEVICE_CHANGE => { + with_app(|app| app.raw_device_change(wparam as u32, lparam as HANDLE)); + 0 + } WM_FIRMWARE => { with_app(|app| app.firmware_news()); 0 @@ -480,28 +516,33 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: } WM_TIMER if wparam == TIMER_LIGHTS => { with_app(|app| { - let mut engine = app.engine(); - let relit = engine.retry_lights_back(); - let dimmed = engine.retry_lights_away(); - log_retry(&engine, "back", &relit); - log_retry(&engine, "away", &dimmed); - engine.refresh_frames(); - engine.keep_laptops_lit(); + let relit = { + let mut engine = app.engine(); + let relit = engine.retry_lights_back(); + let dimmed = engine.retry_lights_away(); + log_retry(&engine, "back", &relit); + log_retry(&engine, "away", &dimmed); + engine.refresh_frames(); + engine.keep_laptops_lit(); + relit.done + }; + app.spectrum_applied(&relit); }); 0 } + WM_TIMER if wparam == TIMER_SPECTRUM_WAKE => { + KillTimer(hwnd, TIMER_SPECTRUM_WAKE); + // The app is busy (re-entered from a nested message loop): try again shortly + // rather than lose the wake. + if with_app(|app| app.spectrum_due()).is_none() { + SetTimer(hwnd, TIMER_SPECTRUM_WAKE, SETTLE_MS, None); + } + 0 + } WM_TIMER if wparam == TIMER_STUDIO => { with_app(|app| app.studio_tick()); 0 } - WM_INPUT => { - with_app(|app| { - if let Some((pid, names)) = app.input.read(lparam) { - app.engine().studio().press(pid, names); - } - }); - DefWindowProcW(hwnd, msg, wparam, lparam) - } WM_TIMER if wparam == TIMER_FOREGROUND => { KillTimer(hwnd, TIMER_FOREGROUND); if with_app(|app| app.foreground_changed()).is_none() { @@ -525,6 +566,26 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: } } +/// Register as a background observer (never RIDEV_NOLEGACY) so Windows keeps +/// delivering ordinary mouse and keyboard input to the user's applications. +/// RIDEV_DEVNOTIFY adds WM_INPUT_DEVICE_CHANGE, so handles of devices that go are dropped. +unsafe fn register_wake_raw_input(hwnd: HWND) -> bool { + let flags = RIDEV_INPUTSINK | RIDEV_DEVNOTIFY; + let devices = [ + RAWINPUTDEVICE { usUsagePage: 0x01, usUsage: 0x02, dwFlags: flags, hwndTarget: hwnd }, + RAWINPUTDEVICE { usUsagePage: 0x01, usUsage: 0x06, dwFlags: flags, hwndTarget: hwnd }, + ]; + if RegisterRawInputDevices(devices.as_ptr(), devices.len() as u32, size_of::() as u32) == 0 { + log::append(&format!( + "Spectrum wake: failed to register Raw Input (error {}); manual synchronization remains available", + GetLastError() + )); + return false; + } + log::append("Spectrum wake: background Raw Input enabled for mouse and keyboard"); + true +} + /// Log what a retry of the lights while away (or back) did, if anything. fn log_retry(engine: &Engine, what: &str, retry: &LightsRetry) { if !retry.done.is_empty() { @@ -543,6 +604,23 @@ fn missed_note(engine: &Engine, missed: &[String], window: Duration) -> String { format!("; not answering: {}, trying again for {} s", engine.names(missed), window.as_secs()) } +/// The device path of a Raw Input device, such as `\\?\HID#VID_1532&PID_02C9&MI_02#...`. +unsafe fn raw_input_device_name(device: HANDLE) -> Option { + if device.is_null() { + return None; + } + let mut chars = 0u32; + if GetRawInputDeviceInfoW(device, RIDI_DEVICENAME, null_mut(), &mut chars) == u32::MAX || chars == 0 || chars > 1024 { + return None; + } + let mut buffer = vec![0u16; chars as usize]; + if GetRawInputDeviceInfoW(device, RIDI_DEVICENAME, buffer.as_mut_ptr().cast(), &mut chars) == u32::MAX { + return None; + } + let end = buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len()); + Some(String::from_utf16_lossy(&buffer[..end])) +} + /// A window came to the front: (re)start the settle timer. unsafe extern "system" fn on_foreground(_: HWINEVENTHOOK, _: u32, _: HWND, _: i32, _: i32, _: u32, _: u32) { let hwnd = TRAY_HWND.load(Ordering::Relaxed); @@ -569,26 +647,52 @@ impl App { } fn rescan(&mut self) { + let (applied, all) = self.rescan_devices(); + // When every device got its profile, their Spectrum restarted together; a device + // back from sleep got it alone, out of step with the others. + if !all { + self.spectrum_applied(&applied); + } + } + + /// Re-enumerate, and send their profile to new devices (every device when pending). + /// Returns the keys of the devices sent their profile, and whether that was all of them. + fn rescan_devices(&mut self) -> (Vec, bool) { let apply_all = std::mem::take(&mut self.apply_all_pending); - let (reports, new_names, synapse) = { + let (reports, targets, new_names, gone, synapse) = { let mut engine = self.engine(); + let before: Vec<(String, String)> = engine.devices().iter().map(|d| (d.key(), engine.label(d))).collect(); let new = engine.rescan(); let names: Vec = engine.devices().iter().filter(|d| new.contains(&d.key())).map(|d| engine.label(d)).collect(); + let gone: Vec = before + .into_iter() + .filter(|(key, _)| !engine.devices().iter().any(|d| d.key() == *key)) + .map(|(_, name)| name) + .collect(); let targets = if apply_all { engine.all_keys() } else { new }; - (engine.apply(&targets), names, engine.synapse().to_vec()) + (engine.apply(&targets), targets, names, gone, engine.synapse().to_vec()) }; if !new_names.is_empty() { log::append(&format!("found: {}", new_names.join(", "))); } + // So a wireless device dropped from the list while asleep shows in the log. + if !gone.is_empty() { + log::append(&format!("gone: {} (asleep or unplugged)", gone.join(", "))); + } self.notify_failures(&reports); self.warn_synapse(&synapse); self.check_battery(); self.start_listeners(); + if self.wake_sync_on { + let peers = self.engine().wake_peers(); + self.wake_sync.set_peers(peers); + } // A device that arrives (or wakes) while the PC is locked comes up lit. if let Some(percent) = TraySettings::load().away_percent().filter(|_| self.engine().is_away()) { self.engine().lights_away(percent); } + (targets, apply_all) } /// The lights go down while the PC is locked or its screen is off, if that's set (#48), @@ -605,7 +709,7 @@ impl App { (studio.busy(), studio.wants(), studio.senses.clone()) }; self.sensors.want(audio, screen, &senses); - self.input.want(self.hwnd, keys); + self.input.want(self.hwnd, keys, self.wake_sync_on); let ms = if busy { STUDIO_FRAME_MS } else { STUDIO_IDLE_MS }; if ms != self.studio_ms { self.studio_ms = ms; @@ -624,6 +728,8 @@ impl App { log::append(&format!("{why}: lights to {percent}%{}", missed_note(&engine, &missed, DIM_FOR))); } None if engine.is_away() => { + // Every device that answers gets its profile at once, so their Spectrum + // restarts together; one that misses it is synced when it answers later. let missed = engine.lights_back(); log::append(&format!("back: lights as saved{}", missed_note(&engine, &missed, RELIGHT_FOR))); } @@ -671,6 +777,183 @@ impl App { } } + /// Only raw input from a Razer device the tray knows counts. Reads the event's header, + /// never an HID report: nothing is sent to any device from here. + fn raw_input(&mut self, lparam: LPARAM) { + if !self.wake_sync_on { + return; + } + let mut header: RAWINPUTHEADER = unsafe { zeroed() }; + let mut size = size_of::() as u32; + let got = unsafe { + GetRawInputData( + lparam as HRAWINPUT, + RID_HEADER, + (&mut header as *mut RAWINPUTHEADER).cast(), + &mut size, + size_of::() as u32, + ) + }; + if got == u32::MAX || got != size_of::() as u32 { + return; + } + if header.dwType != RIM_TYPEMOUSE && header.dwType != RIM_TYPEKEYBOARD { + return; + } + let Some(pid) = self.raw_pid(header.hDevice) else { return }; + let now = Instant::now(); + let Some(wake) = self.wake_sync.input(pid, now) else { return }; + if !TraySettings::load().spectrum_wake_sync { + // Turned off in the editor since the tray started. + self.wake_sync.finish(Outcome::Done); + return; + } + let quiet = wake.idle.map_or_else(|| "first input seen".to_string(), |idle| format!("after {} s quiet", idle.as_secs())); + log::append(&format!("Spectrum wake: {:04X} woke ({quiet}); {}", wake.pid, self.wake_sync.describe(now))); + self.arm_spectrum(wake_sync::SETTLE); + } + + /// The Razer product id of a Raw Input device, looked up once per handle. + fn raw_pid(&mut self, device: HANDLE) -> Option { + let handle = device as isize; + if let Some(pid) = self.raw_devices.get(&handle) { + return *pid; + } + let path = unsafe { raw_input_device_name(device) }; + let pid = path.as_deref().and_then(wake_sync::razer_pid); + if let (Some(pid), Some(path)) = (pid, &path) { + log::append(&format!( + "Spectrum wake: raw input device {handle:#x} is Razer {pid:04X} {}", + wake_sync::collection(path) + )); + } + self.raw_devices.insert(handle, pid); + pid + } + + /// Windows says a Raw Input device came or went (RIDEV_DEVNOTIFY). Razer ones are logged, + /// to see whether a receiver's collections come and go while its device sleeps. + fn raw_device_change(&mut self, change: u32, device: HANDLE) { + let handle = device as isize; + if change == GIDC_REMOVAL { + if let Some(Some(pid)) = self.raw_devices.remove(&handle) { + log::append(&format!("Spectrum wake: raw input device {handle:#x} (Razer {pid:04X}) removed")); + } + } else if change == GIDC_ARRIVAL { + // Windows can hand a freed handle to another device: look it up again. + self.raw_devices.remove(&handle); + self.raw_pid(device); + } + } + + fn arm_spectrum(&self, delay: Duration) { + unsafe { SetTimer(self.hwnd, TIMER_SPECTRUM_WAKE, delay.as_millis() as u32, None) }; + } + + /// Product ids of the devices with these keys. + fn pids_of(&self, keys: &[String]) -> Vec { + self.engine().devices().iter().filter(|d| keys.contains(&d.key())).map(|d| d.pid).collect() + } + + /// The tray sent these devices their profile by itself (back in a rescan, or answering + /// after the lights came back). That restarted their Spectrum alone: restart it on the + /// awake devices with them. + fn spectrum_applied(&mut self, keys: &[String]) { + if !self.wake_sync_on || keys.is_empty() { + return; + } + let pids = self.pids_of(keys); + if TraySettings::load().spectrum_wake_sync && self.wake_sync.applied(&pids) { + log::append(&format!("Spectrum wake: {} got its profile again; syncing", wake_sync::list(&pids))); + self.arm_spectrum(wake_sync::SETTLE); + } + } + + /// The Spectrum timer fired: one attempt (see [`wake_sync`]). + fn spectrum_due(&mut self) { + let Some(mut job) = self.wake_sync.start() else { return }; + // Sleep timers may have changed in the editor since the last rescan. + let peers = self.engine().wake_peers(); + self.wake_sync.set_peers(peers); + // A retry after a write that didn't take: reopen the handles first, in case the + // receiver came back as a new device. + let rescanned = job.attempt > 1; + if rescanned { + self.rescan_for_spectrum(&mut job); + } + let mut plan = self.spectrum_plan(&job); + if !rescanned && matches!(plan, Plan::Missing(_)) { + if let Plan::Missing(missing) = &plan { + log::append(&format!( + "Spectrum wake: {} isn't in the device list (dropped while asleep?): rescanning", + wake_sync::list(missing) + )); + } + self.rescan_for_spectrum(&mut job); + plan = self.spectrum_plan(&job); + } + let outcome = match plan { + Plan::Write { order, strict } => { + let writes = self.engine().restart_spectrum(&order, strict); + let not_ready = writes.iter().any(|w| w.result.is_err() && order[..strict].contains(&w.pid)); + log::append(&format!( + "Spectrum wake: attempt {} on {}: {}", + job.attempt, + wake_sync::list(&order), + describe_writes(&writes) + )); + if not_ready { + Outcome::NotReady + } else { + Outcome::Done + } + } + Plan::Missing(missing) => { + log::append(&format!( + "Spectrum wake: attempt {}: {} still not in the device list", + job.attempt, + wake_sync::list(&missing) + )); + Outcome::NotReady + } + Plan::Wait(why) => { + log::append(&format!("Spectrum wake: attempt {}: nothing written, {why}", job.attempt)); + Outcome::Done + } + }; + match self.wake_sync.finish(outcome) { + Some(delay) => { + log::append(&format!("Spectrum wake: trying again in {} s", delay.as_secs())); + self.arm_spectrum(delay); + } + None if outcome == Outcome::NotReady => log::append("Spectrum wake: giving up until the next wake"), + None => {} + } + } + + /// What to write for `job`, from the devices the tray has now. + fn spectrum_plan(&self, job: &Job) -> Plan { + let engine = self.engine(); + let present: Vec = engine.devices().iter().map(|d| d.pid).collect(); + match engine.spectrum_pids() { + Ok(spectrum) => self.wake_sync.plan(job, &present, &spectrum, Instant::now()), + Err(why) => Plan::Wait(why), + } + } + + /// Rescan within an attempt. Devices it sends their profile to restarted their Spectrum + /// alone, so they are written first along with the devices that woke. + fn rescan_for_spectrum(&mut self, job: &mut Job) { + let (applied, _) = self.rescan_devices(); + let pids = self.pids_of(&applied); + for &pid in &pids { + if !job.woke.contains(&pid) { + job.woke.push(pid); + } + } + self.wake_sync.applied(&pids); + } + fn device_events(&mut self) { while let Ok(event) = self.events.try_recv() { match event {