bluetooth_hci/event/
mod.rs

1//! Bluetooth events and event deserialization.
2//!
3//! This module defines all of the HCI events that can be generated by the Bluetooth controller. In
4//! addition to all of the event types, the core functionality of the module is the `Event` enum,
5//! which converts a byte buffer into an HCI event.
6
7#![macro_use]
8
9/// Verifies that the length of the LHS expression is exactly the RHS expression.  Fails with a
10/// [`BadLength`](crate::event::Error::BadLength) error if not.
11#[macro_export]
12macro_rules! require_len {
13    ($left:expr, $right:expr) => {
14        if $left.len() != $right {
15            return Err($crate::event::Error::BadLength($left.len(), $right));
16        }
17    };
18}
19
20/// Verifies that the length of the LHS expression is greater than or equal to the RHS expression.
21/// Fails with a [`BadLength`](crate::event::Error::BadLength) error if not.
22#[macro_export]
23macro_rules! require_len_at_least {
24    ($left:expr, $right:expr) => {
25        if $left.len() < $right {
26            return Err($crate::event::Error::BadLength($left.len(), $right));
27        }
28    };
29}
30
31/// Converts a specific generic enum value between specializations.  This is used below to convert
32/// from [`Error<NeverError>`] to [`Error<VendorError>`] in various places where only one error
33/// value is possible (such as from `try_into`).
34macro_rules! self_convert {
35    ($val:path) => {
36        |e| {
37            if let $val(value) = e {
38                return $val(value);
39            }
40            unreachable!();
41        }
42    };
43}
44
45pub mod command;
46
47use crate::types::{ConnectionIntervalError, FixedConnectionInterval};
48use crate::{BadStatusError, ConnectionHandle, Status};
49use byteorder::{ByteOrder, LittleEndian};
50use core::convert::{TryFrom, TryInto};
51use core::fmt::{Debug, Formatter, Result as FmtResult};
52use core::marker::{PhantomData, Sized};
53use core::mem;
54
55/// Potential events that can be generated by the controller.
56///
57/// See the Bluetooth Spec v4.1, Vol 2, Part E, Section 7.7 for a description of each event.  The
58/// events are the same for versions 4.1, 4.2, and 5.0 except where noted.
59///
60/// The spec defines an "LE Meta-Event" event. This event is not exposed directly. Instead,
61/// individual LE events are included in this enum.
62#[allow(clippy::large_enum_variant)]
63#[derive(Clone, Debug)]
64pub enum Event<V>
65where
66    V: VendorEvent,
67{
68    /// Vol 2, Part E, Section 7.7.3
69    ConnectionComplete(ConnectionComplete<V::Status>),
70
71    /// Vol 2, Part E, Section 7.7.5
72    DisconnectionComplete(DisconnectionComplete<V::Status>),
73
74    /// Vol 2, Part E, Section 7.7.8
75    EncryptionChange(EncryptionChange<V::Status>),
76
77    /// Vol 2, Part E, Section 7.7.12
78    ReadRemoteVersionInformationComplete(RemoteVersionInformation<V::Status>),
79
80    /// Vol 2, Part E, Section 7.7.14
81    CommandComplete(command::CommandComplete<V>),
82
83    /// Vol 2, Part E, Section 7.7.15
84    CommandStatus(CommandStatus<V::Status>),
85
86    /// Vol 2, Part E, Section 7.7.16
87    HardwareError(HardwareError),
88
89    /// Vol 2, Part E, Section 7.7.19
90    NumberOfCompletedPackets(NumberOfCompletedPackets),
91
92    /// Vol 2, Part E, Section 7.7.26
93    DataBufferOverflow(DataBufferOverflow),
94
95    /// Vol 2, Part E, Section 7.7.39
96    EncryptionKeyRefreshComplete(EncryptionKeyRefreshComplete<V::Status>),
97
98    /// Vol 2, Part E, Section 7.7.65.1
99    LeConnectionComplete(LeConnectionComplete<V::Status>),
100
101    /// Vol 2, Part E, Section 7.7.65.2
102    LeAdvertisingReport(LeAdvertisingReport),
103
104    /// Vol 2, Part E, Section 7.7.65.3
105    LeConnectionUpdateComplete(LeConnectionUpdateComplete<V::Status>),
106
107    /// Vol 2, Part E, Section 7.7.65.4
108    LeReadRemoteUsedFeaturesComplete(LeReadRemoteUsedFeaturesComplete<V::Status>),
109
110    /// Vol 2, Part E, Section 7.7.65.5
111    LeLongTermKeyRequest(LeLongTermKeyRequest),
112
113    /// Vendor-specific events (opcode 0xFF)
114    Vendor(V),
115}
116
117/// Trait for [vendor-specific events](Event::Vendor).
118pub trait VendorEvent {
119    /// Enumeration of vendor-specific errors that may occur when deserializing events. Generally,
120    /// this means some values in the buffer are out of range for the event.
121    type Error;
122
123    /// Enumeration of vendor-specific status codes.
124    type Status: TryFrom<u8, Error = BadStatusError> + Clone + Debug;
125
126    /// Enumeration of return parameters for vendor-specific commands.
127    type ReturnParameters: VendorReturnParameters<Error = Self::Error> + Clone + Debug;
128
129    /// Creates a new vendor-specific event from the contents of buffer. The buffer contains only
130    /// the payload of the event, which does not include the BLE event type (which must be 0xFF) or
131    /// the parameter length (which is provided by `buffer.len()`).
132    ///
133    /// # Errors
134    ///
135    /// - Shall return one of the appropriate error types (potentially including vendor-specific
136    ///   errors) if the buffer does not describe a valid event.
137    fn new(buffer: &[u8]) -> Result<Self, Error<Self::Error>>
138    where
139        Self: Sized;
140}
141
142/// Trait for return parameters for vendor-specific commands.
143pub trait VendorReturnParameters {
144    /// Enumeration of vendor-specific errors that may occur when deserializing return parameters
145    /// for vendor-specific commands.
146    type Error;
147
148    /// Deserializes vendor-specific return parameters from the contents of the buffer.  The buffer
149    /// is the full payload of the command complete event, starting with the length (1 byte) and
150    /// opcode (2 bytes).
151    fn new(buffer: &[u8]) -> Result<Self, Error<Self::Error>>
152    where
153        Self: Sized;
154}
155
156/// Errors that may occur when deserializing an event. Must be specialized by the vendor crate to
157/// allow for vendor-specific event errors.
158#[derive(Copy, Clone, Debug, PartialEq)]
159pub enum Error<V> {
160    /// The event type byte was unknown. The byte is provided.
161    UnknownEvent(u8),
162
163    /// The buffer provided that is supposed to contain an event does not have the correct
164    /// length. Field 0 is the provided length, field 1 is the expected length.
165    BadLength(usize, usize),
166
167    /// For all events: The status was not recognized (reserved for future use). Includes the
168    /// unrecognized byte.
169    BadStatus(u8),
170
171    /// For the [Connection Complete](Event::ConnectionComplete) or [Data Buffer
172    /// Overflow](Event::DataBufferOverflow) events: the link type was not recognized (reserved for
173    /// future use). Includes the unrecognized byte.
174    BadLinkType(u8),
175
176    /// For the [Connection Complete](Event::ConnectionComplete) event: the encryption enabled value
177    /// was not recognized (reserved for future use). Includes the unrecognized byte.
178    BadEncryptionEnabledValue(u8),
179
180    /// For the [Disconnection Complete](Event::DisconnectionComplete) event: the disconnection
181    /// reason was not recognized.  Includes the unrecognized byte.
182    BadReason(u8),
183
184    /// For the [Encryption Change](Event::EncryptionChange) event: The encryption type was not
185    /// recognized.  Includes the unrecognized byte.
186    BadEncryptionType(u8),
187
188    /// For the [Command Complete](Event::CommandComplete) event: The event indicated a command
189    /// completed whose opcode was not recognized. Includes the unrecognized opcode.
190    UnknownOpcode(crate::opcode::Opcode),
191
192    /// For the [Command Complete](Event::CommandComplete) event, for the Read Local Supported
193    /// Commands command return parameters: The returned command flags are invalid (i.e., they
194    /// include a flag that is reserved for future use).
195    BadCommandFlag,
196
197    /// For the [Command Complete](Event::CommandComplete) event, for the [LE Read Channel
198    /// Map](command::ReturnParameters::LeReadChannelMap) command return parameters: The returned
199    /// channel map includes a reserved bit.
200    InvalidChannelMap([u8; 5]),
201
202    /// For the [Command Complete](Event::CommandComplete) event, for the [LE Read Supported
203    /// States](command::ReturnParameters::LeReadSupportedStates) command return parameters: The
204    /// returned supported states bitfield includes a reserved bit.
205    InvalidLeStates(u64),
206
207    /// For the [LE Connection Complete](Event::LeConnectionComplete) event: The connection role was
208    /// not recognized. Includes the unrecognized byte.
209    BadLeConnectionRole(u8),
210
211    /// For the [LE Connection Complete](Event::LeConnectionComplete) or [LE Advertising
212    /// Report](Event::LeAdvertisingReport) events: The address type was not recognized. Includes
213    /// the unrecognized byte.
214    BadLeAddressType(u8),
215
216    /// For the [LE Connection Complete](Event::LeConnectionComplete) event: The returned connection
217    /// interval was invalid. Includes the error returned when attempting to create the
218    /// [FixedConnectionInterval].
219    BadConnectionInterval(ConnectionIntervalError),
220
221    /// For the [LE Connection Complete](Event::LeConnectionComplete) event: The central clock
222    /// accuracy value was not recognized.  Includes the unrecognized byte.
223    BadLeCentralClockAccuracy(u8),
224
225    /// For the [LE Advertising Report](Event::LeAdvertisingReport) event: The packet ended with a
226    /// partial report.
227    LeAdvertisementReportIncomplete,
228
229    /// For the [LE Advertising Report](Event::LeAdvertisingReport) event: The packet includes an
230    /// invalid advertisement type.  Includes the unrecognized byte.
231    BadLeAdvertisementType(u8),
232
233    /// For the [LE Read Remote Used Features Complete](Event::LeReadRemoteUsedFeaturesComplete)
234    /// event: The response included an invalid bit set for the remote features.  Includes the 8
235    /// bytes of flags.
236    BadRemoteUsedFeatureFlag(u64),
237
238    /// A vendor-specific error was detected when deserializing a vendor-specific event.
239    Vendor(V),
240}
241
242/// Extracts the value from a [`BadStatusError`](BadStatusError) and returns it as a
243/// [`BadStatus`](Error::BadStatus) error.
244pub fn rewrap_bad_status<VE>(bad_status: BadStatusError) -> Error<VE> {
245    let BadStatusError::BadValue(v) = bad_status;
246    Error::BadStatus(v)
247}
248
249fn rewrap_bad_reason<VE>(bad_status: BadStatusError) -> Error<VE> {
250    let BadStatusError::BadValue(v) = bad_status;
251    Error::BadReason(v)
252}
253
254fn rewrap_bd_addr_type_err<VE>(bad_addr_type: crate::BdAddrTypeError) -> Error<VE> {
255    Error::BadLeAddressType(bad_addr_type.0)
256}
257
258/// Defines a newtype to indicate that the buffer is supposed to contain an HCI event.
259pub struct Packet<'a>(pub &'a [u8]);
260
261impl<'a> Packet<'a> {
262    fn full_length(&self) -> usize {
263        PACKET_HEADER_LENGTH + self.0[PARAM_LEN_BYTE] as usize
264    }
265}
266
267const PACKET_HEADER_LENGTH: usize = 2;
268const EVENT_TYPE_BYTE: usize = 0;
269const PARAM_LEN_BYTE: usize = 1;
270
271impl<V> Event<V>
272where
273    V: VendorEvent,
274{
275    /// Deserializes an event from the given packet. The packet should contain all of the data
276    /// needed to deserialize the event.
277    ///
278    /// # Errors
279    ///
280    /// - [`UnknownEvent`](Error::UnknownEvent) error if the first byte of the header is not a
281    ///   recognized event type. This includes events that may be valid BLE events, but are not yet
282    ///   be implemented by this crate.
283    /// - [`BadLength`](Error::BadLength) error if the length of the packet is not sufficient to
284    ///   either (1) contain a packet header, or (2) contain the packet data as defined by the
285    ///   header.
286    /// - Other errors if the particular event cannot be correctly deserialized from the
287    ///   packet. This includes vendor-specific errors for vendor events.
288    pub fn new(packet: Packet) -> Result<Event<V>, Error<V::Error>> {
289        require_len_at_least!(packet.0, PACKET_HEADER_LENGTH);
290        require_len!(packet.0, packet.full_length());
291
292        let event_type = packet.0[EVENT_TYPE_BYTE];
293        let payload = &packet.0[PACKET_HEADER_LENGTH..packet.full_length()];
294        match event_type {
295            0x03 => Ok(Event::ConnectionComplete(to_connection_complete(payload)?)),
296            0x05 => Ok(Event::DisconnectionComplete(to_disconnection_complete(
297                payload,
298            )?)),
299            0x08 => Ok(Event::EncryptionChange(to_encryption_change(payload)?)),
300            0x0C => Ok(Event::ReadRemoteVersionInformationComplete(
301                to_remote_version_info(payload)?,
302            )),
303            0x0E => Ok(Event::CommandComplete(command::CommandComplete::new(
304                payload,
305            )?)),
306            0x0F => Ok(Event::CommandStatus(to_command_status(payload)?)),
307            0x10 => Ok(Event::HardwareError(to_hardware_error(payload)?)),
308            0x13 => Ok(Event::NumberOfCompletedPackets(
309                to_number_of_completed_packets(payload)?,
310            )),
311            0x1A => Ok(Event::DataBufferOverflow(to_data_buffer_overflow(payload)?)),
312            0x30 => Ok(Event::EncryptionKeyRefreshComplete(
313                to_encryption_key_refresh_complete(payload)?,
314            )),
315            0x3E => to_le_meta_event(payload),
316            0xFF => Ok(Event::Vendor(V::new(payload)?)),
317            _ => Err(Error::UnknownEvent(event_type)),
318        }
319    }
320}
321
322fn to_le_meta_event<V>(payload: &[u8]) -> Result<Event<V>, Error<V::Error>>
323where
324    V: VendorEvent,
325{
326    require_len_at_least!(payload, 1);
327    match payload[0] {
328        0x01 => Ok(Event::LeConnectionComplete(to_le_connection_complete(
329            payload,
330        )?)),
331        0x02 => Ok(Event::LeAdvertisingReport(to_le_advertising_report(
332            payload,
333        )?)),
334        0x03 => Ok(Event::LeConnectionUpdateComplete(
335            to_le_connection_update_complete(payload)?,
336        )),
337        0x04 => Ok(Event::LeReadRemoteUsedFeaturesComplete(
338            to_le_read_remote_used_features_complete(payload)?,
339        )),
340        0x05 => Ok(Event::LeLongTermKeyRequest(to_le_ltk_request(payload)?)),
341        _ => Err(Error::UnknownEvent(payload[0])),
342    }
343}
344
345/// The [Connection Complete](Event::ConnectionComplete) event indicates to both of the Hosts
346/// forming the connection that a new connection has been established.
347///
348/// This event also indicates to the Host which issued the connection command and then received a
349/// [Command Status](Event::CommandStatus) event, if the issued command failed or was successful.
350#[derive(Copy, Clone, Debug)]
351pub struct ConnectionComplete<VS> {
352    /// Did the connection attempt fail, and if so, how?
353    pub status: Status<VS>,
354    /// Identifies a connection between two BR/ EDR Controllers. This is used as an identifier for
355    /// transmitting and receiving voice or data.
356    pub conn_handle: ConnectionHandle,
357    /// BD ADDR of the other connected device forming the connection.
358    pub bd_addr: crate::BdAddr,
359    /// Type of connection.
360    pub link_type: LinkType,
361    /// True if the connection is encrypted.
362    pub encryption_enabled: bool,
363}
364
365/// Permissible values for [`ConnectionComplete::link_type`].
366#[derive(Copy, Clone, Debug, PartialEq)]
367pub enum LinkType {
368    /// Synchronous, connection-oriented link
369    Sco,
370    /// Asynchronous, connection-less link
371    Acl,
372}
373
374/// [TODO](https://doc.rust-lang.org/std/primitive.never.html): Replace NeverError with the
375/// language's never type (!).
376#[derive(Debug)]
377pub enum NeverError {}
378
379impl TryFrom<u8> for LinkType {
380    type Error = Error<NeverError>;
381
382    fn try_from(value: u8) -> Result<LinkType, Self::Error> {
383        match value {
384            0 => Ok(LinkType::Sco),
385            1 => Ok(LinkType::Acl),
386            _ => Err(Error::BadLinkType(value)),
387        }
388    }
389}
390
391fn to_connection_complete<VE, VS>(payload: &[u8]) -> Result<ConnectionComplete<VS>, Error<VE>>
392where
393    Status<VS>: TryFrom<u8, Error = BadStatusError>,
394{
395    require_len!(payload, 11);
396
397    let mut bd_addr = crate::BdAddr([0; 6]);
398    bd_addr.0.copy_from_slice(&payload[3..9]);
399    Ok(ConnectionComplete {
400        status: payload[0].try_into().map_err(rewrap_bad_status)?,
401        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
402        bd_addr,
403        link_type: payload[9]
404            .try_into()
405            .map_err(self_convert!(Error::BadLinkType))?,
406        encryption_enabled: try_into_encryption_enabled(payload[10])
407            .map_err(self_convert!(Error::BadEncryptionEnabledValue))?,
408    })
409}
410
411fn try_into_encryption_enabled(value: u8) -> Result<bool, Error<NeverError>> {
412    match value {
413        0 => Ok(false),
414        1 => Ok(true),
415        _ => Err(Error::BadEncryptionEnabledValue(value)),
416    }
417}
418
419/// The [Disconnection Complete](Event::DisconnectionComplete) event occurs when a connection is
420/// terminated.
421///
422/// Note: When a physical link fails, one Disconnection Complete event will be returned for each
423/// logical channel on the physical link with the corresponding [connection
424/// handle](DisconnectionComplete::conn_handle) as a parameter.
425///
426/// See the Bluetooth v4.1 spec, Vol 2, Part E, Section 7.7.5.
427#[derive(Copy, Clone, Debug)]
428pub struct DisconnectionComplete<VS> {
429    /// Indicates if the disconnection was successful or not.
430    pub status: Status<VS>,
431
432    /// Connection handle which was disconnected.
433    pub conn_handle: ConnectionHandle,
434
435    /// Indicates the reason for the disconnection if the disconnection was successful. If the
436    /// disconnection was not successful, the value of the reason parameter can be ignored by the
437    /// Host. For example, this can be the case if the Host has issued the
438    /// [Disconnect](crate::host::Hci::disconnect) command and there was a parameter error, or the
439    /// command was not presently allowed, or a connection handle that didn't correspond to a
440    /// connection was given.
441    pub reason: Status<VS>,
442}
443
444fn to_disconnection_complete<VE, VS>(payload: &[u8]) -> Result<DisconnectionComplete<VS>, Error<VE>>
445where
446    Status<VS>: TryFrom<u8, Error = BadStatusError>,
447{
448    require_len!(payload, 4);
449
450    Ok(DisconnectionComplete {
451        status: payload[0].try_into().map_err(rewrap_bad_status)?,
452        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
453        reason: payload[3].try_into().map_err(rewrap_bad_reason)?,
454    })
455}
456
457/// The [Encryption Change](Event::EncryptionChange) event is used to indicate that the change of
458/// the encryption mode has been completed.
459///
460/// This event will occur on both devices to notify the Hosts when Encryption has changed for the
461/// specified connection handle between two devices. Note: This event shall not be generated if
462/// encryption is paused or resumed; during a role switch, for example.
463///
464/// See the Bluetooth v4.1 spec, Vol 2, Part E, Section 7.7.8.
465#[derive(Copy, Clone, Debug)]
466pub struct EncryptionChange<VS> {
467    /// Indicates if the encryption change was successful or not.
468    pub status: Status<VS>,
469
470    /// Connection handle for which the link layer encryption has been enabled/disabled for all
471    /// connection handles with the same BR/EDR Controller endpoint as the specified
472    /// connection handle.
473    ///
474    /// The connection handle will be a connection handle for an ACL connection.
475    pub conn_handle: ConnectionHandle,
476
477    /// Specifies the new encryption type parameter for
478    /// [`conn_handle`](EncryptionChange::conn_handle).
479    pub encryption: Encryption,
480}
481
482/// The type of used encryption for the connection.
483///
484/// The meaning of the encryption type depends on whether the Host has indicated support for Secure
485/// Connections in the secure connections host support parameter. When secure connections host
486/// support is 'disabled' or the connection handle refers to an LE link, the Controller shall only
487/// use values [`Off`](Encryption::Off) and [`On`](Encryption::On). When secure connections host
488/// support is 'enabled' and the connection handle refers to a BR/EDR link, the Controller shall set
489/// the encryption type [`Off`](Encryption::Off) when encryption is off, to [`On`](Encryption::On)
490/// when encryption is on and using E0 and to [`OnAesCcmForBrEdr`](Encryption::OnAesCcmForBrEdr)
491/// when encryption is on and using AES-CCM.
492#[derive(Copy, Clone, Debug, PartialEq)]
493pub enum Encryption {
494    /// Encryption is disabled.
495    Off,
496    /// - On a BR/EDR link, encryption is enabled using E0
497    /// - On an LE link, encryption is enabled using AES-CCM
498    On,
499    /// On a BR/EDR link, encryption is enabled using AES-CCM. Unused for LE links.
500    OnAesCcmForBrEdr,
501}
502
503impl TryFrom<u8> for Encryption {
504    type Error = Error<NeverError>;
505    fn try_from(value: u8) -> Result<Encryption, Self::Error> {
506        match value {
507            0x00 => Ok(Encryption::Off),
508            0x01 => Ok(Encryption::On),
509            0x02 => Ok(Encryption::OnAesCcmForBrEdr),
510            _ => Err(Error::BadEncryptionType(value)),
511        }
512    }
513}
514
515fn to_encryption_change<VE, VS>(payload: &[u8]) -> Result<EncryptionChange<VS>, Error<VE>>
516where
517    Status<VS>: TryFrom<u8, Error = BadStatusError>,
518{
519    require_len!(payload, 4);
520    Ok(EncryptionChange {
521        status: payload[0].try_into().map_err(rewrap_bad_status)?,
522        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
523        encryption: payload[3]
524            .try_into()
525            .map_err(self_convert!(Error::BadEncryptionType))?,
526    })
527}
528
529/// Indicates the completion of the process obtaining the version information of the remote
530/// Controller specified by [`conn_handle`](RemoteVersionInformation::conn_handle).
531///
532/// See [`RemoteVersionInformationComplete`](Event::ReadRemoteVersionInformationComplete).
533#[derive(Copy, Clone, Debug)]
534pub struct RemoteVersionInformation<VS> {
535    /// Status of the read event.
536    pub status: Status<VS>,
537
538    /// Connection Handle which was used for the
539    /// [`read_remote_version_information`](crate::host::Hci::read_remote_version_information)
540    /// command.  The connection handle shall be for an ACL connection.
541    pub conn_handle: ConnectionHandle,
542
543    /// Version of the Current LMP in the remote Controller. See [LMP] version and [Link Layer]
544    /// version in the Bluetooth Assigned Numbers.
545    /// - When the connection handle is associated with a BR/EDR ACL-U logical link, the Version
546    ///   event parameter shall be LMP version parameter
547    /// - When the connection handle is associated with an LE-U logical link, the Version event
548    ///   parameter shall be Link Layer version parameter
549    ///
550    /// [LMP]: https://www.bluetooth.com/specifications/assigned-numbers/link-manager
551    /// [Link Layer]: https://www.bluetooth.com/specifications/assigned-numbers/link-layer
552    pub version: u8,
553
554    /// Manufacturer name of the remote Controller. See [CompId] in the Bluetooth Assigned Numbers.
555    ///
556    /// [CompId]: https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers
557    pub mfgr_name: u16,
558
559    /// Subversion of the [LMP] in the remote Controller. See the Bluetooth Spec, v4.1, Vol 2, Part
560    /// C, Table 5.2 and Vol 6, Part B, Section 2.4.2.13 (SubVersNr).  The sections are the same in
561    /// v4.2 and v5.0 of the spec.
562    ///
563    /// This field shall contain a unique value for each implementation or revision of an
564    /// implementation of the Bluetooth Controller.
565    ///
566    /// The meaning of the subversion is implementation-defined.
567    ///
568    /// [LMP]: https://www.bluetooth.com/specifications/assigned-numbers/link-manager
569    pub subversion: u16,
570}
571
572fn to_remote_version_info<VE, VS>(payload: &[u8]) -> Result<RemoteVersionInformation<VS>, Error<VE>>
573where
574    Status<VS>: TryFrom<u8, Error = BadStatusError>,
575{
576    require_len!(payload, 8);
577    Ok(RemoteVersionInformation {
578        status: payload[0].try_into().map_err(rewrap_bad_status)?,
579        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
580        version: payload[3],
581        mfgr_name: LittleEndian::read_u16(&payload[4..]),
582        subversion: LittleEndian::read_u16(&payload[6..]),
583    })
584}
585
586/// The [Command Status](Event::CommandStatus) event is used to indicate that the command described
587/// by the [`opcode`](CommandStatus::opcode) parameter has been received, and that the Controller is
588/// currently performing the task for this command.
589///
590/// Defined in Vol 2, Part E, Section 7.7.15 of the spec.
591#[derive(Copy, Clone, Debug)]
592pub struct CommandStatus<VS> {
593    /// Status of the command that has started.
594    pub status: Status<VS>,
595
596    /// Number of HCI Command packets that can be sent to the controller from the host.
597    pub num_hci_command_packets: u8,
598
599    /// Opcode of the command that generated this event. The controller can generate a spontaneous
600    /// [`Command Status`](Event::CommandStatus) with opcode 0 if the number of allowed HCI commands
601    /// has changed.
602    pub opcode: crate::opcode::Opcode,
603}
604
605fn to_command_status<VE, VS>(buffer: &[u8]) -> Result<CommandStatus<VS>, Error<VE>>
606where
607    Status<VS>: TryFrom<u8, Error = BadStatusError>,
608{
609    require_len!(buffer, 4);
610
611    Ok(CommandStatus {
612        status: buffer[0].try_into().map_err(rewrap_bad_status)?,
613        num_hci_command_packets: buffer[1],
614        opcode: crate::opcode::Opcode(LittleEndian::read_u16(&buffer[2..])),
615    })
616}
617
618/// The [Hardware Error](Event::HardwareError) event is used to notify the Host that a hardware
619/// failure has occurred in the Controller.
620///
621/// Defined in Vol 2, Part E, Section 7.7.16 of the spec.
622#[derive(Copy, Clone, Debug)]
623pub struct HardwareError {
624    /// These hardware codes will be implementation-specific, and can be assigned to indicate
625    /// various hardware problems.
626    pub code: u8,
627}
628
629fn to_hardware_error<VE>(payload: &[u8]) -> Result<HardwareError, Error<VE>> {
630    require_len!(payload, 1);
631    Ok(HardwareError { code: payload[0] })
632}
633
634/// The [`Number of Completed Packets`](Event::NumberOfCompletedPackets) event is used by the
635/// Controller to indicate to the Host how many HCI Data Packets have been completed (transmitted or
636/// flushed) for each connection handle since the previous Number Of Completed Packets event was
637/// sent to the Host.
638///
639/// Defined in Vol 2, Part E, Section 7.7.19 of the spec.
640#[derive(Copy, Clone)]
641pub struct NumberOfCompletedPackets {
642    /// Number of connection handles whose data is sent in this event.
643    num_handles: usize,
644
645    /// Data buffer for the event.
646    data_buf: [u8; NUMBER_OF_COMPLETED_PACKETS_MAX_LEN],
647}
648
649// The maximum number of bytes in the buffer is the max HCI packet size (255) less the other data in
650// the packet.
651const NUMBER_OF_COMPLETED_PACKETS_MAX_LEN: usize = 254;
652
653impl Debug for NumberOfCompletedPackets {
654    fn fmt(&self, f: &mut Formatter) -> FmtResult {
655        write!(f, "{{")?;
656        for pair in self.iter() {
657            write!(f, "{:?}", pair)?;
658        }
659        write!(f, "}}")
660    }
661}
662
663impl NumberOfCompletedPackets {
664    /// Returns an iterator over the connection handle-number of completed packet pairs.
665    pub fn iter(&self) -> NumberOfCompletedPacketsIterator {
666        NumberOfCompletedPacketsIterator {
667            event: self,
668            next_index: 0,
669        }
670    }
671}
672
673/// Iterator over the connection handle-number of completed packet pairs from the
674/// [`NumberOfCompletedPackets`] event.
675pub struct NumberOfCompletedPacketsIterator<'a> {
676    event: &'a NumberOfCompletedPackets,
677    next_index: usize,
678}
679
680const NUM_COMPLETED_PACKETS_PAIR_LEN: usize = 4;
681impl<'a> Iterator for NumberOfCompletedPacketsIterator<'a> {
682    type Item = NumberOfCompletedPacketsPair;
683
684    /// Returns the next connection handle-number of completed packets pair from the event.
685    fn next(&mut self) -> Option<Self::Item> {
686        if self.next_index >= self.event.num_handles * NUM_COMPLETED_PACKETS_PAIR_LEN {
687            return None;
688        }
689
690        let index = self.next_index;
691        self.next_index += NUM_COMPLETED_PACKETS_PAIR_LEN;
692        Some(NumberOfCompletedPacketsPair {
693            conn_handle: ConnectionHandle(LittleEndian::read_u16(&self.event.data_buf[index..])),
694            num_completed_packets: LittleEndian::read_u16(&self.event.data_buf[index + 2..])
695                as usize,
696        })
697    }
698}
699
700/// The [`NumberOfCompletedPackets`] event includes a series of connection handle-number of
701/// completed packets pairs.
702#[derive(Copy, Clone, Debug)]
703pub struct NumberOfCompletedPacketsPair {
704    /// Connection handle
705    pub conn_handle: ConnectionHandle,
706    /// The number of HCI Data Packets that have been completed (transmitted or flushed) for
707    /// [`conn_handle`](NumberOfCompletedPacketsPair::conn_handle) since the previous time the event
708    /// was returned.
709    pub num_completed_packets: usize,
710}
711
712fn to_number_of_completed_packets<VE>(
713    payload: &[u8],
714) -> Result<NumberOfCompletedPackets, Error<VE>> {
715    require_len_at_least!(payload, 1);
716
717    let num_pairs = payload[0] as usize;
718    require_len!(payload, 1 + num_pairs * NUM_COMPLETED_PACKETS_PAIR_LEN);
719
720    let mut data_buf = [0; NUMBER_OF_COMPLETED_PACKETS_MAX_LEN];
721    data_buf[..num_pairs * NUM_COMPLETED_PACKETS_PAIR_LEN].copy_from_slice(&payload[1..]);
722    Ok(NumberOfCompletedPackets {
723        num_handles: num_pairs,
724        data_buf,
725    })
726}
727
728/// Indicates that the Controller's data buffers have been overflowed.  This can occur if the Host
729/// has sent more packets than allowed.
730///
731/// Defined in Vol 2, Part E, Section 7.7.26 of the spec.
732#[derive(Copy, Clone, Debug)]
733pub struct DataBufferOverflow {
734    /// Indicates whether the overflow was caused by ACL or synchronous data.
735    pub link_type: LinkType,
736}
737
738fn to_data_buffer_overflow<VE>(payload: &[u8]) -> Result<DataBufferOverflow, Error<VE>> {
739    require_len!(payload, 1);
740    Ok(DataBufferOverflow {
741        link_type: payload[0]
742            .try_into()
743            .map_err(self_convert!(Error::BadLinkType))?,
744    })
745}
746
747/// Indicates to the Host that the encryption key was refreshed.
748///
749/// The encryption key is refreshed on the given
750/// [`conn_handle`](EncryptionKeyRefreshComplete::conn_handle) any time encryption is paused and
751/// then resumed. The BR/EDR Controller shall send this event when the encryption key has been
752/// refreshed due to encryption being started or resumed.
753///
754/// If the [Encryption Key Refresh Complete](Event::EncryptionKeyRefreshComplete) event was
755/// generated due to an encryption pause and resume operation embedded within a change connection
756/// link key procedure, the Encryption Key Refresh Complete event shall be sent prior to the Change
757/// Connection Link Key Complete event.
758///
759/// If the Encryption Key Refresh Complete event was generated due to an encryption pause and resume
760/// operation embedded within a role switch procedure, the Encryption Key Refresh Complete event
761/// shall be sent prior to the Role Change event.
762///
763/// Defined in Vol 2, Part E, Section 7.7.39 of the spec.
764#[derive(Copy, Clone, Debug)]
765pub struct EncryptionKeyRefreshComplete<VS> {
766    /// Did the encryption key refresh fail, and if so, how?
767    pub status: Status<VS>,
768    /// Connection Handle for the ACL connection to have the encryption key refreshed on.
769    pub conn_handle: ConnectionHandle,
770}
771
772fn to_encryption_key_refresh_complete<VE, VS>(
773    payload: &[u8],
774) -> Result<EncryptionKeyRefreshComplete<VS>, Error<VE>>
775where
776    Status<VS>: TryFrom<u8, Error = BadStatusError>,
777{
778    require_len!(payload, 3);
779    Ok(EncryptionKeyRefreshComplete {
780        status: payload[0].try_into().map_err(rewrap_bad_status)?,
781        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
782    })
783}
784
785/// Indicates to both of the Hosts forming the connection that a new connection has been
786/// created. Upon the creation of the connection a connection handle shall be assigned by the
787/// Controller, and passed to the Host in this event. If the connection establishment fails this
788/// event shall be provided to the Host that had issued the [LE Create
789/// Connection](crate::host::Hci::le_create_connection) command.
790///
791/// This event indicates to the Host which issued a [LE Create
792/// Connection](crate::host::Hci::le_create_connection) command and received a [Command
793/// Status](Event::CommandStatus) event if the connection establishment failed or was successful.
794///
795/// Defined in Vol 2, Part E, Section 7.7.65.1 of the spec.
796#[derive(Copy, Clone, Debug)]
797pub struct LeConnectionComplete<VS> {
798    /// Did the LE Connection fail, and if so, how?
799    pub status: Status<VS>,
800
801    /// Connection handle to be used to identify a connection between two Bluetooth devices. The
802    /// connection handle is used as an identifier for transmitting and receiving data.
803    pub conn_handle: ConnectionHandle,
804
805    /// Role of the device receiving this event in the connection.
806    pub role: ConnectionRole,
807
808    /// Address of the peer device.
809    pub peer_bd_addr: crate::BdAddrType,
810
811    /// Connection interval used on this connection.
812    pub conn_interval: FixedConnectionInterval,
813
814    /// This is only valid for a peripheral. On a central device, this parameter shall be set to
815    /// Ppm500.
816    pub central_clock_accuracy: CentralClockAccuracy,
817}
818
819/// Connection roles as returned by the [LE Connection Complete](Event::LeConnectionComplete) event.
820#[derive(Copy, Clone, Debug, PartialEq)]
821pub enum ConnectionRole {
822    /// The device is the central device for the connection.
823    ///
824    /// The Bluetooth spec refers to these as "master" devices.
825    Central,
826    /// The device is a peripheral device for the connection.
827    ///
828    /// The Bluetooth spec refers to these as "slave" devices.
829    Peripheral,
830}
831
832impl TryFrom<u8> for ConnectionRole {
833    type Error = Error<NeverError>;
834    fn try_from(value: u8) -> Result<ConnectionRole, Self::Error> {
835        match value {
836            0 => Ok(ConnectionRole::Central),
837            1 => Ok(ConnectionRole::Peripheral),
838            _ => Err(Error::BadLeConnectionRole(value)),
839        }
840    }
841}
842
843/// Values for the central (master) clock accuracy as returned by the [LE Connection
844/// Complete](Event::LeConnectionComplete) event.
845#[derive(Copy, Clone, Debug, PartialEq)]
846pub enum CentralClockAccuracy {
847    /// The central clock is accurate to at least 500 parts-per-million.  This value is also used
848    /// when the device is a central device.
849    Ppm500,
850    /// The central clock is accurate to at least 250 parts-per-million.
851    Ppm250,
852    /// The central clock is accurate to at least 150 parts-per-million.
853    Ppm150,
854    /// The central clock is accurate to at least 100 parts-per-million.
855    Ppm100,
856    /// The central clock is accurate to at least 75 parts-per-million.
857    Ppm75,
858    /// The central clock is accurate to at least 50 parts-per-million.
859    Ppm50,
860    /// The central clock is accurate to at least 30 parts-per-million.
861    Ppm30,
862    /// The central clock is accurate to at least 20 parts-per-million.
863    Ppm20,
864}
865
866impl TryFrom<u8> for CentralClockAccuracy {
867    type Error = Error<NeverError>;
868    fn try_from(value: u8) -> Result<CentralClockAccuracy, Self::Error> {
869        match value {
870            0 => Ok(CentralClockAccuracy::Ppm500),
871            1 => Ok(CentralClockAccuracy::Ppm250),
872            2 => Ok(CentralClockAccuracy::Ppm150),
873            3 => Ok(CentralClockAccuracy::Ppm100),
874            4 => Ok(CentralClockAccuracy::Ppm75),
875            5 => Ok(CentralClockAccuracy::Ppm50),
876            6 => Ok(CentralClockAccuracy::Ppm30),
877            7 => Ok(CentralClockAccuracy::Ppm20),
878            _ => Err(Error::BadLeCentralClockAccuracy(value)),
879        }
880    }
881}
882
883fn to_le_connection_complete<VE, VS>(payload: &[u8]) -> Result<LeConnectionComplete<VS>, Error<VE>>
884where
885    Status<VS>: TryFrom<u8, Error = BadStatusError>,
886{
887    require_len!(payload, 19);
888    let mut bd_addr = crate::BdAddr([0; 6]);
889    bd_addr.0.copy_from_slice(&payload[6..12]);
890    Ok(LeConnectionComplete {
891        status: payload[1].try_into().map_err(rewrap_bad_status)?,
892        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[2..])),
893        role: payload[4]
894            .try_into()
895            .map_err(self_convert!(Error::BadLeConnectionRole))?,
896        peer_bd_addr: crate::to_bd_addr_type(payload[5], bd_addr)
897            .map_err(rewrap_bd_addr_type_err)?,
898        conn_interval: FixedConnectionInterval::from_bytes(&payload[12..18])
899            .map_err(Error::BadConnectionInterval)?,
900        central_clock_accuracy: payload[18]
901            .try_into()
902            .map_err(self_convert!(Error::BadLeCentralClockAccuracy))?,
903    })
904}
905
906/// The [LE Advertising Report](Event::LeAdvertisingReport) event indicates that a Bluetooth device
907/// or multiple Bluetooth devices have responded to an active scan or received some information
908/// during a passive scan. The Controller may queue these advertising reports and send information
909/// from multiple devices in one event.
910///
911/// For Bluetooth Version 5.0: This event shall only be generated if scanning was enabled using the
912/// [LE Set Scan Enable](crate::host::Hci::le_set_scan_enable) command. It only reports advertising
913/// events that used legacy advertising PDUs.
914///
915/// Defined in Vol 2, Part E, Section 7.7.65.2 of the spec.
916#[derive(Copy, Clone)]
917pub struct LeAdvertisingReport {
918    data_len: usize,
919    data_buf: [u8; MAX_ADVERTISING_REPORT_LEN],
920}
921
922const MAX_ADVERTISING_REPORT_LEN: usize = 253;
923
924impl LeAdvertisingReport {
925    /// Returns an iterator over the advertisements from the event.
926    pub fn iter(&self) -> LeAdvertisingReportIterator {
927        LeAdvertisingReportIterator {
928            inner_iter: self.inner_iter(),
929        }
930    }
931
932    fn inner_iter<VE>(&self) -> LeAdvertisingReportInnerIterator<'_, VE> {
933        LeAdvertisingReportInnerIterator {
934            event_data: &self.data_buf[..self.data_len],
935            next_index: 0,
936            phantom: PhantomData,
937        }
938    }
939}
940
941/// Collection of functions to aid in external tests.
942pub mod test_helpers {
943    use super::*;
944
945    /// Create an [`LeAdvertisingReport`] from a slice of [`LeAdvertisement`] structs.
946    ///
947    /// Panics if the resulting report would be too big to fit in a report event.
948    pub fn report_with_advertisements<'a>(
949        advertisements: &[LeAdvertisement<'a>],
950    ) -> LeAdvertisingReport {
951        let mut data_len = 0;
952        let mut data_buf = [0; MAX_ADVERTISING_REPORT_LEN];
953
954        for advertisement in advertisements {
955            let event_type_index = data_len;
956            let addr_index = 1 + event_type_index;
957            let data_len_index = 7 + addr_index;
958            let data_start_index = 1 + data_len_index;
959            let rssi_index = data_start_index + advertisement.data.len();
960
961            data_buf[event_type_index] = advertisement.event_type as u8;
962            advertisement
963                .address
964                .copy_into_slice(&mut data_buf[addr_index..data_len_index]);
965            data_buf[data_len_index] = advertisement.data.len() as u8;
966            data_buf[data_start_index..rssi_index].copy_from_slice(advertisement.data);
967            data_buf[rssi_index] =
968                unsafe { mem::transmute::<i8, u8>(advertisement.rssi.unwrap_or(127)) };
969
970            data_len = 1 + rssi_index;
971        }
972
973        LeAdvertisingReport { data_len, data_buf }
974    }
975}
976
977impl Debug for LeAdvertisingReport {
978    fn fmt(&self, f: &mut Formatter) -> FmtResult {
979        write!(f, "{{")?;
980        for report in self.iter() {
981            write!(f, "{:?}", report)?;
982        }
983        write!(f, "}}")
984    }
985}
986
987/// Iterator over the individual LE advertisement responses in the [LE Advertising
988/// Report](Event::LeAdvertisingReport) event.
989pub struct LeAdvertisingReportIterator<'a> {
990    inner_iter: LeAdvertisingReportInnerIterator<'a, NeverError>,
991}
992
993struct LeAdvertisingReportInnerIterator<'a, VE> {
994    event_data: &'a [u8],
995    next_index: usize,
996    phantom: PhantomData<VE>,
997}
998
999impl<'a> Iterator for LeAdvertisingReportIterator<'a> {
1000    type Item = LeAdvertisement<'a>;
1001
1002    /// Returns the next connection handle-number of completed packets pair from the event.
1003    fn next(&mut self) -> Option<Self::Item> {
1004        self.inner_iter.next().unwrap()
1005    }
1006}
1007
1008impl<'a, VE> LeAdvertisingReportInnerIterator<'a, VE> {
1009    fn next(&mut self) -> Result<Option<LeAdvertisement<'a>>, Error<VE>> {
1010        if self.next_index >= self.event_data.len() {
1011            return Ok(None);
1012        }
1013
1014        let event_type_index = self.next_index;
1015        let addr_type_index = event_type_index + 1;
1016        let addr_index = addr_type_index + 1;
1017        let data_len_index = addr_index + 6;
1018        let data_len = self.event_data[data_len_index] as usize;
1019        let data_start_index = data_len_index + 1;
1020        let rssi_index = data_start_index + data_len;
1021        self.next_index = rssi_index + 1;
1022
1023        if self.next_index > self.event_data.len() {
1024            return Err(Error::LeAdvertisementReportIncomplete);
1025        }
1026
1027        let mut bd_addr = crate::BdAddr([0; 6]);
1028        bd_addr
1029            .0
1030            .copy_from_slice(&self.event_data[addr_index..data_len_index]);
1031        Ok(Some(LeAdvertisement {
1032            event_type: self.event_data[event_type_index]
1033                .try_into()
1034                .map_err(self_convert!(Error::BadLeAdvertisementType))?,
1035            address: crate::to_bd_addr_type(self.event_data[addr_type_index], bd_addr)
1036                .map_err(rewrap_bd_addr_type_err)?,
1037            data: &self.event_data[data_start_index..rssi_index],
1038            rssi: match unsafe { mem::transmute::<u8, i8>(self.event_data[rssi_index]) } {
1039                127 => None,
1040                value => Some(value),
1041            },
1042        }))
1043    }
1044}
1045
1046/// A single advertising report returned by the [LE Advertising Report](Event::LeAdvertisingReport)
1047/// event.
1048#[derive(Copy, Clone, Debug)]
1049pub struct LeAdvertisement<'a> {
1050    /// Advertising respons type
1051    pub event_type: AdvertisementEvent,
1052    /// Address of the advertising device
1053    pub address: crate::BdAddrType,
1054    /// Advertising or scan response data formatted as defined in Vol 3, Part C, Section 11 of the
1055    /// spec.
1056    pub data: &'a [u8],
1057    /// Received signal strength.
1058    ///
1059    /// - Range is -128 dBm to 20 dBm.
1060    /// - If the controller sends the value 127, `None` is returned here, since that value indicates
1061    ///   "RSSI is not available".
1062    pub rssi: Option<i8>,
1063}
1064
1065/// Types of advertisement reports.
1066///
1067/// See [`LeAdvertisement`]($crate::event::LeAdvertisement).
1068#[derive(Copy, Clone, Debug, PartialEq)]
1069pub enum AdvertisementEvent {
1070    /// Connectable undirected advertising
1071    Advertisement,
1072    /// Connectable directed advertising
1073    DirectAdvertisement,
1074    /// Scannable undirected advertising
1075    Scan,
1076    /// Non connectable undirected advertising
1077    NonConnectableAdvertisement,
1078    /// Scan Response
1079    ScanResponse,
1080}
1081
1082impl TryFrom<u8> for AdvertisementEvent {
1083    type Error = Error<NeverError>;
1084
1085    fn try_from(value: u8) -> Result<AdvertisementEvent, Self::Error> {
1086        match value {
1087            0 => Ok(AdvertisementEvent::Advertisement),
1088            1 => Ok(AdvertisementEvent::DirectAdvertisement),
1089            2 => Ok(AdvertisementEvent::Scan),
1090            3 => Ok(AdvertisementEvent::NonConnectableAdvertisement),
1091            4 => Ok(AdvertisementEvent::ScanResponse),
1092            _ => Err(Error::BadLeAdvertisementType(value)),
1093        }
1094    }
1095}
1096
1097fn to_le_advertising_report<VE>(payload: &[u8]) -> Result<LeAdvertisingReport, Error<VE>> {
1098    let mut check_iter = LeAdvertisingReportInnerIterator {
1099        event_data: &payload[2..],
1100        next_index: 0,
1101        phantom: PhantomData,
1102    };
1103    while let Some(_) = check_iter.next()? {}
1104
1105    let data_len = payload.len() - 2;
1106    let mut data_buf = [0; MAX_ADVERTISING_REPORT_LEN];
1107    data_buf[..data_len].copy_from_slice(&payload[2..]);
1108    Ok(LeAdvertisingReport { data_len, data_buf })
1109}
1110
1111/// Indicates that the Controller process to update the connection has completed.
1112///
1113/// On a peripheral, if no connection parameters are updated, then this event shall not
1114/// be issued.
1115///
1116/// On a central device, this event shall be issued if the
1117/// [`connection_update`](crate::host::Hci::le_connection_update) command was sent.
1118///
1119/// Note: This event can be issued autonomously by the central device's Controller if it decides to
1120/// change the connection interval based on the range of allowable connection intervals for that
1121/// connection.
1122///
1123/// Note: The parameter values returned in this event may be different from the parameter values
1124/// provided by the Host through the [LE Connection Update](crate::host::Hci::le_connection_update)
1125/// command or the LE Remote Connection Parameter Request Reply command (Section 7.8.31).
1126///
1127/// Defined in Vol 2, Part E, Section 7.7.65.3 of the spec.
1128#[derive(Copy, Clone, Debug)]
1129pub struct LeConnectionUpdateComplete<VS> {
1130    /// Did the LE Connection Update fail, and if so, how?
1131    pub status: Status<VS>,
1132
1133    /// Connection handle to be used to identify a connection between two Bluetooth devices. The
1134    /// connection handle is used as an identifier for transmitting and receiving data.
1135    pub conn_handle: ConnectionHandle,
1136
1137    /// Connection interval used on this connection.
1138    pub conn_interval: FixedConnectionInterval,
1139}
1140
1141fn to_le_connection_update_complete<VE, VS>(
1142    payload: &[u8],
1143) -> Result<LeConnectionUpdateComplete<VS>, Error<VE>>
1144where
1145    Status<VS>: TryFrom<u8, Error = BadStatusError>,
1146{
1147    require_len!(payload, 10);
1148    Ok(LeConnectionUpdateComplete {
1149        status: payload[1].try_into().map_err(rewrap_bad_status)?,
1150        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[2..])),
1151        conn_interval: FixedConnectionInterval::from_bytes(&payload[4..10])
1152            .map_err(Error::BadConnectionInterval)?,
1153    })
1154}
1155
1156/// Indicates the completion of the process of the Controller obtaining the features used on the
1157/// connection and the features supported by the remote Bluetooth device specified by
1158/// [`conn_handle`](LeReadRemoteUsedFeaturesComplete::conn_handle).
1159///
1160/// Note (v5.0): If the features are requested more than once while a connection exists between the
1161/// two devices, the second and subsequent requests may report a cached copy of the features rather
1162/// than fetching the feature mask again.
1163///
1164/// Defined in Vol 2, Part E, Section 7.7.65.4 of the spec.
1165#[derive(Copy, Clone, Debug)]
1166pub struct LeReadRemoteUsedFeaturesComplete<VS> {
1167    /// Did the read fail, and if so, how?
1168    pub status: Status<VS>,
1169    /// Connection handle to be used to identify a connection between two Bluetooth devices.
1170    pub conn_handle: ConnectionHandle,
1171    /// Bit Mask List of used LE features.
1172    pub features: crate::LinkLayerFeature,
1173}
1174
1175fn to_le_read_remote_used_features_complete<VE, VS>(
1176    payload: &[u8],
1177) -> Result<LeReadRemoteUsedFeaturesComplete<VS>, Error<VE>>
1178where
1179    Status<VS>: TryFrom<u8, Error = BadStatusError>,
1180{
1181    require_len!(payload, 12);
1182
1183    let feature_flags = LittleEndian::read_u64(&payload[4..]);
1184    Ok(LeReadRemoteUsedFeaturesComplete {
1185        status: payload[1].try_into().map_err(rewrap_bad_status)?,
1186        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[2..])),
1187        features: crate::LinkLayerFeature::from_bits(feature_flags)
1188            .ok_or_else(|| Error::BadRemoteUsedFeatureFlag(feature_flags))?,
1189    })
1190}
1191
1192/// The [LE Long Term Key Request](Event::LeLongTermKeyRequest) event indicates that the master
1193/// device is attempting to encrypt or re-encrypt the link and is requesting the Long Term Key from
1194/// the Host. (See Vol 6, Part B, Section 5.1.3).
1195///
1196/// Defined in Vol 2, Part E, Section 7.7.65.5 of the spec.
1197#[derive(Copy, Clone, Debug)]
1198pub struct LeLongTermKeyRequest {
1199    /// Connection handle to be used to identify a connection between two Bluetooth devices.
1200    pub conn_handle: ConnectionHandle,
1201    /// 64-bit random number.
1202    pub random_value: u64,
1203    /// 16-bit encrypted diversifier
1204    pub encrypted_diversifier: u16,
1205}
1206
1207fn to_le_ltk_request<VE>(payload: &[u8]) -> Result<LeLongTermKeyRequest, Error<VE>> {
1208    require_len!(payload, 13);
1209
1210    Ok(LeLongTermKeyRequest {
1211        conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
1212        random_value: LittleEndian::read_u64(&payload[3..]),
1213        encrypted_diversifier: LittleEndian::read_u16(&payload[11..]),
1214    })
1215}