1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use bluez_generated::OrgBluezDevice1Properties;
use dbus::arg::{cast, PropMap, RefArg, Variant};
use dbus::Path;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{self, Display, Formatter};
use std::str::FromStr;
use uuid::Uuid;

use crate::{AdapterId, BluetoothError, MacAddress};

/// Opaque identifier for a Bluetooth device which the system knows about. This includes a reference
/// to which Bluetooth adapter it was discovered on, which means that any attempt to connect to it
/// will also happen from that adapter (in case the system has more than one).
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DeviceId {
    #[serde(with = "crate::serde_path")]
    pub(crate) object_path: Path<'static>,
}

impl DeviceId {
    pub(crate) fn new(object_path: &str) -> Self {
        Self {
            object_path: object_path.to_owned().into(),
        }
    }

    /// Get the ID of the Bluetooth adapter on which this device was discovered, e.g. `"hci0"`.
    pub fn adapter(&self) -> AdapterId {
        let index = self
            .object_path
            .rfind('/')
            .expect("DeviceId object_path must contain a slash.");
        AdapterId::new(&self.object_path[0..index])
    }
}

impl From<DeviceId> for Path<'static> {
    fn from(id: DeviceId) -> Self {
        id.object_path
    }
}

impl Display for DeviceId {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.object_path
                .to_string()
                .strip_prefix("/org/bluez/")
                .ok_or(fmt::Error)?
        )
    }
}

/// Information about a Bluetooth device which was discovered.
/// See https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeviceInfo {
    /// An opaque identifier for the device, including a reference to which adapter it was
    /// discovered on. This can be used to connect to it.
    pub id: DeviceId,
    /// The MAC address of the device.
    pub mac_address: MacAddress,
    /// The type of MAC address the device uses.
    pub address_type: AddressType,
    /// The human-readable name of the device, if available.
    /// Use the Alias property instead.
    pub name: Option<String>,
    /// The appearance of the device, as defined by GAP.
    pub appearance: Option<u16>,
    /// The GATT service UUIDs (if any) from the device's advertisement or service discovery.
    ///
    /// Note that service discovery only happens after a connection has been made to the device, but
    /// BlueZ may cache the list of services after it is disconnected.
    pub services: Vec<Uuid>,
    /// Whether the device is currently paired with the adapter.
    pub paired: bool,
    /// Whether the device is currently connected to the adapter.
    pub connected: bool,
    /// The Received Signal Strength Indicator of the device advertisement or inquiry.
    pub rssi: Option<i16>,
    /// The transmission power level advertised by the device.
    pub tx_power: Option<i16>,
    /// Manufacturer-specific advertisement data, if any. The keys are 'manufacturer IDs'.
    pub manufacturer_data: HashMap<u16, Vec<u8>>,
    /// The GATT service data from the device's advertisement, if any. This is a map from the
    /// service UUID to its data.
    pub service_data: HashMap<Uuid, Vec<u8>>,
    /// Whether service discovery has finished for the device.
    pub services_resolved: bool,
    /// The Bluetooth friendly name. This defaults to the system hostname.
    pub alias: Option<String>,
    /// The Bluetooth class of device, automatically configured by DMI/ACPI information
    /// or provided as static configuration.
    pub class: Option<u32>,
    // Indicates if the information exchanged on pairing process has been stored
    // and will be persisted.
    pub bonded: bool,
    // Proposed icon name according to the freedesktop.org icon naming specification.
    pub icon: Option<String>,
    // Indicates if the remote is seen as trusted.
    pub trusted: bool,
    // If set to true any incoming connections from the device will be immediately rejected.
    // Any device drivers will also be removed.
    pub blocked: bool,
    // Set to true if the device only supports the pre-2.1 Bluetooth pairing mechanism.
    // This property is useful during device discovery to anticipate whether legacy or
    // simple pairing will occur if pairing is initiated.
    pub legacy_pairing: bool,
    // Remote Device ID information in modalias format used by the kernel and udev.
    pub modalias: Option<String>,
    // If set to true this device will be allowed to wake the host from system suspend.
    pub wake_allowed: bool,
}

