bt-hci 0.8.1

Bluetooth HCI data types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Parameter types for HCI command and event packets [📖](https://www.bluetooth.com/wp-content/uploads/Files/Specification/HTML/Core-54/out/en/host-controller-interface/host-controller-interface-functional-specification.html#UUID-8af7a4d8-7a08-0895-b041-fdf9e27d6508)

use crate::{AsHciBytes, ByteAlignedValue, FixedSizeValue, FromHciBytes, FromHciBytesError, WriteHci};

mod classic;
mod cmd_mask;
mod event_masks;
mod feature_masks;
mod le;
mod macros;
mod primitives;
mod status;

pub use classic::*;
pub use cmd_mask::*;
pub use event_masks::*;
pub use feature_masks::*;
pub use le::*;
pub(crate) use macros::{param, param_slice};
pub use status::*;

/// A special parameter which takes all remaining bytes in the buffer
#[repr(transparent)]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct RemainingBytes<'a>(&'a [u8]);

impl core::ops::Deref for RemainingBytes<'_> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.0
    }
}

impl WriteHci for RemainingBytes<'_> {
    #[inline(always)]
    fn size(&self) -> usize {
        self.0.len()
    }

    #[inline(always)]
    fn write_hci<W: embedded_io::Write>(&self, mut writer: W) -> Result<(), W::Error> {
        writer.write_all(self.0)
    }

    #[inline(always)]
    async fn write_hci_async<W: embedded_io_async::Write>(&self, mut writer: W) -> Result<(), W::Error> {
        writer.write_all(self.0).await
    }
}

impl AsHciBytes for RemainingBytes<'_> {
    fn as_hci_bytes(&self) -> &[u8] {
        self.0
    }
}

impl<'a> FromHciBytes<'a> for RemainingBytes<'a> {
    fn from_hci_bytes(data: &'a [u8]) -> Result<(Self, &'a [u8]), FromHciBytesError> {
        Ok((RemainingBytes(data), &[]))
    }
}

impl<'a> RemainingBytes<'a> {
    pub(crate) fn into_inner(self) -> &'a [u8] {
        self.0
    }
}

param!(struct BdAddr([u8; 6]));

impl BdAddr {
    /// Create a new instance.
    pub fn new(val: [u8; 6]) -> Self {
        Self(val)
    }

    /// Get the byte representation.
    pub fn raw(&self) -> &[u8] {
        &self.0[..]
    }
}

unsafe impl ByteAlignedValue for BdAddr {}

impl<'de> crate::FromHciBytes<'de> for &'de BdAddr {
    #[inline(always)]
    fn from_hci_bytes(data: &'de [u8]) -> Result<(Self, &'de [u8]), crate::FromHciBytesError> {
        <BdAddr as crate::ByteAlignedValue>::ref_from_hci_bytes(data)
    }
}

param!(struct ConnHandle(u16));

impl ConnHandle {
    /// Create a new instance.
    pub fn new(val: u16) -> Self {
        assert!(val <= 0xeff);
        Self(val)
    }

    /// Get the underlying representation.
    pub fn raw(&self) -> u16 {
        self.0
    }
}

/// An 8-bit duration. The `US` generic parameter indicates the timebase in µs.
#[repr(transparent)]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DurationU8<const US: u32 = 125>(u8);

unsafe impl<const US: u32> FixedSizeValue for DurationU8<US> {
    #[inline(always)]
    fn is_valid(_data: &[u8]) -> bool {
        true
    }
}

impl<const US: u32> DurationU8<US> {
    #[inline(always)]
    /// Create a new instance from raw value.
    pub const fn from_u8(val: u8) -> Self {
        Self(val)
    }

    /// Create an instance from microseconds.
    #[inline(always)]
    pub fn from_micros(val: u64) -> Self {
        Self::from_u8(unwrap!((val / u64::from(US)).try_into()))
    }

    /// Create an instance from milliseconds.
    #[inline(always)]
    pub fn from_millis(val: u32) -> Self {
        Self::from_micros(u64::from(val) * 1000)
    }

    /// Create an instance from seconds.
    #[inline(always)]
    pub fn from_secs(val: u32) -> Self {
        Self::from_micros(u64::from(val) * 1_000_000)
    }

    /// Get the underlying representation.
    #[inline(always)]
    pub fn as_u8(&self) -> u8 {
        self.0
    }

    /// Get value as microseconds.
    #[inline(always)]
    pub fn as_micros(&self) -> u64 {
        u64::from(self.as_u8()) * u64::from(US)
    }

    /// Get value as milliseconds.
    #[inline(always)]
    pub fn as_millis(&self) -> u32 {
        (self.as_micros() / 1000) as u32
    }

    /// Get value as seconds.
    #[inline(always)]
    pub fn as_secs(&self) -> u32 {
        (self.as_micros() / 1_000_000) as u32
    }
}

