Skip to main content

device/
bluetooth.rs

1//! Bluetooth Low Energy controls for `/devices/bluetooth/hci0`.
2//!
3//! An opening owns its operations and event stream. A command returns when
4//! accepted. Read its completion event before submitting the next command.
5//! Each read returns one fixed-size [`Event`]. Use the VFS readiness API to
6//! wait for events, or use a blocking read.
7
8use file_system::{ControlCommand, IoErrorKind, define_command};
9
10define_command!(
11    GET_CAPABILITIES,
12    Read,
13    crate::kind::BLUETOOTH,
14    0,
15    (),
16    Capabilities
17);
18define_command!(GET_STATE, Read, crate::kind::BLUETOOTH, 1, (), State);
19define_command!(
20    START_SCAN,
21    Write,
22    crate::kind::BLUETOOTH,
23    2,
24    ScanConfiguration,
25    ()
26);
27define_command!(STOP_SCAN, Write, crate::kind::BLUETOOTH, 3, (), ());
28define_command!(
29    CONNECT,
30    Write,
31    crate::kind::BLUETOOTH,
32    4,
33    ConnectionRequest,
34    ()
35);
36define_command!(
37    DISCONNECT,
38    Write,
39    crate::kind::BLUETOOTH,
40    5,
41    ConnectionHandle,
42    ()
43);
44define_command!(
45    DISCOVER_SERVICES,
46    Write,
47    crate::kind::BLUETOOTH,
48    6,
49    ConnectionHandle,
50    ()
51);
52define_command!(
53    DISCOVER_CHARACTERISTICS,
54    Write,
55    crate::kind::BLUETOOTH,
56    7,
57    AttributeRequest,
58    ()
59);
60define_command!(
61    DISCOVER_DESCRIPTORS,
62    Write,
63    crate::kind::BLUETOOTH,
64    8,
65    AttributeRequest,
66    ()
67);
68define_command!(
69    READ_ATTRIBUTE,
70    Write,
71    crate::kind::BLUETOOTH,
72    9,
73    AttributeRequest,
74    ()
75);
76define_command!(
77    WRITE_ATTRIBUTE,
78    Write,
79    crate::kind::BLUETOOTH,
80    10,
81    WriteRequest,
82    ()
83);
84define_command!(
85    SET_NOTIFICATIONS,
86    Write,
87    crate::kind::BLUETOOTH,
88    11,
89    NotificationRequest,
90    ()
91);
92define_command!(
93    START_ADVERTISING,
94    Write,
95    crate::kind::BLUETOOTH,
96    12,
97    AdvertisingData,
98    ()
99);
100define_command!(STOP_ADVERTISING, Write, crate::kind::BLUETOOTH, 13, (), ());
101
102file_system::plain_data! {
103    #[repr(C)]
104    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
105    pub struct Capabilities {
106        /// Bit set of supported operations.
107        pub features: u16,
108        pub connection_limit: u8,
109        pub value_capacity: u8,
110    }
111}
112
113impl Capabilities {
114    pub const CENTRAL: u16 = 1;
115    pub const OBSERVER: u16 = 2;
116    pub const BROADCASTER: u16 = 4;
117    pub const GATT_CLIENT: u16 = 8;
118}
119
120file_system::plain_data! {
121    #[repr(transparent)]
122    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123    pub struct ConnectionHandle(pub u32);
124}
125
126impl ConnectionHandle {
127    pub const NONE: Self = Self(0);
128}
129
130file_system::plain_data! {
131    #[repr(C)]
132    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
133    pub struct State {
134        pub connection: ConnectionHandle,
135        pub scanning: u8,
136        pub advertising: u8,
137        pub reserved: [u8; 2],
138    }
139}
140
141file_system::plain_data! {
142    #[repr(C)]
143    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
144    pub struct Address {
145        /// Address bytes in HCI order, least significant byte first.
146        pub bytes: [u8; 6],
147        pub kind: u8,
148    }
149}
150
151impl Address {
152    pub const PUBLIC: u8 = 0;
153    pub const RANDOM: u8 = 1;
154}
155
156file_system::plain_data! {
157    #[repr(C)]
158    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
159    pub struct ScanConfiguration {
160        /// One for active scanning. Zero for passive scanning.
161        pub active: u8,
162        /// One to request duplicate filtering. Zero to receive duplicates.
163        pub filter_duplicates: u8,
164    }
165}
166
167file_system::plain_data! {
168    #[repr(C)]
169    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
170    pub struct ConnectionRequest {
171        /// Time limit in milliseconds. This must be greater than zero.
172        pub timeout_milliseconds: u32,
173        pub peer: Address,
174        pub reserved: u8,
175    }
176}
177
178file_system::plain_data! {
179    #[repr(C)]
180    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
181    pub struct AdvertisingData {
182        pub length: u8,
183        pub bytes: [u8; 31],
184    }
185}
186
187impl AdvertisingData {
188    pub fn as_slice(&self) -> Option<&[u8]> {
189        self.bytes.get(..usize::from(self.length))
190    }
191}
192
193file_system::plain_data! {
194    #[repr(C)]
195    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
196    pub struct ScanResult {
197        pub peer: Address,
198        pub rssi: i8,
199        pub data: AdvertisingData,
200        /// The HCI legacy advertising event type.
201        pub event_type: u8,
202    }
203}
204
205file_system::plain_data! {
206    #[repr(C)]
207    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
208    pub struct Uuid {
209        /// UUID bytes in Bluetooth order, least significant byte first.
210        pub bytes: [u8; 16],
211        /// Number of valid bytes: 2, 4 or 16.
212        pub length: u8,
213    }
214}
215
216impl Uuid {
217    pub const fn short(value: u16) -> Self {
218        let [low, high] = value.to_le_bytes();
219        Self {
220            bytes: [low, high, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
221            length: 2,
222        }
223    }
224}
225
226file_system::plain_data! {
227    #[repr(C)]
228    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
229    pub struct Service {
230        pub first_handle: u16,
231        pub last_handle: u16,
232        pub uuid: Uuid,
233        pub reserved: u8,
234    }
235}
236
237file_system::plain_data! {
238    #[repr(C)]
239    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
240    pub struct Characteristic {
241        pub value_handle: u16,
242        pub last_handle: u16,
243        pub configuration_handle: u16,
244        pub properties: u8,
245        pub uuid: Uuid,
246    }
247}
248
249file_system::plain_data! {
250    #[repr(C)]
251    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
252    pub struct Descriptor {
253        pub handle: u16,
254        pub uuid: Uuid,
255        pub reserved: u8,
256    }
257}
258
259file_system::plain_data! {
260    #[repr(C)]
261    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
262    pub struct AttributeRequest {
263        pub connection: ConnectionHandle,
264        /// The service's first handle, characteristic value handle or attribute handle.
265        pub handle: u16,
266        pub reserved: u16,
267    }
268}
269
270pub const VALUE_CAPACITY: usize = 41;
271
272file_system::plain_data! {
273    #[repr(C)]
274    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
275    pub struct AttributeValue {
276        pub handle: u16,
277        pub length: u8,
278        pub bytes: [u8; VALUE_CAPACITY],
279    }
280}
281
282impl Default for AttributeValue {
283    fn default() -> Self {
284        Self {
285            handle: 0,
286            length: 0,
287            bytes: [0; VALUE_CAPACITY],
288        }
289    }
290}
291
292impl AttributeValue {
293    pub fn as_slice(&self) -> Option<&[u8]> {
294        self.bytes.get(..usize::from(self.length))
295    }
296}
297
298file_system::plain_data! {
299    #[repr(C)]
300    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
301    pub struct WriteRequest {
302        pub connection: ConnectionHandle,
303        pub value: AttributeValue,
304    }
305}
306
307file_system::plain_data! {
308    #[repr(C)]
309    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
310    pub struct NotificationRequest {
311        pub characteristic: AttributeRequest,
312        /// One to subscribe to notifications. Zero to unsubscribe.
313        pub enabled: u8,
314        pub reserved: [u8; 3],
315    }
316}
317
318const EVENT_PAYLOAD_SIZE: usize = size_of::<AttributeValue>();
319
320file_system::plain_data! {
321    #[repr(C)]
322    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
323    pub struct Event {
324        pub connection: ConnectionHandle,
325        /// For a completion, the stable I/O error ID. Zero means success.
326        pub status: u16,
327        pub kind: u8,
328        /// The command number for a completion or a discovery result.
329        pub command: u8,
330        pub length: u8,
331        pub reserved: [u8; 3],
332        payload: [u8; EVENT_PAYLOAD_SIZE],
333    }
334}
335
336impl Default for Event {
337    fn default() -> Self {
338        Self::new(0, 0, ConnectionHandle::NONE)
339    }
340}
341
342impl Event {
343    /// No payload.
344    pub const COMPLETION: u8 = 1;
345    /// [`ScanResult`] payload.
346    pub const SCAN_RESULT: u8 = 2;
347    /// [`Service`] payload.
348    pub const SERVICE: u8 = 3;
349    /// [`Characteristic`] payload.
350    pub const CHARACTERISTIC: u8 = 4;
351    /// [`Descriptor`] payload.
352    pub const DESCRIPTOR: u8 = 5;
353    /// [`AttributeValue`] payload.
354    pub const VALUE: u8 = 6;
355    /// [`AttributeValue`] payload.
356    pub const NOTIFICATION: u8 = 7;
357    /// Disconnect reason, as an HCI error byte.
358    pub const DISCONNECTED: u8 = 8;
359    /// Saturating count of dropped events, as a `u32`.
360    pub const OVERFLOW: u8 = 9;
361
362    pub const fn new(kind: u8, command: u8, connection: ConnectionHandle) -> Self {
363        Self {
364            connection,
365            status: 0,
366            kind,
367            command,
368            length: 0,
369            reserved: [0; 3],
370            payload: [0; EVENT_PAYLOAD_SIZE],
371        }
372    }
373
374    pub fn with_payload<T: file_system::PlainData>(mut self, mut payload: T) -> Self {
375        const { assert!(size_of::<T>() <= EVENT_PAYLOAD_SIZE) };
376        let bytes = shared::AnyByLayout::from_mutable(&mut payload).as_mutable_bytes();
377        self.payload[..bytes.len()].copy_from_slice(bytes);
378        self.length = bytes.len() as u8;
379        self
380    }
381
382    /// Decode a payload after checking the event kind and length.
383    pub fn payload<T: file_system::PlainData + Default>(&self, kind: u8) -> Option<T> {
384        let bytes = self.payload.get(..usize::from(self.length))?;
385        if self.kind != kind || bytes.len() != size_of::<T>() {
386            return None;
387        }
388        let mut value = T::default();
389        shared::AnyByLayout::from_mutable(&mut value)
390            .as_mutable_bytes()
391            .copy_from_slice(bytes);
392        Some(value)
393    }
394
395    pub fn as_mutable_bytes(&mut self) -> &mut [u8] {
396        shared::AnyByLayout::from_mutable(self).as_mutable_bytes()
397    }
398
399    pub fn completion(&self) -> Result<(), IoErrorKind> {
400        match (self.kind, self.status) {
401            (Self::COMPLETION, 0) => Ok(()),
402            (Self::COMPLETION, status) => {
403                Err(IoErrorKind::try_from(status).unwrap_or(IoErrorKind::InvalidData))
404            }
405            _ => Err(IoErrorKind::InvalidData),
406        }
407    }
408}