use crate::event::SpaceMouseEvent;
const REPORT_ID_TRANSLATION: u8 = 1;
const REPORT_ID_ROTATION: u8 = 2;
const MIN_AXIS_REPORT_LEN: usize = 7;
pub fn parse_report(data: &[u8]) -> Option<SpaceMouseEvent> {
let (&report_id, rest) = data.split_first()?;
match report_id {
REPORT_ID_TRANSLATION if data.len() >= MIN_AXIS_REPORT_LEN => {
let (x, y, z) = read_three_axes(rest);
Some(SpaceMouseEvent::Translation { x, y, z })
}
REPORT_ID_ROTATION if data.len() >= MIN_AXIS_REPORT_LEN => {
let (x, y, z) = read_three_axes(rest);
Some(SpaceMouseEvent::Rotation { x, y, z })
}
_ => None,
}
}
fn read_three_axes(data: &[u8]) -> (i16, i16, i16) {
(
le_i16(&data[0..2]),
le_i16(&data[2..4]),
le_i16(&data[4..6]),
)
}
fn le_i16(bytes: &[u8]) -> i16 {
i16::from_le_bytes([bytes[0], bytes[1]])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_translation_report() {
let data = [1u8, 0x10, 0x00, 0x20, 0x00, 0xf0, 0xff];
assert_eq!(
parse_report(&data),
Some(SpaceMouseEvent::Translation {
x: 0x10,
y: 0x20,
z: -16,
})
);
}
#[test]
fn parses_rotation_report() {
let data = [2u8, 0xff, 0xff, 0x00, 0x00, 0xff, 0x7f];
assert_eq!(
parse_report(&data),
Some(SpaceMouseEvent::Rotation {
x: -1,
y: 0,
z: 0x7fff,
})
);
}
#[test]
fn rejects_unknown_report_id() {
assert_eq!(parse_report(&[9, 0, 0, 0, 0, 0, 0]), None);
}
#[test]
fn rejects_too_short_axis_report() {
assert_eq!(parse_report(&[1, 0, 0, 0, 0]), None);
}
#[test]
fn rejects_empty_report() {
assert_eq!(parse_report(&[]), None);
}
}