#![warn(missing_docs)]
pub use webbluetooth_core::{
adapter, backlog, blocklist, chooser, error, filter, grants, timer, uuid,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
negotiate_a2dp, negotiate_sbc_parameters, A2dpCapability, A2dpCodec, A2dpConfiguration,
A2dpNegotiationError, SbcAllocation, SbcChannelMode, SbcConfiguration,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
parse_obex_header, DunState, ObexError, ObexHeader, ObexOperation, ObexPacket, PanRole,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{PanControlMessage, PanError, PanFrame, PanPacketType};
use webbluetooth_core::{address, restoration, scan};
#[cfg(all(
feature = "classic-l2cap",
any(target_os = "linux", target_os = "android")
))]
pub mod classic_l2cap;
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub mod classic_l2cap_windows;
#[cfg(l2cap)]
pub mod l2cap;
#[cfg(peripheral_role)]
pub mod peripheral;
#[cfg(all(
target_os = "linux",
any(feature = "raw-acl", feature = "raw-sco", feature = "le-audio")
))]
pub mod raw_hci;
#[cfg(feature = "rfcomm")]
pub mod rfcomm;
#[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;
#[cfg(not(target_arch = "wasm32"))]
mod run_loop;
#[cfg(not(target_arch = "wasm32"))]
pub use run_loop::run_with_main_run_loop;
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,
};
#[cfg(all(
target_os = "linux",
any(feature = "raw-acl", feature = "raw-sco", feature = "le-audio")
))]
pub use raw_hci::RawHciSocket;
#[cfg(feature = "classic")]
pub use webbluetooth_core::classic::{
BluetoothAddress, ClassOfDevice, ClassicAddressError, ClassicPsm, ClassicSecurity,
RfcommChannel as ClassicRfcommChannel,
};
#[cfg(feature = "classic")]
pub use webbluetooth_core::sdp::{SdpDataElement, SdpError, SdpServiceRecord};
#[cfg(feature = "raw-acl")]
pub use webbluetooth_core::AclPacket;
#[cfg(any(
all(feature = "classic", any(target_os = "windows", target_os = "android", all(target_os = "linux", not(feature = "linux-hci")))),
all(feature = "apple-classic", target_os = "macos")
))]
pub use webbluetooth_core::ClassicDevice;
#[cfg(feature = "le-audio")]
pub use webbluetooth_core::IsoPacket;
#[cfg(feature = "raw-sco")]
pub use webbluetooth_core::ScoPacket;
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
absolute_volume, negotiate_sbc_capabilities, playback_status, AvrcpCommand, AvrcpEvent,
AvrcpMetadata, AvrcpPassThrough, PlaybackStatus,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
encode_command, AtError, AtLine, AtParser, CallCommand, CallInfo, CallState,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
AvdtpCapabilitiesError, AvdtpDiscoverError, AvdtpEndpointType, AvdtpError, AvdtpMediaType,
AvdtpMessageType, AvdtpPacketType, AvdtpResponse, AvdtpResponseResult, AvdtpSbcCapability,
AvdtpServiceCategory, AvdtpSignalIdentifier, AvdtpSignalingPacket,
AvdtpStreamEndpointDescriptor, AvdtpStreamEndpointId,
};
#[cfg(feature = "le-audio")]
pub use webbluetooth_core::{
CodecError, IsoConfiguration, IsoMetadata, IsoStream, Lc3Codec, Lc3Frame,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
HidError, HidPacket, InputValue, ReportDescriptor, ReportField, TransactionType,
};
#[cfg(feature = "mesh")]
pub use webbluetooth_core::{
MeshAddress, MeshNetworkPdu, NetworkHeader, ProvisioningEvent, ProvisioningFailure,
ProvisioningSession, ProvisioningState,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{Profile, ProfileRequest, ProfileRole};
pub use webbluetooth_core::{Protocol, ProtocolCapabilities};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{SbcFrame, SbcMediaError, SbcMediaPacket};
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(feature = "public")]
pub mod public {
pub use crate::stream::{Stream, StreamExt};
pub use crate::uuid::{BluetoothUuid, IntoUuid};
pub use crate::{
Availability, Bluetooth, BluetoothDevice, DataPrefix, DeviceFilter, Error, Grant,
LeScanOptions, Notifications, RemoteGattCharacteristic, RemoteGattDescriptor,
RemoteGattServer, RemoteGattService, RequestDeviceOptions, Result, Tagged,
};
}
#[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);
pub const CLASSIC: bool = cfg!(feature = "classic");
pub const RFCOMM: bool = cfg!(feature = "rfcomm");
pub const PROFILES: bool = cfg!(feature = "profiles");
pub const MESH: bool = cfg!(feature = "mesh");
pub const RAW_ACL: bool = cfg!(feature = "raw-acl");
pub const RAW_SCO: bool = cfg!(feature = "raw-sco");
pub const LE_AUDIO: bool = cfg!(feature = "le-audio");
pub const APPLE_CLASSIC: bool = cfg!(all(feature = "apple-classic", target_os = "macos"));
#[cfg(target_os = "android")]
pub mod android {
pub use crate::backend::init;
pub use webbluetooth_android::jni::{JObject, Vm};
}
#[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
pub use classic_l2cap::ClassicL2capChannel;
#[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
pub use classic_l2cap::ClassicL2capListener;
#[cfg(all(feature = "classic-l2cap", target_os = "android"))]
pub use classic_l2cap::{ClassicL2capChannel, ClassicL2capListener};
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub use classic_l2cap_windows::ClassicL2capChannel;
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub use classic_l2cap_windows::ClassicL2capListener;
#[cfg(peripheral_role)]
pub use peripheral::Peripheral;
pub use restoration::Restoration;
#[cfg(all(
feature = "rfcomm",
any(
target_os = "linux",
target_os = "android",
target_os = "windows",
target_os = "macos"
)
))]
pub use rfcomm::RfcommChannel;
#[cfg(all(feature = "rfcomm", target_os = "linux"))]
pub use rfcomm::RfcommListener;
#[cfg(all(feature = "rfcomm", target_os = "android"))]
pub use rfcomm::RfcommListener;
#[cfg(all(feature = "rfcomm", target_os = "windows"))]
pub use rfcomm::RfcommListener;
pub use timer::{sleep, timeout};
#[cfg(all(feature = "profiles", feature = "classic-l2cap", target_os = "linux"))]
pub use webbluetooth_linux::a2dp::A2dpSession;
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 {
#[cfg(all(feature = "rfcomm", target_os = "linux", not(feature = "linux-hci")))]
pub async fn query_sdp(
&self,
address: &str,
service: BluetoothUuid,
) -> Result<Vec<SdpServiceRecord>> {
webbluetooth_linux::sdp::query(address, service).map_err(Error::Network)
}
#[cfg(all(feature = "apple-classic", target_os = "macos"))]
pub async fn paired_classic_devices(&self) -> Result<Vec<ClassicDevice>> {
webbluetooth_apple::classic::paired_devices()
}
#[cfg(all(feature = "rfcomm", target_os = "macos"))]
pub async fn open_rfcomm_channel(&self, address: &str, channel: u8) -> Result<RfcommChannel> {
rfcomm::open_macos_address(address, channel).await
}
#[cfg(all(feature = "rfcomm", target_os = "linux"))]
pub async fn open_rfcomm_channel(&self, address: &str, channel: u8) -> Result<RfcommChannel> {
rfcomm::open(address, channel)
}
#[cfg(all(feature = "rfcomm", target_os = "windows"))]
pub async fn open_rfcomm_channel(&self, address: &str, channel: u8) -> Result<RfcommChannel> {
rfcomm::open_windows(address, channel)
}
#[cfg(any(
all(feature = "apple-classic", target_os = "macos"),
all(feature = "classic", any(target_os = "windows", target_os = "android", all(target_os = "linux", not(feature = "linux-hci"))))
))]
pub async fn paired_devices(&self) -> Result<Vec<ClassicDevice>> {
#[cfg(target_os = "macos")]
{
self.paired_classic_devices().await
}
#[cfg(target_os = "windows")]
{
Ok(self.classic_devices().await?.into_iter().filter(|d| d.bonded).collect())
}
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let mut out: Vec<ClassicDevice> = Vec::new();
for a in self.bonded_classic_devices().await? {
let address = a.parse().ok();
if address.is_some() && out.iter().any(|d| d.address == address) {
continue;
}
out.push(ClassicDevice { address, name: None, class_of_device: None, bonded: true, authenticated: false, connected: false });
}
Ok(out)
}
}
#[cfg(all(feature = "classic", target_os = "windows"))]
pub async fn classic_devices(&self) -> Result<Vec<ClassicDevice>> {
self.inner.backend().classic_devices().await
}
#[cfg(all(feature = "classic", target_os = "linux", not(feature = "linux-hci")))]
pub async fn bonded_classic_devices(&self) -> Result<Vec<String>> {
self.inner.require_powered_on().await?;
self.inner.backend().bonded_classic_devices().await
}
#[cfg(all(feature = "rfcomm", target_os = "linux", not(feature = "linux-hci")))]
pub async fn register_classic_profile(
&self,
service: BluetoothUuid,
security: ClassicSecurity,
) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
self.inner
.backend()
.register_classic_profile(service, security)
.await
}
#[cfg(all(feature = "rfcomm", target_os = "linux", not(feature = "linux-hci")))]
pub async fn register_classic_profile_channel(
&self,
service: BluetoothUuid,
channel: u8,
security: ClassicSecurity,
) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
self.inner
.backend()
.register_classic_profile_channel(service, channel, security)
.await
}
#[cfg(all(
feature = "profiles",
feature = "rfcomm",
target_os = "linux",
not(feature = "linux-hci")
))]
pub async fn register_profile(
&self,
profile: Profile,
security: ClassicSecurity,
) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
let service = profile
.service_uuid()
.ok_or_else(|| Error::NotSupported("this profile has no RFCOMM service UUID".into()))?;
self.register_classic_profile(service, security).await
}
#[cfg(all(
feature = "classic-l2cap",
target_os = "linux",
not(feature = "linux-hci")
))]
pub async fn register_classic_l2cap_profile(
&self,
service: BluetoothUuid,
psm: ClassicPsm,
security: ClassicSecurity,
) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
self.inner
.backend()
.register_classic_l2cap_profile(service, psm, security)
.await
}
#[cfg(all(feature = "classic", target_os = "android"))]
pub async fn classic_service_uuids(&self, id: &str) -> Result<Vec<BluetoothUuid>> {
self.inner.backend().classic_service_uuids(id).await
}
#[cfg(all(feature = "classic", target_os = "linux", not(feature = "linux-hci")))]
pub async fn classic_service_uuids(&self, id: &str) -> Result<Vec<BluetoothUuid>> {
self.inner.backend().classic_service_uuids(id).await
}
#[cfg(all(feature = "classic", target_os = "android"))]
pub async fn bonded_classic_devices(&self) -> Result<Vec<String>> {
self.inner.require_powered_on().await?;
self.inner.backend().bonded_classic_devices().await
}
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub fn listen_classic_l2cap(&self, psm: ClassicPsm) -> Result<ClassicL2capListener> {
classic_l2cap_windows::listen(psm)
}
#[cfg(all(feature = "rfcomm", target_os = "windows"))]
pub fn listen_rfcomm(&self, channel: u8) -> Result<RfcommListener> {
rfcomm::listen_windows(channel)
}
#[cfg(all(feature = "classic-l2cap", target_os = "android"))]
pub async fn listen_classic_l2cap(&self, secure: bool) -> Result<ClassicL2capListener> {
self.inner.require_powered_on().await?;
classic_l2cap::listen_android(self, secure).await
}
#[cfg(all(feature = "rfcomm", target_os = "android"))]
pub async fn listen_rfcomm_service(
&self,
name: &str,
service_uuid: &str,
) -> Result<RfcommListener> {
self.inner.require_powered_on().await?;
rfcomm::listen_android(self, name, service_uuid).await
}
#[cfg(all(target_os = "linux", feature = "raw-acl"))]
pub fn open_raw_acl(&self, device: u16) -> Result<RawHciSocket> {
raw_hci::open_acl(device)
}
#[cfg(all(target_os = "linux", feature = "raw-sco"))]
pub fn open_raw_sco(&self, device: u16) -> Result<RawHciSocket> {
raw_hci::open_sco(device)
}
#[cfg(all(target_os = "linux", feature = "le-audio"))]
pub fn open_raw_iso(&self, device: u16) -> Result<RawHciSocket> {
raw_hci::open_iso(device)
}
pub const fn protocol_capabilities() -> ProtocolCapabilities {
ProtocolCapabilities::current()
}
#[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
pub fn listen_classic_l2cap(&self, psm: ClassicPsm) -> Result<ClassicL2capListener> {
classic_l2cap::listen(psm)
}
#[cfg(all(feature = "rfcomm", target_os = "linux"))]
pub fn listen_rfcomm(&self, channel: u8) -> Result<RfcommListener> {
rfcomm::listen(channel)
}
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,
#[cfg(feature = "unrestricted")]
all_manufacturer_data: 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
}
#[cfg(feature = "unrestricted")]
pub fn accept_all_manufacturer_data(mut self) -> Self {
self.all_manufacturer_data = true;
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());
}
#[cfg(feature = "unrestricted")]
if self.all_manufacturer_data {
request = request.accept_all_manufacturer_data();
}
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 async fn collect_for(&mut self, duration: std::time::Duration) -> Vec<AdvertisementEvent> {
use futures_util::StreamExt;
let mut seen: Vec<AdvertisementEvent> = Vec::new();
let _ = timeout(duration, async {
while let Some(sighting) = self.next().await {
match seen.iter_mut().find(|known| known.id == sighting.id) {
Some(known) => known.merge(sighting),
None => seen.push(sighting),
}
}
})
.await;
seen
}
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")
}
}