diff --git a/README.md b/README.md
index 0ee953710c..cc79581d72 100644
--- a/README.md
+++ b/README.md
@@ -75,7 +75,7 @@ Things OpenLogi does that Options+ won't:
- **Run on Linux.** Linux is a first-class platform in OpenLogi.
- **Gestures on supported buttons.** Assign gesture actions to supported controls — or turn gestures off entirely.
- **Plain-text config.** Everything is one TOML file you can sync between machines however you like.
-- **Script it.** A real CLI alongside the GUI: a JSON [automation API](docs/USAGE.md#automation-api) for DPI, SmartShift, Fn-lock, and report rate, plus hardware diagnostics.
+- **Script it.** A real CLI alongside the GUI: a JSON [automation API](docs/USAGE.md#automation-api) for DPI, SmartShift, Fn-lock, and report rate, [haptic pulses](docs/USAGE.md#haptic-feedback) on mice that have them, plus hardware diagnostics.
## Features
diff --git a/crates/openlogi-agent-core/src/action_ring.rs b/crates/openlogi-agent-core/src/action_ring.rs
index d2ec76b4e4..af53226242 100644
--- a/crates/openlogi-agent-core/src/action_ring.rs
+++ b/crates/openlogi-agent-core/src/action_ring.rs
@@ -176,9 +176,19 @@ impl Default for ActionRingManager {
}
impl ActionRingManager {
+ /// Take the next session ID without opening a ring.
+ ///
+ /// The agent's haptic worker orders the haptic sessions it owes an engine
+ /// restore by ID. Haptics played for another client than the ring open a
+ /// session of their own, and take its ID here so it orders against the
+ /// ring's.
+ pub fn reserve_session_id(&self) -> u64 {
+ self.next_session.fetch_add(1, Ordering::Relaxed)
+ }
+
/// Open or replace the current session and wake the overlay long-poll.
pub fn begin(&self, spec: ActionRingSessionSpec) -> ActionRingInvocation {
- let session_id = self.next_session.fetch_add(1, Ordering::Relaxed);
+ let session_id = self.reserve_session_id();
let mut actions = BTreeMap::new();
let mut slots = BTreeMap::new();
for (slot, entry) in spec.layout.slots {
diff --git a/crates/openlogi-agent/src/bin/mock_agent.rs b/crates/openlogi-agent/src/bin/mock_agent.rs
index 2ae02e9c53..212e61813e 100644
--- a/crates/openlogi-agent/src/bin/mock_agent.rs
+++ b/crates/openlogi-agent/src/bin/mock_agent.rs
@@ -63,7 +63,7 @@ use openlogi_core::device::{
BatteryInfo, BatteryLevel, BatteryStatus, Capabilities, DeviceInventory, DeviceKind, LockKey,
PairedDevice, StandaloneDevice, prettify_codename,
};
-use openlogi_core::hid::{DisableKeysMask, DisableKeysState, HidppOperation};
+use openlogi_core::hid::{DisableKeysMask, DisableKeysState, HapticPulse, HidppOperation};
use openlogi_core::single_instance::{self, InstanceError, Role};
use openlogi_fixture::{DeviceProfile, FixtureError, ProfileDeviceSettings, ProfileSetting};
use openlogi_hid::{
@@ -1603,6 +1603,17 @@ impl Agent for MockAgent {
) -> Result<(), ActionRingCommandError> {
Err(ActionRingCommandError::SessionNotFound)
}
+
+ async fn play_haptic(
+ self,
+ _: Context,
+ route: DeviceRoute,
+ pulse: HapticPulse,
+ ) -> Result<(), WriteError> {
+ self.state.lock().await.settings_for(&route)?;
+ info!(%route, ?pulse, "play_haptic (no-op in the mock)");
+ Ok(())
+ }
}
#[cfg(test)]
diff --git a/crates/openlogi-agent/src/server.rs b/crates/openlogi-agent/src/server.rs
index 366284c465..ddd8732e0d 100644
--- a/crates/openlogi-agent/src/server.rs
+++ b/crates/openlogi-agent/src/server.rs
@@ -7,6 +7,7 @@
pub(crate) mod backlight;
mod haptic_restore;
+mod haptic_sessions;
mod settings;
use std::sync::{Arc, PoisonError};
@@ -22,6 +23,7 @@ use openlogi_agent_core::runtime::ActionDispatcher;
use openlogi_core::binding::ActionRingSlot;
use openlogi_core::config::{ConfigFile, ConfigRevision, Lighting};
use openlogi_core::device::DeviceInventory;
+use openlogi_core::hid::HapticPulse;
use openlogi_hid::{
BacklightChange, BacklightState, DeviceRoute, Dpi, DpiInfo, EasySwitchHosts, FnLockState,
ForceSensingInfo, HapticRestore, HapticRestoreOutcome, HapticWaveform, HidppOperation,
@@ -38,7 +40,8 @@ use openlogi_ipc::{
};
use succession::Compat;
-use self::haptic_restore::RestoreLedger;
+use self::haptic_restore::{Lane, RestoreLedger, Session};
+use self::haptic_sessions::{Paused, Sessions};
use crate::pairing::PairingManager;
// Brings `Listener::accept` into scope for the concrete listener `transport::bind`
// returns; `as _` keeps it anonymous (method resolution only).
@@ -542,8 +545,12 @@ impl Agent for AgentServer {
slot: ActionRingSlot,
) -> Result<(), ActionRingCommandError> {
if let Some(hover) = self.action_ring.hover(session_id, slot)? {
- self.ring_haptics
- .play(hover.haptic_route, HapticWaveform::SubtleCollision, "hover");
+ self.ring_haptics.play(
+ session_id,
+ hover.haptic_route,
+ HapticWaveform::SubtleCollision,
+ "hover",
+ );
}
Ok(())
}
@@ -599,6 +606,61 @@ impl Agent for AgentServer {
) -> Result<(), ActionRingCommandError> {
self.action_ring.unhover(session_id)
}
+
+ async fn play_haptic(
+ self,
+ _: Context,
+ route: DeviceRoute,
+ pulse: HapticPulse,
+ ) -> Result<(), WriteError> {
+ self.observable
+ .read(|snapshot| check_haptic_target(&snapshot.inventory, &route))?;
+ let waveform = match pulse {
+ HapticPulse::SubtleCollision => HapticWaveform::SubtleCollision,
+ HapticPulse::DampStateChange => HapticWaveform::DampStateChange,
+ };
+ self.ring_haptics
+ .play_external(route, waveform, || self.action_ring.reserve_session_id())
+ .await
+ }
+}
+
+/// Refuse a client's play that the agent's inventory already rules out,
+/// before it reaches the haptic worker: a route no device answers on, a
+/// device that is offline, or one whose measured features lack `0x19b0`. The
+/// worker retries, and its breaker counts, lost replies; none of these is
+/// one, and retrying them would only cool the Actions Ring's haptics down.
+fn check_haptic_target(
+ inventory: &[DeviceInventory],
+ route: &DeviceRoute,
+) -> Result<(), WriteError> {
+ let device = inventory
+ .iter()
+ .flat_map(|inventory| {
+ inventory
+ .paired
+ .iter()
+ .map(move |device| (inventory, device))
+ })
+ .find(|(inventory, device)| {
+ DeviceRoute::for_slot(inventory, device.slot).as_ref() == Some(route)
+ })
+ .map(|(_, device)| device)
+ .ok_or(WriteError::DeviceNotFound)?;
+ if !device.online {
+ return Err(WriteError::DeviceUnreachable {
+ index: route.device_index(),
+ });
+ }
+ if !device
+ .capabilities
+ .is_some_and(|capabilities| capabilities.haptic_feedback)
+ {
+ return Err(WriteError::FeatureUnsupported {
+ feature_hex: 0x19b0,
+ });
+ }
+ Ok(())
}
/// Run the action a ring session closed on, whether a click on the overlay
@@ -611,6 +673,7 @@ pub(crate) fn run_ring_activation(
) {
dispatcher.dispatch(&activation.action, Some(&activation.device_key));
haptics.play(
+ session_id,
activation.haptic_route,
HapticWaveform::DampStateChange,
"activation",
@@ -632,10 +695,15 @@ pub(crate) fn run_ring_activation(
///
/// The worker also owns the device-wide enable flag that arming may turn on
/// for a session: [`haptic_restore::RestoreLedger`] records each enable
-/// arming made, and the worker hands it back once that session is over.
+/// arming made, and the worker hands it back once every session playing on
+/// that engine is over.
+///
+/// Clients other than the ring play through the same worker
+/// ([`Self::play_external`]), so their buzzes coalesce with the ring's and
+/// their enables are handed back the same way.
#[derive(Clone)]
pub struct RingHapticPlayer {
- tx: tokio::sync::watch::Sender>,
+ tx: tokio::sync::watch::Sender >,
sessions: Arc>,
/// Wakes the worker for a closed session without touching the play slot:
/// an activation buzz queued just before must still play first, and a
@@ -643,29 +711,40 @@ pub struct RingHapticPlayer {
closed: tokio::sync::watch::Sender<()>,
}
-/// What the worker shares with the trigger, the IPC handlers, and the
-/// lifecycle.
-#[derive(Debug, Default)]
-struct Sessions {
- /// What the worker has not looked at yet.
- news: SessionNews,
- /// While set, no session arms the engine: the agent is leaving, or
- /// handing over to a replacement, and an enable made now could not be
- /// handed back.
- paused: bool,
+/// A waveform queued for the worker; the newest replaces any not yet played.
+#[derive(Clone)]
+struct Play {
+ /// The session it plays in. The worker arms a session it has not armed
+ /// yet before its play, so a play never outruns its own arming.
+ session: Session,
+ route: DeviceRoute,
+ waveform: HapticWaveform,
+ interaction: &'static str,
+ /// Where a client waits to hear how its play went, `None` for the ring.
+ reply: Option,
}
-/// What the trigger and the IPC handlers have reported about ring sessions
-/// since the worker last looked. Only the newest of each matters: session ids
-/// only grow, and one session is open at a time.
-#[derive(Debug, Default)]
-struct SessionNews {
- /// The newest session that opened with haptic feedback, and its device.
- opened: Option<(u64, DeviceRoute)>,
- /// The newest session that closed.
- closed: Option,
- /// Hand every engine back now, then answer here.
- hand_back: Option>,
+/// A client's answer slot. Shared because the worker takes the play slot by
+/// clone; a play replaced before the worker took it drops the slot's last
+/// handle unanswered, which the client reads as superseded.
+#[derive(Clone)]
+struct Reply(Arc>>);
+
+/// Where the worker answers one client play.
+type ReplySender = tokio::sync::oneshot::Sender>;
+
+impl Reply {
+ fn new(sender: ReplySender) -> Self {
+ Self(Arc::new(std::sync::Mutex::new(Some(sender))))
+ }
+
+ fn send(&self, result: Result<(), WriteError>) {
+ let sender = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
+ if let Some(sender) = sender {
+ // The client may have given up waiting; nothing is owed to it then.
+ let _ = sender.send(result);
+ }
+ }
}
/// How long every attempt at one buzz may take together.
@@ -700,6 +779,22 @@ const RESTORE_BUDGET: Duration = Duration::from_secs(1);
/// the engine on, as it would if the agent crashed.
const FINISH_BUDGET: Duration = PLAY_BUDGET.saturating_add(RESTORE_BUDGET);
+/// How long a burst of client plays keeps its session after the last play.
+///
+/// A radial menu ticks several times a second while the pointer moves, so
+/// plays this close together share one arming and play from the cached
+/// feature in one round-trip; the engine an arming turned on is handed back
+/// this long after they stop.
+const BURST_IDLE: Duration = Duration::from_secs(2);
+
+/// How long a burst keeps one session before its next play opens a new one.
+///
+/// The ledger hands an open session's enable back
+/// [`SESSION_LIFETIME`](openlogi_agent_core::action_ring::SESSION_LIFETIME) after
+/// it opened, so a burst that kept ticking past that would play into an
+/// engine handed back under it. Renewing re-arms and carries the restore over.
+const BURST_RENEW: Duration = Duration::from_secs(5);
+
/// Re-assert the firmware haptic engine before the session's first buzz,
/// within [`ARM_BUDGET`]. Returns the restore owed when this turned the
/// engine on.
@@ -810,11 +905,14 @@ async fn restore_firmware_haptics(
/// single-flight.
async fn play_within_budget(
shared: &SharedHandles,
- rx: &tokio::sync::watch::Receiver>,
+ rx: &tokio::sync::watch::Receiver >,
route: &DeviceRoute,
waveform: HapticWaveform,
interaction: &'static str,
-) -> PlayOutcome {
+) -> Result<(), WriteError> {
+ let out_of_time = || WriteError::RequestTimedOut {
+ operation: HidppOperation::PlayHaptic,
+ };
let budget = Budget::starting_at(Instant::now(), PLAY_BUDGET);
for attempt in 1..=3u8 {
let Some(remaining) = budget.remaining(Instant::now()) else {
@@ -822,7 +920,7 @@ async fn play_within_budget(
interaction,
"ring haptic gave up — out of time to be feedback"
);
- return PlayOutcome::Failed;
+ return Err(out_of_time());
};
match tokio::time::timeout(
remaining,
@@ -834,17 +932,17 @@ async fn play_within_budget(
)
.await
{
- Ok(Ok(())) => return PlayOutcome::Played,
+ Ok(Ok(())) => return Ok(()),
Ok(Err(error)) if !is_worth_retrying(&error) => {
// Nothing was sent, and every hover asks again: no warning.
debug!(%error, interaction, "Actions Ring haptic skipped");
- return PlayOutcome::Skipped;
+ return Err(error);
}
Ok(Err(error)) => {
let superseded = rx.has_changed().unwrap_or(true);
if attempt == 3 || superseded {
warn!(%error, interaction, attempt, superseded, "Actions Ring haptic failed");
- return PlayOutcome::Failed;
+ return Err(error);
}
}
// Out of budget mid-attempt; the loop head reports it and stops,
@@ -852,7 +950,7 @@ async fn play_within_budget(
Err(_elapsed) => {}
}
}
- PlayOutcome::Failed
+ Err(out_of_time())
}
/// What one interaction's play came to.
@@ -866,6 +964,17 @@ enum PlayOutcome {
Failed,
}
+impl PlayOutcome {
+ /// What a play's result says about the link.
+ fn of(result: &Result<(), WriteError>) -> Self {
+ match result {
+ Ok(()) => Self::Played,
+ Err(error) if !is_worth_retrying(error) => Self::Skipped,
+ Err(_) => Self::Failed,
+ }
+ }
+}
+
/// The circuit breaker over lost plays. When replies keep getting lost,
/// further attempts only keep the channel saturated (and starve unrelated
/// writes), so haptics pause for a short cool-down while the pipe drains;
@@ -957,9 +1066,7 @@ impl Budget {
impl RingHapticPlayer {
/// Spawn the single-flight worker. Must be called from a tokio runtime.
pub fn spawn(shared: SharedHandles) -> Self {
- let (tx, mut rx) = tokio::sync::watch::channel::<
- Option<(DeviceRoute, HapticWaveform, &'static str)>,
- >(None);
+ let (tx, mut rx) = tokio::sync::watch::channel:: >(None);
let (closed, mut closed_rx) = tokio::sync::watch::channel(());
let sessions = Arc::new(std::sync::Mutex::new(Sessions::default()));
let worker_sessions = Arc::clone(&sessions);
@@ -982,49 +1089,32 @@ impl RingHapticPlayer {
due.map_or_else(tokio::time::Instant::now, tokio::time::Instant::from_std),
), if due.is_some() => false,
};
- let (news, paused) = {
- let mut sessions = worker_sessions
- .lock()
- .unwrap_or_else(PoisonError::into_inner);
- (std::mem::take(&mut sessions.news), sessions.paused)
- };
+ let news = worker_sessions
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .take_news();
+ // Closes first, so a session that already closed is never
+ // armed. Restores run last, so a session's last buzz, queued
+ // before its close, still plays before the engine is handed
+ // back.
+ let now = Instant::now();
+ for session in [news.ring_closed, news.burst_closed].into_iter().flatten() {
+ ledger.closed(session, now);
+ }
// Firmware arming is sequenced through this worker so it is
// guaranteed to complete before the session's first buzz —
// spawning it separately let the first hover race (and lose
- // to) a disarmed haptic engine. A session that already closed
- // is not armed at all, nor is one while the agent is leaving.
- if let Some((session, route)) = news.opened
- && !paused
- && news.closed.is_none_or(|closed| closed < session)
+ // to) a disarmed haptic engine. Nothing arms while the agent
+ // is leaving. A ring arms as it opens, so its first hover
+ // plays in one round-trip.
+ if let Some((session, route)) = news.ring_opened
+ && !news.paused
+ && ledger.is_new(session)
{
- // A new session starts the breaker over. It is
- // worker-lifetime state, so without this a session that
- // ended two failures deep makes the next session's first
- // failure trip the cool-down, and a cool-down opened at the
- // tail of one ring silences the opening of the next.
- breaker = HapticBreaker::default();
- let restore = arm_firmware_haptics(&shared, &route).await;
- ledger.opened(session, route, restore, Instant::now());
+ arm_session(&shared, &mut ledger, &mut breaker, session, &route).await;
}
- // Plays before closes: a session's last buzz is queued before
- // its close, so it plays before the engine is handed back.
if woke_for_play || rx.has_changed().unwrap_or(false) {
- let request = rx.borrow_and_update().clone();
- if let Some((route, waveform, interaction)) = request
- && breaker.allows(Instant::now())
- {
- let outcome =
- play_within_budget(&shared, &rx, &route, waveform, interaction).await;
- if breaker.record(outcome, Instant::now()) {
- info!(
- interaction,
- "ring haptics cooling down after repeated HID++ loss"
- );
- }
- }
- }
- if let Some(session) = news.closed {
- ledger.closed(session, Instant::now());
+ play_newest(&shared, &mut rx, &mut ledger, &mut breaker, news.paused).await;
}
if news.hand_back.is_some() {
ledger.leaving(Instant::now());
@@ -1057,33 +1147,26 @@ impl RingHapticPlayer {
let Some(route) = route else {
return;
};
- self.sessions().news.opened = Some((session, route));
+ self.sessions().begin_ring(session, route);
let _ = self.tx.send(None);
}
/// Report that ring session `session` closed, after queueing any buzz it
/// still plays. An enable its arming made is handed back once that buzz
- /// has played. A close older than a device's newest session leaves that
- /// device's engine alone.
+ /// has played and no client burst plays on the engine. A close older
+ /// than the newest ring session leaves that session's engine alone.
pub fn end_session(&self, session: u64) {
- {
- let mut sessions = self.sessions();
- sessions.news.closed = sessions.news.closed.max(Some(session));
- }
+ self.sessions().end_ring(session);
let _ = self.closed.send(());
}
/// End every session as the agent leaves or hands over to a replacement:
- /// hand back each enable still owed, within [`FINISH_BUDGET`], and arm no
- /// session until [`Self::resume`]. Call it while inventory still
- /// publishes the channels the restores need.
+ /// hand back each enable still owed, within [`FINISH_BUDGET`]. Until
+ /// [`Self::resume`], no session arms and client plays are refused. Call
+ /// it while inventory still publishes the channels the restores need.
pub async fn finish(&self) {
let (done, handed_back) = tokio::sync::oneshot::channel();
- {
- let mut sessions = self.sessions();
- sessions.paused = true;
- sessions.news.hand_back = Some(done);
- }
+ self.sessions().finish(done);
let _ = self.closed.send(());
if tokio::time::timeout(FINISH_BUDGET, handed_back)
.await
@@ -1096,16 +1179,81 @@ impl RingHapticPlayer {
/// Arm sessions again after [`Self::finish`]: a replacement did not
/// happen, and the agent stays.
pub fn resume(&self) {
- self.sessions().paused = false;
+ self.sessions().resume();
+ }
+
+ /// Play `waveform` on `route` for a client other than the ring, and
+ /// answer with how it went.
+ ///
+ /// Consecutive plays on one device share a haptic session, a burst: its
+ /// first play opens the session with an ID from `new_session`, so the
+ /// worker arms the engine first, and later plays reuse the cached feature
+ /// in one round-trip. The session closes [`BURST_IDLE`] after the last
+ /// play, which hands back any enable its arming made once no ring plays
+ /// on the engine either, and renews after [`BURST_RENEW`]. A play
+ /// replaced before it reached the device answers
+ /// [`WriteError::WriteSuperseded`], and one while the agent is leaving
+ /// or handing over answers [`WriteError::AgentUnavailable`].
+ pub async fn play_external(
+ &self,
+ route: DeviceRoute,
+ waveform: HapticWaveform,
+ new_session: impl FnOnce() -> u64,
+ ) -> Result<(), WriteError> {
+ let (sender, answer) = tokio::sync::oneshot::channel();
+ let pending = {
+ let mut sessions = self.sessions();
+ let id = sessions
+ .join_burst(&route, tokio::time::Instant::now(), new_session)
+ .map_err(|Paused| WriteError::AgentUnavailable)?;
+ // Queued under the lock that ordered the join, so plays reach
+ // the worker in burst order: none carries a burst older than
+ // one the worker may already have armed past, which would play
+ // unarmed.
+ let _ = self.tx.send(Some(Play {
+ session: Session {
+ lane: Lane::Client,
+ id,
+ },
+ route,
+ waveform,
+ interaction: "client",
+ reply: Some(Reply::new(sender)),
+ }));
+ PendingPlay {
+ player: self.clone(),
+ session: id,
+ }
+ };
+ let answered = answer.await;
+ drop(pending);
+ answered.unwrap_or(Err(WriteError::WriteSuperseded {
+ operation: HidppOperation::PlayHaptic,
+ }))
+ }
+
+ /// Close burst `session` if no play is waiting on it and none was
+ /// answered for [`BURST_IDLE`]. A later play's own timer closes it
+ /// otherwise, and a renewed burst's old session is left to the ledger,
+ /// which ends it as the new session opens.
+ fn close_idle_burst(&self, session: u64) {
+ if self
+ .sessions()
+ .close_idle_burst(session, tokio::time::Instant::now())
+ {
+ let _ = self.closed.send(());
+ }
}
fn sessions(&self) -> std::sync::MutexGuard<'_, Sessions> {
self.sessions.lock().unwrap_or_else(PoisonError::into_inner)
}
- /// Queue `waveform`, replacing any not-yet-played request.
+ /// Queue `waveform` for ring session `session`, replacing any
+ /// not-yet-played request.
fn play(
&self,
+ session: u64,
route: Option,
waveform: HapticWaveform,
interaction: &'static str,
@@ -1113,10 +1261,111 @@ impl RingHapticPlayer {
let Some(route) = route else {
return;
};
- let _ = self.tx.send(Some((route, waveform, interaction)));
+ let _ = self.tx.send(Some(Play {
+ session: Session {
+ lane: Lane::Ring,
+ id: session,
+ },
+ route,
+ waveform,
+ interaction,
+ reply: None,
+ }));
}
}
+/// Play the newest queued waveform, arming its session first if the worker
+/// has not yet, and answer the client that queued it.
+///
+/// A session can open while another device's arming runs, so a play reads
+/// its own session to know whether it still needs arming. A pass arms at
+/// most one session and then plays the play it armed for, even if a newer
+/// one arrived meanwhile: that one stays queued for the next pass. Switching
+/// to it would arm again, and plays alternating between devices faster than
+/// arming completes would then keep the worker arming forever, playing no
+/// pulse and handing no engine back. While `paused`, nothing arms, and a
+/// client play is refused: unarmed, its buzz may not be felt, and the client
+/// hears so rather than a false success.
+async fn play_newest(
+ shared: &SharedHandles,
+ rx: &mut tokio::sync::watch::Receiver>,
+ ledger: &mut RestoreLedger,
+ breaker: &mut HapticBreaker,
+ paused: bool,
+) {
+ let Some(play) = rx.borrow_and_update().clone() else {
+ return;
+ };
+ if !paused && ledger.is_new(play.session) {
+ arm_session(shared, ledger, breaker, play.session, &play.route).await;
+ }
+ let result = if paused && play.session.lane == Lane::Client {
+ Err(WriteError::AgentUnavailable)
+ } else if breaker.allows(Instant::now()) {
+ let result =
+ play_within_budget(shared, rx, &play.route, play.waveform, play.interaction).await;
+ if breaker.record(PlayOutcome::of(&result), Instant::now()) {
+ info!(
+ interaction = play.interaction,
+ "ring haptics cooling down after repeated HID++ loss"
+ );
+ }
+ result
+ } else {
+ // Cooling down after lost replies: the play is dropped as one more
+ // would be lost.
+ Err(WriteError::RequestTimedOut {
+ operation: HidppOperation::PlayHaptic,
+ })
+ };
+ if let Some(reply) = play.reply {
+ reply.send(result);
+ }
+}
+
+/// A client play its burst still waits on. Dropping it, once the play is
+/// answered or its client gave up, starts the burst's idle clock: a burst
+/// never closes under a play the worker has not armed for yet.
+struct PendingPlay {
+ player: RingHapticPlayer,
+ session: u64,
+}
+
+impl Drop for PendingPlay {
+ fn drop(&mut self) {
+ self.player
+ .sessions()
+ .settle(self.session, tokio::time::Instant::now());
+ // Outside a runtime the agent is gone, and its ledger with it.
+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {
+ let player = self.player.clone();
+ let session = self.session;
+ runtime.spawn(async move {
+ tokio::time::sleep(BURST_IDLE).await;
+ player.close_idle_burst(session);
+ });
+ }
+ }
+}
+
+/// Arm `session`'s engine on `route` within [`ARM_BUDGET`] and record it, so
+/// the enable that arming made is owed back once the session is over.
+async fn arm_session(
+ shared: &SharedHandles,
+ ledger: &mut RestoreLedger,
+ breaker: &mut HapticBreaker,
+ session: Session,
+ route: &DeviceRoute,
+) {
+ // A new session starts the breaker over. It is worker-lifetime state,
+ // so without this a session that ended two failures deep makes the next
+ // session's first failure trip the cool-down, and a cool-down opened at
+ // the tail of one ring silences the opening of the next.
+ *breaker = HapticBreaker::default();
+ let restore = arm_firmware_haptics(shared, route).await;
+ ledger.opened(session, route.clone(), restore, Instant::now());
+}
+
/// Bind the agent's IPC socket and serve [`Agent`] requests until the process
/// exits. A stale socket left by a prior crash is reclaimed by the listener —
/// `main` holds the single-instance lock (`agent.lock`), so no other live agent
@@ -1175,6 +1424,19 @@ mod tests {
use std::sync::{Arc, PoisonError};
use std::time::{Duration, Instant};
+ mod client_play;
+
+ /// A burst of client plays renews its session while the ledger still
+ /// holds its restore, so continuous ticking never plays into an engine
+ /// handed back under it, even behind an arming.
+ #[test]
+ fn a_burst_renews_before_its_session_expires() {
+ assert!(
+ super::BURST_RENEW + super::BURST_IDLE + ARM_BUDGET
+ < openlogi_agent_core::action_ring::SESSION_LIFETIME
+ );
+ }
+
fn disable_keys_response(request: &[u8]) -> Option> {
if request.len() < 7 || !matches!(request[0], 0x10 | 0x11) {
return None;
diff --git a/crates/openlogi-agent/src/server/haptic_restore.rs b/crates/openlogi-agent/src/server/haptic_restore.rs
index 3760166c16..5202e02aa7 100644
--- a/crates/openlogi-agent/src/server/haptic_restore.rs
+++ b/crates/openlogi-agent/src/server/haptic_restore.rs
@@ -1,6 +1,6 @@
-//! Which device-wide haptic enables the Actions Ring still owes back.
+//! Which device-wide haptic enables the agent still owes back.
//!
-//! Arming may turn a device's haptic engine on for a ring session
+//! Arming may turn a device's haptic engine on for a session
//! ([`openlogi_hid::ensure_haptics_armed_on`]). That flag is device-wide, so
//! leaving it on would override a user who turned haptics off in another app.
//! This ledger decides when each enable is handed back; the worker in
@@ -21,99 +21,164 @@ use openlogi_hid::{DeviceRoute, HidppFeatureErrorKind, WriteError};
/// the engine back soon after it returns.
pub(super) const RESTORE_RETRY: Duration = Duration::from_secs(10);
-/// One device whose haptic engine a ring session turned on.
+/// Who opened a haptic session.
+///
+/// Each lane holds at most one open session: a ring replaces the ring
+/// before it, and a client burst the burst before it. The two lanes are
+/// independent, so a ring and a burst can play on one engine at once.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum Lane {
+ /// The Actions Ring.
+ Ring,
+ /// A client's burst of plays.
+ Client,
+}
+
+/// One haptic session: its lane and its ID, which only grows within a lane.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct Session {
+ pub(super) lane: Lane,
+ pub(super) id: u64,
+}
+
+/// One device whose haptic engine a session turned on.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Owed {
/// The device to hand the engine back on.
pub(super) route: DeviceRoute,
/// What arming proved, for the restore to check the device against.
pub(super) restore: R,
- /// The newest session that may still play on the engine.
- session: u64,
- /// When the restore is attempted without waiting any longer for a close.
+ /// When the restore is attempted once no open session plays on the
+ /// engine.
due: Instant,
}
-/// The enables still owed back, at most one per device.
+/// A lane's open session.
+#[derive(Debug)]
+struct Open {
+ id: u64,
+ route: DeviceRoute,
+ /// When the session is over without a close.
+ ends: Instant,
+}
+
+/// What one lane has opened and closed.
+#[derive(Debug, Default)]
+struct LaneState {
+ /// The newest session the lane opened or closed. A session no newer is
+ /// never opened again: its close already arrived, or it is open.
+ newest: Option,
+ open: Option,
+}
+
+/// The enables still owed back, at most one per device, and the sessions
+/// still playing on them.
+///
+/// An engine is handed back only once no open session plays on it: a ring
+/// closing does not turn off the engine a client burst still plays on, nor
+/// the other way round.
#[derive(Debug)]
pub(super) struct RestoreLedger {
owed: Vec>,
+ ring: LaneState,
+ client: LaneState,
}
impl Default for RestoreLedger {
fn default() -> Self {
- Self { owed: Vec::new() }
+ Self {
+ owed: Vec::new(),
+ ring: LaneState::default(),
+ client: LaneState::default(),
+ }
}
}
impl RestoreLedger {
- /// Session `session` opened on `route`, and arming it returned `restore`:
- /// `Some` when that arming turned the engine on.
+ /// Whether `session` is newer than anything its lane has opened or
+ /// closed, so arming it is still owed.
+ pub(super) fn is_new(&self, session: Session) -> bool {
+ self.lane(session.lane)
+ .newest
+ .is_none_or(|newest| session.id > newest)
+ }
+
+ /// `session` opened on `route`, and arming it returned `restore`: `Some`
+ /// when that arming turned the engine on. A session that is not
+ /// [new](Self::is_new) is ignored.
///
- /// Only one session is open at a time, so every other device's session
- /// has ended, and its restore is due at `now`. This device's restore, if
- /// it already owes one, moves to the new session instead: the session
- /// plays on the engine that enable left on, and handing it back first
- /// would only turn it off and on again. A session that never reports its
- /// close is over [`SESSION_LIFETIME`] after `now`.
+ /// The session replaces its lane's previous one, which is over. An
+ /// enable `route` already owes stays owed until this session is over
+ /// too: the session plays on the engine that enable left on, and
+ /// handing it back first would only turn it off and on again. A session
+ /// that never reports its close is over [`SESSION_LIFETIME`] after `now`.
+ /// Every engine no session plays on any more is handed back at `now`.
pub(super) fn opened(
&mut self,
- session: u64,
+ session: Session,
route: DeviceRoute,
restore: Option,
now: Instant,
) {
- let ends = now + SESSION_LIFETIME;
- for owed in &mut self.owed {
- if owed.route != route {
- owed.due = owed.due.min(now);
- }
+ if !self.is_new(session) {
+ return;
}
- if let Some(owed) = self.owed.iter_mut().find(|owed| owed.route == route) {
- owed.session = session;
- owed.due = ends;
- if let Some(restore) = restore {
+ let lane = self.lane_mut(session.lane);
+ lane.newest = Some(session.id);
+ lane.open = Some(Open {
+ id: session.id,
+ route: route.clone(),
+ ends: now + SESSION_LIFETIME,
+ });
+ self.due_at_latest(now);
+ if let Some(restore) = restore {
+ if let Some(owed) = self.owed.iter_mut().find(|owed| owed.route == route) {
owed.restore = restore;
+ } else {
+ self.owed.push(Owed {
+ route,
+ restore,
+ due: now,
+ });
}
- } else if let Some(restore) = restore {
- self.owed.push(Owed {
- route,
- restore,
- session,
- due: ends,
- });
}
}
- /// Session `session` closed. Restores owed for it, or for an older
- /// session, are due at `now`. A newer session's restore waits: a close
- /// that arrives late must not turn off the engine the next session plays
- /// on.
- pub(super) fn closed(&mut self, session: u64, now: Instant) {
- for owed in &mut self.owed {
- if owed.session <= session {
- owed.due = owed.due.min(now);
- }
+ /// `session` closed, and with it any older session of its lane. Restores
+ /// no other open session still plays on are due at `now`. A close older
+ /// than its lane's open session leaves that session open: a close that
+ /// arrives late must not turn off the engine the next session plays on.
+ pub(super) fn closed(&mut self, session: Session, now: Instant) {
+ let lane = self.lane_mut(session.lane);
+ lane.newest = lane.newest.max(Some(session.id));
+ if lane.open.as_ref().is_some_and(|open| open.id <= session.id) {
+ lane.open = None;
}
+ self.due_at_latest(now);
}
/// The agent is leaving, or handing over to a replacement, which ends
/// every session: every restore is due at `now`.
pub(super) fn leaving(&mut self, now: Instant) {
- for owed in &mut self.owed {
- owed.due = owed.due.min(now);
- }
+ self.ring.open = None;
+ self.client.open = None;
+ self.due_at_latest(now);
}
/// When the next restore is due, or `None` when nothing is owed.
pub(super) fn next_due(&self) -> Option {
- self.owed.iter().map(|owed| owed.due).min()
+ self.owed.iter().map(|owed| self.due(owed)).min()
}
/// Take one restore that is due at `now`. It is no longer owed unless
/// the caller hands it back through [`Self::retry`].
pub(super) fn take_due(&mut self, now: Instant) -> Option> {
- let index = self.owed.iter().position(|owed| owed.due <= now)?;
+ for lane in [&mut self.ring, &mut self.client] {
+ if lane.open.as_ref().is_some_and(|open| open.ends <= now) {
+ lane.open = None;
+ }
+ }
+ let index = self.owed.iter().position(|owed| self.due(owed) <= now)?;
Some(self.owed.swap_remove(index))
}
@@ -132,6 +197,41 @@ impl RestoreLedger {
owed.due = now + RESTORE_RETRY;
self.owed.push(owed);
}
+
+ /// When `owed` is due: once the last open session on its device is
+ /// over, or at its own time when none is.
+ fn due(&self, owed: &Owed) -> Instant {
+ [&self.ring, &self.client]
+ .into_iter()
+ .filter_map(|lane| lane.open.as_ref())
+ .filter(|open| open.route == owed.route)
+ .map(|open| open.ends)
+ .max()
+ .unwrap_or(owed.due)
+ }
+
+ /// A session opening or closing is a fresh chance to reach every device:
+ /// each restore is due at `now` at the latest, once no open session plays
+ /// on its engine (see [`Self::due`]).
+ fn due_at_latest(&mut self, now: Instant) {
+ for owed in &mut self.owed {
+ owed.due = owed.due.min(now);
+ }
+ }
+
+ fn lane(&self, lane: Lane) -> &LaneState {
+ match lane {
+ Lane::Ring => &self.ring,
+ Lane::Client => &self.client,
+ }
+ }
+
+ fn lane_mut(&mut self, lane: Lane) -> &mut LaneState {
+ match lane {
+ Lane::Ring => &mut self.ring,
+ Lane::Client => &mut self.client,
+ }
+ }
}
/// Whether a failed restore never reached the device, so a later attempt can
@@ -176,6 +276,20 @@ mod tests {
}
}
+ fn ring(id: u64) -> Session {
+ Session {
+ lane: Lane::Ring,
+ id,
+ }
+ }
+
+ fn client(id: u64) -> Session {
+ Session {
+ lane: Lane::Client,
+ id,
+ }
+ }
+
/// Every restore due at `now`, as (route, proof) pairs.
fn due(ledger: &mut RestoreLedger, now: Instant) -> Vec<(DeviceRoute, u8)> {
std::iter::from_fn(|| ledger.take_due(now))
@@ -187,10 +301,10 @@ mod tests {
fn a_session_that_turned_the_engine_on_hands_it_back_when_it_closes() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
let closed = start + Duration::from_secs(2);
assert_eq!(due(&mut ledger, closed), vec![], "still open");
- ledger.closed(1, closed);
+ ledger.closed(ring(1), closed);
assert_eq!(due(&mut ledger, closed), vec![(mouse(), 7)]);
assert_eq!(ledger.next_due(), None, "handed back once");
}
@@ -199,9 +313,9 @@ mod tests {
fn a_session_that_found_the_engine_on_owes_nothing() {
let start = Instant::now();
let mut ledger = RestoreLedger::::default();
- ledger.opened(1, mouse(), None, start);
+ ledger.opened(ring(1), mouse(), None, start);
assert_eq!(ledger.next_due(), None);
- ledger.closed(1, start);
+ ledger.closed(ring(1), start);
assert_eq!(due(&mut ledger, start + SESSION_LIFETIME), vec![]);
}
@@ -209,7 +323,7 @@ mod tests {
fn a_session_whose_close_never_arrives_is_handed_back_once_it_must_have_expired() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
assert_eq!(ledger.next_due(), Some(start + SESSION_LIFETIME));
let just_before = start + SESSION_LIFETIME.saturating_sub(Duration::from_millis(1));
assert_eq!(due(&mut ledger, just_before), vec![]);
@@ -223,15 +337,15 @@ mod tests {
fn a_late_close_does_not_turn_off_the_engine_a_newer_session_plays_on() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
// The next session on the same mouse finds the engine on: the enable
// it plays on is still session 1's, so it carries the restore.
let reopened = start + Duration::from_secs(1);
- ledger.opened(2, mouse(), None, reopened);
- ledger.closed(1, reopened);
+ ledger.opened(ring(2), mouse(), None, reopened);
+ ledger.closed(ring(1), reopened);
assert_eq!(due(&mut ledger, reopened), vec![]);
assert_eq!(ledger.next_due(), Some(reopened + SESSION_LIFETIME));
- ledger.closed(2, reopened);
+ ledger.closed(ring(2), reopened);
assert_eq!(due(&mut ledger, reopened), vec![(mouse(), 7)]);
}
@@ -239,10 +353,10 @@ mod tests {
fn a_newer_arming_replaces_the_proof_it_supersedes() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
// Something cleared the flag between sessions; arming set it again.
- ledger.opened(2, mouse(), Some(8), start);
- ledger.closed(2, start);
+ ledger.opened(ring(2), mouse(), Some(8), start);
+ ledger.closed(ring(2), start);
assert_eq!(due(&mut ledger, start), vec![(mouse(), 8)]);
}
@@ -250,11 +364,11 @@ mod tests {
fn a_session_on_another_device_ends_the_previous_one() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
let switched = start + Duration::from_secs(1);
- ledger.opened(2, other_mouse(), Some(9), switched);
+ ledger.opened(ring(2), other_mouse(), Some(9), switched);
assert_eq!(due(&mut ledger, switched), vec![(mouse(), 7)]);
- ledger.closed(2, switched);
+ ledger.closed(ring(2), switched);
assert_eq!(due(&mut ledger, switched), vec![(other_mouse(), 9)]);
}
@@ -263,13 +377,13 @@ mod tests {
let start = Instant::now();
// A session still open.
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
assert_eq!(due(&mut ledger, start), vec![]);
ledger.leaving(start);
assert_eq!(due(&mut ledger, start), vec![(mouse(), 7)]);
// A restore waiting for its next attempt.
- ledger.opened(2, mouse(), Some(8), start);
- ledger.closed(2, start);
+ ledger.opened(ring(2), mouse(), Some(8), start);
+ ledger.closed(ring(2), start);
let owed = ledger.take_due(start).expect("due at the close");
ledger.retry(owed, start);
assert_eq!(due(&mut ledger, start), vec![]);
@@ -281,8 +395,8 @@ mod tests {
fn an_unreached_device_is_tried_again_later() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
- ledger.closed(1, start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
+ ledger.closed(ring(1), start);
let owed = ledger.take_due(start).expect("due at the close");
ledger.retry(owed, start);
assert_eq!(ledger.next_due(), Some(start + RESTORE_RETRY));
@@ -296,7 +410,7 @@ mod tests {
// A ring opened on another device is a fresh chance to try, so the
// restore does not wait for the pace.
let switched = start + Duration::from_secs(1);
- ledger.opened(2, other_mouse(), None, switched);
+ ledger.opened(ring(2), other_mouse(), None, switched);
assert_eq!(due(&mut ledger, switched), vec![(mouse(), 7)]);
}
@@ -304,15 +418,15 @@ mod tests {
fn an_unreached_device_that_opens_a_session_waits_for_that_session() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
- ledger.closed(1, start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
+ ledger.closed(ring(1), start);
let owed = ledger.take_due(start).expect("due at the close");
ledger.retry(owed, start);
// The mouse is back and opens a ring: the engine stays on for it.
let back = start + Duration::from_secs(30);
- ledger.opened(2, mouse(), None, back);
+ ledger.opened(ring(2), mouse(), None, back);
assert_eq!(due(&mut ledger, back), vec![]);
- ledger.closed(2, back);
+ ledger.closed(ring(2), back);
assert_eq!(due(&mut ledger, back), vec![(mouse(), 7)]);
}
@@ -320,16 +434,110 @@ mod tests {
fn a_retry_never_duplicates_a_device_that_owes_a_newer_restore() {
let start = Instant::now();
let mut ledger = RestoreLedger::default();
- ledger.opened(1, mouse(), Some(7), start);
- ledger.closed(1, start);
+ ledger.opened(ring(1), mouse(), Some(7), start);
+ ledger.closed(ring(1), start);
let stale = ledger.take_due(start).expect("due at the close");
- ledger.opened(2, mouse(), Some(8), start);
+ ledger.opened(ring(2), mouse(), Some(8), start);
ledger.retry(stale, start);
- ledger.closed(2, start);
+ ledger.closed(ring(2), start);
assert_eq!(due(&mut ledger, start), vec![(mouse(), 8)]);
assert_eq!(ledger.next_due(), None);
}
+ #[test]
+ fn a_ring_and_a_burst_on_one_engine_hand_it_back_once_both_closed() {
+ let start = Instant::now();
+ let later = start + Duration::from_secs(1);
+ // Ring first, the burst closing first; then the burst first, the
+ // ring closing first.
+ for (first, second) in [(ring(1), client(2)), (client(1), ring(2))] {
+ for closing_first in [first, second] {
+ let closing_last = if closing_first == first {
+ second
+ } else {
+ first
+ };
+ let mut ledger = RestoreLedger::default();
+ ledger.opened(first, mouse(), Some(7), start);
+ // The second finds the engine the first turned on.
+ ledger.opened(second, mouse(), None, start);
+ ledger.closed(closing_first, later);
+ assert_eq!(
+ due(&mut ledger, later),
+ vec![],
+ "{closing_last:?} still plays on the engine"
+ );
+ assert_eq!(ledger.next_due(), Some(start + SESSION_LIFETIME));
+ ledger.closed(closing_last, later);
+ assert_eq!(due(&mut ledger, later), vec![(mouse(), 7)]);
+ assert_eq!(ledger.next_due(), None, "handed back once");
+ }
+ }
+ }
+
+ #[test]
+ fn a_close_in_one_lane_never_closes_the_other_lanes_older_session() {
+ let start = Instant::now();
+ let mut ledger = RestoreLedger::default();
+ ledger.opened(ring(1), mouse(), Some(7), start);
+ ledger.opened(client(2), other_mouse(), Some(9), start);
+ // A newer close, but the burst's: the ring on the other mouse
+ // stays open.
+ ledger.closed(client(2), start);
+ assert_eq!(due(&mut ledger, start), vec![(other_mouse(), 9)]);
+ assert_eq!(ledger.next_due(), Some(start + SESSION_LIFETIME));
+ ledger.closed(ring(1), start);
+ assert_eq!(due(&mut ledger, start), vec![(mouse(), 7)]);
+ }
+
+ #[test]
+ fn a_session_whose_close_arrived_first_or_that_is_open_is_never_new() {
+ let start = Instant::now();
+ let mut ledger = RestoreLedger::::default();
+ assert!(ledger.is_new(ring(3)));
+ ledger.closed(ring(3), start);
+ assert!(!ledger.is_new(ring(3)), "closed before it was armed");
+ assert!(
+ ledger.is_new(client(3)),
+ "the other lane keeps its own count"
+ );
+ ledger.opened(client(3), mouse(), None, start);
+ assert!(!ledger.is_new(client(3)), "already armed");
+ assert!(!ledger.is_new(client(2)), "older than the open burst");
+ assert!(ledger.is_new(client(4)));
+ // An arming for a session that is not new changes nothing.
+ ledger.opened(client(2), other_mouse(), Some(9), start);
+ assert_eq!(ledger.next_due(), None);
+ }
+
+ #[test]
+ fn a_burst_that_moves_to_another_device_hands_back_the_one_it_left() {
+ let start = Instant::now();
+ let mut ledger = RestoreLedger::default();
+ ledger.opened(ring(1), mouse(), Some(7), start);
+ ledger.opened(client(2), mouse(), None, start);
+ ledger.opened(client(3), other_mouse(), Some(9), start);
+ assert_eq!(
+ due(&mut ledger, start),
+ vec![],
+ "the ring still plays on the mouse"
+ );
+ ledger.opened(client(4), mouse(), None, start);
+ assert_eq!(due(&mut ledger, start), vec![(other_mouse(), 9)]);
+ }
+
+ #[test]
+ fn leaving_ends_both_lanes() {
+ let start = Instant::now();
+ let mut ledger = RestoreLedger::default();
+ ledger.opened(ring(1), mouse(), Some(7), start);
+ ledger.opened(client(2), other_mouse(), Some(9), start);
+ ledger.leaving(start);
+ let mut handed_back = due(&mut ledger, start);
+ handed_back.sort_by_key(|(_, proof)| *proof);
+ assert_eq!(handed_back, vec![(mouse(), 7), (other_mouse(), 9)]);
+ }
+
#[test]
fn only_failures_that_never_reached_the_device_are_tried_again() {
let operation = HidppOperation::PlayHaptic;
diff --git a/crates/openlogi-agent/src/server/haptic_sessions.rs b/crates/openlogi-agent/src/server/haptic_sessions.rs
new file mode 100644
index 0000000000..4f547d4868
--- /dev/null
+++ b/crates/openlogi-agent/src/server/haptic_sessions.rs
@@ -0,0 +1,299 @@
+//! What the ring, client plays, and the lifecycle tell the haptic worker.
+//!
+//! One mutable owner for the sessions the worker has not looked at yet, the
+//! open client burst, and whether the agent is leaving: its methods are the
+//! only writers, so a burst cannot outlive a hand-back or open while the
+//! agent is leaving. The worker in [`super::RingHapticPlayer`] takes a
+//! snapshot with [`Sessions::take_news`] and does the I/O.
+
+use openlogi_hid::DeviceRoute;
+use tokio::sync::oneshot;
+use tokio::time::Instant;
+
+use super::haptic_restore::{Lane, Session};
+use super::{BURST_IDLE, BURST_RENEW};
+
+/// The haptic session state the trigger, the IPC handlers, the lifecycle,
+/// and the worker share.
+#[derive(Debug)]
+pub(super) struct Sessions {
+ /// The newest ring session that opened with haptic feedback, and its
+ /// device, not yet seen by the worker.
+ ring_opened: Option<(u64, DeviceRoute)>,
+ /// The newest ring session that closed, not yet seen by the worker.
+ ring_closed: Option,
+ /// The newest client burst that went idle, not yet seen by the worker.
+ burst_closed: Option,
+ phase: Phase,
+}
+
+#[derive(Debug)]
+enum Phase {
+ /// Sessions arm the engine, and consecutive client plays on one device
+ /// share `burst`.
+ Running { burst: Option },
+ /// The agent is leaving or handing over to a replacement: no session
+ /// arms, since an enable made now could not be handed back, and client
+ /// plays are refused. `hand_back` asks the worker to hand every engine
+ /// back, then answers.
+ Paused {
+ hand_back: Option>,
+ },
+}
+
+/// The haptic session consecutive client plays on one device share.
+#[derive(Debug)]
+struct Burst {
+ session: u64,
+ route: DeviceRoute,
+ opened: Instant,
+ /// Plays joined but not yet answered. The burst stays open while any
+ /// waits, however long the worker takes to reach it.
+ pending: usize,
+ /// When the last play was answered.
+ last: Instant,
+}
+
+/// A client play refused because the agent is leaving.
+#[derive(Debug, PartialEq, Eq)]
+pub(super) struct Paused;
+
+/// What the worker has not looked at yet, taken in one snapshot.
+#[derive(Debug, Default)]
+pub(super) struct News {
+ pub(super) ring_opened: Option<(Session, DeviceRoute)>,
+ pub(super) ring_closed: Option,
+ pub(super) burst_closed: Option,
+ /// No session arms, and no client play plays.
+ pub(super) paused: bool,
+ /// Hand every engine back now, then answer here.
+ pub(super) hand_back: Option>,
+}
+
+impl Default for Sessions {
+ fn default() -> Self {
+ Self {
+ ring_opened: None,
+ ring_closed: None,
+ burst_closed: None,
+ phase: Phase::Running { burst: None },
+ }
+ }
+}
+
+impl Sessions {
+ /// Ring session `session` opened on `route`.
+ pub(super) fn begin_ring(&mut self, session: u64, route: DeviceRoute) {
+ self.ring_opened = Some((session, route));
+ }
+
+ /// Ring session `session` closed, and with it any older ring session.
+ pub(super) fn end_ring(&mut self, session: u64) {
+ self.ring_closed = self.ring_closed.max(Some(session));
+ }
+
+ /// The burst session a client play on `route` at `now` belongs to; the
+ /// burst stays open until the play [settles](Self::settle).
+ ///
+ /// It joins the open burst on `route` unless that burst is
+ /// [`BURST_RENEW`] old; otherwise it opens a new one with an ID from
+ /// `new_session`, which replaces any burst open on another device.
+ pub(super) fn join_burst(
+ &mut self,
+ route: &DeviceRoute,
+ now: Instant,
+ new_session: impl FnOnce() -> u64,
+ ) -> Result {
+ let Phase::Running { burst } = &mut self.phase else {
+ return Err(Paused);
+ };
+ if let Some(open) = burst
+ .as_mut()
+ .filter(|open| open.route == *route && now < open.opened + BURST_RENEW)
+ {
+ open.pending += 1;
+ return Ok(open.session);
+ }
+ let session = new_session();
+ *burst = Some(Burst {
+ session,
+ route: route.clone(),
+ opened: now,
+ pending: 1,
+ last: now,
+ });
+ Ok(session)
+ }
+
+ /// A play that joined burst `session` was answered, or its client gave
+ /// up, at `now`.
+ pub(super) fn settle(&mut self, session: u64, now: Instant) {
+ if let Phase::Running { burst: Some(open) } = &mut self.phase
+ && open.session == session
+ {
+ open.pending = open.pending.saturating_sub(1);
+ open.last = now;
+ }
+ }
+
+ /// Close burst `session` if no play waits on it and none was answered
+ /// for [`BURST_IDLE`] up to `now`. Returns whether it closed, so the
+ /// worker hands its engine back.
+ pub(super) fn close_idle_burst(&mut self, session: u64, now: Instant) -> bool {
+ let Phase::Running { burst } = &mut self.phase else {
+ return false;
+ };
+ if !burst.as_ref().is_some_and(|open| {
+ open.session == session && open.pending == 0 && now - open.last >= BURST_IDLE
+ }) {
+ return false;
+ }
+ *burst = None;
+ self.burst_closed = self.burst_closed.max(Some(session));
+ true
+ }
+
+ /// The agent is leaving or handing over: end the burst, arm nothing, and
+ /// ask the worker to hand every engine back, answering on `done`.
+ pub(super) fn finish(&mut self, done: oneshot::Sender<()>) {
+ self.phase = Phase::Paused {
+ hand_back: Some(done),
+ };
+ }
+
+ /// The agent stays after [`Self::finish`]: sessions arm again, and the
+ /// next client play opens a new burst. A hand-back the worker has not
+ /// taken yet is dropped with the pause: it would end sessions that open
+ /// from now on.
+ pub(super) fn resume(&mut self) {
+ self.phase = Phase::Running { burst: None };
+ }
+
+ /// Take everything the worker has not looked at yet.
+ pub(super) fn take_news(&mut self) -> News {
+ let (paused, hand_back) = match &mut self.phase {
+ Phase::Running { .. } => (false, None),
+ Phase::Paused { hand_back } => (true, hand_back.take()),
+ };
+ let ring = |id| Session {
+ lane: Lane::Ring,
+ id,
+ };
+ News {
+ ring_opened: self.ring_opened.take().map(|(id, route)| (ring(id), route)),
+ ring_closed: self.ring_closed.take().map(ring),
+ burst_closed: self.burst_closed.take().map(|id| Session {
+ lane: Lane::Client,
+ id,
+ }),
+ paused,
+ hand_back,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use super::*;
+
+ fn mouse() -> DeviceRoute {
+ DeviceRoute::Direct {
+ vendor_id: 0x046d,
+ product_id: 0xb042,
+ }
+ }
+
+ fn other_mouse() -> DeviceRoute {
+ DeviceRoute::Direct {
+ vendor_id: 0x046d,
+ product_id: 0xb034,
+ }
+ }
+
+ #[test]
+ fn plays_on_one_device_share_a_burst_until_it_renews_or_moves() {
+ let start = Instant::now();
+ let mut sessions = Sessions::default();
+ let mut ids = 1..;
+ let mut join = |sessions: &mut Sessions, route, at| {
+ sessions.join_burst(&route, at, || ids.next().expect("an ID"))
+ };
+ assert_eq!(join(&mut sessions, mouse(), start), Ok(1));
+ assert_eq!(
+ join(&mut sessions, mouse(), start + Duration::from_secs(1)),
+ Ok(1)
+ );
+ assert_eq!(
+ join(&mut sessions, mouse(), start + BURST_RENEW),
+ Ok(2),
+ "renewed"
+ );
+ assert_eq!(
+ join(&mut sessions, other_mouse(), start + BURST_RENEW),
+ Ok(3),
+ "another device opens its own"
+ );
+ }
+
+ #[test]
+ fn a_burst_closes_only_once_every_play_settled_and_it_sat_idle() {
+ let start = Instant::now();
+ let mut sessions = Sessions::default();
+ assert_eq!(sessions.join_burst(&mouse(), start, || 1), Ok(1));
+ assert_eq!(sessions.join_burst(&mouse(), start, || 2), Ok(1));
+ let late = start + BURST_IDLE * 3;
+ assert!(
+ !sessions.close_idle_burst(1, late),
+ "two plays still wait on it, however long the worker takes"
+ );
+ let answered = start + Duration::from_secs(1);
+ sessions.settle(1, answered);
+ assert!(!sessions.close_idle_burst(1, late), "one play still waits");
+ sessions.settle(1, answered);
+ assert!(
+ !sessions.close_idle_burst(1, answered + BURST_IDLE / 2),
+ "answered too recently"
+ );
+ assert!(!sessions.close_idle_burst(9, late), "not this burst");
+ assert!(sessions.close_idle_burst(1, answered + BURST_IDLE));
+ assert_eq!(
+ sessions.take_news().burst_closed,
+ Some(Session {
+ lane: Lane::Client,
+ id: 1
+ })
+ );
+ assert!(!sessions.close_idle_burst(1, late), "closed once");
+ }
+
+ #[test]
+ fn a_hand_back_ends_the_burst_and_refuses_client_plays_until_resumed() {
+ let start = Instant::now();
+ let mut sessions = Sessions::default();
+ assert_eq!(sessions.join_burst(&mouse(), start, || 1), Ok(1));
+ let (done, _answer) = oneshot::channel();
+ sessions.finish(done);
+ assert_eq!(sessions.join_burst(&mouse(), start, || 2), Err(Paused));
+ assert!(
+ !sessions.close_idle_burst(1, start + BURST_IDLE),
+ "already ended"
+ );
+ let news = sessions.take_news();
+ assert!(news.paused);
+ assert!(
+ news.hand_back.is_some(),
+ "the worker hears the hand-back once"
+ );
+ assert!(sessions.take_news().hand_back.is_none());
+
+ sessions.resume();
+ assert!(!sessions.take_news().paused);
+ assert_eq!(
+ sessions.join_burst(&mouse(), start, || 3),
+ Ok(3),
+ "the burst from before the hand-back is gone"
+ );
+ }
+}
diff --git a/crates/openlogi-agent/src/server/tests/client_play.rs b/crates/openlogi-agent/src/server/tests/client_play.rs
new file mode 100644
index 0000000000..1acde03baf
--- /dev/null
+++ b/crates/openlogi-agent/src/server/tests/client_play.rs
@@ -0,0 +1,672 @@
+//! Haptics a client plays through [`RingHapticPlayer::play_external`]: the
+//! burst arms a disarmed engine once, plays, and hands the engine back once
+//! the plays stop.
+
+use std::future::Future;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex as StdMutex};
+use std::time::Duration;
+
+use openlogi_core::device::{
+ Capabilities, DeviceInventory, DeviceKind, PairedDevice, ReceiverInfo,
+};
+use openlogi_device::test_support::{ScriptedRawHidHandle, publish_scripted_channel};
+use openlogi_fixture::RequestMatch;
+use openlogi_hid::HapticWaveform;
+
+use super::super::{ARM_BUDGET, BURST_IDLE, RingHapticPlayer, check_haptic_target};
+use super::{DeviceRoute, ObservableState, Orchestrator, WriteError};
+
+/// The device layer caches the haptic feature location process-wide.
+static CACHE_SLOT: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+/// How long one scenario may take once it holds [`CACHE_SLOT`]: every wait
+/// in it is a few seconds of real time at most.
+const SCENARIO_DEADLINE: Duration = Duration::from_secs(30);
+
+/// How long a scenario may wait for the others to let go of [`CACHE_SLOT`].
+const SLOT_WAIT: Duration = Duration::from_secs(180);
+
+/// Run `scenario` alone against the feature cache, and fail it rather than
+/// hang the test job when a regression strands one of its waits.
+async fn bounded(scenario: impl Future) -> T {
+ let _slot = tokio::time::timeout(SLOT_WAIT, CACHE_SLOT.lock())
+ .await
+ .expect("no other scenario holds the haptic feature cache this long");
+ tokio::time::timeout(SCENARIO_DEADLINE, scenario)
+ .await
+ .expect("the scenario finishes in time instead of stranding a wait")
+}
+
+const HAPTIC_INDEX: u8 = 0x0b;
+const SUBTLE_COLLISION: u32 = 1 << 4;
+const BOTH_WAVEFORMS: u32 = (1 << 1) | SUBTLE_COLLISION;
+/// Disabled, with power save and the user's 60 % intensity; the third byte
+/// is the level count and step the firmware reports.
+const DISARMED: [u8; 3] = [0x82, 60, 0x34];
+
+fn mouse() -> DeviceRoute {
+ DeviceRoute::Direct {
+ vendor_id: 0x046d,
+ product_id: 0xb042,
+ }
+}
+
+fn other_mouse() -> DeviceRoute {
+ DeviceRoute::Direct {
+ vendor_id: 0x046d,
+ product_id: 0xb034,
+ }
+}
+
+fn third_mouse() -> DeviceRoute {
+ DeviceRoute::Direct {
+ vendor_id: 0x046d,
+ product_id: 0xb035,
+ }
+}
+
+const ARMED: [u8; 3] = [0x83, 60, 0x34];
+
+/// A `0x19b0` device advertising `waveforms`, keeping the configuration that
+/// `setConfiguration` writes, reporting a zero haptic status, and accepting
+/// every play. It has no `0x0003`, so arming records no unit ID.
+fn haptic_device(
+ config: Arc>,
+ waveforms: u32,
+) -> impl Fn(&[u8]) -> Option> + Send + Sync + 'static {
+ move |request| {
+ if request.len() < 7 || request[0] != 0x10 {
+ return None;
+ }
+ let function = request[3] >> 4;
+ if (request[2], function) == (HAPTIC_INDEX, 0x00) {
+ // getCapabilities: a long reply, the waveform mask in bytes 8..12.
+ let mut response = vec![0x11, request[1], request[2], request[3], 0, 0, 0, 0];
+ response.extend_from_slice(&waveforms.to_be_bytes());
+ response.resize(20, 0);
+ return Some(response);
+ }
+ let mut payload = [0u8; 3];
+ match (request[2], function) {
+ (0x00, 0x01) => payload[0] = 4,
+ (0x00, 0x00) => {
+ if u16::from_be_bytes([request[4], request[5]]) == 0x19b0 {
+ payload[0] = HAPTIC_INDEX;
+ }
+ }
+ (HAPTIC_INDEX, 0x01) => payload = *config.lock().expect("config"),
+ (HAPTIC_INDEX, 0x02) => {
+ let mut current = config.lock().expect("config");
+ current[..2].copy_from_slice(&request[4..6]);
+ payload = *current;
+ }
+ // getHapticInfo (status 0) and playWaveform.
+ (HAPTIC_INDEX, 0x03 | 0x04) => {}
+ _ => return None,
+ }
+ let mut response = request[..4].to_vec();
+ response.extend_from_slice(&payload);
+ Some(response)
+ }
+}
+
+fn reports(handle: &ScriptedRawHidHandle, function: u8) -> Vec> {
+ handle
+ .written_reports()
+ .into_iter()
+ .filter(|report| report[2] == HAPTIC_INDEX && report[3] >> 4 == function)
+ .collect()
+}
+
+/// The `setConfiguration` flag and intensity bytes, in order.
+fn config_writes(handle: &ScriptedRawHidHandle) -> Vec<[u8; 2]> {
+ reports(handle, 0x02)
+ .into_iter()
+ .map(|report| [report[4], report[5]])
+ .collect()
+}
+
+/// The waveform IDs played, in order.
+fn plays(handle: &ScriptedRawHidHandle) -> Vec {
+ reports(handle, 0x04)
+ .into_iter()
+ .map(|report| report[4])
+ .collect()
+}
+
+/// A worker over one scripted haptic mouse holding `config`.
+async fn player_for(
+ config: Arc>,
+ waveforms: u32,
+) -> (RingHapticPlayer, ScriptedRawHidHandle) {
+ let (player, mut handles) =
+ player_over(vec![(mouse(), Box::new(haptic_device(config, waveforms)))]).await;
+ (player, handles.remove(0))
+}
+
+/// How a scripted device answers a request.
+type Responder = Box Option> + Send + Sync>;
+
+/// [`haptic_device`] holding `config` with both waveforms, which stops
+/// answering plays and configuration writes once `lossy` is set.
+fn lossy_haptic_device(config: Arc>, lossy: Arc) -> Responder {
+ let device = haptic_device(config, BOTH_WAVEFORMS);
+ Box::new(move |request| {
+ let lost = lossy.load(Ordering::SeqCst)
+ && request.len() >= 4
+ && request[2] == HAPTIC_INDEX
+ && matches!(request[3] >> 4, 0x02 | 0x04);
+ if lost { None } else { device(request) }
+ })
+}
+
+/// [`haptic_device`] holding `config` with both waveforms, whose arming read
+/// is never answered: every arming on it takes its whole budget.
+fn slow_arming_haptic_device(config: Arc>) -> Responder {
+ let device = haptic_device(config, BOTH_WAVEFORMS);
+ Box::new(move |request| {
+ let arming_read =
+ request.len() >= 4 && request[2] == HAPTIC_INDEX && request[3] >> 4 == 0x01;
+ if arming_read { None } else { device(request) }
+ })
+}
+
+/// A worker over one scripted device per entry, each answering on its
+/// route.
+async fn player_over(
+ devices: Vec<(DeviceRoute, Responder)>,
+) -> (RingHapticPlayer, Vec) {
+ let observable = Arc::new(ObservableState::new("test".to_owned()));
+ let shared = Orchestrator::new(openlogi_core::config::Config::default(), observable).shared();
+ let mut handles = Vec::new();
+ for (index, (route, responder)) in devices.into_iter().enumerate() {
+ let (_, handle) = publish_scripted_channel(
+ &shared.channel_registry,
+ &format!("mouse-{index}"),
+ route,
+ responder,
+ )
+ .await;
+ handles.push(handle);
+ }
+ (RingHapticPlayer::spawn(shared), handles)
+}
+
+/// Wait until `done`, or a few seconds have passed.
+async fn until(mut done: impl FnMut() -> bool) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ while !done() && tokio::time::Instant::now() < deadline {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
+/// Wait until the engine reads `expected`, or a few seconds have passed.
+async fn until_engine_reads(config: &StdMutex<[u8; 3]>, expected: [u8; 3]) {
+ until(|| *config.lock().expect("config") == expected).await;
+}
+
+/// The `setConfiguration` (2) and `playWaveform` (4) functions written, in
+/// order.
+fn engine_writes(handle: &ScriptedRawHidHandle) -> Vec {
+ handle
+ .written_reports()
+ .into_iter()
+ .filter(|report| report[2] == HAPTIC_INDEX && matches!(report[3] >> 4, 0x02 | 0x04))
+ .map(|report| report[3] >> 4)
+ .collect()
+}
+
+/// Let the burst go idle, then wait until the engine reads `expected`.
+///
+/// Real time, not a paused clock: the scripted device answers on a thread,
+/// so a paused tokio clock jumps past the worker's play and restore budgets
+/// while it waits for those answers, and the tests flake under load.
+async fn after_the_burst(config: &StdMutex<[u8; 3]>, expected: [u8; 3]) {
+ tokio::time::sleep(BURST_IDLE + Duration::from_millis(300)).await;
+ until_engine_reads(config, expected).await;
+}
+
+#[tokio::test]
+async fn a_burst_on_a_disarmed_engine_arms_once_plays_and_hands_it_back() {
+ bounded(async {
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handle) = player_for(Arc::clone(&config), BOTH_WAVEFORMS).await;
+ let mut sessions = 10..;
+
+ for waveform in [
+ HapticWaveform::SubtleCollision,
+ HapticWaveform::SubtleCollision,
+ HapticWaveform::DampStateChange,
+ ] {
+ player
+ .play_external(mouse(), waveform, || sessions.next().expect("an ID"))
+ .await
+ .expect("the scripted mouse plays");
+ }
+ assert_eq!(plays(&handle), vec![4, 4, 1]);
+ assert_eq!(
+ config_writes(&handle),
+ vec![[0x83, 60]],
+ "the burst's first play turned the engine on, and only it"
+ );
+ assert_eq!(
+ reports(&handle, 0x01).len(),
+ 1,
+ "one arming read for the whole burst; later plays take one round-trip"
+ );
+ assert_eq!(sessions.next(), Some(11), "the burst opened one session");
+
+ after_the_burst(&config, DISARMED).await;
+ assert_eq!(
+ config_writes(&handle),
+ vec![[0x83, 60], [0x82, 60]],
+ "the enable the burst made was handed back once it went idle"
+ );
+ assert_eq!(*config.lock().expect("config"), DISARMED);
+
+ // The next play is a new burst: it arms again rather than playing into
+ // the engine it just handed back.
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 20)
+ .await
+ .expect("the scripted mouse plays");
+ assert_eq!(config_writes(&handle).len(), 3);
+ after_the_burst(&config, DISARMED).await;
+ assert_eq!(*config.lock().expect("config"), DISARMED);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn an_armed_engine_is_played_on_and_left_alone() {
+ bounded(async {
+ let armed = [0x83, 60, 0x34];
+ let config = Arc::new(StdMutex::new(armed));
+ let (player, handle) = player_for(Arc::clone(&config), BOTH_WAVEFORMS).await;
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 1)
+ .await
+ .expect("the scripted mouse plays");
+ after_the_burst(&config, armed).await;
+ assert_eq!(plays(&handle), vec![4]);
+ assert!(
+ config_writes(&handle).is_empty(),
+ "nothing to arm or hand back"
+ );
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn an_unadvertised_waveform_is_refused_and_leaves_no_engine_on() {
+ bounded(async {
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handle) = player_for(Arc::clone(&config), SUBTLE_COLLISION).await;
+ assert!(matches!(
+ player
+ .play_external(mouse(), HapticWaveform::DampStateChange, || 1)
+ .await,
+ Err(WriteError::HapticWaveformUnsupported { waveform: 1 })
+ ));
+ assert!(plays(&handle).is_empty(), "the refusal sent no play");
+ after_the_burst(&config, DISARMED).await;
+ assert_eq!(
+ *config.lock().expect("config"),
+ DISARMED,
+ "the arming the refused play opened with was handed back too"
+ );
+ })
+ .await;
+}
+
+/// A ring opened on the mouse a client burst plays on shares its engine: the
+/// burst going idle leaves the engine on for the ring, and the ring's close
+/// hands it back.
+#[tokio::test]
+async fn a_burst_going_idle_leaves_the_engine_on_for_an_open_ring() {
+ bounded(async {
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handle) = player_for(Arc::clone(&config), BOTH_WAVEFORMS).await;
+ player.begin_session(5, Some(mouse()));
+ until_engine_reads(&config, ARMED).await;
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 6)
+ .await
+ .expect("the scripted mouse plays");
+
+ tokio::time::sleep(BURST_IDLE + Duration::from_millis(500)).await;
+ assert_eq!(
+ *config.lock().expect("config"),
+ ARMED,
+ "the burst is over, but the ring still plays on the engine"
+ );
+ player.end_session(5);
+ until_engine_reads(&config, DISARMED).await;
+ assert_eq!(
+ config_writes(&handle),
+ vec![[0x83, 60], [0x82, 60]],
+ "armed once, handed back once both sessions closed"
+ );
+ })
+ .await;
+}
+
+/// The other order: a ring armed and closed inside a burst leaves the engine
+/// on for the burst, which hands it back once it goes idle.
+#[tokio::test]
+async fn a_ring_closing_inside_a_burst_leaves_the_engine_on_for_it() {
+ bounded(async {
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handle) = player_for(Arc::clone(&config), BOTH_WAVEFORMS).await;
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 5)
+ .await
+ .expect("the scripted mouse plays");
+ let reads = reports(&handle, 0x01).len();
+ player.begin_session(6, Some(mouse()));
+ // The ring's arming reads the engine, finds it on, and owes nothing
+ // of its own; only then does the ring close.
+ until(|| reports(&handle, 0x01).len() > reads).await;
+ assert_eq!(reports(&handle, 0x01).len(), reads + 1, "the ring armed");
+ player.end_session(6);
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert_eq!(
+ *config.lock().expect("config"),
+ ARMED,
+ "the ring is over, but the burst still plays on the engine"
+ );
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 7)
+ .await
+ .expect("the scripted mouse plays");
+ assert_eq!(
+ config_writes(&handle),
+ vec![[0x83, 60]],
+ "the burst's later play found its engine still on"
+ );
+ after_the_burst(&config, DISARMED).await;
+ assert_eq!(config_writes(&handle), vec![[0x83, 60], [0x82, 60]]);
+ })
+ .await;
+}
+
+/// A play for a device whose session opened while the worker was arming
+/// another device's waits for its own arming, rather than playing into an
+/// engine that is still off.
+#[tokio::test]
+async fn a_play_queued_behind_another_devices_arming_is_armed_first() {
+ bounded(async {
+ let stalled = Arc::new(StdMutex::new(DISARMED));
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handles) = player_over(vec![
+ (
+ other_mouse(),
+ Box::new(haptic_device(Arc::clone(&stalled), BOTH_WAVEFORMS)),
+ ),
+ (
+ mouse(),
+ Box::new(haptic_device(Arc::clone(&config), BOTH_WAVEFORMS)),
+ ),
+ ])
+ .await;
+ // The other mouse's ring arms first; its configuration read stalls.
+ let read = handles[0].hold_next_response(
+ RequestMatch::Hidpp20,
+ &[0x10, 0xff, HAPTIC_INDEX, 0x10, 0, 0, 0],
+ );
+ player.begin_session(1, Some(other_mouse()));
+ read.request_written().await;
+
+ let (published, opened) = tokio::sync::oneshot::channel();
+ let client = {
+ let player = player.clone();
+ tokio::spawn(async move {
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, move || {
+ let _ = published.send(());
+ 2
+ })
+ .await
+ })
+ };
+ opened.await.expect("the client play opened its session");
+ read.release();
+
+ client
+ .await
+ .expect("the client task")
+ .expect("the scripted mouse plays");
+ let written = engine_writes(&handles[1]);
+ assert_eq!(
+ written.first(),
+ Some(&0x02),
+ "the mouse's engine was turned on before its play: {written:?}"
+ );
+ player.end_session(1);
+ after_the_burst(&config, DISARMED).await;
+ })
+ .await;
+}
+
+/// A client play stuck behind a worker held up by a lost ring buzz and an
+/// unreachable restore keeps its burst open until it has played, so the
+/// burst cannot close before its arming and play into an engine still off.
+#[tokio::test]
+async fn a_burst_stays_open_while_its_play_waits_behind_a_stalled_worker() {
+ bounded(async {
+ let lossy = Arc::new(AtomicBool::new(false));
+ let stalled = Arc::new(StdMutex::new(DISARMED));
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handles) = player_over(vec![
+ (
+ other_mouse(),
+ lossy_haptic_device(Arc::clone(&stalled), Arc::clone(&lossy)),
+ ),
+ (
+ mouse(),
+ Box::new(haptic_device(Arc::clone(&config), BOTH_WAVEFORMS)),
+ ),
+ ])
+ .await;
+ player.begin_session(1, Some(other_mouse()));
+ until_engine_reads(&stalled, ARMED).await;
+ // The ring's last buzz is lost, holding the worker for its whole
+ // play budget, and so is the restore its close owes after it.
+ lossy.store(true, Ordering::SeqCst);
+ player.play(
+ 1,
+ Some(other_mouse()),
+ HapticWaveform::SubtleCollision,
+ "hover",
+ );
+ player.end_session(1);
+ until(|| !plays(&handles[0]).is_empty()).await;
+
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 2)
+ .await
+ .expect("the scripted mouse plays");
+ let written = engine_writes(&handles[1]);
+ assert_eq!(
+ written.first(),
+ Some(&0x02),
+ "the mouse's engine was turned on before its play: {written:?}"
+ );
+ after_the_burst(&config, DISARMED).await;
+ })
+ .await;
+}
+
+/// Two clients alternating between two mice faster than either can be
+/// armed open a new burst with every play. Each worker pass still plays a
+/// pulse and reaches the restores, rather than arming the newest burst over
+/// and over while nothing plays and nothing is handed back.
+#[tokio::test]
+async fn alternating_plays_during_slow_arming_still_play_and_restore() {
+ bounded(async {
+ let ringed = Arc::new(StdMutex::new(DISARMED));
+ let (player, handles) = player_over(vec![
+ (
+ third_mouse(),
+ Box::new(haptic_device(Arc::clone(&ringed), BOTH_WAVEFORMS)),
+ ),
+ (
+ mouse(),
+ slow_arming_haptic_device(Arc::new(StdMutex::new(DISARMED))),
+ ),
+ (
+ other_mouse(),
+ slow_arming_haptic_device(Arc::new(StdMutex::new(DISARMED))),
+ ),
+ ])
+ .await;
+ // A ring on a third mouse owes its engine back once it closes.
+ player.begin_session(1, Some(third_mouse()));
+ until_engine_reads(&ringed, ARMED).await;
+
+ let stop = Arc::new(AtomicBool::new(false));
+ let clients = {
+ let player = player.clone();
+ let stop = Arc::clone(&stop);
+ tokio::spawn(async move {
+ let ids = Arc::new(AtomicU64::new(10));
+ for route in [mouse(), other_mouse()].into_iter().cycle() {
+ if stop.load(Ordering::SeqCst) {
+ break;
+ }
+ let player = player.clone();
+ let ids = Arc::clone(&ids);
+ tokio::spawn(async move {
+ let _ = player
+ .play_external(route, HapticWaveform::SubtleCollision, || {
+ ids.fetch_add(1, Ordering::SeqCst)
+ })
+ .await;
+ });
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ }
+ })
+ };
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ player.end_session(1);
+ tokio::time::sleep(ARM_BUDGET * 4).await;
+
+ // Read while the plays still keep coming.
+ let pulses = plays(&handles[1]).len() + plays(&handles[2]).len();
+ let ring_engine = *ringed.lock().expect("config");
+ stop.store(true, Ordering::SeqCst);
+ clients.await.expect("the clients");
+ assert!(
+ pulses >= 2,
+ "pulses kept playing between armings, but {pulses} played"
+ );
+ assert_eq!(
+ ring_engine, DISARMED,
+ "the closed ring's engine was handed back meanwhile"
+ );
+ })
+ .await;
+}
+
+/// A hand-back ends the burst with every other session, so the next play
+/// after the agent stays opens a new burst that arms again rather than
+/// playing into the engine just handed back.
+#[tokio::test]
+async fn a_play_after_a_hand_back_arms_the_engine_again() {
+ bounded(async {
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handle) = player_for(Arc::clone(&config), BOTH_WAVEFORMS).await;
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 1)
+ .await
+ .expect("the scripted mouse plays");
+ player.finish().await;
+ assert_eq!(*config.lock().expect("config"), DISARMED, "handed back");
+
+ player.resume();
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 2)
+ .await
+ .expect("the scripted mouse plays");
+ assert_eq!(
+ config_writes(&handle),
+ vec![[0x83, 60], [0x82, 60], [0x83, 60]],
+ "the play after the agent stayed armed the engine again"
+ );
+ after_the_burst(&config, DISARMED).await;
+ assert_eq!(config_writes(&handle).len(), 4);
+ })
+ .await;
+}
+
+/// While the agent is leaving or handing over, nothing arms the engine, so
+/// a client play is refused instead of reporting a buzz that may not have
+/// been felt.
+#[tokio::test]
+async fn a_client_play_while_the_agent_is_leaving_is_refused() {
+ bounded(async {
+ let config = Arc::new(StdMutex::new(DISARMED));
+ let (player, handle) = player_for(Arc::clone(&config), BOTH_WAVEFORMS).await;
+ player.finish().await;
+ assert!(matches!(
+ player
+ .play_external(mouse(), HapticWaveform::SubtleCollision, || 1)
+ .await,
+ Err(WriteError::AgentUnavailable)
+ ));
+ assert!(plays(&handle).is_empty(), "the refused play sent nothing");
+ assert!(config_writes(&handle).is_empty(), "nor armed anything");
+ })
+ .await;
+}
+
+#[test]
+fn only_an_online_device_with_measured_haptics_is_played_on() {
+ let device = |online, capabilities: Option| DeviceInventory {
+ receiver: ReceiverInfo {
+ name: "MX Master 4".into(),
+ vendor_id: 0x046d,
+ product_id: 0xb042,
+ unique_id: None,
+ },
+ paired: vec![PairedDevice {
+ slot: 0xff,
+ codename: Some("MX Master 4".into()),
+ wpid: None,
+ kind: DeviceKind::Mouse,
+ online,
+ battery: None,
+ model_info: None,
+ capabilities,
+ settings_revision: 0,
+ hidpp10: false,
+ }],
+ };
+ let haptics = Some(Capabilities::from_feature_ids(&[0x19b0]));
+ assert_eq!(
+ DeviceRoute::for_slot(&device(true, None), 0xff),
+ Some(mouse()),
+ "the fixture addresses the route under test"
+ );
+ assert!(matches!(
+ check_haptic_target(&[device(true, haptics)], &mouse()),
+ Ok(())
+ ));
+ assert!(matches!(
+ check_haptic_target(&[], &mouse()),
+ Err(WriteError::DeviceNotFound)
+ ));
+ assert!(matches!(
+ check_haptic_target(&[device(false, haptics)], &mouse()),
+ Err(WriteError::DeviceUnreachable { .. })
+ ));
+ for capabilities in [None, Some(Capabilities::default())] {
+ assert!(matches!(
+ check_haptic_target(&[device(true, capabilities)], &mouse()),
+ Err(WriteError::FeatureUnsupported {
+ feature_hex: 0x19b0
+ })
+ ));
+ }
+}
diff --git a/crates/openlogi-cli/src/agent.rs b/crates/openlogi-cli/src/agent.rs
index 78c001fcc9..11319e3fd2 100644
--- a/crates/openlogi-cli/src/agent.rs
+++ b/crates/openlogi-cli/src/agent.rs
@@ -8,9 +8,11 @@
use std::future::Future;
use std::time::Duration;
-use anyhow::{Result, anyhow};
+use anyhow::{Context as _, Result, anyhow, bail};
+use openlogi_core::device::Capabilities;
+use openlogi_core::hid::DeviceRoute;
use openlogi_ipc::client::{self, ConnectError};
-use openlogi_ipc::{AgentClient, AgentSnapshot, ClientKind};
+use openlogi_ipc::{AgentClient, AgentSnapshot, ClientKind, InventoryHealth};
use tarpc::client::RpcError;
use tarpc::context;
@@ -61,3 +63,107 @@ pub(crate) async fn snapshot(client: &AgentClient) -> Result {
}
})
}
+
+/// The device feature a human-facing command selects a device for.
+pub(crate) struct Feature {
+ /// The feature as messages name it, such as `backlight`.
+ pub(crate) noun: &'static str,
+ /// Whether a device's measured capabilities offer the feature. Only such a
+ /// device is selected without `--device`.
+ pub(crate) measured: fn(&Capabilities) -> bool,
+ /// What a device measured without it lacks, such as `HID++ Backlight2
+ /// support`.
+ pub(crate) missing: &'static str,
+}
+
+/// Select the one online HID++ device a human-facing command acts on: the
+/// one whose name contains `query` (case-insensitively), or without a query
+/// the one online device measured to offer `feature`. Returns its route and
+/// display name.
+///
+/// Refuses an incomplete inventory, no match, several matches, a match with
+/// no route or a route another device shares, and a device measured without
+/// the feature. Human-readable selection differs from the JSON API's exact
+/// opaque IDs. Only the agent's HID++ inventory is eligible, never standalone
+/// raw-HID lights.
+pub(crate) fn select_device(
+ snapshot: &AgentSnapshot,
+ query: Option<&str>,
+ feature: &Feature,
+) -> Result<(DeviceRoute, String)> {
+ let noun = feature.noun;
+ if snapshot.status.inventory != InventoryHealth::Ready {
+ bail!("agent inventory is not ready; wait for OpenLogi to finish scanning and try again");
+ }
+ let devices: Vec<_> = snapshot
+ .inventory
+ .iter()
+ .flat_map(|inventory| {
+ inventory
+ .paired
+ .iter()
+ .filter(|device| device.online)
+ .map(|device| {
+ (
+ DeviceRoute::for_slot(inventory, device.slot),
+ device
+ .codename
+ .clone()
+ .unwrap_or_else(|| format!("Slot {}", device.slot)),
+ device.capabilities.as_ref(),
+ )
+ })
+ })
+ .collect();
+ let needle = query.map(str::to_lowercase);
+ let matches: Vec<_> = devices
+ .iter()
+ .filter(|(_, name, caps)| {
+ needle.as_ref().map_or_else(
+ || caps.is_some_and(feature.measured),
+ |needle| name.to_lowercase().contains(needle),
+ )
+ })
+ .collect();
+ let selected = if let [selected] = matches.as_slice() {
+ *selected
+ } else {
+ let reason = if matches.is_empty() {
+ format!("no matching online {noun} device")
+ } else {
+ format!("ambiguous {noun} device selection")
+ };
+ let list = devices
+ .iter()
+ .map(|(route, name, _)| {
+ format!(
+ " - {name} ({})",
+ route
+ .as_ref()
+ .map_or_else(|| "route unavailable".into(), ToString::to_string)
+ )
+ })
+ .collect::>()
+ .join("\n");
+ bail!(
+ "{reason}; use --device . Automatic selection requires measured {noun} support.\nOnline HID++ devices:\n{list}"
+ );
+ };
+ let (route, name, caps) = selected;
+ let route = route
+ .as_ref()
+ .context("selected device has no resolvable agent route")?;
+ // Distinct names cannot disambiguate identical direct VID/PID routes.
+ if devices
+ .iter()
+ .filter(|(candidate, _, _)| candidate.as_ref() == Some(route))
+ .count()
+ != 1
+ {
+ bail!("ambiguous agent route for {name} ({route}); no operation was attempted");
+ }
+ if caps.is_some_and(|caps| !(feature.measured)(caps)) {
+ bail!("{name} does not advertise {}", feature.missing);
+ }
+ Ok((route.clone(), name.clone()))
+}
diff --git a/crates/openlogi-cli/src/cmd.rs b/crates/openlogi-cli/src/cmd.rs
index 4d3b59f624..0db9a9f612 100644
--- a/crates/openlogi-cli/src/cmd.rs
+++ b/crates/openlogi-cli/src/cmd.rs
@@ -9,6 +9,7 @@ pub mod backlight;
pub mod camera;
pub mod diag;
pub mod fixture;
+pub mod haptic;
#[cfg(target_os = "macos")]
mod input_monitoring;
pub mod light;
@@ -23,6 +24,8 @@ pub enum Command {
List(list::ListArgs),
/// Read or persistently set the keyboard backlight (HID++ 0x1982).
Backlight(backlight::BacklightArgs),
+ /// Play haptic feedback on a mouse (HID++ 0x19b0), for scripts and apps.
+ Haptic(haptic::HapticArgs),
/// Capture one frame from a Logitech webcam to a PNG.
Snapshot(snapshot::SnapshotArgs),
/// Read or write device-level UVC image controls on a webcam.
@@ -51,6 +54,7 @@ impl Command {
Self::Api(command) => return api::run(command).await,
Self::List(args) => return list::run(args).await,
Self::Backlight(args) => backlight::run(args).await?,
+ Self::Haptic(args) => haptic::run(args).await?,
// Camera capture is blocking AVFoundation — no need for the async runtime.
Self::Snapshot(args) => snapshot::run(args)?,
// UVC control transfers are blocking IOKit — no async runtime needed.
diff --git a/crates/openlogi-cli/src/cmd/api.rs b/crates/openlogi-cli/src/cmd/api.rs
index 91e489e177..835e8e07af 100644
--- a/crates/openlogi-cli/src/cmd/api.rs
+++ b/crates/openlogi-cli/src/cmd/api.rs
@@ -15,6 +15,7 @@ use serde_json::{Value, json};
use tarpc::context;
use crate::agent;
+use crate::cmd::haptic::Waveform;
mod output;
mod persistence;
@@ -91,6 +92,15 @@ pub enum ApiCommand {
#[arg(long, requires = "channel")]
name: Option,
},
+ /// Play one haptic pulse now (HID++ 0x19b0). Nothing is saved.
+ Haptic {
+ /// Exact opaque ID returned by `api devices`.
+ #[arg(long)]
+ device: String,
+ /// A light `tick`, or a firmer `confirm` pulse.
+ #[arg(long, value_enum, default_value_t = Waveform::Tick)]
+ waveform: Waveform,
+ },
}
/// A partial SmartShift update; omitted fields are read from the device.
@@ -263,6 +273,11 @@ async fn execute(
)
.await
}
+ ApiCommand::Haptic { device, waveform } => {
+ let route = select_device(&snapshot, &device)?;
+ agent::call(client.play_haptic(context::current(), route, waveform.pulse())).await??;
+ Ok(json!({ "device": device, "waveform": waveform.name() }))
+ }
}?;
if let Some(save) = save {
save.commit(client).await?;
diff --git a/crates/openlogi-cli/src/cmd/api/tests.rs b/crates/openlogi-cli/src/cmd/api/tests.rs
index e3642423a5..29ca0c8d75 100644
--- a/crates/openlogi-cli/src/cmd/api/tests.rs
+++ b/crates/openlogi-cli/src/cmd/api/tests.rs
@@ -17,6 +17,7 @@ use openlogi_ipc::{
use super::*;
mod easy_switch;
+mod haptic;
mod persistence;
mod report_rate;
diff --git a/crates/openlogi-cli/src/cmd/api/tests/haptic.rs b/crates/openlogi-cli/src/cmd/api/tests/haptic.rs
new file mode 100644
index 0000000000..c75edcf3a5
--- /dev/null
+++ b/crates/openlogi-cli/src/cmd/api/tests/haptic.rs
@@ -0,0 +1,83 @@
+use openlogi_core::hid::HapticPulse;
+
+use super::*;
+
+fn command(waveform: Waveform) -> ApiCommand {
+ ApiCommand::Haptic {
+ device: route().to_string(),
+ waveform,
+ }
+}
+
+/// The agent receives `pulse` for the test mouse and answers `result`.
+fn play(pulse: HapticPulse, result: Result<(), WriteError>) -> Step {
+ Box::new(move |request| {
+ let AgentRequest::PlayHaptic {
+ route: requested,
+ pulse: asked,
+ } = request
+ else {
+ panic!("expected a haptic play, got {request:?}");
+ };
+ assert_eq!((requested, asked), (route(), pulse));
+ AgentResponse::PlayHaptic(result)
+ })
+}
+
+#[tokio::test]
+async fn a_play_answers_the_device_and_waveform() {
+ for (waveform, pulse, name) in [
+ (Waveform::Tick, HapticPulse::SubtleCollision, "tick"),
+ (Waveform::Confirm, HapticPulse::DampStateChange, "confirm"),
+ ] {
+ let result = run_script(snapshot(), command(waveform), vec![play(pulse, Ok(()))]).await;
+ assert_eq!(
+ result,
+ json!({
+ "schema_version": 1,
+ "ok": true,
+ "data": { "device": route().to_string(), "waveform": name },
+ })
+ );
+ }
+}
+
+#[tokio::test]
+async fn the_agents_refusals_keep_their_stable_codes() {
+ for (error, code) in [
+ (
+ WriteError::HapticWaveformUnsupported { waveform: 1 },
+ "unsupported_feature",
+ ),
+ (
+ WriteError::FeatureUnsupported {
+ feature_hex: 0x19b0,
+ },
+ "unsupported_feature",
+ ),
+ (WriteError::DeviceUnreachable { index: 3 }, "device_offline"),
+ (WriteError::HapticsUnavailable { status: 2 }, "device_error"),
+ ] {
+ let result = run_script(
+ snapshot(),
+ command(Waveform::Confirm),
+ vec![play(HapticPulse::DampStateChange, Err(error))],
+ )
+ .await;
+ assert_eq!(result["ok"], json!(false));
+ assert_eq!(result["error"]["code"], json!(code));
+ }
+}
+
+#[tokio::test]
+async fn an_offline_device_and_save_are_refused_before_any_play() {
+ let mut offline = snapshot();
+ offline.inventory[0].paired[0].online = false;
+ let result = run_script(offline, command(Waveform::Tick), vec![]).await;
+ assert_eq!(result["error"]["code"], json!("device_offline"));
+
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join(openlogi_core::paths::CONFIG_FILE);
+ let result = run_script_at(snapshot(), command(Waveform::Tick), vec![], Some(&path)).await;
+ assert_eq!(result["error"]["code"], json!("invalid_value"));
+}
diff --git a/crates/openlogi-cli/src/cmd/backlight.rs b/crates/openlogi-cli/src/cmd/backlight.rs
index 8249658b29..162eebd0cd 100644
--- a/crates/openlogi-cli/src/cmd/backlight.rs
+++ b/crates/openlogi-cli/src/cmd/backlight.rs
@@ -6,16 +6,15 @@
use std::io::{self, Write};
-use anyhow::{Context, Result, anyhow, bail};
+use anyhow::{Context, Result, anyhow};
use clap::{Args, Subcommand};
-use openlogi_core::device::Capabilities;
use openlogi_core::hid::backlight::max_backlight_level;
use openlogi_core::hid::{
BacklightChange, BacklightControls, BacklightDuration, BacklightMode, BacklightState,
- BacklightStatus, DeviceRoute,
+ BacklightStatus,
};
+use openlogi_ipc::AgentClient;
use openlogi_ipc::client::ConnectError;
-use openlogi_ipc::{AgentClient, AgentSnapshot, InventoryHealth};
use tarpc::context;
use crate::agent::{self, CallFailure};
@@ -108,6 +107,13 @@ impl BacklightAction {
}
}
+/// What automatic selection looks for, and what a refusal names.
+const BACKLIGHT: agent::Feature = agent::Feature {
+ noun: "backlight",
+ measured: |caps| caps.backlight,
+ missing: "HID++ Backlight2 support",
+};
+
pub async fn run(args: BacklightArgs) -> Result<()> {
let connection = agent::connect().await;
execute(args, connection, &mut io::stdout()).await
@@ -125,7 +131,7 @@ async fn execute(
"backlight requires a running, compatible OpenLogi agent; start the matching OpenLogi build with the same OPENLOGI_PROFILE (no direct hardware fallback)",
)?;
let snapshot = agent::snapshot(&client).await?;
- let (route, name) = select_device(&snapshot, args.device.as_deref())?;
+ let (route, name) = agent::select_device(&snapshot, args.device.as_deref(), &BACKLIGHT)?;
writeln!(out, "device: {name} ({route})")?;
let before = agent::call(client.read_backlight(context::current(), route.clone()))
@@ -168,85 +174,6 @@ fn call_error(failure: CallFailure) -> anyhow::Error {
}
}
-/// Human-readable selection differs from the JSON API's exact opaque IDs.
-/// Only the agent's HID++ inventory is eligible, never standalone raw-HID lights.
-fn select_device(snapshot: &AgentSnapshot, query: Option<&str>) -> Result<(DeviceRoute, String)> {
- if snapshot.status.inventory != InventoryHealth::Ready {
- bail!("agent inventory is not ready; wait for OpenLogi to finish scanning and try again");
- }
- let devices: Vec<_> = snapshot
- .inventory
- .iter()
- .flat_map(|inventory| {
- inventory
- .paired
- .iter()
- .filter(|device| device.online)
- .map(|device| {
- (
- DeviceRoute::for_slot(inventory, device.slot),
- device
- .codename
- .clone()
- .unwrap_or_else(|| format!("Slot {}", device.slot)),
- device.capabilities.as_ref(),
- )
- })
- })
- .collect();
- let needle = query.map(str::to_lowercase);
- let matches: Vec<_> = devices
- .iter()
- .filter(|(_, name, caps)| {
- needle.as_ref().map_or_else(
- || caps.is_some_and(|caps: &Capabilities| caps.backlight),
- |needle| name.to_lowercase().contains(needle),
- )
- })
- .collect();
- let selected = if let [selected] = matches.as_slice() {
- *selected
- } else {
- let reason = if matches.is_empty() {
- "no matching online backlight device"
- } else {
- "ambiguous backlight device selection"
- };
- let list = devices
- .iter()
- .map(|(route, name, _)| {
- format!(
- " - {name} ({})",
- route
- .as_ref()
- .map_or_else(|| "route unavailable".into(), ToString::to_string)
- )
- })
- .collect::>()
- .join("\n");
- bail!(
- "{reason}; use --device . Automatic selection requires measured backlight support.\nOnline HID++ devices:\n{list}"
- );
- };
- let (route, name, caps) = selected;
- let route = route
- .as_ref()
- .context("selected device has no resolvable agent route")?;
- // Distinct names cannot disambiguate identical direct VID/PID routes.
- if devices
- .iter()
- .filter(|(candidate, _, _)| candidate.as_ref() == Some(route))
- .count()
- != 1
- {
- bail!("ambiguous agent route for {name} ({route}); no operation was attempted");
- }
- if caps.is_some_and(|caps| !caps.backlight) {
- bail!("{name} does not advertise HID++ Backlight2 support");
- }
- Ok((route.clone(), name.clone()))
-}
-
/// Whether `change` writes the stored mode back as it was read.
fn keeps_the_mode(change: BacklightChange) -> bool {
matches!(
diff --git a/crates/openlogi-cli/src/cmd/backlight/tests/agent_routing.rs b/crates/openlogi-cli/src/cmd/backlight/tests/agent_routing.rs
index 596f9433e1..351dc560d5 100644
--- a/crates/openlogi-cli/src/cmd/backlight/tests/agent_routing.rs
+++ b/crates/openlogi-cli/src/cmd/backlight/tests/agent_routing.rs
@@ -2,11 +2,15 @@ use std::collections::VecDeque;
use std::future::pending;
use std::sync::{Arc, Mutex};
-use openlogi_core::device::{DeviceInventory, DeviceKind, PairedDevice, ReceiverInfo};
-use openlogi_core::hid::WriteError;
+use openlogi_core::device::{
+ Capabilities, DeviceInventory, DeviceKind, PairedDevice, ReceiverInfo,
+};
+use openlogi_core::hid::{DeviceRoute, WriteError};
use openlogi_ipc::client::ProtocolSkew;
use openlogi_ipc::testing::{Answer, in_memory_agent};
-use openlogi_ipc::{AgentRequest, AgentResponse, AgentStatus, ForegroundApps};
+use openlogi_ipc::{
+ AgentRequest, AgentResponse, AgentSnapshot, AgentStatus, ForegroundApps, InventoryHealth,
+};
use super::*;
diff --git a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs
index 9fc4d8045c..872ef00426 100644
--- a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs
+++ b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs
@@ -459,6 +459,15 @@ impl Agent for TestAgent {
unreachable!("profile capture must not drive the Actions Ring")
}
+ async fn play_haptic(
+ self,
+ _: TarpcContext,
+ _route: DeviceRoute,
+ _pulse: openlogi_core::hid::HapticPulse,
+ ) -> Result<(), WriteError> {
+ unreachable!("profile capture must never play haptics")
+ }
+
async fn reload_saved_config(
self,
_: TarpcContext,
diff --git a/crates/openlogi-cli/src/cmd/haptic.rs b/crates/openlogi-cli/src/cmd/haptic.rs
new file mode 100644
index 0000000000..48da1f93e2
--- /dev/null
+++ b/crates/openlogi-cli/src/cmd/haptic.rs
@@ -0,0 +1,105 @@
+//! `openlogi haptic` — play HID++ `0x19b0` haptic feedback on a mouse through
+//! the running agent, for scripts and other apps.
+
+use std::io::{self, Write};
+
+use anyhow::{Context, Result, anyhow};
+use clap::{Args, Subcommand, ValueEnum};
+use openlogi_core::hid::{HapticPulse, WriteError};
+use openlogi_ipc::AgentClient;
+use openlogi_ipc::client::ConnectError;
+use tarpc::context;
+
+use crate::agent::{self, CallFailure};
+
+#[derive(Debug, Args)]
+#[command(
+ after_help = "Requires a running, compatible OpenLogi agent in the same OPENLOGI_PROFILE. No direct hardware fallback. Without --device, selects only one online device with measured haptic feedback (HID++ 0x19b0). Ambiguous matches are refused."
+)]
+pub struct HapticArgs {
+ /// Select exactly one online device by a case-insensitive name substring.
+ #[arg(long, value_name = "NAME", global = true)]
+ pub device: Option,
+
+ #[command(subcommand)]
+ pub action: HapticAction,
+}
+
+#[derive(Debug, Subcommand)]
+pub enum HapticAction {
+ /// Play one haptic pulse now.
+ Play {
+ #[arg(value_enum, default_value_t = Waveform::Tick)]
+ waveform: Waveform,
+ },
+}
+
+/// The waveforms a script can ask for, by what they feel like.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+pub enum Waveform {
+ /// A light tick, as when the Actions Ring highlights another slot.
+ Tick,
+ /// A firmer confirmation pulse, as when an Actions Ring action runs.
+ Confirm,
+}
+
+impl Waveform {
+ pub(crate) fn pulse(self) -> HapticPulse {
+ match self {
+ Self::Tick => HapticPulse::SubtleCollision,
+ Self::Confirm => HapticPulse::DampStateChange,
+ }
+ }
+
+ pub(crate) fn name(self) -> &'static str {
+ match self {
+ Self::Tick => "tick",
+ Self::Confirm => "confirm",
+ }
+ }
+}
+
+/// What automatic selection looks for, and what a refusal names.
+const HAPTICS: agent::Feature = agent::Feature {
+ noun: "haptic",
+ measured: |caps| caps.haptic_feedback,
+ missing: "HID++ haptic feedback (0x19b0)",
+};
+
+pub async fn run(args: HapticArgs) -> Result<()> {
+ let connection = agent::connect().await;
+ execute(args, connection, &mut io::stdout()).await
+}
+
+/// The connection result and output sink are parameters so tests reach the
+/// whole path without a socket, an agent, or hardware.
+async fn execute(
+ args: HapticArgs,
+ connection: Result,
+ out: &mut impl Write,
+) -> Result<()> {
+ let HapticAction::Play { waveform } = args.action;
+ let client = connection.context(
+ "haptic requires a running, compatible OpenLogi agent; start the matching OpenLogi build with the same OPENLOGI_PROFILE (no direct hardware fallback)",
+ )?;
+ let snapshot = agent::snapshot(&client).await?;
+ let (route, name) = agent::select_device(&snapshot, args.device.as_deref(), &HAPTICS)?;
+ agent::call(client.play_haptic(context::current(), route.clone(), waveform.pulse()))
+ .await
+ .map_err(|failure| match failure {
+ CallFailure::TimedOut => anyhow!("agent haptic call timed out"),
+ CallFailure::Disconnected => anyhow!("agent disconnected during haptic call"),
+ })?
+ .map_err(|error| match error {
+ WriteError::WriteSuperseded { .. } => {
+ anyhow!("a newer haptic replaced this one before it played")
+ }
+ error => anyhow!(error),
+ })
+ .with_context(|| format!("play {} on {name}", waveform.name()))?;
+ writeln!(out, "played {} on {name} ({route})", waveform.name())?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/openlogi-cli/src/cmd/haptic/tests.rs b/crates/openlogi-cli/src/cmd/haptic/tests.rs
new file mode 100644
index 0000000000..e0b71d63e2
--- /dev/null
+++ b/crates/openlogi-cli/src/cmd/haptic/tests.rs
@@ -0,0 +1,248 @@
+use std::collections::VecDeque;
+use std::future::pending;
+use std::sync::{Arc, Mutex};
+
+use openlogi_core::device::{
+ Capabilities, DeviceInventory, DeviceKind, PairedDevice, ReceiverInfo,
+};
+use openlogi_core::hid::DeviceRoute;
+use openlogi_ipc::client::ProtocolSkew;
+use openlogi_ipc::testing::{Answer, in_memory_agent};
+use openlogi_ipc::{
+ AgentRequest, AgentResponse, AgentSnapshot, AgentStatus, ForegroundApps, InventoryHealth,
+};
+
+use super::*;
+
+type Step = Box Answer + Send>;
+
+fn paired(slot: u8, name: &str, kind: DeviceKind, features: &[u16]) -> PairedDevice {
+ PairedDevice {
+ slot,
+ codename: Some(name.into()),
+ wpid: None,
+ kind,
+ online: true,
+ battery: None,
+ model_info: None,
+ capabilities: Some(Capabilities::from_feature_ids(features)),
+ settings_revision: 0,
+ hidpp10: false,
+ }
+}
+
+/// A receiver with a haptic mouse on slot 2 and a keyboard without haptics
+/// on slot 3.
+fn snapshot() -> AgentSnapshot {
+ AgentSnapshot {
+ status: AgentStatus {
+ accessibility_granted: false,
+ hook_installed: false,
+ launch_at_login: false,
+ inventory: InventoryHealth::Ready,
+ protocol_version: 0,
+ agent_version: "test-agent".into(),
+ input_monitoring_granted: true,
+ hid_open_failures: false,
+ secure_input: openlogi_ipc::SecureInput::Off,
+ virtual_keyboard: openlogi_ipc::VirtualKeyboardStatus::Unsupported,
+ },
+ inventory: vec![DeviceInventory {
+ receiver: ReceiverInfo {
+ name: "Test Bolt receiver".into(),
+ vendor_id: 0x046d,
+ product_id: 0xc548,
+ unique_id: Some("test-receiver".into()),
+ },
+ paired: vec![
+ paired(2, "MX Master 4", DeviceKind::Mouse, &[0x19b0]),
+ paired(3, "MX Keys S", DeviceKind::Keyboard, &[0x1982]),
+ ],
+ }],
+ standalone: Vec::new(),
+ camera_active: false,
+ pairing: None,
+ foreground: ForegroundApps {
+ current: None,
+ recent: Vec::new(),
+ },
+ lights: Vec::new(),
+ flow: openlogi_ipc::FlowStatus::default(),
+ config_revision: openlogi_core::config::ConfigRevision::default(),
+ }
+}
+
+fn slot(slot: u8) -> DeviceRoute {
+ DeviceRoute::Bolt {
+ receiver_uid: "test-receiver".into(),
+ slot,
+ }
+}
+
+fn reply(f: impl FnOnce(AgentRequest) -> AgentResponse + Send + 'static) -> Step {
+ Box::new(move |request| {
+ let response = f(request);
+ Box::pin(async move { Ok(response) })
+ })
+}
+
+/// The agent receives `pulse` for `route` and answers `result`.
+fn play(route: DeviceRoute, pulse: HapticPulse, result: Result<(), WriteError>) -> Step {
+ reply(move |request| {
+ let AgentRequest::PlayHaptic {
+ route: actual,
+ pulse: asked,
+ } = request
+ else {
+ panic!("expected a haptic play, got {request:?}");
+ };
+ assert_eq!((actual, asked), (route, pulse));
+ AgentResponse::PlayHaptic(result)
+ })
+}
+
+async fn run(
+ snapshot: AgentSnapshot,
+ device: Option<&str>,
+ waveform: Waveform,
+ steps: Vec,
+) -> (Result<()>, String) {
+ let mut steps = VecDeque::from(steps);
+ steps.push_front(reply(move |request| {
+ assert!(matches!(request, AgentRequest::Snapshot {}));
+ AgentResponse::Snapshot(snapshot)
+ }));
+ let queue = Arc::new(Mutex::new(steps));
+ let calls = queue.clone();
+ let client = in_memory_agent(
+ move |request| calls.lock().unwrap().pop_front().expect("unexpected RPC")(request),
+ pending(),
+ );
+ let mut out = Vec::new();
+ let args = HapticArgs {
+ device: device.map(str::to_owned),
+ action: HapticAction::Play { waveform },
+ };
+ let result = execute(args, Ok(client), &mut out).await;
+ assert!(queue.lock().unwrap().is_empty(), "missing expected RPC");
+ (result, String::from_utf8(out).unwrap())
+}
+
+fn failure(result: Result<()>, out: &str, message: &str) {
+ let error = format!("{:#}", result.unwrap_err());
+ assert!(
+ error.contains(message),
+ "{error:?} does not contain {message:?}"
+ );
+ assert!(!out.contains("played"), "failure printed success: {out}");
+}
+
+#[tokio::test]
+async fn a_tick_plays_on_the_one_haptic_device_without_a_name() {
+ let (result, out) = run(
+ snapshot(),
+ None,
+ Waveform::Tick,
+ vec![play(slot(2), HapticPulse::SubtleCollision, Ok(()))],
+ )
+ .await;
+ result.unwrap();
+ assert!(out.starts_with("played tick on MX Master 4"), "{out}");
+}
+
+#[tokio::test]
+async fn confirm_plays_the_confirmation_waveform_on_the_named_device() {
+ let (result, out) = run(
+ snapshot(),
+ Some("master"),
+ Waveform::Confirm,
+ vec![play(slot(2), HapticPulse::DampStateChange, Ok(()))],
+ )
+ .await;
+ result.unwrap();
+ assert!(out.starts_with("played confirm on MX Master 4"), "{out}");
+}
+
+#[tokio::test]
+async fn selection_refusals_never_reach_the_agent_with_a_play() {
+ let mut no_haptics = snapshot();
+ no_haptics.inventory[0].paired.remove(0);
+ let mut offline = snapshot();
+ offline.inventory[0].paired[0].online = false;
+ let mut two = snapshot();
+ two.inventory[0].paired[1] = paired(3, "MX Master 4 (2)", DeviceKind::Mouse, &[0x19b0]);
+ let mut scanning = snapshot();
+ scanning.status.inventory = InventoryHealth::Scanning;
+ for (snapshot, device, message) in [
+ (no_haptics, None, "measured haptic support"),
+ (offline, None, "no matching online haptic device"),
+ (two.clone(), None, "ambiguous haptic device selection"),
+ (two, Some("master"), "ambiguous haptic device selection"),
+ (
+ snapshot(),
+ Some("keys"),
+ "does not advertise HID++ haptic feedback",
+ ),
+ (scanning, None, "inventory is not ready"),
+ ] {
+ let (result, out) = run(snapshot, device, Waveform::Tick, vec![]).await;
+ failure(result, &out, message);
+ }
+}
+
+#[tokio::test]
+async fn the_agents_refusals_are_reported_as_failures() {
+ for (error, message) in [
+ (
+ WriteError::HapticWaveformUnsupported { waveform: 1 },
+ "does not advertise haptic waveform 1",
+ ),
+ (
+ WriteError::HapticsUnavailable { status: 2 },
+ "haptic status 2",
+ ),
+ (
+ WriteError::DeviceUnreachable { index: 2 },
+ "did not respond",
+ ),
+ (
+ WriteError::FeatureUnsupported {
+ feature_hex: 0x19b0,
+ },
+ "0x19b0",
+ ),
+ (
+ WriteError::WriteSuperseded {
+ operation: openlogi_core::hid::HidppOperation::PlayHaptic,
+ },
+ "a newer haptic replaced this one",
+ ),
+ ] {
+ let (result, out) = run(
+ snapshot(),
+ None,
+ Waveform::Confirm,
+ vec![play(slot(2), HapticPulse::DampStateChange, Err(error))],
+ )
+ .await;
+ failure(result, &out, message);
+ }
+}
+
+#[tokio::test]
+async fn no_agent_means_no_play_and_no_fallback() {
+ let mut out = Vec::new();
+ let args = HapticArgs {
+ device: None,
+ action: HapticAction::Play {
+ waveform: Waveform::Tick,
+ },
+ };
+ let skew = ConnectError::Skew(ProtocolSkew::AgentOlder { agent: 46 });
+ let error = format!(
+ "{:#}",
+ execute(args, Err(skew), &mut out).await.unwrap_err()
+ );
+ assert!(error.contains("no direct hardware fallback"), "{error}");
+ assert!(out.is_empty());
+}
diff --git a/crates/openlogi-cli/src/lib.rs b/crates/openlogi-cli/src/lib.rs
index 4012d480f9..3dba0bbaf2 100644
--- a/crates/openlogi-cli/src/lib.rs
+++ b/crates/openlogi-cli/src/lib.rs
@@ -50,6 +50,7 @@ mod tests {
use cmd::fixture::record_profile::RecordProfileArgs;
use cmd::fixture::verify::VerifyArgs;
use cmd::fixture::{FixtureCmd, FixtureRecordCmd};
+ use cmd::haptic::{HapticAction, Waveform};
/// Clap's own structural validation (arg ID collisions, invalid
/// `conflicts_with` targets, etc.) — cheap and catches a broken derive
@@ -161,6 +162,47 @@ mod tests {
}
}
+ /// A script's bare `haptic play` is the light tick; the device filter may
+ /// come before or after the subcommand.
+ #[test]
+ fn haptic_play_defaults_to_a_tick_and_takes_a_waveform_and_device() {
+ for (argv, device, waveform) in [
+ (&["play"][..], None, Waveform::Tick),
+ (&["play", "confirm"], None, Waveform::Confirm),
+ (
+ &["--device", "MX", "play", "tick"],
+ Some("MX"),
+ Waveform::Tick,
+ ),
+ (
+ &["play", "confirm", "--device", "MX"],
+ Some("MX"),
+ Waveform::Confirm,
+ ),
+ ] {
+ let cli = Cli::try_parse_from(["openlogi", "haptic"].iter().chain(argv))
+ .unwrap_or_else(|error| panic!("{argv:?} parses: {error}"));
+ let Some(Command::Haptic(args)) = cli.cmd else {
+ panic!("expected haptic command for {argv:?}");
+ };
+ assert_eq!(args.device.as_deref(), device, "{argv:?}");
+ let HapticAction::Play { waveform: parsed } = args.action;
+ assert_eq!(parsed, waveform, "{argv:?}");
+ }
+ }
+
+ #[test]
+ fn haptic_rejects_an_unknown_waveform_and_a_missing_action() {
+ for argv in [&["haptic", "play", "buzz"][..], &["haptic"]] {
+ let error = Cli::try_parse_from(["openlogi"].iter().chain(argv)).expect_err("rejected");
+ assert_ne!(
+ error.kind(),
+ clap::error::ErrorKind::DisplayHelp,
+ "{argv:?}"
+ );
+ }
+ }
+
#[test]
fn backlight_help_explains_agent_requirement_and_selection_changes() {
let help = Cli::try_parse_from(["openlogi", "backlight", "--help"]).unwrap_err();
diff --git a/crates/openlogi-core/src/hid.rs b/crates/openlogi-core/src/hid.rs
index 8f9cbd5803..6a1dda57d7 100644
--- a/crates/openlogi-core/src/hid.rs
+++ b/crates/openlogi-core/src/hid.rs
@@ -15,6 +15,7 @@ pub mod easy_switch;
pub mod error;
pub mod fn_lock;
pub mod force_sensing;
+pub mod haptic;
pub mod light;
pub mod onboard;
pub mod pairing;
@@ -35,6 +36,7 @@ pub use easy_switch::{EasySwitchHosts, EasySwitchSlot, HostConnection, HostOsInf
pub use error::{HidppFeatureErrorKind, HidppOperation, WriteError};
pub use fn_lock::FnLockState;
pub use force_sensing::ForceSensingInfo;
+pub use haptic::HapticPulse;
pub use light::{LightCommand, commands_for_light_settings};
pub use onboard::{OnboardMode, OnboardProfile, OnboardState, ProfileIndex};
pub use pairing::{Click, PairingError, PasskeyMethod, ReceiverSelector};
diff --git a/crates/openlogi-core/src/hid/haptic.rs b/crates/openlogi-core/src/hid/haptic.rs
new file mode 100644
index 0000000000..d28b299cdf
--- /dev/null
+++ b/crates/openlogi-core/src/hid/haptic.rs
@@ -0,0 +1,20 @@
+//! A haptic pulse a client asks the agent to play — pure data, no I/O.
+//!
+//! The HID++ `0x19b0` play that carries it lives in
+//! `openlogi_device::write::haptic`, which knows the firmware waveform IDs;
+//! the agent converts at that boundary.
+
+use serde::{Deserialize, Serialize};
+
+/// One of the waveforms HID++ `0x19b0 HapticFeedback` plays, named as the
+/// firmware names them.
+///
+/// Variant order is wire format: append only.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum HapticPulse {
+ /// A light tick: the Actions Ring plays it when the highlighted slot
+ /// changes.
+ SubtleCollision,
+ /// A confirmation pulse: the Actions Ring plays it when an action runs.
+ DampStateChange,
+}
diff --git a/crates/openlogi-ipc/src/ipc.rs b/crates/openlogi-ipc/src/ipc.rs
index 97a745d242..766c2bb816 100644
--- a/crates/openlogi-ipc/src/ipc.rs
+++ b/crates/openlogi-ipc/src/ipc.rs
@@ -20,9 +20,9 @@ use openlogi_core::device::{
};
use openlogi_core::hid::{
BacklightChange, BacklightState, DeviceRoute, DisableKeysMask, DisableKeysState, Dpi, DpiInfo,
- EasySwitchHosts, FnLockState, ForceSensingInfo, LightCommand, OnboardState, PairingError,
- PasskeyMethod, PointerSpeed, ReceiverSelector, ReportRate, ReportRateInfo, ScrollWheelMode,
- SidetoneLevel, SmartShiftStatus, WriteError,
+ EasySwitchHosts, FnLockState, ForceSensingInfo, HapticPulse, LightCommand, OnboardState,
+ PairingError, PasskeyMethod, PointerSpeed, ReceiverSelector, ReportRate, ReportRateInfo,
+ ScrollWheelMode, SidetoneLevel, SmartShiftStatus, WriteError,
};
use serde::{Deserialize, Serialize};
pub use succession::Identity;
@@ -194,7 +194,10 @@ pub use succession::Identity;
/// and `ActionRingIcon::{Channel1, Channel2, Channel3}` appended after
/// them — a device's move to another Easy-Switch channel, bound to a
/// button or an Actions Ring slot.
-pub const PROTOCOL_VERSION: u32 = 46;
+/// v47: `Agent::play_haptic` and [`HapticPulse`] appended — any client asks
+/// the agent to play one `0x19b0` waveform on a device, and hears how it
+/// went.
+pub const PROTOCOL_VERSION: u32 = 47;
/// Environment variable through which the agent hands a supervised helper the
/// run token it will serve, so the helper knows which agent it belongs to
@@ -1263,4 +1266,16 @@ pub trait Agent {
/// held trigger cancels instead of choosing the slot last reported by
/// [`Agent::action_ring_hover`].
async fn action_ring_unhover(session_id: u64) -> Result<(), ActionRingCommandError>;
+ /// Play `pulse` on the device at `route` now, for a client outside the
+ /// Actions Ring (the CLI, a script), and answer once it played or failed.
+ ///
+ /// Plays share the Actions Ring's single-flight haptic worker: a play a
+ /// newer one replaced before it reached the device answers
+ /// [`WriteError::WriteSuperseded`]. A device the agent does not list
+ /// online answers [`WriteError::DeviceNotFound`] or
+ /// [`WriteError::DeviceUnreachable`], and one without measured `0x19b0`
+ /// [`WriteError::FeatureUnsupported`], before anything is sent. When the
+ /// firmware engine is off, the agent turns it on for a burst of plays and
+ /// back off once they stop, as it does for a ring session.
+ async fn play_haptic(route: DeviceRoute, pulse: HapticPulse) -> Result<(), WriteError>;
}
diff --git a/crates/openlogi-ipc/tests/wire_format.rs b/crates/openlogi-ipc/tests/wire_format.rs
index 644af8d463..e9e67a860f 100644
--- a/crates/openlogi-ipc/tests/wire_format.rs
+++ b/crates/openlogi-ipc/tests/wire_format.rs
@@ -119,7 +119,7 @@ fn representative_smartshift_status() -> SmartShiftStatus {
/// unreleased version and leave this pin alone (`crates/openlogi-ipc/AGENTS.md`).
#[test]
fn protocol_version_is_pinned() {
- assert_eq!(PROTOCOL_VERSION, 46);
+ assert_eq!(PROTOCOL_VERSION, 47);
}
#[test]
@@ -476,6 +476,25 @@ fn lock_keys() {
);
}
+/// Appended after `action_ring_unhover`; the pulse is a unit variant index,
+/// append-only like every other enum on the wire.
+#[test]
+fn play_haptic() {
+ use openlogi_core::hid::HapticPulse;
+ assert_wire(
+ &AgentRequest::PlayHaptic {
+ route: DeviceRoute::Bolt {
+ receiver_uid: "F00DCAFE".into(),
+ slot: 1,
+ },
+ pulse: HapticPulse::DampStateChange,
+ },
+ "3a000846303044434146450101",
+ );
+ assert_wire(&HapticPulse::SubtleCollision, "00");
+ assert_wire(&HapticPulse::DampStateChange, "01");
+}
+
#[test]
fn switch_host() {
assert_wire(
diff --git a/docs/USAGE.md b/docs/USAGE.md
index b5499e35d6..e43a3d0808 100644
--- a/docs/USAGE.md
+++ b/docs/USAGE.md
@@ -110,6 +110,7 @@ openlogi api report-rate --device "$DEVICE_ID"
openlogi api report-rate --device "$DEVICE_ID" --set 1000 --save
openlogi api easy-switch --device "$DEVICE_ID"
openlogi api easy-switch --device "$DEVICE_ID" --channel 2 --name "Work laptop"
+openlogi api haptic --device "$DEVICE_ID" --waveform confirm
```
### Output and compatibility
@@ -142,6 +143,7 @@ stdout cannot provide a JSON envelope.
| `fn-lock` | `device`, `persistence`, `fn_lock`, `default_fn_lock` (boolean, or null when the keyboard reports no firmware default) |
| `os-layout` | `device`, `persistence`, `keep_os_layout` (boolean) |
| `report-rate` | `device`, `persistence`, `current` (integer, hertz), `supported` (array of integers in hertz, for the current connection) |
+| `haptic` | `device`, `waveform` (`tick` or `confirm`) |
| `easy-switch` | `device`, `persistence`, `current_channel` (integer from 1, or null), `can_rename` (boolean), `channels`: array of `channel` (integer from 1), `paired` (boolean), `connection` (`unknown`, `unifying`, `usb`, `bluetooth`, or `bolt`), `name` (string or null), `name_max_len` (integer, UTF-8 bytes), `os` (string such as `macOS 15.2`, or null) |
`inventory` is `scanning`, `ready`, or `unavailable`. Only `ready` with an empty
@@ -169,6 +171,11 @@ Not every readable setting has an inventory flag; a setting read can return
descriptor and null battery. Cameras are not part of this agent inventory API.
The response excludes pairing passkeys, application history, and model serials.
+`haptic` plays one pulse now and saves nothing, so `--save` fails with
+`invalid_value`. A device without measured haptic feedback, or one that does
+not advertise the waveform, returns `unsupported_feature`. The pulse plays as
+with `openlogi haptic play`, described below.
+
### Immediate control and saved preferences
The DPI, SmartShift, Fn-lock, and report-rate commands read only unless a setting flag is supplied. Without
@@ -255,6 +262,36 @@ Stable error codes: `agent_unavailable`, `handshake_failed`, `version_mismatch`,
`config_reload_failed`, and `config_reload_unknown`. A protocol mismatch requires matching
OpenLogi CLI and agent builds; it never triggers direct-hardware fallback.
+## Haptic feedback
+
+`openlogi haptic play` buzzes a mouse with HID++ haptic feedback (`0x19b0`),
+such as the MX Master 4, through the running agent, so a script or another
+app can confirm something on the hand. Like `backlight`, it needs a running,
+protocol-compatible agent in the same `OPENLOGI_PROFILE` and never opens HID
+directly.
+
+```sh
+openlogi haptic play # a light tick
+openlogi haptic play confirm # a firmer confirmation pulse
+openlogi haptic --device "MX Master 4" play tick
+```
+
+`tick` is the pulse the Actions Ring plays when it highlights another slot,
+and `confirm` the one it plays when an action runs. `--device NAME` selects as
+`backlight` does; without it the command picks the one online device with
+measured haptic feedback. Success prints one line and exits zero once the
+device played the pulse.
+
+Plays go through the agent's Actions Ring haptic worker. While another buzz
+is playing, only the newest waiting play survives; one replaced before it
+reached the device fails with "a newer haptic replaced this one". Plays that
+follow each other within 2 seconds share one haptic session, so after the
+first, each costs a single round-trip to the device. If the device's haptic
+engine was turned off, for example in Logi Options+, the first play of such a
+burst turns it on and the agent turns it back off 2 seconds after the last
+one. A device that does not advertise the waveform, or that reports it cannot
+play right now, fails before anything is sent.
+
## Asset synchronization
Asset synchronization probes `assets.openlogi.org`, the Cloudflare Pages alias