gearvr-controller 0.1.2

Read the Samsung Gear VR Controller (ET-YO324) over Bluetooth LE: packet decoding, orientation tracking and a btleplug transport
Documentation
//! A simulated controller, for developing and testing without the hardware.
//!
//! [`Simulator`] produces the same 60-byte packets a real controller sends: the controller
//! sways through a repeating motion while a finger circles the touchpad and each button is
//! pressed in turn.

use std::f64::consts::PI;
use std::time::Duration;

use crate::orientation::{Euler, Quat};
use crate::protocol::{
    Buttons, ImuSample, Packet, Touch, PACKET_LEN, SAMPLE_INTERVAL_US, TOUCH_MAX,
};

const GRAVITY: f32 = 9.80665;
/// A plausible magnetic field in the world frame (µT): pointing north and down.
const FIELD: [f32; 3] = [0.0, 20.0, -44.0];
/// Length of the scripted touch and button sequence, in seconds. It matches the period of
/// the yaw motion, so Home (which applications use to recenter) is pressed at yaw 0.
const CYCLE: f64 = 4.0 * PI;

/// Generates packets from a simulated controller.
#[derive(Clone, Debug, Default)]
pub struct Simulator {
    sample_index: u64,
}

impl Simulator {
    /// Time covered by one packet (three samples). Send packets this far apart for real-time playback.
    pub const PACKET_INTERVAL: Duration = Duration::from_micros(3 * SAMPLE_INTERVAL_US as u64);
    /// The name the simulated controller reports.
    pub const NAME: &'static str = "Simulated controller";

    pub fn new() -> Simulator {
        Simulator::default()
    }

    /// Seconds of simulated time produced so far.
    pub fn elapsed(&self) -> f64 {
        time_of(self.sample_index)
    }

    /// The simulated controller's true orientation `t` seconds in.
    pub fn pose_at(t: f64) -> Quat {
        Quat::from_euler(angles(t).0)
    }

    /// The next packet, as raw bytes.
    pub fn next_bytes(&mut self) -> [u8; PACKET_LEN] {
        let mut samples = [ImuSample::default(); 3];
        for sample in &mut samples {
            *sample = sample_at(self.sample_index);
            self.sample_index += 1;
        }
        let t = time_of(self.sample_index - 1);
        let (touch, buttons) = inputs(t % CYCLE);
        let to_body = Simulator::pose_at(t).conjugate();
        Packet {
            samples,
            mag: to_body.rotate(FIELD),
            touch,
            temperature: 25,
            buttons,
        }
        .encode()
    }

    /// The next packet, decoded. Values are quantized exactly as a real controller's are.
    pub fn next_packet(&mut self) -> Packet {
        Packet::parse(&self.next_bytes()).expect("simulated packets are full length")
    }
}

fn time_of(sample_index: u64) -> f64 {
    sample_index as f64 * SAMPLE_INTERVAL_US as f64 * 1e-6
}

/// Heading, pitch and roll at time `t`, and their rates of change.
fn angles(t: f64) -> (Euler, Euler) {
    let angle = Euler {
        yaw: (0.9 * (0.5 * t).sin()) as f32,
        pitch: (0.5 * (0.8 * t).sin() + 0.15) as f32,
        roll: (0.6 * (1.1 * t).sin()) as f32,
    };
    let rate = Euler {
        yaw: (0.45 * (0.5 * t).cos()) as f32,
        pitch: (0.4 * (0.8 * t).cos()) as f32,
        roll: (0.66 * (1.1 * t).cos()) as f32,
    };
    (angle, rate)
}

fn sample_at(index: u64) -> ImuSample {
    let t = time_of(index);
    let (angle, rate) = angles(t);
    let (sp, cp) = angle.pitch.sin_cos();
    let (sr, cr) = angle.roll.sin_cos();
    // Angular velocity in the controller's frame for the yaw-pitch-roll (z, x, y) sequence.
    let gyro = [
        -sr * cp * rate.yaw + cr * rate.pitch,
        sp * rate.yaw + rate.roll,
        cr * cp * rate.yaw + sr * rate.pitch,
    ];
    let accel = Quat::from_euler(angle)
        .conjugate()
        .rotate([0.0, 0.0, GRAVITY]);
    ImuSample {
        // The device clock is 32 bits of microseconds and wraps.
        timestamp_us: (1_000_000 + index * SAMPLE_INTERVAL_US as u64) as u32,
        accel,
        gyro,
    }
}

/// Touch position and buttons `c` seconds into the scripted cycle.
fn inputs(c: f64) -> (Option<Touch>, Buttons) {
    let touch = (2.0..6.0).contains(&c).then(|| {
        let half = TOUCH_MAX as f64 / 2.0;
        let a = (c - 2.0) * 1.8;
        Touch {
            x: (half + 110.0 * a.cos()).round() as u16,
            y: (half + 110.0 * a.sin()).round() as u16,
        }
    });
    let script = [
        (0.0..0.3, Buttons::HOME),
        (4.5..4.9, Buttons::TOUCHPAD),
        (6.8..7.6, Buttons::TRIGGER),
        (8.4..8.8, Buttons::BACK),
        (9.6..10.0, Buttons::VOLUME_UP),
        (10.6..11.0, Buttons::VOLUME_DOWN),
    ];
    let buttons = script
        .into_iter()
        .filter(|(range, _)| range.contains(&c))
        .fold(Buttons::NONE, |held, (_, button)| held | button);
    (touch, buttons)
}

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

    #[test]
    fn packets_look_like_real_ones() {
        let mut sim = Simulator::new();
        let mut last = None;
        for _ in 0..200 {
            let p = sim.next_packet();
            for s in &p.samples {
                if let Some(last) = last {
                    assert_eq!(s.timestamp_us - last, SAMPLE_INTERVAL_US);
                }
                last = Some(s.timestamp_us);
                let g = s.accel.iter().map(|v| v * v).sum::<f32>().sqrt() / GRAVITY;
                assert!((g - 1.0).abs() < 0.01, "accelerometer reads {g} g");
            }
            assert_eq!(p.temperature, 25);
        }
    }

    #[test]
    fn the_filter_tracks_the_simulated_motion() {
        let mut sim = Simulator::new();
        let mut orientation = Orientation::new();
        let mut worst = 0.0f32;
        // Two full motion cycles.
        while sim.elapsed() < 25.0 {
            orientation.update(&sim.next_packet());
            if sim.elapsed() > 1.5 {
                let truth = Simulator::pose_at(sim.elapsed() - time_of(1));
                worst = worst.max(orientation.quaternion().angle_to(truth));
            }
        }
        assert!(
            worst.to_degrees() < 3.0,
            "worst error {:.2}°",
            worst.to_degrees()
        );
    }

    #[test]
    fn every_button_and_the_touchpad_are_exercised() {
        let mut sim = Simulator::new();
        let mut seen = Buttons::NONE;
        let (mut touched, mut untouched) = (false, false);
        let mut first = None;
        while sim.elapsed() < CYCLE {
            let p = sim.next_packet();
            first.get_or_insert(p.buttons);
            seen = seen | p.buttons;
            match p.touch {
                Some(t) => {
                    touched = true;
                    assert!(t.x <= TOUCH_MAX && t.y <= TOUCH_MAX);
                }
                None => untouched = true,
            }
        }
        assert_eq!(seen.bits(), 0b11_1111);
        assert!(touched && untouched);
        assert_eq!(
            first,
            Some(Buttons::HOME),
            "Home is pressed at the start, where yaw is 0"
        );
    }
}