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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use bluez_generated::{
    OrgBluezAdapter1Properties, OrgBluezDevice1Properties, OrgBluezGattCharacteristic1Properties,
    ORG_BLUEZ_ADAPTER1_NAME, ORG_BLUEZ_DEVICE1_NAME, ORG_BLUEZ_GATT_CHARACTERISTIC1_NAME,
};
use dbus::message::{MatchRule, SignalArgs};
use dbus::nonblock::stdintf::org_freedesktop_dbus::{
    ObjectManagerInterfacesAdded, PropertiesPropertiesChanged,
};
use dbus::{Message, Path};
use std::collections::HashMap;
use uuid::Uuid;

use super::device::{convert_manufacturer_data, convert_service_data, convert_services};
use super::{AdapterId, CharacteristicId, DeviceId};

/// An event relating to a Bluetooth device or adapter.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BluetoothEvent {
    /// An event related to a Bluetooth adapter.
    Adapter {
        /// The ID of the Bluetooth adapter in question.
        id: AdapterId,
        /// Details of the specific event.
        event: AdapterEvent,
    },
    /// An event related to a Bluetooth device.
    Device {
        /// The ID of the Bluetooth device in question.
        id: DeviceId,
        /// Details of the specific event.
        event: DeviceEvent,
    },
    /// An event related to a GATT characteristic of a Bluetooth device.
    Characteristic {
        /// The ID of the GATT characteristic in question.
        id: CharacteristicId,
        /// Details of the specific event.
        event: CharacteristicEvent,
    },
}

/// Details of an event related to a Bluetooth adapter.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum AdapterEvent {
    /// The adapter has been powered on or off.
    Powered { powered: bool },
    /// The adapter has started or stopped scanning for devices.
    Discovering { discovering: bool },
}

/// Details of an event related to a Bluetooth device.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DeviceEvent {
    /// A new device has been discovered.
    Discovered,
    /// The device has connected or disconnected.
    Connected { connected: bool },
    /// A new value is available for the RSSI of the device.
    Rssi { rssi: i16 },
    /// A new value is available for the manufacturer-specific advertisement data of the device.
    ManufacturerData {
        /// The manufacturer-specific advertisement data. The keys are 'manufacturer IDs'.
        manufacturer_data: HashMap<u16, Vec<u8>>,
    },
    /// New GATT service advertisement data is available for the device.
    ServiceData {
        /// The new GATT service data. This is a map from the service UUID to its data.
        service_data: HashMap<Uuid, Vec<u8>>,
    },
    /// The set of GATT services known for the device has changed.
    Services {
        /// The new set of GATT service UUIDs from the device's advertisement or service discovery.
        services: Vec<Uuid>,
    },
    /// Service discovery has completed.
    ServicesResolved,
}

/// Details of an event related to a GATT characteristic.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CharacteristicEvent {
    /// A new value of the characteristic has been received. This may be from a notification.
    Value { value: Vec<u8> },
}

impl BluetoothEvent {
    /// Return a set of `MatchRule`s which will match all D-Bus messages which represent Bluetooth
    /// events, possibly limited to those for a particular object (such as a device, service or
    /// characteristic).
    ///
    /// Set `interfaces_added` to true to include ObjectManager InterfacesAdded signals, which map
    /// to `DeviceEvent::Discovered` events.
    pub(crate) fn match_rules(
        object: Option<impl Into<Path<'static>>>,
        interfaces_added: bool,
    ) -> Vec<MatchRule<'static>> {
        // BusName validation just checks that the length and format is valid, so it should never
        // fail for a constant that we know is valid.
        let bus_name = "org.bluez".into();

        let mut match_rules = vec![];

        // If we aren't filtering to a single device or characteristic, then match ObjectManager
        // signals so we can get events for new devices being discovered.
        if interfaces_added {
            let match_rule =
                ObjectManagerInterfacesAdded::match_rule(Some(&bus_name), None).static_clone();
            match_rules.push(match_rule);
        }

        // Match PropertiesChanged signals for the given device or characteristic and all objects
        // under it. If no object is specified then this will match PropertiesChanged signals for
        // all BlueZ objects.
        let object_path = object.map(|o| o.into());
        let mut match_rule =
            PropertiesPropertiesChanged::match_rule(Some(&bus_name), object_path.as_ref())
                .static_clone();
        match_rule.path_is_namespace = true;
        match_rules.push(match_rule);

