gearvr-controller 0.1.1

Read the Samsung Gear VR Controller (ET-YO324) over Bluetooth LE: packet decoding, orientation tracking and a btleplug transport
Documentation
//! The controller's Bluetooth LE wire format.
//!
//! The controller exposes one custom GATT service with two characteristics: one to write
//! two-byte [`Command`]s to, and one that notifies with 60-byte data packets once
//! [`Command::Sensor`] has been sent.
//!
//! | Bytes  | Content                                                              |
//! |--------|----------------------------------------------------------------------|
//! | 0–15   | Motion sample 1: `u32` time (µs), accel xyz, gyro xyz (`i16` each)   |
//! | 16–31  | Motion sample 2, same layout                                         |
//! | 32–47  | Motion sample 3, same layout                                         |
//! | 48–53  | Magnetometer, `i16` each, stored in y, x, z order                    |
//! | 54–56  | Touchpad position: two 10-bit values packed into 20 bits             |
//! | 57     | Temperature                                                          |
//! | 58     | Buttons, one bit each; bit 6 is set while nothing is pressed         |
//! | 59     | Unknown                                                              |
//!
//! All multi-byte values are little-endian.

use std::fmt;
use std::ops::BitOr;

/// The controller's custom GATT service.
pub const SERVICE_UUID: u128 = 0x4f63756c_7573_2054_6872_65656d6f7465;
/// Characteristic that notifies with data packets.
pub const NOTIFY_UUID: u128 = 0xc8c51726_81bc_483b_a052_f7a14ea3d281;
/// Characteristic that accepts [`Command`]s.
pub const WRITE_UUID: u128 = 0xc8c51726_81bc_483b_a052_f7a14ea3d282;
/// The advertised name starts with this, followed by a four-character id in brackets.
pub const NAME_PREFIX: &str = "Gear VR";

/// Length of a full data packet.
pub const PACKET_LEN: usize = 60;
/// Accelerometer scale: m/s² per count.
pub const ACCEL_SCALE: f32 = 9.80665 / 2048.0;
/// Gyroscope scale: rad/s per count.
pub const GYRO_SCALE: f32 = 0.017_453_292 / 14.285;
/// Magnetometer scale: µT per count.
pub const MAG_SCALE: f32 = 0.06;
/// Largest touchpad coordinate on either axis.
pub const TOUCH_MAX: u16 = 315;
/// Typical spacing of motion samples, in microseconds (about 206 samples per second).
pub const SAMPLE_INTERVAL_US: u32 = 4850;

/// A command written to the controller.
///
/// The controller also has a "VR mode" (`08 00`). It does not work when the controller is
/// driven from a computer, so it is not offered here.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Command {
    /// Stop sending data.
    Off,
    /// Start sending 60-byte data packets.
    Sensor,
    /// Keep-alive. It does not stop the controller sleeping when left untouched.
    KeepAlive,
}

impl Command {
    /// The two bytes to write to [`WRITE_UUID`].
    pub const fn bytes(self) -> [u8; 2] {
        match self {
            Command::Off => [0x00, 0x00],
            Command::Sensor => [0x01, 0x00],
            Command::KeepAlive => [0x04, 0x00],
        }
    }
}

/// One gyroscope and accelerometer reading. Each packet carries three.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ImuSample {
    /// The controller's clock in microseconds. Wraps about every 71.6 minutes.
    pub timestamp_us: u32,
    /// Acceleration in m/s², including gravity (about +9.8 on the axis pointing up).
    pub accel: [f32; 3],
    /// Angular velocity in rad/s, right-handed about each axis.
    pub gyro: [f32; 3],
}

/// The set of buttons held down.
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Buttons(u8);

