Skip to main content

Crate webbluetooth

Crate webbluetooth 

Source
Expand description

§The Web Bluetooth API, in Rust, on macOS and iOS

A faithful port of Web Bluetooth — requestDevice, gatt.connect(), getPrimaryService, readValue, startNotifications — over CoreBluetooth. The JavaScript API’s promises become async fns and its events become Streams; everything else keeps its name, so a port reads like the original.

use webbluetooth::prelude::*;
use webbluetooth::uuid::{characteristics, services};

let bluetooth = Bluetooth::new();

let device = bluetooth
    .request_device(
        RequestDeviceOptions::new()
            .filter(DeviceFilter::new().service(services::HEART_RATE)?)
            .optional_service(services::BATTERY_SERVICE)?,
    )
    .await?;

println!("connecting to {}", device.name().unwrap_or_else(|| device.id().into()));
let gatt = device.gatt();
gatt.connect().await?;

let service = gatt.get_primary_service(services::HEART_RATE).await?;
let measurement = service
    .get_characteristic(characteristics::HEART_RATE_MEASUREMENT)
    .await?;

let mut beats = measurement.start_notifications().await?;
while let Some(value) = beats.next().await {
    println!("{} bpm", value[1]);
}

§What is different from a browser

The chooser is yours. requestDevice() is defined around a user gesture and a picker dialog, and that consent step is the reason the API is safe to expose. A library has no chrome, so it is a trait: see DeviceChooser. The default, chooser::FirstMatch, takes the first match automatically — convenient, and a deliberate removal of that consent step. Use chooser::TerminalChooser (feature terminal-chooser) or your own implementation for anything user-facing.

Everything else about the security model is kept. The GATT blocklist is vendored from the Web Bluetooth Community Group registry and enforced; the per-device service allowlist from filters + optional_services is enforced on every get_primary_service; blocklisted attributes are filtered out of discovery rather than reported and refused.

No device addresses. BluetoothDevice::id is CoreBluetooth’s per-host identifier, not a BD_ADDR — Apple does not expose hardware addresses, and the value differs between machines for the same peripheral.

§Authorization

Bluetooth is TCC-gated. A process with no NSBluetoothAlwaysUsageDescription is reported Availability::Unauthorized and is not prompted, so a bare cargo run binary silently sees no adapter. See the README for how to embed an Info.plist in a CLI binary and what an app bundle needs.

§How it works

There is no Swift, no Objective-C source, and no build-time code generation: CoreBluetooth is an Objective-C framework, so webbluetooth-apple synthesises the CBCentralManagerDelegate class at run time with objc_allocateClassPair, installing Rust extern "C" functions as its method implementations. Callbacks are delivered on a private dispatch_queue, so this works in a plain fn main() with no NSRunLoop.

§License

MIT — Copyright © 2025 Eugene Hauptmann

Modules§

adapter
The controllers themselves.
backlog
A bounded queue for things a peer sends us.
blocklist
The GATT blocklist.
chooser
Choosing a device — the part a browser draws a dialog for.
error
Errors, named after the DOMExceptions the Web Bluetooth spec throws.
filter
requestDevice options, and matching them against an advertisement.
future
Futures, and the combinators these APIs are used with.
grants
Grants that outlive the process.
l2cap
L2CAP connection-oriented channels.
peripheral
Publishing a GATT server.
prelude
Everything a program needs in scope, in one import.
stream
Streams, and the pieces needed to work with several at once.
timer
Runtime-agnostic timers.
uuid
BluetoothUUID — always the canonical 128-bit lowercase form.

Structs§

