@@ -23,19 +23,50 @@ 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) ;
58
+ manager_clone. emit ( CentralEvent :: StateUpdate ( state. into ( ) ) ) ;
59
+ Ok ( ( ) )
60
+ } ) ;
61
+ if let Err ( err) = radio. StateChanged ( & handler) {
62
+ eprintln ! ( "radio.StateChanged error: {}" , err) ;
63
+ }
64
+
65
+ Adapter {
66
+ watcher,
67
+ manager,
68
+ radio,
69
+ }
39
70
}
40
71
}
41
72
@@ -102,6 +133,6 @@ impl Central for Adapter {
102
133
}
103
134
104
135
async fn adapter_state ( & self ) -> Result < CentralState > {
105
- Ok ( CentralState :: Unknown )
136
+ Ok ( get_central_state ( & self . radio ) )
106
137
}
107
138
}
0 commit comments