Skip to content

Commit

Permalink
feat: winrtble adapter_info and StateUpdate implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
szymonlesisz committed Sep 10, 2024
1 parent de81724 commit 44d71ca
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
35 changes: 32 additions & 3 deletions src/winrtble/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,48 @@ use std::convert::TryInto;
use std::fmt::{self, Debug, Formatter};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use windows::{
Devices::Radios::{Radio, RadioState},
Foundation::TypedEventHandler,
};

/// Implementation of [api::Central](crate::api::Central).
#[derive(Clone)]
pub struct Adapter {
watcher: Arc<Mutex<BLEWatcher>>,
manager: Arc<AdapterManager<Peripheral>>,
radio: Radio,
}

// https://github.com/microsoft/windows-rs/blob/master/crates/libs/windows/src/Windows/Devices/Radios/mod.rs
fn get_central_state(radio: Radio) -> CentralState {
let state = radio.State().unwrap_or(RadioState::Unknown);
match state {
RadioState::On => CentralState::PoweredOn,
RadioState::Off => CentralState::PoweredOff,
_ => CentralState::Unknown,
}
}

impl Adapter {
pub(crate) fn new() -> Self {
pub(crate) fn new(radio: Radio) -> Self {
let watcher = Arc::new(Mutex::new(BLEWatcher::new()));
let manager = Arc::new(AdapterManager::default());
Adapter { watcher, manager }

let radio_clone = radio.clone();
let manager_clone = manager.clone();
let handler = TypedEventHandler::new(move |_sender, _args| {
let state = get_central_state(radio_clone.clone());
manager_clone.emit(CentralEvent::StateUpdate(state.into()));
Ok(())
});
radio.StateChanged(&handler);

Adapter {
watcher,
manager,
radio,
}
}
}

Expand Down Expand Up @@ -102,6 +131,6 @@ impl Central for Adapter {
}

async fn adapter_state(&self) -> Result<CentralState> {
Ok(CentralState::Unknown)
Ok(get_central_state(self.radio.clone()))
}
}
2 changes: 1 addition & 1 deletion src/winrtble/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl api::Manager for Manager {
Ok(radios
.into_iter()
.filter(|radio| radio.Kind() == Ok(RadioKind::Bluetooth))
.map(|_| Adapter::new())
.map(|radio| Adapter::new(radio.clone()))
.collect())
}
}

0 comments on commit 44d71ca

Please sign in to comment.