Skip to main content

webbluetooth_windows/
peripheral_backend.rs

1//! The Windows peripheral engine: `GattServiceProvider`.
2//!
3//! Closer to CoreBluetooth than to Android: Windows manages the Client
4//! Characteristic Configuration descriptor itself and reports subscriptions
5//! directly, so none of the bookkeeping the Android engine needs applies here.
6//!
7//! Three things are particular to Windows:
8//!
9//! * **Advertising belongs to the service.** There is no separate publisher for
10//!   a GATT server — `GattServiceProvider.StartAdvertising` advertises the
11//!   service it was created for. Publishing two services means two providers.
12//! * **A request must be held open with a deferral.** The event handler returns
13//!   long before a caller has decided what to answer, and without a deferral
14//!   the window closes and the central sees a timeout.
15//! * **The local name is the system's.** Windows advertises the machine's
16//!   Bluetooth name; nothing in the API sets a per-advertisement one.
17
18use crate::ble;
19use crate::com::{succeeded, ComPtr, Delegate};
20use crate::guid::Signature;
21use crate::iids::{classes, generics, interfaces, slots};
22use crate::winrt;
23use futures_channel::oneshot;
24use futures_core::Stream;
25use std::collections::HashMap;
26use std::ffi::c_void;
27use std::pin::Pin;
28use std::sync::atomic::{AtomicBool, Ordering};
29use std::sync::{Arc, Mutex};
30use std::task::{Context, Poll};
31use webbluetooth_core::error::{Availability, Error, Result};
32use webbluetooth_core::peripheral::{Advertising, AttError, RestoredPeripheral, Service, Write};
33use webbluetooth_core::uuid::{BluetoothUuid, IntoUuid};
34
35/// `GattServiceProviderAdvertisementStatus.Started`.
36const ADVERTISEMENT_STARTED: i32 = 2;
37
38fn class_signature(class: classes::Class) -> Signature {
39    Signature::Class {
40        name: class.0,
41        default_interface: class.1,
42    }
43}
44
45/// Await a WinRT operation.
46async fn await_operation(operation: ComPtr, result: Signature) -> Result<ComPtr> {
47    let (tx, rx) = oneshot::channel();
48    let sender = Mutex::new(Some(tx));
49    let attached = ble::on_completed(&operation, result, move |value| {
50        if let Ok(mut guard) = sender.lock() {
51            if let Some(tx) = guard.take() {
52                let _ = tx.send(value);
53            }
54        }
55    });
56    if !attached {
57        return Err(Error::Network(
58            "could not attach a completion handler".into(),
59        ));
60    }
61    let held = operation;
62    let value = rx
63        .await
64        .map_err(|_| Error::Aborted("the operation was cancelled".into()))?;
65    drop(held);
66    value.ok_or_else(|| Error::Network("the operation reported no result".into()))
67}
68
69/// Call a no-argument method returning an `IAsyncOperation`.
70fn invoke_async(object: &ComPtr, slot: usize) -> Option<ComPtr> {
71    let mut operation: *mut c_void = std::ptr::null_mut();
72    let hr = unsafe {
73        let f: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> i32 =
74            object.method(slot);
75        f(object.as_raw(), &mut operation)
76    };
77    succeeded(hr)
78        .then(|| unsafe { ComPtr::adopt(operation) })
79        .flatten()
80}
81
82// ── Inbound requests ────────────────────────────────────────────────────────
83
84/// A central connected to this peripheral.
85#[derive(Debug, Clone)]
86pub struct RemoteCentral {
87    client: Option<ComPtr>,
88    id: String,
89}
90
91impl RemoteCentral {
92    /// The central's session id.
93    ///
94    /// Windows identifies a subscriber by session rather than by address — it
95    /// does not hand out the peer's address on this side at all.
96    pub fn id(&self) -> &str {
97        &self.id
98    }
99
100    /// Whether the platform actually identified this central.
101    ///
102    /// When it did not, [`id`](Self::id) is a placeholder that unrelated centrals share, so
103    /// never use it to tell centrals apart — for example, to bind an authenticated session to
104    /// the central that opened it. Check this first and treat an unidentified central as
105    /// untrusted.
106    pub fn is_identified(&self) -> bool {
107        !self.id.is_empty()
108    }
109
110    /// The most bytes one notification to this central can carry.
111    pub fn max_notification_length(&self) -> usize {
112        self.client
113            .as_ref()
114            .and_then(|c| ble::get_i32(c, slots::igatt_subscribed_client::MAX_NOTIFICATION_SIZE))
115            .filter(|n| *n > 0)
116            .unwrap_or(20) as usize
117    }
118}
119
120/// An inbound ATT read.
121///
122/// Held open by a deferral until it is answered; dropping it answers
123/// [`webbluetooth_core::peripheral::AttError::RequestNotSupported`] rather than leaving the central waiting.
124pub struct ReadRequest {
125    request: ComPtr,
126    deferral: Option<ComPtr>,
127    central: RemoteCentral,
128    characteristic: BluetoothUuid,
129    offset: usize,
130    answered: bool,
131}
132
133impl ReadRequest {
134    pub fn characteristic(&self) -> &BluetoothUuid {
135        &self.characteristic
136    }
137    pub fn central(&self) -> &RemoteCentral {
138        &self.central
139    }
140    pub fn offset(&self) -> usize {
141        self.offset
142    }
143
144    /// Answer with a value. The offset is applied for you.
145    pub fn respond(mut self, value: &[u8]) -> Result<()> {
146        if self.offset > value.len() {
147            self.fail(AttError::InvalidOffset);
148            return Err(Error::InvalidModification(format!(
149                "read offset {} is past the end of a {}-byte value",
150                self.offset,
151                value.len()
152            )));
153        }
154        let buffer = ble::bytes_to_buffer(&value[self.offset..])
155            .ok_or_else(|| Error::Network("could not build a response buffer".into()))?;
156        let hr = unsafe {
157            let f: unsafe extern "system" fn(*mut c_void, *mut c_void) -> i32 = self
158                .request
159                .method(slots::igatt_read_request::RESPOND_WITH_VALUE);
160            f(self.request.as_raw(), buffer.as_raw())
161        };
162        self.answered = true;
163        self.complete();
164        succeeded(hr)
165            .then_some(())
166            .ok_or_else(|| Error::Network("RespondWithValue was refused".into()))
167    }
168
169    /// Refuse, with a reason the central sees as an ATT error.
170    pub fn reject(mut self, error: AttError) {
171        self.fail(error);
172    }
173
174    fn fail(&mut self, error: AttError) {
175        if self.answered {
176            return;
177        }
178        self.answered = true;
179        unsafe {
180            let f: unsafe extern "system" fn(*mut c_void, u8) -> i32 = self
181                .request
182                .method(slots::igatt_read_request::RESPOND_WITH_PROTOCOL_ERROR);
183            f(self.request.as_raw(), error as u8);
184        }
185        self.complete();
186    }
187
188    /// Release the deferral, which is what tells Windows the request is done.
189    fn complete(&mut self) {
190        if let Some(deferral) = self.deferral.take() {
191            ble::call_void(&deferral, slots::ideferral::COMPLETE);
192        }
193    }
194}
195
196impl Drop for ReadRequest {
197    fn drop(&mut self) {
198        self.fail(AttError::RequestNotSupported);
199    }
200}
201
202impl std::fmt::Debug for ReadRequest {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        f.debug_struct("ReadRequest")
205            .field("characteristic", &self.characteristic.as_str())
206            .field("offset", &self.offset)
207            .finish()
208    }
209}
210
211/// One or more inbound ATT writes.
212///
213/// Windows delivers writes one at a time, so this carries exactly one — the
214/// shape matches CoreBluetooth, which batches.
215pub struct WriteRequest {
216    request: ComPtr,
217    deferral: Option<ComPtr>,
218    central: RemoteCentral,
219    writes: Vec<Write>,
220    /// A write-without-response asks for no reply, and answering one is an
221    /// error rather than a courtesy.
222    response_needed: bool,
223    answered: bool,
224}
225
226impl WriteRequest {
227    pub fn writes(&self) -> &[Write] {
228        &self.writes
229    }
230    pub fn central(&self) -> &RemoteCentral {
231        &self.central
232    }
233
234    pub fn accept(mut self) {
235        self.answer(None);
236    }
237
238    pub fn reject_all(mut self, error: AttError) {
239        self.answer(Some(error));
240    }
241
242    fn answer(&mut self, error: Option<AttError>) {
243        if self.answered {
244            return;
245        }
246        self.answered = true;
247        if self.response_needed {
248            unsafe {
249                match error {
250                    None => {
251                        let f: unsafe extern "system" fn(*mut c_void) -> i32 =
252                            self.request.method(slots::igatt_write_request::RESPOND);
253                        f(self.request.as_raw());
254                    }
255                    Some(error) => {
256                        let f: unsafe extern "system" fn(*mut c_void, u8) -> i32 = self
257                            .request
258                            .method(slots::igatt_write_request::RESPOND_WITH_PROTOCOL_ERROR);
259                        f(self.request.as_raw(), error as u8);
260                    }
261                }
262            }
263        }
264        if let Some(deferral) = self.deferral.take() {
265            ble::call_void(&deferral, slots::ideferral::COMPLETE);
266        }
267    }
268}
269
270impl Drop for WriteRequest {
271    fn drop(&mut self) {
272        self.answer(Some(AttError::RequestNotSupported));
273    }
274}
275
276impl std::fmt::Debug for WriteRequest {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("WriteRequest")
279            .field("writes", &self.writes.len())
280            .finish()
281    }
282}
283
284/// Something a connected central did.
285#[derive(Debug)]
286pub enum Request {
287    Read(ReadRequest),
288    Write(WriteRequest),
289    Subscribed {
290        central: RemoteCentral,
291        characteristic: BluetoothUuid,
292    },
293    Unsubscribed {
294        central: RemoteCentral,
295        characteristic: BluetoothUuid,
296    },
297    /// The previous notification was delivered and another may be sent.
298    ReadyToNotify,
299}
300
301/// The stream of [`Request`]s, returned once by [`Peripheral::new`].
302/// How many requests from a central queue before one is dropped.
303const REQUEST_BACKLOG: usize = 1024;
304
305pub struct Requests {
306    rx: webbluetooth_core::backlog::Receiver<Request>,
307}
308
309impl Requests {
310    /// How many requests were dropped because this stream was not being read
311    /// fast enough.
312    ///
313    /// A central can write as fast as the link allows and the callback
314    /// delivering those writes cannot be made to wait, so a handler that falls
315    /// behind loses the newest — the ones already queued are answered first.
316    /// Anything treating these as an ordered command stream should check this
317    /// rather than assume it saw them all.
318    pub fn lost(&self) -> u64 {
319        self.rx.lost()
320    }
321}
322
323impl Stream for Requests {
324    type Item = Request;
325    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Request>> {
326        Pin::new(&mut self.rx).poll_next(cx)
327    }
328}
329
330// ── Engine ──────────────────────────────────────────────────────────────────
331
332struct Inner {
333    available: bool,
334    /// One `GattServiceProvider` per published service — advertising belongs to
335    /// the provider, so they cannot be shared.
336    providers: Mutex<Vec<ComPtr>>,
337    /// Handlers, held so Windows keeps calling them.
338    handlers: Mutex<Vec<ComPtr>>,
339    /// Who is subscribed to what, as Windows last reported it.
340    subscribers: Mutex<HashMap<BluetoothUuid, Vec<RemoteCentral>>>,
341    requests: Mutex<Option<webbluetooth_core::backlog::Sender<Request>>>,
342    advertising: AtomicBool,
343}
344
345impl Inner {
346    fn send(&self, request: Request) {
347        let tx = self.requests.lock().unwrap().clone();
348        if let Some(tx) = tx {
349            if tx.send(request).is_err() {
350                *self.requests.lock().unwrap() = None;
351            }
352        }
353    }
354
355    async fn require_powered_on(&self) -> Result<()> {
356        if !self.available {
357            return Err(Error::NotAvailable(Availability::Unsupported));
358        }
359        match ble::statics(
360            classes::GATT_SERVICE_PROVIDER,
361            interfaces::I_GATT_SERVICE_PROVIDER_STATICS,
362        ) {
363            Some(_) => Ok(()),
364            None => Err(Error::NotAvailable(Availability::Unsupported)),
365        }
366    }
367}
368
369/// A local GATT server.
370#[derive(Clone)]
371pub struct Peripheral {
372    inner: Arc<Inner>,
373}
374
375impl Peripheral {
376    /// Open the peripheral role, returning the handle and its request stream.
377    pub fn new() -> (Self, Requests) {
378        // Requests from a connected central: reads and writes against the
379        // GATT server this process publishes. Bounded, keeping the *oldest*,
380        // because these are commands in order — a control point told to do
381        // three things wants the first three, not the last three, and a
382        // contiguous prefix with a known stopping point is something a
383        // handler can reason about. `Requests::lost` reports the rest.
384        let (tx, rx) = webbluetooth_core::backlog::bounded(
385            REQUEST_BACKLOG,
386            webbluetooth_core::backlog::Overflow::KeepOldest,
387        );
388        let inner = Arc::new(Inner {
389            available: winrt::initialize(),
390            providers: Mutex::new(Vec::new()),
391            handlers: Mutex::new(Vec::new()),
392            subscribers: Mutex::new(HashMap::new()),
393            requests: Mutex::new(Some(tx)),
394            advertising: AtomicBool::new(false),
395        });
396        (Self { inner }, Requests { rx })
397    }
398
399    /// Windows preserves nothing across a restart; the identifier is ignored.
400    pub fn with_restoration(_restoration: webbluetooth_core::Restoration) -> (Self, Requests) {
401        Self::new()
402    }
403
404    pub async fn availability(&self) -> std::result::Result<(), Availability> {
405        match self.inner.require_powered_on().await {
406            Ok(()) => Ok(()),
407            Err(Error::NotAvailable(a)) => Err(a),
408            Err(_) => Err(Availability::Unknown),
409        }
410    }
411
412    /// Publish a service.
413    ///
414    /// Each service gets its own `GattServiceProvider`, because on Windows the
415    /// provider is also what advertises it.
416    pub async fn publish(&self, service: Service) -> Result<PublishedService> {
417        service.validate()?;
418        self.inner.require_powered_on().await?;
419
420        let statics = ble::statics(
421            classes::GATT_SERVICE_PROVIDER,
422            interfaces::I_GATT_SERVICE_PROVIDER_STATICS,
423        )
424        .ok_or(Error::NotAvailable(Availability::Unsupported))?;
425
426        // GattServiceProvider.CreateAsync(uuid)
427        let uuid = crate::guid::Guid::parse(service.uuid.as_str());
428        let mut operation: *mut c_void = std::ptr::null_mut();
429        let hr = unsafe {
430            let f: unsafe extern "system" fn(
431                *mut c_void,
432                crate::guid::Guid,
433                *mut *mut c_void,
434            ) -> i32 = statics.method(slots::igatt_service_provider_statics::CREATE_ASYNC);
435            f(statics.as_raw(), uuid, &mut operation)
436        };
437        let operation = succeeded(hr)
438            .then(|| unsafe { ComPtr::adopt(operation) })
439            .flatten()
440            .ok_or_else(|| Error::Network("GattServiceProvider.CreateAsync was refused".into()))?;
441
442        let result = await_operation(
443            operation,
444            class_signature(classes::GATT_SERVICE_PROVIDER_RESULT),
445        )
446        .await?;
447        let provider = ble::get_object(
448            &result,
449            slots::igatt_service_provider_result::SERVICE_PROVIDER,
450        )
451        .ok_or_else(|| Error::Network("no service provider was created".into()))?;
452        let local_service = ble::get_object(&provider, slots::igatt_service_provider::SERVICE)
453            .ok_or_else(|| Error::Network("the provider published no service".into()))?;
454
455        let mut characteristics = Vec::new();
456        for definition in &service.characteristics {
457            let handle = self
458                .create_characteristic(&local_service, definition)
459                .await?;
460            characteristics.push(handle);
461        }
462
463        self.inner.providers.lock().unwrap().push(provider.clone());
464        Ok(PublishedService {
465            inner: self.inner.clone(),
466            uuid: service.uuid,
467            provider,
468            characteristics,
469        })
470    }
471
472    /// Build one characteristic and wire its request handlers.
473    async fn create_characteristic(
474        &self,
475        local_service: &ComPtr,
476        definition: &webbluetooth_core::peripheral::Characteristic,
477    ) -> Result<PublishedCharacteristic> {
478        let parameters = ble::activate(classes::GATT_LOCAL_CHARACTERISTIC_PARAMETERS)
479            .ok_or_else(|| Error::Network("could not build characteristic parameters".into()))?;
480
481        unsafe {
482            let f: unsafe extern "system" fn(*mut c_void, i32) -> i32 = parameters.method(
483                slots::igatt_local_characteristic_parameters::SET_CHARACTERISTIC_PROPERTIES,
484            );
485            f(parameters.as_raw(), definition.properties as i32);
486        }
487        if let Some(value) = &definition.value {
488            if let Some(buffer) = ble::bytes_to_buffer(value) {
489                unsafe {
490                    let f: unsafe extern "system" fn(*mut c_void, *mut c_void) -> i32 = parameters
491                        .method(slots::igatt_local_characteristic_parameters::SET_STATIC_VALUE);
492                    f(parameters.as_raw(), buffer.as_raw());
493                }
494            }
495        }
496
497        let uuid = crate::guid::Guid::parse(definition.uuid.as_str());
498        let mut operation: *mut c_void = std::ptr::null_mut();
499        let hr = unsafe {
500            let f: unsafe extern "system" fn(
501                *mut c_void,
502                crate::guid::Guid,
503                *mut c_void,
504                *mut *mut c_void,
505            ) -> i32 =
506                local_service.method(slots::igatt_local_service::CREATE_CHARACTERISTIC_ASYNC);
507            f(
508                local_service.as_raw(),
509                uuid,
510                parameters.as_raw(),
511                &mut operation,
512            )
513        };
514        let operation = succeeded(hr)
515            .then(|| unsafe { ComPtr::adopt(operation) })
516            .flatten()
517            .ok_or_else(|| Error::Network("CreateCharacteristicAsync was refused".into()))?;
518
519        let result = await_operation(
520            operation,
521            class_signature(classes::GATT_LOCAL_CHARACTERISTIC_RESULT),
522        )
523        .await?;
524        let characteristic = ble::get_object(
525            &result,
526            slots::igatt_local_characteristic_result::CHARACTERISTIC,
527        )
528        .ok_or_else(|| Error::Network("no characteristic was created".into()))?;
529
530        self.attach_handlers(&characteristic, definition.uuid);
531        Ok(PublishedCharacteristic {
532            inner: self.inner.clone(),
533            uuid: definition.uuid,
534            handle: characteristic,
535        })
536    }
537
538    /// Route `ReadRequested`, `WriteRequested` and `SubscribedClientsChanged`.
539    fn attach_handlers(&self, characteristic: &ComPtr, uuid: BluetoothUuid) {
540        use slots::igatt_local_characteristic as c;
541
542        let read_iid = typed_handler_iid(classes::GATT_READ_REQUESTED_EVENT_ARGS);
543        let write_iid = typed_handler_iid(classes::GATT_WRITE_REQUESTED_EVENT_ARGS);
544        let subscribed_iid = Signature::Parameterized {
545            generic: generics::TYPED_EVENT_HANDLER,
546            arguments: vec![
547                class_signature(classes::GATT_LOCAL_CHARACTERISTIC),
548                Signature::OBJECT,
549            ],
550        }
551        .iid()
552        .expect("a parameterised signature always has an IID");
553
554        let engine = Arc::downgrade(&self.inner);
555        let for_read = uuid;
556        let read = Delegate::new(read_iid, move |_sender, args| {
557            let Some(engine) = engine.upgrade() else {
558                return;
559            };
560            on_read_requested(&engine, args, for_read);
561        });
562
563        let engine = Arc::downgrade(&self.inner);
564        let for_write = uuid;
565        let write = Delegate::new(write_iid, move |_sender, args| {
566            let Some(engine) = engine.upgrade() else {
567                return;
568            };
569            on_write_requested(&engine, args, for_write);
570        });
571
572        let engine = Arc::downgrade(&self.inner);
573        let for_subscribe = uuid;
574        let subscribed = Delegate::new(subscribed_iid, move |sender, _args| {
575            let Some(engine) = engine.upgrade() else {
576                return;
577            };
578            on_subscribers_changed(&engine, sender, for_subscribe);
579        });
580
581        for (slot, handler) in [
582            (c::READ_REQUESTED, &read),
583            (c::WRITE_REQUESTED, &write),
584            (c::SUBSCRIBED_CLIENTS_CHANGED, &subscribed),
585        ] {
586            let mut token: i64 = 0;
587            unsafe {
588                let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut i64) -> i32 =
589                    characteristic.method(slot);
590                f(characteristic.as_raw(), handler.as_raw(), &mut token);
591            }
592        }
593        let mut held = self.inner.handlers.lock().unwrap();
594        held.push(read);
595        held.push(write);
596        held.push(subscribed);
597    }
598
599    /// Remove every published service.
600    pub fn unpublish_all(&self) {
601        for provider in self.inner.providers.lock().unwrap().drain(..) {
602            ble::call_void(&provider, slots::igatt_service_provider::STOP_ADVERTISING);
603        }
604        self.inner.handlers.lock().unwrap().clear();
605        self.inner.subscribers.lock().unwrap().clear();
606        self.inner.advertising.store(false, Ordering::Release);
607    }
608
609    /// Start advertising every published service.
610    ///
611    /// Windows advertises the machine's Bluetooth name, so
612    /// [`Advertising::local_name`](webbluetooth_core::peripheral::Advertising::local_name) has no
613    /// effect here; the service UUIDs come from what was published.
614    pub async fn start_advertising(&self, _advertising: Advertising) -> Result<()> {
615        self.inner.require_powered_on().await?;
616        let providers = self.inner.providers.lock().unwrap().clone();
617        if providers.is_empty() {
618            return Err(Error::InvalidState(
619                "publish a service before advertising — Windows advertises services, not names"
620                    .into(),
621            ));
622        }
623
624        let parameters = ble::activate(classes::GATT_SERVICE_PROVIDER_ADVERTISING_PARAMETERS)
625            .ok_or_else(|| Error::Network("could not build advertising parameters".into()))?;
626        use slots::igatt_service_provider_advertising_parameters as ap;
627        for (slot, value) in [
628            (ap::SET_IS_CONNECTABLE, true),
629            (ap::SET_IS_DISCOVERABLE, true),
630        ] {
631            unsafe {
632                let f: unsafe extern "system" fn(*mut c_void, u8) -> i32 = parameters.method(slot);
633                f(parameters.as_raw(), u8::from(value));
634            }
635        }
636
637        for provider in &providers {
638            let hr = unsafe {
639                let f: unsafe extern "system" fn(*mut c_void, *mut c_void) -> i32 = provider
640                    .method(slots::igatt_service_provider::START_ADVERTISING_WITH_PARAMETERS);
641                f(provider.as_raw(), parameters.as_raw())
642            };
643            if !succeeded(hr) {
644                return Err(Error::Network("StartAdvertising was refused".into()));
645            }
646        }
647        self.inner.advertising.store(true, Ordering::Release);
648        Ok(())
649    }
650
651    pub fn stop_advertising(&self) {
652        for provider in self.inner.providers.lock().unwrap().iter() {
653            ble::call_void(
654                &provider.clone(),
655                slots::igatt_service_provider::STOP_ADVERTISING,
656            );
657        }
658        self.inner.advertising.store(false, Ordering::Release);
659    }
660
661    /// Whether the radio is currently advertising.
662    pub fn is_advertising(&self) -> bool {
663        // Ask the provider rather than trusting the flag: Windows stops
664        // advertising on its own when the radio is turned off.
665        let providers = self.inner.providers.lock().unwrap();
666        let live = providers.iter().any(|p| {
667            ble::get_i32(p, slots::igatt_service_provider::ADVERTISEMENT_STATUS)
668                == Some(ADVERTISEMENT_STARTED)
669        });
670        live || (providers.is_empty() && self.inner.advertising.load(Ordering::Acquire))
671    }
672
673    /// Not available: Windows exposes no L2CAP channel API at all.
674    pub async fn publish_l2cap_channel(
675        &self,
676        _encryption_required: bool,
677    ) -> Result<webbluetooth_core::Psm> {
678        Err(Error::NotSupported(
679            "Windows exposes no L2CAP connection-oriented channel API".into(),
680        ))
681    }
682
683    pub async fn unpublish_l2cap_channel(&self, _psm: webbluetooth_core::Psm) -> Result<()> {
684        Ok(())
685    }
686
687    /// Always `None`: Windows preserves nothing across a restart.
688    pub async fn restored_state(&self) -> Option<RestoredPeripheral> {
689        None
690    }
691}
692
693impl std::fmt::Debug for Peripheral {
694    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
695        f.debug_struct("Peripheral")
696            .field("advertising", &self.is_advertising())
697            .finish()
698    }
699}
700
701/// `TypedEventHandler<GattLocalCharacteristic, TArgs>`.
702fn typed_handler_iid(args: classes::Class) -> crate::guid::Guid {
703    Signature::Parameterized {
704        generic: generics::TYPED_EVENT_HANDLER,
705        arguments: vec![
706            class_signature(classes::GATT_LOCAL_CHARACTERISTIC),
707            class_signature(args),
708        ],
709    }
710    .iid()
711    .expect("a parameterised signature always has an IID")
712}
713
714/// The central behind a request, identified by its session.
715fn central_from_session(session: Option<ComPtr>) -> RemoteCentral {
716    let id = session
717        .as_ref()
718        .and_then(|s| ble::get_object(s, slots::igatt_session::DEVICE_ID))
719        .and_then(|d| ble::get_string(&d, slots::igatt_session::DEVICE_ID))
720        .unwrap_or_default();
721    RemoteCentral { client: None, id }
722}
723
724fn on_read_requested(engine: &Arc<Inner>, args: *mut c_void, characteristic: BluetoothUuid) {
725    if args.is_null() {
726        return;
727    }
728    let args = std::mem::ManuallyDrop::new(unsafe { ComPtr::adopt(args) });
729    let Some(args) = args.as_ref() else { return };
730
731    // Take the deferral first: without it the request window closes as soon as
732    // this handler returns, long before a caller has answered.
733    let deferral = invoke_deferral(args, slots::igatt_read_requested_event_args::GET_DEFERRAL);
734    let central = central_from_session(ble::get_object(
735        args,
736        slots::igatt_read_requested_event_args::SESSION,
737    ));
738
739    let Some(operation) = invoke_async(
740        args,
741        slots::igatt_read_requested_event_args::GET_REQUEST_ASYNC,
742    ) else {
743        return;
744    };
745    let engine = engine.clone();
746    let result_signature = class_signature(classes::GATT_READ_REQUEST);
747    let once = Mutex::new(Some((deferral, central, characteristic)));
748
749    ble::on_completed(&operation, result_signature, move |request| {
750        let Some(request) = request else { return };
751        let Ok(mut guard) = once.lock() else { return };
752        let Some((deferral, central, characteristic)) = guard.take() else {
753            return;
754        };
755        let offset = ble::get_i32(&request, slots::igatt_read_request::OFFSET)
756            .unwrap_or(0)
757            .max(0) as usize;
758        engine.send(Request::Read(ReadRequest {
759            request,
760            deferral,
761            central,
762            characteristic,
763            offset,
764            answered: false,
765        }));
766    });
767    // The operation must outlive its handler; Windows holds a reference.
768    std::mem::forget(operation);
769}
770
771fn on_write_requested(engine: &Arc<Inner>, args: *mut c_void, characteristic: BluetoothUuid) {
772    if args.is_null() {
773        return;
774    }
775    let args = std::mem::ManuallyDrop::new(unsafe { ComPtr::adopt(args) });
776    let Some(args) = args.as_ref() else { return };
777
778    let deferral = invoke_deferral(args, slots::igatt_write_requested_event_args::GET_DEFERRAL);
779    let central = central_from_session(ble::get_object(
780        args,
781        slots::igatt_write_requested_event_args::SESSION,
782    ));
783
784    let Some(operation) = invoke_async(
785        args,
786        slots::igatt_write_requested_event_args::GET_REQUEST_ASYNC,
787    ) else {
788        return;
789    };
790    let engine = engine.clone();
791    let result_signature = class_signature(classes::GATT_WRITE_REQUEST);
792    let once = Mutex::new(Some((deferral, central, characteristic)));
793
794    ble::on_completed(&operation, result_signature, move |request| {
795        let Some(request) = request else { return };
796        let Ok(mut guard) = once.lock() else { return };
797        let Some((deferral, central, characteristic)) = guard.take() else {
798            return;
799        };
800
801        let offset = ble::get_i32(&request, slots::igatt_write_request::OFFSET)
802            .unwrap_or(0)
803            .max(0) as usize;
804        let value = ble::get_object(&request, slots::igatt_write_request::VALUE)
805            .and_then(|b| ble::buffer_to_bytes(&b))
806            .unwrap_or_default();
807        // GattWriteOption::WriteWithResponse == 0.
808        let response_needed =
809            ble::get_i32(&request, slots::igatt_write_request::OPTION).unwrap_or(0) == 0;
810
811        engine.send(Request::Write(WriteRequest {
812            request,
813            deferral,
814            central,
815            writes: vec![Write {
816                characteristic,
817                offset,
818                value,
819            }],
820            response_needed,
821            answered: false,
822        }));
823    });
824    std::mem::forget(operation);
825}
826
827fn on_subscribers_changed(engine: &Arc<Inner>, sender: *mut c_void, characteristic: BluetoothUuid) {
828    if sender.is_null() {
829        return;
830    }
831    let sender = std::mem::ManuallyDrop::new(unsafe { ComPtr::adopt(sender) });
832    let Some(sender) = sender.as_ref() else {
833        return;
834    };
835
836    let mut current = Vec::new();
837    if let Some(vector) = ble::get_object(
838        sender,
839        slots::igatt_local_characteristic::SUBSCRIBED_CLIENTS,
840    ) {
841        ble::for_each(&vector, |client| {
842            let id = ble::get_object(&client, slots::igatt_subscribed_client::SESSION)
843                .and_then(|s| ble::get_string(&s, slots::igatt_session::DEVICE_ID))
844                .unwrap_or_default();
845            current.push(RemoteCentral {
846                client: Some(client),
847                id,
848            });
849        });
850    }
851
852    // Windows reports the whole list, so what changed is the difference.
853    let mut subscribers = engine.subscribers.lock().unwrap();
854    let previous = subscribers.remove(&characteristic).unwrap_or_default();
855    subscribers.insert(characteristic, current.clone());
856    drop(subscribers);
857
858    for central in &current {
859        if !previous.iter().any(|p| p.id == central.id) {
860            engine.send(Request::Subscribed {
861                central: central.clone(),
862                characteristic,
863            });
864        }
865    }
866    for central in &previous {
867        if !current.iter().any(|c| c.id == central.id) {
868            engine.send(Request::Unsubscribed {
869                central: central.clone(),
870                characteristic,
871            });
872        }
873    }
874}
875
876/// `GetDeferral()`, which holds a request open past the handler.
877fn invoke_deferral(args: &ComPtr, slot: usize) -> Option<ComPtr> {
878    let mut deferral: *mut c_void = std::ptr::null_mut();
879    let hr = unsafe {
880        let f: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> i32 = args.method(slot);
881        f(args.as_raw(), &mut deferral)
882    };
883    succeeded(hr)
884        .then(|| unsafe { ComPtr::adopt(deferral) })
885        .flatten()
886}
887
888/// A service that is live in the local GATT database.
889pub struct PublishedService {
890    inner: Arc<Inner>,
891    uuid: BluetoothUuid,
892    provider: ComPtr,
893    characteristics: Vec<PublishedCharacteristic>,
894}
895
896impl PublishedService {
897    pub fn uuid(&self) -> &BluetoothUuid {
898        &self.uuid
899    }
900
901    pub fn characteristics(&self) -> Vec<PublishedCharacteristic> {
902        self.characteristics.to_vec()
903    }
904
905    pub fn characteristic(&self, uuid: impl IntoUuid) -> Option<PublishedCharacteristic> {
906        let uuid = uuid.into_uuid().ok()?;
907        self.characteristics
908            .iter()
909            .find(|c| c.uuid == uuid)
910            .cloned()
911    }
912
913    /// Remove just this service.
914    pub fn unpublish(self) {
915        ble::call_void(
916            &self.provider,
917            slots::igatt_service_provider::STOP_ADVERTISING,
918        );
919        let mut providers = self.inner.providers.lock().unwrap();
920        providers.retain(|p| p.key() != self.provider.key());
921    }
922}
923
924impl std::fmt::Debug for PublishedService {
925    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
926        f.debug_struct("PublishedService")
927            .field("uuid", &self.uuid.as_str())
928            .field("characteristics", &self.characteristics.len())
929            .finish()
930    }
931}
932
933/// A characteristic that is live in the local GATT database.
934#[derive(Clone)]
935pub struct PublishedCharacteristic {
936    inner: Arc<Inner>,
937    uuid: BluetoothUuid,
938    handle: ComPtr,
939}
940
941impl PublishedCharacteristic {
942    pub fn uuid(&self) -> &BluetoothUuid {
943        &self.uuid
944    }
945
946    /// The centrals currently subscribed, as Windows last reported them.
947    pub fn subscribers(&self) -> Vec<RemoteCentral> {
948        self.inner
949            .subscribers
950            .lock()
951            .unwrap()
952            .get(&self.uuid)
953            .cloned()
954            .unwrap_or_default()
955    }
956
957    /// Send a value to every subscriber without waiting.
958    pub fn try_notify(&self, value: &[u8]) -> bool {
959        let Some(buffer) = ble::bytes_to_buffer(value) else {
960            return false;
961        };
962        let mut operation: *mut c_void = std::ptr::null_mut();
963        let hr = unsafe {
964            let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut *mut c_void) -> i32 =
965                self.handle
966                    .method(slots::igatt_local_characteristic::NOTIFY_VALUE_ASYNC);
967            f(self.handle.as_raw(), buffer.as_raw(), &mut operation)
968        };
969        // Fire and forget: the per-client results are not awaited here.
970        if succeeded(hr) {
971            if let Some(operation) = unsafe { ComPtr::adopt(operation) } {
972                std::mem::forget(operation);
973            }
974            true
975        } else {
976            false
977        }
978    }
979
980    /// Send a value to specific subscribers.
981    ///
982    /// Windows notifies every subscriber or none — there is no per-client
983    /// variant — so this notifies all of them when `centrals` is non-empty.
984    pub fn try_notify_centrals(&self, value: &[u8], centrals: &[RemoteCentral]) -> bool {
985        !centrals.is_empty() && self.try_notify(value)
986    }
987
988    /// Send a value to every subscriber.
989    pub async fn notify(&self, value: &[u8]) -> Result<()> {
990        if self.subscribers().is_empty() {
991            return Ok(());
992        }
993        if self.try_notify(value) {
994            Ok(())
995        } else {
996            Err(Error::Network("NotifyValueAsync was refused".into()))
997        }
998    }
999}
1000
1001impl std::fmt::Debug for PublishedCharacteristic {
1002    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1003        f.debug_struct("PublishedCharacteristic")
1004            .field("uuid", &self.uuid.as_str())
1005            .field("subscribers", &self.subscribers().len())
1006            .finish()
1007    }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013    use webbluetooth_core::peripheral::{cccd_uuid, Characteristic, Descriptor};
1014    use webbluetooth_core::uuid::characteristics;
1015
1016    #[test]
1017    fn a_static_value_may_also_be_writable() {
1018        // CoreBluetooth forbids this and applies that rule where it publishes;
1019        // the portable checks do not, and Windows adds none of its own.
1020        assert!(Characteristic::new(characteristics::BATTERY_LEVEL)
1021            .unwrap()
1022            .read()
1023            .write()
1024            .value([50])
1025            .validate()
1026            .is_ok());
1027    }
1028
1029    #[test]
1030    fn a_characteristic_still_needs_a_property() {
1031        assert!(Characteristic::new(characteristics::BATTERY_LEVEL)
1032            .unwrap()
1033            .validate()
1034            .is_err());
1035    }
1036
1037    #[test]
1038    fn windows_manages_the_cccd_itself() {
1039        let err = Descriptor {
1040            uuid: cccd_uuid(),
1041            value: vec![0, 0],
1042            is_string: false,
1043        }
1044        .validate()
1045        .unwrap_err();
1046        assert!(err.to_string().contains("manages it"), "got {err}");
1047        assert!(Descriptor::user_description("x").validate().is_ok());
1048        assert!(Descriptor {
1049            uuid: BluetoothUuid::from_u16(0x2901),
1050            value: Vec::new(),
1051            is_string: true,
1052        }
1053        .validate()
1054        .is_err());
1055    }
1056}