stm32wb_hci/host/
mod.rs

1//! Host-side interface to the Bluetooth HCI.
2//!
3//! # Ideas for discussion and improvements
4//!
5//! - Remove `cmd_link` and `event_link` modules. These provide alternative mechanisms for writing
6//! to and reading from the controller, respectively, without the packet identifier byte. The
7//! open-source Bluetooth implementations I have found (admittedly, I haven't looked hard) only
8//! support sending the packet ID, as `uart` does. In that case, it would make sense to also remove
9//! `uart` and move its contents up one level.
10
11use crate::event::{NumberOfCompletedPackets, NUMBER_OF_COMPLETED_PACKETS_MAX_LEN};
12use crate::ConnectionHandle;
13use byteorder::{ByteOrder, LittleEndian};
14use core::convert::Into;
15use core::fmt::{Debug, Formatter, Result as FmtResult};
16use core::time::Duration;
17
18pub mod uart;
19
20pub use super::types::{
21    AdvertisingInterval, AdvertisingType, ConnectionInterval, ConnectionIntervalBuilder,
22    ExpectedConnectionLength, ScanWindow,
23};
24
25use crate::Status;
26
27/// Trait to define a command packet header.
28///
29/// See the Bluetooth Specification Vol 2, Part E, section 5.4.1. The command packet header contains
30/// an opcode (comprising a 6-bit OGF and 10-bit OCF) and a 1-byte parameter length. The packet
31/// itself then contains various parameters as defined by the Bluetooth specification.
32///
33/// Before this command header, many (all?) Bluetooth implementations include a 1-byte packet type
34/// preceding the command header. This version of the `HciHeader` is implemented by
35/// [`uart::CommandHeader`].
36pub trait HciHeader {
37    /// Defines the length of the packet header. With the packet byte, this is 4. Without it, the
38    /// length shall be 3.
39    const HEADER_LENGTH: usize;
40
41    /// Returns a new header with the given opcode and parameter length.
42    fn new(opcode: crate::opcode::Opcode, param_len: usize) -> Self;
43
44    /// Serialize the header into the given buffer, in Bluetooth byte order (little-endian).
45    ///
46    /// # Panics
47    ///
48    /// Panics if `buf.len() < Self::HEADER_LENGTH`
49    fn copy_into_slice(&self, buf: &mut [u8]);
50}
51
52/// Trait defining the interface from the host to the controller.
53///
54/// Defines one function for each command in the Bluetooth Specification Vol 2, Part E, Sections
55/// 7.1-7.6.
56///
57/// Specializations must define the error type `E`, used for communication errors.
58///
59/// An implementation is defined or all types that implement [`Controller`](super::Controller).
60pub trait HostHci {
61    /// Terminates an existing connection.  All synchronous connections on a physical link should be
62    /// disconnected before the ACL connection on the same physical connection is disconnected.
63    ///
64    /// - `conn_handle` indicates which connection is to be disconnected.
65    /// - `reason` indicates the reason for ending the connection. The remote Controller will
66    ///   receive the Reason command parameter in the
67    /// [Disconnection Complete](crate::event::Event::DisconnectionComplete) event.
68    ///
69    /// See the Bluetooth spec, Vol 2, Part E, Section 7.1.6.
70    ///
71    /// # Errors
72    ///
73    /// - [`BadDisconnectionReason`](Error::BadDisconnectionReason) when `reason` is not a valid
74    ///   disconnection reason.  The reason must be one of [`AuthFailure`](Status::AuthFailure),
75    ///   [`RemoteTerminationByUser`](Status::RemoteTerminationByUser),
76    ///   [`RemoteTerminationLowResources`](Status::RemoteTerminationLowResources),
77    ///   [`RemoteTerminationPowerOff`](Status::RemoteTerminationPowerOff),
78    ///   [`UnsupportedRemoteFeature`](Status::UnsupportedRemoteFeature),
79    ///   [`PairingWithUnitKeyNotSupported`](Status::PairingWithUnitKeyNotSupported), or
80    ///   [`UnacceptableConnectionParameters`](Status::UnacceptableConnectionParameters).
81    /// - Underlying communication errors.
82    ///
83    /// # Generated Events
84    ///
85    /// When the Controller receives the Disconnect command, it shall send the
86    /// [Command Status](crate::event::Event::CommandStatus) event to the Host. The
87    /// [Disconnection Complete](crate::event::Event::DisconnectionComplete) event will occur at each Host when the
88    /// termination of the connection has completed, and indicates that this command has been
89    /// completed.
90    ///
91    /// Note: No Command Complete event will be sent by the Controller to indicate that this command
92    /// has been completed. Instead, the [Disconnection Complete](crate::event::Event::DisconnectionComplete)
93    /// event will indicate that this command has been completed.
94    async fn disconnect(
95        &mut self,
96        conn_handle: ConnectionHandle,
97        reason: Status,
98    ) -> Result<(), Error>;
99
100    /// Obtains the values for the version information for the remote device identified by the
101    /// `conn_handle` parameter, which must be a connection handle for an ACL or LE connection.
102    ///
103    /// See the Bluetooth spec, Vol 2, Part E, Section 7.1.23.
104    ///
105    /// # Errors
106    ///
107    /// Only underlying communication errors are reported.
108    ///
109    /// # Generated Events
110    ///
111    /// When the Controller receives the Read Remote Version Information command, the Controller
112    /// shall send the [Command Status](crate::event::Event::CommandStatus) event to the Host. When
113    /// the Link Manager or Link Layer has completed the sequence to determine the remote version
114    /// information, the local Controller shall send a
115    /// [Read Remote Version Information Complete](crate::event::Event::ReadRemoteVersionInformationComplete)
116    /// event to the Host. That event contains the status of this command, and parameters describing the version and
117    /// subversion of the LMP or Link Layer used by the remote device.
118    ///
119    /// Note: No Command Complete event will be sent by the Controller to indicate that this command
120    /// has been completed. Instead, the [Read Remote Version Information Complete](crate::event::Event::ReadRemoteVersionInformationComplete)
121    /// event will indicate that this command has been completed.
122    async fn read_remote_version_information(&mut self, conn_handle: ConnectionHandle);
123
124    /// Controls which events are generated by the HCI for the Host. If the flag in the mask is set,
125    /// then the event associated with that bit will be enabled. For an LE Controller, the
126    /// [LE Meta Event](EventFlags::LE_META_EVENT) flag shall enable or disable all LE events (see Section
127    /// 7.7.65). The Host has to deal with each event that occurs. The event mask allows the Host to
128    /// control how much it is interrupted.
129    ///
130    /// See the Bluetooth spec, Vol 2, Part E, Section 7.3.1.
131    ///
132    /// # Errors
133    ///
134    /// Only underlying communication errors are reported.
135    ///
136    /// # Generated Events
137    ///
138    /// A [Command Complete](crate::event::command::ReturnParameters::SetEventMask) event is
139    /// generated.
140    async fn set_event_mask(&mut self, mask: EventFlags);
141
142    /// Resets the Controller and the Link Manager on the BR/EDR Controller, the PAL on an AMP
143    /// Controller, or the Link Layer on an LE Controller. If the Controller supports both BR/EDR
144    /// and LE then the Reset command shall reset the Link Manager, Baseband and Link Layer. The
145    /// Reset command shall not affect the used HCI transport layer since the HCI transport layers
146    /// may have reset mechanisms of their own. After the reset is completed, the current
147    /// operational state will be lost, the Controller will enter standby mode and the Controller
148    /// will automatically revert to the default values for the parameters for which default values
149    /// are defined in the specification.
150    ///
151    /// Note: The Reset command will not necessarily perform a hardware reset. This is
152    /// implementation defined. On an AMP Controller, the Reset command shall reset the service
153    /// provided at the logical HCI to its initial state, but beyond this the exact effect on the
154    /// Controller device is implementation defined and should not interrupt the service provided to
155    /// other protocol stacks.
156    ///
157    /// The Host shall not send additional HCI commands before the Command Complete event related to
158    /// the Reset command has been received.
159    ///
160    /// See the Bluetooth spec, Vol 2, Part E, Section 7.3.2.
161    ///
162    /// # Errors
163    ///
164    /// Only underlying communication errors are reported.
165    ///
166    /// # Generated Events
167    ///
168    /// A [Command Complete](crate::event::command::ReturnParameters::Reset) event is generated.
169    async fn reset(&mut self);
170
171    /// Reads the values for the transmit power level for the specified
172    /// `conn_handle`. `conn_handle` shall be a connection handle for an ACL connection.
173    ///
174    /// See the Bluetooth spec, Vol 2, Part E, Section 7.3.35.
175    ///
176    /// # Errors
177    ///
178    /// Only underlying communication errors are reported.
179    ///
180    /// # Generated Events
181    ///
182    /// A [Comand Complete](crate::event::command::ReturnParameters::ReadTxPowerLevel) event is
183    /// generated.
184    async fn read_tx_power_level(
185        &mut self,
186        conn_handle: ConnectionHandle,
187        power_level_type: TxPowerLevel,
188    );
189
190    /// This command is used by the Host to turn flow control on and off for data and/or voice
191    /// sent in the direction from the Controller to the Host.
192    ///
193    /// If the flow control is turned off, the Host should not send the
194    /// [Number of Completed Packets](HostHci::number_of_completed_packets) command.
195    /// That command will be ignored by the Controller it is sent by the Host and flow control is
196    /// off.
197    ///
198    /// If flow control is turned on for HCI ACL Data Packets and off for HCI synchronous
199    /// Data Packets, [Number of Completed Packets](HostHci::number_of_completed_packets)
200    /// commands sent by the Host should only contain [Connection Handles](ConnectionHandle)
201    /// for ACL connections.
202    ///
203    /// If flow control is turned off for HCI ACL Data Packets and on for HCI synchronous Data Packets,
204    /// [Number of Completed Packets](HostHci::number_of_completed_packets) commands sent
205    /// by the Host should only contain [Connection Handles](ConnectionHandle) for synchronous connections.
206    ///
207    /// If flow control is turned on for HCI ACL Data Packets and HCI synchronous Data Packets,
208    /// the Host will send [Number of Completed Packets](HostHci::number_of_completed_packets)
209    /// commands both for ACL connections and synchronous connections.
210    /// The [Flow Control](FlowControl) parameter shall only be changed if no connections exist.
211    async fn set_controller_to_host_flow_control(&mut self, flow_control: FlowControl);
212
213    /// This command is used by the Host to notify the Controller about the Maximum size of the data portion
214    /// of HCI ACL and Synchronous Sata Packets sent from the controller to the Host.
215    ///
216    /// The Controller shal segment the data to be transmitted from the Controller to the Host according
217    /// to these sizes, so that the HCI Data Packets will contain data with up to these sizes.
218    ///
219    /// This command also notifies the Controller about the total number of HCI ACL and Synchronous Data Packets
220    /// that can be storede in the data buffers of the Host.
221    ///
222    /// If flow control from the Controller to the Host is turned off, and this command has not been issued
223    /// by the Host, this means the controller will send HCI Data Packets to the Host with any lengths the
224    /// Controlller wants to use, and it is assumed that the data buffer sizes of the Host are unlimited.
225    ///
226    /// If flow control from the Controller to the Host is turned on, this command shall after a power-on
227    /// or a reset always be sent by the Host before the first
228    /// [Number of Completed Packets](HostHci::number_of_completed_packets) command is sent.
229    ///
230    /// The [Set Controller to Host Flow Control](HostHci::set_controller_to_host_flow_control) commad
231    /// is used to turn flow control on or off.
232    async fn host_buffer_size(&mut self, params: HostBufferSize);
233
234    /// This command is used by the Host to indicate to the Controller the number of HCI Data Packets
235    /// that have been completed for each [Connection Handle](ConnectionHandle) since the previous
236    /// [Number of Completed Packets](HostHci::number_of_completed_packets) command was sent to
237    /// the Controller. This means that the corresponding buffer space has been freed in the Host.
238    ///
239    ///  Based on this information, and the
240    /// [Total Number of ACL Data Packets](HostBufferSize::total_acl_data_packets) and
241    /// [Total Number of Synchronous Data Packets](HostBufferSize::total_sync_data_packets)
242    /// parameters of the [Host Buffer Size](HostHci::host_buffer_size) command, the Controller can
243    /// determine for which [Connection Handles](ConnectionHandle) the following HCI Data Packets
244    /// should be sent to the Host.
245    ///
246    /// The command should only be issued  by the Host if flow control in the direction from the Controller
247    /// to the host is on and there is at least one connection, or if the Controller  is in local loopback
248    /// mode. Otherwise, the command will will be ignored by the Controller.
249    ///
250    /// When the Host has completed one or more HCI Data Packet(s) it shall send a
251    /// [Number of Completed Packets](HostHci::number_of_completed_packets) command to the Controller,
252    /// unitl it finally reports that all pending HCI Data Packets have been completed. The frequency
253    /// at which this command is sent.
254    ///
255    /// # Note:
256    /// This command is a special command in the sense that no event is normally generated after the
257    /// command has completed. The command may be sent at any time by the Host when there is at leat
258    /// one connection, or if the Controller  is in local loopback mode independent of other commands.
259    /// The normal flow control for commands is not used for the
260    /// [Number of Complete Packets](HostHci::number_of_completed_packets) command.
261    ///
262    /// See Bluetooth spec. v.5.4 [Vol 4, Part E, 7.3.40].
263    async fn number_of_completed_packets(&mut self, params: NumberOfCompletedPackets);
264
265    /// This command reads the values for the version information for the local Controller.
266    ///
267    /// Defined in Bluetooth Specification Vol 2, Part E, Section 7.4.1.
268    ///
269    /// # Errors
270    ///
271    /// Only underlying communication errors are reported
272    ///
273    /// # Generated events
274    ///
275    /// A [Comand Complete](crate::event::command::ReturnParameters::ReadLocalVersionInformation)
276    /// event is generated.
277    async fn read_local_version_information(&mut self);
278
279    /// Reads the list of HCI commands supported for the local Controller.
280    ///
281    /// This command shall return the supported commands configuration parameter. It is implied that
282    /// if a command is listed as supported, the feature underlying that command is also supported.
283    ///
284    /// See the Bluetooth Spec, Vol 2, Part E, Section 6.27 for more information.
285    ///
286    /// See the Bluetooth spec, Vol 2, Part E, Section 7.4.2.
287    ///
288    /// # Errors
289    ///
290    /// Only underlying communication errors are reported
291    ///
292    /// # Generated events
293    ///
294    /// A [Command Complete](crate::event::command::ReturnParameters::ReadLocalSupportedCommands)
295    /// event is generated.
296    async fn read_local_supported_commands(&mut self);
297
298    /// Requests a list of the supported features for the local BR/EDR Controller.
299    ///
300    /// See the Bluetooth Spec, Vol 2, Part C, Section 3.3 for more information about the features.
301    ///
302    /// See the Bluetooth spec, Vol 2, Part E, Section 7.4.3.
303    ///
304    /// # Errors
305    ///
306    /// Only underlying communication errors are reported.
307    ///
308    /// # Generated events
309    ///
310    /// A [Command Complete](crate::event::command::ReturnParameters::ReadLocalSupportedFeatures)
311    /// event is generated.
312    async fn read_local_supported_features(&mut self);
313
314    /// On a BR/EDR Controller, this command reads the Bluetooth Controller address (BD_ADDR).
315    ///
316    /// On an LE Controller, this command shall read the Public Device Address as defined in the
317    /// Bluetooth spec, Vol 6, Part B, Section 1.3. If this Controller does not have a Public Device
318    /// Address, the value 0x000000000000 shall be returned.
319    ///
320    /// On a BR/EDR/LE Controller, the public address shall be the same as the BD_ADDR.
321    ///
322    /// See the Bluetooth spec, Vol 2, Part E, Section 7.4.6.
323    ///
324    /// # Errors
325    ///
326    /// Only underlying communication errors are reported.
327    ///
328    /// # Generated events
329    ///
330    /// A [Command Complete](crate::event::command::ReturnParameters::ReadBdAddr) event is
331    /// generated.
332    async fn read_bd_addr(&mut self);
333
334    /// Reads the Received Signal Strength Indication (RSSI) value from a Controller.
335    ///
336    /// For a BR/EDR Controller, a connection handle is used as the Handle command parameter and
337    /// return parameter. The RSSI parameter returns the difference between the measured Received
338    /// Signal Strength Indication (RSSI) and the limits of the Golden Receive Power Range for a
339    /// connection handle to another BR/EDR Controller. The connection handle must be a
340    /// connection handle for an ACL connection. Any positive RSSI value returned by the Controller
341    /// indicates how many dB the RSSI is above the upper limit, any negative value indicates how
342    /// many dB the RSSI is below the lower limit. The value zero indicates that the RSSI is inside
343    /// the Golden Receive Power Range.
344    ///
345    /// Note: How accurate the dB values will be depends on the Bluetooth hardware. The only
346    /// requirements for the hardware are that the BR/EDR Controller is able to tell whether the
347    /// RSSI is inside, above or below the Golden Device Power Range.
348    ///
349    /// The RSSI measurement compares the received signal power with two threshold levels, which
350    /// define the Golden Receive Power Range. The lower threshold level corresponds to a received
351    /// power between -56 dBm and 6 dB above the actual sensitivity of the receiver. The upper
352    /// threshold level is 20 dB above the lower threshold level to an accuracy of +/- 6 dB.
353    ///
354    /// For an AMP Controller, a physical link handle is used for the Handle command parameter and
355    /// return parameter. The meaning of the RSSI metric is AMP type specific and defined in the AMP
356    /// PALs (see Volume 5, Core System Package, AMP Controller volume).
357    ///
358    /// For an LE transport, a connection handle is used as the Handle command parameter and return
359    /// parameter. The meaning of the RSSI metric is an absolute receiver signal strength value in
360    /// dBm to ± 6 dB accuracy. If the RSSI cannot be read, the RSSI metric shall be set to 127.
361    ///
362    /// See the Bluetooth spec, Vol 2, Part E, Section 7.5.4.
363    ///
364    /// # Errors
365    ///
366    /// Only underlying communication errors are reported.
367    ///
368    /// # Generated events
369    ///
370    /// A [Command Complete](crate::event::command::ReturnParameters::ReadRssi) event is generated.
371    async fn read_rssi(&mut self, conn_handle: ConnectionHandle);
372
373    /// Controls which LE events are generated by the HCI for the Host. If the flag in `event_mask`
374    /// is set, then the event associated with that flag will be enabled. The Host has to deal with
375    /// each event that is generated by an LE Controller. The event mask allows the Host to control
376    /// which events will interrupt it.
377    ///
378    /// For LE events to be generated, the [LE Meta-Event](EventFlags::LE_META_EVENT) flag in the
379    /// [Event Mask](HostHci::set_event_mask) shall also be set. If that bit is not set, then LE events
380    /// shall not be generated, regardless of how the LE Event Mask is set.
381    ///
382    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.1.
383    ///
384    /// # Errors
385    ///
386    /// Only underlying communication errors are reported.
387    ///
388    /// # Generated events
389    ///
390    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetEventMask) event is
391    /// generated.
392    async fn le_set_event_mask(&mut self, event_mask: LeEventFlags);
393
394    /// Reads the maximum size of the data portion of HCI LE ACL Data Packets sent from the Host to
395    /// the Controller.  The Host will segment the data transmitted to the Controller according to
396    /// these values, so that the HCI Data Packets will contain data with up to this size. This
397    /// command also returns the total number of HCI LE ACL Data Packets that can be stored in the
398    /// data buffers of the Controller. This command must be issued by the Host before it sends any
399    /// data to an LE Controller (see Section 4.1.1).
400    ///
401    /// If the Controller returns a length value of zero, the Host shall use the `read_buffer_size`
402    /// command to determine the size of the data buffers (shared between BR/EDR and LE
403    /// transports).
404    ///
405    /// Note: Both the `read_buffer_size` and `le_read_buffer_size` commands may return buffer
406    /// length and number of packets parameter values that are nonzero. This allows a Controller to
407    /// offer different buffers and number of buffers for BR/EDR data packets and LE data packets.
408    ///
409    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.2.
410    ///
411    /// # Errors
412    ///
413    /// Only underlying communication errors are reported.
414    ///
415    /// # Generated events
416    ///
417    /// A [Command Complete](crate::event::command::ReturnParameters::LeReadBufferSize) event is
418    /// generated.
419    async fn le_read_buffer_size(&mut self);
420
421    /// Requests the list of the supported LE features for the Controller.
422    ///
423    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.3.
424    ///
425    /// # Errors
426    ///
427    /// Only underlying communication errors are reported.
428    ///
429    /// # Generated events
430    ///
431    /// A [Command Complete](crate::event::command::ReturnParameters::LeReadLocalSupportedFeatures)
432    /// event is generated.
433    async fn le_read_local_supported_features(&mut self);
434
435    /// Sets the LE Random Device Address in the Controller.
436    ///
437    /// See the Bluetooth spec, Vol 6, Part B, Section 1.3.
438    ///
439    /// Details added in v5.0:
440    ///
441    /// - If this command is used to change the address, the new random address shall take effect
442    ///   for advertising no later than the next successful [`le_set_advertise_enable`](HostHci) command
443    ///   (v4.x, renamed to [`le_set_advertising_enable`](HostHci) in v5.0), for scanning no later than
444    ///   the next successful [`le_set_scan_enable`](HostHci::le_set_scan_enable) command or
445    ///   `le_set_extended_scan_enable` command, and for initiating no later than the next
446    ///   successful [`le_create_connection`](HostHci::le_create_connection) command or
447    ///   `le_extended_create_connection` command.
448    ///
449    /// - Note: If Extended Advertising is in use, this command only affects the address used for
450    ///   scanning and initiating. The addresses used for advertising are set by the
451    ///   `le_set_advertising_set_random_address` command (see Section 7.8.52).
452    ///
453    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.4.
454    ///
455    /// # Errors
456    ///
457    /// - If the given address does not meet the requirements from Vol 6, Part B, Section 1.3, a
458    ///   [`BadRandomAddress`](Error::BadRandomAddress) error is returned.
459    ///   - The 2 most significant bits of the (last byte of the) address must be 00 (non-resolvable
460    ///     private address), 10 (resolvable private address), or 11 (static address).
461    ///   - The random part of the address must contain at least one 0 and at least one 1.  For
462    ///     static and non-resolvable private addresses, the random part is the entire address
463    ///     (except the 2 most significant bits).  For resolvable private addresses, the 3 least
464    ///     significant bytes are a hash, and the random part is the 3 most significant bytes.  The
465    ///     hash part of resolvable private addresses is not checked.
466    /// - Underlying communication errors are reported.
467    ///
468    /// # Generated Events
469    ///
470    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetRandomAddress) event is
471    /// generated.
472    ///
473    /// (v5.0) If the Host issues this command when scanning or legacy advertising is enabled, the
474    /// Controller shall return the error code [Command Disallowed](Status::CommandDisallowed).
475    async fn le_set_random_address(&mut self, bd_addr: crate::BdAddr) -> Result<(), Error>;
476
477    /// Sets the advertising parameters on the Controller.
478    ///
479    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.5.
480    ///
481    /// # Errors
482    ///
483    /// - [`BadChannelMap`](Error::BadChannelMap) if no channels are enabled in the channel map.
484    /// - Underlying communication errors
485    ///
486    /// # Generated events
487    ///
488    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetAdvertisingParameters)
489    /// event is generated.
490    ///
491    /// The Host shall not issue this command when advertising is enabled in the Controller; if it
492    /// is the [Command Disallowed](Status::CommandDisallowed) error code shall be used.
493    async fn le_set_advertising_parameters(
494        &mut self,
495        params: &AdvertisingParameters,
496    ) -> Result<(), Error>;
497
498    /// Reads the transmit power level used for LE advertising channel packets.
499    ///
500    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.6.
501    ///
502    /// # Errors
503    ///
504    /// Only underlying communication errors are reported.
505    ///
506    /// # Generated events
507    ///
508    /// A [Command Complete](crate::event::command::CommandComplete) event is
509    /// generated.
510    async fn le_read_advertising_channel_tx_power(&mut self);
511
512    /// Sets the data used in advertising packets that have a data field.
513    ///
514    /// Only the significant part of the advertising data should be transmitted in the advertising
515    /// packets, as defined in the Bluetooth spec, Vol 3, Part C, Section 11. All bytes in `data`
516    /// are considered significant.
517    ///
518    /// If advertising is currently enabled, the Controller shall use the new data in subsequent
519    /// advertising events. If an advertising event is in progress when this command is issued, the
520    /// Controller may use the old or new data for that event.  If advertising is currently
521    /// disabled, the data shall be kept by the Controller and used once advertising is enabled.
522    ///
523    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.7.
524    ///
525    /// # Errors
526    ///
527    /// - [`AdvertisingDataTooLong`](Error::AdvertisingDataTooLong) if `data` is 32 bytes or more.
528    /// - Underlying communication errors
529    ///
530    /// # Generated events
531    ///
532    /// A [Command Complete](crate::event::Event::CommandComplete) event is generated.
533    async fn le_set_advertising_data(&mut self, data: &[u8]) -> Result<(), Error>;
534
535    /// Provides data used in scanning packets that have a data field.
536    ///
537    /// Only the significant part of the scan response data should be transmitted in the Scanning
538    /// Packets, as defined in the Bluetooth spec, Vol 3, Part C, Section 11.  All bytes in `data`
539    /// are considered significant.
540    ///
541    /// If advertising is currently enabled, the Controller shall use the new data in subsequent
542    /// advertising events. If an advertising event is in progress when this command is issued, the
543    /// Controller may use the old or new data for that event. If advertising is currently disabled,
544    /// the data shall be kept by the Controller and used once advertising is enabled.
545    ///
546    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.8.
547    ///
548    /// # Errors
549    ///
550    /// - [`AdvertisingDataTooLong`](Error::AdvertisingDataTooLong) if `data` is 32 bytes or more.
551    /// - Underlying communication errors
552    ///
553    /// # Generated events
554    ///
555    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetScanResponseData) event
556    /// is generated.
557    async fn le_set_scan_response_data(&mut self, data: &[u8]) -> Result<(), Error>;
558
559    /// Requests the Controller to start or stop advertising. The Controller manages the timing of
560    /// advertisements as per the advertising parameters given in the
561    /// [`le_set_advertising_parameters`](HostHci::le_set_advertising_parameters) command.
562    ///
563    /// The Controller shall continue advertising until the Host issues this command with `enable`
564    /// set to false (Advertising is disabled) or until a connection is created or until the
565    /// advertising is timed out due to high duty cycle directed advertising. In these cases,
566    /// advertising is then disabled.
567    ///
568    /// If [`own_address_type`](AdvertisingParameters::own_address_type) is set to
569    /// [`Random`](OwnAddressType::Random) and the random address for the device has not been
570    /// initialized, the Controller shall return the error code
571    /// [`InvalidParameters`](Status::InvalidParameters).
572    ///
573    /// If [`own_address_type`](AdvertisingParameters::own_address_type) is set to
574    /// [`PrivateFallbackRandom`](OwnAddressType::PrivateFallbackRandom), the controller's resolving
575    /// list did not contain a matching entry, and the random address for the device has not been
576    /// initialized, the Controller shall return the error code
577    /// [`InvalidParameters`](Status::InvalidParameters).
578    ///
579    /// Note: Enabling advertising when it is already enabled can cause the random address to
580    /// change. Disabling advertising when it is already disabled has no effect.
581    ///
582    /// This function was renamed from `le_set_advertise_enable` in Bluetooth v5.0.
583    ///
584    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.9, in versions 5.0.
585    ///
586    /// # Errors
587    ///
588    /// Only underlying communication errors are reported.
589    ///
590    /// # Generated events
591    ///
592    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetAdvertisingEnable) event
593    /// is generated.
594    ///
595    /// If [`advertising_type`](crate::types::AdvertisingInterval::_advertising_type) is
596    /// [`ConnectableDirectedHighDutyCycle`](AdvertisingType::ConnectableDirectedHighDutyCycle) and
597    /// the directed advertising fails to create a connection, an
598    /// [LE Connection Complete](crate::event::Event::LeConnectionComplete) event shall be generated with the
599    /// Status code set to [`AdvertisingTimeout`](Status::AdvertisingTimeout).
600    ///
601    /// If [`advertising_type`](crate::types::AdvertisingInterval::_advertising_type) is
602    /// [`ConnectableUndirected`](AdvertisingType::ConnectableUndirected),
603    /// [`ConnectableDirectedHighDutyCycle`](AdvertisingType::ConnectableDirectedHighDutyCycle), or
604    /// [`ConnectableDirectedLowDutyCycle`](AdvertisingType::ConnectableDirectedLowDutyCycle) and a
605    /// connection is created, an
606    /// [LE Connection Complete](crate::event::Event::LeConnectionComplete) or LE Enhanced Connection Complete
607    /// event shall be generated.
608    ///
609    /// Note: There is a possible race condition if `enable` is set to false (Disable) and
610    /// [`advertising_type`](crate::types::AdvertisingInterval::_advertising_type) is
611    /// [`ConnectableUndirected`](AdvertisingType::ConnectableUndirected),
612    /// [`ConnectableDirectedHighDutyCycle`](AdvertisingType::ConnectableDirectedHighDutyCycle), or
613    /// [`ConnectableDirectedLowDutyCycle`](AdvertisingType::ConnectableDirectedLowDutyCycle). The
614    /// advertisements might not be stopped before a connection is created, and therefore both the
615    /// Command Complete event and an LE Connection Complete event or an LE Enhanced Connection
616    /// Complete event could be generated. This can also occur when high duty cycle directed
617    /// advertising is timed out and this command disables advertising.
618    async fn le_set_advertising_enable(&mut self, enable: bool);
619
620    /// Sets the scan parameters.
621    ///
622    /// The Host shall not issue this command when scanning is enabled in the Controller; if it is
623    /// the [`CommandDisallowed`](Status::CommandDisallowed) error code shall be used.
624    ///
625    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.10.
626    ///
627    /// # Errors
628    ///
629    /// Only underlying communication errors are reported.
630    ///
631    /// # Generated events
632    ///
633    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetScanParameters) event is
634    /// generated.
635    async fn le_set_scan_parameters(&mut self, params: &ScanParameters);
636
637    /// Starts scanning. Scanning is used to discover advertising devices nearby.
638    ///
639    /// `filter_duplicates` controls whether the Link Layer shall filter duplicate advertising
640    /// reports to the Host, or if the Link Layer should generate advertising reports for each
641    /// packet received.
642    ///
643    /// If [`own_address_type`](ScanParameters::own_address_type) is set to
644    /// [`Random`](OwnAddressType::Random) or [`PrivateFallbackRandom`](OwnAddressType) and the
645    /// random address for the device has not been initialized, the Controller shall return the
646    /// error code [`InvalidParameters`](Status::InvalidParameters).
647    ///
648    /// If `enable` is true and scanning is already enabled, any change to the `filter_duplicates`
649    /// setting shall take effect.
650    ///
651    /// Note: Disabling scanning when it is disabled has no effect.
652    ///
653    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.11.
654    ///
655    /// # Errors
656    ///
657    /// Only underlying communication errors are reported.
658    ///
659    /// # Generated events
660    ///
661    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetScanEnable) event is
662    /// generated.
663    ///
664    /// Zero or more [LE Advertising Reports](crate::event::Event::LeAdvertisingReport) are
665    /// generated by the Controller based on advertising packets received and the duplicate
666    /// filtering. More than one advertising packet may be reported in each LE Advertising Report
667    /// event.
668    async fn le_set_scan_enable(&mut self, enable: bool, filter_duplicates: bool);
669
670    /// Creates a Link Layer connection to a connectable advertiser.
671    ///
672    /// The Host shall not issue this command when another `le_create_connection` is pending in the
673    /// Controller; if this does occur the Controller shall return the
674    /// [`CommandDisallowed`](Status::CommandDisallowed) error code.
675    ///
676    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.12.
677    ///
678    /// # Errors
679    ///
680    /// Only underlying communication errors are reported.
681    ///
682    /// # Generated events
683    ///
684    /// The Controller sends the [Command Status](crate::event::Event::CommandStatus) event to the
685    /// Host when the event is received.  An [LE Connection Complete](crate::event::Event::LeConnectionComplete)
686    /// event shall be generated when a connection is created or the connection creation procedure is cancelled.
687    ///
688    /// Note: No Command Complete event is sent by the Controller to indicate that this command has
689    /// been completed. Instead, the LE Connection Complete event indicates that this command has
690    /// been completed.
691    async fn le_create_connection(&mut self, params: &ConnectionParameters);
692
693    /// Cancels the [`le_create_connection`](HostHci::le_create_connection) or
694    /// `le_extended_create_connection` (for v5.0) command. This command shall only be issued after
695    /// the [`le_create_connection`](HostHci::le_create_connection) command has been issued, a
696    /// [`CommandStatus`](crate::event::Event::CommandStatus) event has been received for the
697    /// [`le_create_connection`](HostHci::le_create_connection) command and before the
698    /// [`LeConnectionComplete`](crate::event::Event::LeConnectionComplete) event.
699    ///
700    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.13.
701    ///
702    /// # Errors
703    ///
704    /// Only underlying communication errors are reported.
705    ///
706    /// # Generated events
707    ///
708    /// A [Command Complete](crate::event::command::ReturnParameters::LeCreateConnectionCancel)
709    /// event shall be generated.
710    ///
711    /// If this command is sent to the Controller without a preceding
712    /// [`le_create_connection`](HostHci::le_create_connection) command, the Controller shall return a
713    /// [Command Complete](crate::event::command::ReturnParameters::LeCreateConnectionCancel) event
714    /// with the error code [`CommandDisallowed`](Status::CommandDisallowed).
715    ///
716    /// The [LE Connection Complete](crate::event::Event::LeConnectionComplete) event with the error
717    /// code [`UnknownConnectionId`](Status::UnknownConnectionId) shall be sent after the Command
718    /// Complete event for this command if the cancellation was successful.
719    async fn le_create_connection_cancel(&mut self);
720
721    /// Reads the total number of White List entries that can be stored in the Controller.
722    ///
723    /// Note: The number of entries that can be stored is not fixed and the Controller can change it
724    /// at any time (e.g. because the memory used to store the White List can also be used for other
725    /// purposes).
726    ///
727    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.14.
728    ///
729    /// # Errors
730    ///
731    /// Only underlying communication errors are reported.
732    ///
733    /// # Generated events
734    ///
735    /// A [Command Complete](crate::event::command::ReturnParameters::LeReadWhiteListSize) event is
736    /// generated.
737    async fn le_read_white_list_size(&mut self);
738
739    /// Clears the white list stored in the Controller.
740    ///
741    /// This command can be used at any time except when:
742    /// - the advertising filter policy uses the white list and advertising is enabled.
743    /// - the scanning filter policy uses the white list and scanning is enabled.
744    /// - the initiator filter policy uses the white list and an
745    ///   [`le_create_connection`](HostHci::le_create_connection) command is outstanding.
746    ///
747    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.15
748    ///
749    /// # Errors
750    ///
751    /// Only underlying communication errors are reported.
752    ///
753    /// # Generated events
754    ///
755    /// A [Command Complete](crate::event::command::ReturnParameters::LeClearWhiteList) event is
756    /// generated.
757    async fn le_clear_white_list(&mut self);
758
759    /// Adds a single device to the white list stored in the Controller.
760    ///
761    /// This command can be used at any time except when:
762    /// - the advertising filter policy uses the white list and advertising is enabled.
763    /// - the scanning filter policy uses the white list and scanning is enabled.
764    /// - the initiator filter policy uses the white list and a
765    ///   [`le_create_connection`](HostHci::le_create_connection) command is outstanding.
766    ///
767    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.16.
768    ///
769    /// # Errors
770    ///
771    /// Only underlying communication errors are reported.
772    ///
773    /// # Generated events
774    ///
775    /// A [Command Complete](crate::event::command::ReturnParameters::LeAddDeviceToWhiteList) event
776    /// is generated. When a Controller cannot add a device to the White List because there is no
777    /// space available, it shall return [`OutOfMemory`](Status::OutOfMemory).
778    async fn le_add_device_to_white_list(&mut self, addr: crate::BdAddrType);
779
780    /// Adds anonymous devices sending advertisements to the white list stored in the Controller.
781    ///
782    /// This command can be used at any time except when:
783    /// - the advertising filter policy uses the white list and advertising is enabled.
784    /// - the scanning filter policy uses the white list and scanning is enabled.
785    /// - the initiator filter policy uses the white list and a
786    ///   [`le_create_connection`](HostHci::le_create_connection) command is outstanding.
787    ///
788    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.16.
789    ///
790    /// # Errors
791    ///
792    /// Only underlying communication errors are reported.
793    ///
794    /// # Generated events
795    ///
796    /// A [Command Complete](crate::event::command::ReturnParameters::LeAddDeviceToWhiteList) event
797    /// is generated.  When a Controller cannot add a device to the White List because there is no
798    /// space available, it shall return [`OutOfMemory`](Status::OutOfMemory).
799    async fn le_add_anon_advertising_devices_to_white_list(&mut self);
800
801    /// Removes a single device from the white list stored in the Controller.
802    ///
803    /// This command can be used at any time except when:
804    /// - the advertising filter policy uses the white list and advertising is enabled.
805    /// - the scanning filter policy uses the white list and scanning is enabled.
806    /// - the initiator filter policy uses the white list and a
807    ///   [`le_create_connection`](HostHci::le_create_connection) command is outstanding.
808    ///
809    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.17.
810    ///
811    /// # Errors
812    ///
813    /// Only underlying communication errors are reported.
814    ///
815    /// # Generated events
816    ///
817    /// A [Command Complete](crate::event::command::ReturnParameters::LeRemoveDeviceFromWhiteList)
818    /// event is generated.
819    async fn le_remove_device_from_white_list(&mut self, addr: crate::BdAddrType);
820
821    /// Removes anonymous devices sending advertisements from the white list stored in the
822    /// Controller.
823    ///
824    /// This command can be used at any time except when:
825    /// - the advertising filter policy uses the white list and advertising is enabled.
826    /// - the scanning filter policy uses the white list and scanning is enabled.
827    /// - the initiator filter policy uses the white list and a
828    ///   [`le_create_connection`](HostHci::le_create_connection) command is outstanding.
829    ///
830    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.17.
831    ///
832    /// # Errors
833    ///
834    /// Only underlying communication errors are reported.
835    ///
836    /// # Generated events
837    ///
838    /// A [Command Complete](crate::event::command::ReturnParameters::LeRemoveDeviceFromWhiteList)
839    /// event is generated.
840    async fn le_remove_anon_advertising_devices_from_white_list(&mut self);
841
842    /// Changes the Link Layer connection parameters of a connection. This command may be issued on
843    /// both the central and peripheral devices.
844    ///
845    /// The actual parameter values selected by the Link Layer may be different from the parameter
846    /// values provided by the Host through this command.
847    ///
848    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.18.
849    ///
850    /// # Errors
851    ///
852    /// Only underlying communication errors are reported.
853    ///
854    /// # Generated events
855    ///
856    /// When the Controller receives the command, the Controller sends the
857    /// [Command Status](crate::event::Event::CommandStatus) event to the Host. The
858    /// [LE Connection Update Complete](crate::event::Event::LeConnectionUpdateComplete)
859    /// event shall be generated after the connection parameters have been applied by the Controller.
860    ///
861    /// Note: a Command Complete event is not sent by the Controller to indicate that this command
862    /// has been completed. Instead, the LE Connection Update Complete event indicates that this
863    /// command has been completed.
864    async fn le_connection_update(&mut self, params: &ConnectionUpdateParameters);
865
866    /// This command allows the Host to specify a channel classification for data channels based on
867    /// its "local information". This classification persists until overwritten with a subsequent
868    /// `le_set_host_channel_classification` command or until the Controller is reset using the
869    /// [`reset`](HostHci::reset) command.
870    ///
871    /// If this command is used, the Host should send it within 10 seconds of knowing that the
872    /// channel classification has changed. The interval between two successive commands sent shall
873    /// be at least one second.
874    ///
875    /// This command shall only be used when the local device supports the central role.
876    ///
877    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.19.
878    ///
879    /// # Errors
880    ///
881    /// - [`NoValidChannel`](Error::NoValidChannel) if all channels are reported as bad.
882    /// - Underlying communication errors are reported.
883    ///
884    /// # Generated events
885    ///
886    /// A [Command Complete](crate::event::command::ReturnParameters::LeSetHostChannelClassification) event is
887    /// generated.
888    async fn le_set_host_channel_classification(
889        &mut self,
890        channels: crate::ChannelClassification,
891    ) -> Result<(), Error>;
892
893    /// Returns the current channel map for the specified connection handle. The returned value
894    /// indicates the state of the channel map specified by the last transmitted or received channel
895    /// map (in a CONNECT_REQ or LL_CHANNEL_MAP_REQ message) for the specified connection handle,
896    /// regardless of whether the Master has received an acknowledgement.
897    ///
898    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.20.
899    ///
900    /// # Errors
901    ///
902    /// Only underlying communication errors are reported.
903    ///
904    /// # Generated events
905    ///
906    /// A [Command Complete](crate::event::command::ReturnParameters::LeReadChannelMap) event is
907    /// generated.
908    async fn le_read_channel_map(&mut self, conn_handle: ConnectionHandle);
909
910    /// Requests a list of the used LE features from the remote device.  This command shall return a
911    /// list of the used LE features.
912    ///
913    /// This command may be issued on both the central and peripheral devices.
914    ///
915    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.21.
916    ///
917    /// # Errors
918    ///
919    /// Only underlying communication errors are reported.
920    ///
921    /// # Generated events
922    ///
923    /// When the Controller receives this command, the Controller shall send the
924    /// [Command  Status](`crate::event::Event::CommandStatus) event to the Host. When the Controller has
925    /// completed the procedure to determine the remote features, the Controller shall send a
926    /// [LE Read Remote Used Features Complete](crate::event::Event::LeReadRemoteUsedFeaturesComplete)
927    /// event to the Host.
928    ///
929    /// The [LE Read Remote Used Features Complete](crate::event::Event::LeReadRemoteUsedFeaturesComplete)
930    /// event contains the status of this command, and the parameter describing the used features of the remote device.
931    ///
932    /// Note: A Command Complete event is not sent by the Controller to indicate that this command
933    /// has been completed. Instead, the LE Read Remote Used Features Complete event indicates that
934    /// this command has been completed.
935    async fn le_read_remote_used_features(&mut self, conn_handle: ConnectionHandle);
936
937    /// Requests the Controller to encrypt the plaintext data in the command using the key given in
938    /// the command and returns the encrypted data to the Host. The AES-128 bit block cypher is
939    /// defined in NIST Publication
940    /// [FIPS-197](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf).
941    ///
942    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.22.
943    ///
944    /// # Errors
945    ///
946    /// Only underlying communication errors are reported.
947    ///
948    /// # Generated events
949    ///
950    /// A [Command Complete](crate::event::command::ReturnParameters::LeEncrypt) event is generated.
951    async fn le_encrypt(&mut self, params: &AesParameters);
952
953    /// Requests the Controller to generate 8 octets of random data to be sent to the Host. The
954    /// random number shall be generated according to the Bluetooth spec, Vol 2, Part H, Section 2
955    /// if the [LL Encryption](crate::event::command::LmpFeatures::ENCRYPTION) Feature is supported.
956    ///
957    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.23.
958    ///
959    /// # Errors
960    ///
961    /// Only underlying communication are reported.
962    ///
963    /// # Generated events
964    ///
965    /// A [Command Complete](crate::event::command::ReturnParameters::LeRand) event is generated.
966    async fn le_rand(&mut self);
967
968    /// Authenticates the given encryption key associated with the remote device specified by the
969    /// connection handle, and once authenticated will encrypt the connection. The parameters are as
970    /// defined in the Bluetooth spec, Vol 3, Part H, Section 2.4.4.
971    ///
972    /// If the connection is already encrypted then the Controller shall pause connection encryption
973    /// before attempting to authenticate the given encryption key, and then re-encrypt the
974    /// connection. While encryption is paused no user data shall be transmitted.
975    ///
976    /// On an authentication failure, the connection shall be automatically disconnected by the Link
977    /// Layer. If this command succeeds, then the connection shall be encrypted.
978    ///
979    /// This command shall only be used when the local device is the central device.
980    ///
981    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.24.
982    ///
983    /// # Errors
984    ///
985    /// Only underlying communication errors are reported
986    ///
987    /// # Generated events
988    ///
989    /// When the Controller receives this command it shall send the [Command Status](crate::event::Event::CommandStatus)
990    ///  event to the Host. If the connection is not encrypted when this command is issued, an
991    /// [Encryption Change](crate::event::Event::EncryptionChange) event shall occur when encryption has been
992    /// started for the connection. If the connection is encrypted when this command is issued, an
993    /// [Encryption Key Refresh Complete](crate::event::Event::EncryptionKeyRefreshComplete) event
994    /// shall occur when encryption has been resumed.
995    ///
996    /// Note: A Command Complete event is not sent by the Controller to indicate that this command
997    /// has been completed. Instead, the Encryption Change or Encryption Key Refresh Complete events
998    /// indicate that this command has been completed.
999    async fn le_start_encryption(&mut self, params: &EncryptionParameters);
1000
1001    /// Replies to an [LE Long Term Key Request](crate::event::Event::LeLongTermKeyRequest) event
1002    /// from the Controller, and specifies the long term key parameter that shall be used for this
1003    /// connection handle.
1004    ///
1005    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.25.
1006    ///
1007    /// # Errors
1008    ///
1009    /// Only underlying communication errors are reported
1010    ///
1011    /// # Generated events
1012    ///
1013    /// A [Command Complete](crate::event::command::ReturnParameters::LeLongTermKeyRequestReply)
1014    /// event is generated.
1015    async fn le_long_term_key_request_reply(
1016        &mut self,
1017        conn_handle: ConnectionHandle,
1018        key: &EncryptionKey,
1019    );
1020
1021    /// Replies to an [LE Long Term Key Request](crate::event::Event::LeLongTermKeyRequest) event
1022    /// from the Controller if the Host cannot provide a Long Term Key for this connection handle.
1023    ///
1024    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.26.
1025    ///
1026    /// # Errors
1027    ///
1028    /// Only underlying communication errors are reported
1029    ///
1030    /// # Generated events
1031    ///
1032    /// A [Command Complete](crate::event::command::ReturnParameters::LeLongTermKeyRequestNegativeReply) event
1033    /// is generated.
1034    async fn le_long_term_key_request_negative_reply(&mut self, conn_handle: ConnectionHandle);
1035
1036    /// Reads the states and state combinations that the link layer supports.
1037    ///
1038    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.27.
1039    ///
1040    /// # Errors
1041    ///
1042    /// Only underlying communication errors are reported
1043    ///
1044    /// # Generated events
1045    ///
1046    /// A [Command Complete](crate::event::command::ReturnParameters::LeReadSupportedStates) event
1047    /// is generated.
1048    async fn le_read_supported_states(&mut self);
1049
1050    /// Starts a test where the DUT receives test reference packets at a fixed interval. The tester
1051    /// generates the test reference packets.
1052    ///
1053    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.28.
1054    ///
1055    /// # Errors
1056    ///
1057    /// - [`InvalidTestChannel`](Error::InvalidTestChannel) if the channel is out of range (greater
1058    ///   than 39).
1059    /// - Underlying communication errors
1060    ///
1061    /// # Generated events
1062    ///
1063    /// A [Command Complete](crate::event::command::ReturnParameters::LeReceiverTest) event is
1064    /// generated.
1065    async fn le_receiver_test(&mut self, channel: u8) -> Result<(), Error>;
1066
1067    /// Starts a test where the DUT generates test reference packets at a fixed interval. The
1068    /// Controller shall transmit at maximum power.
1069    ///
1070    /// An LE Controller supporting the `le_transmitter_test` command shall support `payload` values
1071    /// [`PrbS9`](TestPacketPayload::PrbS9), [`Nibbles10`](TestPacketPayload::Nibbles10) and
1072    /// [`Bits10`](TestPacketPayload::Bits10). An LE Controller may support other values of
1073    /// `payload`.
1074    ///
1075    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.29.
1076    ///
1077    /// # Errors
1078    ///
1079    /// - [`InvalidTestChannel`](Error::InvalidTestChannel) if the channel is out of range (greater
1080    ///   than 39).
1081    /// - [`InvalidTestPayloadLength`](Error::InvalidTestPayloadLength) if `payload_length` is out
1082    ///   of range (greater than 37).
1083    /// - Underlying communication errors.
1084    ///
1085    /// # Generated events
1086    ///
1087    /// A [Command Complete](crate::event::command::ReturnParameters::LeTransmitterTest) event is
1088    /// generated.
1089    async fn le_transmitter_test(
1090        &mut self,
1091        channel: u8,
1092        payload_length: usize,
1093        payload: TestPacketPayload,
1094    ) -> Result<(), Error>;
1095
1096    /// Stops any test which is in progress.
1097    ///
1098    /// See the Bluetooth spec, Vol 2, Part E, Section 7.8.30.
1099    ///
1100    /// # Errors
1101    ///
1102    /// Only underlying communication errors are reported.
1103    ///
1104    /// # Generated events
1105    ///
1106    /// A [Command Complete](crate::event::command::ReturnParameters::LeTestEnd) event is generated.
1107    async fn le_test_end(&mut self);
1108}
1109
1110/// Errors that may occur when sending commands to the controller.  Must be specialized on the types
1111/// of communication errors.
1112#[derive(Copy, Clone, Debug, PartialEq)]
1113#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1114pub enum Error {
1115    /// For the [`disconnect`](HostHci::disconnect) command: The provided reason is not a valid
1116    /// disconnection reason. Includes the reported reason.
1117    BadDisconnectionReason(Status),
1118
1119    /// For the [`le_set_random_address`](HostHci::le_set_random_address) command: The provided address
1120    /// does not meet the rules for random addresses in the Bluetooth Spec, Vol 6, Part B, Section
1121    /// 1.3.  Includes the invalid address.
1122    BadRandomAddress(crate::BdAddr),
1123
1124    /// For the [`le_set_advertising_parameters`](HostHci::le_set_advertising_parameters) command: The
1125    /// channel map did not include any enabled channels.  Includes the provided channel map.
1126    BadChannelMap(Channels),
1127
1128    /// For the [`le_set_advertising_data`](HostHci::le_set_advertising_data) or
1129    /// [`le_set_scan_response_data`](HostHci::le_set_scan_response_data) commands: The provided data is
1130    /// too long to fit in the command.  The maximum allowed length is 31.  The actual length is
1131    /// returned.
1132    AdvertisingDataTooLong(usize),
1133
1134    /// For the [`le_create_connection`](HostHci::le_create_connection) command: the connection length
1135    /// range is inverted (i.e, the minimum is greater than the maximum). Returns the range, min
1136    /// first.
1137    BadConnectionLengthRange(Duration, Duration),
1138
1139    /// For the [`le_set_host_channel_classification`](HostHci::le_set_host_channel_classification)
1140    /// command: all channels were marked 'bad'.
1141    NoValidChannel,
1142
1143    /// For the [`le_receiver_test`](HostHci::le_receiver_test) and
1144    /// [`le_transmitter_test`](HostHci::le_transmitter_test) commands: the channel was out of
1145    /// range. The maximum allowed channel is 39. Includes the invalid value.
1146    InvalidTestChannel(u8),
1147
1148    /// For the [`le_transmitter_test`](HostHci::le_transmitter_test) command: The payload length is
1149    /// invalid. The maximum value is 37. Includes the invalid value.
1150    InvalidTestPayloadLength(usize),
1151}
1152
1153async fn set_outbound_data<T>(
1154    controller: &mut T,
1155    opcode: crate::opcode::Opcode,
1156    data: &[u8],
1157) -> Result<(), Error>
1158where
1159    T: crate::Controller,
1160{
1161    const MAX_DATA_LEN: usize = 31;
1162    if data.len() > MAX_DATA_LEN {
1163        return Err(Error::AdvertisingDataTooLong(data.len()));
1164    }
1165    let mut params = [0; 32];
1166    params[0] = data.len() as u8;
1167    params[1..=data.len()].copy_from_slice(data);
1168    controller.controller_write(opcode, &params).await;
1169
1170    Ok(())
1171}
1172
1173impl<T> HostHci for T
1174where
1175    T: crate::Controller,
1176{
1177    async fn disconnect(
1178        &mut self,
1179        conn_handle: ConnectionHandle,
1180        reason: Status,
1181    ) -> Result<(), Error> {
1182        match reason {
1183            Status::AuthFailure
1184            | Status::RemoteTerminationByUser
1185            | Status::RemoteTerminationLowResources
1186            | Status::RemoteTerminationPowerOff
1187            | Status::UnsupportedRemoteFeature
1188            | Status::PairingWithUnitKeyNotSupported
1189            | Status::UnacceptableConnectionParameters => (),
1190            _ => return Err(Error::BadDisconnectionReason(reason)),
1191        }
1192
1193        let mut params = [0; 3];
1194        LittleEndian::write_u16(&mut params[0..], conn_handle.0);
1195        params[2] = reason.into();
1196        self.controller_write(crate::opcode::DISCONNECT, &params)
1197            .await;
1198
1199        Ok(())
1200    }
1201
1202    async fn read_remote_version_information(&mut self, conn_handle: ConnectionHandle) {
1203        let mut params = [0; 2];
1204        LittleEndian::write_u16(&mut params, conn_handle.0);
1205        self.controller_write(crate::opcode::READ_REMOTE_VERSION_INFO, &params)
1206            .await;
1207    }
1208
1209    async fn set_event_mask(&mut self, mask: EventFlags) {
1210        let mut params = [0; 8];
1211        LittleEndian::write_u64(&mut params, mask.bits());
1212
1213        self.controller_write(crate::opcode::SET_EVENT_MASK, &params)
1214            .await;
1215    }
1216
1217    async fn reset(&mut self) {
1218        self.controller_write(crate::opcode::RESET, &[]).await;
1219    }
1220
1221    async fn read_tx_power_level(
1222        &mut self,
1223        conn_handle: ConnectionHandle,
1224        power_level_type: TxPowerLevel,
1225    ) {
1226        let mut params = [0; 3];
1227        LittleEndian::write_u16(&mut params, conn_handle.0);
1228        params[2] = power_level_type as u8;
1229        self.controller_write(crate::opcode::READ_TX_POWER_LEVEL, &params)
1230            .await;
1231    }
1232
1233    async fn set_controller_to_host_flow_control(&mut self, flow_control: FlowControl) {
1234        self.controller_write(
1235            crate::opcode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL,
1236            &[flow_control as u8],
1237        )
1238        .await;
1239    }
1240
1241    async fn host_buffer_size(&mut self, params: HostBufferSize) {
1242        let mut bytes = [0; 6];
1243        params.copy_into_slice(&mut bytes);
1244        self.controller_write(crate::opcode::HOST_BUFFER_SIZE, &bytes)
1245            .await;
1246    }
1247
1248    async fn number_of_completed_packets(&mut self, params: NumberOfCompletedPackets) {
1249        let mut bytes = [0; NUMBER_OF_COMPLETED_PACKETS_MAX_LEN + 1];
1250        bytes[0] = params.num_handles as u8;
1251        bytes[1..].copy_from_slice(&params.data_buf);
1252        self.controller_write(crate::opcode::NUMBER_OF_COMPLETED_PACKETS, &bytes)
1253            .await;
1254    }
1255
1256    async fn read_local_version_information(&mut self) {
1257        self.controller_write(crate::opcode::READ_LOCAL_VERSION_INFO, &[])
1258            .await;
1259    }
1260
1261    async fn read_local_supported_commands(&mut self) {
1262        self.controller_write(crate::opcode::READ_LOCAL_SUPPORTED_COMMANDS, &[])
1263            .await;
1264    }
1265
1266    async fn read_local_supported_features(&mut self) {
1267        self.controller_write(crate::opcode::READ_LOCAL_SUPPORTED_FEATURES, &[])
1268            .await;
1269    }
1270
1271    async fn read_bd_addr(&mut self) {
1272        self.controller_write(crate::opcode::READ_BD_ADDR, &[])
1273            .await;
1274    }
1275
1276    async fn read_rssi(&mut self, conn_handle: ConnectionHandle) {
1277        let mut params = [0; 2];
1278        LittleEndian::write_u16(&mut params, conn_handle.0);
1279        self.controller_write(crate::opcode::READ_RSSI, &params)
1280            .await;
1281    }
1282
1283    async fn le_set_event_mask(&mut self, event_mask: LeEventFlags) {
1284        let mut params = [0; 8];
1285        LittleEndian::write_u64(&mut params, event_mask.bits());
1286
1287        self.controller_write(crate::opcode::LE_SET_EVENT_MASK, &params)
1288            .await;
1289    }
1290
1291    async fn le_read_buffer_size(&mut self) {
1292        self.controller_write(crate::opcode::LE_READ_BUFFER_SIZE, &[])
1293            .await;
1294    }
1295
1296    async fn le_read_local_supported_features(&mut self) {
1297        self.controller_write(crate::opcode::LE_READ_LOCAL_SUPPORTED_FEATURES, &[])
1298            .await;
1299    }
1300
1301    async fn le_set_random_address(&mut self, bd_addr: crate::BdAddr) -> Result<(), Error> {
1302        validate_random_address(bd_addr)?;
1303        self.controller_write(crate::opcode::LE_SET_RANDOM_ADDRESS, &bd_addr.0)
1304            .await;
1305
1306        Ok(())
1307    }
1308
1309    async fn le_set_advertising_parameters(
1310        &mut self,
1311        params: &AdvertisingParameters,
1312    ) -> Result<(), Error> {
1313        let mut bytes = [0; 15];
1314        params.copy_into_slice(&mut bytes)?;
1315        self.controller_write(crate::opcode::LE_SET_ADVERTISING_PARAMETERS, &bytes)
1316            .await;
1317
1318        Ok(())
1319    }
1320
1321    async fn le_read_advertising_channel_tx_power(&mut self) {
1322        self.controller_write(crate::opcode::LE_READ_ADVERTISING_CHANNEL_TX_POWER, &[])
1323            .await;
1324    }
1325
1326    async fn le_set_advertising_data(&mut self, data: &[u8]) -> Result<(), Error> {
1327        set_outbound_data::<T>(self, crate::opcode::LE_SET_ADVERTISING_DATA, data).await
1328    }
1329
1330    async fn le_set_scan_response_data(&mut self, data: &[u8]) -> Result<(), Error> {
1331        set_outbound_data::<T>(self, crate::opcode::LE_SET_SCAN_RESPONSE_DATA, data).await
1332    }
1333
1334    async fn le_set_advertising_enable(&mut self, enable: bool) {
1335        self.controller_write(crate::opcode::LE_SET_ADVERTISE_ENABLE, &[enable as u8])
1336            .await
1337    }
1338
1339    async fn le_set_scan_parameters(&mut self, params: &ScanParameters) {
1340        let mut bytes = [0; 7];
1341        params.copy_into_slice(&mut bytes);
1342        self.controller_write(crate::opcode::LE_SET_SCAN_PARAMETERS, &bytes)
1343            .await;
1344    }
1345
1346    async fn le_set_scan_enable(&mut self, enable: bool, filter_duplicates: bool) {
1347        self.controller_write(
1348            crate::opcode::LE_SET_SCAN_ENABLE,
1349            &[enable as u8, filter_duplicates as u8],
1350        )
1351        .await;
1352    }
1353
1354    async fn le_create_connection(&mut self, params: &ConnectionParameters) {
1355        let mut bytes = [0; 25];
1356        params.copy_into_slice(&mut bytes);
1357        self.controller_write(crate::opcode::LE_CREATE_CONNECTION, &bytes)
1358            .await;
1359    }
1360
1361    async fn le_create_connection_cancel(&mut self) {
1362        self.controller_write(crate::opcode::LE_CREATE_CONNECTION_CANCEL, &[])
1363            .await;
1364    }
1365
1366    async fn le_read_white_list_size(&mut self) {
1367        self.controller_write(crate::opcode::LE_READ_WHITE_LIST_SIZE, &[])
1368            .await;
1369    }
1370
1371    async fn le_clear_white_list(&mut self) {
1372        self.controller_write(crate::opcode::LE_CLEAR_WHITE_LIST, &[])
1373            .await;
1374    }
1375
1376    async fn le_add_device_to_white_list(&mut self, addr: crate::BdAddrType) {
1377        let mut params = [0; 7];
1378        addr.copy_into_slice(&mut params);
1379        self.controller_write(crate::opcode::LE_ADD_DEVICE_TO_WHITE_LIST, &params)
1380            .await;
1381    }
1382
1383    async fn le_add_anon_advertising_devices_to_white_list(&mut self) {
1384        self.controller_write(
1385            crate::opcode::LE_ADD_DEVICE_TO_WHITE_LIST,
1386            &[0xFF, 0, 0, 0, 0, 0, 0],
1387        )
1388        .await;
1389    }
1390
1391    async fn le_remove_device_from_white_list(&mut self, addr: crate::BdAddrType) {
1392        let mut params = [0; 7];
1393        addr.copy_into_slice(&mut params);
1394        self.controller_write(crate::opcode::LE_REMOVE_DEVICE_FROM_WHITE_LIST, &params)
1395            .await;
1396    }
1397
1398    async fn le_remove_anon_advertising_devices_from_white_list(&mut self) {
1399        self.controller_write(
1400            crate::opcode::LE_REMOVE_DEVICE_FROM_WHITE_LIST,
1401            &[0xFF, 0, 0, 0, 0, 0, 0],
1402        )
1403        .await;
1404    }
1405
1406    async fn le_connection_update(&mut self, params: &ConnectionUpdateParameters) {
1407        let mut bytes = [0; 14];
1408        params.copy_into_slice(&mut bytes);
1409        self.controller_write(crate::opcode::LE_CONNECTION_UPDATE, &bytes)
1410            .await;
1411    }
1412
1413    async fn le_set_host_channel_classification(
1414        &mut self,
1415        channels: crate::ChannelClassification,
1416    ) -> Result<(), Error> {
1417        if channels.is_empty() {
1418            return Err(Error::NoValidChannel);
1419        }
1420
1421        let mut bytes = [0; 5];
1422        channels.copy_into_slice(&mut bytes);
1423        self.controller_write(crate::opcode::LE_SET_HOST_CHANNEL_CLASSIFICATION, &bytes)
1424            .await;
1425
1426        Ok(())
1427    }
1428
1429    async fn le_read_channel_map(&mut self, conn_handle: ConnectionHandle) {
1430        let mut bytes = [0; 2];
1431        LittleEndian::write_u16(&mut bytes, conn_handle.0);
1432        self.controller_write(crate::opcode::LE_READ_CHANNEL_MAP, &bytes)
1433            .await;
1434    }
1435
1436    async fn le_read_remote_used_features(&mut self, conn_handle: ConnectionHandle) {
1437        let mut bytes = [0; 2];
1438        LittleEndian::write_u16(&mut bytes, conn_handle.0);
1439        self.controller_write(crate::opcode::LE_READ_REMOTE_USED_FEATURES, &bytes)
1440            .await;
1441    }
1442
1443    async fn le_encrypt(&mut self, params: &AesParameters) {
1444        let mut bytes = [0; 32];
1445        bytes[..16].copy_from_slice(&params.key.0);
1446        bytes[16..].copy_from_slice(&params.plaintext_data.0);
1447        self.controller_write(crate::opcode::LE_ENCRYPT, &bytes)
1448            .await;
1449    }
1450
1451    async fn le_rand(&mut self) {
1452        self.controller_write(crate::opcode::LE_RAND, &[]).await;
1453    }
1454
1455    async fn le_start_encryption(&mut self, params: &EncryptionParameters) {
1456        let mut bytes = [0; 28];
1457        LittleEndian::write_u16(&mut bytes[0..], params.conn_handle.0);
1458        LittleEndian::write_u64(&mut bytes[2..], params.random_number);
1459        LittleEndian::write_u16(&mut bytes[10..], params.encrypted_diversifier);
1460        bytes[12..].copy_from_slice(&params.long_term_key.0);
1461        self.controller_write(crate::opcode::LE_START_ENCRYPTION, &bytes)
1462            .await;
1463    }
1464
1465    async fn le_long_term_key_request_reply(
1466        &mut self,
1467        conn_handle: ConnectionHandle,
1468        key: &EncryptionKey,
1469    ) {
1470        let mut bytes = [0; 18];
1471        LittleEndian::write_u16(&mut bytes[0..], conn_handle.0);
1472        bytes[2..].copy_from_slice(&key.0);
1473        self.controller_write(crate::opcode::LE_LTK_REQUEST_REPLY, &bytes)
1474            .await;
1475    }
1476
1477    async fn le_long_term_key_request_negative_reply(&mut self, conn_handle: ConnectionHandle) {
1478        let mut bytes = [0; 2];
1479        LittleEndian::write_u16(&mut bytes[0..], conn_handle.0);
1480        self.controller_write(crate::opcode::LE_LTK_REQUEST_NEGATIVE_REPLY, &bytes)
1481            .await;
1482    }
1483
1484    async fn le_read_supported_states(&mut self) {
1485        self.controller_write(crate::opcode::LE_READ_STATES, &[])
1486            .await;
1487    }
1488
1489    async fn le_receiver_test(&mut self, channel: u8) -> Result<(), Error> {
1490        if channel > MAX_TEST_CHANNEL {
1491            return Err(Error::InvalidTestChannel(channel));
1492        }
1493
1494        self.controller_write(crate::opcode::LE_RECEIVER_TEST, &[channel])
1495            .await;
1496
1497        Ok(())
1498    }
1499
1500    async fn le_transmitter_test(
1501        &mut self,
1502        channel: u8,
1503        payload_length: usize,
1504        payload: TestPacketPayload,
1505    ) -> Result<(), Error> {
1506        if channel > MAX_TEST_CHANNEL {
1507            return Err(Error::InvalidTestChannel(channel));
1508        }
1509
1510        const MAX_PAYLOAD_LENGTH: usize = 0x25;
1511        if payload_length > MAX_PAYLOAD_LENGTH {
1512            return Err(Error::InvalidTestPayloadLength(payload_length));
1513        }
1514
1515        self.controller_write(
1516            crate::opcode::LE_TRANSMITTER_TEST,
1517            &[channel, payload_length as u8, payload as u8],
1518        )
1519        .await;
1520
1521        Ok(())
1522    }
1523
1524    async fn le_test_end(&mut self) {
1525        self.controller_write(crate::opcode::LE_TEST_END, &[]).await;
1526    }
1527}
1528
1529const MAX_TEST_CHANNEL: u8 = 0x27;
1530
1531#[cfg(not(feature = "defmt"))]
1532bitflags::bitflags! {
1533    /// Event flags defined for the [`set_event_mask`](HostHci::set_event_mask) command.
1534    #[derive(Default)]
1535    pub struct EventFlags : u64 {
1536        /// Inquiry complete event
1537        const INQUIRY_COMPLETE = 0x0000_0000_0000_0001;
1538        /// Inquiry result event
1539        const INQUIRY_RESULT = 0x0000_0000_0000_0002;
1540        /// Connection complete event
1541        const CONNECTION_COMPLETE = 0x0000_0000_0000_0004;
1542        /// Connection request event
1543        const CONNECTION_REQUEST = 0x0000_0000_0000_0008;
1544        /// Disconnection complete event
1545        const DISCONNECTION_COMPLETE = 0x0000_0000_0000_0010;
1546        /// Authentication complete event
1547        const AUTHENTICATION_COMPLETE = 0x0000_0000_0000_0020;
1548        /// Remote name request complete event
1549        const REMOTE_NAME_REQUEST_COMPLETE = 0x0000_0000_0000_0040;
1550        /// Encryption change event
1551        const ENCRYPTION_CHANGE = 0x0000_0000_0000_0080;
1552        /// Change connection link key complete event
1553        const CHANGE_CONNECTION_LINK_KEY_COMPLETE = 0x0000_0000_0000_0100;
1554        /// Master link key complete event
1555        const MASTER_LINK_KEY_COMPLETE = 0x0000_0000_0000_0200;
1556        /// Read remote supported features complete event
1557        const READ_REMOTE_SUPPORTED_FEATURES_COMPLETE = 0x0000_0000_0000_0400;
1558        /// Read remote version information complete event
1559        const READ_REMOTE_VERSION_INFORMATION_COMPLETE = 0x0000_0000_0000_0800;
1560        /// Qos setup complete event
1561        const QOS_SETUP_COMPLETE = 0x0000_0000_0000_1000;
1562        /// Hardware error event
1563        const HARDWARE_ERROR = 0x0000_0000_0000_8000;
1564        /// Flush occurred event
1565        const FLUSH_OCCURRED = 0x0000_0000_0001_0000;
1566        /// Role change event
1567        const ROLE_CHANGE = 0x0000_0000_0002_0000;
1568        /// Mode change event
1569        const MODE_CHANGE = 0x0000_0000_0008_0000;
1570        /// Return link keys event
1571        const RETURN_LINK_KEYS = 0x0000_0000_0010_0000;
1572        /// Pin code request event
1573        const PIN_CODE_REQUEST = 0x0000_0000_0020_0000;
1574        /// Link key request event
1575        const LINK_KEY_REQUEST = 0x0000_0000_0040_0000;
1576        /// Link key notification event
1577        const LINK_KEY_NOTIFICATION = 0x0000_0000_0080_0000;
1578        /// Loopback command event
1579        const LOOPBACK_COMMAND = 0x0000_0000_0100_0000;
1580        /// Data buffer overflow event
1581        const DATA_BUFFER_OVERFLOW = 0x0000_0000_0200_0000;
1582        /// Max slots change event
1583        const MAX_SLOTS_CHANGE = 0x0000_0000_0400_0000;
1584        /// Read clock offset complete event
1585        const READ_CLOCK_OFFSET_COMPLETE = 0x0000_0000_0800_0000;
1586        /// Connection packet type changed event
1587        const CONNECTION_PACKET_TYPE_CHANGED = 0x0000_0000_1000_0000;
1588        /// Qos violation event
1589        const QOS_VIOLATION = 0x0000_0000_2000_0000;
1590        /// Page scan mode change event. Deprecated in Bluetooth spec.
1591        #[deprecated]
1592        const PAGE_SCAN_MODE_CHANGE = 0x0000_0000_4000_0000;
1593        /// Page scan repetition mode change event
1594        const PAGE_SCAN_REPETITION_MODE_CHANGE = 0x0000_0000_8000_0000;
1595        /// Flow specification complete event
1596        const FLOW_SPECIFICATION_COMPLETE = 0x0000_0001_0000_0000;
1597        /// Inquiry result with rssi event
1598        const INQUIRY_RESULT_WITH_RSSI = 0x0000_0002_0000_0000;
1599        /// Read remote extended features complete event
1600        const READ_REMOTE_EXTENDED_FEATURES_COMPLETE = 0x0000_0004_0000_0000;
1601        /// Synchronous connection complete event
1602        const SYNCHRONOUS_CONNECTION_COMPLETE = 0x0000_0800_0000_0000;
1603        /// Synchronous connection changed event
1604        const SYNCHRONOUS_CONNECTION_CHANGED = 0x0000_1000_0000_0000;
1605        /// Sniff subrating event
1606        const SNIFF_SUBRATING = 0x0000_2000_0000_0000;
1607        /// Extended inquiry result event
1608        const EXTENDED_INQUIRY_RESULT = 0x0000_4000_0000_0000;
1609        /// Encryption key refresh complete event
1610        const ENCRYPTION_KEY_REFRESH_COMPLETE = 0x0000_8000_0000_0000;
1611        /// Io capability request event
1612        const IO_CAPABILITY_REQUEST = 0x0001_0000_0000_0000;
1613        /// Io capability request reply event
1614        const IO_CAPABILITY_REQUEST_REPLY = 0x0002_0000_0000_0000;
1615        /// User confirmation request event
1616        const USER_CONFIRMATION_REQUEST = 0x0004_0000_0000_0000;
1617        /// User passkey request event
1618        const USER_PASSKEY_REQUEST = 0x0008_0000_0000_0000;
1619        /// Remote oob data request event
1620        const REMOTE_OOB_DATA_REQUEST = 0x0010_0000_0000_0000;
1621        /// Simple pairing complete event
1622        const SIMPLE_PAIRING_COMPLETE = 0x0020_0000_0000_0000;
1623        /// Link supervision timeout changed event
1624        const LINK_SUPERVISION_TIMEOUT_CHANGED = 0x0080_0000_0000_0000;
1625        /// Enhanced flush complete event
1626        const ENHANCED_FLUSH_COMPLETE = 0x0100_0000_0000_0000;
1627        /// User passkey notification event
1628        const USER_PASSKEY_NOTIFICATION = 0x0400_0000_0000_0000;
1629        /// Keypress notification event
1630        const KEYPRESS_NOTIFICATION = 0x0800_0000_0000_0000;
1631        /// Remote host supported features notification event
1632        const REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION = 0x1000_0000_0000_0000;
1633        /// LE meta-events
1634        const LE_META_EVENT = 0x2000_0000_0000_0000;
1635    }
1636}
1637
1638#[cfg(feature = "defmt")]
1639defmt::bitflags! {
1640    /// Event flags defined for the [`set_event_mask`](HostHci::set_event_mask) command.
1641    #[derive(Default)]
1642    pub struct EventFlags : u64 {
1643        /// Inquiry complete event
1644        const INQUIRY_COMPLETE = 0x0000_0000_0000_0001;
1645        /// Inquiry result event
1646        const INQUIRY_RESULT = 0x0000_0000_0000_0002;
1647        /// Connection complete event
1648        const CONNECTION_COMPLETE = 0x0000_0000_0000_0004;
1649        /// Connection request event
1650        const CONNECTION_REQUEST = 0x0000_0000_0000_0008;
1651        /// Disconnection complete event
1652        const DISCONNECTION_COMPLETE = 0x0000_0000_0000_0010;
1653        /// Authentication complete event
1654        const AUTHENTICATION_COMPLETE = 0x0000_0000_0000_0020;
1655        /// Remote name request complete event
1656        const REMOTE_NAME_REQUEST_COMPLETE = 0x0000_0000_0000_0040;
1657        /// Encryption change event
1658        const ENCRYPTION_CHANGE = 0x0000_0000_0000_0080;
1659        /// Change connection link key complete event
1660        const CHANGE_CONNECTION_LINK_KEY_COMPLETE = 0x0000_0000_0000_0100;
1661        /// Master link key complete event
1662        const MASTER_LINK_KEY_COMPLETE = 0x0000_0000_0000_0200;
1663        /// Read remote supported features complete event
1664        const READ_REMOTE_SUPPORTED_FEATURES_COMPLETE = 0x0000_0000_0000_0400;
1665        /// Read remote version information complete event
1666        const READ_REMOTE_VERSION_INFORMATION_COMPLETE = 0x0000_0000_0000_0800;
1667        /// Qos setup complete event
1668        const QOS_SETUP_COMPLETE = 0x0000_0000_0000_1000;
1669        /// Hardware error event
1670        const HARDWARE_ERROR = 0x0000_0000_0000_8000;
1671        /// Flush occurred event
1672        const FLUSH_OCCURRED = 0x0000_0000_0001_0000;
1673        /// Role change event
1674        const ROLE_CHANGE = 0x0000_0000_0002_0000;
1675        /// Mode change event
1676        const MODE_CHANGE = 0x0000_0000_0008_0000;
1677        /// Return link keys event
1678        const RETURN_LINK_KEYS = 0x0000_0000_0010_0000;
1679        /// Pin code request event
1680        const PIN_CODE_REQUEST = 0x0000_0000_0020_0000;
1681        /// Link key request event
1682        const LINK_KEY_REQUEST = 0x0000_0000_0040_0000;
1683        /// Link key notification event
1684        const LINK_KEY_NOTIFICATION = 0x0000_0000_0080_0000;
1685        /// Loopback command event
1686        const LOOPBACK_COMMAND = 0x0000_0000_0100_0000;
1687        /// Data buffer overflow event
1688        const DATA_BUFFER_OVERFLOW = 0x0000_0000_0200_0000;
1689        /// Max slots change event
1690        const MAX_SLOTS_CHANGE = 0x0000_0000_0400_0000;
1691        /// Read clock offset complete event
1692        const READ_CLOCK_OFFSET_COMPLETE = 0x0000_0000_0800_0000;
1693        /// Connection packet type changed event
1694        const CONNECTION_PACKET_TYPE_CHANGED = 0x0000_0000_1000_0000;
1695        /// Qos violation event
1696        const QOS_VIOLATION = 0x0000_0000_2000_0000;
1697        /// Page scan mode change event. Deprecated in Bluetooth spec.
1698        #[deprecated]
1699        const PAGE_SCAN_MODE_CHANGE = 0x0000_0000_4000_0000;
1700        /// Page scan repetition mode change event
1701        const PAGE_SCAN_REPETITION_MODE_CHANGE = 0x0000_0000_8000_0000;
1702        /// Flow specification complete event
1703        const FLOW_SPECIFICATION_COMPLETE = 0x0000_0001_0000_0000;
1704        /// Inquiry result with rssi event
1705        const INQUIRY_RESULT_WITH_RSSI = 0x0000_0002_0000_0000;
1706        /// Read remote extended features complete event
1707        const READ_REMOTE_EXTENDED_FEATURES_COMPLETE = 0x0000_0004_0000_0000;
1708        /// Synchronous connection complete event
1709        const SYNCHRONOUS_CONNECTION_COMPLETE = 0x0000_0800_0000_0000;
1710        /// Synchronous connection changed event
1711        const SYNCHRONOUS_CONNECTION_CHANGED = 0x0000_1000_0000_0000;
1712        /// Sniff subrating event
1713        const SNIFF_SUBRATING = 0x0000_2000_0000_0000;
1714        /// Extended inquiry result event
1715        const EXTENDED_INQUIRY_RESULT = 0x0000_4000_0000_0000;
1716        /// Encryption key refresh complete event
1717        const ENCRYPTION_KEY_REFRESH_COMPLETE = 0x0000_8000_0000_0000;
1718        /// Io capability request event
1719        const IO_CAPABILITY_REQUEST = 0x0001_0000_0000_0000;
1720        /// Io capability request reply event
1721        const IO_CAPABILITY_REQUEST_REPLY = 0x0002_0000_0000_0000;
1722        /// User confirmation request event
1723        const USER_CONFIRMATION_REQUEST = 0x0004_0000_0000_0000;
1724        /// User passkey request event
1725        const USER_PASSKEY_REQUEST = 0x0008_0000_0000_0000;
1726        /// Remote oob data request event
1727        const REMOTE_OOB_DATA_REQUEST = 0x0010_0000_0000_0000;
1728        /// Simple pairing complete event
1729        const SIMPLE_PAIRING_COMPLETE = 0x0020_0000_0000_0000;
1730        /// Link supervision timeout changed event
1731        const LINK_SUPERVISION_TIMEOUT_CHANGED = 0x0080_0000_0000_0000;
1732        /// Enhanced flush complete event
1733        const ENHANCED_FLUSH_COMPLETE = 0x0100_0000_0000_0000;
1734        /// User passkey notification event
1735        const USER_PASSKEY_NOTIFICATION = 0x0400_0000_0000_0000;
1736        /// Keypress notification event
1737        const KEYPRESS_NOTIFICATION = 0x0800_0000_0000_0000;
1738        /// Remote host supported features notification event
1739        const REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION = 0x1000_0000_0000_0000;
1740        /// LE meta-events
1741        const LE_META_EVENT = 0x2000_0000_0000_0000;
1742    }
1743}
1744
1745/// For the [`read_tx_power_level`](HostHci::read_tx_power_level) command, the allowed values for the
1746/// type of power level to read.
1747///
1748/// See the Bluetooth spec, Vol 2, Part E, Section 7.3.35.
1749#[repr(u8)]
1750#[derive(Copy, Clone, Debug, PartialEq)]
1751#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1752pub enum TxPowerLevel {
1753    /// Read Current Transmit Power Level.
1754    Current = 0x00,
1755    /// Read Maximum Transmit Power Level.
1756    Maximum = 0x01,
1757}
1758
1759/// For the [set_controller_to_host_flow_control](HostHci::set_controller_to_host_flow_control) command, the
1760/// allowed values for flow control.
1761///
1762/// See Bluetooth spec. v.5.4 [Vol 4, Part E, 7.3.38].
1763#[repr(u8)]
1764#[derive(Copy, Clone, Debug, PartialEq, Default)]
1765#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1766pub enum FlowControl {
1767    /// Flow control off in direction from controller to host. `default`
1768    #[default]
1769    Off = 0x00,
1770    /// Flow control on for HCI ACL Data Packets and off for HCI synchronous.
1771    /// Data Packets in direction from Controller to Host.
1772    HciAclDataOnly = 0x01,
1773    /// Flow control off for HCI ACL Data Packets and on for HCI synchronous.
1774    /// Data Packets in direction from Controller to Host.
1775    HciSyncDataOnly = 0x02,
1776    /// control on both for HCI ACL Data Packets and HCI synchronous.
1777    /// Data Packets in direction from Controller to Host.
1778    Both = 0x03,
1779}
1780
1781#[derive(Copy, Clone, Debug)]
1782#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1783/// Parameters for the [host_buffer_size](HostHci::host_buffer_size) commad
1784///
1785/// # Note:
1786/// The [Host ACL Data Packet Length](HostBufferSize::acl_data_packet_length) and
1787/// [Host Synchronous Data Packet Length](HostBufferSize::sync_data_packet_length) command parameters
1788/// do not include the length of the HCI Data Packet header.
1789///
1790/// See Bluetooth spec. v.5.4 [Vol 4, Part E, 7.3.39].
1791pub struct HostBufferSize {
1792    /// Maximum length (in octets) of the data portion of each HCI ACL Data Packet that the host is able
1793    /// to accept.
1794    ///
1795    /// this parameter will be used to determine the size of the L2CAP segments contained in the ACL Data
1796    /// Packets, which are transferred from the Controller to the Host.
1797    ///
1798    /// Values:
1799    /// - 251 .. 65535
1800    pub acl_data_packet_length: u16,
1801    /// Maximum length (in octets) of the data portion of each HCI Synchronous Data Packet that the Host
1802    /// is able to accept. `NOT USED`
1803    ///
1804    /// This parameter is used to determine the maximum size of HCI Synchronous Data Packets. Both the Host
1805    /// and the Controller shall support command and event packets, zhere the data portion (excluding header)
1806    /// contained in the packet is 255 octets is size.
1807    pub sync_data_packet_length: u8,
1808    /// The total number of HCI ACL Data Packets that can be stored in the data buffers of the Host.
1809    ///
1810    /// This parameter contains the total number of HCI ACL Data Packets that can be stored in the data buffers
1811    /// of the Host. The Controller will determine how the buffers are to be divided between different
1812    /// [Connection Handles](ConnectionHandle).
1813    pub total_acl_data_packets: u16,
1814    /// Total number of HCI Synchronous Data Packets that can be stored in the data buffers of the Host. `NOT USED`
1815    ///
1816    /// This parameter gives the save information for HCI Synchronous Data Packets.
1817    pub total_sync_data_packets: u16,
1818}
1819
1820impl HostBufferSize {
1821    fn copy_into_slice(&self, bytes: &mut [u8]) {
1822        assert_eq!(bytes.len(), 6);
1823
1824        LittleEndian::write_u16(&mut bytes[0..], self.acl_data_packet_length);
1825        bytes[2] = self.sync_data_packet_length;
1826        LittleEndian::write_u16(&mut bytes[3..], self.total_acl_data_packets);
1827        LittleEndian::write_u16(&mut bytes[5..], self.total_sync_data_packets);
1828    }
1829}
1830
1831#[cfg(not(feature = "defmt"))]
1832bitflags::bitflags! {
1833    /// Event flags defined for the [`le_set_event_mask`](HostHci::le_set_event_mask) command.
1834    #[derive(Default)]
1835    pub struct LeEventFlags : u64 {
1836        /// LE connection complete event
1837        const CONNECTION_COMPLETE = 1 << 0;
1838        /// LE advertising report event
1839        const ADVERTISING_REPORT = 1 << 1;
1840        /// LE connection update complete event
1841        const CONNECTION_UPDATE_COMPLETE = 1 << 2;
1842        /// LE read remote features complete event
1843        const READ_REMOTE_FEATURES_COMPLETE = 1 << 3;
1844        /// LE long term key request event
1845        const LONG_TERM_KEY_REQUEST = 1 << 4;
1846        /// LE remote connection parameter request event
1847        const REMOTE_CONNECTION_PARAMETER_REQUEST = 1 << 5;
1848        /// LE data length change event
1849        const DATA_LENGTH_CHANGE = 1 << 6;
1850        /// LE read local p256 public key complete event
1851        const READ_LOCAL_P256_PUBLIC_KEY_COMPLETE = 1 << 7;
1852        /// LE generate dhkey complete event
1853        const GENERATE_DHKEY_COMPLETE = 1 << 8;
1854        /// LE enhanced connection complete event
1855        const ENHANCED_CONNECTION_COMPLETE = 1 << 9;
1856        /// LE directed advertising report event
1857        const DIRECTED_ADVERTISING_REPORT = 1 << 10;
1858        /// LE phy update complete event
1859        const PHY_UPDATE_COMPLETE = 1 << 11;
1860        /// LE extended advertising report event
1861        const EXTENDED_ADVERTISING_REPORT = 1 << 12;
1862        /// LE periodic advertising sync established event
1863        const PERIODIC_ADVERTISING_SYNC_ESTABLISHED = 1 << 13;
1864        /// LE periodic advertising report event
1865        const PERIODIC_ADVERTISING_REPORT = 1 << 14;
1866        /// LE periodic advertising sync lost event
1867        const PERIODIC_ADVERTISING_SYNC_LOST = 1 << 15;
1868        /// LE extended scan timeout event
1869        const EXTENDED_SCAN_TIMEOUT = 1 << 16;
1870        /// LE extended advertising set terminated event
1871        const EXTENDED_ADVERTISING_SET_TERMINATED = 1 << 17;
1872        /// LE scan request received event
1873        const SCAN_REQUEST_RECEIVED = 1 << 18;
1874        /// LE channel selection algorithm event
1875        const CHANNEL_SELECTION_ALGORITHM = 1 << 19;
1876    }
1877}
1878
1879#[cfg(feature = "defmt")]
1880defmt::bitflags! {
1881    /// Event flags defined for the [`le_set_event_mask`](HostHci::le_set_event_mask) command.
1882    #[derive(Default)]
1883    pub struct LeEventFlags : u64 {
1884        /// LE connection complete event
1885        const CONNECTION_COMPLETE = 1 << 0;
1886        /// LE advertising report event
1887        const ADVERTISING_REPORT = 1 << 1;
1888        /// LE connection update complete event
1889        const CONNECTION_UPDATE_COMPLETE = 1 << 2;
1890        /// LE read remote features complete event
1891        const READ_REMOTE_FEATURES_COMPLETE = 1 << 3;
1892        /// LE long term key request event
1893        const LONG_TERM_KEY_REQUEST = 1 << 4;
1894        /// LE remote connection parameter request event
1895        const REMOTE_CONNECTION_PARAMETER_REQUEST = 1 << 5;
1896        /// LE data length change event
1897        const DATA_LENGTH_CHANGE = 1 << 6;
1898        /// LE read local p256 public key complete event
1899        const READ_LOCAL_P256_PUBLIC_KEY_COMPLETE = 1 << 7;
1900        /// LE generate dhkey complete event
1901        const GENERATE_DHKEY_COMPLETE = 1 << 8;
1902        /// LE enhanced connection complete event
1903        const ENHANCED_CONNECTION_COMPLETE = 1 << 9;
1904        /// LE directed advertising report event
1905        const DIRECTED_ADVERTISING_REPORT = 1 << 10;
1906        /// LE phy update complete event
1907        const PHY_UPDATE_COMPLETE = 1 << 11;
1908        /// LE extended advertising report event
1909        const EXTENDED_ADVERTISING_REPORT = 1 << 12;
1910        /// LE periodic advertising sync established event
1911        const PERIODIC_ADVERTISING_SYNC_ESTABLISHED = 1 << 13;
1912        /// LE periodic advertising report event
1913        const PERIODIC_ADVERTISING_REPORT = 1 << 14;
1914        /// LE periodic advertising sync lost event
1915        const PERIODIC_ADVERTISING_SYNC_LOST = 1 << 15;
1916        /// LE extended scan timeout event
1917        const EXTENDED_SCAN_TIMEOUT = 1 << 16;
1918        /// LE extended advertising set terminated event
1919        const EXTENDED_ADVERTISING_SET_TERMINATED = 1 << 17;
1920        /// LE scan request received event
1921        const SCAN_REQUEST_RECEIVED = 1 << 18;
1922        /// LE channel selection algorithm event
1923        const CHANNEL_SELECTION_ALGORITHM = 1 << 19;
1924    }
1925}
1926
1927fn validate_random_address(bd_addr: crate::BdAddr) -> Result<(), Error> {
1928    let (pop_count, bit_count) = match (bd_addr.0[5] & 0b1100_0000) >> 6 {
1929        0b00 | 0b11 => (pop_count_except_top_2_bits(&bd_addr.0[0..]), 46),
1930        0b10 => (pop_count_except_top_2_bits(&bd_addr.0[3..]), 22),
1931        _ => return Err(Error::BadRandomAddress(bd_addr)),
1932    };
1933
1934    if pop_count == 0 || pop_count == bit_count {
1935        return Err(Error::BadRandomAddress(bd_addr));
1936    }
1937
1938    Ok(())
1939}
1940
1941fn pop_count_except_top_2_bits(bytes: &[u8]) -> u32 {
1942    let mut pop_count = 0;
1943    for byte in bytes[..bytes.len() - 1].iter() {
1944        pop_count += pop_count_of(*byte);
1945    }
1946    pop_count += pop_count_of(bytes[bytes.len() - 1] & 0b0011_1111);
1947
1948    pop_count
1949}
1950
1951fn pop_count_of(byte: u8) -> u32 {
1952    byte.count_ones()
1953}
1954
1955/// Parameters for the [`le_set_advertising_parameters`](HostHci::le_set_advertising_parameters)
1956/// command.
1957#[derive(Clone, Debug)]
1958pub struct AdvertisingParameters {
1959    /// Type and allowable duration of advertising.
1960    pub advertising_interval: AdvertisingInterval,
1961
1962    /// Indicates the type of address being used in the advertising packets.
1963    ///
1964    /// If this is [`PrivateFallbackPublic`](OwnAddressType) or
1965    /// [`PrivateFallbackRandom`](OwnAddressType), the
1966    /// [`peer_address`](AdvertisingParameters::peer_address) parameter contains the peer's identity
1967    /// address and type. These parameters are used to locate the corresponding local IRK in the
1968    /// resolving list; this IRK is used to generate the own address used in the advertisement.
1969    pub own_address_type: OwnAddressType,
1970
1971    /// If directed advertising is performed, i.e. when `advertising_type` is set to
1972    /// [`ConnectableDirectedHighDutyCycle`](AdvertisingType::ConnectableDirectedHighDutyCycle) or
1973    /// [`ConnectableDirectedLowDutyCycle`](AdvertisingType::ConnectableDirectedLowDutyCycle), then
1974    /// `peer_address` shall be valid.
1975    ///
1976    /// If `own_address_type` is [`PrivateFallbackPublic`](OwnAddressType) or
1977    /// [`PrivateFallbackRandom`](OwnAddressType), the Controller generates
1978    /// the peer's Resolvable Private Address using the peer's IRK corresponding to the peer's
1979    /// Identity Address contained in `peer_address`.
1980    pub peer_address: crate::BdAddrType,
1981
1982    /// Bit field that indicates the advertising channels that shall be used when transmitting
1983    /// advertising packets. At least one channel bit shall be set in the bitfield.
1984    pub advertising_channel_map: Channels,
1985
1986    /// This parameter shall be ignored when directed advertising is enabled.
1987    pub advertising_filter_policy: AdvertisingFilterPolicy,
1988}
1989
1990impl AdvertisingParameters {
1991    fn copy_into_slice(&self, bytes: &mut [u8]) -> Result<(), Error> {
1992        assert_eq!(bytes.len(), 15);
1993
1994        if self.advertising_channel_map.is_empty() {
1995            return Err(Error::BadChannelMap(self.advertising_channel_map));
1996        }
1997
1998        self.advertising_interval.copy_into_slice(&mut bytes[0..5]);
1999        bytes[5] = self.own_address_type as u8;
2000        self.peer_address.copy_into_slice(&mut bytes[6..13]);
2001        bytes[13] = self.advertising_channel_map.bits();
2002        bytes[14] = self.advertising_filter_policy as u8;
2003
2004        Ok(())
2005    }
2006}
2007
2008/// Indicates the type of address being used in the advertising packets.
2009#[repr(u8)]
2010#[derive(Copy, Clone, Debug, PartialEq)]
2011#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2012pub enum OwnAddressType {
2013    /// Public Device Address (default)
2014    Public = 0x00,
2015    /// Random Device Address
2016    Random = 0x01,
2017    /// Controller generates Resolvable Private Address based on the local IRK from resolving
2018    /// list. If resolving list contains no matching entry, use public address.
2019    PrivateFallbackPublic = 0x02,
2020    /// Controller generates Resolvable Private Address based on the local IRK from resolving
2021    /// list. If resolving list contains no matching entry, use random address from
2022    /// [`le_set_random_address`](HostHci::le_set_random_address).
2023    PrivateFallbackRandom = 0x03,
2024}
2025
2026#[cfg(not(feature = "defmt"))]
2027bitflags::bitflags! {
2028    /// The advertising channels that shall be used when transmitting advertising packets.
2029    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2030    pub struct Channels : u8 {
2031        /// Channel 37 shall be used
2032        const CH_37 = 0b0000_0001;
2033        /// Channel 38 shall be used
2034        const CH_38 = 0b0000_0010;
2035        /// Channel 39 shall be used
2036        const CH_39 = 0b0000_0100;
2037    }
2038}
2039
2040#[cfg(feature = "defmt")]
2041defmt::bitflags! {
2042    /// The advertising channels that shall be used when transmitting advertising packets.
2043    pub struct Channels : u8 {
2044        /// Channel 37 shall be used
2045        const CH_37 = 0b0000_0001;
2046        /// Channel 38 shall be used
2047        const CH_38 = 0b0000_0010;
2048        /// Channel 39 shall be used
2049        const CH_39 = 0b0000_0100;
2050    }
2051}
2052
2053impl Default for Channels {
2054    fn default() -> Channels {
2055        Channels::all()
2056    }
2057}
2058
2059/// Possible filter policies used for undirected advertising.
2060///
2061/// See [`AdvertisingParameters`](crate::host::AdvertisingParameters).
2062#[repr(u8)]
2063#[derive(Copy, Clone, Debug, PartialEq)]
2064#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2065pub enum AdvertisingFilterPolicy {
2066    /// Process scan and connection requests from all devices (i.e., the White List is not in use)
2067    /// (default).
2068    AllowConnectionAndScan = 0x00,
2069    /// Process connection requests from all devices and only scan requests from devices that are in
2070    /// the White List.
2071    AllowConnectionWhiteListScan = 0x01,
2072    /// Process scan requests from all devices and only connection requests from devices that are in
2073    /// the White List.
2074    WhiteListConnectionAllowScan = 0x02,
2075    /// Process scan and connection requests only from devices in the White List.
2076    WhiteListConnectionAndScan = 0x03,
2077}
2078
2079/// Parameters for the [`le_set_scan_parameters`](HostHci::le_set_scan_parameters) command.
2080#[derive(Clone, Debug, PartialEq)]
2081pub struct ScanParameters {
2082    /// The type of scan to perform
2083    pub scan_type: ScanType,
2084
2085    /// Recommendation from the host on how frequently the controller should scan.  See the
2086    /// Bluetooth spec, Vol 6, Part B, Section 4.5.3.
2087    pub scan_window: ScanWindow,
2088
2089    /// Indicates the type of address being used in the scan request packets.
2090    pub own_address_type: OwnAddressType,
2091
2092    /// Indicates which advertising packets to accept.
2093    pub filter_policy: ScanFilterPolicy,
2094}
2095
2096impl ScanParameters {
2097    fn copy_into_slice(&self, bytes: &mut [u8]) {
2098        assert_eq!(bytes.len(), 7);
2099
2100        bytes[0] = self.scan_type as u8;
2101        self.scan_window.copy_into_slice(&mut bytes[1..5]);
2102        bytes[5] = self.own_address_type as u8;
2103        bytes[6] = self.filter_policy as u8;
2104    }
2105}
2106
2107/// Types of scan to perform.
2108///
2109/// See [`ScanParameters`] and [`le_set_scan_parameters`](HostHci::le_set_scan_parameters).
2110#[derive(Copy, Clone, Debug, PartialEq)]
2111#[repr(u8)]
2112#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2113pub enum ScanType {
2114    /// Passive Scanning. No scanning PDUs shall be sent (default).
2115    Passive = 0x00,
2116    /// Active scanning. Scanning PDUs may be sent.
2117    Active = 0x01,
2118}
2119
2120/// Which advertising packets to accept from a scan.
2121///
2122/// See [`ScanParameters`] and [`le_set_scan_parameters`](HostHci::le_set_scan_parameters).
2123#[derive(Copy, Clone, Debug, PartialEq)]
2124#[repr(u8)]
2125#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2126pub enum ScanFilterPolicy {
2127    /// Accept all advertising packets except directed advertising packets not addressed to this
2128    /// device (default).
2129    AcceptAll = 0x00,
2130    /// Accept only advertising packets from devices where the advertiser’s address is in the White
2131    /// List. Directed advertising packets which are not addressed to this device shall be ignored.
2132    WhiteList = 0x01,
2133    /// Accept all advertising packets except directed advertising packets where the initiator's
2134    /// identity address does not address this device.
2135    ///
2136    /// Note: Directed advertising packets where the initiator's address is a resolvable private
2137    /// address that cannot be resolved are also accepted.
2138    AddressedToThisDevice = 0x02,
2139    /// Accept all advertising packets except:
2140    /// - advertising packets where the advertiser's identity address is not in the White List; and
2141    /// - directed advertising packets where the initiator's identity addressdoes not address this
2142    ///   device
2143    ///
2144    /// Note: Directed advertising packets where the initiator's address is a resolvable private
2145    /// address that cannot be resolved are also accepted.
2146    WhiteListAddressedToThisDevice = 0x03,
2147}
2148
2149/// Parameters for the [`le_create_connection`](HostHci::le_create_connection`) event.
2150#[derive(Clone, Debug)]
2151pub struct ConnectionParameters {
2152    /// Recommendation from the host on how frequently the Controller should scan.
2153    pub scan_window: ScanWindow,
2154
2155    /// Determines whether the White List is used.  If the White List is not used, `peer_address`
2156    /// specifies the address type and address of the advertising device to connect to.
2157    pub initiator_filter_policy: ConnectionFilterPolicy,
2158
2159    /// Indicates the type and value of the address used in the connectable advertisement sent by
2160    /// the peer. The Host shall not use [`PublicIdentityAddress`](PeerAddrType) or
2161    /// [`RandomIdentityAddress`](PeerAddrType) (both introduced in v4.2) if both the Host and the
2162    /// Controller support the `le_set_privacy_mode` command (introduced in v5.0). If a Controller
2163    /// that supports the LE Set Privacy Mode command receives the
2164    /// [`le_create_connection`](HostHci::le_create_connection) command with `peer_address` set to
2165    /// either [`PublicIdentityAddress`](PeerAddrType) or [`RandomIdentityAddress`](PeerAddrType),
2166    /// it may use either device privacy mode or network privacy mode for that peer device.
2167    pub peer_address: PeerAddrType,
2168
2169    /// The type of address being used in the connection request packets.
2170    ///
2171    /// If this is [`Random`](OwnAddressType::Random) and the random address for the device has not
2172    /// been initialized, the Controller shall return the error code
2173    /// [`Status::InvalidParameters`].
2174    ///
2175    /// If this is [`PrivateFallbackRemote`](OwnAddressType), `initiator_filter_policy` is
2176    /// [`UseAddress`](ConnectionFilterPolicy::UseAddress), the controller's resolving list did not
2177    /// contain a matching entry, and the random address for the device has not been initialized,
2178    /// the Controller shall return the error code [`Status::InvalidParameters`].
2179    ///
2180    /// If this is set [`PrivateFallbackRandom`](`OwnAddressType`), `initiator_filter_policy` is
2181    /// [`WhiteList`](ConnectionFilterPolicy::WhiteList), and the random address for the device has
2182    /// not been initialized, the Controller shall return the error code
2183    /// [`Status::InvalidParameters`].
2184    pub own_address_type: OwnAddressType,
2185
2186    /// Defines the minimum and maximum allowed connection interval, latency, and supervision
2187    /// timeout.
2188    pub conn_interval: ConnectionInterval,
2189
2190    /// Informative parameters providing the Controller with the expected minimum and maximum length
2191    /// of the connection events.
2192    pub expected_connection_length: ExpectedConnectionLength,
2193}
2194
2195impl ConnectionParameters {
2196    fn copy_into_slice(&self, bytes: &mut [u8]) {
2197        assert_eq!(bytes.len(), 25);
2198
2199        self.scan_window.copy_into_slice(&mut bytes[0..4]);
2200        bytes[4] = self.initiator_filter_policy as u8;
2201        match self.initiator_filter_policy {
2202            ConnectionFilterPolicy::UseAddress => {
2203                self.peer_address.copy_into_slice(&mut bytes[5..12]);
2204            }
2205            ConnectionFilterPolicy::WhiteList => {
2206                bytes[5..12].copy_from_slice(&[0; 7]);
2207            }
2208        }
2209        bytes[12] = self.own_address_type as u8;
2210        self.conn_interval.copy_into_slice(&mut bytes[13..21]);
2211        self.expected_connection_length
2212            .copy_into_slice(&mut bytes[21..25]);
2213    }
2214}
2215
2216/// Possible values for the initiator filter policy in the
2217/// [`le_create_connection`](HostHci::le_create_connection) command.
2218#[derive(Copy, Clone, Debug)]
2219#[repr(u8)]
2220#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2221pub enum ConnectionFilterPolicy {
2222    /// White List is not used to determine which advertiser to connect to.  `peer_address` shall be
2223    /// used in the connection complete event.
2224    UseAddress = 0x00,
2225
2226    /// White List is used to determine which advertiser to connect to. `peer_address` shall be
2227    /// ignored in the connection complete event.
2228    WhiteList = 0x01,
2229}
2230
2231/// Possible values for the peer address in the [`le_create_connection`](HostHci::le_create_connection)
2232/// command.
2233#[derive(Copy, Clone, Debug)]
2234#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2235pub enum PeerAddrType {
2236    /// Public Device Address
2237    PublicDeviceAddress(crate::BdAddr),
2238    /// Random Device Address
2239    RandomDeviceAddress(crate::BdAddr),
2240    /// Public Identity Address (Corresponds to peer's Resolvable Private Address). This value shall
2241    /// only be used by the Host if either the Host or the Controller does not support the LE Set
2242    /// Privacy Mode command.
2243    PublicIdentityAddress(crate::BdAddr),
2244    /// Random (static) Identity Address (Corresponds to peer’s Resolvable Private Address). This
2245    /// value shall only be used by a Host if either the Host or the Controller does not support the
2246    /// LE Set Privacy Mode command.
2247    RandomIdentityAddress(crate::BdAddr),
2248}
2249
2250impl PeerAddrType {
2251    /// Serialize the peer address into the given byte buffer.
2252    ///
2253    /// # Panics
2254    ///
2255    /// `bytes` must be 7 bytes long.
2256    pub fn copy_into_slice(&self, bytes: &mut [u8]) {
2257        assert_eq!(bytes.len(), 7);
2258        match *self {
2259            PeerAddrType::PublicDeviceAddress(bd_addr) => {
2260                bytes[0] = 0x00;
2261                bytes[1..7].copy_from_slice(&bd_addr.0);
2262            }
2263            PeerAddrType::RandomDeviceAddress(bd_addr) => {
2264                bytes[0] = 0x01;
2265                bytes[1..7].copy_from_slice(&bd_addr.0);
2266            }
2267            PeerAddrType::PublicIdentityAddress(bd_addr) => {
2268                bytes[0] = 0x02;
2269                bytes[1..7].copy_from_slice(&bd_addr.0);
2270            }
2271            PeerAddrType::RandomIdentityAddress(bd_addr) => {
2272                bytes[0] = 0x03;
2273                bytes[1..7].copy_from_slice(&bd_addr.0);
2274            }
2275        }
2276    }
2277}
2278
2279/// Parameters for the [`le_connection_update`](HostHci::le_connection_update) command.
2280///
2281/// See the Bluetooth spec, Vol 2, Part E, Section 7.8.18.
2282pub struct ConnectionUpdateParameters {
2283    /// Handle for identifying a connection.
2284    pub conn_handle: ConnectionHandle,
2285
2286    /// Defines the connection interval, latency, and supervision timeout.
2287    pub conn_interval: ConnectionInterval,
2288
2289    /// Information parameters providing the Controller with a hint about the expected minimum and
2290    /// maximum length of the connection events.
2291    pub expected_connection_length: ExpectedConnectionLength,
2292}
2293
2294impl ConnectionUpdateParameters {
2295    fn copy_into_slice(&self, bytes: &mut [u8]) {
2296        assert_eq!(bytes.len(), 14);
2297
2298        LittleEndian::write_u16(&mut bytes[0..], self.conn_handle.0);
2299        self.conn_interval.copy_into_slice(&mut bytes[2..10]);
2300        self.expected_connection_length
2301            .copy_into_slice(&mut bytes[10..14]);
2302    }
2303}
2304
2305/// Parameters for the [`le_encrypt`](HostHci::le_encrypt) command.
2306#[derive(Clone, Debug)]
2307pub struct AesParameters {
2308    /// Key for the encryption of the data given in the command.
2309    ///
2310    /// The most significant (last) octet of the key corresponds to `key[0]` using the notation
2311    /// specified in FIPS 197.
2312    pub key: EncryptionKey,
2313
2314    /// Data block that is requested to be encrypted.
2315    ///
2316    /// The most significant (last) octet of the PlainText_Data corresponds to `in[0]` using the
2317    /// notation specified in FIPS 197.
2318    pub plaintext_data: PlaintextBlock,
2319}
2320
2321/// Newtype for the encryption key.
2322///
2323/// See [`AesParameters`]
2324#[derive(Clone, PartialEq)]
2325#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2326pub struct EncryptionKey(pub [u8; 16]);
2327
2328impl Debug for EncryptionKey {
2329    fn fmt(&self, f: &mut Formatter) -> FmtResult {
2330        write!(f, "AES-128 Key ({:X?})", self.0)
2331    }
2332}
2333
2334/// Newtype for the plaintext data.
2335///
2336/// See [`AesParameters`].
2337#[derive(Clone)]
2338pub struct PlaintextBlock(pub [u8; 16]);
2339
2340impl Debug for PlaintextBlock {
2341    fn fmt(&self, f: &mut Formatter) -> FmtResult {
2342        write!(f, "AES-128 Plaintext (REDACTED)")
2343    }
2344}
2345
2346/// Parameters for the [`le_start_encryption`](HostHci::le_start_encryption) command.
2347pub struct EncryptionParameters {
2348    /// ID for the connection.
2349    pub conn_handle: ConnectionHandle,
2350
2351    /// Random value distrubuted by the peripheral during pairing
2352    pub random_number: u64,
2353
2354    /// Encrypted diversifier distrubuted by the peripheral during pairing
2355    pub encrypted_diversifier: u16,
2356
2357    /// Encryption key, distributed by the host.
2358    pub long_term_key: EncryptionKey,
2359}
2360
2361/// Possible values of the `payload` parameter for the
2362/// [`le_transmitter_test`](HostHci::le_transmitter_test) command.
2363#[derive(Copy, Clone, Debug)]
2364#[repr(u8)]
2365#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2366pub enum TestPacketPayload {
2367    /// Pseudo-Random bit sequence 9
2368    PrbS9 = 0x00,
2369    /// Pattern of alternating bits `11110000
2370    Nibbles10 = 0x01,
2371    /// Pattern of alternating bits `10101010'
2372    Bits10 = 0x02,
2373    /// Pseudo-Random bit sequence 15
2374    PrbS15 = 0x03,
2375    /// Pattern of All `1' bits
2376    All1 = 0x04,
2377    /// Pattern of All `0' bits
2378    All0 = 0x05,
2379    /// Pattern of alternating bits `00001111
2380    Nibbles01 = 0x06,
2381    /// Pattern of alternating bits `0101'
2382    Bits01 = 0x07,
2383}