Skip to main content

bluetooth_host/
central.rs

1//! The central role: connecting, and the filter accept list.
2
3use std::time::Duration;
4
5use bt_hci::cmd::le::{
6    LeAddDeviceToFilterAcceptList, LeClearFilterAcceptList, LeCreateConn, LeCreateConnCancel,
7    LeExtCreateConn, LeRemoveDeviceFromFilterAcceptList,
8};
9use bt_hci::param::{AddrKind, BdAddr, Duration as HciDuration, InitiatingPhy, PhyParams};
10use serde::{Deserialize, Serialize};
11use tokio::sync::oneshot;
12
13use crate::address::Address;
14use crate::connection::{Connection, ParamsRequest, Phy};
15use crate::error::{Error, Result};
16use crate::host::Host;
17
18/// How to connect.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(default)]
21pub struct ConnectParams {
22    /// Scan interval while initiating, ms.
23    pub scan_interval_ms: u32,
24    /// Scan window while initiating, ms.
25    pub scan_window_ms: u32,
26    /// Connection parameters to ask for.
27    pub params: ParamsRequest,
28    /// PHYs to initiate on (Bluetooth 5): `le1m`, `le2m`, `le_coded`.
29    pub phys: Vec<Phy>,
30    /// Give up after this long, ms.
31    pub timeout_ms: u32,
32}
33
34impl Default for ConnectParams {
35    fn default() -> Self {
36        ConnectParams {
37            scan_interval_ms: 60,
38            scan_window_ms: 30,
39            params: ParamsRequest::default(),
40            phys: vec![Phy::Le1m],
41            timeout_ms: 10_000,
42        }
43    }
44}
45
46fn u625(ms: u32) -> HciDuration<625> {
47    HciDuration::from_u16(
48        u16::try_from((u64::from(ms) * 1000 / 625).clamp(4, 0x4000)).unwrap_or(0x4000),
49    )
50}
51
52impl Host {
53    /// Connects to a device as central.
54    pub async fn connect(&self, peer: Address, p: &ConnectParams) -> Result<Connection> {
55        p.params.check()?;
56        if p.scan_window_ms > p.scan_interval_ms {
57            return Err(Error::InvalidParameter(
58                "the scan window must not exceed the interval".into(),
59            ));
60        }
61        let (tx, rx) = oneshot::channel();
62        {
63            let mut w = self
64                .inner
65                .connect_waiter
66                .lock()
67                .unwrap_or_else(|e| e.into_inner());
68            if w.is_some() {
69                return Err(Error::InvalidParameter(
70                    "a connection is already being made".into(),
71                ));
72            }
73            *w = Some(tx);
74        }
75        let r = self.initiate(peer, p).await;
76        if let Err(e) = r {
77            self.inner
78                .connect_waiter
79                .lock()
80                .unwrap_or_else(|e| e.into_inner())
81                .take();
82            return Err(e);
83        }
84        let mut rx = rx;
85        let state =
86            match tokio::time::timeout(Duration::from_millis(u64::from(p.timeout_ms)), &mut rx)
87                .await
88            {
89                Ok(Ok(r)) => r?,
90                Ok(Err(_)) => return Err(Error::Stopped),
91                Err(_) => {
92                    let _ = self.inner.hci.exec(&LeCreateConnCancel::new()).await;
93                    // The controller answers a cancel with a failed Connection
94                    // Complete, or with the connection if it raced the cancel.
95                    match tokio::time::timeout(Duration::from_secs(3), rx).await {
96                        Ok(Ok(Ok(s))) => s,
97                        _ => {
98                            self.inner
99                                .connect_waiter
100                                .lock()
101                                .unwrap_or_else(|e| e.into_inner())
102                                .take();
103                            return Err(Error::Timeout("the device to accept the connection"));
104                        }
105                    }
106                }
107            };
108        Ok(Connection::new(self.clone(), state))
109    }
110
111    async fn initiate(&self, peer: Address, p: &ConnectParams) -> Result<()> {
112        let caps = self.inner.caps();
113        let own = AddrKind::new(self.address().hci_type());
114        let c = &p.params;
115        if caps.extended_advertising() {
116            let phy = InitiatingPhy {
117                scan_interval: u625(p.scan_interval_ms),
118                scan_window: u625(p.scan_window_ms),
119                conn_interval_min: HciDuration::from_u16(c.interval_min),
120                conn_interval_max: HciDuration::from_u16(c.interval_max),
121                max_latency: c.latency,
122                supervision_timeout: HciDuration::from_u16(c.timeout),
123                min_ce_len: HciDuration::from_u16(0),
124                max_ce_len: HciDuration::from_u16(0),
125            };
126            let want = |x: Phy| p.phys.contains(&x);
127            let phys = PhyParams {
128                le_1m_phy: (want(Phy::Le1m) || p.phys.is_empty()).then_some(phy),
129                le_2m_phy: (want(Phy::Le2m) && caps.phy_2m()).then_some(phy),
130                le_coded_phy: (want(Phy::LeCoded) && caps.coded_phy()).then_some(phy),
131            };
132            self.inner
133                .hci
134                .exec_async(&LeExtCreateConn::new(
135                    false,
136                    own,
137                    AddrKind::new(peer.hci_type()),
138                    BdAddr::new(peer.bytes),
139                    phys,
140                ))
141                .await
142        } else {
143            self.inner
144                .hci
145                .exec_async(&LeCreateConn::new(
146                    u625(p.scan_interval_ms),
147                    u625(p.scan_window_ms),
148                    false,
149                    AddrKind::new(peer.hci_type()),
150                    BdAddr::new(peer.bytes),
151                    own,
152                    HciDuration::from_u16(c.interval_min),
153                    HciDuration::from_u16(c.interval_max),
154                    c.latency,
155                    HciDuration::from_u16(c.timeout),
156                    HciDuration::from_u16(0),
157                    HciDuration::from_u16(0),
158                ))
159                .await
160        }
161    }
162
163    /// Adds a device to the controller's filter accept list.
164    pub async fn accept_list_add(&self, a: Address) -> Result<()> {
165        self.inner
166            .hci
167            .exec(&LeAddDeviceToFilterAcceptList::new(
168                AddrKind::new(a.hci_type()),
169                BdAddr::new(a.bytes),
170            ))
171            .await
172    }
173
174    /// Removes a device from the filter accept list.
175    pub async fn accept_list_remove(&self, a: Address) -> Result<()> {
176        self.inner
177            .hci
178            .exec(&LeRemoveDeviceFromFilterAcceptList::new(
179                AddrKind::new(a.hci_type()),
180                BdAddr::new(a.bytes),
181            ))
182            .await
183    }
184
185    /// Empties the filter accept list.
186    pub async fn accept_list_clear(&self) -> Result<()> {
187        self.inner.hci.exec(&LeClearFilterAcceptList::new()).await
188    }
189
190    /// Registers an L2CAP credit-based channel server on `spsm`; incoming
191    /// channels arrive on the receiver.
192    pub fn listen_channel(
193        &self,
194        spsm: u16,
195        mtu: u16,
196    ) -> tokio::sync::mpsc::Receiver<crate::l2cap::Channel> {
197        crate::l2cap::listen(self, spsm, mtu)
198    }
199}