Skip to main content

xbox_controller_core/
report.rs

1use crate::{ParseError, XboxButtonState, XboxControllerState, XboxSticks, XboxTriggers};
2
3/// Length of the currently supported Xbox Series input report.
4pub const INPUT_REPORT_LEN: usize = 16;
5
6/// Parse an Xbox Series controller BLE input notification.
7///
8/// This initially supports the 16-byte layout documented by the
9/// `asukiaaa/arduino-XboxControllerNotificationParser` project. The report ID
10/// belongs to the GATT Report characteristic/descriptor and is therefore not
11/// present in these notification bytes.
12pub fn parse_input_report(bytes: &[u8]) -> Result<XboxControllerState, ParseError> {
13    if bytes.len() < INPUT_REPORT_LEN {
14        return Err(ParseError::TooShort {
15            expected: INPUT_REPORT_LEN,
16            actual: bytes.len(),
17        });
18    }
19
20    let main = bytes[13];
21    let center = bytes[14];
22    let dpad = bytes[12];
23
24    Ok(XboxControllerState {
25        buttons: XboxButtonState {
26            a: main & 0x01 != 0,
27            b: main & 0x02 != 0,
28            x: main & 0x08 != 0,
29            y: main & 0x10 != 0,
30            lb: main & 0x40 != 0,
31            rb: main & 0x80 != 0,
32            view: center & 0x04 != 0,
33            menu: center & 0x08 != 0,
34            xbox: center & 0x10 != 0,
35            left_stick_button: center & 0x20 != 0,
36            right_stick_button: center & 0x40 != 0,
37            share: bytes[15] & 0x01 != 0,
38            dpad_up: matches!(dpad, 1 | 2 | 8),
39            dpad_right: matches!(dpad, 2..=4),
40            dpad_down: matches!(dpad, 4..=6),
41            dpad_left: matches!(dpad, 6..=8),
42        },
43        sticks: XboxSticks {
44            left_x: centered_axis(bytes, 0),
45            left_y: centered_axis(bytes, 2),
46            right_x: centered_axis(bytes, 4),
47            right_y: centered_axis(bytes, 6),
48        },
49        triggers: XboxTriggers {
50            left: u16_at(bytes, 8),
51            right: u16_at(bytes, 10),
52        },
53    })
54}
55
56fn u16_at(bytes: &[u8], offset: usize) -> u16 {
57    u16::from_le_bytes([bytes[offset], bytes[offset + 1]])
58}
59
60fn centered_axis(bytes: &[u8], offset: usize) -> i16 {
61    (i32::from(u16_at(bytes, offset)) - 0x8000) as i16
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    // These samples encode the currently known 16-byte layout. Offsets may
69    // need adjustment after comparison with real controller firmware dumps.
70    fn neutral_report() -> [u8; INPUT_REPORT_LEN] {
71        [
72            0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0, 0, 0, 0, 0, 0, 0, 0,
73        ]
74    }
75
76    #[test]
77    fn rejects_too_short_input() {
78        assert_eq!(
79            parse_input_report(&[0; 15]),
80            Err(ParseError::TooShort {
81                expected: 16,
82                actual: 15
83            })
84        );
85    }
86
87    #[test]
88    fn parses_neutral_state() {
89        assert_eq!(
90            parse_input_report(&neutral_report()).unwrap(),
91            XboxControllerState::default()
92        );
93    }
94
95    #[test]
96    fn parses_face_buttons() {
97        let mut report = neutral_report();
98        report[13] = 0x01 | 0x02 | 0x08 | 0x10;
99        let buttons = parse_input_report(&report).unwrap().buttons;
100        assert!(buttons.a && buttons.b && buttons.x && buttons.y);
101    }
102
103    #[test]
104    fn parses_dpad_cardinals_and_diagonals() {
105        for (hat, up, right, down, left) in [
106            (0, false, false, false, false),
107            (1, true, false, false, false),
108            (2, true, true, false, false),
109            (3, false, true, false, false),
110            (5, false, false, true, false),
111            (7, false, false, false, true),
112            (8, true, false, false, true),
113        ] {
114            let mut report = neutral_report();
115            report[12] = hat;
116            let buttons = parse_input_report(&report).unwrap().buttons;
117            assert_eq!(
118                (
119                    buttons.dpad_up,
120                    buttons.dpad_right,
121                    buttons.dpad_down,
122                    buttons.dpad_left
123                ),
124                (up, right, down, left)
125            );
126        }
127    }
128
129    #[test]
130    fn parses_triggers() {
131        let mut report = neutral_report();
132        report[8..12].copy_from_slice(&[0x23, 0x01, 0xff, 0x03]);
133        assert_eq!(
134            parse_input_report(&report).unwrap().triggers,
135            XboxTriggers {
136                left: 0x123,
137                right: 0x3ff
138            }
139        );
140    }
141
142    #[test]
143    fn parses_and_centers_sticks() {
144        let mut report = neutral_report();
145        report[..8].copy_from_slice(&[0, 0, 0xff, 0xff, 0x34, 0x92, 0xcc, 0x6d]);
146        assert_eq!(
147            parse_input_report(&report).unwrap().sticks,
148            XboxSticks {
149                left_x: i16::MIN,
150                left_y: i16::MAX,
151                right_x: 0x1234,
152                right_y: -0x1234
153            }
154        );
155    }
156
157    #[test]
158    fn accepts_transport_metadata_after_report() {
159        let mut report = [0u8; 17];
160        report[0..16].copy_from_slice(&neutral_report());
161        assert!(parse_input_report(&report).is_ok());
162    }
163}