br-ble 0.2.0

This is an Bluetooth
Documentation
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use std::thread;
use std::sync::{Arc, mpsc};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::thread::sleep;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::time::timeout;
use futures::StreamExt;
use json::JsonValue;
use log::{error, info};
use windows::Devices::Bluetooth::Advertisement::{BluetoothLEAdvertisementReceivedEventArgs, BluetoothLEAdvertisementWatcher, BluetoothLEScanningMode};
use windows::Devices::Bluetooth::{BluetoothAdapter, BluetoothAddressType, BluetoothCacheMode, BluetoothConnectionStatus, BluetoothLEDevice};
use windows::Devices::Bluetooth::GenericAttributeProfile::{GattCharacteristic, GattClientCharacteristicConfigurationDescriptorValue, GattDeviceService};
use windows::core::{Error, Ref};
use windows::Devices::Radios::RadioState;
use windows::Foundation::TypedEventHandler;
use crate::device::Characteristic;
use crate::win::until::{connected_device, subscribe};

#[derive(Clone)]
pub enum CentralEvent {
    /// 蓝牙适配器状态
    ManagerStateChanged {
        /// 设备状态
        new_state: ManagerState,
    },
    /// 已连接设备
    ConnectedPeripheral {
        connected_device: Vec<String>,
    },
    /// 发现设备
    PeripheralDiscovered {
        peripheral: BluetoothLEDevice,
        advertisement_data: AdvertisementData,
        rssi: i16,
    },
    /// 已连接
    PeripheralConnected {
        peripheral: BluetoothLEDevice,
    },
    /// 未连接
    PeripheralUnConnected {
        peripheral: BluetoothLEDevice,
    },
    /// 断连
    PeripheralDisconnected {
        peripheral: BluetoothLEDevice,
    },
    /// 发现服务
    ServicesDiscovered { peripheral: BluetoothLEDevice, services: Vec<GattDeviceService> },
    /// 发现特征
    CharacteristicsDiscovered {
        peripheral: BluetoothLEDevice,
        service: GattDeviceService,
        characteristics: Vec<GattCharacteristic>,
    },
    /// 订阅
    SubscriptionChangeResult {
        peripheral: BluetoothLEDevice,
        characteristic: Characteristic,
    },
    /// 监听收值
    CharacteristicValue {
        peripheral: BluetoothLEDevice,

        characteristic: Characteristic,

        value: Result<Vec<u8>, Error>,
    },
    /// 连接失败
    PeripheralConnectFailed {
        peripheral: BluetoothLEDevice,
    },
}


