1use std::{thread, time::Duration};
12
13use razers_protocol_core::{REPORT_90_SIZE, Report90, Report90Error};
14use razers_transport::{ReportIo, TransportError};
15use thiserror::Error;
16
17pub const STATUS_NEW_COMMAND: u8 = 0x00;
18pub const STATUS_BUSY: u8 = 0x01;
19pub const STATUS_SUCCESSFUL: u8 = 0x02;
20pub const STATUS_FAILURE: u8 = 0x03;
21pub const STATUS_TIMEOUT: u8 = 0x04;
22pub const STATUS_NOT_SUPPORTED: u8 = 0x05;
23
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub enum BusyHandling {
34 Accept,
35 Retry,
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub struct ExchangePolicy {
43 pub report_id: u8,
44 pub response_wait: Duration,
45 pub busy_handling: BusyHandling,
46 pub busy_retries: u8,
47 pub busy_retry_wait: Duration,
48 pub validate_transaction_id: bool,
49 pub validate_remaining_packets: bool,
50}
51
52impl ExchangePolicy {
53 pub const fn new(report_id: u8, response_wait: Duration) -> Self {
58 Self {
59 report_id,
60 response_wait,
61 busy_handling: BusyHandling::Accept,
62 busy_retries: 0,
63 busy_retry_wait: Duration::from_millis(10),
64 validate_transaction_id: false,
65 validate_remaining_packets: true,
66 }
67 }
68
69 pub const fn with_busy_retry(mut self, retries: u8, wait: Duration) -> Self {
74 self.busy_handling = BusyHandling::Retry;
75 self.busy_retries = retries;
76 self.busy_retry_wait = wait;
77 self
78 }
79
80 pub const fn with_transaction_validation(mut self, enabled: bool) -> Self {
81 self.validate_transaction_id = enabled;
82 self
83 }
84
85 pub const fn with_remaining_packets_validation(mut self, enabled: bool) -> Self {
86 self.validate_remaining_packets = enabled;
87 self
88 }
89}
90
91pub trait Delay {
95 fn wait(&mut self, duration: Duration);
96}
97
98#[derive(Clone, Copy, Debug, Default)]
99pub struct ThreadDelay;
100
101impl Delay for ThreadDelay {
102 fn wait(&mut self, duration: Duration) {
103 thread::sleep(duration);
104 }
105}
106
107pub struct FeatureExchange<T, D = ThreadDelay> {
111 transport: T,
112 policy: ExchangePolicy,
113 delay: D,
114}
115
116impl<T> FeatureExchange<T, ThreadDelay> {
117 pub fn new(transport: T, policy: ExchangePolicy) -> Self {
118 Self {
119 transport,
120 policy,
121 delay: ThreadDelay,
122 }
123 }
124}
125
126impl<T, D> FeatureExchange<T, D> {
127 pub fn with_delay(transport: T, policy: ExchangePolicy, delay: D) -> Self {
128 Self {
129 transport,
130 policy,
131 delay,
132 }
133 }
134
135 pub const fn policy(&self) -> &ExchangePolicy {
136 &self.policy
137 }
138
139 pub fn into_parts(self) -> (T, D) {
140 (self.transport, self.delay)
141 }
142}
143
144impl<T: ReportIo, D: Delay> FeatureExchange<T, D> {
145 pub fn execute(&mut self, request: &Report90) -> Result<Report90, ExchangeError> {
152 let request_bytes = request.encode()?;
153 let maximum_attempts = usize::from(self.policy.busy_retries) + 1;
154
155 for attempt in 1..=maximum_attempts {
156 self.transport
157 .set_feature(self.policy.report_id, &request_bytes)?;
158 self.delay.wait(self.policy.response_wait);
159
160 let mut response_bytes = [0_u8; REPORT_90_SIZE];
161 let actual = self
162 .transport
163 .get_feature(self.policy.report_id, &mut response_bytes)?;
164 if actual != REPORT_90_SIZE {
165 return Err(ExchangeError::ShortRead {
166 expected: REPORT_90_SIZE,
167 actual,
168 });
169 }
170 let response = Report90::decode(&response_bytes)?;
171 self.validate_response(request, &response)?;
172
173 match response.status {
174 STATUS_SUCCESSFUL => return Ok(response),
175 STATUS_BUSY if self.policy.busy_handling == BusyHandling::Accept => {
176 return Ok(response);
177 }
178 STATUS_BUSY if attempt < maximum_attempts => {
179 self.delay.wait(self.policy.busy_retry_wait);
180 }
181 STATUS_BUSY => return Err(ExchangeError::BusyExhausted { attempts: attempt }),
182 status => {
183 return Err(ExchangeError::DeviceStatus {
184 status,
185 command_class: request.command_class,
186 command_id: request.command_id,
187 });
188 }
189 }
190 }
191
192 unreachable!("the inclusive attempt range always executes")
193 }
194
195 fn validate_response(
196 &self,
197 request: &Report90,
198 response: &Report90,
199 ) -> Result<(), ExchangeError> {
200 if response.command_class != request.command_class
201 || response.command_id != request.command_id
202 {
203 return Err(ExchangeError::EchoMismatch {
204 expected_class: request.command_class,
205 expected_id: request.command_id,
206 actual_class: response.command_class,
207 actual_id: response.command_id,
208 });
209 }
210 if self.policy.validate_transaction_id && response.transaction_id != request.transaction_id
211 {
212 return Err(ExchangeError::TransactionMismatch {
213 expected: request.transaction_id,
214 actual: response.transaction_id,
215 });
216 }
217 if self.policy.validate_remaining_packets
218 && response.remaining_packets != request.remaining_packets
219 {
220 return Err(ExchangeError::RemainingPacketsMismatch {
221 expected: request.remaining_packets,
222 actual: response.remaining_packets,
223 });
224 }
225 Ok(())
226 }
227}
228
229#[derive(Clone, Debug, Error, Eq, PartialEq)]
230pub enum ExchangeError {
231 #[error(transparent)]
232 Transport(#[from] TransportError),
233 #[error(transparent)]
234 Codec(#[from] Report90Error),
235 #[error("short feature response: expected {expected} bytes, received {actual}")]
236 ShortRead { expected: usize, actual: usize },
237 #[error(
238 "response echo mismatch: expected class/id 0x{expected_class:02x}/0x{expected_id:02x}, received 0x{actual_class:02x}/0x{actual_id:02x}"
239 )]
240 EchoMismatch {
241 expected_class: u8,
242 expected_id: u8,
243 actual_class: u8,
244 actual_id: u8,
245 },
246 #[error("response transaction ID mismatch: expected 0x{expected:02x}, received 0x{actual:02x}")]
247 TransactionMismatch { expected: u8, actual: u8 },
248 #[error("response remaining-packets mismatch: expected {expected}, received {actual}")]
249 RemainingPacketsMismatch { expected: u16, actual: u16 },
250 #[error(
251 "device returned status 0x{status:02x} for class/id 0x{command_class:02x}/0x{command_id:02x}"
252 )]
253 DeviceStatus {
254 status: u8,
255 command_class: u8,
256 command_id: u8,
257 },
258 #[error("device remained busy after {attempts} attempts")]
259 BusyExhausted { attempts: usize },
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265 use razers_transport::{ReplayStep, ReplayTransport};
266
267 #[derive(Default)]
268 struct RecordingDelay {
269 waits: Vec<Duration>,
270 }
271
272 impl Delay for RecordingDelay {
273 fn wait(&mut self, duration: Duration) {
274 self.waits.push(duration);
275 }
276 }
277
278 fn request() -> Report90 {
279 Report90::command(0x04, 0x85, [0x01])
280 .unwrap()
281 .with_transaction_id(0x3f)
282 }
283
284 fn response(request: &Report90, status: u8) -> Report90 {
285 let mut response = Report90::command(request.command_class, request.command_id, [0x7f])
286 .unwrap()
287 .with_transaction_id(request.transaction_id);
288 response.status = status;
289 response.remaining_packets = request.remaining_packets;
290 response
291 }
292
293 fn exchange_steps(request: &Report90, response: &Report90) -> [ReplayStep; 2] {
294 [
295 ReplayStep::SetFeature {
296 report_id: 0,
297 payload: request.encode().unwrap().to_vec(),
298 },
299 ReplayStep::GetFeature {
300 report_id: 0,
301 response: response.encode().unwrap().to_vec(),
302 },
303 ]
304 }
305
306 fn test_policy() -> ExchangePolicy {
307 ExchangePolicy::new(0, Duration::from_millis(5)).with_transaction_validation(true)
308 }
309
310 #[test]
311 fn completes_a_valid_exchange_without_real_waiting() {
312 let request = request();
313 let expected = response(&request, STATUS_SUCCESSFUL);
314 let transport = ReplayTransport::new(exchange_steps(&request, &expected));
315 let mut exchange =
316 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
317
318 assert_eq!(exchange.execute(&request).unwrap(), expected);
319 let (transport, delay) = exchange.into_parts();
320 assert_eq!(transport.verify_complete(), Ok(()));
321 assert_eq!(delay.waits, [Duration::from_millis(5)]);
322 }
323
324 #[test]
325 fn can_accept_busy_without_resending_a_write() {
326 let request = request();
327 let expected = response(&request, STATUS_BUSY);
328 let transport = ReplayTransport::new(exchange_steps(&request, &expected));
329 let mut exchange =
330 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
331
332 assert_eq!(exchange.execute(&request).unwrap(), expected);
333 let (transport, delay) = exchange.into_parts();
334 assert_eq!(transport.verify_complete(), Ok(()));
335 assert_eq!(delay.waits, [Duration::from_millis(5)]);
336 }
337
338 #[test]
339 fn retries_busy_when_the_policy_explicitly_allows_it() {
340 let request = request();
341 let busy = response(&request, STATUS_BUSY);
342 let success = response(&request, STATUS_SUCCESSFUL);
343 let steps = exchange_steps(&request, &busy)
344 .into_iter()
345 .chain(exchange_steps(&request, &success));
346 let transport = ReplayTransport::new(steps);
347 let policy = test_policy().with_busy_retry(2, Duration::from_millis(10));
348 let mut exchange =
349 FeatureExchange::with_delay(transport, policy, RecordingDelay::default());
350
351 assert_eq!(exchange.execute(&request).unwrap(), success);
352 let (transport, delay) = exchange.into_parts();
353 assert_eq!(transport.verify_complete(), Ok(()));
354 assert_eq!(
355 delay.waits,
356 [
357 Duration::from_millis(5),
358 Duration::from_millis(10),
359 Duration::from_millis(5)
360 ]
361 );
362 }
363
364 #[test]
365 fn reports_busy_retry_exhaustion() {
366 let request = request();
367 let busy = response(&request, STATUS_BUSY);
368 let steps = (0..3).flat_map(|_| exchange_steps(&request, &busy));
369 let transport = ReplayTransport::new(steps);
370 let policy = test_policy().with_busy_retry(2, Duration::from_millis(10));
371 let mut exchange =
372 FeatureExchange::with_delay(transport, policy, RecordingDelay::default());
373
374 assert_eq!(
375 exchange.execute(&request),
376 Err(ExchangeError::BusyExhausted { attempts: 3 })
377 );
378 let (transport, delay) = exchange.into_parts();
379 assert_eq!(transport.verify_complete(), Ok(()));
380 assert_eq!(delay.waits.len(), 5);
381 }
382
383 #[test]
384 fn rejects_a_mismatched_command_echo() {
385 let request = request();
386 let mut wrong = response(&request, STATUS_SUCCESSFUL);
387 wrong.command_id ^= 1;
388 let transport = ReplayTransport::new(exchange_steps(&request, &wrong));
389 let mut exchange =
390 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
391
392 assert!(matches!(
393 exchange.execute(&request),
394 Err(ExchangeError::EchoMismatch { .. })
395 ));
396 }
397
398 #[test]
399 fn optionally_rejects_a_mismatched_transaction() {
400 let request = request();
401 let mut wrong = response(&request, STATUS_SUCCESSFUL);
402 wrong.transaction_id = 0x1f;
403 let transport = ReplayTransport::new(exchange_steps(&request, &wrong));
404 let mut exchange =
405 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
406
407 assert_eq!(
408 exchange.execute(&request),
409 Err(ExchangeError::TransactionMismatch {
410 expected: 0x3f,
411 actual: 0x1f
412 })
413 );
414 }
415
416 #[test]
417 fn rejects_a_mismatched_packet_counter_by_default() {
418 let request = request();
419 let mut wrong = response(&request, STATUS_SUCCESSFUL);
420 wrong.remaining_packets = 1;
421 let transport = ReplayTransport::new(exchange_steps(&request, &wrong));
422 let mut exchange =
423 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
424
425 assert_eq!(
426 exchange.execute(&request),
427 Err(ExchangeError::RemainingPacketsMismatch {
428 expected: 0,
429 actual: 1
430 })
431 );
432 }
433
434 #[test]
435 fn preserves_a_device_failure_status() {
436 let request = request();
437 let failed = response(&request, STATUS_NOT_SUPPORTED);
438 let transport = ReplayTransport::new(exchange_steps(&request, &failed));
439 let mut exchange =
440 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
441
442 assert_eq!(
443 exchange.execute(&request),
444 Err(ExchangeError::DeviceStatus {
445 status: STATUS_NOT_SUPPORTED,
446 command_class: 0x04,
447 command_id: 0x85
448 })
449 );
450 }
451
452 #[test]
453 fn rejects_a_short_response_before_decoding() {
454 let request = request();
455 let transport = ReplayTransport::new([
456 ReplayStep::SetFeature {
457 report_id: 0,
458 payload: request.encode().unwrap().to_vec(),
459 },
460 ReplayStep::GetFeature {
461 report_id: 0,
462 response: vec![0; REPORT_90_SIZE - 1],
463 },
464 ]);
465 let mut exchange =
466 FeatureExchange::with_delay(transport, test_policy(), RecordingDelay::default());
467
468 assert_eq!(
469 exchange.execute(&request),
470 Err(ExchangeError::ShortRead {
471 expected: REPORT_90_SIZE,
472 actual: REPORT_90_SIZE - 1
473 })
474 );
475 }
476}