webbluetooth_wasm/lib.rs
1//! Web Bluetooth from Rust in the browser.
2//!
3//! Every other backend in this workspace reaches the radio: CoreBluetooth
4//! through the Objective-C runtime, BlueZ over D-Bus, the kernel over an HCI
5//! socket, WinRT through COM vtables. In a browser there is no radio to reach.
6//! `navigator.bluetooth` *is* the interface, the page is sandboxed beneath it,
7//! and WebAssembly cannot call it — a wasm module has linear memory and
8//! numbers, no DOM and no way to obtain one.
9//!
10//! So this backend is the one that does not speak a protocol. It speaks to the
11//! page, and the page speaks Web Bluetooth. That boundary needs glue in
12//! JavaScript; `wasm-bindgen` would generate it, and here it is written down
13//! instead, in `js/webbluetooth.js`, because a generated bridge is still a
14//! bridge and this one is short enough to read in a sitting.
15//!
16//! What that buys is worth being clear about: the same Rust program, and the
17//! same API, runs against a real controller on five platforms and against the
18//! browser's own Web Bluetooth on the sixth. The permission model on this one
19//! is the browser's — the chooser is Chrome's device picker, not this crate's,
20//! and the blocklist enforced is the browser's own.
21//!
22//! # Shape of the boundary
23//!
24//! - [`host`] — requests out, answers back, one import for all of them.
25//! - [`events`] — notifications and disconnections pushed in.
26//! - [`codec`] — how a message is laid out, since wasm passes only numbers.
27//! - [`exec`] — somewhere for futures to live, since a browser cannot block.
28//!
29//! # Using it
30//!
31//! ```html
32//! <script type="module">
33//! import { start } from './webbluetooth.js';
34//! await start('./your_app.wasm');
35//! </script>
36//! ```
37//!
38//! The shim imports nothing and depends on nothing.
39
40// The adapter: this platform expressed as the portable model.
41// Public so `webbluetooth` can reach it, and not an API anyone else
42// should call: the facade is what a caller holds. Hidden from the docs
43// for the same reason, which also keeps the same 38 adapter methods from
44// being documented six times over.
45#[doc(hidden)]
46pub mod backend;
47pub mod codec;
48pub mod events;
49pub mod exec;
50pub mod host;
51
52pub use events::{set_sink, Event};
53pub use exec::{oneshot, spawn, Oneshot, Sender, TaskId};
54pub use host::{call, call_empty, call_str, Answer, HostError, Op};
55
56/// The shim, so a build can emit it next to the `.wasm` without the file
57/// having to be copied by hand or fetched from anywhere.
58///
59/// Writing it out is one line, and it cannot drift from the ABI above because
60/// it is compiled in from the same source tree.
61pub const SHIM_JS: &str = include_str!("../js/webbluetooth.js");
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 /// The shim is the other half of the ABI. If it is empty or truncated the
68 /// module loads and then fails at the first call, which is a much worse
69 /// place to find out.
70 #[test]
71 fn the_shim_is_present_and_implements_the_boundary() {
72 assert!(
73 SHIM_JS.len() > 1_000,
74 "the shim looks truncated: {} bytes",
75 SHIM_JS.len()
76 );
77 for expected in [
78 "wbt_call",
79 "wbt_settle",
80 "wbt_event",
81 "wbt_alloc",
82 "wbt_free",
83 "navigator.bluetooth",
84 ] {
85 assert!(
86 SHIM_JS.contains(expected),
87 "the shim does not mention {expected:?}"
88 );
89 }
90 }
91
92 /// Every operation, by the name the shim gives it and the number this
93 /// side gives it.
94 ///
95 /// The pairing is the whole point: the two halves are separate languages
96 /// with no shared header, so the only thing stopping `RequestDevice` from
97 /// meaning `Connect` is that both files say `2`.
98 const OPS: &[(Op, &str)] = &[
99 (Op::Availability, "AVAILABILITY"),
100 (Op::RequestDevice, "REQUEST_DEVICE"),
101 (Op::GetDevices, "GET_DEVICES"),
102 (Op::Forget, "FORGET"),
103 (Op::Connect, "CONNECT"),
104 (Op::Disconnect, "DISCONNECT"),
105 (Op::DiscoverServices, "DISCOVER_SERVICES"),
106 (Op::DiscoverIncludedServices, "DISCOVER_INCLUDED_SERVICES"),
107 (Op::DiscoverCharacteristics, "DISCOVER_CHARACTERISTICS"),
108 (Op::DiscoverDescriptors, "DISCOVER_DESCRIPTORS"),
109 (Op::ReadCharacteristic, "READ_CHARACTERISTIC"),
110 (Op::WriteCharacteristic, "WRITE_CHARACTERISTIC"),
111 (Op::ReadDescriptor, "READ_DESCRIPTOR"),
112 (Op::WriteDescriptor, "WRITE_DESCRIPTOR"),
113 (Op::SetNotify, "SET_NOTIFY"),
114 (Op::WatchAdvertisements, "WATCH_ADVERTISEMENTS"),
115 (Op::UnwatchAdvertisements, "UNWATCH_ADVERTISEMENTS"),
116 (Op::SetTimeout, "SET_TIMEOUT"),
117 ];
118
119 /// Both sides must agree on what number each operation is.
120 ///
121 /// This is the failure that would be worst to debug: the call succeeds,
122 /// the wrong thing happens, and nothing reports an error — a read that
123 /// silently connects, or a write that forgets the device.
124 #[test]
125 fn the_shim_and_this_side_agree_on_every_op_code() {
126 for (op, name) in OPS {
127 let expected = format!("{name}: {},", *op as u32);
128 assert!(
129 SHIM_JS.contains(&expected),
130 "the shim should define `{expected}` for {op:?}, and does not"
131 );
132 }
133 }
134
135 /// A notification has to name its characteristic the way the rest of the
136 /// crate names one: by handle key.
137 ///
138 /// [`backend`] registers a subscriber under the handle key it was given,
139 /// and caches the value under that key too. A shim reporting
140 /// `event.target.uuid` instead is a lookup that can never match, and the
141 /// failure is silent in the worst way — the page connects, discovers,
142 /// writes, `startNotifications()` succeeds, and not one notification ever
143 /// reaches a stream. That shipped in 0.0.2.
144 ///
145 /// Checked as a string for the same reason as the op codes above: the two
146 /// halves are separate languages with no shared header, so nothing but a
147 /// test like this holds them together.
148 #[test]
149 fn the_shim_reports_a_notification_by_handle_key() {
150 let emit = SHIM_JS
151 .split_once("EVENTS.CHARACTERISTIC_VALUE")
152 .expect("the shim should emit CHARACTERISTIC_VALUE")
153 .1
154 .split_once("finish()")
155 .expect("the emit should be terminated by finish()")
156 .0;
157
158 assert!(
159 emit.contains(".str(key)"),
160 "a notification should carry the handle key, which is what \
161 `backend::subscribe` registers under; it carries: {emit}"
162 );
163 assert!(
164 !emit.contains("event.target.uuid"),
165 "a notification is carrying a UUID where the backend expects a \
166 handle key, so every subscriber lookup will miss: {emit}"
167 );
168 }
169
170 /// And every one of them must actually be handled, or the call returns a
171 /// token that is never settled and the caller waits forever.
172 #[test]
173 fn the_shim_handles_every_operation() {
174 for (op, name) in OPS {
175 assert!(
176 SHIM_JS.contains(&format!("case OPS.{name}:")),
177 "the shim has no case for {op:?}"
178 );
179 }
180 }
181
182 /// The event codes have the same problem in the other direction: a
183 /// mismatch turns a disconnection into a notification.
184 #[test]
185 fn the_shim_and_this_side_agree_on_every_event_code() {
186 for (kind, name) in [
187 (
188 crate::host::EventKind::CharacteristicValue,
189 "CHARACTERISTIC_VALUE",
190 ),
191 (
192 crate::host::EventKind::GattServerDisconnected,
193 "DISCONNECTED",
194 ),
195 (crate::host::EventKind::ServiceChanged, "SERVICE_CHANGED"),
196 (
197 crate::host::EventKind::AdvertisementReceived,
198 "ADVERTISEMENT",
199 ),
200 (
201 crate::host::EventKind::AvailabilityChanged,
202 "AVAILABILITY_CHANGED",
203 ),
204 ] {
205 let expected = format!("{name}: {},", kind as u32);
206 assert!(
207 SHIM_JS.contains(&expected),
208 "the shim should define `{expected}` for {kind:?}, and does not"
209 );
210 }
211 }
212
213 /// As do the error codes, which decide whether a caller retries.
214 #[test]
215 fn the_shim_and_this_side_agree_on_every_error_code() {
216 for (error, name) in [
217 (HostError::NotFound, "NotFoundError"),
218 (HostError::Security, "SecurityError"),
219 (HostError::Network, "NetworkError"),
220 (HostError::InvalidState, "InvalidStateError"),
221 (HostError::NotSupported, "NotSupportedError"),
222 (HostError::InvalidModification, "InvalidModificationError"),
223 (HostError::Abort, "AbortError"),
224 (HostError::NotAllowed, "NotAllowedError"),
225 ] {
226 let expected = format!("{name}: {},", error as u32);
227 assert!(
228 SHIM_JS.contains(&expected),
229 "the shim should map `{expected}`, and does not"
230 );
231 }
232 }
233}