Skip to content

Commit

Permalink
Support propagating vendor events to an external handler
Browse files Browse the repository at this point in the history
  • Loading branch information
lulf committed Apr 18, 2024
1 parent e0826cb commit 6d6ba56
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 19 deletions.
2 changes: 1 addition & 1 deletion examples/nrf-sdc/src/bin/ble_bas_peripheral.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ async fn main(spawner: Spawner) {

let mut adapter: Adapter<'_, NoopRawMutex, _, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> =
Adapter::new(sdc, host_resources);
unwrap!(adapter.set_random_address(my_addr()).await);
adapter.set_random_address(my_addr());

let mut table: AttributeTable<'_, NoopRawMutex, 10> = AttributeTable::new();

Expand Down
2 changes: 1 addition & 1 deletion examples/nrf-sdc/src/bin/ble_l2cap_central.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ async fn main(spawner: Spawner) {

let mut adapter: Adapter<'_, NoopRawMutex, _, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> =
Adapter::new(sdc, host_resources);
unwrap!(adapter.set_random_address(my_addr()).await);
adapter.set_random_address(my_addr());

// NOTE: Modify this to match the address of the peripheral you want to connect to
let target: Address = Address::random([0xf5, 0x9f, 0x1a, 0x05, 0xe4, 0xee]);
Expand Down
2 changes: 1 addition & 1 deletion examples/nrf-sdc/src/bin/ble_l2cap_peripheral.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ async fn main(spawner: Spawner) {

let mut adapter: Adapter<'_, NoopRawMutex, _, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> =
Adapter::new(sdc, host_resources);
unwrap!(adapter.set_random_address(my_addr()).await);
adapter.set_random_address(my_addr());
let mut adv_data = [0; 31];
unwrap!(AdStructure::encode_slice(
&[AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED),],
Expand Down
48 changes: 37 additions & 11 deletions host/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ use bt_hci::controller::{CmdError, Controller};
use bt_hci::controller::{ControllerCmdAsync, ControllerCmdSync};
use bt_hci::data::{AclBroadcastFlag, AclPacket, AclPacketBoundary};
use bt_hci::event::le::LeEvent;
use bt_hci::event::Event;
use bt_hci::event::{Event, Vendor};
use bt_hci::param::{
AddrKind, AdvHandle, AdvKind, BdAddr, ConnHandle, DisconnectReason, EventMask, FilterDuplicates, InitiatingPhy,
LeEventMask, Operation, PhyParams, ScanningPhy,
AddrKind, AdvChannelMap, AdvHandle, AdvKind, BdAddr, ConnHandle, DisconnectReason, EventMask, FilterDuplicates,
InitiatingPhy, LeEventMask, Operation, PhyParams, ScanningPhy,
};
use bt_hci::ControllerToHostPacket;
use core::future::pending;
Expand Down Expand Up @@ -54,6 +54,11 @@ impl<M: RawMutex, const CHANNELS: usize, const PACKETS: usize, const L2CAP_MTU:
}
}

/// Event handler for vendor-specific events handled outside the adapter.
pub trait VendorEventHandler {
fn on_event(&self, event: &Vendor<'_>);
}

pub struct Adapter<
'd,
M,
Expand Down Expand Up @@ -188,8 +193,7 @@ where
.exec(&self.controller)
.await?;
let info = self.connections.accept(config.scan_config.filter_accept_list).await;
let _ = LeCreateConnCancel::new().exec(&self.controller).await;
return Ok(Connection { info });
Ok(Connection { info })
} else {
LeCreateConn::new(
config.scan_config.interval.into(),
Expand All @@ -208,8 +212,7 @@ where
.exec(&self.controller)
.await?;
let info = self.connections.accept(config.scan_config.filter_accept_list).await;
let _ = LeCreateConnCancel::new().exec(&self.controller).await;
return Ok(Connection { info });
Ok(Connection { info })
}
}

Expand Down Expand Up @@ -377,7 +380,7 @@ where
self.address.map(|a| a.kind).unwrap_or(AddrKind::RANDOM),
peer.kind,
peer.addr,
config.channel_map,
config.channel_map.unwrap_or(AdvChannelMap::ALL),
config.filter_policy,
)
.exec(&self.controller)
Expand Down Expand Up @@ -446,7 +449,7 @@ where
params.props,
config.interval_min.into(),
config.interval_max.into(),
config.channel_map,
config.channel_map.unwrap_or(AdvChannelMap::ALL),
self.address.map(|a| a.kind).unwrap_or(AddrKind::RANDOM),
peer.kind,
peer.addr,
Expand Down Expand Up @@ -571,6 +574,24 @@ where
}

