1
1
use std:: sync:: atomic:: { AtomicBool , Ordering } ;
2
2
use std:: sync:: Arc ;
3
+ use std:: time:: Duration ;
3
4
use std:: { f32, thread} ;
4
5
5
6
use btleplug:: api:: { Central , CentralEvent , Manager as _, Peripheral , ScanFilter } ;
@@ -51,13 +52,24 @@ async fn get_data(spinning: Arc<AtomicBool>, dropping: Arc<AtomicBool>) {
51
52
52
53
if let Some ( event) = event_option {
53
54
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
+
56
65
let local_name = peripheral. properties ( ) . await . unwrap ( ) . unwrap ( ) . local_name ;
57
66
58
67
if local_name. is_some_and ( |x| x. contains ( "bidrum-hat" ) ) {
59
68
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
+ }
61
73
}
62
74
63
75
peripheral
@@ -81,13 +93,29 @@ async fn get_data(spinning: Arc<AtomicBool>, dropping: Arc<AtomicBool>) {
81
93
. expect ( "Failed to make notification stream" ) ;
82
94
83
95
// 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
+ }
91
119
}
92
120
}
93
121
}
0 commit comments