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 identified: bool,
101}
102
103impl RemoteCentral {
104 fn from_options(options: Option<&Value>, fallback_mtu: usize) -> Self {
105 let device = options.map(|o| o.as_map()).and_then(|m| {
106 m.get("device")
107 .and_then(|v| v.peel().as_str().map(str::to_owned))
108 });
109 let identified = device.is_some();
110 let id = device
112 .as_deref()
113 .and_then(|path| path.rsplit('/').next())
114 .and_then(|last| last.strip_prefix("dev_"))
115 .map(|a| a.replace('_', ":"))
116 .or(device)
117 .unwrap_or_else(|| "unknown".to_string());
118 let mtu = option_u64(options, "mtu")
120 .map(|v| (v as usize).saturating_sub(3))
121 .unwrap_or(fallback_mtu);
122 Self { id, mtu, identified }
123 }
124
125 pub fn id(&self) -> &str {
126 &self.id
127 }
128
129 pub fn is_identified(&self) -> bool {
136 self.identified
137 }
138
139 pub fn max_notification_length(&self) -> usize {
141 self.mtu
142 }
143}
144
145pub struct ReadRequest {
147 characteristic: BluetoothUuid,
148 central: RemoteCentral,
149 offset: usize,
150 answer: Option<Sender<std::result::Result<Vec<u8>, AttError>>>,
151}
152
153impl ReadRequest {
154 pub fn characteristic(&self) -> &BluetoothUuid {
155 &self.characteristic
156 }
157
158 pub fn central(&self) -> &RemoteCentral {
159 &self.central
160 }
161
162 pub fn offset(&self) -> usize {
164 self.offset
165 }
166
167 pub fn respond(mut self, value: &[u8]) -> Result<()> {
169 let Some(answer) = self.answer.take() else {
170 return Err(Error::InvalidState("this read was already answered".into()));
171 };
172 answer
173 .send(Ok(value.to_vec()))
174 .map_err(|_| Error::InvalidState("the central stopped waiting".into()))
175 }
176
177 pub fn reject(mut self, error: AttError) {
179 if let Some(answer) = self.answer.take() {
180 let _ = answer.send(Err(error));
181 }
182 }
183}
184
185impl Drop for ReadRequest {
186 fn drop(&mut self) {
187 if let Some(answer) = self.answer.take() {
190 let _ = answer.send(Err(AttError::UnlikelyError));
191 }
192 }
193}
194
195impl std::fmt::Debug for ReadRequest {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 f.debug_struct("ReadRequest")
198 .field("characteristic", &self.characteristic.as_str())
199 .field("central", &self.central.id)
200 .field("offset", &self.offset)
201 .finish()
202 }
203}
204
205pub struct WriteRequest {
207 writes: Vec<Write>,
208 central: RemoteCentral,
209 answer: Option<Sender<std::result::Result<(), AttError>>>,
210}
211
212impl WriteRequest {
213 pub fn writes(&self) -> &[Write] {
214 &self.writes
215 }
216
217 pub fn central(&self) -> &RemoteCentral {
218 &self.central
219 }
220
221 pub fn accept(mut self) {
223 if let Some(answer) = self.answer.take() {
224 let _ = answer.send(Ok(()));
225 }
226 }
227
228 pub fn reject_all(mut self, error: AttError) {
230 if let Some(answer) = self.answer.take() {
231 let _ = answer.send(Err(error));
232 }
233 }
234}
235
236impl Drop for WriteRequest {
237 fn drop(&mut self) {
238 if let Some(answer) = self.answer.take() {
239 let _ = answer.send(Err(AttError::UnlikelyError));
240 }
241 }
242}
243
244impl std::fmt::Debug for WriteRequest {
245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 f.debug_struct("WriteRequest")
247 .field("writes", &self.writes.len())
248 .field("central", &self.central.id)
249 .finish()
250 }
251}
252
253#[derive(Debug)]
255pub enum Request {
256 Read(ReadRequest),
257 Write(WriteRequest),
258 Subscribed {
259 central: RemoteCentral,
260 characteristic: BluetoothUuid,
261 },
262 Unsubscribed {
263 central: RemoteCentral,
264 characteristic: BluetoothUuid,
265 },
266 ReadyToNotify,
273 ChannelOpened(crate::l2cap::L2capChannel),
275}
276
277const REQUEST_BACKLOG: usize = 1024;
280
281pub struct Requests {
282 rx: webbluetooth_core::backlog::Receiver<Request>,
283}
284
285impl Requests {
286 pub fn lost(&self) -> u64 {
295 self.rx.lost()
296 }
297}
298
299impl Stream for Requests {
300 type Item = Request;
301 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Request>> {
302 Pin::new(&mut self.rx).poll_next(cx)
303 }
304}
305
306struct CharacteristicState {
310 uuid: BluetoothUuid,
311 path: String,
312 flags: Vec<String>,
313 value: Mutex<Vec<u8>>,
316 fixed: bool,
319 subscribers: Mutex<Vec<RemoteCentral>>,
321 descriptors: Vec<DescriptorState>,
322}
323
324struct DescriptorState {
325 uuid: BluetoothUuid,
326 path: String,
327 value: Vec<u8>,
328}
329
330struct ServiceState {
331 uuid: BluetoothUuid,
332 path: String,
333 primary: bool,
334 characteristics: Vec<Arc<CharacteristicState>>,
335}
336
337struct Inner {
338 bluez: Option<Arc<Bluez>>,
339 to_app: webbluetooth_core::backlog::Sender<Request>,
340 services: Mutex<Vec<Arc<ServiceState>>>,
341 registered: AtomicBool,
342 advertising: AtomicBool,
343 next_index: AtomicUsize,
344 advertisement: Mutex<Vec<(Value, Value)>>,
347 l2cap_listeners: Mutex<HashMap<webbluetooth_core::Psm, crate::l2cap::L2capListenerHandle>>,
348}
349
350impl Inner {
351 fn adapter(&self) -> Result<(Arc<Bluez>, String)> {
352 let bluez = self
353 .bluez
354 .clone()
355 .ok_or(Error::NotAvailable(Availability::Unsupported))?;
356 let adapter = bluez
357 .adapter()
358 .ok_or(Error::NotAvailable(Availability::Unsupported))?;
359 Ok((bluez, adapter))
360 }
361
362 fn characteristic_at(&self, path: &str) -> Option<Arc<CharacteristicState>> {
363 self.services
364 .lock()
365 .unwrap()
366 .iter()
367 .flat_map(|s| s.characteristics.clone())
368 .find(|c| c.path == path)
369 }
370
371 fn descriptor_at(&self, path: &str) -> Option<(Arc<CharacteristicState>, Vec<u8>)> {
372 for service in self.services.lock().unwrap().iter() {
373 for characteristic in &service.characteristics {
374 for descriptor in &characteristic.descriptors {
375 if descriptor.path == path {
376 return Some((characteristic.clone(), descriptor.value.clone()));
377 }
378 }
379 }
380 }
381 None
382 }
383
384 fn managed_objects(&self) -> Value {
386 let mut objects: Vec<(Value, Value)> = Vec::new();
387 for service in self.services.lock().unwrap().iter() {
388 objects.push((
389 Value::ObjectPath(service.path.clone()),
390 interfaces_of(vec![(
391 interfaces::SERVICE,
392 properties(vec![
393 ("UUID", Value::Str(service.uuid.as_str().to_owned())),
394 ("Primary", Value::Bool(service.primary)),
395 ]),
396 )]),
397 ));
398 for characteristic in &service.characteristics {
399 objects.push((
400 Value::ObjectPath(characteristic.path.clone()),
401 interfaces_of(vec![(
402 interfaces::CHARACTERISTIC,
403 properties(vec![
404 ("UUID", Value::Str(characteristic.uuid.as_str().to_owned())),
405 ("Service", Value::ObjectPath(service.path.clone())),
406 (
407 "Flags",
408 Value::string_array(characteristic.flags.iter().cloned()),
409 ),
410 ]),
411 )]),
412 ));
413 for descriptor in &characteristic.descriptors {
414 objects.push((
415 Value::ObjectPath(descriptor.path.clone()),
416 interfaces_of(vec![(
417 interfaces::DESCRIPTOR,
418 properties(vec![
419 ("UUID", Value::Str(descriptor.uuid.as_str().to_owned())),
420 (
421 "Characteristic",
422 Value::ObjectPath(characteristic.path.clone()),
423 ),
424 ("Flags", Value::string_array(["read".to_string()])),
425 ]),
426 )]),
427 ));
428 }
429 }
430 }
431 dict_of("{oa{sa{sv}}}", objects)
432 }
433}
434
435fn dict_of(element: &str, entries: Vec<(Value, Value)>) -> Value {
436 Value::Array {
437 element: element.into(),
438 items: entries
439 .into_iter()
440 .map(|(k, v)| Value::DictEntry(Box::new(k), Box::new(v)))
441 .collect(),
442 }
443}
444
445fn properties(entries: Vec<(&str, Value)>) -> Value {
447 dict_of(
448 "{sv}",
449 entries
450 .into_iter()
451 .map(|(name, value)| (Value::Str(name.to_owned()), Value::Variant(Box::new(value))))
452 .collect(),
453 )
454}
455
456fn interfaces_of(entries: Vec<(&str, Value)>) -> Value {
458 dict_of(
459 "{sa{sv}}",
460 entries
461 .into_iter()
462 .map(|(interface, props)| (Value::Str(interface.to_owned()), props))
463 .collect(),
464 )
465}
466
467struct Application {
470 inner: Arc<Inner>,
471}
472
473impl ObjectHandler for Application {
474 fn handle(&self, call: &Message) -> std::result::Result<Vec<Value>, (String, String)> {
475 let path = call.path.clone().unwrap_or_default();
476 let interface = call.interface.clone().unwrap_or_default();
477 let member = call.member.clone().unwrap_or_default();
478
479 match (interface.as_str(), member.as_str()) {
480 (interfaces::OBJECT_MANAGER, "GetManagedObjects") => {
481 Ok(vec![self.inner.managed_objects()])
482 }
483
484 (DBUS_PROPERTIES, "GetAll") => Ok(vec![self.properties_of(&path)]),
485
486 (DBUS_PROPERTIES, "Get") => {
487 let name = call.arg(1).and_then(Value::as_str).unwrap_or_default();
488 self.property(&path, name)
489 .map(|v| vec![Value::Variant(Box::new(v))])
490 .ok_or_else(|| {
491 (
492 "org.freedesktop.DBus.Error.InvalidArgs".to_string(),
493 format!("no property {name} at {path}"),
494 )
495 })
496 }
497
498 (interfaces::CHARACTERISTIC, "ReadValue") => self.read(&path, call.arg(0)),
499 (interfaces::CHARACTERISTIC, "WriteValue") => {
500 self.write(&path, call.arg(0), call.arg(1))
501 }
502 (interfaces::CHARACTERISTIC, "StartNotify") => self.set_subscribed(&path, true),
503 (interfaces::CHARACTERISTIC, "StopNotify") => self.set_subscribed(&path, false),
504
505 (interfaces::DESCRIPTOR, "ReadValue") => match self.inner.descriptor_at(&path) {
508 Some((_, value)) => Ok(vec![Value::bytes(&value)]),
509 None => Err((
510 "org.bluez.Error.Failed".to_string(),
511 format!("no descriptor at {path}"),
512 )),
513 },
514
515 (interfaces::LE_ADVERTISEMENT, "Release") => Ok(Vec::new()),
518
519 _ => Err((
520 "org.freedesktop.DBus.Error.UnknownMethod".to_string(),
521 format!("{interface}.{member} is not implemented"),
522 )),
523 }
524 }
525}
526
527impl Application {
528 fn properties_of(&self, path: &str) -> Value {
529 if path == ADVERTISEMENT {
530 return dict_of("{sv}", self.inner.advertisement.lock().unwrap().clone());
533 }
534 if let Some(characteristic) = self.inner.characteristic_at(path) {
535 return properties(vec![
536 ("UUID", Value::Str(characteristic.uuid.as_str().to_owned())),
537 (
538 "Flags",
539 Value::string_array(characteristic.flags.iter().cloned()),
540 ),
541 ("Value", Value::bytes(&characteristic.value.lock().unwrap())),
542 ]);
543 }
544 properties(Vec::new())
545 }
546
547 fn property(&self, path: &str, name: &str) -> Option<Value> {
548 let characteristic = self.inner.characteristic_at(path)?;
549 match name {
550 "UUID" => Some(Value::Str(characteristic.uuid.as_str().to_owned())),
551 "Value" => Some(Value::bytes(&characteristic.value.lock().unwrap())),
552 "Flags" => Some(Value::string_array(characteristic.flags.iter().cloned())),
553 _ => None,
554 }
555 }
556
557 fn read(
559 &self,
560 path: &str,
561 options: Option<&Value>,
562 ) -> std::result::Result<Vec<Value>, (String, String)> {
563 let Some(characteristic) = self.inner.characteristic_at(path) else {
564 return Err((
565 "org.bluez.Error.Failed".to_string(),
566 format!("no characteristic at {path}"),
567 ));
568 };
569 let central = RemoteCentral::from_options(options, DEFAULT_NOTIFY_LEN);
570 let offset = option_u64(options, "offset").unwrap_or(0) as usize;
571
572 if characteristic.fixed {
576 let value = characteristic.value.lock().unwrap();
577 return Ok(vec![Value::bytes(value.get(offset..).unwrap_or_default())]);
578 }
579
580 let (tx, rx) = channel();
581 let request = Request::Read(ReadRequest {
582 characteristic: characteristic.uuid,
583 central,
584 offset,
585 answer: Some(tx),
586 });
587 if self.inner.to_app.send(request).is_err() {
588 return Ok(vec![Value::bytes(&characteristic.value.lock().unwrap())]);
591 }
592
593 match rx.recv_timeout(ANSWER_TIMEOUT) {
594 Ok(Ok(value)) => {
595 *characteristic.value.lock().unwrap() = value.clone();
596 Ok(vec![Value::bytes(&value)])
597 }
598 Ok(Err(error)) => Err((att_error_name(error), format!("read refused: {error:?}"))),
599 Err(reason) => Err((
600 "org.bluez.Error.Failed".to_string(),
601 format!("the application did not answer the read: {reason}"),
602 )),
603 }
604 }
605
606 fn write(
607 &self,
608 path: &str,
609 value: Option<&Value>,
610 options: Option<&Value>,
611 ) -> std::result::Result<Vec<Value>, (String, String)> {
612 let Some(characteristic) = self.inner.characteristic_at(path) else {
613 return Err((
614 "org.bluez.Error.Failed".to_string(),
615 format!("no characteristic at {path}"),
616 ));
617 };
618 let written: Vec<u8> = value.and_then(Value::as_bytes).unwrap_or_default();
619 let central = RemoteCentral::from_options(options, DEFAULT_NOTIFY_LEN);
620 let offset = option_u64(options, "offset").unwrap_or(0) as usize;
621
622 let (tx, rx) = channel();
623 let request = Request::Write(WriteRequest {
624 writes: vec![Write {
625 characteristic: characteristic.uuid,
626 offset,
627 value: written.clone(),
628 }],
629 central,
630 answer: Some(tx),
631 });
632 if self.inner.to_app.send(request).is_err() {
633 *characteristic.value.lock().unwrap() = written;
634 return Ok(Vec::new());
635 }
636
637 match rx.recv_timeout(ANSWER_TIMEOUT) {
638 Ok(Ok(())) => {
639 *characteristic.value.lock().unwrap() = written;
640 Ok(Vec::new())
641 }
642 Ok(Err(error)) => Err((att_error_name(error), format!("write refused: {error:?}"))),
643 Err(reason) => Err((
644 "org.bluez.Error.Failed".to_string(),
645 format!("the application did not answer the write: {reason}"),
646 )),
647 }
648 }
649
650 fn set_subscribed(
653 &self,
654 path: &str,
655 subscribed: bool,
656 ) -> std::result::Result<Vec<Value>, (String, String)> {
657 let Some(characteristic) = self.inner.characteristic_at(path) else {
658 return Err((
659 "org.bluez.Error.Failed".to_string(),
660 format!("no characteristic at {path}"),
661 ));
662 };
663 let central = RemoteCentral {
666 id: "subscribed".to_string(),
667 mtu: DEFAULT_NOTIFY_LEN,
668 identified: false,
669 };
670 {
671 let mut subscribers = characteristic.subscribers.lock().unwrap();
672 if subscribed {
673 subscribers.push(central.clone());
674 } else {
675 subscribers.clear();
676 }
677 }
678 let request = if subscribed {
679 Request::Subscribed {
680 central,
681 characteristic: characteristic.uuid,
682 }
683 } else {
684 Request::Unsubscribed {
685 central,
686 characteristic: characteristic.uuid,
687 }
688 };
689 let _ = self.inner.to_app.send(request);
690 Ok(Vec::new())
691 }
692}
693
694fn att_error_name(error: AttError) -> String {
696 match error {
701 AttError::ReadNotPermitted | AttError::WriteNotPermitted => "org.bluez.Error.NotPermitted",
702 AttError::InsufficientAuthentication | AttError::InsufficientEncryption => {
703 "org.bluez.Error.NotPaired"
704 }
705 AttError::InsufficientAuthorization => "org.bluez.Error.NotAuthorized",
706 AttError::RequestNotSupported => "org.bluez.Error.NotSupported",
707 AttError::InvalidOffset => "org.bluez.Error.InvalidOffset",
708 AttError::InvalidAttributeValueLength => "org.bluez.Error.InvalidValueLength",
709 _ => "org.bluez.Error.Failed",
710 }
711 .to_string()
712}
713
714struct Discard;
716impl EventSink for Discard {
717 fn emit(&self, _event: Event) {}
718}
719
720#[derive(Clone)]
724pub struct Peripheral {
725 inner: Arc<Inner>,
726}
727
728impl Peripheral {
729 pub fn new() -> (Self, Requests) {
731 let (to_app, rx) = webbluetooth_core::backlog::bounded(
736 REQUEST_BACKLOG,
737 webbluetooth_core::backlog::Overflow::KeepOldest,
738 );
739 let bluez = Bluez::new(Arc::new(Discard)).ok().map(Arc::new);
740 let inner = Arc::new(Inner {
741 bluez,
742 to_app,
743 services: Mutex::new(Vec::new()),
744 registered: AtomicBool::new(false),
745 advertising: AtomicBool::new(false),
746 next_index: AtomicUsize::new(0),
747 advertisement: Mutex::new(Vec::new()),
748 l2cap_listeners: Mutex::new(HashMap::new()),
749 });
750 if let Some(bluez) = &inner.bluez {
751 bluez.export(
752 ROOT,
753 Arc::new(Application {
754 inner: inner.clone(),
755 }),
756 );
757 }
758 (Self { inner }, Requests { rx })
759 }
760
761 pub fn with_restoration(_restoration: webbluetooth_core::Restoration) -> (Self, Requests) {
763 Self::new()
764 }
765
766 pub async fn availability(&self) -> std::result::Result<(), Availability> {
768 let Some(bluez) = &self.inner.bluez else {
769 return Err(Availability::Unauthorized);
770 };
771 if bluez.adapter().is_none() {
772 return Err(Availability::Unsupported);
773 }
774 if !bluez.is_powered() {
775 return Err(Availability::PoweredOff);
776 }
777 Ok(())
778 }
779
780 pub async fn publish(&self, service: Service) -> Result<PublishedService> {
786 service.validate()?;
787 let (bluez, adapter) = self.inner.adapter()?;
788 if !bluez.is_powered() {
789 return Err(Error::NotAvailable(Availability::PoweredOff));
790 }
791
792 let index = self.inner.next_index.fetch_add(1, Ordering::Relaxed);
793 let service_path = format!("{ROOT}/service{index}");
794 let mut characteristics = Vec::new();
795
796 for (i, definition) in service.characteristics.iter().enumerate() {
797 let path = format!("{service_path}/char{i}");
798 let descriptors = definition
799 .descriptors
800 .iter()
801 .enumerate()
802 .map(|(j, d)| DescriptorState {
803 uuid: d.uuid,
804 path: format!("{path}/desc{j}"),
805 value: d.value.clone(),
806 })
807 .collect();
808 characteristics.push(Arc::new(CharacteristicState {
809 uuid: definition.uuid,
810 path,
811 flags: flags_for(Properties(definition.properties)),
812 value: Mutex::new(definition.value.clone().unwrap_or_default()),
813 fixed: definition.value.is_some(),
814 subscribers: Mutex::new(Vec::new()),
815 descriptors,
816 }));
817 }
818
819 let state = Arc::new(ServiceState {
820 uuid: service.uuid,
821 path: service_path,
822 primary: service.primary,
823 characteristics,
824 });
825 self.inner.services.lock().unwrap().push(state.clone());
826
827 if self.inner.registered.swap(true, Ordering::SeqCst) {
829 let _ = call(
830 &bluez,
831 &adapter,
832 interfaces::GATT_MANAGER,
833 "UnregisterApplication",
834 vec![Value::ObjectPath(ROOT.to_string())],
835 );
836 }
837 call(
838 &bluez,
839 &adapter,
840 interfaces::GATT_MANAGER,
841 "RegisterApplication",
842 vec![Value::ObjectPath(ROOT.to_string()), properties(Vec::new())],
843 )
844 .inspect_err(|_| {
845 self.inner
848 .services
849 .lock()
850 .unwrap()
851 .retain(|s| s.path != state.path);
852 self.inner.registered.store(false, Ordering::SeqCst);
853 })?;
854
855 Ok(PublishedService {
856 inner: self.inner.clone(),
857 state,
858 })
859 }
860
861 pub fn unpublish_all(&self) {
863 self.inner.services.lock().unwrap().clear();
864 if self.inner.registered.swap(false, Ordering::SeqCst) {
865 if let Ok((bluez, adapter)) = self.inner.adapter() {
866 let _ = call(
867 &bluez,
868 &adapter,
869 interfaces::GATT_MANAGER,
870 "UnregisterApplication",
871 vec![Value::ObjectPath(ROOT.to_string())],
872 );
873 }
874 }
875 }
876
877 pub async fn start_advertising(&self, advertising: Advertising) -> Result<()> {
879 let (bluez, adapter) = self.inner.adapter()?;
880 if self.inner.advertising.load(Ordering::SeqCst) {
881 self.stop_advertising();
882 }
883
884 let mut entries: Vec<(Value, Value)> = vec![(
887 Value::Str("Type".into()),
888 Value::Variant(Box::new(Value::Str("peripheral".into()))),
889 )];
890 if !advertising.services.is_empty() {
891 entries.push((
892 Value::Str("ServiceUUIDs".into()),
893 Value::Variant(Box::new(Value::string_array(
894 advertising.services.iter().map(|u| u.as_str().to_owned()),
895 ))),
896 ));
897 }
898 if let Some(name) = &advertising.local_name {
899 entries.push((
900 Value::Str("LocalName".into()),
901 Value::Variant(Box::new(Value::Str(name.clone()))),
902 ));
903 }
904 if let Some((min, max)) = advertising.interval {
907 for (key, d) in [("MinInterval", min), ("MaxInterval", max)] {
908 entries.push((
909 Value::Str(key.into()),
910 Value::Variant(Box::new(Value::Uint32(d.as_millis() as u32))),
911 ));
912 }
913 }
914 *self.inner.advertisement.lock().unwrap() = entries;
915
916 bluez.export(
917 ADVERTISEMENT,
918 Arc::new(Application {
919 inner: self.inner.clone(),
920 }),
921 );
922 call(
923 &bluez,
924 &adapter,
925 interfaces::LE_ADVERTISING_MANAGER,
926 "RegisterAdvertisement",
927 vec![
928 Value::ObjectPath(ADVERTISEMENT.to_string()),
929 properties(Vec::new()),
930 ],
931 )?;
932 self.inner.advertising.store(true, Ordering::SeqCst);
933 Ok(())
934 }
935
936 pub fn stop_advertising(&self) {
938 if !self.inner.advertising.swap(false, Ordering::SeqCst) {
939 return;
940 }
941 if let Ok((bluez, adapter)) = self.inner.adapter() {
942 let _ = call(
943 &bluez,
944 &adapter,
945 interfaces::LE_ADVERTISING_MANAGER,
946 "UnregisterAdvertisement",
947 vec![Value::ObjectPath(ADVERTISEMENT.to_string())],
948 );
949 }
950 }
951
952 pub fn is_advertising(&self) -> bool {
953 self.inner.advertising.load(Ordering::SeqCst)
954 }
955
956 pub async fn publish_l2cap_channel(
965 &self,
966 encryption_required: bool,
967 ) -> Result<webbluetooth_core::Psm> {
968 let (psm, listener) = crate::l2cap::listen(0, encryption_required)?;
969 let sender = self.inner.to_app.clone();
970 let handle = listener.spawn(move |channel| {
971 let request = match channel {
972 Ok(channel) => Request::ChannelOpened(channel),
973 Err(error) => {
974 eprintln!("LE L2CAP listener error: {error}");
975 return;
976 }
977 };
978 let _ = sender.send(request);
979 })?;
980 self.inner
981 .l2cap_listeners
982 .lock()
983 .unwrap()
984 .insert(psm, handle);
985 Ok(psm)
986 }
987
988 pub async fn unpublish_l2cap_channel(&self, psm: webbluetooth_core::Psm) -> Result<()> {
989 self.inner
990 .l2cap_listeners
991 .lock()
992 .unwrap()
993 .remove(&psm)
994 .ok_or_else(|| Error::NotFound(format!("no published L2CAP channel on PSM {psm}")))?;
995 Ok(())
996 }
997
998 pub async fn restored_state(&self) -> Option<RestoredPeripheral> {
1000 None
1001 }
1002}
1003
1004impl std::fmt::Debug for Peripheral {
1005 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1006 f.debug_struct("Peripheral")
1007 .field("services", &self.inner.services.lock().unwrap().len())
1008 .field("advertising", &self.is_advertising())
1009 .finish()
1010 }
1011}
1012
1013fn call(
1014 bluez: &Arc<Bluez>,
1015 path: &str,
1016 interface: &str,
1017 member: &str,
1018 body: Vec<Value>,
1019) -> Result<Message> {
1020 bluez
1021 .call(path, interface, member, body)
1022 .map_err(|e| Error::Network(format!("{interface}.{member} failed: {e}")))
1023}
1024
1025pub struct PublishedService {
1029 inner: Arc<Inner>,
1030 state: Arc<ServiceState>,
1031}
1032
1033impl PublishedService {
1034 pub fn uuid(&self) -> &BluetoothUuid {
1035 &self.state.uuid
1036 }
1037
1038 pub fn characteristics(&self) -> Vec<PublishedCharacteristic> {
1039 self.state
1040 .characteristics
1041 .iter()
1042 .map(|c| PublishedCharacteristic {
1043 inner: self.inner.clone(),
1044 state: c.clone(),
1045 })
1046 .collect()
1047 }
1048
1049 pub fn characteristic(&self, uuid: impl IntoUuid) -> Option<PublishedCharacteristic> {
1050 let uuid = uuid.into_uuid().ok()?;
1051 self.state
1052 .characteristics
1053 .iter()
1054 .find(|c| c.uuid == uuid)
1055 .map(|c| PublishedCharacteristic {
1056 inner: self.inner.clone(),
1057 state: c.clone(),
1058 })
1059 }
1060
1061 pub fn unpublish(self) {
1066 self.inner
1067 .services
1068 .lock()
1069 .unwrap()
1070 .retain(|s| s.path != self.state.path);
1071 if let Ok((bluez, adapter)) = self.inner.adapter() {
1072 let _ = call(
1073 &bluez,
1074 &adapter,
1075 interfaces::GATT_MANAGER,
1076 "UnregisterApplication",
1077 vec![Value::ObjectPath(ROOT.to_string())],
1078 );
1079 let empty = self.inner.services.lock().unwrap().is_empty();
1080 if empty {
1081 self.inner.registered.store(false, Ordering::SeqCst);
1082 } else {
1083 let _ = call(
1084 &bluez,
1085 &adapter,
1086 interfaces::GATT_MANAGER,
1087 "RegisterApplication",
1088 vec![Value::ObjectPath(ROOT.to_string()), properties(Vec::new())],
1089 );
1090 }
1091 }
1092 }
1093}
1094
1095impl std::fmt::Debug for PublishedService {
1096 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1097 f.debug_struct("PublishedService")
1098 .field("uuid", &self.state.uuid.as_str())
1099 .field("characteristics", &self.state.characteristics.len())
1100 .finish()
1101 }
1102}
1103
1104#[derive(Clone)]
1106pub struct PublishedCharacteristic {
1107 inner: Arc<Inner>,
1108 state: Arc<CharacteristicState>,
1109}
1110
1111impl PublishedCharacteristic {
1112 pub fn uuid(&self) -> &BluetoothUuid {
1113 &self.state.uuid
1114 }
1115
1116 pub fn subscribers(&self) -> Vec<RemoteCentral> {
1122 self.state.subscribers.lock().unwrap().clone()
1123 }
1124
1125 pub fn try_notify(&self, value: &[u8]) -> bool {
1132 *self.state.value.lock().unwrap() = value.to_vec();
1133 if self.state.subscribers.lock().unwrap().is_empty() {
1134 return false;
1135 }
1136 let Some(bluez) = &self.inner.bluez else {
1137 return false;
1138 };
1139 let signal = Message::signal(&self.state.path, DBUS_PROPERTIES, "PropertiesChanged")
1140 .with_body(vec![
1141 Value::Str(interfaces::CHARACTERISTIC.to_string()),
1142 properties(vec![("Value", Value::bytes(value))]),
1143 Value::string_array(Vec::<String>::new()),
1144 ]);
1145 bluez.connection().send(signal).is_ok()
1146 }
1147
1148 pub async fn notify(&self, value: &[u8]) -> Result<()> {
1150 if self.try_notify(value) {
1151 return Ok(());
1152 }
1153 if self.state.subscribers.lock().unwrap().is_empty() {
1154 return Err(Error::InvalidState(format!(
1155 "nothing is subscribed to {}",
1156 self.state.uuid
1157 )));
1158 }
1159 Err(Error::Network(
1160 "could not emit the value change on the bus".into(),
1161 ))
1162 }
1163}
1164
1165impl std::fmt::Debug for PublishedCharacteristic {
1166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1167 f.debug_struct("PublishedCharacteristic")
1168 .field("uuid", &self.state.uuid.as_str())
1169 .field("subscribers", &self.subscribers().len())
1170 .finish()
1171 }
1172}