From 26af2620f9c4555fd6975851c0c1715a9c0c05c1 Mon Sep 17 00:00:00 2001 From: Szymon Lesisz Date: Thu, 15 Feb 2024 14:02:54 +0100 Subject: [PATCH] feat: `bluez` adapter_info and StateUpdate implementation --- src/bluez/adapter.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/bluez/adapter.rs b/src/bluez/adapter.rs index f72daf34..61069f45 100644 --- a/src/bluez/adapter.rs +++ b/src/bluez/adapter.rs @@ -4,6 +4,7 @@ use crate::{Error, Result}; use async_trait::async_trait; use bluez_async::{ AdapterId, BluetoothError, BluetoothEvent, BluetoothSession, DeviceEvent, DiscoveryFilter, + AdapterEvent, Transport, }; use futures::stream::{self, Stream, StreamExt}; @@ -22,6 +23,13 @@ impl Adapter { } } +fn get_central_state(state: bool) -> CentralState { + match state { + true => CentralState::PoweredOn, + false => CentralState::PoweredOff, + } +} + #[async_trait] impl Central for Adapter { type Peripheral = Peripheral; @@ -51,7 +59,7 @@ impl Central for Adapter { let session = self.session.clone(); let adapter_id = self.adapter.clone(); let events = events - .filter_map(move |event| central_event(event, session.clone(), adapter_id.clone())); + .filter_map(move |event| central_event(event, session.clone(), adapter_id.clone())); Ok(Box::pin(initial_events.chain(events))) } @@ -107,7 +115,11 @@ impl Central for Adapter { } async fn adapter_state(&self) -> Result { - Ok(CentralState::Unknown) + let mut powered = false; + if let Ok(info) = self.session.get_adapter_info(&self.adapter).await { + powered = info.powered; + } + Ok(get_central_state(powered)) } } @@ -166,6 +178,16 @@ async fn central_event( } _ => None, }, + BluetoothEvent::Adapter { + id, + event: adapter_event, + } if id == adapter_id => match adapter_event { + AdapterEvent::Powered { powered } => { + let state = get_central_state(powered); + Some(CentralEvent::StateUpdate(state.into())) + }, + _ => None, + }, _ => None, } }