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