Skip to main content

webbluetooth_linux/
gatt.rs

1//! A GATT client over an L2CAP socket, with no daemon in the way.
2//!
3//! Connecting an L2CAP socket to CID 4 — the fixed ATT channel — makes the
4//! kernel establish the LE link and hands back a GATT connection. From there
5//! everything is [`crate::att`] PDUs.
6//!
7//! # Serialising requests
8//!
9//! ATT allows exactly **one outstanding request per connection**: the peer will
10//! not answer a second until the first is done. So a request takes a lock,
11//! writes, and waits for its reply, while a reader thread separates replies
12//! from unsolicited notifications — which may arrive at any time, including in
13//! the middle of a request, and must not be mistaken for its answer.
14
15use crate::att::{self, AttError, Characteristic, Descriptor, Response, Service, Uuid};
16use crate::sys::{
17    address_type, bind_le_source, close, connect, errno, parse_address, read, shutdown, socket,
18    wait_ready, write, Ready, SockAddrL2, AF_BLUETOOTH, BTPROTO_L2CAP, EINTR, POLLIN, POLLOUT,
19    SHUT_RDWR, SOCK_SEQPACKET,
20};
21use std::ffi::c_int;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Condvar, Mutex};
24use std::time::Duration;
25
26const ATT_CID: u16 = 4;
27const DEFAULT_MTU: u16 = 517;
28const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
29
30/// Why a GATT operation failed.
31#[derive(Debug, Clone)]
32pub enum Error {
33    /// The socket could not be opened or connected.
34    Io(String),
35    /// The peer refused, with an ATT error code.
36    Att(AttError),
37    /// No reply within the deadline.
38    Timeout,
39    /// The link dropped.
40    Disconnected,
41    /// A reply that did not decode, or was not the one asked for.
42    Protocol(String),
43}
44
45impl std::fmt::Display for Error {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Self::Io(m) => write!(f, "{m}"),
49            Self::Att(e) => write!(f, "the peer refused: {e}"),
50            Self::Timeout => f.write_str("the peer did not answer"),
51            Self::Disconnected => f.write_str("the link dropped"),
52            Self::Protocol(m) => write!(f, "protocol error: {m}"),
53        }
54    }
55}
56
57type Result<T> = std::result::Result<T, Error>;
58
59/// Where unsolicited traffic goes.
60pub trait NotificationSink: Send + Sync {
61    /// A `Handle Value Notification` or `Indication` arrived.
62    fn on_notification(&self, handle: u16, value: Vec<u8>);
63    /// The link dropped.
64    fn on_disconnected(&self);
65}
66
67struct Shared {
68    fd: c_int,
69    /// The reply to the request in flight, if it has arrived.
70    reply: Mutex<Option<Response>>,
71    arrived: Condvar,
72    stopped: AtomicBool,
73}
74
75impl Shared {
76    /// Write a PDU with a short deadline, discarding failures.
77    ///
78    /// Used for the replies this side owes the peer. There is nobody to report
79    /// a failure to and nothing useful to do about one, but it still must not
80    /// block the reader thread indefinitely.
81    fn send(&self, pdu: &[u8]) {
82        if !matches!(wait_ready(self.fd, POLLOUT, 1000), Ok(Ready::Yes)) {
83            return;
84        }
85        unsafe { write(self.fd, pdu.as_ptr(), pdu.len()) };
86    }
87
88    /// Answer a request the peer made of us.
89    ///
90    /// This crate is a GATT client and has no attribute database to serve, but
91    /// a client still shares the connection with a peer that may ask. BlueZ
92    /// opens with `Exchange MTU Request`, and leaving it unanswered leaves the
93    /// peer waiting on a reply that never comes. Everything else is declined
94    /// properly, which is what `Error Response` is for.
95    fn answer(&self, opcode: u8, body: &[u8]) {
96        if opcode == att::opcode::EXCHANGE_MTU_REQUEST && body.len() >= 2 {
97            self.send(&att::exchange_mtu_response(DEFAULT_MTU));
98            return;
99        }
100        // The handle, where the request carries one, so the error names it.
101        let handle = if body.len() >= 2 {
102            u16::from_le_bytes([body[0], body[1]])
103        } else {
104            0
105        };
106        self.send(&att::error_response(
107            opcode,
108            handle,
109            AttError(AttError::REQUEST_NOT_SUPPORTED),
110        ));
111    }
112}
113
114impl Drop for Shared {
115    fn drop(&mut self) {
116        unsafe { close(self.fd) };
117    }
118}
119
120/// A GATT connection to one peer.
121pub struct Connection {
122    shared: Arc<Shared>,
123    /// ATT allows one outstanding request; this enforces it.
124    in_flight: Mutex<()>,
125    mtu: Mutex<u16>,
126    peer: String,
127}
128
129impl Connection {
130    /// Open an ATT connection to `address`.
131    ///
132    /// `random_address` must match how the peer advertised — connecting to a
133    /// random address as though it were public simply times out.
134    pub fn open(
135        address: &str,
136        random_address: bool,
137        sink: Arc<dyn NotificationSink>,
138    ) -> Result<Self> {
139        let bdaddr = parse_address(address)
140            .ok_or_else(|| Error::Io(format!("{address:?} is not a Bluetooth address")))?;
141
142        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
143        if fd < 0 {
144            return Err(Error::Io(format!(
145                "could not create an L2CAP socket (errno {})",
146                errno()
147            )));
148        }
149
150        if let Err(e) = bind_le_source(fd, 0, ATT_CID) {
151            unsafe { close(fd) };
152            return Err(Error::Io(format!(
153                "could not bind an LE ATT socket (errno {e})"
154            )));
155        }
156
157        let addr = SockAddrL2 {
158            family: AF_BLUETOOTH as u16,
159            psm: 0,
160            bdaddr,
161            cid: ATT_CID.to_le(),
162            bdaddr_type: address_type(random_address),
163        };
164        if unsafe { connect(fd, &addr, std::mem::size_of::<SockAddrL2>() as u32) } < 0 {
165            let e = errno();
166            unsafe { close(fd) };
167            return Err(Error::Io(connect_error(address, e)));
168        }
169
170        let shared = Arc::new(Shared {
171            fd,
172            reply: Mutex::new(None),
173            arrived: Condvar::new(),
174            stopped: AtomicBool::new(false),
175        });
176        spawn_reader(shared.clone(), sink);
177
178        let connection = Self {
179            shared,
180            in_flight: Mutex::new(()),
181            mtu: Mutex::new(23),
182            peer: address.to_owned(),
183        };
184
185        // Negotiate up from the 23-byte default. A peer that refuses keeps 23,
186        // which is correct rather than fatal.
187        if let Ok(Response::Mtu(mtu)) = connection.request(&att::exchange_mtu_request(DEFAULT_MTU))
188        {
189            *connection.mtu.lock().unwrap() = mtu.clamp(23, DEFAULT_MTU);
190        }
191        Ok(connection)
192    }
193
194    pub fn peer(&self) -> &str {
195        &self.peer
196    }
197
198    /// The negotiated ATT MTU. A write carries `mtu - 3` bytes.
199    pub fn mtu(&self) -> u16 {
200        *self.mtu.lock().unwrap()
201    }
202
203    pub fn is_connected(&self) -> bool {
204        !self.shared.stopped.load(Ordering::Acquire)
205    }
206
207    pub fn close(&self) {
208        self.shared.stopped.store(true, Ordering::Release);
209        unsafe { shutdown(self.shared.fd, SHUT_RDWR) };
210    }
211
212    /// Send one request and wait for its reply.
213    fn request(&self, pdu: &[u8]) -> Result<Response> {
214        let _one_at_a_time = self.in_flight.lock().map_err(|_| Error::Disconnected)?;
215        if !self.is_connected() {
216            return Err(Error::Disconnected);
217        }
218        *self.shared.reply.lock().unwrap() = None;
219
220        let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
221        self.send(pdu, deadline)?;
222
223        let mut guard = self.shared.reply.lock().map_err(|_| Error::Disconnected)?;
224        while guard.is_none() {
225            if !self.is_connected() {
226                return Err(Error::Disconnected);
227            }
228            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
229            if remaining.is_zero() {
230                return Err(Error::Timeout);
231            }
232            let (g, _) = self
233                .shared
234                .arrived
235                .wait_timeout(guard, remaining)
236                .map_err(|_| Error::Disconnected)?;
237            guard = g;
238        }
239        guard.take().ok_or(Error::Disconnected)
240    }
241
242    /// Write one PDU, waiting for the socket rather than blocking in it.
243    ///
244    /// A bare `write` on an L2CAP socket has no deadline: if the channel is
245    /// suspended — which the kernel does while security is pending — the call
246    /// parks in `bt_sock_wait_ready` with `SO_SNDTIMEO` unset and never
247    /// returns. That is a hang with no error and no timeout, below the reach of
248    /// the deadline this request is already carrying. Polling first gives the
249    /// deadline somewhere to apply.
250    fn send(&self, pdu: &[u8], deadline: std::time::Instant) -> Result<()> {
251        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
252        if remaining.is_zero() {
253            return Err(Error::Timeout);
254        }
255        let ms = remaining.as_millis().min(i32::MAX as u128) as i32;
256        match wait_ready(self.shared.fd, POLLOUT, ms) {
257            Ok(Ready::Yes) => {}
258            Ok(Ready::TimedOut) => return Err(Error::Timeout),
259            Ok(Ready::Closed) => return Err(Error::Disconnected),
260            Err(e) => return Err(Error::Io(format!("poll failed (errno {e})"))),
261        }
262        let n = unsafe { write(self.shared.fd, pdu.as_ptr(), pdu.len()) };
263        if n as usize != pdu.len() {
264            return Err(Error::Io(format!("ATT write failed (errno {})", errno())));
265        }
266        Ok(())
267    }
268
269    /// Write a value in `Prepare Write` fragments, then apply them.
270    ///
271    /// One `Write Request` carries at most `MTU - 3` bytes, but a GATT
272    /// attribute holds up to 512. Anything longer has to be queued in
273    /// fragments and committed with `Execute Write`, or the peer rejects the
274    /// oversized request.
275    fn write_long(&self, handle: u16, value: &[u8]) -> Result<()> {
276        // Prepare Write spends two more header bytes than Write Request on the
277        // offset.
278        let chunk = (*self.mtu.lock().unwrap() as usize)
279            .saturating_sub(5)
280            .max(1);
281        for (i, part) in value.chunks(chunk).enumerate() {
282            let offset = (i * chunk) as u16;
283            match self.checked(&att::prepare_write_request(handle, offset, part)) {
284                Ok(Response::PrepareWriteComplete) => {}
285                Ok(other) => {
286                    // Abandon the queue rather than leave a partial value to be
287                    // committed by anyone else.
288                    let _ = self.request(&att::execute_write_request(false));
289                    return Err(Error::Protocol(format!(
290                        "unexpected reply to a prepared write: {other:?}"
291                    )));
292                }
293                Err(e) => {
294                    let _ = self.request(&att::execute_write_request(false));
295                    return Err(e);
296                }
297            }
298        }
299        match self.checked(&att::execute_write_request(true))? {
300            Response::WriteComplete => Ok(()),
301            other => Err(Error::Protocol(format!(
302                "unexpected reply to an executed write: {other:?}"
303            ))),
304        }
305    }
306
307    /// Send a request, turning an ATT error reply into an `Err`.
308    fn checked(&self, pdu: &[u8]) -> Result<Response> {
309        match self.request(pdu)? {
310            Response::Error { error, .. } => Err(Error::Att(error)),
311            other => Ok(other),
312        }
313    }
314
315    /// Every primary service on the peer.
316    ///
317    /// Repeats `Read By Group Type` from where the last reply stopped until the
318    /// peer answers `ATTRIBUTE_NOT_FOUND`, which is how it says "no more".
319    pub fn discover_services(&self) -> Result<Vec<Service>> {
320        let mut found: Vec<Service> = Vec::new();
321        let mut start = 0x0001u16;
322        loop {
323            let pdu =
324                att::read_by_group_type_request(start, 0xFFFF, att::gatt_type::PRIMARY_SERVICE);
325            match self.request(&pdu)? {
326                Response::Services(batch) if !batch.is_empty() => {
327                    let last = batch.last().map(|s| s.end_handle).unwrap_or(0xFFFF);
328                    found.extend(batch);
329                    // `last` is a u16, so this is the only way the range ends.
330                    if last == 0xFFFF {
331                        break;
332                    }
333                    start = last + 1;
334                }
335                Response::Error { error, .. } if error.is_end_of_discovery() => break,
336                Response::Error { error, .. } => return Err(Error::Att(error)),
337                other => {
338                    return Err(Error::Protocol(format!(
339                        "unexpected reply to discovery: {other:?}"
340                    )))
341                }
342            }
343        }
344        Ok(found)
345    }
346
347    /// Every characteristic within a service's handle range.
348    /// The services this one includes.
349    ///
350    /// An `Include` declaration whose included service has a 128-bit UUID does
351    /// not carry it, so the UUID is read from the included service's own
352    /// declaration — otherwise the caller would have a handle range it cannot
353    /// name.
354    pub fn discover_included_services(&self, service: &Service) -> Result<Vec<Service>> {
355        let mut found: Vec<Service> = Vec::new();
356        let mut start = service.start_handle;
357        loop {
358            if start > service.end_handle {
359                break;
360            }
361            let pdu = att::read_by_type_request(start, service.end_handle, att::gatt_type::INCLUDE);
362            match self.request(&pdu)? {
363                Response::Includes(batch) if !batch.is_empty() => {
364                    let last = batch.last().map(|i| i.handle).unwrap_or(service.end_handle);
365                    for include in batch {
366                        let uuid = match include.uuid {
367                            Some(uuid) => uuid,
368                            // A 128-bit included service: read its declaration.
369                            None => match self.read(include.start_handle) {
370                                Ok(bytes) => match att::Uuid::parse(&bytes) {
371                                    Some(uuid) => uuid,
372                                    None => continue,
373                                },
374                                Err(_) => continue,
375                            },
376                        };
377                        found.push(Service {
378                            start_handle: include.start_handle,
379                            end_handle: include.end_handle,
380                            uuid,
381                        });
382                    }
383                    if last >= service.end_handle {
384                        break;
385                    }
386                    start = last + 1;
387                }
388                // An empty batch or "attribute not found" both mean there are
389                // no more; a service that includes nothing is the common case.
390                Response::Includes(_) => break,
391                Response::Error { error, .. } if error.is_end_of_discovery() => break,
392                Response::Error { error, .. } => return Err(Error::Att(error)),
393                other => {
394                    return Err(Error::Protocol(format!(
395                        "unexpected reply to include discovery: {other:?}"
396                    )))
397                }
398            }
399        }
400        Ok(found)
401    }
402
403    pub fn discover_characteristics(&self, service: &Service) -> Result<Vec<Characteristic>> {
404        let mut found: Vec<Characteristic> = Vec::new();
405        let mut start = service.start_handle;
406        loop {
407            if start > service.end_handle {
408                break;
409            }
410            let pdu = att::read_by_type_request(
411                start,
412                service.end_handle,
413                att::gatt_type::CHARACTERISTIC,
414            );
415            match self.request(&pdu)? {
416                Response::Characteristics(batch) if !batch.is_empty() => {
417                    let last = batch.last().map(|c| c.handle).unwrap_or(service.end_handle);
418                    found.extend(batch);
419                    if last >= service.end_handle {
420                        break;
421                    }
422                    start = last + 1;
423                }
424                Response::Error { error, .. } if error.is_end_of_discovery() => break,
425                Response::Error { error, .. } => return Err(Error::Att(error)),
426                other => {
427                    return Err(Error::Protocol(format!(
428                        "unexpected reply to discovery: {other:?}"
429                    )))
430                }
431            }
432        }
433        Ok(found)
434    }
435
436    /// The descriptors of one characteristic — everything between its value
437    /// handle and the next characteristic (or the end of the service).
438    pub fn discover_descriptors(&self, start: u16, end: u16) -> Result<Vec<Descriptor>> {
439        if start > end {
440            return Ok(Vec::new());
441        }
442        let mut found: Vec<Descriptor> = Vec::new();
443        let mut cursor = start;
444        loop {
445            if cursor > end {
446                break;
447            }
448            match self.request(&att::find_information_request(cursor, end))? {
449                Response::Descriptors(batch) if !batch.is_empty() => {
450                    let last = batch.last().map(|d| d.handle).unwrap_or(end);
451                    found.extend(batch);
452                    if last >= end {
453                        break;
454                    }
455                    cursor = last + 1;
456                }
457                Response::Error { error, .. } if error.is_end_of_discovery() => break,
458                Response::Error { error, .. } => return Err(Error::Att(error)),
459                other => {
460                    return Err(Error::Protocol(format!(
461                        "unexpected reply to discovery: {other:?}"
462                    )))
463                }
464            }
465        }
466        Ok(found)
467    }
468
469    /// Read an attribute, following on with `Read Blob` if the value filled the
470    /// MTU — which is the only signal that there is more of it.
471    pub fn read(&self, handle: u16) -> Result<Vec<u8>> {
472        let Response::Value(mut value) = self.checked(&att::read_request(handle))? else {
473            return Err(Error::Protocol("expected a value".into()));
474        };
475        let first_chunk = self.mtu() as usize - 1;
476        while value.len() == first_chunk + (value.len() - first_chunk) && value.len() >= first_chunk
477        {
478            let offset = value.len() as u16;
479            match self.checked(&att::read_blob_request(handle, offset)) {
480                Ok(Response::Value(more)) if !more.is_empty() => value.extend_from_slice(&more),
481                // `ATTRIBUTE_NOT_LONG` and an empty blob both mean "that was all".
482                _ => break,
483            }
484            if value.len() >= 512 {
485                break;
486            }
487        }
488        Ok(value)
489    }
490
491    /// Write and wait for the peer to acknowledge.
492    pub fn write(&self, handle: u16, value: &[u8]) -> Result<()> {
493        // One Write Request carries `MTU - 3` bytes. Longer values have to go
494        // as prepared fragments; sending an oversized request instead gets it
495        // refused, or silently truncated by a lenient peer.
496        let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
497        if value.len() > single {
498            return self.write_long(handle, value);
499        }
500        match self.checked(&att::write_request(handle, value))? {
501            Response::WriteComplete => Ok(()),
502            other => Err(Error::Protocol(format!(
503                "unexpected reply to a write: {other:?}"
504            ))),
505        }
506    }
507
508    /// Write without acknowledgement. Nothing comes back, so nothing is waited
509    /// for and a dropped write is invisible.
510    pub fn write_command(&self, handle: u16, value: &[u8]) -> Result<()> {
511        // There is no unacknowledged form of a long write: `Prepare Write` is
512        // a request and needs its response. Refusing beats sending a truncated
513        // value that the caller believes was delivered whole.
514        let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
515        if value.len() > single {
516            return Err(Error::Protocol(format!(
517                "{} bytes does not fit one unacknowledged write (MTU allows {single}); \
518                 use an acknowledged write",
519                value.len()
520            )));
521        }
522        let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
523        self.send(&att::write_command(handle, value), deadline)
524    }
525
526    /// Subscribe by writing the Client Characteristic Configuration descriptor.
527    ///
528    /// There is no "subscribe" in ATT — `0x0001` asks for notifications,
529    /// `0x0002` for indications, `0x0000` stops both.
530    pub fn set_notify(&self, cccd_handle: u16, notify: bool, indicate: bool) -> Result<()> {
531        let bits: u16 = u16::from(notify) | (u16::from(indicate) << 1);
532        self.write(cccd_handle, &bits.to_le_bytes())
533    }
534}
535
536/// Say why an ATT connect failed, where the errno alone would not.
537///
538/// `EBUSY` is the one worth explaining. Linux gives an LE link exactly one ATT
539/// channel, and when `bluetoothd` is running it takes that channel for itself
540/// on any link it brings up — which it does on its own for a bonded device on
541/// its auto-connect list, as soon as the device advertises. The link is then up
542/// before this backend asks, its ATT channel is spoken for, and there is no
543/// sharing it: this backend cannot reach that device while the daemon holds it.
544fn connect_error(address: &str, errno: i32) -> String {
545    if errno == crate::sys::EBUSY {
546        format!(
547            "could not connect to {address}: its LE link already has an ATT client \
548             (errno {errno}), almost certainly bluetoothd, which connects bonded devices \
549             by itself. linux-hci cannot share a link with it; disconnect the device \
550             in bluetoothd (`bluetoothctl disconnect {address}`) and take it off \
551             auto-connect, or stop bluetoothd"
552        )
553    } else {
554        format!("could not connect to {address} (errno {errno})")
555    }
556}
557
558impl Drop for Connection {
559    fn drop(&mut self) {
560        self.close();
561    }
562}
563
564fn spawn_reader(shared: Arc<Shared>, sink: Arc<dyn NotificationSink>) {
565    std::thread::Builder::new()
566        .name("webbluetooth-att".into())
567        .spawn(move || {
568            let mut buf = vec![0u8; 1024];
569            while !shared.stopped.load(Ordering::Acquire) {
570                // Poll rather than block in `read`, so `close()` is observed
571                // instead of leaving this thread parked on a dead descriptor.
572                match wait_ready(shared.fd, POLLIN, 250) {
573                    Ok(Ready::Yes) => {}
574                    Ok(Ready::TimedOut) => continue,
575                    Ok(Ready::Closed) => break,
576                    Err(e) if e == EINTR => continue,
577                    Err(_) => break,
578                }
579                let n = unsafe { read(shared.fd, buf.as_mut_ptr(), buf.len()) };
580                if n <= 0 {
581                    if n < 0 && errno() == EINTR {
582                        continue; // EINTR
583                    }
584                    break;
585                }
586                let pdu = &buf[..n as usize];
587                let Some(response) = att::parse(pdu) else {
588                    continue;
589                };
590
591                // Three kinds of inbound PDU, and only one of them is a reply.
592                // Unsolicited values are delivered to the sink; the peer's own
593                // requests are answered; everything else is the response to
594                // whatever request is in flight.
595                match response {
596                    Response::Notification { handle, value } => sink.on_notification(handle, value),
597                    Response::Indication { handle, value } => {
598                        sink.on_notification(handle, value);
599                        shared.send(&att::handle_value_confirmation());
600                    }
601                    Response::PeerRequest { opcode, body } => {
602                        shared.answer(opcode, &body);
603                    }
604                    other => {
605                        *shared.reply.lock().unwrap() = Some(other);
606                        shared.arrived.notify_all();
607                    }
608                }
609            }
610            shared.stopped.store(true, Ordering::Release);
611            // Wake anyone waiting on a reply that will never come.
612            shared.arrived.notify_all();
613            sink.on_disconnected();
614        })
615        .expect("could not start the ATT reader thread");
616}
617
618/// Find the Client Characteristic Configuration descriptor among a set.
619pub fn find_cccd(descriptors: &[Descriptor]) -> Option<u16> {
620    descriptors
621        .iter()
622        .find(|d| d.uuid == Uuid::Short(att::gatt_type::CLIENT_CHARACTERISTIC_CONFIGURATION))
623        .map(|d| d.handle)
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629
630    /// EBUSY means the daemon holds the link; the message has to say so and
631    /// say what to do. Anything else keeps its errno.
632    #[test]
633    fn a_link_held_by_bluetoothd_is_explained() {
634        let busy = connect_error("AA:BB:CC:DD:EE:FF", crate::sys::EBUSY);
635        assert!(busy.contains("bluetoothd"), "{busy}");
636        assert!(
637            busy.contains("bluetoothctl disconnect AA:BB:CC:DD:EE:FF"),
638            "{busy}"
639        );
640        assert_eq!(
641            connect_error("AA:BB:CC:DD:EE:FF", 111),
642            "could not connect to AA:BB:CC:DD:EE:FF (errno 111)"
643        );
644    }
645
646    // Address parsing and the socket layout are tested in `sys`.
647
648    #[test]
649    fn the_cccd_is_found_by_uuid() {
650        let descriptors = vec![
651            Descriptor {
652                handle: 0x0010,
653                uuid: Uuid::Short(0x2901),
654            },
655            Descriptor {
656                handle: 0x0011,
657                uuid: Uuid::Short(0x2902),
658            },
659        ];
660        assert_eq!(find_cccd(&descriptors), Some(0x0011));
661        assert_eq!(find_cccd(&[]), None);
662    }
663}