br_ble/
device.rs

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
use std::collections::HashMap;
use json::{Error, JsonValue, object};
#[cfg(target_os = "windows")]
use windows::core::GUID;
#[cfg(target_os = "windows")]
use windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementReceivedEventArgs;
#[cfg(target_os = "windows")]
use windows::Devices::Bluetooth::BluetoothLEDevice;
#[cfg(target_os = "windows")]
use windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic;
#[cfg(target_os = "windows")]
use windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristicProperties;
#[cfg(target_os = "macos")]
use crate::mac::central::{AdvertisementData, CentralManager};
#[cfg(target_os = "macos")]
use crate::mac::central::peripheral::Peripheral;

/// 蓝牙设备
#[derive(Clone)]
pub struct Device {
    /// 设备名称
    pub name: String,
    /// 设备id
    pub uuid: String,
    /// 设备信号
    pub rssi: i32,
    /// 服务列表
    pub characteristic: HashMap<String, Characteristic>,
    /// 发现
    pub discover: bool,
    /// 连接
    pub connect: bool,
    /// 禁用
    pub disable: bool,
    /// 环境类型
    pub types: Types,
}
impl Device {
    #[cfg(target_os = "macos")]
    pub fn new(uuid: String, name: String, rssi: i32, manager: CentralManager, peripheral: Peripheral, advertisement_data: AdvertisementData) -> Self {
        Self {
            name,
            uuid,
            rssi,
            characteristic: Default::default(),
            discover: false,
            connect: false,
            disable: false,
            types: Types::Mac(manager, peripheral, advertisement_data),
        }
    }
    #[cfg(target_os = "windows")]
    pub fn new(uuid: String, name: String, rssi: i32, manager: CentralManager, peripheral: BluetoothLEDevice, advertisement_data: AdvertisementData) -> Self {
        Self {
            name,
            uuid,
            rssi,
            characteristic: Default::default(),
            discover: false,
            connect: false,
            disable: false,
            types: Types::Win(manager, peripheral, advertisement_data),
        }
    }
    /// 关闭连接
    pub fn disconnect(&mut self) -> bool {
        return match self.clone().types {
            #[cfg(target_os = "macos")]
            Types::Mac(manager, peripheral, _advertisement_data) => {
                manager.cancel_connect(&peripheral);
                true
            }
            #[cfg(target_os = "windows")]
            Types::Win(manager, peripheral, _2) => {
                manager.cancel_connect(peripheral);
                true
            }
        };
    }
    /// 开启连接
    pub fn connect(&mut self) -> bool {
        return match self.clone().types {
            #[cfg(target_os = "macos")]
            Types::Mac(manager, peripheral, _advertisement_data) => {
                manager.connect(&peripheral);
                true
            }
            #[cfg(target_os = "windows")]
            Types::Win(manager, BluetoothLEDevice, _2) => {
                manager.connect(BluetoothLEDevice);
                true
            }
        };
    }
    /// 订阅
    pub fn subscribe(&mut self, characteristic: Characteristic) -> bool {
        match self.clone().types {
            #[cfg(target_os = "macos")]
            Types::Mac(_, peripheral, _) => {
                peripheral.subscribe(&characteristic.characteristic);
                return true;
            }
            #[cfg(target_os = "windows")]
            Types::Win(manager, BluetoothLEDevice, _2) => {
                manager.subscribe(BluetoothLEDevice,characteristic);
                return true
            }
        }
        return false;
    }
    pub fn json(&mut self) -> JsonValue {
        return object! {
            name:self.name.clone(),
            uuid:self.uuid.clone(),
            rssi:self.rssi.clone(),
            discover: self.discover.clone(),
            connect: self.connect.clone(),
            disable:self.disable.clone(),
        };
    }
}
#[derive(Clone)]
pub enum Types {
    #[cfg(target_os = "macos")]
    Mac(CentralManager, Peripheral, AdvertisementData),
    #[cfg(target_os = "windows")]
    Win(CentralManager, BluetoothLEDevice, AdvertisementData),
}

#[cfg(target_os = "macos")]
use crate::mac::central::characteristic::Characteristic as Char;
#[cfg(target_os = "windows")]
use crate::win::central::{AdvertisementData, CentralManager};
#[cfg(target_os = "windows")]
use crate::win::Win;

/// 特征
#[derive(Clone)]
pub struct Characteristic {
    /// 特征UUID
    pub uuid: String,
    pub properties: Properties,
    #[cfg(target_os = "macos")]
    characteristic: Char,
    #[cfg(target_os = "windows")]
    pub characteristic: GattCharacteristicProperties,
    #[cfg(target_os = "windows")]
    pub gatt_characteristic: GattCharacteristic,
    /// 是否订阅
    pub is_subscribe: Option<bool>,
}

