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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Bluetooth LE transport, built on [btleplug](https://docs.rs/btleplug) and tokio.
//!
//! There are two ways in:
//!
//! - [`events`] is the easy one. It runs a background task that finds the controller,
//!   connects, keeps the data flowing and reconnects after the controller goes to sleep.
//! - [`Controller`] is the manual one: connect once and read packets yourself.
//!
//! ```no_run
//! use gearvr_controller::{ble, Orientation};
//!
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() {
//!     let mut orientation = Orientation::new();
//!     let mut events = ble::events();
//!     while let Some(event) = events.recv().await {
//!         match event {
//!             ble::Event::Packet(packet) => {
//!                 orientation.update(&packet);
//!                 let e = orientation.euler();
//!                 println!("yaw {:.0}°  buttons {:?}", e.yaw.to_degrees(), packet.buttons);
//!             }
//!             other => println!("{other:?}"),
//!         }
//!     }
//! }
//! ```
//!
//! # Things to know
//!
//! - The controller sleeps after about a minute without movement and drops the connection.
//!   Pressing any button wakes it; [`events`] then reconnects on its own.
//! - Only one program can hold the connection. If a phone or a browser tab is connected, the
//!   controller will not be found.
//! - On macOS the terminal (or app) running your program needs the Bluetooth permission:
//!   System Settings → Privacy & Security → Bluetooth.

use std::fmt;
use std::pin::Pin;
use std::time::Duration;

use btleplug::api::{
    Central, CharPropFlags, Characteristic, Manager as _, Peripheral as _,
    RetrievePeripheralsOptions, ScanFilter, WriteType,
};
use btleplug::platform::{Adapter, Manager, Peripheral};
use futures::{Stream, StreamExt};
use tokio::sync::mpsc;
use tokio::time::{self, Instant};
use uuid::Uuid;

use crate::protocol::{
    Command, Packet, ParseError, NAME_PREFIX, NOTIFY_UUID, SERVICE_UUID, WRITE_UUID,
};

/// Standard Bluetooth "Battery Level" characteristic.
const BATTERY_LEVEL_UUID: Uuid = Uuid::from_u128(0x00002a19_0000_1000_8000_00805f9b34fb);

/// What can go wrong talking to the controller.
#[derive(Debug)]
pub enum Error {
    /// This computer has no usable Bluetooth adapter.
    NoAdapter,
    /// No controller showed up before the timeout.
    NotFound,
    /// The device connected but does not expose the expected characteristic.
    MissingCharacteristic(&'static str),
    /// An error from the Bluetooth stack.
    Bluetooth(btleplug::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::NoAdapter => write!(f, "no Bluetooth adapter found"),
            Error::NotFound => write!(
                f,
                "no Gear VR Controller found; press a button on it to wake it"
            ),
            Error::MissingCharacteristic(which) => {
                write!(
                    f,
                    "the device has no {which} characteristic; is it a Gear VR Controller?"
                )
            }
            Error::Bluetooth(e) => write!(f, "Bluetooth error: {e}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Bluetooth(e) => Some(e),
            _ => None,
        }
    }
}

impl From<btleplug::Error> for Error {
    fn from(e: btleplug::Error) -> Error {
        Error::Bluetooth(e)
    }
}

/// A stream of decoded packets. Short packets (sent when the controller is not in sensor
/// mode) appear as errors.
pub type PacketStream = Pin<Box<dyn Stream<Item = Result<Packet, ParseError>> + Send>>;

/// A connected controller.
#[derive(Debug)]
pub struct Controller {
    // Keeps the Bluetooth backend alive for as long as the peripheral is in use.
    _adapter: Adapter,
    peripheral: Peripheral,
    name: String,
    notify: Characteristic,
    write: Characteristic,
}

impl Controller {
    /// Finds a controller and connects to it, waiting up to `timeout` for one to show up.
    ///
    /// The controller sends nothing until [`start`](Self::start) is called.
    pub async fn connect(timeout: Duration) -> Result<Controller, Error> {
        let adapter = default_adapter().await?;
        Controller::connect_on(&adapter, timeout).await
    }

    async fn connect_on(adapter: &Adapter, timeout: Duration) -> Result<Controller, Error> {
        let (peripheral, name) = find(adapter, timeout).await?;
        if !peripheral.is_connected().await? {
            peripheral.connect().await?;
        }
        peripheral.discover_services().await?;

        let characteristics = peripheral.characteristics();
        let lookup = |uuid: u128, which: &'static str| {
            let uuid = Uuid::from_u128(uuid);
            characteristics
                .iter()
                .find(|c| c.uuid == uuid)
                .cloned()
                .ok_or(Error::MissingCharacteristic(which))
        };
        let notify = lookup(NOTIFY_UUID, "data")?;
        let write = lookup(WRITE_UUID, "command")?;
        peripheral.subscribe(&notify).await?;

        Ok(Controller {
            _adapter: adapter.clone(),
            peripheral,
            name,
            notify,
            write,
        })
    }

    /// The controller's Bluetooth name, such as `Gear VR Controller(1A2B)`.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Sends a command.
    pub async fn send(&self, command: Command) -> Result<(), Error> {
        let kind = if self.write.properties.contains(CharPropFlags::WRITE) {
            WriteType::WithResponse
        } else {
            WriteType::WithoutResponse
        };
        self.peripheral
            .write(&self.write, &command.bytes(), kind)
            .await?;
        Ok(())
    }

    /// Asks the controller to start sending data packets.
    pub async fn start(&self) -> Result<(), Error> {
        self.send(Command::Sensor).await
    }

    /// Asks the controller to stop sending data packets.
    pub async fn stop(&self) -> Result<(), Error> {
        self.send(Command::Off).await
    }

    /// The packets the controller sends. The stream ends when the connection is lost on most
    /// platforms; check [`is_connected`](Self::is_connected) if it goes quiet.
    pub async fn packets(&self) -> Result<PacketStream, Error> {
        let uuid = self.notify.uuid;
        let notifications = self.peripheral.notifications().await?;
        Ok(Box::pin(notifications.filter_map(move |n| {
            std::future::ready((n.uuid == uuid).then(|| Packet::parse(&n.value)))
        })))
    }

    /// Battery charge in percent, if the controller reports it.
    pub async fn battery_level(&self) -> Result<Option<u8>, Error> {
        let Some(battery) = self
            .peripheral
            .characteristics()
            .into_iter()
            .find(|c| c.uuid == BATTERY_LEVEL_UUID)
        else {
            return Ok(None);
        };
        Ok(self.peripheral.read(&battery).await?.first().copied())
    }

    pub async fn is_connected(&self) -> bool {
        self.peripheral.is_connected().await.unwrap_or(false)
    }

    /// Stops the data and drops the connection.
    pub async fn disconnect(self) -> Result<(), Error> {
        let _ = self.stop().await;
        self.peripheral.disconnect().await?;
        Ok(())
    }
}

async fn default_adapter() -> Result<Adapter, Error> {
    let manager = Manager::new().await?;
    manager
        .adapters()
        .await?
        .into_iter()
        .next()
        .ok_or(Error::NoAdapter)
}

/// Longest device name passed on. Real controllers use about 24 characters.
const NAME_LIMIT: usize = 64;
/// Longest error message passed on.
const MESSAGE_LIMIT: usize = 200;

/// Text that came from outside this program, made safe to print: control characters are
/// dropped and the length is capped. Any nearby device can advertise any name, and a name
/// carrying terminal escape sequences could otherwise rewrite the screen of whoever prints it.
fn printable(text: &str, limit: usize) -> String {
    text.chars()
        .filter(|c| !c.is_control())
        .take(limit)
        .collect()
}

async fn name_of(peripheral: &Peripheral) -> Option<String> {
    let properties = peripheral.properties().await.ok()??;
    let name = properties.local_name.or(properties.advertisement_name)?;
    Some(printable(&name, NAME_LIMIT))
}

async fn find(adapter: &Adapter, timeout: Duration) -> Result<(Peripheral, String), Error> {
    // A controller this computer is already connected to does not advertise, so a scan would
    // miss it. Not every platform can list connected devices; ignore it when it can't.
    let connected = RetrievePeripheralsOptions {
        identifiers: None,
        services: Some(vec![Uuid::from_u128(SERVICE_UUID)]),
    };
    if let Ok(peripherals) = adapter.retrieve_peripherals(connected).await {
        if let Some(peripheral) = peripherals.into_iter().next() {
            let name = name_of(&peripheral)
                .await
                .unwrap_or_else(|| "Gear VR Controller".into());
            return Ok((peripheral, name));
        }
    }

    // Forget devices seen in earlier scans: one that has since gone to sleep is still listed.
    let _ = adapter.clear_peripherals().await;
    adapter.start_scan(ScanFilter::default()).await?;
    let deadline = Instant::now() + timeout;
    let found = 'scan: loop {
        for peripheral in adapter.peripherals().await? {
            if let Some(name) = name_of(&peripheral).await {
                if name.starts_with(NAME_PREFIX) {
                    break 'scan Some((peripheral, name));
                }
            }
        }
        if Instant::now() >= deadline {
            break None;
        }
        time::sleep(Duration::from_millis(200)).await;
    };
    let _ = adapter.stop_scan().await;
    found.ok_or(Error::NotFound)
}

pub use crate::event::Event;

/// How often the keep-alive command is sent.
const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(10);
/// With no data for this long, the sensor command is sent again.
const SILENCE: Duration = Duration::from_secs(3);
/// The sensor command is re-sent at most this often.
const RESTART_EVERY: Duration = Duration::from_secs(5);
/// Pause after an error before trying again.
const RETRY_AFTER: Duration = Duration::from_secs(3);
/// Length of one scan. Searching continues with a new scan when one finds nothing.
const SCAN_FOR: Duration = Duration::from_secs(20);

/// Starts a background task that finds the controller, streams its packets, and reconnects
/// whenever the connection drops. The task stops when the receiver is dropped.
///
/// Must be called from within a tokio runtime. If the receiver falls more than a few seconds
/// behind, the oldest unread packets are kept and new ones are dropped.
pub fn events() -> mpsc::Receiver<Event> {
    let (tx, rx) = mpsc::channel(256);
    tokio::spawn(supervise(tx));
    rx
}

async fn supervise(tx: mpsc::Sender<Event>) {
    let mut adapter: Option<Adapter> = None;
    let mut searching = false;
    let mut last_error = String::new();

    loop {
        if !searching {
            searching = true;
            if tx.send(Event::Searching).await.is_err() {
                return;
            }
        }

        let attempt = async {
            if adapter.is_none() {
                adapter = Some(default_adapter().await?);
            }
            Controller::connect_on(adapter.as_ref().expect("set above"), SCAN_FOR).await
        };
        let controller = tokio::select! {
            _ = tx.closed() => return,
            result = attempt => result,
        };
        let controller = match controller {
            Ok(controller) => controller,
            Err(Error::NotFound) => continue,
            Err(error) => {
                // Report a repeating error once, not on every retry.
                let message = printable(&error.to_string(), MESSAGE_LIMIT);
                if message != last_error {
                    last_error.clone_from(&message);
                    if tx.send(Event::Error(message)).await.is_err() {
                        return;
                    }
                }
                tokio::select! {
                    _ = tx.closed() => return,
                    _ = time::sleep(RETRY_AFTER) => {}
                }
                continue;
            }
        };
        last_error.clear();
        searching = false;

        let outcome = stream(&controller, &tx).await;
        let _ = controller.disconnect().await;
        match outcome {
            Ok(false) => return,
            Ok(true) => {}
            Err(error) => {
                let message = printable(&error.to_string(), MESSAGE_LIMIT);
                if tx.send(Event::Error(message)).await.is_err() {
                    return;
                }
            }
        }
        if tx.send(Event::Disconnected).await.is_err() {
            return;
        }
    }
}

/// Forwards packets until the connection drops (`Ok(true)`) or the receiver is gone (`Ok(false)`).
async fn stream(controller: &Controller, tx: &mpsc::Sender<Event>) -> Result<bool, Error> {
    let mut packets = controller.packets().await?;
    controller.start().await?;
    let battery = controller.battery_level().await.ok().flatten();
    if tx
        .send(Event::Connected {
            name: controller.name().to_owned(),
            battery,
        })
        .await
        .is_err()
    {
        return Ok(false);
    }

    let mut keep_alive = time::interval_at(Instant::now() + KEEP_ALIVE_EVERY, KEEP_ALIVE_EVERY);
    let mut watchdog = time::interval(Duration::from_secs(1));
    let mut last_packet = Instant::now();
    let mut last_start = Instant::now();

    loop {
        tokio::select! {
            item = packets.next() => match item {
                None => return Ok(true),
                Some(Ok(packet)) => {
                    last_packet = Instant::now();
                    match tx.try_send(Event::Packet(packet)) {
                        Err(mpsc::error::TrySendError::Closed(_)) => return Ok(false),
                        // A full queue means the receiver is far behind; newer data is dropped.
                        Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {}
                    }
                }
                // A short packet: the controller has left sensor mode.
                Some(Err(_)) => {
                    if last_start.elapsed() >= RESTART_EVERY {
                        last_start = Instant::now();
                        controller.start().await?;
                    }
                }
            },
            _ = keep_alive.tick() => {
                // A failed keep-alive is not fatal by itself; the watchdog notices a lost link.
                let _ = controller.send(Command::KeepAlive).await;
            }
            _ = watchdog.tick() => {
                if !controller.is_connected().await {
                    return Ok(true);
                }
                if last_packet.elapsed() >= SILENCE && last_start.elapsed() >= RESTART_EVERY {
                    last_start = Instant::now();
                    controller.start().await?;
                }
            }
            _ = tx.closed() => return Ok(false),
        }
    }
}

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

    #[test]
    fn names_from_other_devices_cannot_carry_terminal_commands() {
        // An escape sequence that clears the screen, a line break and a C1 control character.
        let hostile = "Gear VR\x1b[2J\x1b]0;title\x07 Controller\r\n(\u{9b}31mAB12)";
        assert_eq!(
            printable(hostile, NAME_LIMIT),
            "Gear VR[2J]0;title Controller(31mAB12)"
        );
        assert_eq!(
            printable("Gear VR Controller(AB12)", NAME_LIMIT),
            "Gear VR Controller(AB12)"
        );
    }

    #[test]
    fn long_names_are_cut() {
        let long = "Gear VR ".repeat(100);
        assert_eq!(printable(&long, NAME_LIMIT).chars().count(), NAME_LIMIT);
        // The limit counts characters, so a cut never lands inside one.
        assert_eq!(printable(&"é".repeat(100), 3), "ééé");
    }
}