1use core::{
2 cell::{Cell, RefCell},
3 future::pending,
4};
5
6use bt_hci::{
7 cmd::le::{LeSetAdvEnable, LeSetScanEnable, LeSetScanParams},
8 controller::ControllerCmdSync,
9 param::{AddrKind, BdAddr, FilterDuplicates, LeAdvReportsIter},
10};
11use embassy_futures::select::{Either, Either3, select, select3};
12use embassy_time::{Duration, with_timeout};
13use file_system::{ControlCommand, IoErrorKind, Result};
14use heapless::Vec;
15use trouble_host::{
16 BleHostError, Error,
17 prelude::{
18 Advertisement, AdvertisementParameters, AsGatt, ConnectConfig, Connection, ConnectionEvent,
19 DefaultPacketPool, EventHandler, GattClient, HostResources, ScanConfig, Scanner,
20 ServiceHandle, Stack,
21 },
22};
23
24use crate::{node::Request, *};
25
26const DISCOVERY_LIMIT: usize = 8;
27type Pool = DefaultPacketPool;
28type Host<'a, C> = Stack<'a, C, Pool>;
29type Client<'a, C> = GattClient<'a, C, Pool, DISCOVERY_LIMIT>;
30type HostCharacteristic = trouble_host::prelude::Characteristic<[u8]>;
31
32pub trait Controller: trouble_host::Controller + ControllerCmdSync<LeSetScanParams> {}
35
36impl<C> Controller for C where C: trouble_host::Controller + ControllerCmdSync<LeSetScanParams> {}
37
38impl BluetoothDevice {
39 pub async fn run<C: Controller>(&self, controller: C) -> Result<()> {
44 let _running = self.begin_run()?;
45 let mut resources = HostResources::<Pool, 1, 1>::new();
46 let stack = trouble_host::new(controller, &mut resources).build();
47 let mut runner = stack.runner();
48 match select(runner.run_with_handler(&Reports(self)), serve(self, &stack)).await {
49 Either::First(result) => result.map_err(map_error),
50 Either::Second(()) => Ok(()),
51 }
52 }
53}
54
55struct Reports<'a>(&'a BluetoothDevice);
56
57impl EventHandler for Reports<'_> {
58 fn on_adv_reports(&self, reports: LeAdvReportsIter<'_>) {
59 for report in reports.flatten() {
60 let mut result = ScanResult {
61 peer: Address {
62 bytes: report.addr.raw().try_into().expect("six address bytes"),
63 kind: report.addr_kind.as_raw(),
64 },
65 rssi: report.rssi,
66 event_type: report.event_kind as u8,
67 ..ScanResult::default()
68 };
69 if report.data.len() > result.data.bytes.len() {
70 continue;
71 }
72 result.data.length = report.data.len() as u8;
73 result.data.bytes[..report.data.len()].copy_from_slice(report.data);
74 self.0.emit(
75 Event::new(Event::SCAN_RESULT, 0, ConnectionHandle::NONE).with_payload(result),
76 );
77 }
78 }
79}
80
81async fn serve<C: Controller>(device: &BluetoothDevice, stack: &Host<'_, C>) {
82 loop {
83 device.wait_open().await;
84 let mut scanning = None;
85 let mut advertising = None;
86 let mut link = None;
87 let session = async {
88 let mut central = stack.central();
89 let mut peripheral = stack.peripheral();
90 loop {
91 let (command, request) = device.next_request().await;
92 let result = match request {
93 Request::StartScan(configuration)
94 if scanning.is_none() && advertising.is_none() =>
95 {
96 let mut scanner = Scanner::new(&mut central);
97 let configuration = ScanConfig {
98 active: configuration.active != 0,
99 filter_duplicates: if configuration.filter_duplicates != 0 {
100 FilterDuplicates::Enabled
101 } else {
102 FilterDuplicates::Disabled
103 },
104 ..Default::default()
105 };
106 device.set_scanning(true);
107 match scanner.scan(&configuration).await {
108 Ok(scan) => {
109 scanning = Some(scan);
110 Ok(())
111 }
112 Err(error) => {
113 device.set_scanning(false);
114 Err(map_error(error))
115 }
116 }
117 }
118 Request::StopScan => {
119 device.set_scanning(false);
120 if let Some(scan) = scanning.take() {
121 scan.stop().await;
122 }
123 Ok(())
124 }
125 Request::StartAdvertising(data)
126 if advertising.is_none() && scanning.is_none() =>
127 {
128 let advertisement = Advertisement::NonconnectableNonscannableUndirected {
129 adv_data: data.as_slice().expect("validated advertising length"),
130 };
131 match peripheral
132 .advertise(&AdvertisementParameters::default(), advertisement)
133 .await
134 {
135 Ok(advertiser) => {
136 advertising = Some(advertiser);
137 device.set_advertising(true);
138 Ok(())
139 }
140 Err(error) => Err(map_error(error)),
141 }
142 }
143 Request::StopAdvertising => {
144 if advertising.is_some()
145 && let Err(error) = stack.command(LeSetAdvEnable::new(false)).await
146 {
147 Err(map_error(error))
148 } else {
149 drop(advertising.take());
150 device.set_advertising(false);
151 Ok(())
152 }
153 }
154 Request::Connect(request) if scanning.is_none() && advertising.is_none() => {
155 let kind = if request.peer.kind == Address::PUBLIC {
156 AddrKind::PUBLIC
157 } else {
158 AddrKind::RANDOM
159 };
160 let peer =
161 trouble_host::Address::new(kind, BdAddr::new(request.peer.bytes));
162 let configuration = ConnectConfig {
163 scan_config: ScanConfig {
164 filter_accept_list: &[peer],
165 ..Default::default()
166 },
167 connect_params: Default::default(),
168 };
169 let result = with_timeout(
170 Duration::from_millis(u64::from(request.timeout_milliseconds)),
171 async {
172 link =
173 Some(central.connect(&configuration).await.map_err(map_error)?);
174 Client::new(stack, link.as_ref().expect("connected link"))
175 .await
176 .map_err(map_error)
177 },
178 )
179 .await;
180 let result = match result {
181 Ok(Ok(client)) => {
182 let handle = device.connected();
183 device.complete(command, handle, Ok(()));
184 serve_connection(
185 device,
186 handle,
187 link.as_ref().expect("connected link"),
188 &client,
189 )
190 .await;
191 drop(link.take());
192 continue;
193 }
194 Ok(Err(error)) => Err(error),
195 Err(_) => Err(IoErrorKind::TimedOut),
196 };
197 device.complete(command, ConnectionHandle::NONE, result);
198 finish_link(link.take()).await;
199 continue;
200 }
201 Request::Connect(_) | Request::StartScan(_) | Request::StartAdvertising(_) => {
202 Err(IoErrorKind::ResourceBusy)
203 }
204 _ => Err(IoErrorKind::NotConnected),
205 };
206 device.complete(command, ConnectionHandle::NONE, result);
207 }
208 };
209 select(device.wait_closed(), session).await;
210 device.set_scanning(false);
211 if let Some(scan) = scanning {
212 scan.stop().await;
213 }
214 let _ = stack.command(LeSetScanEnable::new(false, false)).await;
216 let _ = stack.command(LeSetAdvEnable::new(false)).await;
217 drop(advertising);
218 finish_link(link).await;
219 device.finish_close();
220 }
221}
222
223async fn serve_connection<C: Controller>(
224 device: &BluetoothDevice,
225 handle: ConnectionHandle,
226 connection: &Connection<'_, Pool>,
227 client: &Client<'_, C>,
228) {
229 let mut listener = match client.listen_all() {
230 Ok(listener) => listener,
231 Err(_) => {
232 connection.disconnect();
233 let reason = disconnected(connection).await;
234 device.disconnected();
235 emit(device, handle, 0, Event::DISCONNECTED, reason);
236 return;
237 }
238 };
239 let active = Cell::new(None);
240 let services = RefCell::new(Vec::<ServiceHandle, DISCOVERY_LIMIT>::new());
241 let subscriptions = RefCell::new(Vec::<u16, DISCOVERY_LIMIT>::new());
242
243 let notifications = async {
244 loop {
245 let notification = listener.next().await;
246 if notification.is_indication() {
247 let _ = client.confirm_indication().await;
248 continue;
249 }
250 if subscriptions.borrow().contains(¬ification.handle()) {
251 let mut value = AttributeValue {
252 handle: notification.handle(),
253 ..AttributeValue::default()
254 };
255 let bytes = notification.as_ref();
256 if bytes.len() <= value.bytes.len() {
257 value.length = bytes.len() as u8;
258 value.bytes[..bytes.len()].copy_from_slice(bytes);
259 emit(device, handle, 0, Event::NOTIFICATION, value);
260 }
261 }
262 }
263 };
264
265 let commands = async {
266 loop {
267 let (command, request) = device.next_request().await;
268 active.set(Some(command));
269 if matches!(request, Request::Disconnect) {
270 connection.disconnect();
271 pending::<()>().await;
272 }
273 let result = run_gatt(
274 device,
275 handle,
276 client,
277 &services,
278 &subscriptions,
279 command,
280 request,
281 connection.att_mtu(),
282 )
283 .await;
284 device.complete(command, handle, result);
285 active.set(None);
286 }
287 };
288
289 let reason = match select3(
290 disconnected(connection),
291 client.task(),
292 select(notifications, commands),
293 )
294 .await
295 {
296 Either3::First(reason) => reason,
297 _ => {
298 if connection.is_connected() {
299 connection.disconnect();
300 }
301 disconnected(connection).await
302 }
303 };
304 device.disconnected();
305 emit(device, handle, 0, Event::DISCONNECTED, reason);
306 if let Some(command) = active.get() {
307 let result = if command == DISCONNECT::IDENTIFIER.get_number() {
308 Ok(())
309 } else {
310 Err(IoErrorKind::NotConnected)
311 };
312 device.complete(command, handle, result);
313 }
314}
315
316async fn disconnected(connection: &Connection<'_, Pool>) -> u8 {
317 loop {
318 if let ConnectionEvent::Disconnected { reason } = connection.next().await {
319 return reason.into_inner();
320 }
321 }
322}
323
324async fn finish_link(link: Option<Connection<'_, Pool>>) {
325 if let Some(link) = link {
326 if link.is_connected() {
327 link.disconnect();
328 }
329 disconnected(&link).await;
330 }
331}
332
333#[allow(clippy::too_many_arguments)]
334async fn run_gatt<C: Controller>(
335 device: &BluetoothDevice,
336 connection: ConnectionHandle,
337 client: &Client<'_, C>,
338 services: &RefCell<Vec<ServiceHandle, DISCOVERY_LIMIT>>,
339 subscriptions: &RefCell<Vec<u16, DISCOVERY_LIMIT>>,
340 command: u8,
341 request: Request,
342 maximum_transmission_unit: u16,
343) -> Result<()> {
344 match request {
345 Request::Services => {
346 let found = client.services().await.map_err(map_error)?;
347 for service in &found {
348 let range = service.handle_range();
349 let payload = Service {
350 first_handle: *range.start(),
351 last_handle: *range.end(),
352 uuid: uuid(service.uuid()),
353 reserved: 0,
354 };
355 emit(device, connection, command, Event::SERVICE, payload);
356 }
357 services.replace(found);
358 }
359 Request::Characteristics(handle) => {
360 let service = services
361 .borrow()
362 .iter()
363 .find(|s| *s.handle_range().start() == handle)
364 .cloned()
365 .ok_or(IoErrorKind::NotFound)?;
366 for item in client
367 .characteristics::<DISCOVERY_LIMIT>(&service)
368 .await
369 .map_err(map_error)?
370 {
371 let payload = Characteristic {
372 value_handle: item.handle,
373 last_handle: item.end_handle,
374 configuration_handle: item.cccd_handle.unwrap_or(0),
375 properties: item.props.as_gatt()[0],
376 uuid: uuid(item.uuid),
377 };
378 emit(device, connection, command, Event::CHARACTERISTIC, payload);
379 }
380 }
381 Request::Descriptors(handle) => {
382 let characteristic = find_characteristic(client, services, handle).await?;
383 for descriptor in client
384 .descriptors::<_, DISCOVERY_LIMIT>(&characteristic)
385 .await
386 .map_err(map_error)?
387 {
388 let payload = Descriptor {
389 handle: descriptor.handle(),
390 uuid: uuid(*descriptor.uuid()),
391 reserved: 0,
392 };
393 emit(device, connection, command, Event::DESCRIPTOR, payload);
394 }
395 }
396 Request::Read(handle) => {
397 let mut bytes = [0; VALUE_CAPACITY + 1];
398 let length = client
399 .read_handle(handle, &mut bytes)
400 .await
401 .map_err(map_error)?;
402 if length > VALUE_CAPACITY {
403 return Err(IoErrorKind::MessageTooLarge);
404 }
405 let mut value = AttributeValue {
406 handle,
407 length: length as u8,
408 ..Default::default()
409 };
410 value.bytes[..length].copy_from_slice(&bytes[..length]);
411 emit(device, connection, command, Event::VALUE, value);
412 }
413 Request::Write(value) => {
414 let bytes = value.as_slice().ok_or(IoErrorKind::InvalidArgument)?;
415 if bytes.len() + 3 > usize::from(maximum_transmission_unit) {
416 return Err(IoErrorKind::MessageTooLarge);
417 }
418 client
419 .write_handle(value.handle, bytes)
420 .await
421 .map_err(map_error)?;
422 }
423 Request::Notifications(request) => {
424 let handle = request.characteristic.handle;
425 let enable = request.enabled != 0;
426 let index = subscriptions
427 .borrow()
428 .iter()
429 .position(|entry| *entry == handle);
430 if enable == index.is_some() {
431 return Ok(());
432 }
433 if enable && subscriptions.borrow().is_full() {
434 return Err(IoErrorKind::NoSpace);
435 }
436 let characteristic = find_characteristic(client, services, handle).await?;
437 if !characteristic
438 .props
439 .any(&[trouble_host::prelude::CharacteristicProp::Notify])
440 {
441 return Err(IoErrorKind::Unsupported);
442 }
443 let configuration = characteristic.cccd_handle.ok_or(IoErrorKind::Unsupported)?;
444 if let Some(index) = index {
445 client
446 .write_handle(configuration, &[0, 0])
447 .await
448 .map_err(map_error)?;
449 subscriptions.borrow_mut().swap_remove(index);
450 } else {
451 subscriptions
452 .borrow_mut()
453 .push(handle)
454 .map_err(|_| IoErrorKind::NoSpace)?;
455 if let Err(error) = client.write_handle(configuration, &[1, 0]).await {
456 subscriptions.borrow_mut().pop();
457 return Err(map_error(error));
458 }
459 }
460 }
461 _ => return Err(IoErrorKind::ResourceBusy),
462 }
463 Ok(())
464}
465
466async fn find_characteristic<C: Controller>(
467 client: &Client<'_, C>,
468 services: &RefCell<Vec<ServiceHandle, DISCOVERY_LIMIT>>,
469 handle: u16,
470) -> Result<HostCharacteristic> {
471 let service = services
472 .borrow()
473 .iter()
474 .find(|s| s.handle_range().contains(&handle))
475 .cloned()
476 .ok_or(IoErrorKind::NotFound)?;
477 client
478 .characteristics::<DISCOVERY_LIMIT>(&service)
479 .await
480 .map_err(map_error)?
481 .into_iter()
482 .find(|item| item.handle == handle)
483 .ok_or(IoErrorKind::NotFound)
484}
485
486fn emit(
487 device: &BluetoothDevice,
488 connection: ConnectionHandle,
489 command: u8,
490 kind: u8,
491 value: impl file_system::PlainData,
492) {
493 device.emit(Event::new(kind, command, connection).with_payload(value));
494}
495
496fn uuid(source: trouble_host::prelude::Uuid) -> Uuid {
497 use trouble_host::prelude::Uuid as HostUuid;
498 let mut uuid = Uuid::default();
499 let source: &[u8] = match &source {
500 HostUuid::Uuid16(bytes) => bytes,
501 HostUuid::Uuid32(bytes) => bytes,
502 HostUuid::Uuid128(bytes) => bytes,
503 };
504 uuid.length = source.len() as u8;
505 uuid.bytes[..source.len()].copy_from_slice(source);
506 uuid
507}
508
509fn map_error<E: embedded_io::Error>(error: BleHostError<E>) -> IoErrorKind {
510 use trouble_host::att::AttErrorCode;
511
512 match error {
513 BleHostError::Controller(error) => match error.kind() {
514 embedded_io::ErrorKind::TimedOut => IoErrorKind::TimedOut,
515 _ => IoErrorKind::InputOutput,
516 },
517 BleHostError::BleHost(error) => match error {
518 Error::Timeout => IoErrorKind::TimedOut,
519 Error::Disconnected => IoErrorKind::NotConnected,
520 Error::NotFound
521 | Error::Att(AttErrorCode::INVALID_HANDLE | AttErrorCode::ATTRIBUTE_NOT_FOUND) => {
522 IoErrorKind::NotFound
523 }
524 Error::Att(
525 AttErrorCode::READ_NOT_PERMITTED
526 | AttErrorCode::WRITE_NOT_PERMITTED
527 | AttErrorCode::INSUFFICIENT_AUTHENTICATION
528 | AttErrorCode::INSUFFICIENT_ENCRYPTION,
529 ) => IoErrorKind::PermissionDenied,
530 Error::InvalidValue => IoErrorKind::InvalidArgument,
531 Error::InsufficientSpace => IoErrorKind::NoSpace,
532 Error::OutOfMemory => IoErrorKind::OutOfMemory,
533 Error::Busy | Error::ConnectionLimitReached => IoErrorKind::ResourceBusy,
534 Error::NotSupported => IoErrorKind::Unsupported,
535 Error::Hci(bt_hci::param::Error::CONN_TIMEOUT) => IoErrorKind::TimedOut,
536 _ => IoErrorKind::ProtocolError,
537 },
538 }
539}