impl Characteristic {
    #[cfg(target_os = "macos")]
    pub fn default(characteristic: Char) -> Characteristic {
        Self {
            uuid: characteristic.id().to_string(),
            properties: Properties::form(format!("{:?}", characteristic.properties())),
            characteristic,
            is_subscribe: None,
        }
    }
    #[cfg(target_os = "windows")]
    pub fn default(uuid: String, characteristic: GattCharacteristicProperties,gatt_characteristic: GattCharacteristic) -> Characteristic {
        Self {
            uuid,
            properties: Properties::form(characteristic.0),
            characteristic,
            gatt_characteristic,
            is_subscribe: None,
        }
    }
}
/// 属性标志
#[derive(Debug, Clone)]
pub struct Properties {
    /// 可读
    pub read: bool,
    /// 可写
    pub write: bool,
    /// 通知
    pub notify: bool,
    /// 发送指示
    pub indicate: bool,
    /// 无响应写入
    pub write_without_response: bool,
    /// 认证签名写入
    pub authenticated_signed_writes: bool,
    /// 指示特征具有扩展的属性
    pub extended_properties: bool,
    /// 支持可靠写入
    pub reliable_write: bool,
    /// 支持可写辅助属性
    pub writable_auxiliaries: bool,
    /// 允许特征值进行广播
    pub broadcast: bool,
}

impl Properties {
    const BROADCAST: u16 = 0b00000001;
    const READ: u16 = 0b00000010;
    const WRITE_WITHOUT_RESPONSE: u16 = 0b00000100;
    const WRITE: u16 = 0b00001000;
    const NOTIFY: u16 = 0b00010000;
    const INDICATE: u16 = 0b00100000;
    const AUTHENTICATED_SIGNED_WRITES: u16 = 0b01000000;
    const EXTENDED_PROPERTIES: u16 = 0b10000000;
    const RELIABLE_WRITE: u16 = 0b000100000000;
    const WRITABLE_AUXILIARIES: u16 = 0b001000000000;

    #[cfg(target_os = "macos")]
    pub fn form(text: String) -> Properties {
        let text = text.trim_start_matches("Properties(BitFlagsDebug(BitFlags<Property>(");
        let text = text.split(",").collect::<Vec<&str>>()[0];
        let text = text.trim_start_matches("0b");
        let raw_value = u16::from_str_radix(text, 2).map_err(|e| e.to_string()).unwrap();
        let is_read = if (Properties::READ & raw_value) == Properties::READ { true } else { false };
        let is_write = if (Properties::WRITE & raw_value) == Properties::WRITE { true } else { false };
        let is_notify = if (Properties::NOTIFY & raw_value) == Properties::NOTIFY { true } else { false };
        let is_indicate = if (Properties::INDICATE & raw_value) == Properties::INDICATE { true } else { false };
        let is_write_without_response = if (Properties::WRITE_WITHOUT_RESPONSE & raw_value) == Properties::WRITE_WITHOUT_RESPONSE { true } else { false };
        let is_authenticated_signed_writes = if (Properties::AUTHENTICATED_SIGNED_WRITES & raw_value) == Properties::AUTHENTICATED_SIGNED_WRITES { true } else { false };
        let is_extended_properties = if (Properties::EXTENDED_PROPERTIES & raw_value) == Properties::EXTENDED_PROPERTIES { true } else { false };
        let is_reliable_write = if (Properties::RELIABLE_WRITE & raw_value) == Properties::RELIABLE_WRITE { true } else { false };
        let is_writable_auxiliaries = if (Properties::WRITABLE_AUXILIARIES & raw_value) == Properties::WRITABLE_AUXILIARIES { true } else { false };
        let is_broadcast = if (Properties::BROADCAST & raw_value) == Properties::BROADCAST { true } else { false };
        return Self {
            read: is_read,
            write: is_write,
            notify: is_notify,
            indicate: is_indicate,
            write_without_response: is_write_without_response,
            authenticated_signed_writes: is_authenticated_signed_writes,
            extended_properties: is_extended_properties,
            reliable_write: is_reliable_write,
            writable_auxiliaries: is_writable_auxiliaries,
            broadcast: is_broadcast,
        };
    }
    #[cfg(target_os = "windows")]
    pub fn form(properties: u32) -> Properties {
        let is_read = if (properties & GattCharacteristicProperties::Read.0) != 0 { true } else { false };
        let is_write = if (properties & GattCharacteristicProperties::Write.0) != 0 { true } else { false };
        let is_notify = if (properties & GattCharacteristicProperties::Notify.0) != 0 { true } else { false };
        let is_indicate = if (properties & GattCharacteristicProperties::Indicate.0) != 0 { true } else { false };
        let is_write_without_response = if (properties & GattCharacteristicProperties::WriteWithoutResponse.0) != 0 { true } else { false };
        let is_authenticated_signed_writes = if (properties & GattCharacteristicProperties::AuthenticatedSignedWrites.0) != 0 { true } else { false };
        let is_extended_properties = if (properties & GattCharacteristicProperties::ExtendedProperties.0) != 0 { true } else { false };
        let is_reliable_write = if (properties & GattCharacteristicProperties::ReliableWrites.0) != 0 { true } else { false };
        let is_writable_auxiliaries = if (properties & GattCharacteristicProperties::WritableAuxiliaries.0) != 0 { true } else { false };
        let is_broadcast = if (properties & GattCharacteristicProperties::Broadcast.0) != 0 { true } else { false };
        Self {
            read: is_read,
            write: is_write,
            notify: is_notify,
            indicate: is_indicate,
            write_without_response: is_write_without_response,
            authenticated_signed_writes: is_authenticated_signed_writes,
            extended_properties: is_extended_properties,
            reliable_write: is_reliable_write,
            writable_auxiliaries: is_writable_auxiliaries,
            broadcast: is_broadcast,
        }
    }
}