Skip to main content

gearvr_controller/
protocol.rs

1//! The controller's Bluetooth LE wire format.
2//!
3//! The controller exposes one custom GATT service with two characteristics: one to write
4//! two-byte [`Command`]s to, and one that notifies with 60-byte data packets once
5//! [`Command::Sensor`] has been sent.
6//!
7//! | Bytes  | Content                                                              |
8//! |--------|----------------------------------------------------------------------|
9//! | 0–15   | Motion sample 1: `u32` time (µs), accel xyz, gyro xyz (`i16` each)   |
10//! | 16–31  | Motion sample 2, same layout                                         |
11//! | 32–47  | Motion sample 3, same layout                                         |
12//! | 48–53  | Magnetometer, `i16` each, stored in y, x, z order                    |
13//! | 54–56  | Touchpad position: two 10-bit values packed into 20 bits             |
14//! | 57     | Temperature                                                          |
15//! | 58     | Buttons, one bit each; bit 6 is set while nothing is pressed         |
16//! | 59     | Unknown                                                              |
17//!
18//! All multi-byte values are little-endian.
19
20use std::fmt;
21use std::ops::BitOr;
22
23/// The controller's custom GATT service.
24pub const SERVICE_UUID: u128 = 0x4f63756c_7573_2054_6872_65656d6f7465;
25/// Characteristic that notifies with data packets.
26pub const NOTIFY_UUID: u128 = 0xc8c51726_81bc_483b_a052_f7a14ea3d281;
27/// Characteristic that accepts [`Command`]s.
28pub const WRITE_UUID: u128 = 0xc8c51726_81bc_483b_a052_f7a14ea3d282;
29/// The advertised name starts with this, followed by a four-character id in brackets.
30pub const NAME_PREFIX: &str = "Gear VR";
31
32/// Length of a full data packet.
33pub const PACKET_LEN: usize = 60;
34/// Accelerometer scale: m/s² per count.
35pub const ACCEL_SCALE: f32 = 9.80665 / 2048.0;
36/// Gyroscope scale: rad/s per count.
37pub const GYRO_SCALE: f32 = 0.017_453_292 / 14.285;
38/// Magnetometer scale: µT per count.
39pub const MAG_SCALE: f32 = 0.06;
40/// Largest touchpad coordinate on either axis.
41pub const TOUCH_MAX: u16 = 315;
42/// Typical spacing of motion samples, in microseconds (about 206 samples per second).
43pub const SAMPLE_INTERVAL_US: u32 = 4850;
44
45/// A command written to the controller.
46///
47/// The controller also has a "VR mode" (`08 00`). It does not work when the controller is
48/// driven from a computer, so it is not offered here.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50pub enum Command {
51    /// Stop sending data.
52    Off,
53    /// Start sending 60-byte data packets.
54    Sensor,
55    /// Keep-alive. It does not stop the controller sleeping when left untouched.
56    KeepAlive,
57}
58
59impl Command {
60    /// The two bytes to write to [`WRITE_UUID`].
61    pub const fn bytes(self) -> [u8; 2] {
62        match self {
63            Command::Off => [0x00, 0x00],
64            Command::Sensor => [0x01, 0x00],
65            Command::KeepAlive => [0x04, 0x00],
66        }
67    }
68}
69
70/// One gyroscope and accelerometer reading. Each packet carries three.
71#[derive(Clone, Copy, Debug, Default, PartialEq)]
72pub struct ImuSample {
73    /// The controller's clock in microseconds. Wraps about every 71.6 minutes.
74    pub timestamp_us: u32,
75    /// Acceleration in m/s², including gravity (about +9.8 on the axis pointing up).
76    pub accel: [f32; 3],
77    /// Angular velocity in rad/s, right-handed about each axis.
78    pub gyro: [f32; 3],
79}
80
81/// The set of buttons held down.
82#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
83pub struct Buttons(u8);
84
85impl Buttons {
86    pub const NONE: Buttons = Buttons(0);
87    pub const TRIGGER: Buttons = Buttons(1 << 0);
88    pub const HOME: Buttons = Buttons(1 << 1);
89    pub const BACK: Buttons = Buttons(1 << 2);
90    /// The touchpad pressed down until it clicks (touching alone is reported by [`Packet::touch`]).
91    pub const TOUCHPAD: Buttons = Buttons(1 << 3);
92    pub const VOLUME_UP: Buttons = Buttons(1 << 4);
93    pub const VOLUME_DOWN: Buttons = Buttons(1 << 5);
94
95    /// Every button with its name, in a stable order.
96    pub const ALL: [(Buttons, &'static str); 6] = [
97        (Buttons::TRIGGER, "Trigger"),
98        (Buttons::TOUCHPAD, "Touchpad click"),
99        (Buttons::BACK, "Back"),
100        (Buttons::HOME, "Home"),
101        (Buttons::VOLUME_UP, "Volume up"),
102        (Buttons::VOLUME_DOWN, "Volume down"),
103    ];
104
105    const MASK: u8 = 0b0011_1111;
106
107    /// Builds a set from the packet's button byte, ignoring the non-button bits.
108    pub const fn from_bits(bits: u8) -> Buttons {
109        Buttons(bits & Buttons::MASK)
110    }
111
112    pub const fn bits(self) -> u8 {
113        self.0
114    }
115
116    pub const fn is_empty(self) -> bool {
117        self.0 == 0
118    }
119
120    /// True if every button in `other` is held.
121    pub const fn contains(self, other: Buttons) -> bool {
122        self.0 & other.0 == other.0
123    }
124
125    /// Buttons held now that were not held in `previous`.
126    pub const fn pressed_since(self, previous: Buttons) -> Buttons {
127        Buttons(self.0 & !previous.0)
128    }
129
130    pub const fn trigger(self) -> bool {
131        self.contains(Buttons::TRIGGER)
132    }
133    pub const fn home(self) -> bool {
134        self.contains(Buttons::HOME)
135    }
136    pub const fn back(self) -> bool {
137        self.contains(Buttons::BACK)
138    }
139    pub const fn touchpad(self) -> bool {
140        self.contains(Buttons::TOUCHPAD)
141    }
142    pub const fn volume_up(self) -> bool {
143        self.contains(Buttons::VOLUME_UP)
144    }
145    pub const fn volume_down(self) -> bool {
146        self.contains(Buttons::VOLUME_DOWN)
147    }
148}
149
150impl BitOr for Buttons {
151    type Output = Buttons;
152    fn bitor(self, rhs: Buttons) -> Buttons {
153        Buttons(self.0 | rhs.0)
154    }
155}
156
157impl fmt::Debug for Buttons {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        let names = Buttons::ALL
160            .iter()
161            .filter(|(b, _)| self.contains(*b))
162            .map(|(_, name)| *name);
163        f.debug_set().entries(names).finish()
164    }
165}
166
167/// Where a finger is on the touchpad. Both axes run from 0 to [`TOUCH_MAX`];
168/// x grows to the right and y grows toward the handle.
169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
170pub struct Touch {
171    pub x: u16,
172    pub y: u16,
173}
174
175impl Touch {
176    /// Position with the pad centre at (0, 0) and the rim at distance 1.
177    /// x grows to the right, y grows toward the tip.
178    pub fn normalized(self) -> (f32, f32) {
179        let half = TOUCH_MAX as f32 / 2.0;
180        ((self.x as f32 - half) / half, (half - self.y as f32) / half)
181    }
182}
183
184/// One decoded data packet.
185#[derive(Clone, Copy, Debug, Default, PartialEq)]
186pub struct Packet {
187    /// Three consecutive motion samples, oldest first.
188    pub samples: [ImuSample; 3],
189    /// Magnetic field in µT (x, y, z), uncalibrated.
190    pub mag: [f32; 3],
191    /// Finger position, or `None` when the pad is not touched.
192    pub touch: Option<Touch>,
193    /// Temperature byte as sent; it appears to be in °C.
194    pub temperature: u8,
195    pub buttons: Buttons,
196}
197
198/// Why a packet could not be decoded.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub enum ParseError {
201    /// The packet is shorter than [`PACKET_LEN`]. The controller sends short packets when it
202    /// is not in sensor mode; sending [`Command::Sensor`] again restores full packets.
203    TooShort { len: usize },
204}
205
206impl fmt::Display for ParseError {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        match self {
209            ParseError::TooShort { len } => {
210                write!(f, "packet is {len} bytes, expected {PACKET_LEN}")
211            }
212        }
213    }
214}
215
216impl std::error::Error for ParseError {}
217
218/// Magnetometer byte offsets for x, y, z (the wire order is y, x, z).
219const MAG_OFFSETS: [usize; 3] = [50, 48, 52];
220
221impl Packet {
222    /// Decodes a notification from [`NOTIFY_UUID`].
223    pub fn parse(data: &[u8]) -> Result<Packet, ParseError> {
224        if data.len() < PACKET_LEN {
225            return Err(ParseError::TooShort { len: data.len() });
226        }
227        let i16_at = |o: usize| i16::from_le_bytes([data[o], data[o + 1]]) as f32;
228
229        let mut samples = [ImuSample::default(); 3];
230        for (i, sample) in samples.iter_mut().enumerate() {
231            let base = i * 16;
232            sample.timestamp_us =
233                u32::from_le_bytes([data[base], data[base + 1], data[base + 2], data[base + 3]]);
234            for k in 0..3 {
235                sample.accel[k] = i16_at(base + 4 + 2 * k) * ACCEL_SCALE;
236                sample.gyro[k] = i16_at(base + 10 + 2 * k) * GYRO_SCALE;
237            }
238        }
239
240        let x = ((data[54] as u16 & 0x0F) << 6) | ((data[55] as u16 & 0xFC) >> 2);
241        let y = ((data[55] as u16 & 0x03) << 8) | data[56] as u16;
242
243        Ok(Packet {
244            samples,
245            mag: MAG_OFFSETS.map(|o| i16_at(o) * MAG_SCALE),
246            touch: (x != 0 || y != 0).then_some(Touch { x, y }),
247            temperature: data[57],
248            buttons: Buttons::from_bits(data[58]),
249        })
250    }
251
252    /// Encodes the packet as the controller would send it. Useful for tests and simulation.
253    pub fn encode(&self) -> [u8; PACKET_LEN] {
254        let mut out = [0u8; PACKET_LEN];
255        let mut put = |o: usize, value: f32, scale: f32| {
256            let counts = (value / scale)
257                .round()
258                .clamp(i16::MIN as f32, i16::MAX as f32) as i16;
259            out[o..o + 2].copy_from_slice(&counts.to_le_bytes());
260        };
261        for (i, sample) in self.samples.iter().enumerate() {
262            let base = i * 16;
263            for k in 0..3 {
264                put(base + 4 + 2 * k, sample.accel[k], ACCEL_SCALE);
265                put(base + 10 + 2 * k, sample.gyro[k], GYRO_SCALE);
266            }
267        }
268        for (k, o) in MAG_OFFSETS.into_iter().enumerate() {
269            put(o, self.mag[k], MAG_SCALE);
270        }
271        for (i, sample) in self.samples.iter().enumerate() {
272            out[i * 16..i * 16 + 4].copy_from_slice(&sample.timestamp_us.to_le_bytes());
273        }
274        let (x, y) = self.touch.map_or((0, 0), |t| (t.x & 0x3FF, t.y & 0x3FF));
275        out[54] = ((x >> 6) & 0x0F) as u8;
276        out[55] = (((x & 0x3F) << 2) | ((y >> 8) & 0x03)) as u8;
277        out[56] = (y & 0xFF) as u8;
278        out[57] = self.temperature;
279        out[58] = if self.buttons.is_empty() {
280            1 << 6
281        } else {
282            self.buttons.bits()
283        };
284        out
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    /// A packet captured from a real controller, held in the hand with a finger on the pad.
293    const CAPTURED: [u8; 60] = [
294        0x33, 0x4d, 0x18, 0x03, 0x12, 0xfc, 0x4d, 0x06, 0x25, 0x04, 0x9a, 0x00, 0x3e, 0xff, 0xca,
295        0xfd, 0x3e, 0x60, 0x18, 0x03, 0x0c, 0xfc, 0x06, 0x06, 0x26, 0x04, 0x9e, 0x00, 0x36, 0xff,
296        0xbe, 0xfd, 0x30, 0x73, 0x18, 0x03, 0xf9, 0xfb, 0x03, 0x06, 0x49, 0x04, 0xa9, 0x00, 0x86,
297        0xff, 0xdf, 0xfd, 0xe0, 0x0b, 0xba, 0xf0, 0xf2, 0xfa, 0x14, 0x7c, 0xf6, 0x19, 0x40, 0x37,
298    ];
299
300    fn close(a: f32, b: f32, tolerance: f32) -> bool {
301        (a - b).abs() <= tolerance
302    }
303
304    #[test]
305    fn decodes_a_captured_packet() {
306        let p = Packet::parse(&CAPTURED).unwrap();
307
308        assert_eq!(p.samples[0].timestamp_us, 51_924_275);
309        assert_eq!(p.samples[1].timestamp_us - p.samples[0].timestamp_us, 4875);
310        assert_eq!(p.samples[2].timestamp_us - p.samples[1].timestamp_us, 4850);
311
312        let a = p.samples[0].accel;
313        assert!(close(a[0], -4.82, 0.01) && close(a[1], 7.72, 0.01) && close(a[2], 5.08, 0.01));
314        for sample in &p.samples {
315            let g = sample.accel.iter().map(|v| v * v).sum::<f32>().sqrt() / 9.80665;
316            assert!(
317                close(g, 1.0, 0.1),
318                "a hand-held controller reads about 1 g, got {g}"
319            );
320        }
321        let w = p.samples[0].gyro;
322        assert!(
323            close(w[0], 0.188, 0.001) && close(w[1], -0.237, 0.001) && close(w[2], -0.692, 0.001)
324        );
325
326        assert!(
327            close(p.mag[0], -234.6, 0.1)
328                && close(p.mag[1], 182.4, 0.1)
329                && close(p.mag[2], -77.6, 0.1)
330        );
331        assert_eq!(p.touch, Some(Touch { x: 287, y: 246 }));
332        assert_eq!(p.temperature, 25);
333        assert!(p.buttons.is_empty(), "bit 6 means no button, not a button");
334    }
335
336    #[test]
337    fn rejects_short_packets() {
338        assert_eq!(
339            Packet::parse(&CAPTURED[..59]),
340            Err(ParseError::TooShort { len: 59 })
341        );
342        assert_eq!(Packet::parse(&[]), Err(ParseError::TooShort { len: 0 }));
343    }
344
345    #[test]
346    fn encode_round_trips() {
347        let original = Packet::parse(&CAPTURED).unwrap();
348        let again = Packet::parse(&original.encode()).unwrap();
349        assert_eq!(original, again);
350
351        let mut p = original;
352        p.touch = None;
353        p.buttons = Buttons::TRIGGER | Buttons::VOLUME_DOWN;
354        let bytes = p.encode();
355        assert_eq!(bytes[58], 0b10_0001);
356        assert_eq!(Packet::parse(&bytes).unwrap(), p);
357    }
358
359    #[test]
360    fn touch_uses_the_full_range() {
361        let mut p = Packet::default();
362        for (x, y) in [(1, 0), (0, 1), (315, 315), (157, 300), (1023, 1023)] {
363            p.touch = Some(Touch { x, y });
364            assert_eq!(
365                Packet::parse(&p.encode()).unwrap().touch,
366                Some(Touch { x, y })
367            );
368        }
369        let (nx, ny) = Touch { x: 315, y: 0 }.normalized();
370        assert!(close(nx, 1.0, 1e-6) && close(ny, 1.0, 1e-6));
371    }
372
373    #[test]
374    fn buttons_report_presses() {
375        let held = Buttons::from_bits(0b0100_1001);
376        assert!(held.trigger() && held.touchpad() && !held.home());
377        assert_eq!(held.bits(), 0b1001);
378        assert_eq!(held.pressed_since(Buttons::TRIGGER), Buttons::TOUCHPAD);
379        assert_eq!(format!("{held:?}"), r#"{"Trigger", "Touchpad click"}"#);
380    }
381
382    #[test]
383    fn commands_have_the_documented_bytes() {
384        assert_eq!(Command::Off.bytes(), [0, 0]);
385        assert_eq!(Command::Sensor.bytes(), [1, 0]);
386        assert_eq!(Command::KeepAlive.bytes(), [4, 0]);
387    }
388}