Bluetooth
Bluetooth is permission-sensitive hardware integration. The app should describe the service it needs and let the host map that request to Classic Bluetooth, Bluetooth Low Energy, nearby-device permissions, pairing, and platform scan rules.
This example finds heart-rate sensors advertising the standard Heart Rate service UUID. Discovery is only the first step: it does not pair with a sensor, subscribe to measurements, or save health data.
Do not scan indefinitely or expose every nearby device by default. Filter by service UUID when you can and bound scans with a timeout.
1. Start with the state the screen needs
Add the smallest state fields the screen needs to render honestly. For this flow, useful state is:
#[derive(Debug, Default)]
struct BluetoothState {
devices: Vec<BluetoothDevice>,
bluetooth_error: Option<String>,
scanning_bluetooth: bool,
scan_finished: bool,
}
impl GlobalState for BluetoothState {}
Store discovered devices, scan status, and errors in app state. Update them from the typed completion actions.
Run this once from the project root:
fission add-capability bluetooth --project-dir .
That command records the capability in fission.toml and updates generated platform files where Fission can do so safely. It does not replace product-specific review of native manifests, usage text, entitlements, service identifiers, domains, or store policy. The CLI adds Android legacy and Android 12+ Bluetooth permissions plus optional feature declarations. iOS receives Bluetooth usage text. Desktop providers map the contract to the platform Bluetooth stack.
This is the difference between the Fission API, a provider, and packaging configuration:
The Fission API is the typed Bluetooth request your reducer makes; the scan call is shown below.
The provider is the shell-side Rust implementation that turns that typed request into the correct OS, browser, or hardware call.
Packaging configuration is the manifest, plist, entitlement, service-worker, protocol, domain, or store metadata that lets the platform permit that call in a real installed app.
If the API exists but the provider is missing, the request returns a typed unsupported error. If the provider exists but packaging is missing, the operating system or browser may deny the request before the provider can complete it.
3. Define reducers for success and failure
The scan completes after its starting reducer returns. Handle both the result and error in completion reducers.
#[fission_reducer(BluetoothDevicesFound)]
fn on_bluetooth_devices_found(state: &mut BluetoothState, ctx: &mut ReducerContext<BluetoothState>) {
state.scanning_bluetooth = false;
state.scan_finished = true;
match ctx.input.capability_ok(SCAN_BLUETOOTH_DEVICES) {
Some(result) => {
state.devices = result.devices;
state.bluetooth_error = None;
}
None => state.bluetooth_error = Some("The host returned no discovery result".into()),
}
}
#[fission_reducer(BluetoothScanFailed)]
fn on_bluetooth_scan_failed(state: &mut BluetoothState, ctx: &mut ReducerContext<BluetoothState>) {
state.scanning_bluetooth = false;
state.scan_finished = true;
state.bluetooth_error = Some(
ctx.input.capability_error(SCAN_BLUETOOTH_DEVICES)
.map(|error| error.message)
.unwrap_or_else(|| "The host could not discover Bluetooth devices".into()),
);
}
The completion actions contain no invented device list. Read the host's result from ctx.input, and keep an empty successful discovery separate from denial or unsupported hardware. Clear the busy state on both paths so the user can retry.
4. Request the capability from a reducer
Call the capability from the reducer that handles the user's intent. The reducer queues a host effect and returns. The runtime later dispatches either the success reducer or the failure reducer.
#[fission_reducer(ScanBluetoothDevices)]
fn on_scan_bluetooth_devices(state: &mut BluetoothState, ctx: &mut ReducerContext<BluetoothState>) {
if state.scanning_bluetooth { return; }
state.scanning_bluetooth = true;
state.scan_finished = false;
state.devices.clear();
state.bluetooth_error = None;
let found = ctx.effects.bind(BluetoothDevicesFound, reduce_with!(on_bluetooth_devices_found));
let failed = ctx.effects.bind(BluetoothScanFailed, reduce_with!(on_bluetooth_scan_failed));
ctx.effects
.bluetooth()
.scan_devices(BluetoothScanRequest {
service_uuids: vec!["0000180d-0000-1000-8000-00805f9b34fb".into()],
timeout_ms: Some(10_000),
include_paired: true,
allow_duplicates: false,
})
.on_ok(found)
.on_err(failed);
}
The call records a typed request; the host applies platform scan and permission rules.
5. Trigger the reducer from the UI
Bind the button to the reducer that starts the scan:
fission_component! {
pub FindHeartRateSensorsButton<BluetoothState> {}
view(_button, state, cx) {
let run = cx.bind(ScanBluetoothDevices, reduce!(on_scan_bluetooth_devices));
}
=> Column(children: [
Button(child: Text(cx.tr("sensors.find_heart_rate")), disabled: state.scanning_bluetooth, on_press: run),
if state.scanning_bluetooth { Spinner(motion: SpinnerMotion::Default, label: cx.tr("sensors.scanning")) },
for device in &state.devices {
Text(device.name.clone().unwrap_or_else(|| cx.tr("sensors.unnamed")), key: device.id.clone())
},
if state.scan_finished && state.devices.is_empty() && state.bluetooth_error.is_none() {
Text(cx.tr("sensors.none_found"))
},
if let Some(error) = &state.bluetooth_error { Alert(title: error.clone(), kind: AlertKind::Error) },
])
}
Define the sensors.* labels in the translation bundles. Device names can be absent; the portable device id identifies a result independently of its position. Adding connection or measurement capture requires separate explicit actions, loading/error states, and a product policy for any health data retained.
6. Provide and test the host behavior
Register a BluetoothHost with .with_bluetooth_host(...). Use MemoryBluetoothHost in tests. Providers should model scan, connect, read, write, advertise, and disconnect separately because each operation can be supported differently.
Test availability, matching and empty scans, timeout, cancellation, permission denial, connection loss, characteristic read/write errors, unsupported advertising, and provider failures.
Android and iOS have strong Bluetooth paths but different permission and background rules. Web Bluetooth is limited by browser and device policy. Windows and macOS have native APIs. Linux depends heavily on BlueZ, permissions, and distribution setup.
Finished capability flow
A complete Bluetooth integration has all of these pieces in place:
| |
|---|
| fission.toml declares the capability and generated platform files contain the permission text, manifest entry, entitlement, domain, or protocol metadata the target needs. |
| App state records the in-flight flag, the successful value, and the user-facing error separately. |
| One reducer starts the host request, one handles success, and one handles denial, unsupported hosts, cancellation, or provider errors. |
| The shell registers a real provider for production and a memory provider for tests. |
| At least one test covers success and one covers permission denial or unsupported host behavior. |
Diagnose capability failures
Capability failures should be safe to retry and easy to explain. Start by checking fission.toml, then run fission doctor, then inspect the generated target files. If the provider is missing, the request should return an unsupported error. If the provider exists but the platform configuration is wrong, the OS or browser will usually deny the request before the provider can complete it. Keep those cases distinct in the UI so users know whether they can retry, change settings, connect hardware, or choose another path.