AdapterInfo
One Bluetooth controller.
Advertisement
One advertising packet, as the specification’s BluetoothAdvertisingEvent reports it.
Advertisements
Advertisements from one device — what watchAdvertisements() starts.
AvailabilityEvents
Adapter availability, as it changes — Bluetooth.onavailabilitychanged.
Bluetooth
The entry point — navigator.bluetooth.
BluetoothDevice
A device returned by crate::Bluetooth::request_device.
BluetoothUuid
A Bluetooth UUID in canonical 128-bit lowercase form.
Candidate
A device seen during a scan that matched the request’s filters.
Candidates
A live stream of matching devices, ending when the scan stops.
CharacteristicProperties
What a characteristic supports — BluetoothCharacteristicProperties.
ConnectionParameters
What a link actually negotiated.
ConnectionPhy
What a link is actually running at, in each direction.
DataPrefix
A prefix-and-mask test over a byte payload, as the spec defines it.
DeviceFilter
One clause of filters. A device matches a filter when it satisfies every member the filter sets; it matches the request when it satisfies any filter.
DisconnectEvents
Yields () each time the device disconnects.
Grant
What a device has been granted access to.
LeScan
A running scan — BluetoothLEScan.
LeScanOptions
Options for Bluetooth::request_le_scan — BluetoothLEScanOptions.
Notifications
A stream of characteristic values, from RemoteGattCharacteristic::start_notifications.
Peripheral
A local GATT server, published through bluetoothd.
ProtocolCapabilities
Protocol capabilities for the current target and Cargo feature set.
RemoteGattCharacteristic
BluetoothRemoteGATTCharacteristic.
RemoteGattDescriptor
BluetoothRemoteGATTDescriptor.
RemoteGattServer
BluetoothRemoteGATTServer.
RemoteGattService
BluetoothRemoteGATTService.
RequestDeviceOptions
Options for Bluetooth::request_device.
Restoration
Opt in to Bluetooth state preservation and restoration.
RestoredSession
What Bluetooth::with_restoration recovered.
ServiceEvents
The service set changed — see RemoteGattServer::watch_services_changed.
Tagged
Notifications with each value paired with the UUID it came from — Notifications::tagged.

Enums§

Authorization
Whether this process may use Bluetooth at all.
Availability
Why Bluetooth is not currently usable.
ConnectionPriority
How aggressively to maintain a connection.
Error
Why a Web Bluetooth operation failed.
Pairing
What BluetoothDevice::pair did.
Phy
A physical layer an LE link can run at.
Protocol
A protocol family that can be queried from ProtocolCapabilities.
WriteType
Whether a write waits for the peer to acknowledge it.

Constants§

APPLE_CLASSIC
Whether the macOS IOBluetooth Classic backend was explicitly requested.
CLASSIC
Whether Bluetooth Classic APIs were enabled for this build.
L2CAP
Whether L2CAP channels are available on the platform this was built for.
LE_AUDIO
Whether LE Audio APIs were enabled for this build.
MESH
Whether Bluetooth Mesh APIs were enabled for this build.
PERIPHERAL_ROLE
Whether the peripheral role is available on the platform this was built for.
PROFILES
Whether profile APIs were enabled for this build.
RAW_ACL
Whether raw ACL transport APIs were enabled for this build.
RAW_SCO
Whether raw SCO transport APIs were enabled for this build.
RFCOMM
Whether RFCOMM APIs were enabled for this build.

Traits§

DeviceChooser
Decides which device request_device returns.
IntoUuid
Anything that can name a GATT attribute: a BluetoothUuid, a 16-bit number, or a string in any accepted form.

Functions§

authorization
Whether this process is permitted to use Bluetooth at all.
run_with_main_run_loop
Run work on a thread of its own while the calling thread — which must be the main thread — turns its CoreFoundation run loop, and return what work returns.
sleep
Complete after duration.
timeout
Run future, giving up after duration.

Type Aliases§

AdvertisementEvent
What a sighting reports — BluetoothAdvertisingEvent.
L2capChannel
This platform’s channel, wrapped in the portable one.
Psm
A PSM — the L2CAP equivalent of a port number.
Result
The result of any Web Bluetooth operation.