#![warn(missing_docs)]
pub use webbluetooth_core::{
adapter, backlog, blocklist, chooser, error, filter, grants, timer, uuid,
};
use webbluetooth_core::{address, restoration, scan};
#[cfg(l2cap)]
pub mod l2cap;
#[cfg(peripheral_role)]
pub mod peripheral;
#[cfg(target_os = "android")]
use webbluetooth_android::backend;
#[cfg(target_vendor = "apple")]
use webbluetooth_apple::backend;
#[cfg(all(target_os = "linux", not(feature = "linux-hci")))]
use webbluetooth_linux::backend;
#[cfg(all(target_os = "linux", feature = "linux-hci"))]
use webbluetooth_linux::backend_hci as backend;
#[cfg(target_arch = "wasm32")]
use webbluetooth_wasm::backend;
#[cfg(target_os = "windows")]
use webbluetooth_windows::backend;
mod device;
mod gatt;
mod session;
use std::sync::Arc;
pub use adapter::{
AdapterInfo, ConnectionParameters, ConnectionPhy, ConnectionPriority, Pairing, Phy,
};
pub use chooser::{Candidate, Candidates, DeviceChooser};
pub use device::{BluetoothDevice, DisconnectEvents};
pub use error::{Authorization, Availability, Error, Result};
pub use filter::{Advertisement, DataPrefix, DeviceFilter, RequestDeviceOptions};
pub use gatt::{
CharacteristicProperties, Notifications, RemoteGattCharacteristic, RemoteGattDescriptor,
RemoteGattServer, RemoteGattService, Tagged, WriteType,
};
pub mod stream {
pub use futures_core::Stream;
pub use futures_util::stream::{select_all, BoxStream, SelectAll};
pub use futures_util::StreamExt;
}
pub mod future {
pub use futures_util::future::{join, select, BoxFuture, Either};
}
#[cfg(l2cap)]
pub use l2cap::{L2capChannel, Psm};
pub use webbluetooth_core::registry::Grant;
#[cfg(not(l2cap))]
pub type Psm = u16;
pub const L2CAP: bool = cfg!(l2cap);
#[cfg(target_os = "android")]
pub mod android {
pub use crate::backend::init;
pub use webbluetooth_android::jni::{JObject, Vm};
}
#[cfg(peripheral_role)]
pub use peripheral::Peripheral;
pub use restoration::Restoration;
pub use timer::{sleep, timeout};
pub mod prelude {
pub use crate::chooser::{BoxFuture, Candidate, Candidates, DeviceChooser};
pub use crate::uuid::{BluetoothUuid, IntoUuid};
pub use crate::{
Availability, Bluetooth, BluetoothDevice, DataPrefix, DeviceFilter, Grant, LeScanOptions,
RequestDeviceOptions,
};
pub use crate::{
RemoteGattCharacteristic, RemoteGattDescriptor, RemoteGattServer, RemoteGattService,
};
pub use futures_core::Stream;
pub use futures_util::StreamExt;
}
pub use uuid::{BluetoothUuid, IntoUuid};
use backend::Inner;
#[derive(Clone)]
pub struct Bluetooth {
inner: Arc<session::Session>,
chooser: Arc<dyn DeviceChooser>,
}
impl Bluetooth {
pub fn new() -> Self {
Self::with_chooser(chooser::FirstMatch::default())
}
pub fn shared() -> Self {
static SHARED: std::sync::OnceLock<Bluetooth> = std::sync::OnceLock::new();
SHARED.get_or_init(Self::new).clone()
}
pub fn with_chooser(chooser: impl DeviceChooser) -> Self {
Self {
inner: session::Session::new(Inner::new(false), None),
chooser: Arc::new(chooser),
}
}
pub fn with_grants(store: grants::GrantStore, chooser: impl DeviceChooser) -> Self {
Self {
inner: session::Session::new(Inner::new(false), Some(Arc::new(store))),
chooser: Arc::new(chooser),
}
}
pub fn remembered_grant(&self, id: &str) -> Option<Grant> {
let store = self.inner.grants.as_ref()?;
store.load().get(id).map(|stored| stored.grant.clone())
}
pub fn remembered_devices(&self) -> Vec<String> {
let mut ids = self.inner.granted_devices();
if let Some(store) = &self.inner.grants {
for id in store.load().into_keys() {
if !ids.contains(&id) {
ids.push(id);
}
}
}
ids.sort();
ids
}
pub fn with_restoration(restoration: Restoration, chooser: impl DeviceChooser) -> Self {
Self {
inner: session::Session::new(
Inner::with_restoration(
false,
Some(&restoration.identifier),
restoration.allowed_services.into_iter().collect(),
),
None,
),
chooser: Arc::new(chooser),
}
}
pub async fn restored_session(&self) -> Option<RestoredSession> {
let _ = self.inner.settled_state().await;
let restored = self.inner.restored()?;
Some(RestoredSession {
devices: restored
.device_ids
.into_iter()
.map(|id| BluetoothDevice {
inner: self.inner.clone(),
id,
})
.collect(),
scan_services: restored.scan_services,
scan_allow_duplicates: restored.scan_allow_duplicates,
})
}
pub fn with_power_alert(chooser: impl DeviceChooser) -> Self {
Self {
inner: session::Session::new(Inner::new(true), None),
chooser: Arc::new(chooser),
}
}
pub async fn get_availability(&self) -> bool {
self.availability().await.is_ok()
}
pub async fn availability(&self) -> std::result::Result<(), Availability> {
match self.inner.require_powered_on().await {
Ok(()) => Ok(()),
Err(Error::NotAvailable(a)) => Err(a),
Err(_) => Err(Availability::Unknown),
}
}
pub async fn adapters(&self) -> Result<Vec<AdapterInfo>> {
self.inner.adapters().await
}
pub async fn adapter(&self) -> Result<AdapterInfo> {
self.inner.adapter().await
}
pub async fn select_adapter(&self, id: &str) -> Result<()> {
self.inner.select_adapter(id).await
}
pub async fn adopt_device(&self, id: &str, grant: impl Into<Grant>) -> Result<BluetoothDevice> {
let mut grant = grant.into();
grant.validate()?;
if let Some(store) = &self.inner.grants {
if let Some(stored) = store.load().get(id) {
grant = stored.grant.union(&grant);
}
}
let id = self.inner.backend().adopt_device(id, grant).await?;
self.inner.persist_grants();
Ok(BluetoothDevice {
inner: self.inner.clone(),
id,
})
}
pub async fn adopt_candidate(
&self,
candidate: &Candidate,
grant: impl Into<Grant>,
) -> Result<BluetoothDevice> {
self.adopt_device(&candidate.id, grant).await
}
pub async fn request_device(&self, options: RequestDeviceOptions) -> Result<BluetoothDevice> {
self.request_device_with(options, self.chooser.as_ref())
.await
}
pub async fn request_device_with(
&self,
options: RequestDeviceOptions,
chooser: &dyn DeviceChooser,
) -> Result<BluetoothDevice> {
let id = self
.inner
.backend()
.request_device(options, chooser)
.await?;
self.inner.persist_grants();
Ok(BluetoothDevice {
inner: self.inner.clone(),
id,
})
}
pub async fn request_le_scan(&self, options: LeScanOptions) -> Result<LeScan> {
options.validate()?;
self.inner.require_powered_on().await?;
let (watcher, stream, restart) = self.inner.scan_hub().add(scan::Want::Scan {
options: options.as_request(),
keep_repeated: options.keep_repeated_devices,
});
if restart {
if let Err(e) = self.inner.backend().set_radio_scanning(true) {
self.inner.scan_hub().remove(watcher);
return Err(e);
}
}
Ok(LeScan {
inner: self.inner.clone(),
watcher,
stream,
options,
})
}
pub fn watch_availability(&self) -> AvailabilityEvents {
const INTERVAL: std::time::Duration = std::time::Duration::from_millis(750);
let (tx, rx) = futures_channel::mpsc::unbounded();
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let inner = self.inner.clone();
let flag = stop.clone();
std::thread::Builder::new()
.name("webbluetooth-availability".into())
.spawn(move || {
let mut last: Option<std::result::Result<(), Availability>> = None;
while !flag.load(std::sync::atomic::Ordering::Acquire) {
let now = inner.state().availability();
if last.as_ref() != Some(&now) {
last = Some(now);
if tx.unbounded_send(now).is_err() {
return;
}
}
std::thread::sleep(INTERVAL);
}
})
.ok();
AvailabilityEvents { rx, stop }
}
pub fn get_devices(&self) -> Vec<BluetoothDevice> {
self.inner
.granted_devices()
.into_iter()
.map(|id| BluetoothDevice {
inner: self.inner.clone(),
id,
})
.collect()
}
}
impl Default for Bluetooth {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for Bluetooth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Bluetooth")
.field("state", &self.inner.state())
.field("granted_devices", &self.inner.granted_devices().len())
.finish()
}
}
#[derive(Debug)]
pub struct RestoredSession {
pub devices: Vec<BluetoothDevice>,
pub scan_services: Vec<BluetoothUuid>,
pub scan_allow_duplicates: bool,
}
pub const PERIPHERAL_ROLE: bool = cfg!(peripheral_role);
pub fn authorization() -> Authorization {
backend::authorization()
}
pub type AdvertisementEvent = chooser::Candidate;
#[derive(Debug, Clone, Default)]
pub struct LeScanOptions {
filters: Vec<DeviceFilter>,
keep_repeated_devices: bool,
accept_all_advertisements: bool,
}
impl LeScanOptions {
pub fn new() -> Self {
Self::default()
}
pub fn accept_all_advertisements() -> Self {
Self {
accept_all_advertisements: true,
..Self::default()
}
}
pub fn filter(mut self, filter: DeviceFilter) -> Self {
self.filters.push(filter);
self
}
pub fn filters(mut self, filters: impl IntoIterator<Item = DeviceFilter>) -> Self {
self.filters.extend(filters);
self
}
pub fn keep_repeated_devices(mut self, keep: bool) -> Self {
self.keep_repeated_devices = keep;
self
}
pub fn validate(&self) -> Result<()> {
match (self.accept_all_advertisements, self.filters.is_empty()) {
(true, false) => {
return Err(Error::InvalidModification(
"accept_all_advertisements() and filter() are mutually exclusive".into(),
))
}
(false, true) => {
return Err(Error::InvalidModification(
"provide at least one filter(), or call accept_all_advertisements()".into(),
))
}
_ => {}
}
self.as_request().validate()
}
fn as_request(&self) -> RequestDeviceOptions {
let mut request = RequestDeviceOptions::new();
if self.accept_all_advertisements {
request = request.accept_all_devices();
}
for filter in &self.filters {
request = request.filter(filter.clone());
}
request
}
}
pub struct LeScan {
inner: Arc<crate::session::Session>,
watcher: u64,
stream: crate::backlog::Receiver<AdvertisementEvent>,
options: LeScanOptions,
}
impl LeScan {
pub fn is_active(&self) -> bool {
self.inner.scan_hub().contains(self.watcher)
}
pub fn keep_repeated_devices(&self) -> bool {
self.options.keep_repeated_devices
}
pub fn accept_all_advertisements(&self) -> bool {
self.options.accept_all_advertisements
}
pub fn filters(&self) -> &[DeviceFilter] {
&self.options.filters
}
pub fn stop(self) {}
}
impl futures_core::Stream for LeScan {
type Item = AdvertisementEvent;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<AdvertisementEvent>> {
std::pin::Pin::new(&mut self.stream).poll_next(cx)
}
}
impl Drop for LeScan {
fn drop(&mut self) {
if self.inner.scan_hub().remove(self.watcher) {
let _ = self.inner.backend().set_radio_scanning(false);
}
}
}
impl std::fmt::Debug for LeScan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LeScan")
.field("active", &self.is_active())
.field("keep_repeated_devices", &self.keep_repeated_devices())
.field(
"accept_all_advertisements",
&self.accept_all_advertisements(),
)
.finish()
}
}
pub struct Advertisements {
inner: Arc<crate::session::Session>,
watcher: u64,
stream: crate::backlog::Receiver<AdvertisementEvent>,
device_id: String,
}
impl Advertisements {
pub fn lost(&self) -> u64 {
self.stream.lost()
}
pub fn is_watching(&self) -> bool {
self.inner.scan_hub().contains(self.watcher)
}
pub fn device_id(&self) -> &str {
&self.device_id
}
pub fn stop(self) {}
}
impl futures_core::Stream for Advertisements {
type Item = AdvertisementEvent;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<AdvertisementEvent>> {
std::pin::Pin::new(&mut self.stream).poll_next(cx)
}
}
impl Drop for Advertisements {
fn drop(&mut self) {
if self.inner.scan_hub().remove(self.watcher) {
let _ = self.inner.backend().set_radio_scanning(false);
}
#[cfg(target_arch = "wasm32")]
{
let inner = self.inner.clone();
let id = self.device_id.clone();
webbluetooth_wasm::spawn(async move {
let _ = inner.watch_advertisements(&id, false).await;
});
}
}
}
impl std::fmt::Debug for Advertisements {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Advertisements")
.field("device", &self.device_id)
.field("watching", &self.is_watching())
.finish()
}
}
pub struct ServiceEvents {
pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<()>,
}
impl futures_core::Stream for ServiceEvents {
type Item = ();
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<()>> {
std::pin::Pin::new(&mut self.rx).poll_next(cx)
}
}
impl std::fmt::Debug for ServiceEvents {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ServiceEvents")
}
}
pub struct AvailabilityEvents {
rx: futures_channel::mpsc::UnboundedReceiver<std::result::Result<(), Availability>>,
stop: Arc<std::sync::atomic::AtomicBool>,
}
impl futures_core::Stream for AvailabilityEvents {
type Item = std::result::Result<(), Availability>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
std::pin::Pin::new(&mut self.rx).poll_next(cx)
}
}
impl Drop for AvailabilityEvents {
fn drop(&mut self) {
self.stop.store(true, std::sync::atomic::Ordering::Release);
}
}
impl std::fmt::Debug for AvailabilityEvents {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("AvailabilityEvents")
}
}