Skip to main content

Crate webbluetooth_wasm

Crate webbluetooth_wasm 

Source
Expand description

Web Bluetooth from Rust in the browser.

Every other backend in this workspace reaches the radio: CoreBluetooth through the Objective-C runtime, BlueZ over D-Bus, the kernel over an HCI socket, WinRT through COM vtables. In a browser there is no radio to reach. navigator.bluetooth is the interface, the page is sandboxed beneath it, and WebAssembly cannot call it — a wasm module has linear memory and numbers, no DOM and no way to obtain one.

So this backend is the one that does not speak a protocol. It speaks to the page, and the page speaks Web Bluetooth. That boundary needs glue in JavaScript; wasm-bindgen would generate it, and here it is written down instead, in js/webbluetooth.js, because a generated bridge is still a bridge and this one is short enough to read in a sitting.

What that buys is worth being clear about: the same Rust program, and the same API, runs against a real controller on five platforms and against the browser’s own Web Bluetooth on the sixth. The permission model on this one is the browser’s — the chooser is Chrome’s device picker, not this crate’s, and the blocklist enforced is the browser’s own.

§Shape of the boundary

  • host — requests out, answers back, one import for all of them.
  • events — notifications and disconnections pushed in.
  • codec — how a message is laid out, since wasm passes only numbers.
  • exec — somewhere for futures to live, since a browser cannot block.

§Using it

<script type="module">
  import { start } from './webbluetooth.js';
  await start('./your_app.wasm');
</script>

The shim imports nothing and depends on nothing.

Re-exports§

pub use events::set_sink;
pub use events::Event;
pub use exec::oneshot;
pub use exec::spawn;
pub use exec::Oneshot;
pub use exec::Sender;
pub use exec::TaskId;
pub use host::call;
pub use host::call_empty;
pub use host::call_str;
pub use host::Answer;
pub use host::HostError;
pub use host::Op;

Modules§

codec
The wire format between Rust and the shim.
events
Events the page pushes: notifications, disconnections, advertisements.
exec
A single-threaded executor, because a browser has no other kind.
host
The boundary: what this module imports from the page, and what it exports back.

Constants§

SHIM_JS
The shim, so a build can emit it next to the .wasm without the file having to be copied by hand or fetched from anywhere.