bluez_async/
descriptor.rs

1use dbus::Path;
2use serde::{Deserialize, Serialize};
3use std::fmt::{self, Display, Formatter};
4use uuid::Uuid;
5
6use crate::CharacteristicId;
7
8/// Opaque identifier for a GATT characteristic descriptor on a Bluetooth device.
9#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
10pub struct DescriptorId {
11    #[serde(with = "crate::serde_path")]
12    pub(crate) object_path: Path<'static>,
13}
14
15impl DescriptorId {
16    #[cfg(test)]
17    pub(crate) fn new(object_path: &str) -> Self {
18        Self {
19            object_path: object_path.to_owned().into(),
20        }
21    }
22
23    /// Get the ID of the characteristic on which this descriptor was advertised.
24    pub fn characteristic(&self) -> CharacteristicId {
25        let index = self
26            .object_path
27            .rfind('/')
28            .expect("DescriptorId object_path must contain a slash.");
29        CharacteristicId::new(&self.object_path[0..index])
30    }
31}
32
33impl From<DescriptorId> for Path<'static> {
34    fn from(id: DescriptorId) -> Self {
35        id.object_path
36    }
37}
38
39impl Display for DescriptorId {
40    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
41        write!(
42            f,
43            "{}",
44            self.object_path
45                .to_string()
46                .strip_prefix("/org/bluez/")
47                .ok_or(fmt::Error)?
48        )
49    }
50}
51
52/// Information about a GATT descriptor on a Bluetooth device.
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct DescriptorInfo {
55    /// An opaque identifier for the descriptor on the device, including a reference to which
56    /// adapter it was discovered on.
57    pub id: DescriptorId,
58    /// The 128-bit UUID of the descriptor.
59    pub uuid: Uuid,
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn descriptor_characteristic() {
68        let characteristic_id =
69            CharacteristicId::new("/org/bluez/hci0/dev_11_22_33_44_55_66/service0022/char0033");
70        let descriptor_id = DescriptorId::new(
71            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0022/char0033/desc0034",
72        );
73        assert_eq!(descriptor_id.characteristic(), characteristic_id);
74    }
75
76    #[test]
77    fn to_string() {
78        let descriptor_id = DescriptorId::new(
79            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0022/char0033/desc0034",
80        );
81        assert_eq!(
82            descriptor_id.to_string(),
83            "hci0/dev_11_22_33_44_55_66/service0022/char0033/desc0034"
84        );
85    }
86}