1use crate::bluez::{interfaces, Bluez, Event, EventSink};
33use crate::dbus::connection::ObjectHandler;
34use crate::dbus::{Message, Value};
35use futures_core::Stream;
36use std::collections::HashMap;
37use std::pin::Pin;
38use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
39use std::sync::mpsc::{channel, Sender};
40use std::sync::{Arc, Mutex};
41use std::task::{Context, Poll};
42use std::time::Duration;
43use webbluetooth_core::error::{Availability, Error, Result};
44use webbluetooth_core::gatt::CharacteristicProperties as Properties;
45use webbluetooth_core::peripheral::{Advertising, AttError, RestoredPeripheral, Service, Write};
46use webbluetooth_core::uuid::{BluetoothUuid, IntoUuid};
47
48const ROOT: &str = "/io/webbluetooth/peripheral";
51const ADVERTISEMENT: &str = "/io/webbluetooth/peripheral/advertisement0";
52
53const DBUS_PROPERTIES: &str = "org.freedesktop.DBus.Properties";
54const ANSWER_TIMEOUT: Duration = Duration::from_secs(10);
59
60const DEFAULT_NOTIFY_LEN: usize = 20;
62
63fn option_u64(options: Option<&Value>, key: &str) -> Option<u64> {
65 options?.as_map().get(key)?.peel().as_u64()
66}
67
68fn flags_for(properties: Properties) -> Vec<String> {
70 let mut flags = Vec::new();
71 if properties.read() {
72 flags.push("read".to_string());
73 }
74 if properties.write() {
75 flags.push("write".to_string());
76 }
77 if properties.write_without_response() {
78 flags.push("write-without-response".to_string());
79 }
80 if properties.notify() {
81 flags.push("notify".to_string());
82 }
83 if properties.indicate() {
84 flags.push("indicate".to_string());
85 }
86 flags
87}
88
89#[derive(Debug, Clone)]
95pub struct RemoteCentral {
96 id: String,
97 mtu: usize,
98}
99
100impl RemoteCentral {
101 fn from_options(options: Option<&Value>, fallback_mtu: usize) -> Self {
102 let device = options.map(|o| o.as_map()).and_then(|m| {
103 m.get("device")
104 .and_then(|v| v.peel().as_str().map(str::to_owned))
105 });
106 let id = device
108 .as_deref()
109 .and_then(|path| path.rsplit('/').next())
110 .and_then(|last| last.strip_prefix("dev_"))
111 .map(|a| a.replace('_', ":"))
112 .or(device)
113 .unwrap_or_else(|| "unknown".to_string());
114 let mtu = option_u64(options, "mtu")
116 .map(|v| (v as usize).saturating_sub(3))
117 .unwrap_or(fallback_mtu);
118 Self { id, mtu }
119 }
120
121 pub fn id(&self) -> &str {
122 &self.id
123 }
124
125 pub fn max_notification_length(&self) -> usize {
127 self.mtu
128 }
129}
130
131pub struct ReadRequest {
133 characteristic: BluetoothUuid,
134 central: RemoteCentral,
135 offset: usize,
136 answer: Option<Sender<std::result::Result<Vec<u8>, AttError>>>,
137}
138
139impl ReadRequest {
140 pub fn characteristic(&self) -> &BluetoothUuid {
141 &self.characteristic
142 }
143
144 pub fn central(&self) -> &RemoteCentral {
145 &self.central
146 }
147
148 pub fn offset(&self) -> usize {
150 self.offset
151 }
152
153 pub fn respond(mut self, value: &[u8]) -> Result<()> {
155 let Some(answer) = self.answer.take() else {
156 return Err(Error::InvalidState("this read was already answered".into()));
157 };
158 answer
159 .send(Ok(value.to_vec()))
160 .map_err(|_| Error::InvalidState("the central stopped waiting".into()))
161 }
162
163 pub fn reject(mut self, error: AttError) {
165 if let Some(answer) = self.answer.take() {
166 let _ = answer.send(Err(error));
167 }
168 }
169}
170
171impl Drop for ReadRequest {
172 fn drop(&mut self) {
173 if let Some(answer) = self.answer.take() {
176 let _ = answer.send(Err(AttError::UnlikelyError));
177 }
178 }
179}
180
181impl std::fmt::Debug for ReadRequest {
182 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183 f.debug_struct("ReadRequest")
184 .field("characteristic", &self.characteristic.as_str())
185 .field("central", &self.central.id)
186 .field("offset", &self.offset)
187 .finish()
188 }
189}
190
191pub struct WriteRequest {
193 writes: Vec<Write>,
194 central: RemoteCentral,
195 answer: Option<Sender<std::result::Result<(), AttError>>>,
196}
197
198impl WriteRequest {
199 pub fn writes(&self) -> &[Write] {
200 &self.writes
201 }
202
203 pub fn central(&self) -> &RemoteCentral {
204 &self.central
205 }
206
207 pub fn accept(mut self) {
209 if let Some(answer) = self.answer.take() {
210 let _ = answer.send(Ok(()));
211 }
212 }
213
214 pub fn reject_all(mut self, error: AttError) {
216 if let Some(answer) = self.answer.take() {
217 let _ = answer.send(Err(error));
218 }
219 }
220}
221
222impl Drop for WriteRequest {
223 fn drop(&mut self) {
224 if let Some(answer) = self.answer.take() {
225 let _ = answer.send(Err(AttError::UnlikelyError));
226 }
227 }
228}
229
230impl std::fmt::Debug for WriteRequest {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 f.debug_struct("WriteRequest")
233 .field("writes", &self.writes.len())
234 .field("central", &self.central.id)
235 .finish()
236 }
237}
238
239#[derive(Debug)]
241pub enum Request {
242 Read(ReadRequest),
243 Write(WriteRequest),
244 Subscribed {
245 central: RemoteCentral,
246 characteristic: BluetoothUuid,
247 },
248 Unsubscribed {
249 central: RemoteCentral,
250 characteristic: BluetoothUuid,
251 },
252 ReadyToNotify,
259 ChannelOpened(crate::l2cap::L2capChannel),
261}
262
263const REQUEST_BACKLOG: usize = 1024;
266
267pub struct Requests {
268 rx: webbluetooth_core::backlog::Receiver<Request>,
269}
270
271impl Requests {
272 pub fn lost(&self) -> u64 {
281 self.rx.lost()
282 }
283}
284
285impl Stream for Requests {
286 type Item = Request;
287 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Request>> {
288 Pin::new(&mut self.rx).poll_next(cx)
289 }
290}
291
292struct CharacteristicState {
296 uuid: BluetoothUuid,
297 path: String,
298 flags: Vec<String>,
299 value: Mutex<Vec<u8>>,
302 subscribers: Mutex<Vec<RemoteCentral>>,
304 descriptors: Vec<DescriptorState>,
305}
306
307struct DescriptorState {
308 uuid: BluetoothUuid,
309 path: String,
310 value: Vec<u8>,
311}
312
313struct ServiceState {
314 uuid: BluetoothUuid,
315 path: String,
316 primary: bool,
317 characteristics: Vec<Arc<CharacteristicState>>,
318}
319
320struct Inner {
321 bluez: Option<Arc<Bluez>>,
322 to_app: webbluetooth_core::backlog::Sender<Request>,
323 services: Mutex<Vec<Arc<ServiceState>>>,
324 registered: AtomicBool,
325 advertising: AtomicBool,
326 next_index: AtomicUsize,
327 advertisement: Mutex<Vec<(Value, Value)>>,
330 l2cap_listeners: Mutex<HashMap<webbluetooth_core::Psm, crate::l2cap::L2capListenerHandle>>,
331}
332
333impl Inner {
334 fn adapter(&self) -> Result<(Arc<Bluez>, String)> {
335 let bluez = self
336 .bluez
337 .clone()
338 .ok_or(Error::NotAvailable(Availability::Unsupported))?;
339 let adapter = bluez
340 .adapter()
341 .ok_or(Error::NotAvailable(Availability::Unsupported))?;
342 Ok((bluez, adapter))
343 }
344
345 fn characteristic_at(&self, path: &str) -> Option<Arc<CharacteristicState>> {
346 self.services
347 .lock()
348 .unwrap()
349 .iter()
350 .flat_map(|s| s.characteristics.clone())
351 .find(|c| c.path == path)
352 }
353
354 fn descriptor_at(&self, path: &str) -> Option<(Arc<CharacteristicState>, Vec<u8>)> {
355 for service in self.services.lock().unwrap().iter() {
356 for characteristic in &service.characteristics {
357 for descriptor in &characteristic.descriptors {
358 if descriptor.path == path {
359 return Some((characteristic.clone(), descriptor.value.clone()));
360 }
361 }
362 }
363 }
364 None
365 }
366
367 fn managed_objects(&self) -> Value {
369 let mut objects: Vec<(Value, Value)> = Vec::new();
370 for service in self.services.lock().unwrap().iter() {
371 objects.push((
372 Value::ObjectPath(service.path.clone()),
373 interfaces_of(vec![(
374 interfaces::SERVICE,
375 properties(vec![
376 ("UUID", Value::Str(service.uuid.as_str().to_owned())),
377 ("Primary", Value::Bool(service.primary)),
378 ]),
379 )]),
380 ));
381 for characteristic in &service.characteristics {
382 objects.push((
383 Value::ObjectPath(characteristic.path.clone()),
384 interfaces_of(vec![(
385 interfaces::CHARACTERISTIC,
386 properties(vec![
387 ("UUID", Value::Str(characteristic.uuid.as_str().to_owned())),
388 ("Service", Value::ObjectPath(service.path.clone())),
389 (
390 "Flags",
391 Value::string_array(characteristic.flags.iter().cloned()),
392 ),
393 ]),
394 )]),
395 ));
396 for descriptor in &characteristic.descriptors {
397 objects.push((
398 Value::ObjectPath(descriptor.path.clone()),
399 interfaces_of(vec![(
400 interfaces::DESCRIPTOR,
401 properties(vec![
402 ("UUID", Value::Str(descriptor.uuid.as_str().to_owned())),
403 (
404 "Characteristic",
405 Value::ObjectPath(characteristic.path.clone()),
406 ),
407 ("Flags", Value::string_array(["read".to_string()])),
408 ]),
409 )]),
410 ));
411 }
412 }
413 }
414 dict_of("{oa{sa{sv}}}", objects)
415 }
416}
417
418fn dict_of(element: &str, entries: Vec<(Value, Value)>) -> Value {
419 Value::Array {
420 element: element.into(),
421 items: entries
422 .into_iter()
423 .map(|(k, v)| Value::DictEntry(Box::new(k), Box::new(v)))
424 .collect(),
425 }
426}
427
428fn properties(entries: Vec<(&str, Value)>) -> Value {
430 dict_of(
431 "{sv}",
432 entries
433 .into_iter()
434 .map(|(name, value)| (Value::Str(name.to_owned()), Value::Variant(Box::new(value))))
435 .collect(),
436 )
437}
438
439fn interfaces_of(entries: Vec<(&str, Value)>) -> Value {
441 dict_of(
442 "{sa{sv}}",
443 entries
444 .into_iter()
445 .map(|(interface, props)| (Value::Str(interface.to_owned()), props))
446 .collect(),
447 )
448}
449
450struct Application {
453 inner: Arc<Inner>,
454}
455
456impl ObjectHandler for Application {
457 fn handle(&self, call: &Message) -> std::result::Result<Vec<Value>, (String, String)> {
458 let path = call.path.clone().unwrap_or_default();
459 let interface = call.interface.clone().unwrap_or_default();
460 let member = call.member.clone().unwrap_or_default();
461
462 match (interface.as_str(), member.as_str()) {
463 (interfaces::OBJECT_MANAGER, "GetManagedObjects") => {
464 Ok(vec![self.inner.managed_objects()])
465 }
466
467 (DBUS_PROPERTIES, "GetAll") => Ok(vec![self.properties_of(&path)]),
468
469 (DBUS_PROPERTIES, "Get") => {
470 let name = call.arg(1).and_then(Value::as_str).unwrap_or_default();
471 self.property(&path, name)
472 .map(|v| vec![Value::Variant(Box::new(v))])
473 .ok_or_else(|| {
474 (
475 "org.freedesktop.DBus.Error.InvalidArgs".to_string(),
476 format!("no property {name} at {path}"),
477 )
478 })
479 }
480
481 (interfaces::CHARACTERISTIC, "ReadValue") => self.read(&path, call.arg(0)),
482 (interfaces::CHARACTERISTIC, "WriteValue") => {
483 self.write(&path, call.arg(0), call.arg(1))
484 }
485 (interfaces::CHARACTERISTIC, "StartNotify") => self.set_subscribed(&path, true),
486 (interfaces::CHARACTERISTIC, "StopNotify") => self.set_subscribed(&path, false),
487
488 (interfaces::DESCRIPTOR, "ReadValue") => match self.inner.descriptor_at(&path) {
491 Some((_, value)) => Ok(vec![Value::bytes(&value)]),
492 None => Err((
493 "org.bluez.Error.Failed".to_string(),
494 format!("no descriptor at {path}"),
495 )),
496 },
497
498 (interfaces::LE_ADVERTISEMENT, "Release") => Ok(Vec::new()),
501
502 _ => Err((
503 "org.freedesktop.DBus.Error.UnknownMethod".to_string(),
504 format!("{interface}.{member} is not implemented"),
505 )),
506 }
507 }
508}
509
510impl Application {
511 fn properties_of(&self, path: &str) -> Value {
512 if path == ADVERTISEMENT {
513 return dict_of("{sv}", self.inner.advertisement.lock().unwrap().clone());
516 }
517 if let Some(characteristic) = self.inner.characteristic_at(path) {
518 return properties(vec![
519 ("UUID", Value::Str(characteristic.uuid.as_str().to_owned())),
520 (
521 "Flags",
522 Value::string_array(characteristic.flags.iter().cloned()),
523 ),
524 ("Value", Value::bytes(&characteristic.value.lock().unwrap())),
525 ]);
526 }
527 properties(Vec::new())
528 }
529
530 fn property(&self, path: &str, name: &str) -> Option<Value> {
531 let characteristic = self.inner.characteristic_at(path)?;
532 match name {
533 "UUID" => Some(Value::Str(characteristic.uuid.as_str().to_owned())),
534 "Value" => Some(Value::bytes(&characteristic.value.lock().unwrap())),
535 "Flags" => Some(Value::string_array(characteristic.flags.iter().cloned())),
536 _ => None,
537 }
538 }
539
540 fn read(
542 &self,
543 path: &str,
544 options: Option<&Value>,
545 ) -> std::result::Result<Vec<Value>, (String, String)> {
546 let Some(characteristic) = self.inner.characteristic_at(path) else {
547 return Err((
548 "org.bluez.Error.Failed".to_string(),
549 format!("no characteristic at {path}"),
550 ));
551 };
552 let central = RemoteCentral::from_options(options, DEFAULT_NOTIFY_LEN);
553 let offset = option_u64(options, "offset").unwrap_or(0) as usize;
554
555 let (tx, rx) = channel();
556 let request = Request::Read(ReadRequest {
557 characteristic: characteristic.uuid,
558 central,
559 offset,
560 answer: Some(tx),
561 });
562 if self.inner.to_app.send(request).is_err() {
563 return Ok(vec![Value::bytes(&characteristic.value.lock().unwrap())]);
566 }
567
568 match rx.recv_timeout(ANSWER_TIMEOUT) {
569 Ok(Ok(value)) => {
570 *characteristic.value.lock().unwrap() = value.clone();
571 Ok(vec![Value::bytes(&value)])
572 }
573 Ok(Err(error)) => Err((att_error_name(error), format!("read refused: {error:?}"))),
574 Err(reason) => Err((
575 "org.bluez.Error.Failed".to_string(),
576 format!("the application did not answer the read: {reason}"),
577 )),
578 }
579 }
580
581 fn write(
582 &self,
583 path: &str,
584 value: Option<&Value>,
585 options: Option<&Value>,
586 ) -> std::result::Result<Vec<Value>, (String, String)> {
587 let Some(characteristic) = self.inner.characteristic_at(path) else {
588 return Err((
589 "org.bluez.Error.Failed".to_string(),
590 format!("no characteristic at {path}"),
591 ));
592 };
593 let written: Vec<u8> = value.and_then(Value::as_bytes).unwrap_or_default();
594 let central = RemoteCentral::from_options(options, DEFAULT_NOTIFY_LEN);
595 let offset = option_u64(options, "offset").unwrap_or(0) as usize;
596
597 let (tx, rx) = channel();
598 let request = Request::Write(WriteRequest {
599 writes: vec![Write {
600 characteristic: characteristic.uuid,
601 offset,
602 value: written.clone(),
603 }],
604 central,
605 answer: Some(tx),
606 });
607 if self.inner.to_app.send(request).is_err() {
608 *characteristic.value.lock().unwrap() = written;
609 return Ok(Vec::new());
610 }
611
612 match rx.recv_timeout(ANSWER_TIMEOUT) {
613 Ok(Ok(())) => {
614 *characteristic.value.lock().unwrap() = written;
615 Ok(Vec::new())
616 }
617 Ok(Err(error)) => Err((att_error_name(error), format!("write refused: {error:?}"))),
618 Err(reason) => Err((
619 "org.bluez.Error.Failed".to_string(),
620 format!("the application did not answer the write: {reason}"),
621 )),
622 }
623 }
624
625 fn set_subscribed(
628 &self,
629 path: &str,
630 subscribed: bool,
631 ) -> std::result::Result<Vec<Value>, (String, String)> {
632 let Some(characteristic) = self.inner.characteristic_at(path) else {
633 return Err((
634 "org.bluez.Error.Failed".to_string(),
635 format!("no characteristic at {path}"),
636 ));
637 };
638 let central = RemoteCentral {
641 id: "subscribed".to_string(),
642 mtu: DEFAULT_NOTIFY_LEN,
643 };
644 {
645 let mut subscribers = characteristic.subscribers.lock().unwrap();
646 if subscribed {
647 subscribers.push(central.clone());
648 } else {
649 subscribers.clear();
650 }
651 }
652 let request = if subscribed {
653 Request::Subscribed {
654 central,
655 characteristic: characteristic.uuid,
656 }
657 } else {
658 Request::Unsubscribed {
659 central,
660 characteristic: characteristic.uuid,
661 }
662 };
663 let _ = self.inner.to_app.send(request);
664 Ok(Vec::new())
665 }
666}
667
668fn att_error_name(error: AttError) -> String {
670 match error {
675 AttError::ReadNotPermitted | AttError::WriteNotPermitted => "org.bluez.Error.NotPermitted",
676 AttError::InsufficientAuthentication | AttError::InsufficientEncryption => {
677 "org.bluez.Error.NotPaired"
678 }
679 AttError::InsufficientAuthorization => "org.bluez.Error.NotAuthorized",
680 AttError::RequestNotSupported => "org.bluez.Error.NotSupported",
681 AttError::InvalidOffset => "org.bluez.Error.InvalidOffset",
682 AttError::InvalidAttributeValueLength => "org.bluez.Error.InvalidValueLength",
683 _ => "org.bluez.Error.Failed",
684 }
685 .to_string()
686}
687
688struct Discard;
690impl EventSink for Discard {
691 fn emit(&self, _event: Event) {}
692}
693
694#[derive(Clone)]
698pub struct Peripheral {
699 inner: Arc<Inner>,
700}
701
702impl Peripheral {
703 pub fn new() -> (Self, Requests) {
705 let (to_app, rx) = webbluetooth_core::backlog::bounded(
710 REQUEST_BACKLOG,
711 webbluetooth_core::backlog::Overflow::KeepOldest,
712 );
713 let bluez = Bluez::new(Arc::new(Discard)).ok().map(Arc::new);
714 let inner = Arc::new(Inner {
715 bluez,
716 to_app,
717 services: Mutex::new(Vec::new()),
718 registered: AtomicBool::new(false),
719 advertising: AtomicBool::new(false),
720 next_index: AtomicUsize::new(0),
721 advertisement: Mutex::new(Vec::new()),
722 l2cap_listeners: Mutex::new(HashMap::new()),
723 });
724 if let Some(bluez) = &inner.bluez {
725 bluez.export(
726 ROOT,
727 Arc::new(Application {
728 inner: inner.clone(),
729 }),
730 );
731 }
732 (Self { inner }, Requests { rx })
733 }
734
735 pub fn with_restoration(_restoration: webbluetooth_core::Restoration) -> (Self, Requests) {
737 Self::new()
738 }
739
740 pub async fn availability(&self) -> std::result::Result<(), Availability> {
742 let Some(bluez) = &self.inner.bluez else {
743 return Err(Availability::Unauthorized);
744 };
745 if bluez.adapter().is_none() {
746 return Err(Availability::Unsupported);
747 }
748 if !bluez.is_powered() {
749 return Err(Availability::PoweredOff);
750 }
751 Ok(())
752 }
753
754 pub async fn publish(&self, service: Service) -> Result<PublishedService> {
760 service.validate()?;
761 let (bluez, adapter) = self.inner.adapter()?;
762 if !bluez.is_powered() {
763 return Err(Error::NotAvailable(Availability::PoweredOff));
764 }
765
766 let index = self.inner.next_index.fetch_add(1, Ordering::Relaxed);
767 let service_path = format!("{ROOT}/service{index}");
768 let mut characteristics = Vec::new();
769
770 for (i, definition) in service.characteristics.iter().enumerate() {
771 let path = format!("{service_path}/char{i}");
772 let descriptors = definition
773 .descriptors
774 .iter()
775 .enumerate()
776 .map(|(j, d)| DescriptorState {
777 uuid: d.uuid,
778 path: format!("{path}/desc{j}"),
779 value: d.value.clone(),
780 })
781 .collect();
782 characteristics.push(Arc::new(CharacteristicState {
783 uuid: definition.uuid,
784 path,
785 flags: flags_for(Properties(definition.properties)),
786 value: Mutex::new(definition.value.clone().unwrap_or_default()),
787 subscribers: Mutex::new(Vec::new()),
788 descriptors,
789 }));
790 }
791
792 let state = Arc::new(ServiceState {
793 uuid: service.uuid,
794 path: service_path,
795 primary: service.primary,
796 characteristics,
797 });
798 self.inner.services.lock().unwrap().push(state.clone());
799
800 if self.inner.registered.swap(true, Ordering::SeqCst) {
802 let _ = call(
803 &bluez,
804 &adapter,
805 interfaces::GATT_MANAGER,
806 "UnregisterApplication",
807 vec![Value::ObjectPath(ROOT.to_string())],
808 );
809 }
810 call(
811 &bluez,
812 &adapter,
813 interfaces::GATT_MANAGER,
814 "RegisterApplication",
815 vec![Value::ObjectPath(ROOT.to_string()), properties(Vec::new())],
816 )
817 .inspect_err(|_| {
818 self.inner
821 .services
822 .lock()
823 .unwrap()
824 .retain(|s| s.path != state.path);
825 self.inner.registered.store(false, Ordering::SeqCst);
826 })?;
827
828 Ok(PublishedService {
829 inner: self.inner.clone(),
830 state,
831 })
832 }
833
834 pub fn unpublish_all(&self) {
836 self.inner.services.lock().unwrap().clear();
837 if self.inner.registered.swap(false, Ordering::SeqCst) {
838 if let Ok((bluez, adapter)) = self.inner.adapter() {
839 let _ = call(
840 &bluez,
841 &adapter,
842 interfaces::GATT_MANAGER,
843 "UnregisterApplication",
844 vec![Value::ObjectPath(ROOT.to_string())],
845 );
846 }
847 }
848 }
849
850 pub async fn start_advertising(&self, advertising: Advertising) -> Result<()> {
852 let (bluez, adapter) = self.inner.adapter()?;
853 if self.inner.advertising.load(Ordering::SeqCst) {
854 self.stop_advertising();
855 }
856
857 let mut entries: Vec<(Value, Value)> = vec![(
860 Value::Str("Type".into()),
861 Value::Variant(Box::new(Value::Str("peripheral".into()))),
862 )];
863 if !advertising.services.is_empty() {
864 entries.push((
865 Value::Str("ServiceUUIDs".into()),
866 Value::Variant(Box::new(Value::string_array(
867 advertising.services.iter().map(|u| u.as_str().to_owned()),
868 ))),
869 ));
870 }
871 if let Some(name) = &advertising.local_name {
872 entries.push((
873 Value::Str("LocalName".into()),
874 Value::Variant(Box::new(Value::Str(name.clone()))),
875 ));
876 }
877 *self.inner.advertisement.lock().unwrap() = entries;
878
879 bluez.export(
880 ADVERTISEMENT,
881 Arc::new(Application {
882 inner: self.inner.clone(),
883 }),
884 );
885 call(
886 &bluez,
887 &adapter,
888 interfaces::LE_ADVERTISING_MANAGER,
889 "RegisterAdvertisement",
890 vec![
891 Value::ObjectPath(ADVERTISEMENT.to_string()),
892 properties(Vec::new()),
893 ],
894 )?;
895 self.inner.advertising.store(true, Ordering::SeqCst);
896 Ok(())
897 }
898
899 pub fn stop_advertising(&self) {
901 if !self.inner.advertising.swap(false, Ordering::SeqCst) {
902 return;
903 }
904 if let Ok((bluez, adapter)) = self.inner.adapter() {
905 let _ = call(
906 &bluez,
907 &adapter,
908 interfaces::LE_ADVERTISING_MANAGER,
909 "UnregisterAdvertisement",
910 vec![Value::ObjectPath(ADVERTISEMENT.to_string())],
911 );
912 }
913 }
914
915 pub fn is_advertising(&self) -> bool {
916 self.inner.advertising.load(Ordering::SeqCst)
917 }
918
919 pub async fn publish_l2cap_channel(
921 &self,
922 _encryption_required: bool,
923 ) -> Result<webbluetooth_core::Psm> {
924 let (psm, listener) = crate::l2cap::listen(0)?;
925 let sender = self.inner.to_app.clone();
926 let handle = listener.spawn(move |channel| {
927 let request = match channel {
928 Ok(channel) => Request::ChannelOpened(channel),
929 Err(error) => {
930 eprintln!("LE L2CAP listener error: {error}");
931 return;
932 }
933 };
934 let _ = sender.send(request);
935 })?;
936 self.inner
937 .l2cap_listeners
938 .lock()
939 .unwrap()
940 .insert(psm, handle);
941 Ok(psm)
942 }
943
944 pub async fn unpublish_l2cap_channel(&self, psm: webbluetooth_core::Psm) -> Result<()> {
945 self.inner
946 .l2cap_listeners
947 .lock()
948 .unwrap()
949 .remove(&psm)
950 .ok_or_else(|| Error::NotFound(format!("no published L2CAP channel on PSM {psm}")))?;
951 Ok(())
952 }
953
954 pub async fn restored_state(&self) -> Option<RestoredPeripheral> {
956 None
957 }
958}
959
960impl std::fmt::Debug for Peripheral {
961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962 f.debug_struct("Peripheral")
963 .field("services", &self.inner.services.lock().unwrap().len())
964 .field("advertising", &self.is_advertising())
965 .finish()
966 }
967}
968
969fn call(
970 bluez: &Arc<Bluez>,
971 path: &str,
972 interface: &str,
973 member: &str,
974 body: Vec<Value>,
975) -> Result<Message> {
976 bluez
977 .call(path, interface, member, body)
978 .map_err(|e| Error::Network(format!("{interface}.{member} failed: {e}")))
979}
980
981pub struct PublishedService {
985 inner: Arc<Inner>,
986 state: Arc<ServiceState>,
987}
988
989impl PublishedService {
990 pub fn uuid(&self) -> &BluetoothUuid {
991 &self.state.uuid
992 }
993
994 pub fn characteristics(&self) -> Vec<PublishedCharacteristic> {
995 self.state
996 .characteristics
997 .iter()
998 .map(|c| PublishedCharacteristic {
999 inner: self.inner.clone(),
1000 state: c.clone(),
1001 })
1002 .collect()
1003 }
1004
1005 pub fn characteristic(&self, uuid: impl IntoUuid) -> Option<PublishedCharacteristic> {
1006 let uuid = uuid.into_uuid().ok()?;
1007 self.state
1008 .characteristics
1009 .iter()
1010 .find(|c| c.uuid == uuid)
1011 .map(|c| PublishedCharacteristic {
1012 inner: self.inner.clone(),
1013 state: c.clone(),
1014 })
1015 }
1016
1017 pub fn unpublish(self) {
1022 self.inner
1023 .services
1024 .lock()
1025 .unwrap()
1026 .retain(|s| s.path != self.state.path);
1027 if let Ok((bluez, adapter)) = self.inner.adapter() {
1028 let _ = call(
1029 &bluez,
1030 &adapter,
1031 interfaces::GATT_MANAGER,
1032 "UnregisterApplication",
1033 vec![Value::ObjectPath(ROOT.to_string())],
1034 );
1035 let empty = self.inner.services.lock().unwrap().is_empty();
1036 if empty {
1037 self.inner.registered.store(false, Ordering::SeqCst);
1038 } else {
1039 let _ = call(
1040 &bluez,
1041 &adapter,
1042 interfaces::GATT_MANAGER,
1043 "RegisterApplication",
1044 vec![Value::ObjectPath(ROOT.to_string()), properties(Vec::new())],
1045 );
1046 }
1047 }
1048 }
1049}
1050
1051impl std::fmt::Debug for PublishedService {
1052 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1053 f.debug_struct("PublishedService")
1054 .field("uuid", &self.state.uuid.as_str())
1055 .field("characteristics", &self.state.characteristics.len())
1056 .finish()
1057 }
1058}
1059
1060#[derive(Clone)]
1062pub struct PublishedCharacteristic {
1063 inner: Arc<Inner>,
1064 state: Arc<CharacteristicState>,
1065}
1066
1067impl PublishedCharacteristic {
1068 pub fn uuid(&self) -> &BluetoothUuid {
1069 &self.state.uuid
1070 }
1071
1072 pub fn subscribers(&self) -> Vec<RemoteCentral> {
1078 self.state.subscribers.lock().unwrap().clone()
1079 }
1080
1081 pub fn try_notify(&self, value: &[u8]) -> bool {
1088 *self.state.value.lock().unwrap() = value.to_vec();
1089 if self.state.subscribers.lock().unwrap().is_empty() {
1090 return false;
1091 }
1092 let Some(bluez) = &self.inner.bluez else {
1093 return false;
1094 };
1095 let signal = Message::signal(&self.state.path, DBUS_PROPERTIES, "PropertiesChanged")
1096 .with_body(vec![
1097 Value::Str(interfaces::CHARACTERISTIC.to_string()),
1098 properties(vec![("Value", Value::bytes(value))]),
1099 Value::string_array(Vec::<String>::new()),
1100 ]);
1101 bluez.connection().send(signal).is_ok()
1102 }
1103
1104 pub async fn notify(&self, value: &[u8]) -> Result<()> {
1106 if self.try_notify(value) {
1107 return Ok(());
1108 }
1109 if self.state.subscribers.lock().unwrap().is_empty() {
1110 return Err(Error::InvalidState(format!(
1111 "nothing is subscribed to {}",
1112 self.state.uuid
1113 )));
1114 }
1115 Err(Error::Network(
1116 "could not emit the value change on the bus".into(),
1117 ))
1118 }
1119}
1120
1121impl std::fmt::Debug for PublishedCharacteristic {
1122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1123 f.debug_struct("PublishedCharacteristic")
1124 .field("uuid", &self.state.uuid.as_str())
1125 .field("subscribers", &self.subscribers().len())
1126 .finish()
1127 }
1128}