blew 0.1.0

Cross-platform async BLE library for Rust (Apple, Linux, Android)
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use crate::error::{BlewError, BlewResult};
use crate::gatt::props::CharacteristicProperties;
use crate::gatt::service::GattService;
use crate::l2cap::{L2capChannel, types::Psm};
use crate::peripheral::backend::{self, PeripheralBackend};
use crate::peripheral::types::{AdvertisingConfig, PeripheralEvent, ReadResponder, WriteResponder};
use crate::platform::linux::l2cap::bridge_l2cap;
use crate::types::DeviceId;
use bluer::adv::{Advertisement, SecondaryChannel, Type as AdvType};
use bluer::gatt::local::{
    Application, ApplicationHandle, Characteristic, CharacteristicControlHandle,
    CharacteristicNotifier, CharacteristicNotify, CharacteristicNotifyMethod, CharacteristicRead,
    CharacteristicReadRequest, CharacteristicWrite, CharacteristicWriteMethod,
    CharacteristicWriteRequest, ReqError, Service, ServiceControlHandle,
};
use bluer::{Adapter, Session};
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
use tokio_stream::wrappers::{ReceiverStream, UnboundedReceiverStream};
use tracing::{debug, trace, warn};
use uuid::Uuid;

/// tokio::sync::Mutex so we can await `notify()` without holding a std MutexGuard
/// across the await point.
type SharedNotifier = Arc<tokio::sync::Mutex<CharacteristicNotifier>>;

struct PeripheralInner {
    _session: Session,
    adapter: Adapter,
    pending_services: Mutex<Vec<GattService>>,
    adv_handle: Mutex<Option<bluer::adv::AdvertisementHandle>>,
    app_handle: Mutex<Option<ApplicationHandle>>,
    notifiers: Mutex<HashMap<Uuid, Vec<SharedNotifier>>>,
    event_tx: Arc<Mutex<Option<mpsc::UnboundedSender<PeripheralEvent>>>>,
    _adapter_task: tokio::task::JoinHandle<()>,
}

pub struct LinuxPeripheral(Arc<PeripheralInner>);

impl backend::private::Sealed for LinuxPeripheral {}

fn emit(inner: &Arc<PeripheralInner>, event: PeripheralEvent) {
    let guard = inner.event_tx.lock().unwrap();
    if let Some(tx) = guard.as_ref() {
        let _ = tx.send(event);
    }
}