impl Buttons {
    pub const NONE: Buttons = Buttons(0);
    pub const TRIGGER: Buttons = Buttons(1 << 0);
    pub const HOME: Buttons = Buttons(1 << 1);
    pub const BACK: Buttons = Buttons(1 << 2);
    /// The touchpad pressed down until it clicks (touching alone is reported by [`Packet::touch`]).
    pub const TOUCHPAD: Buttons = Buttons(1 << 3);
    pub const VOLUME_UP: Buttons = Buttons(1 << 4);
    pub const VOLUME_DOWN: Buttons = Buttons(1 << 5);

    /// Every button with its name, in a stable order.
    pub const ALL: [(Buttons, &'static str); 6] = [
        (Buttons::TRIGGER, "Trigger"),
        (Buttons::TOUCHPAD, "Touchpad click"),
        (Buttons::BACK, "Back"),
        (Buttons::HOME, "Home"),
        (Buttons::VOLUME_UP, "Volume up"),
        (Buttons::VOLUME_DOWN, "Volume down"),
    ];

    const MASK: u8 = 0b0011_1111;

    /// Builds a set from the packet's button byte, ignoring the non-button bits.
    pub const fn from_bits(bits: u8) -> Buttons {
        Buttons(bits & Buttons::MASK)
    }

    pub const fn bits(self) -> u8 {
        self.0
    }

    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// True if every button in `other` is held.
    pub const fn contains(self, other: Buttons) -> bool {
        self.0 & other.0 == other.0
    }

    /// Buttons held now that were not held in `previous`.
    pub const fn pressed_since(self, previous: Buttons) -> Buttons {
        Buttons(self.0 & !previous.0)
    }

    pub const fn trigger(self) -> bool {
        self.contains(Buttons::TRIGGER)
    }
    pub const fn home(self) -> bool {
        self.contains(Buttons::HOME)
    }
    pub const fn back(self) -> bool {
        self.contains(Buttons::BACK)
    }
    pub const fn touchpad(self) -> bool {
        self.contains(Buttons::TOUCHPAD)
    }
    pub const fn volume_up(self) -> bool {
        self.contains(Buttons::VOLUME_UP)
    }
    pub const fn volume_down(self) -> bool {
        self.contains(Buttons::VOLUME_DOWN)
    }
}

impl BitOr for Buttons {
    type Output = Buttons;
    fn bitor(self, rhs: Buttons) -> Buttons {
        Buttons(self.0 | rhs.0)
    }
}

impl fmt::Debug for Buttons {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let names = Buttons::ALL
            .iter()
            .filter(|(b, _)| self.contains(*b))
            .map(|(_, name)| *name);
        f.debug_set().entries(names).finish()
    }
}

/// Where a finger is on the touchpad. Both axes run from 0 to [`TOUCH_MAX`];
/// x grows to the right and y grows toward the handle.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Touch {
    pub x: u16,
    pub y: u16,
}

impl Touch {
    /// Position with the pad centre at (0, 0) and the rim at distance 1.
    /// x grows to the right, y grows toward the tip.
    pub fn normalized(self) -> (f32, f32) {
        let half = TOUCH_MAX as f32 / 2.0;
        ((self.x as f32 - half) / half, (half - self.y as f32) / half)
    }
}

/// One decoded data packet.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Packet {
    /// Three consecutive motion samples, oldest first.
    pub samples: [ImuSample; 3],
    /// Magnetic field in µT (x, y, z), uncalibrated.
    pub mag: [f32; 3],
    /// Finger position, or `None` when the pad is not touched.
    pub touch: Option<Touch>,
    /// Temperature byte as sent; it appears to be in °C.
    pub temperature: u8,
    pub buttons: Buttons,
}

/// Why a packet could not be decoded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParseError {
    /// The packet is shorter than [`PACKET_LEN`]. The controller sends short packets when it
    /// is not in sensor mode; sending [`Command::Sensor`] again restores full packets.
    TooShort { len: usize },
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::TooShort { len } => {
                write!(f, "packet is {len} bytes, expected {PACKET_LEN}")
            }
        }
    }
}

