Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add implementation for WebBluetooth #204

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,27 @@ libc = "0.2.119"
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.33.0", features = ["Devices_Bluetooth", "Devices_Bluetooth_GenericAttributeProfile", "Devices_Bluetooth_Advertisement", "Devices_Radios", "Foundation_Collections", "Foundation", "Storage_Streams"] }

[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3.56"
wasm-bindgen = "0.2.79"
wasm-bindgen-futures = "0.4.29"

[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
version = "0.3.56"
features = [
'Bluetooth',
'BluetoothCharacteristicProperties',
'BluetoothDevice',
'BluetoothLeScanFilterInit',
'BluetoothRemoteGattCharacteristic',
'BluetoothRemoteGattServer',
'BluetoothRemoteGattService',
'Event',
'Navigator',
'RequestDeviceOptions',
'Window',
]

[dev-dependencies]
rand = "0.8.5"
pretty_env_logger = "0.4.0"
Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ mod corebluetooth;
pub mod platform;
#[cfg(feature = "serde")]
pub mod serde;
#[cfg(target_arch = "wasm32")]
mod wasm;
#[cfg(target_os = "windows")]
mod winrtble;

Expand Down Expand Up @@ -132,6 +134,9 @@ pub enum Error {
#[error("Invalid Bluetooth address: {0}")]
InvalidBDAddr(#[from] ParseBDAddrError),

#[error("JavaScript {:?}", _0)]
JavaScript(String),

#[error("{}", _0)]
Other(Box<dyn std::error::Error + Send + Sync>),
}
Expand Down
4 changes: 4 additions & 0 deletions src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ pub use crate::bluez::{
pub use crate::corebluetooth::{
adapter::Adapter, manager::Manager, peripheral::Peripheral, peripheral::PeripheralId,
};
#[cfg(target_arch = "wasm32")]
pub use crate::wasm::{
adapter::Adapter, manager::Manager, peripheral::Peripheral, peripheral::PeripheralId,
};
#[cfg(target_os = "windows")]
pub use crate::winrtble::{
adapter::Adapter, manager::Manager, peripheral::Peripheral, peripheral::PeripheralId,
Expand Down
151 changes: 151 additions & 0 deletions src/wasm/adapter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
use super::peripheral::{Peripheral, PeripheralId};
use super::utils::wrap_promise;
use crate::api::{BDAddr, Central, CentralEvent, Peripheral as _, ScanFilter};
use crate::common::adapter_manager::AdapterManager;
use crate::{Error, Result};
use async_trait::async_trait;
use futures::channel::oneshot;
use futures::stream::Stream;
use js_sys::Array;
use std::pin::Pin;
use std::sync::Arc;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::spawn_local;
use web_sys::{BluetoothDevice, BluetoothLeScanFilterInit, RequestDeviceOptions};

macro_rules! spawn_local {
($a:expr) => {{
let (sender, receiver) = oneshot::channel();
spawn_local(async move {
let _ = sender.send($a);
});
receiver.await.unwrap()
}};
}

/// Implementation of [api::Central](crate::api::Central).
#[derive(Clone, Debug)]
pub struct Adapter {
manager: Arc<AdapterManager<Peripheral>>,
}

fn bluetooth() -> Option<web_sys::Bluetooth> {
web_sys::window().unwrap().navigator().bluetooth()
}

#[async_trait]
trait AddPeripheralAndEmit {
async fn add_inital_periperals(&self) -> Vec<PeripheralId>;
fn add_device(&self, device: JsValue) -> Option<PeripheralId>;
}

#[async_trait]
impl AddPeripheralAndEmit for Arc<AdapterManager<Peripheral>> {
async fn add_inital_periperals(&self) -> Vec<PeripheralId> {
if !self.peripherals().is_empty() {
return vec![];
}

let self_clone = self.clone();
spawn_local!({
wrap_promise::<Array>(bluetooth().unwrap().get_devices())
.await
.map_or(vec![], |devices| {
devices
.iter()
.map(|device| self_clone.add_device(device).unwrap())
.collect()
})
})
}

fn add_device(&self, device: JsValue) -> Option<PeripheralId> {
let p = Peripheral::new(Arc::downgrade(self), BluetoothDevice::from(device));
let id = p.id();
if self.peripheral(&id).is_none() {
self.add_peripheral(p);
Some(id)
} else {
None
}
}
}

impl Adapter {
pub(crate) fn try_new() -> Option<Self> {
if let Some(_) = bluetooth() {
Some(Self {
manager: Arc::new(AdapterManager::default()),
})
} else {
None
}
}
}

#[async_trait]
impl Central for Adapter {
type Peripheral = Peripheral;

async fn events(&self) -> Result<Pin<Box<dyn Stream<Item = CentralEvent> + Send>>> {
Ok(self.manager.event_stream())
}

async fn start_scan(&self, filter: ScanFilter) -> Result<()> {
let manager = self.manager.clone();
spawn_local!({
for id in manager.add_inital_periperals().await {
manager.emit(CentralEvent::DeviceDiscovered(id));
}

let mut options = RequestDeviceOptions::new();
let optional_services = Array::new();
let filters = Array::new();

for uuid in filter.services.iter() {
let mut filter = BluetoothLeScanFilterInit::new();
let filter_services = Array::new();
filter_services.push(&uuid.to_string().into());
filter.services(&filter_services.into());
filters.push(&filter.into());
optional_services.push(&uuid.to_string().into());
}

options.filters(&filters.into());
options.optional_services(&optional_services.into());

wrap_promise(bluetooth().unwrap().request_device(&options))
.await
.map(|device| {
if let Some(id) = manager.add_device(device) {
manager.emit(CentralEvent::DeviceDiscovered(id));
}
()
})
})
}

async fn stop_scan(&self) -> Result<()> {
Ok(())
}

async fn peripherals(&self) -> Result<Vec<Peripheral>> {
self.manager.add_inital_periperals().await;
Ok(self.manager.peripherals())
}

async fn peripheral(&self, id: &PeripheralId) -> Result<Peripheral> {
self.manager.add_inital_periperals().await;
self.manager.peripheral(id).ok_or(Error::DeviceNotFound)
}

async fn add_peripheral(&self, _address: BDAddr) -> Result<Peripheral> {
Err(Error::NotSupported(
"Can't add a Peripheral from a BDAddr".to_string(),
))
}

async fn adapter_info(&self) -> Result<String> {
Ok("WebBluetooth".to_string())
}
}
26 changes: 26 additions & 0 deletions src/wasm/manager.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use super::adapter::Adapter;
use crate::{api, Result};
use async_trait::async_trait;

/// Implementation of [api::Manager](crate::api::Manager).
#[derive(Clone, Debug)]
pub struct Manager {}

impl Manager {
pub async fn new() -> Result<Self> {
Ok(Self {})
}
}

#[async_trait]
impl api::Manager for Manager {
type Adapter = Adapter;

async fn adapters(&self) -> Result<Vec<Adapter>> {
if let Some(adapter) = Adapter::try_new() {
Ok(vec![adapter])
} else {
Ok(vec![])
}
}
}
4 changes: 4 additions & 0 deletions src/wasm/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod adapter;
pub mod manager;
pub mod peripheral;
mod utils;
Loading