Skip to content

Commit 03c6acd

Browse files
committed
feat: winrtble adapter_info and StateUpdate implementation
1 parent d00158e commit 03c6acd

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

src/winrtble/adapter.rs

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,50 @@ use std::convert::TryInto;
2323
use std::fmt::{self, Debug, Formatter};
2424
use std::pin::Pin;
2525
use 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)]
2933
pub 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

3449
impl Adapter {
35-
pub(crate) fn new() -> Self {
50+
pub(crate) fn new(radio: Radio) -> Self {
3651
let watcher = Arc::new(Mutex::new(BLEWatcher::new()));
3752
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+
}
3970
}
4071
}
4172

@@ -102,6 +133,6 @@ impl Central for Adapter {
102133
}
103134

104135
async fn adapter_state(&self) -> Result<CentralState> {
105-
Ok(CentralState::Unknown)
136+
Ok(get_central_state(&self.radio))
106137
}
107138
}

src/winrtble/manager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ impl api::Manager for Manager {
3535
Ok(radios
3636
.into_iter()
3737
.filter(|radio| radio.Kind() == Ok(RadioKind::Bluetooth))
38-
.map(|_| Adapter::new())
38+
.map(|radio| Adapter::new(radio))
3939
.collect())
4040
}
4141
}

0 commit comments

Comments
 (0)