pub async fn run(&self) -> Result<(), AdapterError<T::Error>>
where
T: ControllerCmdSync<Disconnect>
+ ControllerCmdSync<SetEventMask>
+ ControllerCmdSync<LeSetEventMask>
+ ControllerCmdSync<LeSetRandomAddr>
+ ControllerCmdSync<HostBufferSize>
+ ControllerCmdSync<Reset>
// + ControllerCmdSync<LeReadLocalSupportedFeatures>
// + ControllerCmdSync<LeReadNumberOfSupportedAdvSets>
+ ControllerCmdSync<LeReadBufferSize>,
{
self.run_with_handler(None).await
}

pub async fn run_with_handler(
&self,
vendor_handler: Option<&dyn VendorEventHandler>,
) -> Result<(), AdapterError<T::Error>>
where
T: ControllerCmdSync<Disconnect>
+ ControllerCmdSync<SetEventMask>
Expand Down Expand Up @@ -696,7 +717,7 @@ where
.await;
}
_ => {
error!("Unknown event: {:?}", event);
warn!("Unknown LE event!");
}
},
Event::DisconnectionComplete(e) => {
Expand All @@ -709,8 +730,13 @@ where
// trace!("Confirmed {} packets sent", c.completed_packets.len());
self.permits.release(c.completed_packets.len());
}
Event::Vendor(vendor) => {
if let Some(handler) = vendor_handler {
handler.on_event(&vendor);
}
}
_ => {
warn!("Unknown event: {:?}", event);
warn!("Unknown event");
}
},
Ok(p) => {
Expand Down
4 changes: 2 additions & 2 deletions host/src/advertise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub struct AdvertisementConfig {
pub interval_min: Duration,
pub interval_max: Duration,

pub channel_map: AdvChannelMap,
pub channel_map: Option<AdvChannelMap>,
pub filter_policy: AdvFilterPolicy,
}

Expand All @@ -58,7 +58,7 @@ impl Default for AdvertisementConfig {
interval_min: Duration::from_millis(250),
interval_max: Duration::from_millis(250),
filter_policy: AdvFilterPolicy::default(),
channel_map: AdvChannelMap::ALL,
channel_map: None,
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion host/src/channel_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl<'d, M: RawMutex, const CHANNELS: usize, const L2CAP_TXQ: usize, const L2CAP
let mut state = state.borrow_mut();
// 0 is an invalid identifier
if state.next_req_id == 0 {
state.next_req_id = state.next_req_id + 1;
state.next_req_id += 1;
}
let next = state.next_req_id;
state.next_req_id = state.next_req_id.wrapping_add(1);
Expand Down
4 changes: 2 additions & 2 deletions host/src/gatt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl<'reference, 'values, 'resources, M: RawMutex, T: Controller, const MAX: usi
pub async fn notify(
&self,
handle: CharacteristicHandle,
connection: &Connection<'_>,
connection: &Connection,
value: &[u8],
) -> Result<(), AdapterError<T::Error>> {
let conn = connection.handle();
Expand Down Expand Up @@ -116,7 +116,7 @@ impl<'reference, 'values, 'resources, M: RawMutex, T: Controller, const MAX: usi
#[derive(Clone)]
pub enum GattEvent<'reference, 'values> {
Write {
connection: Connection<'reference>,
connection: &'reference Connection,
handle: CharacteristicHandle,
value: &'values [u8],
},
Expand Down

0 comments on commit 6d6ba56

Please sign in to comment.