#[allow(clippy::too_many_lines)]
fn build_characteristic(
    ch: &crate::gatt::service::GattCharacteristic,
    svc_uuid: Uuid,
    inner: &Arc<PeripheralInner>,
) -> Characteristic {
    let uuid = ch.uuid;
    let props = ch.properties;

    let read = if props.contains(CharacteristicProperties::READ) {
        // Static value -- auto-respond without round-tripping through the event
        // handler (matches CoreBluetooth behaviour for characteristics with a
        // non-nil value).
        let static_value = if ch.value.is_empty() {
            None
        } else {
            Some(ch.value.clone())
        };

        let inner_r = Arc::clone(inner);
        Some(CharacteristicRead {
            read: true,
            fun: Box::new(move |req: CharacteristicReadRequest| {
                let inner_r = Arc::clone(&inner_r);
                let static_value = static_value.clone();
                Box::pin(async move {
                    if let Some(val) = static_value {
                        let offset = req.offset as usize;
                        return Ok(if offset > 0 && offset < val.len() {
                            val[offset..].to_vec()
                        } else {
                            val
                        });
                    }

                    let client_id = DeviceId(req.device_address.to_string());
                    let (tx, rx) = tokio::sync::oneshot::channel();
                    emit(
                        &inner_r,
                        PeripheralEvent::ReadRequest {
                            client_id,
                            service_uuid: svc_uuid,
                            char_uuid: uuid,
                            offset: req.offset,
                            responder: ReadResponder::new(tx),
                        },
                    );
                    match rx.await {
                        Ok(Ok(value)) => Ok(value),
                        _ => Err(ReqError::Failed),
                    }
                })
            }),
            ..Default::default()
        })
    } else {
        None
    };

    let write = if props.intersects(
        CharacteristicProperties::WRITE | CharacteristicProperties::WRITE_WITHOUT_RESPONSE,
    ) {
        let inner_w = Arc::clone(inner);
        let write_req = props.contains(CharacteristicProperties::WRITE);
        let write_cmd = props.contains(CharacteristicProperties::WRITE_WITHOUT_RESPONSE);
        Some(CharacteristicWrite {
            write: write_req,
            write_without_response: write_cmd,
            method: CharacteristicWriteMethod::Fun(Box::new(
                move |value: Vec<u8>, req: CharacteristicWriteRequest| {
                    let inner_w = Arc::clone(&inner_w);
                    Box::pin(async move {
                        let client_id = DeviceId(req.device_address.to_string());
                        let (responder, rx) = if req.op_type == bluer::gatt::WriteOp::Request {
                            let (tx, rx) = tokio::sync::oneshot::channel::<bool>();
                            (Some(WriteResponder::new(tx)), Some(rx))
                        } else {
                            (None, None)
                        };
                        emit(
                            &inner_w,
                            PeripheralEvent::WriteRequest {
                                client_id,
                                service_uuid: svc_uuid,
                                char_uuid: uuid,
                                value,
                                responder,
                            },
                        );
                        if let Some(rx) = rx {
                            match rx.await {
                                Ok(true) => Ok(()),
                                _ => Err(ReqError::Failed),
                            }
                        } else {
                            Ok(())
                        }
                    })
                },
            )),
            ..Default::default()
        })
    } else {
        None
    };

    let notify = if props.contains(CharacteristicProperties::NOTIFY) {
        let inner_n = Arc::clone(inner);
        Some(CharacteristicNotify {
            notify: true,
            method: CharacteristicNotifyMethod::Fun(Box::new(
                move |notifier: CharacteristicNotifier| {
                    let inner_n = Arc::clone(&inner_n);
                    Box::pin(async move {
                        inner_n
                            .notifiers
                            .lock()
                            .unwrap()
                            .entry(uuid)
                            .or_default()
                            .push(Arc::new(tokio::sync::Mutex::new(notifier)));
                        emit(
                            &inner_n,
                            PeripheralEvent::SubscriptionChanged {
                                client_id: DeviceId(String::new()),
                                char_uuid: uuid,
                                subscribed: true,
                            },
                        );
                    })
                },
            )),
            ..Default::default()
        })
    } else {
        None
    };

    Characteristic {
        uuid,
        handle: None,
        broadcast: false,
        writable_auxiliaries: false,
        authorize: false,
        descriptors: vec![],
        read,
        write,
        notify,
        control_handle: CharacteristicControlHandle::default(),
        _non_exhaustive: (),
    }
}

impl PeripheralBackend for LinuxPeripheral {
    type EventStream = UnboundedReceiverStream<PeripheralEvent>;

    async fn new() -> BlewResult<Self>
    where
        Self: Sized,
    {
        let session = Session::new().await.map_err(|e| BlewError::Peripheral {
            source: Box::new(e),
        })?;
        let adapter = session
            .default_adapter()
            .await
            .map_err(|_| BlewError::AdapterNotFound)?;
        debug!(adapter = %adapter.name(), "BLE adapter initialized");
        let event_tx: Arc<Mutex<Option<mpsc::UnboundedSender<PeripheralEvent>>>> =
            Arc::new(Mutex::new(None));
        let event_tx_clone = Arc::clone(&event_tx);
        let adapter_clone = adapter.clone();
        let adapter_task = tokio::spawn(async move {
            use tokio_stream::StreamExt as _;
            let Ok(events) = adapter_clone.events().await else {
                warn!("failed to subscribe to adapter events");
                return;
            };
            let mut events = Box::pin(events);
            while let Some(event) = events.next().await {
                if let bluer::AdapterEvent::PropertyChanged(bluer::AdapterProperty::Powered(
                    powered,
                )) = event
                {
                    debug!(powered, "peripheral adapter state changed");
                    let guard = event_tx_clone.lock().unwrap();
                    if let Some(tx) = guard.as_ref() {
                        let _ = tx.send(PeripheralEvent::AdapterStateChanged { powered });
                    }
                }
            }
        });
        Ok(LinuxPeripheral(Arc::new(PeripheralInner {
            _session: session,
            adapter,
            pending_services: Mutex::new(Vec::new()),
            adv_handle: Mutex::new(None),
            app_handle: Mutex::new(None),
            notifiers: Mutex::new(HashMap::new()),
            event_tx,
            _adapter_task: adapter_task,
        })))
    }