        match_rules
    }

    /// Return a list of Bluetooth events parsed from the given D-Bus message.
    pub(crate) fn message_to_events(message: Message) -> Vec<BluetoothEvent> {
        if let Some(properties_changed) = PropertiesPropertiesChanged::from_message(&message) {
            let object_path = message.path().unwrap().into_static();
            Self::properties_changed_to_events(object_path, properties_changed)
        } else if let Some(interfaces_added) = ObjectManagerInterfacesAdded::from_message(&message)
        {
            Self::interfaces_added_to_events(interfaces_added)
        } else {
            log::info!("Unexpected message: {:?}", message);
            vec![]
        }
    }

    /// Return a list of Bluetooth events parsed from an InterfacesAdded signal.
    fn interfaces_added_to_events(
        interfaces_added: ObjectManagerInterfacesAdded,
    ) -> Vec<BluetoothEvent> {
        log::trace!("InterfacesAdded: {:?}", interfaces_added);
        let mut events = vec![];
        let object_path = interfaces_added.object;
        if let Some(_device) =
            OrgBluezDevice1Properties::from_interfaces(&interfaces_added.interfaces)
        {
            let id = DeviceId { object_path };
            events.push(BluetoothEvent::Device {
                id,
                event: DeviceEvent::Discovered,
            })
        }
        events
    }

    /// Return a list of Bluetooth events parsed from a PropertiesChanged signal.
    fn properties_changed_to_events(
        object_path: Path<'static>,
        properties_changed: PropertiesPropertiesChanged,
    ) -> Vec<BluetoothEvent> {
        log::trace!(
            "PropertiesChanged for {}: {:?}",
            object_path,
            properties_changed
        );
        let mut events = vec![];
        let changed_properties = &properties_changed.changed_properties;
        match properties_changed.interface_name.as_ref() {
            ORG_BLUEZ_ADAPTER1_NAME => {
                let id = AdapterId { object_path };
                let adapter = OrgBluezAdapter1Properties(changed_properties);
                if let Some(powered) = adapter.powered() {
                    events.push(BluetoothEvent::Adapter {
                        id: id.clone(),
                        event: AdapterEvent::Powered { powered },
                    })
                }
                if let Some(discovering) = adapter.discovering() {
                    events.push(BluetoothEvent::Adapter {
                        id,
                        event: AdapterEvent::Discovering { discovering },
                    });
                }
            }
            ORG_BLUEZ_DEVICE1_NAME => {
                let id = DeviceId { object_path };
                let device = OrgBluezDevice1Properties(changed_properties);
                if let Some(connected) = device.connected() {
                    events.push(BluetoothEvent::Device {
                        id: id.clone(),
                        event: DeviceEvent::Connected { connected },
                    });
                }
                if let Some(rssi) = device.rssi() {
                    events.push(BluetoothEvent::Device {
                        id: id.clone(),
                        event: DeviceEvent::Rssi { rssi },
                    });
                }
                if let Some(manufacturer_data) = device.manufacturer_data() {
                    events.push(BluetoothEvent::Device {
                        id: id.clone(),
                        event: DeviceEvent::ManufacturerData {
                            manufacturer_data: convert_manufacturer_data(manufacturer_data),
                        },
                    })
                }
                if let Some(service_data) = device.service_data() {
                    events.push(BluetoothEvent::Device {
                        id: id.clone(),
                        event: DeviceEvent::ServiceData {
                            service_data: convert_service_data(service_data),
                        },
                    })
                }
                if let Some(services) = device.uuids() {
                    events.push(BluetoothEvent::Device {
                        id: id.clone(),
                        event: DeviceEvent::Services {
                            services: convert_services(services),
                        },
                    })
                }
                if device.services_resolved() == Some(true) {
                    events.push(BluetoothEvent::Device {
                        id,
                        event: DeviceEvent::ServicesResolved,
                    });
                }
            }
            ORG_BLUEZ_GATT_CHARACTERISTIC1_NAME => {
                let id = CharacteristicId { object_path };
                let characteristic = OrgBluezGattCharacteristic1Properties(changed_properties);
                if let Some(value) = characteristic.value() {
                    events.push(BluetoothEvent::Characteristic {
                        id,
                        event: CharacteristicEvent::Value {
                            value: value.to_owned(),
                        },
                    })
                }
            }
            _ => {}
        }
        events
    }
}

