Skip to main content

gearvr_controller/
ble.rs

1//! Bluetooth LE transport, built on [btleplug](https://docs.rs/btleplug) and tokio.
2//!
3//! There are two ways in:
4//!
5//! - [`events`] is the easy one. It runs a background task that finds the controller,
6//!   connects, keeps the data flowing and reconnects after the controller goes to sleep.
7//! - [`Controller`] is the manual one: connect once and read packets yourself.
8//!
9//! ```no_run
10//! use gearvr_controller::{ble, Orientation};
11//!
12//! #[tokio::main(flavor = "current_thread")]
13//! async fn main() {
14//!     let mut orientation = Orientation::new();
15//!     let mut events = ble::events();
16//!     while let Some(event) = events.recv().await {
17//!         match event {
18//!             ble::Event::Packet(packet) => {
19//!                 orientation.update(&packet);
20//!                 let e = orientation.euler();
21//!                 println!("yaw {:.0}°  buttons {:?}", e.yaw.to_degrees(), packet.buttons);
22//!             }
23//!             other => println!("{other:?}"),
24//!         }
25//!     }
26//! }
27//! ```
28//!
29//! # Things to know
30//!
31//! - The controller sleeps after about a minute without movement and drops the connection.
32//!   Pressing any button wakes it; [`events`] then reconnects on its own.
33//! - Only one program can hold the connection. If a phone or a browser tab is connected, the
34//!   controller will not be found.
35//! - On macOS the terminal (or app) running your program needs the Bluetooth permission:
36//!   System Settings → Privacy & Security → Bluetooth.
37
38use std::fmt;
39use std::pin::Pin;
40use std::time::Duration;
41
42use btleplug::api::{
43    Central, CharPropFlags, Characteristic, Manager as _, Peripheral as _,
44    RetrievePeripheralsOptions, ScanFilter, WriteType,
45};
46use btleplug::platform::{Adapter, Manager, Peripheral};
47use futures::{Stream, StreamExt};
48use tokio::sync::mpsc;
49use tokio::time::{self, Instant};
50use uuid::Uuid;
51
52use crate::protocol::{
53    Command, Packet, ParseError, NAME_PREFIX, NOTIFY_UUID, SERVICE_UUID, WRITE_UUID,
54};
55
56/// Standard Bluetooth "Battery Level" characteristic.
57const BATTERY_LEVEL_UUID: Uuid = Uuid::from_u128(0x00002a19_0000_1000_8000_00805f9b34fb);
58
59/// What can go wrong talking to the controller.
60#[derive(Debug)]
61pub enum Error {
62    /// This computer has no usable Bluetooth adapter.
63    NoAdapter,
64    /// No controller showed up before the timeout.
65    NotFound,
66    /// The device connected but does not expose the expected characteristic.
67    MissingCharacteristic(&'static str),
68    /// An error from the Bluetooth stack.
69    Bluetooth(btleplug::Error),
70}
71
72impl fmt::Display for Error {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match self {
75            Error::NoAdapter => write!(f, "no Bluetooth adapter found"),
76            Error::NotFound => write!(
77                f,
78                "no Gear VR Controller found; press a button on it to wake it"
79            ),
80            Error::MissingCharacteristic(which) => {
81                write!(
82                    f,
83                    "the device has no {which} characteristic; is it a Gear VR Controller?"
84                )
85            }
86            Error::Bluetooth(e) => write!(f, "Bluetooth error: {e}"),
87        }
88    }
89}
90
91impl std::error::Error for Error {
92    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
93        match self {
94            Error::Bluetooth(e) => Some(e),
95            _ => None,
96        }
97    }
98}
99
100impl From<btleplug::Error> for Error {
101    fn from(e: btleplug::Error) -> Error {
102        Error::Bluetooth(e)
103    }
104}
105
106/// A stream of decoded packets. Short packets (sent when the controller is not in sensor
107/// mode) appear as errors.
108pub type PacketStream = Pin<Box<dyn Stream<Item = Result<Packet, ParseError>> + Send>>;
109
110/// A connected controller.
111#[derive(Debug)]
112pub struct Controller {
113    // Keeps the Bluetooth backend alive for as long as the peripheral is in use.
114    _adapter: Adapter,
115    peripheral: Peripheral,
116    name: String,
117    notify: Characteristic,
118    write: Characteristic,
119}
120
121impl Controller {
122    /// Finds a controller and connects to it, waiting up to `timeout` for one to show up.
123    ///
124    /// The controller sends nothing until [`start`](Self::start) is called.
125    pub async fn connect(timeout: Duration) -> Result<Controller, Error> {
126        let adapter = default_adapter().await?;
127        Controller::connect_on(&adapter, timeout).await
128    }
129
130    async fn connect_on(adapter: &Adapter, timeout: Duration) -> Result<Controller, Error> {
131        let (peripheral, name) = find(adapter, timeout).await?;
132        if !peripheral.is_connected().await? {
133            peripheral.connect().await?;
134        }
135        peripheral.discover_services().await?;
136
137        let characteristics = peripheral.characteristics();
138        let lookup = |uuid: u128, which: &'static str| {
139            let uuid = Uuid::from_u128(uuid);
140            characteristics
141                .iter()
142                .find(|c| c.uuid == uuid)
143                .cloned()
144                .ok_or(Error::MissingCharacteristic(which))
145        };
146        let notify = lookup(NOTIFY_UUID, "data")?;
147        let write = lookup(WRITE_UUID, "command")?;
148        peripheral.subscribe(&notify).await?;
149
150        Ok(Controller {
151            _adapter: adapter.clone(),
152            peripheral,
153            name,
154            notify,
155            write,
156        })
157    }
158
159    /// The controller's Bluetooth name, such as `Gear VR Controller(1A2B)`.
160    pub fn name(&self) -> &str {
161        &self.name
162    }
163
164    /// Sends a command.
165    pub async fn send(&self, command: Command) -> Result<(), Error> {
166        let kind = if self.write.properties.contains(CharPropFlags::WRITE) {
167            WriteType::WithResponse
168        } else {
169            WriteType::WithoutResponse
170        };
171        self.peripheral
172            .write(&self.write, &command.bytes(), kind)
173            .await?;
174        Ok(())
175    }
176
177    /// Asks the controller to start sending data packets.
178    pub async fn start(&self) -> Result<(), Error> {
179        self.send(Command::Sensor).await
180    }
181
182    /// Asks the controller to stop sending data packets.
183    pub async fn stop(&self) -> Result<(), Error> {
184        self.send(Command::Off).await
185    }
186
187    /// The packets the controller sends. The stream ends when the connection is lost on most
188    /// platforms; check [`is_connected`](Self::is_connected) if it goes quiet.
189    pub async fn packets(&self) -> Result<PacketStream, Error> {
190        let uuid = self.notify.uuid;
191        let notifications = self.peripheral.notifications().await?;
192        Ok(Box::pin(notifications.filter_map(move |n| {
193            std::future::ready((n.uuid == uuid).then(|| Packet::parse(&n.value)))
194        })))
195    }
196
197    /// Battery charge in percent, if the controller reports it.
198    pub async fn battery_level(&self) -> Result<Option<u8>, Error> {
199        let Some(battery) = self
200            .peripheral
201            .characteristics()
202            .into_iter()
203            .find(|c| c.uuid == BATTERY_LEVEL_UUID)
204        else {
205            return Ok(None);
206        };
207        Ok(self.peripheral.read(&battery).await?.first().copied())
208    }
209
210    pub async fn is_connected(&self) -> bool {
211        self.peripheral.is_connected().await.unwrap_or(false)
212    }
213
214    /// Stops the data and drops the connection.
215    pub async fn disconnect(self) -> Result<(), Error> {
216        let _ = self.stop().await;
217        self.peripheral.disconnect().await?;
218        Ok(())
219    }
220}
221
222async fn default_adapter() -> Result<Adapter, Error> {
223    let manager = Manager::new().await?;
224    manager
225        .adapters()
226        .await?
227        .into_iter()
228        .next()
229        .ok_or(Error::NoAdapter)
230}
231
232/// Longest device name passed on. Real controllers use about 24 characters.
233const NAME_LIMIT: usize = 64;
234/// Longest error message passed on.
235const MESSAGE_LIMIT: usize = 200;
236
237/// Text that came from outside this program, made safe to print: control characters are
238/// dropped and the length is capped. Any nearby device can advertise any name, and a name
239/// carrying terminal escape sequences could otherwise rewrite the screen of whoever prints it.
240fn printable(text: &str, limit: usize) -> String {
241    text.chars()
242        .filter(|c| !c.is_control())
243        .take(limit)
244        .collect()
245}
246
247async fn name_of(peripheral: &Peripheral) -> Option<String> {
248    let properties = peripheral.properties().await.ok()??;
249    let name = properties.local_name.or(properties.advertisement_name)?;
250    Some(printable(&name, NAME_LIMIT))
251}
252
253async fn find(adapter: &Adapter, timeout: Duration) -> Result<(Peripheral, String), Error> {
254    // A controller this computer is already connected to does not advertise, so a scan would
255    // miss it. Not every platform can list connected devices; ignore it when it can't.
256    let connected = RetrievePeripheralsOptions {
257        identifiers: None,
258        services: Some(vec![Uuid::from_u128(SERVICE_UUID)]),
259    };
260    if let Ok(peripherals) = adapter.retrieve_peripherals(connected).await {
261        if let Some(peripheral) = peripherals.into_iter().next() {
262            let name = name_of(&peripheral)
263                .await
264                .unwrap_or_else(|| "Gear VR Controller".into());
265            return Ok((peripheral, name));
266        }
267    }
268
269    // Forget devices seen in earlier scans: one that has since gone to sleep is still listed.
270    let _ = adapter.clear_peripherals().await;
271    adapter.start_scan(ScanFilter::default()).await?;
272    let deadline = Instant::now() + timeout;
273    let found = 'scan: loop {
274        for peripheral in adapter.peripherals().await? {
275            if let Some(name) = name_of(&peripheral).await {
276                if name.starts_with(NAME_PREFIX) {
277                    break 'scan Some((peripheral, name));
278                }
279            }
280        }
281        if Instant::now() >= deadline {
282            break None;
283        }
284        time::sleep(Duration::from_millis(200)).await;
285    };
286    let _ = adapter.stop_scan().await;
287    found.ok_or(Error::NotFound)
288}
289
290pub use crate::event::Event;
291
292/// How often the keep-alive command is sent.
293const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(10);
294/// With no data for this long, the sensor command is sent again.
295const SILENCE: Duration = Duration::from_secs(3);
296/// The sensor command is re-sent at most this often.
297const RESTART_EVERY: Duration = Duration::from_secs(5);
298/// Pause after an error before trying again.
299const RETRY_AFTER: Duration = Duration::from_secs(3);
300/// Length of one scan. Searching continues with a new scan when one finds nothing.
301const SCAN_FOR: Duration = Duration::from_secs(20);
302
303/// Starts a background task that finds the controller, streams its packets, and reconnects
304/// whenever the connection drops. The task stops when the receiver is dropped.
305///
306/// Must be called from within a tokio runtime. If the receiver falls more than a few seconds
307/// behind, the oldest unread packets are kept and new ones are dropped.
308pub fn events() -> mpsc::Receiver<Event> {
309    let (tx, rx) = mpsc::channel(256);
310    tokio::spawn(supervise(tx));
311    rx
312}
313
314async fn supervise(tx: mpsc::Sender<Event>) {
315    let mut adapter: Option<Adapter> = None;
316    let mut searching = false;
317    let mut last_error = String::new();
318
319    loop {
320        if !searching {
321            searching = true;
322            if tx.send(Event::Searching).await.is_err() {
323                return;
324            }
325        }
326
327        let attempt = async {
328            if adapter.is_none() {
329                adapter = Some(default_adapter().await?);
330            }
331            Controller::connect_on(adapter.as_ref().expect("set above"), SCAN_FOR).await
332        };
333        let controller = tokio::select! {
334            _ = tx.closed() => return,
335            result = attempt => result,
336        };
337        let controller = match controller {
338            Ok(controller) => controller,
339            Err(Error::NotFound) => continue,
340            Err(error) => {
341                // Report a repeating error once, not on every retry.
342                let message = printable(&error.to_string(), MESSAGE_LIMIT);
343                if message != last_error {
344                    last_error.clone_from(&message);
345                    if tx.send(Event::Error(message)).await.is_err() {
346                        return;
347                    }
348                }
349                tokio::select! {
350                    _ = tx.closed() => return,
351                    _ = time::sleep(RETRY_AFTER) => {}
352                }
353                continue;
354            }
355        };
356        last_error.clear();
357        searching = false;
358
359        let outcome = stream(&controller, &tx).await;
360        let _ = controller.disconnect().await;
361        match outcome {
362            Ok(false) => return,
363            Ok(true) => {}
364            Err(error) => {
365                let message = printable(&error.to_string(), MESSAGE_LIMIT);
366                if tx.send(Event::Error(message)).await.is_err() {
367                    return;
368                }
369            }
370        }
371        if tx.send(Event::Disconnected).await.is_err() {
372            return;
373        }
374    }
375}
376
377/// Forwards packets until the connection drops (`Ok(true)`) or the receiver is gone (`Ok(false)`).
378async fn stream(controller: &Controller, tx: &mpsc::Sender<Event>) -> Result<bool, Error> {
379    let mut packets = controller.packets().await?;
380    controller.start().await?;
381    let battery = controller.battery_level().await.ok().flatten();
382    if tx
383        .send(Event::Connected {
384            name: controller.name().to_owned(),
385            battery,
386        })
387        .await
388        .is_err()
389    {
390        return Ok(false);
391    }
392
393    let mut keep_alive = time::interval_at(Instant::now() + KEEP_ALIVE_EVERY, KEEP_ALIVE_EVERY);
394    let mut watchdog = time::interval(Duration::from_secs(1));
395    let mut last_packet = Instant::now();
396    let mut last_start = Instant::now();
397
398    loop {
399        tokio::select! {
400            item = packets.next() => match item {
401                None => return Ok(true),
402                Some(Ok(packet)) => {
403                    last_packet = Instant::now();
404                    match tx.try_send(Event::Packet(packet)) {
405                        Err(mpsc::error::TrySendError::Closed(_)) => return Ok(false),
406                        // A full queue means the receiver is far behind; newer data is dropped.
407                        Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {}
408                    }
409                }
410                // A short packet: the controller has left sensor mode.
411                Some(Err(_)) => {
412                    if last_start.elapsed() >= RESTART_EVERY {
413                        last_start = Instant::now();
414                        controller.start().await?;
415                    }
416                }
417            },
418            _ = keep_alive.tick() => {
419                // A failed keep-alive is not fatal by itself; the watchdog notices a lost link.
420                let _ = controller.send(Command::KeepAlive).await;
421            }
422            _ = watchdog.tick() => {
423                if !controller.is_connected().await {
424                    return Ok(true);
425                }
426                if last_packet.elapsed() >= SILENCE && last_start.elapsed() >= RESTART_EVERY {
427                    last_start = Instant::now();
428                    controller.start().await?;
429                }
430            }
431            _ = tx.closed() => return Ok(false),
432        }
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    #[test]
441    fn names_from_other_devices_cannot_carry_terminal_commands() {
442        // An escape sequence that clears the screen, a line break and a C1 control character.
443        let hostile = "Gear VR\x1b[2J\x1b]0;title\x07 Controller\r\n(\u{9b}31mAB12)";
444        assert_eq!(
445            printable(hostile, NAME_LIMIT),
446            "Gear VR[2J]0;title Controller(31mAB12)"
447        );
448        assert_eq!(
449            printable("Gear VR Controller(AB12)", NAME_LIMIT),
450            "Gear VR Controller(AB12)"
451        );
452    }
453
454    #[test]
455    fn long_names_are_cut() {
456        let long = "Gear VR ".repeat(100);
457        assert_eq!(printable(&long, NAME_LIMIT).chars().count(), NAME_LIMIT);
458        // The limit counts characters, so a cut never lands inside one.
459        assert_eq!(printable(&"é".repeat(100), 3), "ééé");
460    }
461}