trouble-host 0.6.0

An async Rust BLE host
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! BLE connection.

use bt_hci::cmd::le::{LeConnUpdate, LeReadLocalSupportedFeatures, LeReadPhy, LeSetDataLength, LeSetPhy};
use bt_hci::cmd::status::ReadRssi;
use bt_hci::controller::{ControllerCmdAsync, ControllerCmdSync};
use bt_hci::param::{
    AddrKind, AllPhys, BdAddr, ConnHandle, DisconnectReason, LeConnRole, PhyKind, PhyMask, PhyOptions, Status,
};
#[cfg(feature = "connection-params-update")]
use bt_hci::{
    cmd::le::{LeRemoteConnectionParameterRequestNegativeReply, LeRemoteConnectionParameterRequestReply},
    param::RemoteConnectionParamsRejectReason,
};
#[cfg(feature = "gatt")]
use embassy_sync::blocking_mutex::raw::RawMutex;
use embassy_time::Duration;

use crate::connection_manager::ConnectionManager;
#[cfg(feature = "connection-metrics")]
pub use crate::connection_manager::Metrics as ConnectionMetrics;
use crate::pdu::Pdu;
#[cfg(feature = "gatt")]
use crate::prelude::{AttributeServer, GattConnection};
#[cfg(feature = "security")]
use crate::security_manager::{BondInformation, PassKey};
use crate::types::l2cap::ConnParamUpdateRes;
use crate::{bt_hci_duration, BleHostError, Error, Identity, PacketPool, Stack};

/// Security level of a connection
///
/// This describes the various security levels that are supported.
///
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SecurityLevel {
    /// No encryption and no authentication. All connections start on this security level.
    NoEncryption,
    /// Encrypted but not authenticated communication. Does not provide MITM protection.
    Encrypted,
    /// Encrypted and authenticated security level. MITM protected.
    EncryptedAuthenticated,
}

impl SecurityLevel {
    /// Check if the security level is encrypted.
    pub fn encrypted(&self) -> bool {
        !matches!(self, SecurityLevel::NoEncryption)
    }

    /// Check if the security level is authenticated.
    pub fn authenticated(&self) -> bool {
        matches!(self, SecurityLevel::EncryptedAuthenticated)
    }
}

/// Connection configuration.
pub struct ConnectConfig<'d> {
    /// Scan configuration to use while connecting.
    pub scan_config: ScanConfig<'d>,
    /// Parameters to use for the connection.
    pub connect_params: RequestedConnParams,
}

/// Scan/connect configuration.
pub struct ScanConfig<'d> {
    /// Active scanning.
    pub active: bool,
    /// List of addresses to accept.
    pub filter_accept_list: &'d [(AddrKind, &'d BdAddr)],
    /// PHYs to scan on.
    pub phys: PhySet,
    /// Scan interval.
    pub interval: Duration,
    /// Scan window.
    pub window: Duration,
    /// Scan timeout.
    pub timeout: Duration,
}

impl Default for ScanConfig<'_> {
    fn default() -> Self {
        Self {
            active: true,
            filter_accept_list: &[],
            phys: PhySet::M1,
            interval: Duration::from_secs(1),
            window: Duration::from_secs(1),
            timeout: Duration::from_secs(0),
        }
    }
}

/// PHYs to scan on.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Eq, PartialEq, Copy, Clone)]
#[repr(u8)]
pub enum PhySet {
    /// 1Mbps phy
    M1 = 1,
    /// 2Mbps phy
    M2 = 2,
    /// 1Mbps + 2Mbps phys
    M1M2 = 3,
    /// Coded phy (125kbps, S=8)
    Coded = 4,
    /// 1Mbps and Coded phys
    M1Coded = 5,
    /// 2Mbps and Coded phys
    M2Coded = 6,
    /// 1Mbps, 2Mbps and Coded phys
    M1M2Coded = 7,
}

/// Requested parameters for a connection.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct RequestedConnParams {
    /// Minimum connection interval.
    pub min_connection_interval: Duration,
    /// Maximum connection interval.
    pub max_connection_interval: Duration,
    /// Maximum slave latency.
    pub max_latency: u16,
    /// Event length.
    pub min_event_length: Duration,
    /// Event length.
    pub max_event_length: Duration,
    /// Supervision timeout.
    pub supervision_timeout: Duration,
}

