@@ -23,19 +23,47 @@ use std::convert::TryInto;
2323use std:: fmt:: { self , Debug , Formatter } ;
2424use std:: pin:: Pin ;
2525use std:: sync:: { Arc , Mutex } ;
26+ use windows:: {
27+ Devices :: Radios :: { Radio , RadioState } ,
28+ Foundation :: TypedEventHandler
29+ } ;
2630
2731/// Implementation of [api::Central](crate::api::Central).
2832#[ derive( Clone ) ]
2933pub struct Adapter {
3034 watcher : Arc < Mutex < BLEWatcher > > ,
3135 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+ }
3247}
3348
49+
3450impl Adapter {
35- pub ( crate ) fn new ( ) -> Self {
51+ pub ( crate ) fn new ( radio : Radio ) -> Self {
3652 let watcher = Arc :: new ( Mutex :: new ( BLEWatcher :: new ( ) ) ) ;
3753 let manager = Arc :: new ( AdapterManager :: default ( ) ) ;
38- Adapter { watcher, manager }
54+
55+ let radio_clone = radio. clone ( ) ;
56+ let manager_clone = manager. clone ( ) ;
57+ let handler = TypedEventHandler :: new (
58+ move |_sender, _args| {
59+ let state = get_central_state ( radio_clone. clone ( ) ) ;
60+ manager_clone. emit ( CentralEvent :: StateUpdate ( state. into ( ) ) ) ;
61+ Ok ( ( ) )
62+ } ,
63+ ) ;
64+ radio. StateChanged ( & handler) ;
65+
66+ Adapter { watcher, manager, radio }
3967 }
4068}
4169
@@ -102,6 +130,6 @@ impl Central for Adapter {
102130 }
103131
104132 async fn adapter_state ( & self ) -> Result < CentralState > {
105- Ok ( CentralState :: Unknown )
133+ Ok ( get_central_state ( self . radio . clone ( ) ) )
106134 }
107135}
0 commit comments