#[cfg(feature = "embassy-time")]
impl<const US: u32> From<embassy_time::Duration> for DurationU8<US> {
    fn from(duration: embassy_time::Duration) -> Self {
        Self::from_micros(duration.as_micros())
    }
}

/// A 16-bit duration. The `US` generic parameter indicates the timebase in µs.
#[repr(transparent)]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Duration<const US: u32 = 625>(u16);

unsafe impl<const US: u32> FixedSizeValue for Duration<US> {
    #[inline(always)]
    fn is_valid(_data: &[u8]) -> bool {
        true
    }
}

impl<const US: u32> Duration<US> {
    #[inline(always)]
    /// Create a new instance from raw value.
    pub const fn from_u16(val: u16) -> Self {
        Self(val)
    }

    /// Create an instance from microseconds.
    #[inline(always)]
    pub fn from_micros(val: u64) -> Self {
        Self::from_u16(unwrap!((val / u64::from(US)).try_into()))
    }

    /// Create an instance from milliseconds.
    #[inline(always)]
    pub fn from_millis(val: u32) -> Self {
        Self::from_micros(u64::from(val) * 1000)
    }

    /// Create an instance from seconds.
    #[inline(always)]
    pub fn from_secs(val: u32) -> Self {
        Self::from_micros(u64::from(val) * 1_000_000)
    }

    /// Get the underlying representation.
    #[inline(always)]
    pub fn as_u16(&self) -> u16 {
        self.0
    }

    /// Get value as microseconds.
    #[inline(always)]
    pub fn as_micros(&self) -> u64 {
        u64::from(self.as_u16()) * u64::from(US)
    }

    /// Get value as milliseconds.
    #[inline(always)]
    pub fn as_millis(&self) -> u32 {
        unwrap!((self.as_micros() / 1000).try_into())
    }

    /// Get value as seconds.
    #[inline(always)]
    pub fn as_secs(&self) -> u32 {
        // (u16::MAX * u32::MAX / 1_000_000) < u32::MAX so this is safe
        (self.as_micros() / 1_000_000) as u32
    }
}

#[cfg(feature = "embassy-time")]
impl<const US: u32> From<embassy_time::Duration> for Duration<US> {
    fn from(duration: embassy_time::Duration) -> Self {
        Self::from_micros(duration.as_micros())
    }
}

/// A 24-bit isochronous duration (in microseconds)
#[repr(transparent)]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ExtDuration<const US: u16 = 1>([u8; 3]);

unsafe impl<const US: u16> FixedSizeValue for ExtDuration<US> {
    #[inline(always)]
    fn is_valid(_data: &[u8]) -> bool {
        true
    }
}

unsafe impl<const US: u16> ByteAlignedValue for ExtDuration<US> {}

impl<'de, const US: u16> FromHciBytes<'de> for &'de ExtDuration<US> {
    #[inline(always)]
    fn from_hci_bytes(data: &'de [u8]) -> Result<(Self, &'de [u8]), crate::FromHciBytesError> {
        <ExtDuration<US> as crate::ByteAlignedValue>::ref_from_hci_bytes(data)
    }
}

impl<const US: u16> ExtDuration<US> {
    /// Create a new instance from raw value.
    #[inline(always)]
    pub fn from_u32(val: u32) -> Self {
        assert!(val < (1 << 24));
        Self(*unwrap!(val.to_le_bytes().first_chunk()))
    }

    /// Create an instance from microseconds.
    #[inline(always)]
    pub fn from_micros(val: u64) -> Self {
        Self::from_u32(unwrap!((val / u64::from(US)).try_into()))
    }

    /// Create an instance from milliseconds.
    #[inline(always)]
    pub fn from_millis(val: u32) -> Self {
        Self::from_micros(u64::from(val) * 1000)
    }

    /// Create an instance from seconds.
    #[inline(always)]
    pub fn from_secs(val: u32) -> Self {
        Self::from_micros(u64::from(val) * 1_000_000)
    }

    /// Get value as microseconds.
    #[inline(always)]
    pub fn as_micros(&self) -> u64 {
        u64::from_le_bytes([self.0[0], self.0[1], self.0[2], 0, 0, 0, 0, 0]) * u64::from(US)
    }

    /// Get value as milliseconds.
    #[inline(always)]
    pub fn as_millis(&self) -> u32 {
        // ((1 << 24 - 1) * u16::MAX / 1_000) < u32::MAX so this is safe
        (self.as_micros() / 1000) as u32
    }

    /// Get value as seconds.
    #[inline(always)]
    pub fn as_secs(&self) -> u32 {
        // ((1 << 24 - 1) * u16::MAX / 1_000_000) < u32::MAX so this is safe
        (self.as_micros() / 1_000_000) as u32
    }
}

#[cfg(feature = "embassy-time")]
impl<const US: u16> From<embassy_time::Duration> for ExtDuration<US> {
    fn from(duration: embassy_time::Duration) -> Self {
        Self::from_micros(duration.as_micros())
    }
}