impl RequestedConnParams {
    /// Check if the connection parameters are valid
    pub fn is_valid(&self) -> bool {
        self.min_connection_interval <= self.max_connection_interval
            && self.min_connection_interval >= Duration::from_micros(7_500)
            && self.max_connection_interval <= Duration::from_secs(4)
            && self.max_latency < 500
            && self.min_event_length <= self.max_event_length
            && self.supervision_timeout >= Duration::from_millis(100)
            && self.supervision_timeout <= Duration::from_millis(32_000)
            && self.supervision_timeout.as_micros()
                > 2 * u64::from(self.max_latency + 1) * self.max_connection_interval.as_micros()
    }
}

/// Current parameters for a connection.
#[derive(Default, Debug, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ConnParams {
    /// Connection interval.
    pub conn_interval: Duration,
    /// Peripheral latency.
    pub peripheral_latency: u16,
    /// Supervision timeout.
    pub supervision_timeout: Duration,
}

/// A connection event.
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConnectionEvent {
    /// Connection disconnected.
    Disconnected {
        /// The reason (status code) for the disconnect.
        reason: Status,
    },
    /// The phy settings was updated for this connection.
    PhyUpdated {
        /// The TX phy.
        tx_phy: PhyKind,
        /// The RX phy.
        rx_phy: PhyKind,
    },
    /// The phy settings was updated for this connection.
    ConnectionParamsUpdated {
        /// Connection interval.
        conn_interval: Duration,
        /// Peripheral latency.
        peripheral_latency: u16,
        /// Supervision timeout.
        supervision_timeout: Duration,
    },
    /// The data length was changed for this connection.
    DataLengthUpdated {
        /// Max TX octets.
        max_tx_octets: u16,
        /// Max TX time.
        max_tx_time: u16,
        /// Max RX octets.
        max_rx_octets: u16,
        /// Max RX time.
        max_rx_time: u16,
    },
    /// A request to change the connection parameters.
    ///
    /// [`ConnectionParamsRequest::accept()`] or [`ConnectionParamsRequest::reject()`]
    /// must be called to respond to the request.
    RequestConnectionParams(ConnectionParamsRequest),
    #[cfg(feature = "security")]
    /// Request to display a pass key
    PassKeyDisplay(PassKey),
    #[cfg(feature = "security")]
    /// Request to display and confirm a pass key
    PassKeyConfirm(PassKey),
    #[cfg(feature = "security")]
    /// Request to make the user input the pass key
    PassKeyInput,
    #[cfg(feature = "security")]
    /// Pairing completed
    PairingComplete {
        /// Security level of this pairing
        security_level: SecurityLevel,
        /// Bond information if the devices create a bond with this pairing.
        bond: Option<BondInformation>,
    },
    #[cfg(feature = "security")]
    /// Pairing completed
    PairingFailed(Error),
}

/// A connection parameters update request
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ConnectionParamsRequest {
    params: RequestedConnParams,
    handle: ConnHandle,
    responded: bool,
    #[cfg(feature = "connection-params-update")]
    l2cap: bool,
}

impl ConnectionParamsRequest {
    pub(crate) fn new(
        params: RequestedConnParams,
        handle: ConnHandle,
        #[cfg(feature = "connection-params-update")] l2cap: bool,
    ) -> Self {
        Self {
            params,
            handle,
            responded: false,
            #[cfg(feature = "connection-params-update")]
            l2cap,
        }
    }

    /// Get the parameters being requested.
    pub fn params(&self) -> &RequestedConnParams {
        &self.params
    }
}

#[cfg(not(feature = "connection-params-update"))]
impl ConnectionParamsRequest {
    /// Accept the connection parameters update request.
    ///
    /// If `params` is `None`, use the parameters requested by the peer.
    pub async fn accept<C, P: PacketPool>(
        mut self,
        params: Option<&RequestedConnParams>,
        stack: &Stack<'_, C, P>,
    ) -> Result<(), BleHostError<C::Error>>
    where
        C: crate::Controller,
    {
        self.responded = true;

        let params = params.unwrap_or(&self.params);
        if !params.is_valid() {
            return self.reject(stack).await;
        }

        match stack.host.async_command(into_le_conn_update(self.handle, params)).await {
            Ok(()) => {
                let param = ConnParamUpdateRes { result: 0 };
                stack.host.send_conn_param_update_res(self.handle, &param).await
            }
            Err(BleHostError::BleHost(crate::Error::Hci(bt_hci::param::Error::UNKNOWN_CONN_IDENTIFIER))) => {
                Err(crate::Error::Disconnected.into())
            }
            Err(e) => {
                info!("Connection parameters request procedure failed");
                if let Err(e) = self.reject(stack).await {
                    warn!("Failed to reject ConnParamRequest after failure");
                }
                Err(e)
            }
        }
    }

