Skip to main content

webbluetooth_windows/
ble.rs

1//! Calling WinRT's Bluetooth APIs.
2//!
3//! Everything here is vtable slots from [`crate::iids::slots`] and IIDs from
4//! [`crate::iids`], both generated from Windows metadata. Nothing is counted or
5//! remembered by hand, because a slot off by one is a jump into a different
6//! function and there is no runtime here that would catch it.
7//!
8//! # Async
9//!
10//! Every WinRT call that can block returns an `IAsyncOperation<T>`, which is
11//! completed by handing it a delegate. The delegate's IID is *computed* from
12//! the result type — see [`crate::guid::Signature`] — so each call site names
13//! the signature of what it expects back.
14//!
15//! # Buffers
16//!
17//! GATT values are `IBuffer`, which has no public accessor. `DataReader` and
18//! `DataWriter` convert both ways without needing the `IBufferByteAccess` COM
19//! escape hatch, at the cost of an allocation nobody will notice.
20
21use crate::com::{succeeded, ComPtr, Hresult, FIRST_METHOD};
22use crate::guid::{Guid, Signature};
23use crate::iids::{classes, generics, interfaces, slots};
24use crate::winrt::{activation_factory, HString, WinRtString};
25use std::ffi::c_void;
26use std::sync::Mutex;
27
28/// `IActivationFactory`.
29///
30/// One of the fundamental COM interfaces rather than a WinRT one, so it is not
31/// in the generated metadata. `ActivateInstance` is its only method, and sits
32/// at the first slot after `IInspectable`.
33const IID_IACTIVATION_FACTORY: Guid = Guid::parse("00000035-0000-0000-c000-000000000046");
34const ACTIVATE_INSTANCE: usize = FIRST_METHOD;
35
36/// Construct a WinRT class that has a default constructor.
37pub fn activate(class: classes::Class) -> Option<ComPtr> {
38    let factory = activation_factory(class.0, IID_IACTIVATION_FACTORY)?;
39    let mut instance: *mut c_void = std::ptr::null_mut();
40    let hr = unsafe {
41        let f: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> Hresult =
42            factory.method(ACTIVATE_INSTANCE);
43        f(factory.as_raw(), &mut instance)
44    };
45    if !succeeded(hr) {
46        return None;
47    }
48    unsafe { ComPtr::adopt(instance) }
49}
50
51/// The statics of a class — `BluetoothLEDevice.FromBluetoothAddressAsync` and
52/// the like, which are not on an instance.
53pub fn statics(class: classes::Class, iid: Guid) -> Option<ComPtr> {
54    activation_factory(class.0, iid)
55}
56
57// ── Reading properties ──────────────────────────────────────────────────────
58
59/// A property returning another object.
60pub fn get_object(object: &ComPtr, slot: usize) -> Option<ComPtr> {
61    let mut out: *mut c_void = std::ptr::null_mut();
62    let hr = unsafe {
63        let f: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> Hresult =
64            object.method(slot);
65        f(object.as_raw(), &mut out)
66    };
67    if !succeeded(hr) {
68        return None;
69    }
70    unsafe { ComPtr::adopt(out) }
71}
72
73/// A property returning a string.
74pub fn get_string(object: &ComPtr, slot: usize) -> Option<String> {
75    let mut out: HString = std::ptr::null_mut();
76    let hr = unsafe {
77        let f: unsafe extern "system" fn(*mut c_void, *mut HString) -> Hresult =
78            object.method(slot);
79        f(object.as_raw(), &mut out)
80    };
81    if !succeeded(hr) {
82        return None;
83    }
84    let text = WinRtString::read(out);
85    // The handle is ours now, and reading does not consume it.
86    unsafe { crate::winrt::delete_string(out) };
87    Some(text)
88}
89
90/// A property returning a 32-bit integer or enum.
91pub fn get_i32(object: &ComPtr, slot: usize) -> Option<i32> {
92    let mut out: i32 = 0;
93    let hr = unsafe {
94        let f: unsafe extern "system" fn(*mut c_void, *mut i32) -> Hresult = object.method(slot);
95        f(object.as_raw(), &mut out)
96    };
97    succeeded(hr).then_some(out)
98}
99
100/// A property returning a boolean — `IsEnabled` is one.
101pub fn get_bool(object: &ComPtr, slot: usize) -> Option<bool> {
102    let mut out: u8 = 0;
103    let hr = unsafe {
104        let f: unsafe extern "system" fn(*mut c_void, *mut u8) -> Hresult = object.method(slot);
105        f(object.as_raw(), &mut out)
106    };
107    succeeded(hr).then_some(out != 0)
108}
109
110/// A property returning a 16-bit integer — `RawSignalStrengthInDBm` is one.
111/// A property returning an unsigned 16-bit integer — `MaxPduSize` is one.
112pub fn get_u16(object: &ComPtr, slot: usize) -> Option<u16> {
113    let mut out: u16 = 0;
114    let hr = unsafe {
115        let f: unsafe extern "system" fn(*mut c_void, *mut u16) -> Hresult = object.method(slot);
116        f(object.as_raw(), &mut out)
117    };
118    succeeded(hr).then_some(out)
119}
120
121pub fn get_i16(object: &ComPtr, slot: usize) -> Option<i16> {
122    let mut out: i16 = 0;
123    let hr = unsafe {
124        let f: unsafe extern "system" fn(*mut c_void, *mut i16) -> Hresult = object.method(slot);
125        f(object.as_raw(), &mut out)
126    };
127    succeeded(hr).then_some(out)
128}
129
130/// A property returning a 64-bit integer — a Bluetooth address is one.
131pub fn get_u64(object: &ComPtr, slot: usize) -> Option<u64> {
132    let mut out: u64 = 0;
133    let hr = unsafe {
134        let f: unsafe extern "system" fn(*mut c_void, *mut u64) -> Hresult = object.method(slot);
135        f(object.as_raw(), &mut out)
136    };
137    succeeded(hr).then_some(out)
138}
139
140/// A property returning a GUID by value — every `Uuid` is one.
141pub fn get_guid(object: &ComPtr, slot: usize) -> Option<Guid> {
142    let mut out = Guid::default();
143    let hr = unsafe {
144        let f: unsafe extern "system" fn(*mut c_void, *mut Guid) -> Hresult = object.method(slot);
145        f(object.as_raw(), &mut out)
146    };
147    succeeded(hr).then_some(out)
148}
149
150/// Call a method that takes nothing and returns nothing.
151pub fn call_void(object: &ComPtr, slot: usize) -> bool {
152    let hr = unsafe {
153        let f: unsafe extern "system" fn(*mut c_void) -> Hresult = object.method(slot);
154        f(object.as_raw())
155    };
156    succeeded(hr)
157}
158
159// ── Collections ─────────────────────────────────────────────────────────────
160
161/// Walk an `IVectorView<T>`.
162///
163/// The slot order is the generic's own and is the same for every
164/// instantiation, which is why this works without knowing `T`.
165pub fn for_each(vector: &ComPtr, mut f: impl FnMut(ComPtr)) {
166    let mut size: u32 = 0;
167    let ok = unsafe {
168        let g: unsafe extern "system" fn(*mut c_void, *mut u32) -> Hresult =
169            vector.method(slots::ivector_view::SIZE);
170        succeeded(g(vector.as_raw(), &mut size))
171    };
172    if !ok {
173        return;
174    }
175    for index in 0..size {
176        let mut item: *mut c_void = std::ptr::null_mut();
177        let hr = unsafe {
178            let g: unsafe extern "system" fn(*mut c_void, u32, *mut *mut c_void) -> Hresult =
179                vector.method(slots::ivector_view::GET_AT);
180            g(vector.as_raw(), index, &mut item)
181        };
182        if succeeded(hr) {
183            if let Some(item) = unsafe { ComPtr::adopt(item) } {
184                f(item);
185            }
186        }
187    }
188}
189
190// ── Async ───────────────────────────────────────────────────────────────────
191
192/// The signature of `AsyncOperationCompletedHandler<T>`, whose IID a completion
193/// handler must answer to.
194pub fn completed_handler_iid(result: Signature) -> Guid {
195    Signature::Parameterized {
196        generic: generics::ASYNC_OPERATION_COMPLETED_HANDLER,
197        arguments: vec![Signature::Parameterized {
198            generic: generics::I_ASYNC_OPERATION,
199            arguments: vec![result],
200        }],
201    }
202    .iid()
203    .expect("a parameterised signature always has an IID")
204}
205
206/// Run `then` when an `IAsyncOperation<T>` completes, with its result.
207///
208/// The delegate answers to a computed IID, so `result` must describe exactly
209/// what the operation returns — a mismatch is refused by `put_Completed` rather
210/// than producing a wrong value.
211pub fn on_completed(
212    operation: &ComPtr,
213    result: Signature,
214    then: impl FnOnce(Option<ComPtr>) + Send + 'static,
215) -> bool {
216    // The handler is a Fn but fires once; this is what lets it own a FnOnce.
217    let once = Mutex::new(Some(then));
218
219    let handler =
220        crate::com::Delegate::new(completed_handler_iid(result), move |sender, _status| {
221            let Ok(mut guard) = once.lock() else { return };
222            let Some(then) = guard.take() else { return };
223
224            // `sender` is the completed operation, borrowed — GetResults does not
225            // consume it, so it must not be adopted.
226            let mut value: *mut c_void = std::ptr::null_mut();
227            let ok = if sender.is_null() {
228                false
229            } else {
230                unsafe {
231                    let vtable = *(sender as *const *const *const c_void);
232                    let f: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> Hresult =
233                        std::mem::transmute_copy(
234                            &*vtable.add(slots::iasync_operation::GET_RESULTS),
235                        );
236                    succeeded(f(sender, &mut value))
237                }
238            };
239            then(if ok {
240                unsafe { ComPtr::adopt(value) }
241            } else {
242                None
243            });
244        });
245
246    let hr = unsafe {
247        let f: unsafe extern "system" fn(*mut c_void, *mut c_void) -> Hresult =
248            operation.method(slots::iasync_operation::SET_COMPLETED);
249        f(operation.as_raw(), handler.as_raw())
250    };
251    succeeded(hr)
252}
253
254// ── Buffers ─────────────────────────────────────────────────────────────────
255
256/// Copy an `IBuffer` out of the runtime.
257pub fn buffer_to_bytes(buffer: &ComPtr) -> Option<Vec<u8>> {
258    let statics = statics(classes::DATA_READER, interfaces::I_DATA_READER_STATICS)?;
259
260    let mut reader: *mut c_void = std::ptr::null_mut();
261    let hr = unsafe {
262        let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut *mut c_void) -> Hresult =
263            statics.method(slots::idata_reader_statics::FROM_BUFFER);
264        f(statics.as_raw(), buffer.as_raw(), &mut reader)
265    };
266    if !succeeded(hr) {
267        return None;
268    }
269    let reader = unsafe { ComPtr::adopt(reader) }?;
270
271    let length = get_i32(&reader, slots::idata_reader::UNCONSUMED_BUFFER_LENGTH)? as usize;
272    let mut bytes = vec![0u8; length];
273    if length == 0 {
274        return Some(bytes);
275    }
276    let hr = unsafe {
277        let f: unsafe extern "system" fn(*mut c_void, u32, *mut u8) -> Hresult =
278            reader.method(slots::idata_reader::READ_BYTES);
279        f(reader.as_raw(), length as u32, bytes.as_mut_ptr())
280    };
281    succeeded(hr).then_some(bytes)
282}
283
284/// Hand bytes to the runtime as an `IBuffer`.
285pub fn bytes_to_buffer(bytes: &[u8]) -> Option<ComPtr> {
286    let writer = activate(classes::DATA_WRITER)?;
287    if !bytes.is_empty() {
288        let hr = unsafe {
289            let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) -> Hresult =
290                writer.method(slots::idata_writer::WRITE_BYTES);
291            f(writer.as_raw(), bytes.len() as u32, bytes.as_ptr())
292        };
293        if !succeeded(hr) {
294            return None;
295        }
296    }
297    get_object(&writer, slots::idata_writer::DETACH_BUFFER)
298}
299
300// ── Bluetooth addresses ─────────────────────────────────────────────────────
301
302/// Format a `BluetoothAddress` as `AA:BB:CC:DD:EE:FF`.
303///
304/// WinRT carries it as a 64-bit integer with the address in the low 48 bits,
305/// most significant octet first — the opposite of the socket APIs on Linux.
306pub fn format_address(address: u64) -> String {
307    let b = address.to_be_bytes();
308    format!(
309        "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
310        b[2], b[3], b[4], b[5], b[6], b[7]
311    )
312}
313
314/// Parse `AA:BB:CC:DD:EE:FF` back into WinRT's form.
315pub fn parse_address(address: &str) -> Option<u64> {
316    let parts: Vec<&str> = address.split(':').collect();
317    if parts.len() != 6 {
318        return None;
319    }
320    let mut value: u64 = 0;
321    for part in parts {
322        value = (value << 8) | u64::from(u8::from_str_radix(part, 16).ok()?);
323    }
324    Some(value)
325}
326
327/// A WinRT `GUID` as the canonical lowercase UUID the spec uses.
328pub fn uuid_string(guid: Guid) -> String {
329    guid.to_string()
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn addresses_are_the_low_48_bits_most_significant_first() {
338        // The opposite of the socket APIs, which are little-endian.
339        assert_eq!(format_address(0x0000_AABB_CCDD_EEFF), "AA:BB:CC:DD:EE:FF");
340        assert_eq!(format_address(0x0000_0000_0000_0001), "00:00:00:00:00:01");
341    }
342
343    #[test]
344    fn address_parsing_is_the_inverse_of_formatting() {
345        for text in [
346            "AA:BB:CC:DD:EE:FF",
347            "00:00:00:00:00:01",
348            "12:34:56:78:9A:BC",
349        ] {
350            let parsed = parse_address(text).expect("should parse");
351            assert_eq!(format_address(parsed), text);
352        }
353        assert_eq!(
354            parse_address("AA:BB:CC:DD:EE:FF"),
355            Some(0x0000_AABB_CCDD_EEFF)
356        );
357    }
358
359    #[test]
360    fn malformed_addresses_are_rejected() {
361        for bad in [
362            "",
363            "AA:BB:CC:DD:EE",
364            "AA:BB:CC:DD:EE:FF:00",
365            "ZZ:BB:CC:DD:EE:FF",
366        ] {
367            assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
368        }
369    }
370
371    #[test]
372    fn a_completion_handler_iid_is_stable_and_type_dependent() {
373        // Each instantiation is a distinct interface; handing an operation the
374        // wrong handler is refused rather than mis-delivered.
375        let of = |s: Signature| completed_handler_iid(s);
376        assert_eq!(of(Signature::BOOL), of(Signature::BOOL));
377        assert_ne!(of(Signature::BOOL), of(Signature::I32));
378
379        let device = Signature::Class {
380            name: classes::BLUETOOTH_LE_DEVICE.0,
381            default_interface: classes::BLUETOOTH_LE_DEVICE.1,
382        };
383        assert_ne!(of(device), of(Signature::BOOL));
384    }
385
386    #[test]
387    fn the_handler_signature_nests_operation_inside_handler() {
388        // AsyncOperationCompletedHandler<IAsyncOperation<T>> — getting the
389        // nesting backwards yields a plausible IID that matches nothing.
390        let signature = Signature::Parameterized {
391            generic: generics::ASYNC_OPERATION_COMPLETED_HANDLER,
392            arguments: vec![Signature::Parameterized {
393                generic: generics::I_ASYNC_OPERATION,
394                arguments: vec![Signature::BOOL],
395            }],
396        };
397        let text = signature.text();
398        assert!(text.starts_with("pinterface({fcdcf02c-e5d8-4478-915a-4d90b74b83a5};"));
399        assert!(text.contains("pinterface({9fc2b0bb-e446-44e2-aa61-9cab8f636af2};b1)"));
400        assert_eq!(
401            signature.iid(),
402            Some(completed_handler_iid(Signature::BOOL))
403        );
404    }
405
406    #[test]
407    fn activation_slots_are_after_iinspectable() {
408        assert_eq!(ACTIVATE_INSTANCE, 6);
409        assert_eq!(slots::iasync_operation::GET_RESULTS, 8);
410        assert_eq!(slots::ivector_view::GET_AT, 6);
411        assert_eq!(slots::ivector_view::SIZE, 7);
412    }
413}