param!(
    enum DisconnectReason {
        AuthenticationFailure = 0x05,
        RemoteUserTerminatedConn = 0x13,
        RemoteDeviceTerminatedConnLowResources = 0x14,
        RemoteDeviceTerminatedConnPowerOff = 0x15,
        UnsupportedRemoteFeature = 0x1A,
        PairingWithUnitKeyNotSupported = 0x29,
        UnacceptableConnParameters = 0x3b,
    }
);

param!(
    enum RemoteConnectionParamsRejectReason {
        UnacceptableConnParameters = 0x3b,
    }
);

param! {
    #[derive(Default)]
    enum PowerLevelKind {
        #[default]
        Current = 0,
        Maximum = 1,
    }
}

param! {
    #[derive(Default)]
    enum ControllerToHostFlowControl {
        #[default]
        Off = 0,
        AclOnSyncOff = 1,
        AclOffSyncOn = 2,
        BothOn = 3,
    }
}

param!(struct CoreSpecificationVersion(u8));

#[allow(missing_docs)]
impl CoreSpecificationVersion {
    pub const VERSION_1_0B: CoreSpecificationVersion = CoreSpecificationVersion(0x00);
    pub const VERSION_1_1: CoreSpecificationVersion = CoreSpecificationVersion(0x01);
    pub const VERSION_1_2: CoreSpecificationVersion = CoreSpecificationVersion(0x02);
    pub const VERSION_2_0_EDR: CoreSpecificationVersion = CoreSpecificationVersion(0x03);
    pub const VERSION_2_1_EDR: CoreSpecificationVersion = CoreSpecificationVersion(0x04);
    pub const VERSION_3_0_HS: CoreSpecificationVersion = CoreSpecificationVersion(0x05);
    pub const VERSION_4_0: CoreSpecificationVersion = CoreSpecificationVersion(0x06);
    pub const VERSION_4_1: CoreSpecificationVersion = CoreSpecificationVersion(0x07);
    pub const VERSION_4_2: CoreSpecificationVersion = CoreSpecificationVersion(0x08);
    pub const VERSION_5_0: CoreSpecificationVersion = CoreSpecificationVersion(0x09);
    pub const VERSION_5_1: CoreSpecificationVersion = CoreSpecificationVersion(0x0A);
    pub const VERSION_5_2: CoreSpecificationVersion = CoreSpecificationVersion(0x0B);
    pub const VERSION_5_3: CoreSpecificationVersion = CoreSpecificationVersion(0x0C);
    pub const VERSION_5_4: CoreSpecificationVersion = CoreSpecificationVersion(0x0D);
}

unsafe impl ByteAlignedValue for CoreSpecificationVersion {}

impl<'de> crate::FromHciBytes<'de> for &'de CoreSpecificationVersion {
    #[inline(always)]
    fn from_hci_bytes(data: &'de [u8]) -> Result<(Self, &'de [u8]), crate::FromHciBytesError> {
        <CoreSpecificationVersion as crate::ByteAlignedValue>::ref_from_hci_bytes(data)
    }
}

param! {
    #[derive(Default)]
    enum LinkType {
        #[default]
        SyncData = 0,
        AclData = 1,
        IsoData = 2,
    }
}

param_slice! {
    [ConnHandleCompletedPackets; 4] {
        handle[0]: ConnHandle,
        num_completed_packets[2]: u16,
    }
}

impl ConnHandleCompletedPackets {
    /// Create a new instance.
    pub fn new(handle: ConnHandle, num_completed_packets: u16) -> Self {
        let mut dest = [0; 4];
        handle.write_hci(&mut dest[0..2]).unwrap();
        num_completed_packets.write_hci(&mut dest[2..4]).unwrap();
        Self(dest)
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "serde")]
    use postcard;

    use super::*;

    #[test]
    fn test_encode_decode_conn_handle_completed_packets() {
        let completed = ConnHandleCompletedPackets::new(ConnHandle::new(42), 2334);

        assert_eq!(completed.handle().unwrap(), ConnHandle::new(42));
        assert_eq!(completed.num_completed_packets().unwrap(), 2334);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serialize_bdaddr() {
        let bytes = [0x01, 0xaa, 0x55, 0x04, 0x05, 0xfe];

        let address = BdAddr::new(bytes);

        let mut buffer = [0u8; 32];
        let vykort = postcard::to_slice(&address, &mut buffer).unwrap();

        assert_eq!(vykort, &bytes);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_deserialize_bdaddr() {
        let bytes = [0xff, 0x5a, 0xa5, 0x00, 0x05, 0xfe];

        let address = postcard::from_bytes::<BdAddr>(&bytes).unwrap();

        let expected = BdAddr::new(bytes);

        assert_eq!(address, expected);
    }
}