    fn is_powered(&self) -> impl Future<Output = BlewResult<bool>> + Send {
        let handle = Arc::clone(&self.0);
        async move {
            handle
                .adapter
                .is_powered()
                .await
                .map_err(|e| BlewError::Peripheral {
                    source: Box::new(e),
                })
        }
    }

    fn add_service(&self, service: &GattService) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        let service = service.clone();
        async move {
            debug!(service_uuid = %service.uuid, characteristics = service.characteristics.len(), "queuing GATT service");
            handle.pending_services.lock().unwrap().push(service);
            Ok(())
        }
    }

    fn start_advertising(
        &self,
        config: &AdvertisingConfig,
    ) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        let config = config.clone();
        async move {
            if handle.adv_handle.lock().unwrap().is_some() {
                return Err(BlewError::AlreadyAdvertising);
            }
            debug!(local_name = %config.local_name, "starting advertising");

            let pending: Vec<GattService> = handle.pending_services.lock().unwrap().clone();
            let bluer_services: Vec<Service> = pending
                .iter()
                .map(|svc| {
                    let chars = svc
                        .characteristics
                        .iter()
                        .map(|ch| build_characteristic(ch, svc.uuid, &handle))
                        .collect();
                    Service {
                        uuid: svc.uuid,
                        handle: None,
                        primary: svc.primary,
                        characteristics: chars,
                        control_handle: ServiceControlHandle::default(),
                        _non_exhaustive: (),
                    }
                })
                .collect();

            let app = Application {
                services: bluer_services,
                _non_exhaustive: (),
            };
            let app_handle = handle
                .adapter
                .serve_gatt_application(app)
                .await
                .map_err(|e| BlewError::Peripheral {
                    source: Box::new(e),
                })?;
            *handle.app_handle.lock().unwrap() = Some(app_handle);

            // Prefer BLE 5 extended advertising with a 2M secondary channel so
            // that BLE 5 centrals can connect at 2M PHY from the start.
            // Fall back to legacy advertising when the hardware or kernel
            // doesn't support extended advertising (BLE 4.x adapters).
            let make_adv = |secondary_channel| Advertisement {
                advertisement_type: AdvType::Peripheral,
                local_name: Some(config.local_name.clone()),
                service_uuids: config.service_uuids.clone().into_iter().collect(),
                secondary_channel,
                ..Default::default()
            };
            let adv_handle = match handle
                .adapter
                .advertise(make_adv(Some(SecondaryChannel::TwoM)))
                .await
            {
                Ok(h) => {
                    debug!("advertising started (BLE 5 extended)");
                    h
                }
                Err(e) => {
                    warn!(error = %e, "BLE 5 extended advertising unavailable, falling back to legacy");
                    let h = handle
                        .adapter
                        .advertise(make_adv(None))
                        .await
                        .map_err(|e| BlewError::Peripheral {
                            source: Box::new(e),
                        })?;
                    debug!("advertising started (legacy)");
                    h
                }
            };
            *handle.adv_handle.lock().unwrap() = Some(adv_handle);

            Ok(())
        }
    }

    fn stop_advertising(&self) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        async move {
            debug!("stopping advertising");
            handle.adv_handle.lock().unwrap().take();
            handle.app_handle.lock().unwrap().take();
            handle.notifiers.lock().unwrap().clear();
            Ok(())
        }
    }

    fn notify_characteristic(
        &self,
        _device_id: &crate::types::DeviceId,
        char_uuid: Uuid,
        value: Vec<u8>,
    ) -> impl Future<Output = BlewResult<()>> + Send {
        // NOTE: BlueZ's `CharacteristicNotifier` callback does not expose the
        // remote device identity, so we cannot route a notification to a
        // specific subscriber here. Every live notifier for the characteristic
        // receives the value. See the trait doc for details.
        let handle = Arc::clone(&self.0);
        async move {
            trace!(%char_uuid, len = value.len(), "notifying characteristic");
            // Collect live notifiers without holding the outer Mutex across awaits.
            let arcs: Vec<SharedNotifier> = handle
                .notifiers
                .lock()
                .unwrap()
                .get(&char_uuid)
                .cloned()
                .unwrap_or_default();

            let mut any_stopped = false;
            for arc in arcs {
                let mut notifier = arc.lock().await;
                if notifier.is_stopped() {
                    any_stopped = true;
                    continue;
                }
                // Best-effort: ignore errors on individual notifiers.
                let _ = notifier.notify(value.clone()).await;
            }

            if any_stopped {
                handle
                    .notifiers
                    .lock()
                    .unwrap()
                    .entry(char_uuid)
                    .and_modify(|v| {
                        v.retain(|arc| !arc.try_lock().map_or(true, |n| n.is_stopped()));
                    });
            }
            Ok(())
        }
    }

    async fn l2cap_listener(
        &self,
    ) -> BlewResult<(
        Psm,
        impl futures_core::Stream<Item = BlewResult<(DeviceId, L2capChannel)>> + Send + 'static,
    )> {
        debug!("starting L2CAP CoC listener");
        // Use low-level Socket API to explicitly set security to Low,
        // preventing BlueZ from triggering a pairing request.
        let socket = bluer::l2cap::Socket::new_stream().map_err(|e| BlewError::L2cap {
            source: Box::new(e),
        })?;
        socket
            .set_security(bluer::l2cap::Security {
                level: bluer::l2cap::SecurityLevel::Low,
                key_size: 0,
            })
            .map_err(|e| BlewError::L2cap {
                source: Box::new(e),
            })?;
        // Advertise a large receive MPS so the peer can send bigger PDUs.
        socket.set_recv_mtu(65535).map_err(|e| BlewError::L2cap {
            source: Box::new(e),
        })?;
        socket
            .bind(bluer::l2cap::SocketAddr::any_le())
            .map_err(|e| BlewError::L2cap {
                source: Box::new(e),
            })?;
        let listener = socket.listen(1).map_err(|e| BlewError::L2cap {
            source: Box::new(e),
        })?;
        let local_addr = listener
            .as_ref()
            .local_addr()
            .map_err(|e| BlewError::L2cap {
                source: Box::new(e),
            })?;
        let psm = Psm(local_addr.psm);
        debug!(psm = psm.0, "L2CAP listener ready");

        let (tx, rx) = mpsc::channel::<BlewResult<(DeviceId, L2capChannel)>>(16);
        tokio::spawn(async move {
            loop {
                match listener.accept().await {
                    Ok((stream, addr)) => {
                        debug!(peer = ?addr, "incoming L2CAP connection accepted");
                        let device_id = DeviceId(addr.addr.to_string());
                        if tx
                            .send(Ok((device_id, bridge_l2cap(stream))))
                            .await
                            .is_err()
                        {
                            break;
                        }
                    }
                    Err(e) => {
                        warn!(error = %e, "L2CAP accept error");
                        let _ = tx
                            .send(Err(BlewError::L2cap {
                                source: Box::new(e),
                            }))
                            .await;
                        break;
                    }
                }
            }
        });

        Ok((psm, ReceiverStream::new(rx)))
    }

    fn events(&self) -> Self::EventStream {
        let (tx, rx) = mpsc::unbounded_channel();
        *self.0.event_tx.lock().unwrap() = Some(tx);
        UnboundedReceiverStream::new(rx)
    }
}