use std::fmt;
use std::ops::BitOr;
pub const SERVICE_UUID: u128 = 0x4f63756c_7573_2054_6872_65656d6f7465;
pub const NOTIFY_UUID: u128 = 0xc8c51726_81bc_483b_a052_f7a14ea3d281;
pub const WRITE_UUID: u128 = 0xc8c51726_81bc_483b_a052_f7a14ea3d282;
pub const NAME_PREFIX: &str = "Gear VR";
pub const PACKET_LEN: usize = 60;
pub const ACCEL_SCALE: f32 = 9.80665 / 2048.0;
pub const GYRO_SCALE: f32 = 0.017_453_292 / 14.285;
pub const MAG_SCALE: f32 = 0.06;
pub const TOUCH_MAX: u16 = 315;
pub const SAMPLE_INTERVAL_US: u32 = 4850;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Command {
Off,
Sensor,
KeepAlive,
}
impl Command {
pub const fn bytes(self) -> [u8; 2] {
match self {
Command::Off => [0x00, 0x00],
Command::Sensor => [0x01, 0x00],
Command::KeepAlive => [0x04, 0x00],
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ImuSample {
pub timestamp_us: u32,
pub accel: [f32; 3],
pub gyro: [f32; 3],
}
#[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);
pub const TOUCHPAD: Buttons = Buttons(1 << 3);
pub const VOLUME_UP: Buttons = Buttons(1 << 4);
pub const VOLUME_DOWN: Buttons = Buttons(1 << 5);
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;
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
}
pub const fn contains(self, other: Buttons) -> bool {
self.0 & other.0 == other.0
}
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()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Touch {
pub x: u16,
pub y: u16,
}
impl Touch {
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)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Packet {
pub samples: [ImuSample; 3],
pub mag: [f32; 3],
pub touch: Option<Touch>,
pub temperature: u8,
pub buttons: Buttons,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParseError {
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 {}
const MAG_OFFSETS: [usize; 3] = [50, 48, 52];
impl Packet {
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]),
})
}
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::*;
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]);
}
}