impl DeviceInfo {
    pub(crate) fn from_properties(
        id: DeviceId,
        device_properties: OrgBluezDevice1Properties,
    ) -> Result<DeviceInfo, BluetoothError> {
        let mac_address = device_properties
            .address()
            .ok_or(BluetoothError::RequiredPropertyMissing("Address"))?
            .parse()?;
        let address_type = device_properties
            .address_type()
            .ok_or(BluetoothError::RequiredPropertyMissing("AddressType"))?
            .parse()?;
        let services = get_services(device_properties);
        let manufacturer_data = get_manufacturer_data(device_properties).unwrap_or_default();
        let service_data = get_service_data(device_properties).unwrap_or_default();

        Ok(DeviceInfo {
            id,
            mac_address,
            address_type,
            name: device_properties.name().cloned(),
            appearance: device_properties.appearance(),
            services,
            paired: device_properties
                .paired()
                .ok_or(BluetoothError::RequiredPropertyMissing("Paired"))?,
            connected: device_properties
                .connected()
                .ok_or(BluetoothError::RequiredPropertyMissing("Connected"))?,
            rssi: device_properties.rssi(),
            tx_power: device_properties.tx_power(),
            manufacturer_data,
            service_data,
            services_resolved: device_properties
                .services_resolved()
                .ok_or(BluetoothError::RequiredPropertyMissing("ServicesResolved"))?,
            alias: device_properties.alias().cloned(),
            class: device_properties.class(),
            bonded: device_properties.bonded().unwrap_or_default(),
            icon: device_properties.icon().cloned(),
            trusted: device_properties
                .trusted()
                .ok_or(BluetoothError::RequiredPropertyMissing("Trusted"))?,
            blocked: device_properties
                .blocked()
                .ok_or(BluetoothError::RequiredPropertyMissing("Blocked"))?,
            legacy_pairing: device_properties
                .legacy_pairing()
                .ok_or(BluetoothError::RequiredPropertyMissing("LegacyPairing"))?,
            modalias: device_properties.modalias().cloned(),
            wake_allowed: device_properties.wake_allowed().unwrap_or(false),
        })
    }
}

/// MAC address type of a Bluetooth device.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AddressType {
    /// Public address.
    Public,
    /// Random address.
    Random,
}

impl AddressType {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Public => "public",
            Self::Random => "random",
        }
    }
}

impl Display for AddressType {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for AddressType {
    type Err = BluetoothError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "public" => Ok(Self::Public),
            "random" => Ok(Self::Random),
            _ => Err(BluetoothError::AddressTypeParseError(s.to_owned())),
        }
    }
}

fn get_manufacturer_data(
    device_properties: OrgBluezDevice1Properties,
) -> Option<HashMap<u16, Vec<u8>>> {
    Some(convert_manufacturer_data(
        device_properties.manufacturer_data()?,
    ))
}

pub(crate) fn convert_manufacturer_data(
    data: &HashMap<u16, Variant<Box<dyn RefArg>>>,
) -> HashMap<u16, Vec<u8>> {
    data.iter()
        .filter_map(|(&k, v)| {
            if let Some(v) = cast::<Vec<u8>>(&v.0) {
                Some((k, v.to_owned()))
            } else {
                log::warn!("Manufacturer data had wrong type: {:?}", &v.0);
                None
            }
        })
        .collect()
}

fn get_service_data(
    device_properties: OrgBluezDevice1Properties,
) -> Option<HashMap<Uuid, Vec<u8>>> {
    Some(convert_service_data(device_properties.service_data()?))
}

pub(crate) fn convert_service_data(data: &PropMap) -> HashMap<Uuid, Vec<u8>> {
    data.iter()
        .filter_map(|(k, v)| match Uuid::parse_str(k) {
            Ok(uuid) => {
                if let Some(v) = cast::<Vec<u8>>(&v.0) {
                    Some((uuid, v.to_owned()))
                } else {
                    log::warn!("Service data had wrong type: {:?}", &v.0);
                    None
                }
            }
            Err(err) => {
                log::warn!("Error parsing service data UUID: {}", err);
                None
            }
        })
        .collect()
}

fn get_services(device_properties: OrgBluezDevice1Properties) -> Vec<Uuid> {
    if let Some(uuids) = device_properties.uuids() {
        convert_services(uuids)
    } else {
        vec![]
    }
}