impl std::error::Error for ParseError {}

/// Magnetometer byte offsets for x, y, z (the wire order is y, x, z).
const MAG_OFFSETS: [usize; 3] = [50, 48, 52];

impl Packet {
    /// Decodes a notification from [`NOTIFY_UUID`].
    pub fn parse(data: &[u8]) -> Result<Packet, ParseError> {
        if data.len() < PACKET_LEN {
            return Err(ParseError::TooShort { len: data.len() });
        }
        let i16_at = |o: usize| i16::from_le_bytes([data[o], data[o + 1]]) as f32;

        let mut samples = [ImuSample::default(); 3];
        for (i, sample) in samples.iter_mut().enumerate() {
            let base = i * 16;
            sample.timestamp_us =
                u32::from_le_bytes([data[base], data[base + 1], data[base + 2], data[base + 3]]);
            for k in 0..3 {
                sample.accel[k] = i16_at(base + 4 + 2 * k) * ACCEL_SCALE;
                sample.gyro[k] = i16_at(base + 10 + 2 * k) * GYRO_SCALE;
            }
        }

        let x = ((data[54] as u16 & 0x0F) << 6) | ((data[55] as u16 & 0xFC) >> 2);
        let y = ((data[55] as u16 & 0x03) << 8) | data[56] as u16;

        Ok(Packet {
            samples,
            mag: MAG_OFFSETS.map(|o| i16_at(o) * MAG_SCALE),
            touch: (x != 0 || y != 0).then_some(Touch { x, y }),
            temperature: data[57],
            buttons: Buttons::from_bits(data[58]),
        })
    }

