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