1use crate::ble;
23use crate::bluetooth::{Event, EventSink, Ref};
24use crate::runtime::Runtime;
25use futures_channel::oneshot;
26use futures_core::Stream;
27use std::collections::HashMap;
28use std::pin::Pin;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Arc, Mutex, Weak};
31use std::task::{Context, Poll};
32use webbluetooth_core::error::{Availability, Error, Result};
33use webbluetooth_core::gatt::CharacteristicProperties as Properties;
34use webbluetooth_core::peripheral::{
35 cccd_uuid, Advertising, AttError, Permissions, RestoredPeripheral, Service, Write,
36};
37use webbluetooth_core::uuid::{BluetoothUuid, IntoUuid};
38
39#[derive(Debug, Clone)]
43pub struct RemoteCentral {
44 device: Ref,
45 id: String,
46}
47
48impl RemoteCentral {
49 fn new(device: Ref) -> Self {
50 let id = Runtime::get()
51 .and_then(|r| r.env().ok())
52 .and_then(|env| ble::device_address(env, device.as_ptr()))
53 .unwrap_or_default();
54 Self { device, id }
55 }
56
57 pub fn id(&self) -> &str {
59 &self.id
60 }
61
62 pub fn max_notification_length(&self) -> usize {
67 20
68 }
69}
70
71pub struct ReadRequest {
77 inner: Arc<Inner>,
78 central: RemoteCentral,
79 request_id: i32,
80 offset: usize,
81 characteristic: BluetoothUuid,
82 answered: bool,
83}
84
85impl ReadRequest {
86 pub fn characteristic(&self) -> &BluetoothUuid {
87 &self.characteristic
88 }
89 pub fn central(&self) -> &RemoteCentral {
90 &self.central
91 }
92 pub fn offset(&self) -> usize {
94 self.offset
95 }
96
97 pub fn respond(mut self, value: &[u8]) -> Result<()> {
99 if self.offset > value.len() {
100 self.answer(AttError::InvalidOffset, &[]);
101 return Err(Error::InvalidModification(format!(
102 "read offset {} is past the end of a {}-byte value",
103 self.offset,
104 value.len()
105 )));
106 }
107 self.answer(AttError::Success, &value[self.offset..]);
108 Ok(())
109 }
110
111 pub fn reject(mut self, error: AttError) {
113 self.answer(error, &[]);
114 }
115
116 fn answer(&mut self, result: AttError, value: &[u8]) {
117 if self.answered {
118 return;
119 }
120 self.answered = true;
121 self.inner.respond(
122 &self.central.device,
123 self.request_id,
124 result,
125 self.offset,
126 value,
127 );
128 }
129}
130
131impl Drop for ReadRequest {
132 fn drop(&mut self) {
133 self.answer(AttError::RequestNotSupported, &[]);
134 }
135}
136
137impl std::fmt::Debug for ReadRequest {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.debug_struct("ReadRequest")
140 .field("characteristic", &self.characteristic.as_str())
141 .field("offset", &self.offset)
142 .finish()
143 }
144}
145
146pub struct WriteRequest {
152 inner: Arc<Inner>,
153 central: RemoteCentral,
154 request_id: i32,
155 writes: Vec<Write>,
156 response_needed: bool,
157 answered: bool,
158}
159
160impl WriteRequest {
161 pub fn writes(&self) -> &[Write] {
162 &self.writes
163 }
164 pub fn central(&self) -> &RemoteCentral {
165 &self.central
166 }
167
168 pub fn accept(mut self) {
169 self.answer(AttError::Success);
170 }
171
172 pub fn reject_all(mut self, error: AttError) {
173 self.answer(error);
174 }
175
176 fn answer(&mut self, result: AttError) {
177 if self.answered {
178 return;
179 }
180 self.answered = true;
181 if !self.response_needed {
184 return;
185 }
186 let offset = self.writes.first().map(|w| w.offset).unwrap_or(0);
187 self.inner
188 .respond(&self.central.device, self.request_id, result, offset, &[]);
189 }
190}
191
192impl Drop for WriteRequest {
193 fn drop(&mut self) {
194 self.answer(AttError::RequestNotSupported);
195 }
196}
197
198impl std::fmt::Debug for WriteRequest {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 f.debug_struct("WriteRequest")
201 .field("writes", &self.writes.len())
202 .finish()
203 }
204}
205
206#[derive(Debug)]
208pub enum Request {
209 Read(ReadRequest),
210 Write(WriteRequest),
211 Subscribed {
213 central: RemoteCentral,
214 characteristic: BluetoothUuid,
215 },
216 Unsubscribed {
217 central: RemoteCentral,
218 characteristic: BluetoothUuid,
219 },
220 ReadyToNotify,
222 ChannelOpened(crate::l2cap::L2capChannel),
224}
225
226const REQUEST_BACKLOG: usize = 1024;
229
230pub struct Requests {
231 rx: webbluetooth_core::backlog::Receiver<Request>,
232}
233
234impl Requests {
235 pub fn lost(&self) -> u64 {
244 self.rx.lost()
245 }
246}
247
248impl Stream for Requests {
249 type Item = Request;
250 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Request>> {
251 Pin::new(&mut self.rx).poll_next(cx)
252 }
253}
254
255struct Inner {
258 server: Mutex<Option<Ref>>,
259 server_callback: Mutex<Option<ble::Callback>>,
261 advertise_callback: Mutex<Option<ble::Callback>>,
262 service_waiters: Mutex<Vec<oneshot::Sender<Result<()>>>>,
263 advertising_waiters: Mutex<Vec<oneshot::Sender<Result<()>>>>,
264 ready_waiters: Mutex<Vec<oneshot::Sender<()>>>,
265 subscribers: Mutex<HashMap<BluetoothUuid, Vec<RemoteCentral>>>,
267 published: Mutex<HashMap<usize, BluetoothUuid>>,
269 cccds: Mutex<HashMap<usize, BluetoothUuid>>,
271 requests: Mutex<Option<webbluetooth_core::backlog::Sender<Request>>>,
272 advertising: AtomicBool,
273 l2cap: Mutex<HashMap<u16, (Ref, Arc<AtomicBool>)>>,
275}
276
277struct Sink(Weak<Inner>);
278
279impl EventSink for Sink {
280 fn emit(&self, event: Event) {
281 if let Some(inner) = self.0.upgrade() {
282 inner.handle(event);
283 }
284 }
285}
286
287impl Inner {
288 fn handle(self: &Arc<Self>, event: Event) {
289 match event {
290 Event::ServiceAdded { status } => {
291 let result = if status == ble::GATT_SUCCESS {
292 Ok(())
293 } else {
294 Err(Error::Network(format!(
295 "could not publish service (status {status})"
296 )))
297 };
298 for tx in self.service_waiters.lock().unwrap().drain(..) {
299 let _ = tx.send(result.clone());
300 }
301 }
302
303 Event::AdvertisingStarted { error } => {
304 let result = match error {
305 None => {
306 self.advertising.store(true, Ordering::Release);
307 Ok(())
308 }
309 Some(code) => Err(Error::Network(format!(
310 "could not start advertising: {}",
311 describe_advertise_error(code)
312 ))),
313 };
314 for tx in self.advertising_waiters.lock().unwrap().drain(..) {
315 let _ = tx.send(result.clone());
316 }
317 }
318
319 Event::ReadRequest {
320 device,
321 request_id,
322 offset,
323 characteristic,
324 } => {
325 let uuid = self.name_of(&characteristic);
326 let central = RemoteCentral::new(device);
327 self.send(Request::Read(ReadRequest {
328 inner: self.clone(),
329 central,
330 request_id,
331 offset: offset.max(0) as usize,
332 characteristic: uuid,
333 answered: false,
334 }));
335 }
336
337 Event::WriteRequest {
338 device,
339 request_id,
340 characteristic,
341 response_needed,
342 offset,
343 value,
344 ..
345 } => {
346 let uuid = self.name_of(&characteristic);
347 let central = RemoteCentral::new(device);
348 self.send(Request::Write(WriteRequest {
349 inner: self.clone(),
350 central,
351 request_id,
352 writes: vec![Write {
353 characteristic: uuid,
354 offset: offset.max(0) as usize,
355 value,
356 }],
357 response_needed,
358 answered: false,
359 }));
360 }
361
362 Event::DescriptorReadRequest {
363 device,
364 request_id,
365 offset,
366 descriptor,
367 } => {
368 let central = RemoteCentral::new(device);
372 let is_subscribed = self
373 .cccds
374 .lock()
375 .unwrap()
376 .get(&descriptor.key())
377 .map(|uuid| self.is_subscribed(uuid, ¢ral))
378 .unwrap_or(false);
379 let value: &[u8] = if is_subscribed {
380 &[0x01, 0x00]
381 } else {
382 &[0x00, 0x00]
383 };
384 self.respond(
385 ¢ral.device,
386 request_id,
387 AttError::Success,
388 offset.max(0) as usize,
389 value,
390 );
391 }
392
393 Event::DescriptorWriteRequest {
394 device,
395 request_id,
396 descriptor,
397 response_needed,
398 offset,
399 value,
400 } => {
401 let central = RemoteCentral::new(device);
402 let owner = self.cccds.lock().unwrap().get(&descriptor.key()).cloned();
403
404 if response_needed {
405 self.respond(
406 ¢ral.device,
407 request_id,
408 AttError::Success,
409 offset.max(0) as usize,
410 &[],
411 );
412 }
413
414 let Some(characteristic) = owner else { return };
416 let enabling = value.first().is_some_and(|b| *b != 0);
417 let mut subscribers = self.subscribers.lock().unwrap();
418 let list = subscribers.entry(characteristic).or_default();
419 if enabling {
420 if !list.iter().any(|c| c.id == central.id) {
421 list.push(central.clone());
422 }
423 } else {
424 list.retain(|c| c.id != central.id);
425 }
426 drop(subscribers);
427
428 self.send(if enabling {
429 Request::Subscribed {
430 central,
431 characteristic,
432 }
433 } else {
434 Request::Unsubscribed {
435 central,
436 characteristic,
437 }
438 });
439 }
440
441 Event::NotificationSent { .. } => {
442 for tx in self.ready_waiters.lock().unwrap().drain(..) {
443 let _ = tx.send(());
444 }
445 self.send(Request::ReadyToNotify);
446 }
447
448 Event::ServerConnectionStateChanged { device, connected } => {
449 if connected {
450 return;
451 }
452 let central = RemoteCentral::new(device);
454 let mut subscribers = self.subscribers.lock().unwrap();
455 let dropped: Vec<BluetoothUuid> = subscribers
456 .iter()
457 .filter(|(_, list)| list.iter().any(|c| c.id == central.id))
458 .map(|(uuid, _)| *uuid)
459 .collect();
460 for uuid in &dropped {
461 if let Some(list) = subscribers.get_mut(uuid) {
462 list.retain(|c| c.id != central.id);
463 }
464 }
465 drop(subscribers);
466 for characteristic in dropped {
467 self.send(Request::Unsubscribed {
468 central: central.clone(),
469 characteristic,
470 });
471 }
472 }
473
474 _ => {}
475 }
476 }
477
478 fn send(&self, request: Request) {
479 let tx = self.requests.lock().unwrap().clone();
480 if let Some(tx) = tx {
481 if tx.send(request).is_err() {
482 *self.requests.lock().unwrap() = None;
483 }
484 }
485 }
486
487 fn name_of(&self, characteristic: &Ref) -> BluetoothUuid {
488 if let Some(uuid) = self.published.lock().unwrap().get(&characteristic.key()) {
489 return *uuid;
490 }
491 Runtime::get()
492 .and_then(|r| r.env().ok())
493 .and_then(|env| ble::attribute_uuid(env, characteristic.as_ptr()))
494 .and_then(|s| BluetoothUuid::parse(&s).ok())
495 .unwrap_or_else(|| BluetoothUuid::from_u16(0))
496 }
497
498 fn is_subscribed(&self, characteristic: &BluetoothUuid, central: &RemoteCentral) -> bool {
499 self.subscribers
500 .lock()
501 .unwrap()
502 .get(characteristic)
503 .is_some_and(|list| list.iter().any(|c| c.id == central.id))
504 }
505
506 fn respond(
507 &self,
508 device: &Ref,
509 request_id: i32,
510 status: AttError,
511 offset: usize,
512 value: &[u8],
513 ) {
514 let (Some(runtime), Some(server)) = (Runtime::get(), self.server.lock().unwrap().clone())
515 else {
516 return;
517 };
518 let Ok(env) = runtime.env() else { return };
519 let _ = ble::server_send_response(
520 env,
521 server.as_ptr(),
522 device.as_ptr(),
523 request_id,
524 status as i32,
525 offset as i32,
526 value,
527 );
528 }
529
530 async fn require_powered_on(&self) -> Result<()> {
531 let runtime = Runtime::get().ok_or_else(|| {
532 Error::NotSupported(
533 "the Android backend is not started — call webbluetooth::android::init(vm, context)"
534 .into(),
535 )
536 })?;
537 let env = runtime.env().map_err(|e| Error::Network(e.to_string()))?;
538 let adapter = ble::Adapter::open(runtime)
539 .map_err(|_| Error::NotAvailable(Availability::Unsupported))?;
540 if adapter.is_enabled(env) {
541 Ok(())
542 } else {
543 Err(Error::NotAvailable(Availability::PoweredOff))
544 }
545 }
546}
547
548fn describe_advertise_error(code: i32) -> &'static str {
550 match code {
551 1 => "the advertising payload is larger than 31 bytes",
552 2 => "too many advertisers are already running",
553 3 => "this peripheral is already advertising",
554 4 => "an internal error",
555 5 => "this device does not support advertising",
556 _ => "an unknown error",
557 }
558}
559
560#[derive(Clone)]
562pub struct Peripheral {
563 inner: Arc<Inner>,
564}
565
566impl Peripheral {
567 pub fn new() -> (Self, Requests) {
569 Self::build(None)
570 }
571
572 pub fn with_restoration(_restoration: webbluetooth_core::Restoration) -> (Self, Requests) {
575 Self::build(None)
576 }
577
578 fn build(_identifier: Option<String>) -> (Self, Requests) {
579 let (tx, rx) = webbluetooth_core::backlog::bounded(
586 REQUEST_BACKLOG,
587 webbluetooth_core::backlog::Overflow::KeepOldest,
588 );
589 let inner = Arc::new_cyclic(|_weak: &Weak<Inner>| Inner {
590 server: Mutex::new(None),
591 server_callback: Mutex::new(None),
592 advertise_callback: Mutex::new(None),
593 service_waiters: Mutex::new(Vec::new()),
594 advertising_waiters: Mutex::new(Vec::new()),
595 ready_waiters: Mutex::new(Vec::new()),
596 subscribers: Mutex::new(HashMap::new()),
597 published: Mutex::new(HashMap::new()),
598 cccds: Mutex::new(HashMap::new()),
599 requests: Mutex::new(Some(tx)),
600 advertising: AtomicBool::new(false),
601 l2cap: Mutex::new(HashMap::new()),
602 });
603 (Self { inner }, Requests { rx })
604 }
605
606 pub async fn availability(&self) -> std::result::Result<(), Availability> {
608 match self.inner.require_powered_on().await {
609 Ok(()) => Ok(()),
610 Err(Error::NotAvailable(a)) => Err(a),
611 Err(_) => Err(Availability::Unknown),
612 }
613 }
614
615 fn server(&self) -> Result<Ref> {
617 if let Some(server) = self.inner.server.lock().unwrap().clone() {
618 return Ok(server);
619 }
620 let runtime = Runtime::get()
621 .ok_or_else(|| Error::NotSupported("the Android backend is not started".into()))?;
622 let env = runtime.env().map_err(|e| Error::Network(e.to_string()))?;
623
624 let callback = ble::Callback::new(
625 runtime,
626 "dev.webbluetooth.GattServerCallback",
627 crate::gatt_server_callback_dex(),
628 &crate::bluetooth::server_natives(),
629 Arc::new(Sink(Arc::downgrade(&self.inner))),
630 )
631 .map_err(|e| Error::Network(e.to_string()))?;
632
633 let server = ble::open_gatt_server(env, runtime, callback.as_ptr())
634 .map_err(|e| Error::Network(e.to_string()))?;
635 let server = Ref::new(env, server).ok_or(Error::NotAvailable(Availability::Unsupported))?;
636
637 *self.inner.server_callback.lock().unwrap() = Some(callback);
638 *self.inner.server.lock().unwrap() = Some(server.clone());
639 Ok(server)
640 }
641
642 pub async fn publish(&self, service: Service) -> Result<PublishedService> {
648 service.validate()?;
649 self.inner.require_powered_on().await?;
650 let runtime = Runtime::get()
651 .ok_or_else(|| Error::NotSupported("the Android backend is not started".into()))?;
652 let env = runtime.env().map_err(|e| Error::Network(e.to_string()))?;
653 let server = self.server()?;
654
655 let java_service = ble::new_service(env, service.uuid.as_str(), service.primary)
656 .map_err(|e| Error::Network(e.to_string()))?;
657 let mut published = Vec::new();
658
659 for definition in &service.characteristics {
660 let characteristic = ble::new_characteristic(
661 env,
662 definition.uuid.as_str(),
663 definition.properties,
664 definition.permissions,
665 )
666 .map_err(|e| Error::Network(e.to_string()))?;
667
668 if let Some(value) = &definition.value {
669 ble::set_value(env, characteristic, value)
670 .map_err(|e| Error::Network(e.to_string()))?;
671 }
672
673 for d in &definition.descriptors {
674 let descriptor = ble::new_descriptor(env, d.uuid.as_str(), Permissions::READABLE)
675 .map_err(|e| Error::Network(e.to_string()))?;
676 ble::set_value(env, descriptor, &d.value)
677 .map_err(|e| Error::Network(e.to_string()))?;
678 ble::characteristic_add_descriptor(env, characteristic, descriptor)
679 .map_err(|e| Error::Network(e.to_string()))?;
680 }
681
682 let properties = Properties(definition.properties);
684 if properties.notify() || properties.indicate() {
685 let cccd = ble::new_descriptor(
686 env,
687 cccd_uuid().as_str(),
688 Permissions::READABLE | Permissions::WRITEABLE,
689 )
690 .map_err(|e| Error::Network(e.to_string()))?;
691 ble::set_value(env, cccd, &[0x00, 0x00])
692 .map_err(|e| Error::Network(e.to_string()))?;
693 ble::characteristic_add_descriptor(env, characteristic, cccd)
694 .map_err(|e| Error::Network(e.to_string()))?;
695 if let Some(cccd) = Ref::new(env, cccd) {
696 self.inner
697 .cccds
698 .lock()
699 .unwrap()
700 .insert(cccd.key(), definition.uuid);
701 std::mem::forget(cccd);
703 }
704 }
705
706 ble::service_add_characteristic(env, java_service, characteristic)
707 .map_err(|e| Error::Network(e.to_string()))?;
708
709 if let Some(handle) = Ref::new(env, characteristic) {
710 self.inner
711 .published
712 .lock()
713 .unwrap()
714 .insert(handle.key(), definition.uuid);
715 published.push(PublishedCharacteristic {
716 inner: self.inner.clone(),
717 uuid: definition.uuid,
718 handle,
719 });
720 }
721 }
722
723 let rx = {
725 let (tx, rx) = oneshot::channel();
726 self.inner.service_waiters.lock().unwrap().push(tx);
727 rx
728 };
729 ble::server_add_service(env, server.as_ptr(), java_service)
730 .map_err(|e| Error::Network(e.to_string()))?;
731 rx.await
732 .map_err(|_| Error::Aborted("publishing was cancelled".into()))??;
733
734 let handle = Ref::new(env, java_service)
735 .ok_or_else(|| Error::Aborted("the published service vanished".into()))?;
736 Ok(PublishedService {
737 inner: self.inner.clone(),
738 uuid: service.uuid,
739 handle,
740 characteristics: published,
741 })
742 }
743
744 pub fn unpublish_all(&self) {
746 if let (Some(runtime), Some(server)) =
747 (Runtime::get(), self.inner.server.lock().unwrap().clone())
748 {
749 if let Ok(env) = runtime.env() {
750 let _ = ble::server_clear_services(env, server.as_ptr());
751 }
752 }
753 self.inner.published.lock().unwrap().clear();
754 self.inner.cccds.lock().unwrap().clear();
755 self.inner.subscribers.lock().unwrap().clear();
756 }
757
758 pub async fn start_advertising(&self, advertising: Advertising) -> Result<()> {
766 self.inner.require_powered_on().await?;
767 let runtime = Runtime::get()
768 .ok_or_else(|| Error::NotSupported("the Android backend is not started".into()))?;
769 let env = runtime.env().map_err(|e| Error::Network(e.to_string()))?;
770 let adapter = ble::Adapter::open(runtime)
771 .map_err(|_| Error::NotAvailable(Availability::Unsupported))?;
772 let advertiser = adapter
773 .advertiser(env)
774 .map_err(|e| Error::Network(e.to_string()))?;
775 if advertiser.is_null() {
776 return Err(Error::NotSupported(
777 "this device cannot advertise — no BluetoothLeAdvertiser".into(),
778 ));
779 }
780
781 let callback = ble::Callback::new(
782 runtime,
783 "dev.webbluetooth.AdvertiseCallback",
784 crate::advertise_callback_dex(),
785 &crate::bluetooth::advertise_natives(),
786 Arc::new(Sink(Arc::downgrade(&self.inner))),
787 )
788 .map_err(|e| Error::Network(e.to_string()))?;
789
790 let services: Vec<String> = advertising
791 .services
792 .iter()
793 .map(|u| u.as_str().to_owned())
794 .collect();
795
796 let rx = {
797 let (tx, rx) = oneshot::channel();
798 self.inner.advertising_waiters.lock().unwrap().push(tx);
799 rx
800 };
801 ble::start_advertising(
802 env,
803 advertiser,
804 callback.as_ptr(),
805 advertising.local_name.is_some(),
806 &services,
807 true,
808 )
809 .map_err(|e| Error::Network(e.to_string()))?;
810 *self.inner.advertise_callback.lock().unwrap() = Some(callback);
811
812 rx.await
813 .map_err(|_| Error::Aborted("advertising was cancelled".into()))?
814 }
815
816 pub fn stop_advertising(&self) {
818 let Some(callback) = self.inner.advertise_callback.lock().unwrap().take() else {
819 return;
820 };
821 if let Some(runtime) = Runtime::get() {
822 if let Ok(env) = runtime.env() {
823 if let Ok(adapter) = ble::Adapter::open(runtime) {
824 if let Ok(advertiser) = adapter.advertiser(env) {
825 let _ = ble::stop_advertising(env, advertiser, callback.as_ptr());
826 }
827 }
828 }
829 }
830 self.inner.advertising.store(false, Ordering::Release);
831 }
832
833 pub fn is_advertising(&self) -> bool {
835 self.inner.advertising.load(Ordering::Acquire)
836 }
837
838 pub async fn publish_l2cap_channel(
843 &self,
844 encryption_required: bool,
845 ) -> Result<webbluetooth_core::Psm> {
846 self.inner.require_powered_on().await?;
847 let runtime = Runtime::get()
848 .ok_or_else(|| Error::NotSupported("the Android backend is not started".into()))?;
849 let env = runtime.env().map_err(|e| Error::Network(e.to_string()))?;
850 let adapter = ble::Adapter::open(runtime)
851 .map_err(|_| Error::NotAvailable(Availability::Unsupported))?;
852
853 let socket = ble::listen_l2cap(env, adapter.as_ptr(), encryption_required)
854 .map_err(|e| Error::Network(e.to_string()))?;
855 if socket.is_null() {
856 return Err(Error::NotSupported(
857 "listenUsingL2capChannel is unavailable — it needs API 29 or newer".into(),
858 ));
859 }
860 let psm =
861 ble::server_socket_psm(env, socket).map_err(|e| Error::Network(e.to_string()))? as u16;
862 let Some(socket) = Ref::new(env, socket) else {
863 return Err(Error::Network("the listening socket vanished".into()));
864 };
865
866 let stop = Arc::new(AtomicBool::new(false));
867 self.inner
868 .l2cap
869 .lock()
870 .unwrap()
871 .insert(psm, (socket.clone(), stop.clone()));
872
873 let inner = self.inner.clone();
875 std::thread::Builder::new()
876 .name(format!("webbluetooth-l2cap-accept-{psm}"))
877 .spawn(move || {
878 let Some(runtime) = Runtime::get() else {
879 return;
880 };
881 let Ok(env) = runtime.env() else { return };
882 while !stop.load(Ordering::Acquire) {
883 let Ok(accepted) = ble::server_socket_accept(env, socket.as_ptr()) else {
884 break;
885 };
886 if accepted.is_null() {
887 break;
888 }
889 if let Ok(channel) = crate::l2cap::from_accepted(accepted, psm) {
890 inner.send(Request::ChannelOpened(channel));
891 }
892 }
893 runtime.vm().detach();
894 })
895 .map_err(|e| Error::Network(format!("could not start the accept thread: {e}")))?;
896
897 Ok(psm)
898 }
899
900 pub async fn unpublish_l2cap_channel(&self, psm: webbluetooth_core::Psm) -> Result<()> {
902 let Some((socket, stop)) = self.inner.l2cap.lock().unwrap().remove(&psm) else {
903 return Ok(());
904 };
905 stop.store(true, Ordering::Release);
906 if let Some(runtime) = Runtime::get() {
907 if let Ok(env) = runtime.env() {
908 let _ = ble::server_socket_close(env, socket.as_ptr());
910 }
911 }
912 Ok(())
913 }
914
915 pub async fn restored_state(&self) -> Option<RestoredPeripheral> {
917 None
918 }
919}
920
921impl std::fmt::Debug for Peripheral {
922 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
923 f.debug_struct("Peripheral")
924 .field("advertising", &self.is_advertising())
925 .finish()
926 }
927}
928
929pub struct PublishedService {
931 inner: Arc<Inner>,
932 uuid: BluetoothUuid,
933 handle: Ref,
934 characteristics: Vec<PublishedCharacteristic>,
935}
936
937impl PublishedService {
938 pub fn uuid(&self) -> &BluetoothUuid {
939 &self.uuid
940 }
941
942 pub fn characteristics(&self) -> Vec<PublishedCharacteristic> {
943 self.characteristics.to_vec()
944 }
945
946 pub fn characteristic(&self, uuid: impl IntoUuid) -> Option<PublishedCharacteristic> {
947 let uuid = uuid.into_uuid().ok()?;
948 self.characteristics
949 .iter()
950 .find(|c| c.uuid == uuid)
951 .cloned()
952 }
953
954 pub fn unpublish(self) {
956 if let (Some(runtime), Some(server)) =
957 (Runtime::get(), self.inner.server.lock().unwrap().clone())
958 {
959 if let Ok(env) = runtime.env() {
960 let _ = ble::server_remove_service(env, server.as_ptr(), self.handle.as_ptr());
961 }
962 }
963 let mut published = self.inner.published.lock().unwrap();
964 for c in &self.characteristics {
965 published.remove(&c.handle.key());
966 }
967 }
968}
969
970impl std::fmt::Debug for PublishedService {
971 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
972 f.debug_struct("PublishedService")
973 .field("uuid", &self.uuid.as_str())
974 .field("characteristics", &self.characteristics.len())
975 .finish()
976 }
977}
978
979#[derive(Clone)]
981pub struct PublishedCharacteristic {
982 inner: Arc<Inner>,
983 uuid: BluetoothUuid,
984 handle: Ref,
985}
986
987impl PublishedCharacteristic {
988 pub fn uuid(&self) -> &BluetoothUuid {
989 &self.uuid
990 }
991
992 pub fn subscribers(&self) -> Vec<RemoteCentral> {
996 self.inner
997 .subscribers
998 .lock()
999 .unwrap()
1000 .get(&self.uuid)
1001 .cloned()
1002 .unwrap_or_default()
1003 }
1004
1005 pub fn try_notify(&self, value: &[u8]) -> bool {
1010 self.try_notify_centrals(value, &self.subscribers())
1011 }
1012
1013 pub fn try_notify_centrals(&self, value: &[u8], centrals: &[RemoteCentral]) -> bool {
1015 let (Some(runtime), Some(server)) =
1016 (Runtime::get(), self.inner.server.lock().unwrap().clone())
1017 else {
1018 return false;
1019 };
1020 let Ok(env) = runtime.env() else { return false };
1021
1022 let indicate = false;
1023 let mut all = true;
1024 for central in centrals {
1025 all &= ble::server_notify(
1026 env,
1027 server.as_ptr(),
1028 central.device.as_ptr(),
1029 self.handle.as_ptr(),
1030 indicate,
1031 value,
1032 )
1033 .unwrap_or(false);
1034 }
1035 all
1036 }
1037
1038 pub async fn notify(&self, value: &[u8]) -> Result<()> {
1040 let centrals = self.subscribers();
1041 if centrals.is_empty() {
1042 return Ok(());
1043 }
1044 loop {
1045 if self.try_notify_centrals(value, ¢rals) {
1046 return Ok(());
1047 }
1048 let rx = {
1049 let (tx, rx) = oneshot::channel();
1050 self.inner.ready_waiters.lock().unwrap().push(tx);
1051 rx
1052 };
1053 rx.await
1054 .map_err(|_| Error::Aborted("notification was cancelled".into()))?;
1055 }
1056 }
1057}
1058
1059impl std::fmt::Debug for PublishedCharacteristic {
1060 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1061 f.debug_struct("PublishedCharacteristic")
1062 .field("uuid", &self.uuid.as_str())
1063 .field("subscribers", &self.subscribers().len())
1064 .finish()
1065 }
1066}
1067
1068#[cfg(test)]
1071mod tests {
1072 use super::*;
1073 use webbluetooth_core::peripheral::{Characteristic, Descriptor};
1074 use webbluetooth_core::uuid::characteristics;
1075
1076 #[test]
1077 fn a_fixed_value_may_also_be_writable() {
1078 assert!(Characteristic::new(characteristics::BATTERY_LEVEL)
1081 .unwrap()
1082 .read()
1083 .write()
1084 .value([50])
1085 .validate()
1086 .is_ok());
1087 }
1088
1089 #[test]
1090 fn a_characteristic_still_needs_a_property() {
1091 assert!(Characteristic::new(characteristics::BATTERY_LEVEL)
1092 .unwrap()
1093 .validate()
1094 .is_err());
1095 }
1096
1097 #[test]
1098 fn the_cccd_cannot_be_declared_by_hand() {
1099 let err = Descriptor {
1102 uuid: cccd_uuid(),
1103 value: vec![0, 0],
1104 is_string: false,
1105 }
1106 .validate()
1107 .unwrap_err();
1108 assert!(err.to_string().contains("automatically"), "got {err}");
1109 }
1110
1111 #[test]
1112 fn any_other_descriptor_is_accepted() {
1113 assert!(Descriptor::user_description("x").validate().is_ok());
1115 assert!(Descriptor::presentation_format([0u8; 7]).validate().is_ok());
1116 assert!(Descriptor {
1117 uuid: BluetoothUuid::from_u16(0x2908),
1118 value: vec![0],
1119 is_string: false,
1120 }
1121 .validate()
1122 .is_ok());
1123 assert!(Descriptor {
1125 uuid: BluetoothUuid::from_u16(0x2901),
1126 value: Vec::new(),
1127 is_string: true,
1128 }
1129 .validate()
1130 .is_err());
1131 }
1132
1133 #[test]
1134 fn advertise_errors_are_explained() {
1135 assert!(describe_advertise_error(1).contains("31 bytes"));
1136 assert!(describe_advertise_error(5).contains("does not support"));
1137 }
1138}