#[derive(Clone)]
pub struct CentralManager {
    sender: Arc<Sender<CentralEvent>>,
    pending_disconnect_devices: Arc<RwLock<Vec<BluetoothLEDevice>>>,
    scan_running: Arc<AtomicBool>,
    connected_running: Arc<AtomicBool>,
}
impl CentralManager {
    pub fn new() -> (Self, Receiver<CentralEvent>) {
        // 先检查有没有蓝牙接收器,没有的话就不做蓝牙通道的初始化
        loop {
            match BluetoothAdapter::GetDefaultAsync() {
                Ok(v) => {
                    match v.get() {
                        Ok(_) => break,
                        Err(e) => {
                            error!("找不到蓝牙接收器2: {}",e);
                            sleep(Duration::from_secs(5));
                            continue
                        }
                    }
                },
                Err(e) => {
                    error!("找不到蓝牙接收器1: {}",e);
                    sleep(Duration::from_secs(5));
                    continue
                }
            }
        }
        
        let (tx, receiver) = mpsc::channel();
        let sender = Arc::new(tx.clone());
        thread::spawn(move || {
            let mut state = ManagerState::None;
            loop {
                let bluetooth_adapter = match BluetoothAdapter::GetDefaultAsync() {
                    Ok(e) => e,
                    Err(e) => {
                        error!("BluetoothAdapter::GetDefaultAsync: {}",e);
                        sender.send(CentralEvent::ManagerStateChanged { new_state: ManagerState::Unsupported }).unwrap();
                        continue;
                    }
                };
                let adapter = match bluetooth_adapter.get() {
                    Ok(e) => e,
                    Err(e) => {
                        error!("BluetoothAdapter::get: {}",e);
                        sender.send(CentralEvent::ManagerStateChanged { new_state: ManagerState::Unsupported }).unwrap();
                        continue;
                    }
                };

                let radio_state = match adapter.GetRadioAsync() {
                    Ok(e) => match e.get() {
                        Ok(e) => match e.State() {
                            Ok(e) => e,
                            Err(e) => {
                                error!("BluetoothAdapter::State: {}",e);
                                sender.send(CentralEvent::ManagerStateChanged { new_state: ManagerState::Unsupported }).unwrap();
                                continue;
                            }
                        },
                        Err(e) => {
                            error!("BluetoothAdapter::get: {}",e);
                            sender.send(CentralEvent::ManagerStateChanged { new_state: ManagerState::Unsupported }).unwrap();
                            continue;
                        }
                    },
                    Err(e) => {
                        error!("BluetoothAdapter::GetRadioAsync: {}",e);
                        sender.send(CentralEvent::ManagerStateChanged { new_state: ManagerState::Unsupported }).unwrap();
                        continue;
                    }
                };

                let manager_state = match radio_state {
                    RadioState::On => ManagerState::PoweredOn,
                    RadioState::Off => ManagerState::PoweredOff,
                    RadioState::Disabled => ManagerState::Unauthorized,
                    RadioState::Unknown => ManagerState::Unknown,
                    _ => ManagerState::Unknown
                };
                if state == manager_state {
                    sleep(Duration::from_secs(2));
                    continue;
                }
                state = manager_state;
                sender.send(CentralEvent::ManagerStateChanged { new_state: manager_state }).unwrap();
            }
        });
        (
            Self {
                sender: Arc::new(tx.clone()),
                pending_disconnect_devices: Arc::new(RwLock::new(Vec::new())),
                scan_running: Arc::new(AtomicBool::new(false)),
                connected_running: Arc::new(AtomicBool::new(false)),
            },
            receiver
        )
    }
    pub fn stop_threads(&self) {
        self.scan_running.store(false, Ordering::SeqCst);
        self.connected_running.store(false, Ordering::SeqCst);
    }
    /// 扫描设备
    pub fn scan(&self) {
        let tx = self.sender.clone();
        if self.scan_running.load(Ordering::SeqCst) {
            return;
        }
        self.scan_running.store(true, Ordering::SeqCst);
        let scan_running = self.scan_running.clone(); // 新增
        thread::spawn(move || {

            let received_handler = TypedEventHandler::new(
                move |_watcher, event_args: Ref<'_, BluetoothLEAdvertisementReceivedEventArgs>| {
                    let name = event_args.clone().unwrap().Advertisement().unwrap().LocalName().ok().and_then(|x| (!x.is_empty()).then(|| x.to_string_lossy())).unwrap_or("unknown".to_string());
                    let addr = match event_args.clone().unwrap().BluetoothAddress().ok() {
                        None => return Ok(()),
                        Some(e) => e
                    };
                    let rssi = match event_args.clone().unwrap().RawSignalStrengthInDBm().ok() {
                        None => return Ok(()),
                        Some(e) => e
                    };
                    let addr_type = match event_args.clone().unwrap().BluetoothAddressType().ok() {
                        None => return Ok(()),
                        Some(e) => e
                    };
                    let is_connectable = event_args.clone().unwrap().IsConnectable().unwrap_or(false);

                    // 打印扫描到的蓝牙设备信息
                    // if name != "unknown" {
                    //     println!(
                    //         "发现设备: 名称: {}, 地址: {}, RSSI: {}, 地址类型: {:?}, 是否可连接: {}",
                    //         name, addr, rssi, addr_type, is_connectable
                    //     );
                    // }

                    let advertisement_data = AdvertisementData {
                        name,
                        addr,
                        addr_type: AddrType::from(addr_type),
                        is_connectable,
                    };
                    let device = match BluetoothLEDevice::FromBluetoothAddressAsync(addr).unwrap().get() {
                        Ok(e) => e,
                        Err(_) => return Ok(()),
                    };
                    match tx.send(CentralEvent::PeripheralDiscovered { peripheral: device.clone(), advertisement_data, rssi}) {
                        Ok(()) => {}
                        Err(e) => {
                            error!("{}", e);
                        }
                    };
                    Ok(())
                },
            );
            let stopped_handler = TypedEventHandler::new(
                move |watcher: Ref<'_, BluetoothLEAdvertisementWatcher>, _event_args| {
                    error!("扫描关闭: {:?}",watcher.clone());
                    // tx.send(CentralEvent::PeripheralDiscovered { peripheral: event_args.clone().unwrap().clone() }).unwrap();
                    Ok(())
                },
            );

            let build_watcher = || -> Result<BluetoothLEAdvertisementWatcher, Error> {
                let watcher = match BluetoothLEAdvertisementWatcher::new() {
                    Ok(e) => e,
                    Err(e) => return Err(e)
                };
                match watcher.SetScanningMode(BluetoothLEScanningMode::Active) {
                    Ok(()) => {}
                    Err(e) => return Err(e)
                };
                watcher.SetAllowExtendedAdvertisements(true).unwrap();
                match watcher.Received(&received_handler) {
                    Ok(e) => e,
                    Err(e) => return Err(e)
                };
                watcher.Stopped(&stopped_handler)?;
                Ok(watcher)
            };
            let build_watcher = match build_watcher() {
                Ok(e) => e,
                Err(_) => {
                    info!("错误");
                    return;
                }
            };
            match build_watcher.Start() {
                Ok(()) => {
                    info!("扫描启动成功");
                }
                Err(_e) => {
                    error!("蓝牙未开启");
                }
            }
            loop {
                if !scan_running.load(Ordering::SeqCst) {
                    info!("扫描线程退出");
                    break;
                }
                sleep(Duration::from_secs(1));
            }
            // 线程退出时重置状态
            scan_running.store(false, Ordering::SeqCst);
        });

    }
    pub fn connected(&self){
        let tx = self.sender.clone();
        if self.connected_running.load(Ordering::SeqCst) {
            return;
        }
        self.connected_running.store(true, Ordering::SeqCst);
        let connected_running = self.connected_running.clone(); // 新增

        thread::spawn(move || {
            loop {
                if !connected_running.load(Ordering::SeqCst) {
                    info!("连接监听已连接蓝牙设备");
                    break;
                }
                match connected_device() {
                    Ok(connected_device) => {
                        
                        info!("本机已连接蓝牙设备: {:#}", JsonValue::from(connected_device.clone()));
                        
                        tx.send(CentralEvent::ConnectedPeripheral { connected_device }).unwrap();
                    }
                    Err(_) => {
                        info!("获取失败");
                    }
                };
                sleep(Duration::from_secs(3));
            }
        });
    }
    /// 连接
    pub fn connect(&self, device: BluetoothLEDevice) {
        match device.ConnectionStatus() {
            Ok(e) => {
                match e {
                    BluetoothConnectionStatus(0i32) => {
                        self.sender.send(CentralEvent::PeripheralUnConnected { peripheral: device.clone() }).unwrap();
                    }
                    _ => {
                        self.sender.send(CentralEvent::PeripheralConnected { peripheral: device.clone() }).unwrap();
                    }
                }
            }
            Err(e) => {
                error!("链接失败: {}",e);
            }
        }
    }
    ///发现服务
    pub fn discover_services(&self, device: BluetoothLEDevice) {
        // 尝试获取服务(不使用缓存)
        let gatt_services_result = match match device.GetGattServicesWithCacheModeAsync(BluetoothCacheMode::Uncached) {
            Ok(e) => e,
            Err(_) => return,
        }.get() {
            Ok(e) => e,
            Err(_) => return,
        };
        let services = match gatt_services_result.Services() {
            Ok(e) => e,
            Err(_) => return
        };
        let mut list = vec![];
        for service in &services {
            list.push(service);
        }
        self.sender.send(CentralEvent::ServicesDiscovered { peripheral: device.clone(), services: list }).unwrap();
    }
    /// 枚举每个服务的特性
    pub fn discover_characteristics(&self, peripheral: BluetoothLEDevice, service: GattDeviceService) {
        let characteristics_result = match service.GetCharacteristicsAsync() {
            Ok(e) => {
                match e.get() {
                    Ok(e) => {
                        e
                    }
                    Err(_) => {
                        info!("错误");
                        return;
                    }
                }
            }
            Err(_) => {
                info!("错误");
                return;
            }
        };
        let characteristics = characteristics_result.Characteristics().unwrap();
        let mut list = vec![];
        for characteristic in &characteristics {
            list.push(characteristic);
        }
        self.sender.send(CentralEvent::CharacteristicsDiscovered { peripheral: peripheral.clone(), service, characteristics: list }).unwrap();
    }
    ///订阅特征
    pub fn subscribe(&self, peripheral: BluetoothLEDevice, characteristic: Characteristic) {
        self.sender.send(CentralEvent::SubscriptionChangeResult { peripheral, characteristic }).unwrap();
    }
    ///接收值
    pub fn get_value(&self, peripheral: BluetoothLEDevice, characteristic: Characteristic) {
        let tx = self.sender.clone();

        let pending_disconnect_devices = self.pending_disconnect_devices.clone();

        thread::spawn(move || {
            let gatt_characteristic = characteristic.gatt_characteristic.clone();
            let mut event_stream = match subscribe(&gatt_characteristic) {
                Ok(v) => {
                    info!("订阅成功! {}", characteristic.uuid);
                    v
                }
                Err(e) => {
                    info!("订阅失败 {} - {:?}", e, gatt_characteristic.Uuid().unwrap());
                    return;
                }
            };
            
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async move {
                loop {
                    // wait for event with timeout
                    match timeout(Duration::from_secs(1), event_stream.next()).await {
                        Ok(Some(value)) => {
                            tx.send(CentralEvent::CharacteristicValue {
                                peripheral: peripheral.clone(),
                                characteristic: characteristic.clone(),
                                value
                            }).unwrap();
                        },
                        Ok(None) => {
                            // stream channel shutdown
                            break;
                        },
                        Err(_) => {
                            // r: read_guard
                            let r = pending_disconnect_devices.read().await;
                            if !r.contains(&peripheral) {
                                drop(r);
                                continue;
                            }
                            drop(r);

                            log::info!("Found pending disconnect device, {:?}, {:?}, prepare disconnect", peripheral.Name(), peripheral.BluetoothAddress());

                            // w: write_guard
                            let mut w = pending_disconnect_devices.write().await;
                            let idx_res = w.iter().position(|item|item == &peripheral);
                            let need_break = idx_res.is_some();

                            if let Some(idx) = idx_res {
                                log::info!("Remove pending disconnect device: {:?}, {:?}",
                                    peripheral.Name().ok(),
                                    peripheral.BluetoothAddress().ok()
                                );

                                w.remove(idx);
                            }
                            drop(w);

                            if need_break {
                                log::debug!("Break get_value() loop");
                                break;
                            } else {
                                continue;
                            }
                        }
                    };
                }
            });

            // 如果需要执行额外的清理工作,可以在此处添加
        });
    }

    /// 主动断开蓝牙设备连接
    pub fn disconnect(&self, peripheral: BluetoothLEDevice) {
        // 主动断开连接
        info!("正在断开与设备的连接: 名称: {:?}, 地址: {:?}",peripheral.Name().ok(),peripheral.BluetoothAddress().ok());
        let mut w = self.pending_disconnect_devices.blocking_write();
        if !w.contains(&peripheral){
            info!("Add pending disconnect peripheral: {:?}, {:?}", peripheral.Name(), peripheral.BluetoothAddress());
            w.push(peripheral.clone());
        }
        drop(w);

        // 取消订阅特性通知
        // 获取Gatt服务
        let gatt_services_result = peripheral.GetGattServicesAsync().ok().unwrap().get().unwrap();
        let gatt_services = gatt_services_result.Services().ok().unwrap();

        // 把每个 service 都关掉
        let count = gatt_services.Size().ok().unwrap();
        // info!("gatt_services数量: {}", count);
        for i in 0..count {
            if let Ok(service) = gatt_services.GetAt(i) {
                // info!("正在关闭service UUID: {:?} ", service.Uuid().unwrap());

                // 获取Service下的characteristic
                let characteristic_res = service.GetCharacteristicsAsync().ok().unwrap().get().unwrap();
                let characteristics = characteristic_res.Characteristics().unwrap();

                // 遍历关闭每个characteristic
                let characteristics_num = characteristics.Size().ok().unwrap();
                for j in 0..characteristics_num {
                    let single_chara = characteristics.GetAt(j).ok().unwrap();
                    // 停止从特性值接收通知
                    match single_chara.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(
                        GattClientCharacteristicConfigurationDescriptorValue::None
                    ) {
                        Ok(_) => {
                            // info!("characteristics 关闭成功 - {:?}", single_chara.Uuid().unwrap());
                        }
                        Err(_e) => {
                            // info!("characteristics 关闭失败 - {:?}", e);
                        }
                    }

                }

                // 关闭Service
                let g_close_res = service.Close(); // 忽略错误也可以
                match g_close_res {
                    Ok(_) => {
                        // info!("gatt_services 关闭成功 - {:?}", service.Uuid().unwrap());
                    }
                    Err(_e) => {
                        // info!("gatt_services 关闭失败, {}", e);
                    }
                }

            }
        }

        // 最后 peripheral 也关掉(如果有 Close 方法)
        let p_close_res = peripheral.Close();
        match p_close_res {
            Ok(_) => {
                // info!("peripheral 关闭成功 - {:?}", peripheral.Name().ok());
            }
            Err(_e) => {
                // warn!("peripheral 关闭失败, {}", e);
            }
        }
        // 再 drop 掉 peripheral
        drop(peripheral.clone());
        self.sender.send(CentralEvent::PeripheralDisconnected { peripheral }).unwrap();
    }
}