    /// Encodes the packet as the controller would send it. Useful for tests and simulation.
    pub fn encode(&self) -> [u8; PACKET_LEN] {
        let mut out = [0u8; PACKET_LEN];
        let mut put = |o: usize, value: f32, scale: f32| {
            let counts = (value / scale)
                .round()
                .clamp(i16::MIN as f32, i16::MAX as f32) as i16;
            out[o..o + 2].copy_from_slice(&counts.to_le_bytes());
        };
        for (i, sample) in self.samples.iter().enumerate() {
            let base = i * 16;
            for k in 0..3 {
                put(base + 4 + 2 * k, sample.accel[k], ACCEL_SCALE);
                put(base + 10 + 2 * k, sample.gyro[k], GYRO_SCALE);
            }
        }
        for (k, o) in MAG_OFFSETS.into_iter().enumerate() {
            put(o, self.mag[k], MAG_SCALE);
        }
        for (i, sample) in self.samples.iter().enumerate() {
            out[i * 16..i * 16 + 4].copy_from_slice(&sample.timestamp_us.to_le_bytes());
        }
        let (x, y) = self.touch.map_or((0, 0), |t| (t.x & 0x3FF, t.y & 0x3FF));
        out[54] = ((x >> 6) & 0x0F) as u8;
        out[55] = (((x & 0x3F) << 2) | ((y >> 8) & 0x03)) as u8;
        out[56] = (y & 0xFF) as u8;
        out[57] = self.temperature;
        out[58] = if self.buttons.is_empty() {
            1 << 6
        } else {
            self.buttons.bits()
        };
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A packet captured from a real controller, held in the hand with a finger on the pad.
    const CAPTURED: [u8; 60] = [
        0x33, 0x4d, 0x18, 0x03, 0x12, 0xfc, 0x4d, 0x06, 0x25, 0x04, 0x9a, 0x00, 0x3e, 0xff, 0xca,
        0xfd, 0x3e, 0x60, 0x18, 0x03, 0x0c, 0xfc, 0x06, 0x06, 0x26, 0x04, 0x9e, 0x00, 0x36, 0xff,
        0xbe, 0xfd, 0x30, 0x73, 0x18, 0x03, 0xf9, 0xfb, 0x03, 0x06, 0x49, 0x04, 0xa9, 0x00, 0x86,
        0xff, 0xdf, 0xfd, 0xe0, 0x0b, 0xba, 0xf0, 0xf2, 0xfa, 0x14, 0x7c, 0xf6, 0x19, 0x40, 0x37,
    ];

    fn close(a: f32, b: f32, tolerance: f32) -> bool {
        (a - b).abs() <= tolerance
    }

    #[test]
    fn decodes_a_captured_packet() {
        let p = Packet::parse(&CAPTURED).unwrap();

        assert_eq!(p.samples[0].timestamp_us, 51_924_275);
        assert_eq!(p.samples[1].timestamp_us - p.samples[0].timestamp_us, 4875);
        assert_eq!(p.samples[2].timestamp_us - p.samples[1].timestamp_us, 4850);

        let a = p.samples[0].accel;
        assert!(close(a[0], -4.82, 0.01) && close(a[1], 7.72, 0.01) && close(a[2], 5.08, 0.01));
        for sample in &p.samples {
            let g = sample.accel.iter().map(|v| v * v).sum::<f32>().sqrt() / 9.80665;
            assert!(
                close(g, 1.0, 0.1),
                "a hand-held controller reads about 1 g, got {g}"
            );
        }
        let w = p.samples[0].gyro;
        assert!(
            close(w[0], 0.188, 0.001) && close(w[1], -0.237, 0.001) && close(w[2], -0.692, 0.001)
        );

        assert!(
            close(p.mag[0], -234.6, 0.1)
                && close(p.mag[1], 182.4, 0.1)
                && close(p.mag[2], -77.6, 0.1)
        );
        assert_eq!(p.touch, Some(Touch { x: 287, y: 246 }));
        assert_eq!(p.temperature, 25);
        assert!(p.buttons.is_empty(), "bit 6 means no button, not a button");
    }

    #[test]
    fn rejects_short_packets() {
        assert_eq!(
            Packet::parse(&CAPTURED[..59]),
            Err(ParseError::TooShort { len: 59 })
        );
        assert_eq!(Packet::parse(&[]), Err(ParseError::TooShort { len: 0 }));
    }

    #[test]
    fn encode_round_trips() {
        let original = Packet::parse(&CAPTURED).unwrap();
        let again = Packet::parse(&original.encode()).unwrap();
        assert_eq!(original, again);

        let mut p = original;
        p.touch = None;
        p.buttons = Buttons::TRIGGER | Buttons::VOLUME_DOWN;
        let bytes = p.encode();
        assert_eq!(bytes[58], 0b10_0001);
        assert_eq!(Packet::parse(&bytes).unwrap(), p);
    }

    #[test]
    fn touch_uses_the_full_range() {
        let mut p = Packet::default();
        for (x, y) in [(1, 0), (0, 1), (315, 315), (157, 300), (1023, 1023)] {
            p.touch = Some(Touch { x, y });
            assert_eq!(
                Packet::parse(&p.encode()).unwrap().touch,
                Some(Touch { x, y })
            );
        }
        let (nx, ny) = Touch { x: 315, y: 0 }.normalized();
        assert!(close(nx, 1.0, 1e-6) && close(ny, 1.0, 1e-6));
    }

    #[test]
    fn buttons_report_presses() {
        let held = Buttons::from_bits(0b0100_1001);
        assert!(held.trigger() && held.touchpad() && !held.home());
        assert_eq!(held.bits(), 0b1001);
        assert_eq!(held.pressed_since(Buttons::TRIGGER), Buttons::TOUCHPAD);
        assert_eq!(format!("{held:?}"), r#"{"Trigger", "Touchpad click"}"#);
    }

    #[test]
    fn commands_have_the_documented_bytes() {
        assert_eq!(Command::Off.bytes(), [0, 0]);
        assert_eq!(Command::Sensor.bytes(), [1, 0]);
        assert_eq!(Command::KeepAlive.bytes(), [4, 0]);
    }
}