pub(crate) fn convert_services(uuids: &[String]) -> Vec<Uuid> {
    uuids
        .iter()
        .filter_map(|uuid| {
            Uuid::parse_str(uuid)
                .map_err(|err| {
                    log::warn!("Error parsing service data UUID: {}", err);
                    err
                })
                .ok()
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use crate::uuid_from_u32;

    use super::*;

    #[test]
    fn device_adapter() {
        let adapter_id = AdapterId::new("/org/bluez/hci0");
        let device_id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(device_id.adapter(), adapter_id);
    }

    #[test]
    fn to_string() {
        let device_id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(device_id.to_string(), "hci0/dev_11_22_33_44_55_66");
    }

    #[test]
    fn service_data() {
        let uuid = uuid_from_u32(0x11223344);
        let mut service_data: PropMap = HashMap::new();
        service_data.insert(uuid.to_string(), Variant(Box::new(vec![1u8, 2, 3])));
        let mut device_properties: PropMap = HashMap::new();
        device_properties.insert("ServiceData".to_string(), Variant(Box::new(service_data)));

        let mut expected_service_data = HashMap::new();
        expected_service_data.insert(uuid, vec![1u8, 2, 3]);

        assert_eq!(
            get_service_data(OrgBluezDevice1Properties(&device_properties)),
            Some(expected_service_data)
        );
    }

    #[test]
    fn manufacturer_data() {
        let manufacturer_id = 0x1122;
        let mut manufacturer_data: HashMap<u16, Variant<Box<dyn RefArg>>> = HashMap::new();
        manufacturer_data.insert(manufacturer_id, Variant(Box::new(vec![1u8, 2, 3])));
        let mut device_properties: PropMap = HashMap::new();
        device_properties.insert(
            "ManufacturerData".to_string(),
            Variant(Box::new(manufacturer_data)),
        );

        let mut expected_manufacturer_data = HashMap::new();
        expected_manufacturer_data.insert(manufacturer_id, vec![1u8, 2, 3]);

        assert_eq!(
            get_manufacturer_data(OrgBluezDevice1Properties(&device_properties)),
            Some(expected_manufacturer_data)
        );
    }

    #[test]
    fn device_info_minimal() {
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        let mut device_properties: PropMap = HashMap::new();
        device_properties.insert(
            "Address".to_string(),
            Variant(Box::new("00:11:22:33:44:55".to_string())),
        );
        device_properties.insert(
            "AddressType".to_string(),
            Variant(Box::new("public".to_string())),
        );
        device_properties.insert("Paired".to_string(), Variant(Box::new(false)));
        device_properties.insert("Connected".to_string(), Variant(Box::new(false)));
        device_properties.insert("ServicesResolved".to_string(), Variant(Box::new(false)));
        device_properties.insert("Bonded".to_string(), Variant(Box::new(false)));
        device_properties.insert("Trusted".to_string(), Variant(Box::new(false)));
        device_properties.insert("Blocked".to_string(), Variant(Box::new(false)));
        device_properties.insert("LegacyPairing".to_string(), Variant(Box::new(false)));

        let device =
            DeviceInfo::from_properties(id.clone(), OrgBluezDevice1Properties(&device_properties))
                .unwrap();
        assert_eq!(
            device,
            DeviceInfo {
                id,
                mac_address: "00:11:22:33:44:55".parse().unwrap(),
                address_type: AddressType::Public,
                name: None,
                appearance: None,
                services: vec![],
                paired: false,
                connected: false,
                rssi: None,
                tx_power: None,
                manufacturer_data: HashMap::new(),
                service_data: HashMap::new(),
                services_resolved: false,
                alias: None,
                class: None,
                bonded: false,
                icon: None,
                trusted: false,
                blocked: false,
                legacy_pairing: false,
                modalias: None,
                wake_allowed: false,
            }
        )
    }

    #[test]
    fn get_services_none() {
        let device_properties: PropMap = HashMap::new();

        assert_eq!(
            get_services(OrgBluezDevice1Properties(&device_properties)),
            vec![]
        )
    }

    #[test]
    fn get_services_some() {
        let uuid = uuid_from_u32(0x11223344);
        let uuids = vec![uuid.to_string()];
        let mut device_properties: PropMap = HashMap::new();
        device_properties.insert("UUIDs".to_string(), Variant(Box::new(uuids)));

        assert_eq!(
            get_services(OrgBluezDevice1Properties(&device_properties)),
            vec![uuid]
        )
    }

    #[test]
    fn address_type_parse() {
        for &address_type in &[AddressType::Public, AddressType::Random] {
            assert_eq!(
                address_type.to_string().parse::<AddressType>().unwrap(),
                address_type
            );
        }
    }
}