/// The possible states of a Core Bluetooth manager.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum ManagerState {
    /// The manager’s state is unknown.
    Unknown = 0,

    /// A state that indicates the connection with the system service was momentarily lost.
    Resetting = 1,

    /// A state that indicates this device doesn’t support the Bluetooth low energy central or client role.
    Unsupported = 2,

    /// A state that indicates the application isn’t authorized to use the Bluetooth low energy role.
    Unauthorized = 3,

    /// A state that indicates Bluetooth is currently powered off.
    PoweredOff = 4,

    /// A state that indicates Bluetooth is currently powered on and available to use.
    PoweredOn = 5,
    None,
}

impl ManagerState {
    fn from_u8(v: u8) -> Option<Self> {
        Some(match v {
            0 => Self::Unknown,
            1 => Self::Resetting,
            2 => Self::Unsupported,
            3 => Self::Unauthorized,
            4 => Self::PoweredOff,
            5 => Self::PoweredOn,
            _ => return None,
        })
    }
}

#[derive(Debug, Clone)]
pub struct AdvertisementData {
    pub(crate) name: String,
    addr: u64,
    addr_type: AddrType,
    pub(crate) is_connectable: bool,
}

#[derive(Debug, Clone)]
pub enum AddrType {
    /// 公共的蓝牙地址类型
    Public,
    /// 随机的蓝牙地址类型
    Random,
    /// 未指定的蓝牙地址类型
    Unspecified,
    None,
}
impl AddrType {
    pub fn from(addr_type: BluetoothAddressType) -> Self {
        match addr_type {
            BluetoothAddressType(0i32) => Self::Public,
            BluetoothAddressType(1i32) => Self::Random,
            BluetoothAddressType(2i32) => Self::Unspecified,
            _ => Self::None
        }
    }
}