hidpp/feature.rs
1//! Specific device feature implementations.
2
3use std::{any::Any, sync::Arc};
4
5use crate::{
6 channel::{HidppChannel, HidppMessage, LONG_REPORT_LENGTH, MessageListenerGuard},
7 event::EventEmitter,
8 nibble::U4,
9 protocol::v20::{self, Hidpp20Error},
10};
11
12pub mod adjustable_dpi;
13pub mod backlight;
14pub mod battery_status;
15pub mod battery_voltage;
16pub mod brightness_control;
17pub mod change_host;
18pub mod color_led_effects;
19pub mod crown;
20pub mod device_friendly_name;
21pub mod device_information;
22pub mod device_type_and_name;
23pub mod disable_keys;
24pub mod disable_keys_by_usage;
25pub mod dual_platform;
26pub mod equalizer;
27pub mod extended_dpi;
28pub mod extended_report_rate;
29pub mod feature_set;
30pub mod fn_inversion;
31pub mod gestures2;
32pub mod haptic_feedback;
33pub mod hires_wheel;
34pub mod hosts_info;
35pub mod illumination;
36pub mod mode_status;
37pub mod mouse_pointer;
38pub mod multi_platform;
39pub mod per_key_lighting;
40pub mod persistent_remappable_action;
41pub mod registry;
42pub mod report_rate;
43pub mod reprog_controls;
44pub mod rgb_effects;
45pub mod root;
46pub mod sidetone;
47pub mod smartshift;
48pub mod smartshift_enhanced;
49pub mod solar_dashboard;
50pub mod thumbwheel;
51pub mod touch_mouse_raw;
52pub mod touchpad_raw_xy;
53pub mod unified_battery;
54pub mod vertical_scrolling;
55pub mod wireless_device_status;
56
57/// Represents a concrete implementation of a HID++2.0 device feature.
58pub trait Feature: Any + Send + Sync {}
59
60/// Represents a [`Feature`] that can be instantiated automatically.
61pub trait CreatableFeature: Feature {
62 /// The protocol ID of the implemented feature.
63 const ID: u16;
64
65 /// The version of the feature the implementation starts to support.
66 const STARTING_VERSION: u8;
67
68 /// Creates a new instance of the feature implementation.
69 fn new(chan: Arc<HidppChannel>, device_index: u8, feature_index: u8) -> Self;
70}
71
72/// Represents a [`Feature`] that emits events of type `T`.
73pub trait EmittingFeature<T>: Feature {
74 /// Creates a receiver that is being notified whenever a new event of type
75 /// `T` is emitted by the feature.
76 fn listen(&self) -> async_channel::Receiver<T>;
77}
78
79/// Decodes a feature's event payload from its HID++2.0 event sub-id.
80///
81/// Implemented by a feature's event enum. [`EventSource::attach`] calls
82/// [`Self::decode`] for every unsolicited broadcast addressed to the feature,
83/// so this is the only part of a feature's event handling that has to vary —
84/// [`EventSource`] owns the listener registration, the [`event_payload`]
85/// filtering, and the emitting. Returning `None` drops the report exactly
86/// like the hand-rolled per-feature listeners this replaced did on an
87/// unrecognised sub-id or an unparsable payload.
88pub(crate) trait DecodeEvent: Clone + Send + Sync + 'static {
89 /// Decodes `payload` for event sub-id `sub_id`, or returns `None` to drop
90 /// the report.
91 fn decode(sub_id: u8, payload: &[u8; LONG_REPORT_LENGTH - 4]) -> Option<Self>
92 where
93 Self: Sized;
94}
95
96/// Owns the [`EventEmitter`] and message listener backing an
97/// [`EmittingFeature`] implementation.
98///
99/// Every emitting feature used to hand-roll the same listener ceremony in its
100/// `CreatableFeature::new`: build an `Arc<EventEmitter<E>>`, register a
101/// guarded message listener, filter the raw report through [`event_payload`],
102/// and emit whatever the feature's own decode step produced. A feature now
103/// holds one `EventSource<E>` field, builds it with [`Self::attach`], and
104/// implements [`EmittingFeature`] with a one-line [`Self::listen`] delegate.
105pub(crate) struct EventSource<E: DecodeEvent> {
106 emitter: Arc<EventEmitter<E>>,
107
108 /// Removes the message listener when the source is dropped.
109 _listener: MessageListenerGuard,
110}
111
112impl<E: DecodeEvent> EventSource<E> {
113 /// Registers a listener on `chan` that decodes broadcasts addressed to
114 /// `(device_index, feature_index)` via [`DecodeEvent::decode`] and emits
115 /// them to receivers created by [`Self::listen`].
116 pub(crate) fn attach(chan: &Arc<HidppChannel>, device_index: u8, feature_index: u8) -> Self {
117 let emitter = Arc::new(EventEmitter::new());
118
119 let listener = chan.add_msg_listener_guarded({
120 let emitter = Arc::clone(&emitter);
121
122 move |raw, matched| {
123 let Some((func, payload)) =
124 event_payload(raw, matched, device_index, feature_index)
125 else {
126 return;
127 };
128 if let Some(event) = E::decode(func.to_lo(), &payload) {
129 emitter.emit(event);
130 }
131 }
132 });
133
134 Self {
135 emitter,
136 _listener: listener,
137 }
138 }
139
140 /// Creates a receiver notified of every event this source decodes.
141 pub(crate) fn listen(&self) -> async_channel::Receiver<E> {
142 self.emitter.create_receiver()
143 }
144}
145
146/// A feature's addressable `(device, feature)` endpoint on a channel.
147///
148/// Embedding this in a feature replaces the three loose `chan` / `device_index`
149/// / `feature_index` fields every implementation used to carry, and centralises
150/// the HID++2.0 request framing that was otherwise hand-written at every call
151/// site.
152#[derive(Clone)]
153pub(crate) struct FeatureEndpoint {
154 /// The underlying HID++ channel.
155 chan: Arc<HidppChannel>,
156
157 /// The index of the device the feature belongs to.
158 device_index: u8,
159
160 /// The index of the feature in the device's feature table.
161 feature_index: u8,
162}
163
164impl FeatureEndpoint {
165 /// Binds an endpoint to `feature_index` on `device_index` of `chan`.
166 pub(crate) fn new(chan: Arc<HidppChannel>, device_index: u8, feature_index: u8) -> Self {
167 Self {
168 chan,
169 device_index,
170 feature_index,
171 }
172 }
173
174 /// The request header addressing `function` on this endpoint, stamped with
175 /// the channel's next software id.
176 ///
177 /// `function` is a HID++2.0 function id, which is 4-bit; only the low nibble
178 /// is sent. The assert keeps a stray out-of-range id from silently routing
179 /// to a different function in debug builds.
180 fn header(&self, function: u8) -> v20::MessageHeader {
181 debug_assert!(
182 function < 16,
183 "HID++2.0 function id {function} exceeds 4 bits"
184 );
185 v20::MessageHeader {
186 device_index: self.device_index,
187 feature_index: self.feature_index,
188 function_id: U4::from_lo(function),
189 software_id: self.chan.get_sw_id(),
190 }
191 }
192
193 /// Calls `function` with a 3-byte short-report payload and waits for the
194 /// matching response.
195 pub(crate) async fn call(
196 &self,
197 function: u8,
198 args: [u8; 3],
199 ) -> Result<v20::Message, Hidpp20Error> {
200 self.chan
201 .send_v20(v20::Message::Short(self.header(function), args))
202 .await
203 }
204
205 /// Calls `function` with a 16-byte long-report payload and waits for the
206 /// matching response.
207 pub(crate) async fn call_long(
208 &self,
209 function: u8,
210 args: [u8; 16],
211 ) -> Result<v20::Message, Hidpp20Error> {
212 self.chan
213 .send_v20(v20::Message::Long(self.header(function), args))
214 .await
215 }
216
217 /// Sends `function` with a 3-byte short-report payload without waiting for a
218 /// response.
219 ///
220 /// For functions the device answers normally use [`Self::call`]; this is for
221 /// the rare function whose side effect (e.g. a host switch that resets the
222 /// device) prevents a response from ever arriving.
223 pub(crate) async fn notify(&self, function: u8, args: [u8; 3]) -> Result<(), Hidpp20Error> {
224 self.chan
225 .send_and_forget(v20::Message::Short(self.header(function), args).into())
226 .await?;
227 Ok(())
228 }
229}
230
231/// Shared prelude for a feature's event listener.
232///
233/// Drops reports already matched to an outgoing request, parses the raw report
234/// as a HID++2.0 message, and keeps only unsolicited broadcasts addressed to
235/// this `(device_index, feature_index)` with a zero software id. Returns the
236/// event's function id (its sub-id) and extended payload, leaving sub-id
237/// dispatch to the caller — so a multi-event feature filters its sub-ids
238/// explicitly rather than folding the check into the header guard.
239pub(crate) fn event_payload(
240 raw: HidppMessage,
241 matched: bool,
242 device_index: u8,
243 feature_index: u8,
244) -> Option<(U4, [u8; LONG_REPORT_LENGTH - 4])> {
245 if matched {
246 return None;
247 }
248
249 let msg = v20::Message::from(raw);
250 let header = msg.header();
251 if header.device_index != device_index
252 || header.feature_index != feature_index
253 || header.software_id.to_lo() != 0
254 {
255 return None;
256 }
257
258 Some((header.function_id, msg.extend_payload()))
259}
260
261bitflags::bitflags! {
262 /// A bitfield describing some properties of a feature.
263 ///
264 /// Documentation is taken from <https://drive.google.com/file/d/1ULmw9uJL8b8iwwUo5xjSS9F5Zvno-86y/view>.
265 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
266 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
267 pub struct FeatureType: u8 {
268 /// An obsolete feature is a feature that has been replaced by a newer
269 /// one, but is advertised in order for older SWs to still be able to
270 /// support the feature (in case the old SW does not know yet the newer
271 /// one).
272 const OBSOLETE = 1 << 7;
273
274 /// A SW hidden feature is a feature that should not be
275 /// known/managed/used by end user configuration SW. The host should
276 /// ignore this type of features.
277 const HIDDEN = 1 << 6;
278
279 /// A hidden feature that has been disabled for user software. Used for
280 /// internal testing and manufacturing.
281 const ENGINEERING = 1 << 5;
282
283 /// A manufacturing feature that can be permanently deactivated. It is
284 /// usually also hidden and engineering.
285 ///
286 /// This flag was added in feature version 2 and is never set by older
287 /// versions.
288 const MANUFACTURING_DEACTIVATABLE = 1 << 4;
289
290 /// A compliance feature that can be permanently deactivated. It is
291 /// usually also hidden and engineering.
292 ///
293 /// This flag was added in feature version 2 and is never set by older
294 /// versions.
295 const COMPLIANCE_DEACTIVATABLE = 1 << 3;
296 }
297}
298
299#[cfg(test)]
300#[allow(
301 clippy::unwrap_used,
302 clippy::expect_used,
303 reason = "expect/unwrap are idiomatic in tests"
304)]
305mod tests {
306 use super::event_payload;
307 use crate::{
308 channel::HidppMessage,
309 nibble::U4,
310 protocol::v20::{Message, MessageHeader},
311 };
312
313 /// Builds a raw long report carrying a HID++2.0 broadcast with the given
314 /// header fields and a recognisable payload.
315 fn broadcast(device_index: u8, feature_index: u8, function: u8, software: u8) -> HidppMessage {
316 Message::Long(
317 MessageHeader {
318 device_index,
319 feature_index,
320 function_id: U4::from_lo(function),
321 software_id: U4::from_lo(software),
322 },
323 [0xab; 16],
324 )
325 .into()
326 }
327
328 #[test]
329 fn accepts_matching_broadcast_and_returns_sub_id() {
330 let (func, payload) =
331 event_payload(broadcast(2, 5, 1, 0), false, 2, 5).expect("broadcast should pass");
332 assert_eq!(func.to_lo(), 1);
333 assert_eq!(payload, [0xab; 16]);
334 }
335
336 #[test]
337 fn rejects_request_matched_report() {
338 // A report already matched to an outgoing request is a response, not an
339 // event.
340 assert!(event_payload(broadcast(2, 5, 0, 0), true, 2, 5).is_none());
341 }
342
343 #[test]
344 fn rejects_other_device_or_feature() {
345 assert!(event_payload(broadcast(9, 5, 0, 0), false, 2, 5).is_none());
346 assert!(event_payload(broadcast(2, 9, 0, 0), false, 2, 5).is_none());
347 }
348
349 #[test]
350 fn gates_on_software_id_only_not_sub_id() {
351 // Only the software id gates a broadcast: a nonzero one is rejected, but
352 // a nonzero function id is a valid event sub-id the caller dispatches on
353 // and must still pass. This is the invariant the old per-feature
354 // `nibble::combine(software_id, function_id) != 0` guard got right only
355 // by accident (those features happened to emit a single sub-id 0 event).
356 assert!(event_payload(broadcast(2, 5, 0, 1), false, 2, 5).is_none());
357 assert!(event_payload(broadcast(2, 5, 7, 0), false, 2, 5).is_some());
358 }
359}