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,
};
const BATTERY_LEVEL_UUID: Uuid = Uuid::from_u128(0x00002a19_0000_1000_8000_00805f9b34fb);
#[derive(Debug)]
pub enum Error {
NoAdapter,
NotFound,
MissingCharacteristic(&'static str),
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)
}
}
pub type PacketStream = Pin<Box<dyn Stream<Item = Result<Packet, ParseError>> + Send>>;
#[derive(Debug)]
pub struct Controller {
_adapter: Adapter,
peripheral: Peripheral,
name: String,
notify: Characteristic,
write: Characteristic,
}
impl Controller {
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(¬ify).await?;
Ok(Controller {
_adapter: adapter.clone(),
peripheral,
name,
notify,
write,
})
}
pub fn name(&self) -> &str {
&self.name
}
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(())
}
pub async fn start(&self) -> Result<(), Error> {
self.send(Command::Sensor).await
}
pub async fn stop(&self) -> Result<(), Error> {
self.send(Command::Off).await
}
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)))
})))
}
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)
}
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)
}
const NAME_LIMIT: usize = 64;
const MESSAGE_LIMIT: usize = 200;
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> {
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));
}
}
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;
const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(10);
const SILENCE: Duration = Duration::from_secs(3);
const RESTART_EVERY: Duration = Duration::from_secs(5);
const RETRY_AFTER: Duration = Duration::from_secs(3);
const SCAN_FOR: Duration = Duration::from_secs(20);
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) => {
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;
}
}
}
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),
Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {}
}
}
Some(Err(_)) => {
if last_start.elapsed() >= RESTART_EVERY {
last_start = Instant::now();
controller.start().await?;
}
}
},
_ = keep_alive.tick() => {
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() {
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);
assert_eq!(printable(&"é".repeat(100), 3), "ééé");
}
}