Skip to content

Commit 8dbede3

Browse files
committed
feat: reconnects hat automatically
1 parent 914d991 commit 8dbede3

File tree

1 file changed

+38
-10
lines changed

1 file changed

+38
-10
lines changed

bidrum-hat/src/lib.rs

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::sync::atomic::{AtomicBool, Ordering};
22
use std::sync::Arc;
3+
use std::time::Duration;
34
use std::{f32, thread};
45

56
use btleplug::api::{Central, CentralEvent, Manager as _, Peripheral, ScanFilter};
@@ -51,13 +52,24 @@ async fn get_data(spinning: Arc<AtomicBool>, dropping: Arc<AtomicBool>) {
5152

5253
if let Some(event) = event_option {
5354
match event {
54-
CentralEvent::DeviceDiscovered(id) => {
55-
let peripheral = adapter.peripheral(&id).await.unwrap();
55+
CentralEvent::DeviceDiscovered(id) | CentralEvent::DeviceUpdated(id) => {
56+
let peripheral = {
57+
let peripheral = adapter.peripheral(&id).await;
58+
if let Ok(peripheral) = peripheral {
59+
peripheral
60+
} else {
61+
break;
62+
}
63+
};
64+
5665
let local_name = peripheral.properties().await.unwrap().unwrap().local_name;
5766

5867
if local_name.is_some_and(|x| x.contains("bidrum-hat")) {
5968
if !peripheral.is_connected().await.unwrap_or(false) {
60-
peripheral.connect().await.expect("Failed to connect");
69+
let connect_result = peripheral.connect().await;
70+
if connect_result.is_err() {
71+
break;
72+
}
6173
}
6274

6375
peripheral
@@ -81,13 +93,29 @@ async fn get_data(spinning: Arc<AtomicBool>, dropping: Arc<AtomicBool>) {
8193
.expect("Failed to make notification stream");
8294

8395
// Process while the BLE connection is not broken or stopped.
84-
while let Some(data) = notification_stream.next().await {
85-
let norm = std::str::from_utf8(data.value.as_slice())
86-
.unwrap_or("0.0")
87-
.parse::<f32>()
88-
.unwrap();
89-
90-
spinning.store(norm > 1.0, Ordering::Relaxed);
96+
loop {
97+
let notification = notification_stream.next();
98+
let timeouted_notification = tokio::time::timeout(
99+
Duration::from_millis(100),
100+
notification,
101+
)
102+
.await;
103+
104+
if !peripheral.is_connected().await.unwrap_or(false) {
105+
break;
106+
}
107+
108+
if let Ok(unwrapped) = timeouted_notification {
109+
if let Some(data) = &unwrapped {
110+
let norm = std::str::from_utf8(data.value.as_slice())
111+
.unwrap_or("0.0")
112+
.parse::<f32>()
113+
.unwrap();
114+
115+
spinning.store(norm > 1.0, Ordering::Relaxed);
116+
println!("spin norm: {:#}", norm);
117+
}
118+
}
91119
}
92120
}
93121
}

0 commit comments

Comments
 (0)