1use 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
56const BATTERY_LEVEL_UUID: Uuid = Uuid::from_u128(0x00002a19_0000_1000_8000_00805f9b34fb);
58
59#[derive(Debug)]
61pub enum Error {
62 NoAdapter,
64 NotFound,
66 MissingCharacteristic(&'static str),
68 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
106pub type PacketStream = Pin<Box<dyn Stream<Item = Result<Packet, ParseError>> + Send>>;
109
110#[derive(Debug)]
112pub struct Controller {
113 _adapter: Adapter,
115 peripheral: Peripheral,
116 name: String,
117 notify: Characteristic,
118 write: Characteristic,
119}
120
121impl Controller {
122 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(¬ify).await?;
149
150 Ok(Controller {
151 _adapter: adapter.clone(),
152 peripheral,
153 name,
154 notify,
155 write,
156 })
157 }
158
159 pub fn name(&self) -> &str {
161 &self.name
162 }
163
164 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 pub async fn start(&self) -> Result<(), Error> {
179 self.send(Command::Sensor).await
180 }
181
182 pub async fn stop(&self) -> Result<(), Error> {
184 self.send(Command::Off).await
185 }
186
187 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 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 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
232const NAME_LIMIT: usize = 64;
234const MESSAGE_LIMIT: usize = 200;
236
237fn 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 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 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
292const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(10);
294const SILENCE: Duration = Duration::from_secs(3);
296const RESTART_EVERY: Duration = Duration::from_secs(5);
298const RETRY_AFTER: Duration = Duration::from_secs(3);
300const SCAN_FOR: Duration = Duration::from_secs(20);
302
303pub 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 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
377async 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 Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {}
408 }
409 }
410 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 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 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 assert_eq!(printable(&"é".repeat(100), 3), "ééé");
460 }
461}