Skip to main content

bluetooth_host/
scan.rs

1//! The observer: scanning (passive and active, legacy and extended, 1M and
2//! coded PHY), duplicate filtering, reassembly of fragmented extended
3//! reports, resolution of private addresses, and periodic advertising sync.
4//!
5//! The controller's own duplicate filter is never used: it forgets data
6//! changes on some chips and drops RSSI updates on all of them. We filter
7//! here, per device and advertising set, with a bounded table.
8
9use std::collections::HashMap;
10use std::hash::{Hash, Hasher};
11use std::sync::Arc;
12use std::time::{Duration, Instant, SystemTime};
13
14use bluetooth_adv::Advertisement;
15use bt_hci::cmd::le::{
16    LePeriodicAdvCreateSync, LePeriodicAdvCreateSyncCancel, LePeriodicAdvTerminateSync,
17    LeSetExtScanEnable, LeSetExtScanParams, LeSetScanEnable, LeSetScanParams,
18};
19use bt_hci::param::{
20    AddrKind, BdAddr, CteMask, Duration as HciDuration, FilterDuplicates, LeAdvReport,
21    LeDirectedAdvertisingReportParam, LeExtAdvReport, LePeriodicAdvCreateSyncOptions, LeScanKind,
22    PhyParams, ScanningFilterPolicy, ScanningPhy, SyncHandle,
23};
24use serde::{Deserialize, Serialize};
25use tokio::sync::oneshot;
26
27use crate::address::Address;
28use crate::connection::Phy;
29use crate::error::{Error, Result};
30use crate::host::{raw6, Host, HostEvent};
31
32/// How to treat repeats of the same advertisement.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
35#[serde(rename_all = "snake_case")]
36pub enum Dedup {
37    /// Report every advertisement received.
38    Off,
39    /// Report a device again only when its data changes.
40    Changes,
41    /// Report when its data changes, and at least every this many
42    /// milliseconds while it is heard (so presence and RSSI stay current).
43    IntervalMs(u64),
44}
45
46/// How to scan.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
49#[serde(default)]
50pub struct ScanConfig {
51    /// Send scan requests to get scan responses.
52    pub active: bool,
53    /// Scan interval, ms (2.5 to 10240).
54    pub interval_ms: u32,
55    /// Scan window, ms (no more than the interval).
56    pub window_ms: u32,
57    /// Scan on the coded PHY too (long range), when the controller can.
58    pub coded: bool,
59    /// Only devices on the filter accept list.
60    pub filter_accept_list: bool,
61    /// Duplicate filtering.
62    pub dedup: Dedup,
63    /// AD types whose advertisements are reported every time, whatever
64    /// `dedup` says: a protocol carried in advertisements, such as Mesh
65    /// (`0x29` to `0x2b`), whose retransmissions are identical and must not
66    /// be filtered as duplicates.
67    #[serde(skip_serializing_if = "Vec::is_empty")]
68    pub always_report: Vec<u8>,
69}
70
71impl Default for ScanConfig {
72    fn default() -> Self {
73        ScanConfig {
74            active: false,
75            interval_ms: 100,
76            window_ms: 100,
77            coded: true,
78            filter_accept_list: false,
79            dedup: Dedup::IntervalMs(10_000),
80            always_report: Vec::new(),
81        }
82    }
83}
84
85/// One advertisement, with its scan response when one came.
86#[derive(Debug, Clone, PartialEq, Serialize)]
87pub struct Report {
88    /// The address it was sent from.
89    pub address: Address,
90    /// The identity behind a private address, when a stored IRK resolves it.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub identity: Option<Address>,
93    /// Received signal strength, dBm.
94    pub rssi: i8,
95    /// The TX power the advertiser reported in the PDU header (extended
96    /// advertising), dBm.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub tx_power: Option<i8>,
99    /// The primary PHY.
100    pub primary_phy: Phy,
101    /// The secondary PHY (extended advertising).
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub secondary_phy: Option<Phy>,
104    /// Advertising set id (extended advertising).
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub sid: Option<u8>,
107    /// Periodic advertising interval, 1.25 ms units, when the set has a train.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub periodic_interval: Option<u16>,
110    /// Connectable.
111    pub connectable: bool,
112    /// Scannable.
113    pub scannable: bool,
114    /// Directed (at `direct_address`).
115    pub directed: bool,
116    /// Sent with legacy PDUs.
117    pub legacy: bool,
118    /// The address a directed advertisement is aimed at.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub direct_address: Option<Address>,
121    /// Advertising data.
122    #[serde(serialize_with = "ser_hex")]
123    pub data: Vec<u8>,
124    /// Scan response data.
125    #[serde(
126        skip_serializing_if = "Option::is_none",
127        serialize_with = "ser_hex_opt"
128    )]
129    pub scan_response: Option<Vec<u8>>,
130    /// The controller could not deliver all of the data.
131    #[serde(skip_serializing_if = "std::ops::Not::not")]
132    pub truncated: bool,
133    /// When it was received.
134    #[serde(serialize_with = "ser_time")]
135    pub time: SystemTime,
136}
137
138fn ser_hex<S: serde::Serializer>(v: &[u8], s: S) -> std::result::Result<S::Ok, S::Error> {
139    s.serialize_str(&hex::encode(v))
140}
141
142fn ser_hex_opt<S: serde::Serializer>(
143    v: &Option<Vec<u8>>,
144    s: S,
145) -> std::result::Result<S::Ok, S::Error> {
146    match v {
147        Some(v) => s.serialize_str(&hex::encode(v)),
148        None => s.serialize_none(),
149    }
150}
151
152fn ser_time<S: serde::Serializer>(t: &SystemTime, s: S) -> std::result::Result<S::Ok, S::Error> {
153    let ms = t
154        .duration_since(SystemTime::UNIX_EPOCH)
155        .map(|d| d.as_millis())
156        .unwrap_or(0);
157    s.serialize_u64(u64::try_from(ms).unwrap_or(u64::MAX))
158}
159
160impl Report {
161    /// The advertising data and scan response, parsed.
162    pub fn advertisement(&self) -> Advertisement {
163        let mut a = Advertisement::parse(&self.data);
164        if let Some(r) = &self.scan_response {
165            a.extend(r);
166        }
167        a
168    }
169
170    /// The identity if resolved, else the address.
171    pub fn device(&self) -> Address {
172        self.identity.unwrap_or(self.address)
173    }
174}
175
176/// A report from a synchronized periodic advertising train.
177#[derive(Debug, Clone, PartialEq, Serialize)]
178pub struct PeriodicReport {
179    /// The sync handle.
180    pub sync: u16,
181    /// The advertiser.
182    pub address: Address,
183    /// Its advertising set.
184    pub sid: u8,
185    /// RSSI, dBm.
186    pub rssi: i8,
187    /// TX power, dBm, when reported.
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub tx_power: Option<i8>,
190    /// The data.
191    #[serde(serialize_with = "ser_hex")]
192    pub data: Vec<u8>,
193    /// The controller could not deliver all of it.
194    #[serde(skip_serializing_if = "std::ops::Not::not")]
195    pub truncated: bool,
196}
197
198/// What a device's last advertisement (not scan response) said about itself.
199#[derive(Clone, Copy)]
200struct Props {
201    tx_power: Option<i8>,
202    primary_phy: Phy,
203    secondary_phy: Option<Phy>,
204    periodic_interval: Option<u16>,
205    connectable: bool,
206    scannable: bool,
207    directed: bool,
208    legacy: bool,
209}
210
211struct Seen {
212    props: Option<Props>,
213    adv: Vec<u8>,
214    scan_rsp: Option<Vec<u8>>,
215    hash: u64,
216    emitted: Option<Instant>,
217    last: Instant,
218}
219
220struct Train {
221    address: Address,
222    sid: u8,
223    partial: Vec<u8>,
224}
225
226/// Scanning state, owned by the host.
227#[derive(Default)]
228pub(crate) struct Scanner {
229    config: Option<ScanConfig>,
230    seen: HashMap<(Address, u8), Seen>,
231    partial: HashMap<(Address, u8), Vec<u8>>,
232    trains: HashMap<u16, Train>,
233}
234
235/// Devices remembered for duplicate filtering; past this the oldest go.
236const SEEN_LIMIT: usize = 8192;
237/// The most extended advertising data one set can carry, with slack.
238const MAX_ADV_DATA: usize = 1650;
239
240impl Scanner {
241    fn prune(&mut self, now: Instant) {
242        if self.seen.len() < SEEN_LIMIT {
243            return;
244        }
245        self.seen
246            .retain(|_, s| now.duration_since(s.last) < Duration::from_secs(60));
247        if self.seen.len() >= SEEN_LIMIT {
248            self.seen.clear();
249        }
250        if self.partial.len() > 256 {
251            self.partial.clear();
252        }
253    }
254}
255
256fn phy(v: u8) -> Phy {
257    Phy::from_hci(v)
258}
259
260/// What a report carries before duplicate filtering.
261struct Incoming {
262    address: Address,
263    sid: u8,
264    rssi: i8,
265    tx_power: Option<i8>,
266    primary_phy: Phy,
267    secondary_phy: Option<Phy>,
268    periodic_interval: Option<u16>,
269    connectable: bool,
270    scannable: bool,
271    directed: bool,
272    legacy: bool,
273    scan_response: bool,
274    direct_address: Option<Address>,
275    data: Vec<u8>,
276    truncated: bool,
277}
278
279fn deliver(host: &Host, i: Incoming) {
280    let now = Instant::now();
281    let identity = host.inner.keys.resolve(&i.address);
282    let report = {
283        let mut sc = host.inner.scanner.lock().unwrap_or_else(|e| e.into_inner());
284        let Some((dedup, always)) = sc.config.as_ref().map(|c| {
285            let always = !c.always_report.is_empty()
286                && bluetooth_adv::AdStructures::new(&i.data)
287                    .flatten()
288                    .any(|s| c.always_report.contains(&s.ad_type));
289            (c.dedup, always)
290        }) else {
291            return;
292        };
293        sc.prune(now);
294        let key = (identity.unwrap_or(i.address), i.sid);
295        let seen = sc.seen.entry(key).or_insert_with(|| Seen {
296            props: None,
297            adv: Vec::new(),
298            scan_rsp: None,
299            hash: 0,
300            emitted: None,
301            last: now,
302        });
303        seen.last = now;
304        let own = Props {
305            tx_power: i.tx_power,
306            primary_phy: i.primary_phy,
307            secondary_phy: i.secondary_phy,
308            periodic_interval: i.periodic_interval,
309            connectable: i.connectable,
310            scannable: i.scannable,
311            directed: i.directed,
312            legacy: i.legacy,
313        };
314        // A scan response says nothing of the advertisement's properties;
315        // keep those of the advertisement it answers.
316        let props = if i.scan_response {
317            seen.scan_rsp = Some(i.data.clone());
318            seen.props.unwrap_or(Props {
319                scannable: true,
320                ..own
321            })
322        } else {
323            seen.adv = i.data.clone();
324            seen.props = Some(own);
325            own
326        };
327        let mut h = std::collections::hash_map::DefaultHasher::new();
328        seen.adv.hash(&mut h);
329        seen.scan_rsp.hash(&mut h);
330        let hash = h.finish();
331        let changed = hash != seen.hash || seen.emitted.is_none();
332        let emit = always
333            || match dedup {
334                Dedup::Off => true,
335                Dedup::Changes => changed,
336                Dedup::IntervalMs(ms) => {
337                    changed
338                        || seen
339                            .emitted
340                            .is_none_or(|t| now.duration_since(t) >= Duration::from_millis(ms))
341                }
342            };
343        if !emit {
344            return;
345        }
346        seen.hash = hash;
347        seen.emitted = Some(now);
348        Report {
349            address: i.address,
350            identity,
351            rssi: i.rssi,
352            tx_power: props.tx_power,
353            primary_phy: props.primary_phy,
354            secondary_phy: props.secondary_phy,
355            sid: (i.sid != 0xff).then_some(i.sid),
356            periodic_interval: props.periodic_interval,
357            connectable: props.connectable,
358            scannable: props.scannable,
359            directed: props.directed,
360            legacy: props.legacy,
361            direct_address: i.direct_address,
362            data: seen.adv.clone(),
363            scan_response: seen.scan_rsp.clone(),
364            truncated: i.truncated,
365            time: SystemTime::now(),
366        }
367    };
368    host.emit(HostEvent::Advertisement(Arc::new(report)));
369}
370
371pub(crate) fn on_legacy_report(host: &Host, r: &LeAdvReport<'_>) {
372    // Legacy event types: 0 ADV_IND, 1 ADV_DIRECT_IND, 2 ADV_SCAN_IND,
373    // 3 ADV_NONCONN_IND, 4 SCAN_RSP.
374    let kind = r.event_kind as u8;
375    deliver(
376        host,
377        Incoming {
378            address: Address::from_hci(r.addr_kind.into_inner(), raw6(&r.addr)),
379            sid: 0xff,
380            rssi: r.rssi,
381            tx_power: None,
382            primary_phy: Phy::Le1m,
383            secondary_phy: None,
384            periodic_interval: None,
385            connectable: kind <= 1,
386            scannable: kind == 0 || kind == 2,
387            directed: kind == 1,
388            legacy: true,
389            scan_response: kind == 4,
390            direct_address: None,
391            data: r.data.to_vec(),
392            truncated: false,
393        },
394    );
395}
396
397pub(crate) fn on_directed_report(host: &Host, r: &LeDirectedAdvertisingReportParam) {
398    let (Ok(kind), Ok(addr), Ok(rssi), Ok(dkind), Ok(daddr)) = (
399        r.addr_kind(),
400        r.addr(),
401        r.rssi(),
402        r.direct_addr_kind(),
403        r.direct_addr(),
404    ) else {
405        return;
406    };
407    deliver(
408        host,
409        Incoming {
410            address: Address::from_hci(kind.into_inner(), raw6(&addr)),
411            sid: 0xff,
412            rssi,
413            tx_power: None,
414            primary_phy: Phy::Le1m,
415            secondary_phy: None,
416            periodic_interval: None,
417            connectable: true,
418            scannable: false,
419            directed: true,
420            legacy: true,
421            scan_response: false,
422            direct_address: Some(Address::from_hci(dkind.into_inner(), raw6(&daddr))),
423            data: Vec::new(),
424            truncated: false,
425        },
426    );
427}
428
429pub(crate) fn on_extended_report(host: &Host, r: &LeExtAdvReport<'_>) {
430    // Event type bits: 0 connectable, 1 scannable, 2 directed, 3 scan
431    // response, 4 legacy, 5-6 data status.
432    let ev = u16::from_le_bytes(r.event_kind.into_inner());
433    let status = (ev >> 5) & 0b11;
434    let address = Address::from_hci(r.addr_kind.into_inner(), raw6(&r.addr));
435    let key = (address, r.adv_sid);
436    // Reassemble data that arrives in several reports.
437    let (data, truncated) = {
438        let mut sc = host.inner.scanner.lock().unwrap_or_else(|e| e.into_inner());
439        let mut buf = sc.partial.remove(&key).unwrap_or_default();
440        if buf.len() + r.data.len() <= MAX_ADV_DATA {
441            buf.extend_from_slice(r.data);
442        }
443        match status {
444            0 => (buf, false),
445            1 => {
446                sc.partial.insert(key, buf);
447                return;
448            }
449            _ => (buf, true),
450        }
451    };
452    let interval = r.adv_interval.as_u16();
453    deliver(
454        host,
455        Incoming {
456            address,
457            sid: r.adv_sid,
458            rssi: r.rssi,
459            // 127 means the advertiser did not say.
460            tx_power: (r.tx_power != 127).then_some(r.tx_power),
461            primary_phy: phy(r.primary_adv_phy as u8),
462            secondary_phy: r.secondary_adv_phy.map(|p| phy(p as u8)),
463            periodic_interval: (interval != 0).then_some(interval),
464            connectable: ev & 0x01 != 0,
465            scannable: ev & 0x02 != 0,
466            directed: ev & 0x04 != 0,
467            legacy: ev & 0x10 != 0,
468            scan_response: ev & 0x08 != 0,
469            direct_address: (ev & 0x04 != 0)
470                .then(|| Address::from_hci(r.direct_addr_kind.into_inner(), raw6(&r.direct_addr))),
471            data,
472            truncated,
473        },
474    );
475}
476
477pub(crate) fn on_scan_timeout(host: &Host) {
478    host.inner
479        .scanner
480        .lock()
481        .unwrap_or_else(|e| e.into_inner())
482        .config = None;
483}
484
485pub(crate) fn on_sync_established(
486    host: &Host,
487    e: &bt_hci::event::le::LePeriodicAdvertisingSyncEstablished,
488) {
489    host.inner
490        .scanner
491        .lock()
492        .unwrap_or_else(|e| e.into_inner())
493        .trains
494        .insert(
495            e.sync_handle.into_inner(),
496            Train {
497                address: Address::from_hci(e.adv_addr_kind.into_inner(), raw6(&e.adv_addr)),
498                sid: e.adv_sid,
499                partial: Vec::new(),
500            },
501        );
502}
503
504pub(crate) fn on_periodic_report(
505    host: &Host,
506    e: &bt_hci::event::le::LePeriodicAdvertisingReport<'_>,
507) {
508    let sync = e.sync_handle.into_inner();
509    let status = e.data_status as u8;
510    let report = {
511        let mut sc = host.inner.scanner.lock().unwrap_or_else(|e| e.into_inner());
512        let Some(t) = sc.trains.get_mut(&sync) else {
513            return;
514        };
515        if t.partial.len() + e.data.len() <= MAX_ADV_DATA {
516            t.partial.extend_from_slice(e.data);
517        }
518        if status == 1 {
519            return;
520        }
521        PeriodicReport {
522            sync,
523            address: t.address,
524            sid: t.sid,
525            rssi: e.rssi,
526            tx_power: (e.tx_power != 127).then_some(e.tx_power),
527            data: std::mem::take(&mut t.partial),
528            truncated: status == 2,
529        }
530    };
531    host.emit(HostEvent::PeriodicReport(Arc::new(report)));
532}
533
534pub(crate) fn on_sync_lost(host: &Host, sync: u16) {
535    host.inner
536        .scanner
537        .lock()
538        .unwrap_or_else(|e| e.into_inner())
539        .trains
540        .remove(&sync);
541}
542
543fn ms_625(ms: u32) -> HciDuration<625> {
544    HciDuration::from_u16(
545        u16::try_from((u64::from(ms) * 1000 / 625).clamp(4, 0xffff)).unwrap_or(0xffff),
546    )
547}
548
549impl Host {
550    /// Starts scanning (or changes how). Advertisements arrive as
551    /// [`HostEvent::Advertisement`].
552    pub async fn start_scan(&self, config: ScanConfig) -> Result<()> {
553        if config.window_ms > config.interval_ms || config.interval_ms == 0 {
554            return Err(Error::InvalidParameter(
555                "the scan window must not exceed the interval".into(),
556            ));
557        }
558        let caps = self.inner.caps();
559        let hci = &self.inner.hci;
560        let _ = self.stop_scan().await;
561        let own = AddrKind::new(self.address().hci_type());
562        let policy = if config.filter_accept_list {
563            ScanningFilterPolicy::BasicFiltered
564        } else {
565            ScanningFilterPolicy::BasicUnfiltered
566        };
567        // A controller with extended commands refuses the legacy ones once
568        // extended advertising is in use, so extended it is.
569        let extended = caps.extended_scanning();
570        {
571            let mut sc = self.inner.scanner.lock().unwrap_or_else(|e| e.into_inner());
572            sc.config = Some(config.clone());
573            sc.seen.clear();
574            sc.partial.clear();
575        }
576        let r = if extended {
577            let p = ScanningPhy {
578                active_scan: config.active,
579                scan_interval: ms_625(config.interval_ms),
580                scan_window: ms_625(config.window_ms),
581            };
582            let phys = PhyParams {
583                le_1m_phy: Some(p),
584                le_2m_phy: None,
585                le_coded_phy: (config.coded && caps.coded_phy()).then_some(p),
586            };
587            hci.exec(&LeSetExtScanParams::new(own, policy, phys))
588                .await?;
589            hci.exec(&LeSetExtScanEnable::new(
590                true,
591                FilterDuplicates::Disabled,
592                HciDuration::from_u16(0),
593                HciDuration::from_u16(0),
594            ))
595            .await
596        } else {
597            hci.exec(&LeSetScanParams::new(
598                if config.active {
599                    LeScanKind::Active
600                } else {
601                    LeScanKind::Passive
602                },
603                ms_625(config.interval_ms),
604                ms_625(config.window_ms),
605                own,
606                policy,
607            ))
608            .await?;
609            hci.exec(&LeSetScanEnable::new(true, false)).await
610        };
611        if r.is_err() {
612            self.inner
613                .scanner
614                .lock()
615                .unwrap_or_else(|e| e.into_inner())
616                .config = None;
617        }
618        r
619    }
620
621    /// Stops scanning.
622    pub async fn stop_scan(&self) -> Result<()> {
623        let was = self
624            .inner
625            .scanner
626            .lock()
627            .unwrap_or_else(|e| e.into_inner())
628            .config
629            .take();
630        let Some(was) = was else { return Ok(()) };
631        let caps = self.inner.caps();
632        let _ = was;
633        if caps.extended_scanning() {
634            self.inner
635                .hci
636                .exec(&LeSetExtScanEnable::new(
637                    false,
638                    FilterDuplicates::Disabled,
639                    HciDuration::from_u16(0),
640                    HciDuration::from_u16(0),
641                ))
642                .await
643        } else {
644            self.inner
645                .hci
646                .exec(&LeSetScanEnable::new(false, false))
647                .await
648        }
649    }
650
651    /// Whether scanning is on, and how.
652    pub fn scan_config(&self) -> Option<ScanConfig> {
653        self.inner
654            .scanner
655            .lock()
656            .unwrap_or_else(|e| e.into_inner())
657            .config
658            .clone()
659    }
660
661    /// Synchronizes to a periodic advertising train (scanning must be on to
662    /// find it). Returns the sync handle; reports arrive as
663    /// [`HostEvent::PeriodicReport`].
664    pub async fn sync_periodic(
665        &self,
666        advertiser: Address,
667        sid: u8,
668        skip: u16,
669        timeout_ms: u32,
670    ) -> Result<u16> {
671        if !self.inner.caps().periodic_advertising() {
672            return Err(Error::Unsupported("periodic advertising"));
673        }
674        let (tx, rx) = oneshot::channel();
675        *self
676            .inner
677            .sync_waiter
678            .lock()
679            .unwrap_or_else(|e| e.into_inner()) = Some(tx);
680        let timeout = u16::try_from((timeout_ms / 10).clamp(10, 0x4000)).unwrap_or(0x4000);
681        self.inner
682            .hci
683            .exec_async(&LePeriodicAdvCreateSync::new(
684                LePeriodicAdvCreateSyncOptions::new(),
685                sid,
686                AddrKind::new(advertiser.hci_type()),
687                BdAddr::new(advertiser.bytes),
688                skip,
689                HciDuration::from_u16(timeout),
690                CteMask::new(),
691            ))
692            .await?;
693        let wait = Duration::from_millis(u64::from(timeout_ms).max(2000) * 3);
694        match tokio::time::timeout(wait, rx).await {
695            Ok(Ok(r)) => r,
696            Ok(Err(_)) => Err(Error::Stopped),
697            Err(_) => {
698                let _ = self
699                    .inner
700                    .hci
701                    .exec(&LePeriodicAdvCreateSyncCancel::new())
702                    .await;
703                Err(Error::Timeout("the periodic advertising train"))
704            }
705        }
706    }
707
708    /// Stops following a periodic train.
709    pub async fn terminate_sync(&self, sync: u16) -> Result<()> {
710        on_sync_lost(self, sync);
711        self.inner
712            .hci
713            .exec(&LePeriodicAdvTerminateSync::new(sync_handle(sync)?))
714            .await
715    }
716}
717
718/// bt-hci's SyncHandle has no constructor; build it from its wire form.
719fn sync_handle(h: u16) -> Result<SyncHandle> {
720    use bt_hci::FromHciBytes;
721    SyncHandle::from_hci_bytes(&h.to_le_bytes())
722        .map(|(s, _)| s)
723        .map_err(|_| Error::InvalidParameter(format!("sync handle {h}")))
724}