    /// Reject the connection parameters update request
    pub async fn reject<C, P: PacketPool>(mut self, stack: &Stack<'_, C, P>) -> Result<(), BleHostError<C::Error>>
    where
        C: crate::Controller,
    {
        self.responded = true;
        let param = ConnParamUpdateRes { result: 1 };
        stack.host.send_conn_param_update_res(self.handle, &param).await
    }
}

#[cfg(feature = "connection-params-update")]
impl ConnectionParamsRequest {
    /// Accept the connection parameters update request.
    ///
    /// If `params` is `None`, use the parameters requested by the peer.
    pub async fn accept<C, P: PacketPool>(
        mut self,
        params: Option<&RequestedConnParams>,
        stack: &Stack<'_, C, P>,
    ) -> Result<(), BleHostError<C::Error>>
    where
        C: crate::Controller
            + ControllerCmdAsync<LeRemoteConnectionParameterRequestReply>
            + ControllerCmdAsync<LeRemoteConnectionParameterRequestNegativeReply>,
    {
        self.responded = true;

        let params = params.unwrap_or(&self.params);
        if !params.is_valid() {
            return self.reject(stack).await;
        }

        match stack.host.async_command(into_le_conn_update(self.handle, params)).await {
            Ok(()) => {
                if self.l2cap {
                    // Use L2CAP signaling to update connection parameters
                    let param = ConnParamUpdateRes { result: 0 };
                    stack.host.send_conn_param_update_res(self.handle, &param).await
                } else {
                    let interval_min: bt_hci::param::Duration<1_250> = bt_hci_duration(params.min_connection_interval);
                    let interval_max: bt_hci::param::Duration<1_250> = bt_hci_duration(params.max_connection_interval);
                    let timeout: bt_hci::param::Duration<10_000> = bt_hci_duration(params.supervision_timeout);
                    stack
                        .host
                        .async_command(LeRemoteConnectionParameterRequestReply::new(
                            self.handle,
                            interval_min,
                            interval_max,
                            params.max_latency,
                            timeout,
                            bt_hci_duration(params.min_event_length),
                            bt_hci_duration(params.max_event_length),
                        ))
                        .await
                }
            }
            Err(BleHostError::BleHost(crate::Error::Hci(bt_hci::param::Error::UNKNOWN_CONN_IDENTIFIER))) => {
                Err(crate::Error::Disconnected.into())
            }
            Err(e) => {
                info!("Connection parameters request procedure failed");
                if let Err(e) = self.reject(stack).await {
                    warn!("Failed to reject ConnParamRequest after failure");
                }
                Err(e)
            }
        }
    }

    /// Reject the connection parameters update request
    pub async fn reject<C, P: PacketPool>(mut self, stack: &Stack<'_, C, P>) -> Result<(), BleHostError<C::Error>>
    where
        C: crate::Controller + ControllerCmdAsync<LeRemoteConnectionParameterRequestNegativeReply>,
    {
        self.responded = true;
        if self.l2cap {
            let param = ConnParamUpdateRes { result: 1 };
            stack.host.send_conn_param_update_res(self.handle, &param).await
        } else {
            stack
                .host
                .async_command(LeRemoteConnectionParameterRequestNegativeReply::new(
                    self.handle,
                    RemoteConnectionParamsRejectReason::UnacceptableConnParameters,
                ))
                .await
        }
    }
}

impl Drop for ConnectionParamsRequest {
    fn drop(&mut self) {
        if !self.responded {
            error!("ConnParamRequest dropped without being acccepted/rejected");
        }
    }
}

impl Default for RequestedConnParams {
    fn default() -> Self {
        Self {
            min_connection_interval: Duration::from_millis(80),
            max_connection_interval: Duration::from_millis(80),
            max_latency: 0,
            min_event_length: Duration::from_secs(0),
            max_event_length: Duration::from_secs(0),
            supervision_timeout: Duration::from_secs(8),
        }
    }
}

impl ConnParams {
    pub(crate) const fn new() -> Self {
        Self {
            conn_interval: Duration::from_ticks(0),
            peripheral_latency: 0,
            supervision_timeout: Duration::from_ticks(0),
        }
    }
}

/// Handle to a BLE connection.
///
/// When the last reference to a connection is dropped, the connection is automatically disconnected.
pub struct Connection<'stack, P: PacketPool> {
    index: u8,
    manager: &'stack ConnectionManager<'stack, P>,
}

impl<P: PacketPool> Clone for Connection<'_, P> {
    fn clone(&self) -> Self {
        self.manager.inc_ref(self.index);
        Connection::new(self.index, self.manager)
    }
}

