1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
|
//! Classic ACL manager
use crate::hci::{Address, CommandSender, EventRegistry};
use crate::link::acl::core;
use bt_common::Bluetooth;
use bt_packets::hci::EventChild::{
AuthenticationComplete, ConnectionComplete, DisconnectionComplete,
};
use bt_packets::hci::{
AcceptConnectionRequestBuilder, AcceptConnectionRequestRole, ClockOffsetValid,
CreateConnectionBuilder, CreateConnectionCancelBuilder, CreateConnectionRoleSwitch,
DisconnectBuilder, DisconnectReason, ErrorCode, EventChild, EventCode, EventPacket,
PageScanRepetitionMode, RejectConnectionReason, RejectConnectionRequestBuilder, Role,
};
use bytes::Bytes;
use gddi::{module, provides, Stoppable};
use log::warn;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::runtime::Runtime;
use tokio::select;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::sync::{oneshot, Mutex};
module! {
classic_acl_module,
providers {
AclManager => provide_acl_manager,
},
}
/// Classic ACL manager
#[derive(Clone, Stoppable)]
pub struct AclManager {
req_tx: Sender<Request>,
/// High level events from AclManager
pub evt_rx: Arc<Mutex<Receiver<Event>>>,
}
/// Events generated by AclManager
#[derive(Debug)]
pub enum Event {
/// Connection was successful - provides the newly created connection
ConnectSuccess(Connection),
/// Locally initialted connection was not successful - indicates address & reason
ConnectFail {
/// Address of the failed connection
addr: Address,
/// Reason of the failed connection
reason: ErrorCode,
},
}
/// A classic ACL connection
#[derive(Debug)]
pub struct Connection {
#[allow(dead_code)]
addr: Address,
#[allow(dead_code)]
rx: Receiver<Bytes>,
#[allow(dead_code)]
tx: Sender<Bytes>,
#[allow(dead_code)]
shared: Arc<Mutex<ConnectionShared>>,
requests: Sender<ConnectionRequest>,
#[allow(dead_code)]
evt_rx: Receiver<ConnectionEvent>,
}
/// Events generated by Connection
#[derive(Debug)]
pub enum ConnectionEvent {
/// Connection was disconnected with the specified code.
Disconnected(ErrorCode),
/// Connection authentication was completed
AuthenticationComplete,
}
impl Connection {
/// Disconnect the connection with the specified reason.
pub async fn disconnect(&mut self, reason: DisconnectReason) {
let (tx, rx) = oneshot::channel();
self.requests.send(ConnectionRequest::Disconnect { reason, fut: tx }).await.unwrap();
rx.await.unwrap()
}
}
#[derive(Debug)]
enum ConnectionRequest {
Disconnect { reason: DisconnectReason, fut: oneshot::Sender<()> },
}
struct ConnectionInternal {
addr: Address,
#[allow(dead_code)]
shared: Arc<Mutex<ConnectionShared>>,
hci_evt_tx: Sender<EventPacket>,
}
#[derive(Debug)]
struct ConnectionShared {
#[allow(dead_code)]
role: Role,
}
impl AclManager {
/// Connect to the specified address, or queue it if a connection is already pending
pub async fn connect(&mut self, addr: Address) {
self.req_tx.send(Request::Connect { addr }).await.unwrap();
}
/// Cancel the connection to the specified address, if it is pending
pub async fn cancel_connect(&mut self, addr: Address) {
let (tx, rx) = oneshot::channel();
self.req_tx.send(Request::CancelConnect { addr, fut: tx }).await.unwrap();
rx.await.unwrap();
}
}
#[derive(Debug)]
enum Request {
Connect { addr: Address },
CancelConnect { addr: Address, fut: oneshot::Sender<()> },
}
#[derive(Eq, PartialEq)]
enum PendingConnect {
Outgoing(Address),
Incoming(Address),
None,
}
impl PendingConnect {
fn take(&mut self) -> Self {
std::mem::replace(self, PendingConnect::None)
}
}
#[provides]
async fn provide_acl_manager(
mut hci: CommandSender,
mut events: EventRegistry,
mut dispatch: core::AclDispatch,
rt: Arc<Runtime>,
) -> AclManager {
let (req_tx, mut req_rx) = channel::<Request>(10);
let (conn_evt_tx, conn_evt_rx) = channel::<Event>(10);
let local_rt = rt.clone();
local_rt.spawn(async move {
let connections: Arc<Mutex<HashMap<u16, ConnectionInternal>>> = Arc::new(Mutex::new(HashMap::new()));
let mut connect_queue: Vec<Address> = Vec::new();
let mut pending = PendingConnect::None;
let (evt_tx, mut evt_rx) = channel(3);
events.register(EventCode::ConnectionComplete, evt_tx.clone()).await;
events.register(EventCode::ConnectionRequest, evt_tx.clone()).await;
events.register(EventCode::AuthenticationComplete, evt_tx).await;
loop {
select! {
Some(req) = req_rx.recv() => {
match req {
Request::Connect { addr } => {
if connections.lock().await.values().any(|c| c.addr == addr) {
warn!("already connected: {}", addr);
return;
}
if let PendingConnect::None = pending {
pending = PendingConnect::Outgoing(addr);
hci.send(build_create_connection(addr)).await;
} else {
connect_queue.insert(0, addr);
}
},
Request::CancelConnect { addr, fut } => {
connect_queue.retain(|p| *p != addr);
if pending == PendingConnect::Outgoing(addr) {
hci.send(CreateConnectionCancelBuilder { bd_addr: addr }).await;
}
fut.send(()).unwrap();
}
}
}
Some(evt) = evt_rx.recv() => {
match evt.specialize() {
ConnectionComplete(evt) => {
let addr = evt.get_bd_addr();
let status = evt.get_status();
let handle = evt.get_connection_handle();
let role = match pending.take() {
PendingConnect::Outgoing(a) if a == addr => Role::Central,
PendingConnect::Incoming(a) if a == addr => Role::Peripheral,
_ => panic!("No prior connection request for {}", addr),
};
match status {
ErrorCode::Success => {
let mut core_conn = dispatch.register(handle, Bluetooth::Classic).await;
let shared = Arc::new(Mutex::new(ConnectionShared { role }));
let (evt_tx, evt_rx) = channel(10);
let (req_tx, req_rx) = channel(10);
let connection = Connection {
addr,
shared: shared.clone(),
rx: core_conn.rx.take().unwrap(),
tx: core_conn.tx.take().unwrap(),
requests: req_tx,
evt_rx,
};
let connection_internal = ConnectionInternal {
addr,
shared,
hci_evt_tx: core_conn.evt_tx.clone(),
};
assert!(connections.lock().await.insert(handle, connection_internal).is_none());
rt.spawn(run_connection(handle, evt_tx, req_rx, core_conn, connections.clone(), hci.clone()));
conn_evt_tx.send(Event::ConnectSuccess(connection)).await.unwrap();
},
_ => conn_evt_tx.send(Event::ConnectFail { addr, reason: status }).await.unwrap(),
}
},
EventChild::ConnectionRequest(evt) => {
let addr = evt.get_bd_addr();
pending = PendingConnect::Incoming(addr);
if connections.lock().await.values().any(|c| c.addr == addr) {
hci.send(RejectConnectionRequestBuilder {
bd_addr: addr,
reason: RejectConnectionReason::UnacceptableBdAddr
}).await;
} else {
hci.send(AcceptConnectionRequestBuilder {
bd_addr: addr,
role: AcceptConnectionRequestRole::BecomeCentral
}).await;
}
},
AuthenticationComplete(e) => dispatch_to(e.get_connection_handle(), &connections, evt).await,
_ => unimplemented!(),
}
}
}
}
});
AclManager { req_tx, evt_rx: Arc::new(Mutex::new(conn_evt_rx)) }
}
fn build_create_connection(bd_addr: Address) -> CreateConnectionBuilder {
CreateConnectionBuilder {
bd_addr,
packet_type: 0x4408 /* DM 1,3,5 */ | 0x8810, /*DH 1,3,5 */
page_scan_repetition_mode: PageScanRepetitionMode::R1,
clock_offset: 0,
clock_offset_valid: ClockOffsetValid::Invalid,
allow_role_switch: CreateConnectionRoleSwitch::AllowRoleSwitch,
}
}
async fn dispatch_to(
handle: u16,
connections: &Arc<Mutex<HashMap<u16, ConnectionInternal>>>,
event: EventPacket,
) {
if let Some(c) = connections.lock().await.get_mut(&handle) {
c.hci_evt_tx.send(event).await.unwrap();
}
}
async fn run_connection(
handle: u16,
evt_tx: Sender<ConnectionEvent>,
mut req_rx: Receiver<ConnectionRequest>,
mut core: core::Connection,
connections: Arc<Mutex<HashMap<u16, ConnectionInternal>>>,
mut hci: CommandSender,
) {
loop {
select! {
Some(evt) = core.evt_rx.recv() => {
match evt.specialize() {
DisconnectionComplete(evt) => {
connections.lock().await.remove(&handle);
evt_tx.send(ConnectionEvent::Disconnected(evt.get_reason())).await.unwrap();
return; // At this point, there is nothing more to run on the connection.
},
AuthenticationComplete(_) => evt_tx.send(ConnectionEvent::AuthenticationComplete).await.unwrap(),
_ => unimplemented!(),
}
},
Some(req) = req_rx.recv() => {
match req {
ConnectionRequest::Disconnect{reason, fut} => {
hci.send(DisconnectBuilder { connection_handle: handle, reason }).await;
fut.send(()).unwrap();
}
}
},
}
}
}
|