Skip to main content

xbox_controller_core/
report.rs

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