ble_ledly/device/
led_device.rs

1use btleplug::api::{Characteristic, Peripheral as _};
2use btleplug::platform::Peripheral;
3
4use uuid::Uuid;
5
6use std::fmt;
7
8use crate::device::Device;
9
10#[derive(Debug)]
11pub struct LedDevice {
12    // BLE localname mapping
13    pub name: String,
14    // user-settable alias
15    pub alias: String,
16
17    // underlying BLE Pheripheral
18    peripheral: Option<Peripheral>,
19
20    // default communication chars
21    write_char: Option<Characteristic>,
22    read_char: Option<Characteristic>,
23}
24
25impl Device for LedDevice {
26    fn new(
27        name: &str,
28        alias: &str,
29        peripheral: Option<Peripheral>,
30        write_char: Option<Characteristic>,
31        read_char: Option<Characteristic>,
32    ) -> Self {
33        Self {
34            name: name.to_string(),
35            alias: alias.to_string(),
36            peripheral,
37            write_char: write_char.clone(),
38            read_char: read_char.clone(),
39        }
40    }
41    //--------//
42    // Getter //
43    //--------//
44    /// Provides access to __user-settable__
45    /// device alias
46    fn alias(&self) -> &str {
47        &self.alias
48    }
49    /// Provides access to the device local_name
50    fn name(&self) -> &str {
51        &self.name
52    }
53    /// Provides access to _BLE-specific_ MAC device address
54    fn address(&self) -> Option<String> {
55        if let Some(peripheral) = self.peripheral.as_ref() {
56            return Some(peripheral.address().to_string());
57        }
58        None
59    }
60    fn peripheral(&self) -> Option<&Peripheral> {
61        self.peripheral.as_ref()
62    }
63    fn write_char(&self) -> Option<&Characteristic> {
64        self.write_char.as_ref()
65    }
66    fn read_char(&self) -> Option<&Characteristic> {
67        self.read_char.as_ref()
68    }
69    fn default_write_characteristic_uuid(&self) -> Uuid {
70        unimplemented!()
71    }
72
73    //--------//
74    // Setter //
75    //--------//
76    /// Allows to set __user-settable__
77    /// device alias
78    fn set_alias(&mut self, alias: &str) {
79        self.alias = alias.to_string();
80    }
81    fn set_name(&mut self, name: &str) {
82        self.name = name.to_string();
83    }
84    fn set_peripheral(&mut self, peripheral: Peripheral) {
85        self.peripheral = Some(peripheral);
86    }
87    fn set_write_char(&mut self, characteristic: &Characteristic) {
88        self.write_char = Some(characteristic.clone());
89    }
90}
91//--------------//
92// Display impl //
93//--------------//
94impl fmt::Display for LedDevice {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        write!(
97            f,
98            "{} ({})",
99            self.name(),
100            self.address().unwrap_or(String::from("-"))
101        )
102    }
103}