@@ -23,19 +23,48 @@ use std::convert::TryInto;
23
23
use std:: fmt:: { self , Debug , Formatter } ;
24
24
use std:: pin:: Pin ;
25
25
use std:: sync:: { Arc , Mutex } ;
26
+ use windows:: {
27
+ Devices :: Radios :: { Radio , RadioState } ,
28
+ Foundation :: TypedEventHandler ,
29
+ } ;
26
30
27
31
/// Implementation of [api::Central](crate::api::Central).
28
32
#[ derive( Clone ) ]
29
33
pub struct Adapter {
30
34
watcher : Arc < Mutex < BLEWatcher > > ,
31
35
manager : Arc < AdapterManager < Peripheral > > ,
36
+ radio : Radio ,
37
+ }
38
+
39
+ // https://github.com/microsoft/windows-rs/blob/master/crates/libs/windows/src/Windows/Devices/Radios/mod.rs
40
+ fn get_central_state ( radio : Radio ) -> CentralState {
41
+ let state = radio. State ( ) . unwrap_or ( RadioState :: Unknown ) ;
42
+ match state {
43
+ RadioState :: On => CentralState :: PoweredOn ,
44
+ RadioState :: Off => CentralState :: PoweredOff ,
45
+ _ => CentralState :: Unknown ,
46
+ }
32
47
}
33
48
34
49
impl Adapter {
35
- pub ( crate ) fn new ( ) -> Self {
50
+ pub ( crate ) fn new ( radio : Radio ) -> Self {
36
51
let watcher = Arc :: new ( Mutex :: new ( BLEWatcher :: new ( ) ) ) ;
37
52
let manager = Arc :: new ( AdapterManager :: default ( ) ) ;
38
- Adapter { watcher, manager }
53
+
54
+ let radio_clone = radio. clone ( ) ;
55
+ let manager_clone = manager. clone ( ) ;
56
+ let handler = TypedEventHandler :: new ( move |_sender, _args| {
57
+ let state = get_central_state ( radio_clone. clone ( ) ) ;
58
+ manager_clone. emit ( CentralEvent :: StateUpdate ( state. into ( ) ) ) ;
59
+ Ok ( ( ) )
60
+ } ) ;
61
+ radio. StateChanged ( & handler) ;
62
+
63
+ Adapter {
64
+ watcher,
65
+ manager,
66
+ radio,
67
+ }
39
68
}
40
69
}
41
70
@@ -102,6 +131,6 @@ impl Central for Adapter {
102
131
}
103
132
104
133
async fn adapter_state ( & self ) -> Result < CentralState > {
105
- Ok ( CentralState :: Unknown )
134
+ Ok ( get_central_state ( self . radio . clone ( ) ) )
106
135
}
107
136
}
0 commit comments