impl<P: PacketPool> Drop for Connection<'_, P> {
    fn drop(&mut self) {
        self.manager.dec_ref(self.index);
    }
}

impl<'stack, P: PacketPool> Connection<'stack, P> {
    pub(crate) fn new(index: u8, manager: &'stack ConnectionManager<'stack, P>) -> Self {
        Self { index, manager }
    }

    pub(crate) fn set_att_mtu(&self, mtu: u16) {
        self.manager.set_att_mtu(self.index, mtu);
    }

    pub(crate) fn get_att_mtu(&self) -> u16 {
        self.manager.get_att_mtu(self.index)
    }

    pub(crate) async fn send(&self, pdu: Pdu<P::Packet>) {
        self.manager.send(self.index, pdu).await
    }

    pub(crate) fn try_send(&self, pdu: Pdu<P::Packet>) -> Result<(), Error> {
        self.manager.try_send(self.index, pdu)
    }

    pub(crate) async fn post_event(&self, event: ConnectionEvent) {
        self.manager.post_event(self.index, event).await
    }

    /// Wait for next connection event.
    pub async fn next(&self) -> ConnectionEvent {
        self.manager.next(self.index).await
    }

    #[cfg(feature = "gatt")]
    pub(crate) async fn next_gatt(&self) -> Pdu<P::Packet> {
        self.manager.next_gatt(self.index).await
    }

    #[cfg(feature = "gatt")]
    pub(crate) async fn next_gatt_client(&self) -> Pdu<P::Packet> {
        self.manager.next_gatt_client(self.index).await
    }

    /// Check if still connected
    pub fn is_connected(&self) -> bool {
        self.manager.is_connected(self.index)
    }

    /// Connection handle of this connection.
    pub fn handle(&self) -> ConnHandle {
        self.manager.handle(self.index)
    }

    /// Expose the att_mtu.
    pub fn att_mtu(&self) -> u16 {
        self.get_att_mtu()
    }

    /// The connection role for this connection.
    pub fn role(&self) -> LeConnRole {
        self.manager.role(self.index)
    }

    /// The peer address kind for this connection.
    pub fn peer_addr_kind(&self) -> AddrKind {
        self.manager.peer_addr_kind(self.index)
    }

    /// The peer address for this connection.
    pub fn peer_address(&self) -> BdAddr {
        self.manager.peer_address(self.index)
    }

    /// The peer identity key for this connection.
    pub fn peer_identity(&self) -> Identity {
        self.manager.peer_identity(self.index)
    }

    /// The current connection params
    pub fn params(&self) -> ConnParams {
        self.manager.params(self.index)
    }

    /// Request a certain security level
    ///
    /// For a peripheral this may cause the peripheral to send a security request. For a central
    /// this may cause the central to send a pairing request.
    ///
    /// If the link is already encrypted then this will always generate an error.
    ///
    pub fn request_security(&self) -> Result<(), Error> {
        self.manager.request_security(self.index)
    }

    /// Get the encrypted state of the connection
    pub fn security_level(&self) -> Result<SecurityLevel, Error> {
        self.manager.get_security_level(self.index)
    }

    /// Get whether the connection is set as bondable or not.
    ///
    /// This is only relevant before pairing has started.
    pub fn bondable(&self) -> Result<bool, Error> {
        self.manager.get_bondable(self.index)
    }