#[cfg(test)]
mod tests {
    use super::super::ServiceId;
    use crate::uuid_from_u32;
    use dbus::arg::{PropMap, RefArg, Variant};

    use super::*;

    #[test]
    fn adapter_powered() {
        let message = adapter_powered_message("/org/bluez/hci0", true);
        let id = AdapterId::new("/org/bluez/hci0");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Adapter {
                id,
                event: AdapterEvent::Powered { powered: true }
            }]
        )
    }

    #[test]
    fn device_rssi() {
        let rssi = 42;
        let message = device_rssi_message("/org/bluez/hci0/dev_11_22_33_44_55_66", rssi);
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Device {
                id,
                event: DeviceEvent::Rssi { rssi }
            }]
        )
    }

    #[test]
    fn device_manufacturer_data() {
        let mut manufacturer_data = HashMap::new();
        manufacturer_data.insert(42, vec![1u8, 2, 3]);
        let message = device_manufacturer_data_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66",
            manufacturer_data.clone(),
        );
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Device {
                id,
                event: DeviceEvent::ManufacturerData { manufacturer_data }
            }]
        )
    }

    #[test]
    fn device_service_data() {
        let mut service_data = HashMap::new();
        service_data.insert(uuid_from_u32(0x11223344), vec![1u8, 2, 3]);
        let message = device_service_data_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66",
            service_data.clone(),
        );
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Device {
                id,
                event: DeviceEvent::ServiceData { service_data }
            }]
        )
    }

    #[test]
    fn device_services() {
        let mut services = Vec::new();
        services.push(uuid_from_u32(0x11223344));
        let message =
            device_services_message("/org/bluez/hci0/dev_11_22_33_44_55_66", services.clone());
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Device {
                id,
                event: DeviceEvent::Services { services }
            }]
        )
    }

    #[test]
    fn characteristic_value() {
        let value: Vec<u8> = vec![1, 2, 3];
        let message = characteristic_value_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034",
            &value,
        );
        let id =
            CharacteristicId::new("/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Characteristic {
                id,
                event: CharacteristicEvent::Value { value }
            }]
        )
    }

    #[test]
    fn device_discovered() {
        let message = new_device_message("/org/bluez/hci0/dev_11_22_33_44_55_66");
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(
            BluetoothEvent::message_to_events(message),
            vec![BluetoothEvent::Device {
                id,
                event: DeviceEvent::Discovered
            }]
        )
    }

    #[test]
    fn match_rules_all() {
        let match_rules = BluetoothEvent::match_rules(None::<DeviceId>, true);

        let message = new_device_message("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);

        let message = adapter_powered_message("/org/bluez/hci0", true);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);

        let message = device_rssi_message("/org/bluez/hci0/dev_11_22_33_44_55_66", 42);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);

        let message = characteristic_value_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034",
            &vec![1, 2, 3],
        );
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);
    }

    #[test]
    fn match_rules_device() {
        let id = DeviceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66");
        let match_rules = BluetoothEvent::match_rules(Some(id), false);

        let message = new_device_message("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = adapter_powered_message("/org/bluez/hci0", true);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = device_rssi_message("/org/bluez/hci0/dev_11_22_33_44_55_66", 42);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);

        let message = characteristic_value_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034",
            &vec![1, 2, 3],
        );
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);
    }

    #[test]
    fn match_rules_service() {
        let id = ServiceId::new("/org/bluez/hci0/dev_11_22_33_44_55_66/service0012");
        let match_rules = BluetoothEvent::match_rules(Some(id), false);

        let message = new_device_message("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = adapter_powered_message("/org/bluez/hci0", true);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = device_rssi_message("/org/bluez/hci0/dev_11_22_33_44_55_66", 42);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = characteristic_value_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034",
            &vec![1, 2, 3],
        );
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);
    }

    #[test]
    fn match_rules_characteristic() {
        let id =
            CharacteristicId::new("/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034");
        let match_rules = BluetoothEvent::match_rules(Some(id), false);

        let message = new_device_message("/org/bluez/hci0/dev_11_22_33_44_55_66");
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = adapter_powered_message("/org/bluez/hci0", true);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = device_rssi_message("/org/bluez/hci0/dev_11_22_33_44_55_66", 42);
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), false);

        let message = characteristic_value_message(
            "/org/bluez/hci0/dev_11_22_33_44_55_66/service0012/char0034",
            &vec![1, 2, 3],
        );
        assert_eq!(match_rules.iter().any(|rule| rule.matches(&message)), true);
    }

    fn new_device_message(device_path: &'static str) -> Message {
        let properties = HashMap::new();
        let mut interfaces = HashMap::new();
        interfaces.insert("org.bluez.Device1".to_string(), properties);
        let interfaces_added = ObjectManagerInterfacesAdded {
            object: device_path.into(),
            interfaces,
        };
        interfaces_added.to_emit_message(&"/".into())
    }

    fn adapter_powered_message(adapter_path: &'static str, powered: bool) -> Message {
        let mut changed_properties: PropMap = HashMap::new();
        changed_properties.insert("Powered".to_string(), Variant(Box::new(powered)));
        let properties_changed = PropertiesPropertiesChanged {
            interface_name: "org.bluez.Adapter1".to_string(),
            changed_properties,
            invalidated_properties: vec![],
        };
        properties_changed.to_emit_message(&adapter_path.into())
    }

    fn device_rssi_message(device_path: &'static str, rssi: i16) -> Message {
        let mut changed_properties: PropMap = HashMap::new();
        changed_properties.insert("RSSI".to_string(), Variant(Box::new(rssi)));
        let properties_changed = PropertiesPropertiesChanged {
            interface_name: "org.bluez.Device1".to_string(),
            changed_properties,
            invalidated_properties: vec![],
        };
        properties_changed.to_emit_message(&device_path.into())
    }

    fn device_manufacturer_data_message(
        device_path: &'static str,
        manufacturer_data: HashMap<u16, Vec<u8>>,
    ) -> Message {
        let manufacturer_data: HashMap<_, _> = manufacturer_data
            .into_iter()
            .map::<(u16, Variant<Box<dyn RefArg>>), _>(|(k, v)| (k, Variant(Box::new(v))))
            .collect();
        let mut changed_properties: PropMap = HashMap::new();
        changed_properties.insert(
            "ManufacturerData".to_string(),
            Variant(Box::new(manufacturer_data)),
        );
        let properties_changed = PropertiesPropertiesChanged {
            interface_name: "org.bluez.Device1".to_string(),
            changed_properties,
            invalidated_properties: vec![],
        };
        properties_changed.to_emit_message(&device_path.into())
    }

    fn device_service_data_message(
        device_path: &'static str,
        service_data: HashMap<Uuid, Vec<u8>>,
    ) -> Message {
        let service_data: HashMap<_, _> = service_data
            .into_iter()
            .map::<(String, Variant<Box<dyn RefArg>>), _>(|(k, v)| {
                (k.to_string(), Variant(Box::new(v)))
            })
            .collect();
        let mut changed_properties: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap::new();
        changed_properties.insert("ServiceData".to_string(), Variant(Box::new(service_data)));
        let properties_changed = PropertiesPropertiesChanged {
            interface_name: "org.bluez.Device1".to_string(),
            changed_properties,
            invalidated_properties: vec![],
        };
        properties_changed.to_emit_message(&device_path.into())
    }

    fn device_services_message(device_path: &'static str, services: Vec<Uuid>) -> Message {
        let services: Vec<_> = services
            .into_iter()
            .map::<String, _>(|k| k.to_string())
            .collect();
        let mut changed_properties: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap::new();
        changed_properties.insert("UUIDs".to_string(), Variant(Box::new(services)));
        let properties_changed = PropertiesPropertiesChanged {
            interface_name: "org.bluez.Device1".to_string(),
            changed_properties,
            invalidated_properties: vec![],
        };
        properties_changed.to_emit_message(&device_path.into())
    }

    fn characteristic_value_message(characteristic_path: &'static str, value: &[u8]) -> Message {
        let mut changed_properties: PropMap = HashMap::new();
        changed_properties.insert("Value".to_string(), Variant(Box::new(value.to_owned())));
        let properties_changed = PropertiesPropertiesChanged {
            interface_name: "org.bluez.GattCharacteristic1".to_string(),
            changed_properties,
            invalidated_properties: vec![],
        };
        properties_changed.to_emit_message(&characteristic_path.into())
    }
}