    /// Set whether the connection is bondable or not.
    ///
    /// By default a connection is **not** bondable.
    ///
    /// This must be set before pairing is initiated. Once the pairing procedure has started
    /// this field is ignored.
    ///
    /// If both peripheral and central are bondable then the [`ConnectionEvent::PairingComplete`]
    /// event contains the bond information for the pairing. This bond information should be stored
    /// in non-volatile memory and restored on reboot using [`Stack::add_bond_information()`].
    ///
    /// If any party in a pairing is not bondable the [`ConnectionEvent::PairingComplete`] contains
    /// a `None` entry for the `bond` member.
    ///
    pub fn set_bondable(&self, bondable: bool) -> Result<(), Error> {
        self.manager.set_bondable(self.index, bondable)
    }

    /// Confirm that the displayed pass key matches the one displayed on the other party
    pub fn pass_key_confirm(&self) -> Result<(), Error> {
        self.manager.pass_key_confirm(self.index, true)
    }

    /// The displayed pass key does not match the one displayed on the other party
    pub fn pass_key_cancel(&self) -> Result<(), Error> {
        self.manager.pass_key_confirm(self.index, false)
    }

    /// Input the pairing pass key
    pub fn pass_key_input(&self, pass_key: u32) -> Result<(), Error> {
        self.manager.pass_key_input(self.index, pass_key)
    }

    /// Request connection to be disconnected.
    pub fn disconnect(&self) {
        self.manager
            .request_disconnect(self.index, DisconnectReason::RemoteUserTerminatedConn);
    }

    /// Read metrics for this connection
    #[cfg(feature = "connection-metrics")]
    pub fn metrics<F: FnOnce(&ConnectionMetrics) -> R, R>(&self, f: F) -> R {
        self.manager.metrics(self.index, f)
    }

    /// The RSSI value for this connection.
    pub async fn rssi<T>(&self, stack: &Stack<'_, T, P>) -> Result<i8, BleHostError<T::Error>>
    where
        T: ControllerCmdSync<ReadRssi>,
    {
        let handle = self.handle();
        let ret = stack.host.command(ReadRssi::new(handle)).await?;
        Ok(ret.rssi)
    }

    /// Update phy for this connection.
    ///
    /// This updates both TX and RX phy of the connection. For more fine grained control,
    /// use the LeSetPhy HCI command directly.
    pub async fn set_phy<T>(&self, stack: &Stack<'_, T, P>, phy: PhyKind) -> Result<(), BleHostError<T::Error>>
    where
        T: ControllerCmdAsync<LeSetPhy>,
    {
        let all_phys = AllPhys::new()
            .set_has_no_rx_phy_preference(false)
            .set_has_no_tx_phy_preference(false);
        let mut mask = PhyMask::new()
            .set_le_coded_phy(false)
            .set_le_1m_phy(false)
            .set_le_2m_phy(false);
        let mut options = PhyOptions::default();
        match phy {
            PhyKind::Le2M => {
                mask = mask.set_le_2m_phy(true);
            }
            PhyKind::Le1M => {
                mask = mask.set_le_1m_phy(true);
            }
            PhyKind::LeCoded => {
                mask = mask.set_le_coded_phy(true);
                options = PhyOptions::S8CodingPreferred;
            }
            PhyKind::LeCodedS2 => {
                mask = mask.set_le_coded_phy(true);
                options = PhyOptions::S2CodingPreferred;
            }
        }
        stack
            .host
            .async_command(LeSetPhy::new(self.handle(), all_phys, mask, mask, options))
            .await?;
        Ok(())
    }

    /// Read the current phy used for the connection.
    pub async fn read_phy<T>(&self, stack: &Stack<'_, T, P>) -> Result<(PhyKind, PhyKind), BleHostError<T::Error>>
    where
        T: ControllerCmdSync<LeReadPhy>,
    {
        let res = stack.host.command(LeReadPhy::new(self.handle())).await?;
        Ok((res.tx_phy, res.rx_phy))
    }

    /// Update data length for this connection.
    pub async fn update_data_length<T>(
        &self,
        stack: &Stack<'_, T, P>,
        length: u16,
        time_us: u16,
    ) -> Result<(), BleHostError<T::Error>>
    where
        T: ControllerCmdSync<LeSetDataLength> + ControllerCmdSync<LeReadLocalSupportedFeatures>,
    {
        let handle = self.handle();
        // First, check the local supported features to ensure that the connection update is supported.
        let features = stack.host.command(LeReadLocalSupportedFeatures::new()).await?;
        if length <= 27 || features.supports_le_data_packet_length_extension() {
            match stack.host.command(LeSetDataLength::new(handle, length, time_us)).await {
                Ok(_) => Ok(()),
                Err(BleHostError::BleHost(crate::Error::Hci(bt_hci::param::Error::UNKNOWN_CONN_IDENTIFIER))) => {
                    Err(crate::Error::Disconnected.into())
                }
                Err(e) => Err(e),
            }
        } else {
            Err(BleHostError::BleHost(Error::InvalidValue))
        }
    }

    /// Update connection parameters for this connection.
    pub async fn update_connection_params<T>(
        &self,
        stack: &Stack<'_, T, P>,
        params: &RequestedConnParams,
    ) -> Result<(), BleHostError<T::Error>>
    where
        T: ControllerCmdAsync<LeConnUpdate> + ControllerCmdSync<LeReadLocalSupportedFeatures>,
    {
        let handle = self.handle();
        // First, check the local supported features to ensure that the connection update is supported.
        let features = stack.host.command(LeReadLocalSupportedFeatures::new()).await?;
        if features.supports_conn_parameters_request_procedure() || self.role() == LeConnRole::Central {
            match stack.host.async_command(into_le_conn_update(handle, params)).await {
                Ok(_) => return Ok(()),
                Err(BleHostError::BleHost(crate::Error::Hci(bt_hci::param::Error::UNKNOWN_CONN_IDENTIFIER))) => {
                    return Err(crate::Error::Disconnected.into());
                }
                Err(BleHostError::BleHost(crate::Error::Hci(bt_hci::param::Error::UNSUPPORTED_REMOTE_FEATURE))) => {
                    // We tried to send the request as a periperhal but the remote central does not support procedure.
                    // Use the L2CAP signaling method below instead.
                    // This code path should never be reached when acting as a central. If a bugged controller implementation
                    // returns this error code we transmit an invalid L2CAP signal which then is rejected by the remote.
                }
                Err(e) => return Err(e),
            }
        }

        if self.role() == LeConnRole::Peripheral || cfg!(feature = "connection-params-update") {
            use crate::types::l2cap::ConnParamUpdateReq;
            // Use L2CAP signaling to update connection parameters
            info!(
                "Connection parameters request procedure not supported, use l2cap connection parameter update req instead"
            );
            let interval_min: bt_hci::param::Duration<1_250> = bt_hci_duration(params.min_connection_interval);
            let interval_max: bt_hci::param::Duration<1_250> = bt_hci_duration(params.max_connection_interval);
            let timeout: bt_hci::param::Duration<10_000> = bt_hci_duration(params.supervision_timeout);
            let param = ConnParamUpdateReq {
                interval_min: interval_min.as_u16(),
                interval_max: interval_max.as_u16(),
                latency: params.max_latency,
                timeout: timeout.as_u16(),
            };
            stack.host.send_conn_param_update_req(handle, &param).await?;
        }
        Ok(())
    }

    /// Transform BLE connection into a `GattConnection`
    #[cfg(feature = "gatt")]
    pub fn with_attribute_server<
        'values,
        'server,
        M: RawMutex,
        const ATT_MAX: usize,
        const CCCD_MAX: usize,
        const CONN_MAX: usize,
    >(
        self,
        server: &'server AttributeServer<'values, M, P, ATT_MAX, CCCD_MAX, CONN_MAX>,
    ) -> Result<GattConnection<'stack, 'server, P>, Error> {
        GattConnection::try_new(self, server)
    }
}

fn into_le_conn_update(handle: ConnHandle, params: &RequestedConnParams) -> LeConnUpdate {
    LeConnUpdate::new(
        handle,
        bt_hci_duration(params.min_connection_interval),
        bt_hci_duration(params.max_connection_interval),
        params.max_latency,
        bt_hci_duration(params.supervision_timeout),
        bt_hci_duration(params.min_event_length),
        bt_hci_duration(params.max_event_length),
    )
}