Skip to main content

bluetooth/
node.rs

1use alloc::boxed::Box;
2use core::cell::RefCell;
3use core::task::{Context as TaskContext, Poll, Waker};
4
5use file_system::{
6    BaseOperations, CharacterDevice, Context, ControlCommand, ControlCommandIdentifier,
7    IoErrorKind, MountOperations, Operation, ReadyEvents, Result, Size, notify_readiness, ready,
8};
9use heapless::Deque;
10use shared::AnyByLayout;
11use synchronization::{
12    blocking_mutex::{Mutex, raw::CriticalSectionRawMutex},
13    signal::Signal,
14};
15
16use crate::*;
17
18const EVENT_CAPACITY: usize = 16;
19type Lock = CriticalSectionRawMutex;
20
21#[derive(Clone, Copy)]
22pub(crate) enum Request {
23    StartScan(ScanConfiguration),
24    StopScan,
25    StartAdvertising(AdvertisingData),
26    StopAdvertising,
27    Connect(ConnectionRequest),
28    Disconnect,
29    Services,
30    Characteristics(u16),
31    Descriptors(u16),
32    Read(u16),
33    Write(AttributeValue),
34    Notifications(NotificationRequest),
35}
36
37#[derive(Clone, Copy, PartialEq, Eq)]
38enum Session {
39    Idle,
40    Open,
41    Closing,
42}
43
44struct Opening;
45
46struct Inner {
47    online: bool,
48    session: Session,
49    state: State,
50    next_handle: u32,
51    work: Option<(u8, Request)>,
52    busy: bool,
53    events: Deque<Event, EVENT_CAPACITY>,
54    dropped: u32,
55    reader: Option<Waker>,
56}
57
58/// The upper half of the Bluetooth device. Start its runner on a local task
59/// before opening the device. Each successful opening owns the controller
60/// until its work has been cancelled and its connection released.
61pub struct BluetoothDevice {
62    inner: Mutex<Lock, RefCell<Inner>>,
63    work: Signal<Lock, ()>,
64    closed: Signal<Lock, ()>,
65}
66
67impl Default for BluetoothDevice {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl BluetoothDevice {
74    pub const fn new() -> Self {
75        Self {
76            inner: Mutex::new(RefCell::new(Inner {
77                online: false,
78                session: Session::Idle,
79                state: State {
80                    connection: ConnectionHandle::NONE,
81                    scanning: 0,
82                    advertising: 0,
83                    reserved: [0; 2],
84                },
85                next_handle: 0,
86                work: None,
87                busy: false,
88                events: Deque::new(),
89                dropped: 0,
90                reader: None,
91            })),
92            work: Signal::new(),
93            closed: Signal::new(),
94        }
95    }
96
97    fn with<T>(&self, operation: impl FnOnce(&mut Inner) -> T) -> T {
98        self.inner.lock(|inner| operation(&mut inner.borrow_mut()))
99    }
100
101    pub(crate) fn begin_run(&self) -> Result<Running<'_>> {
102        self.with(|inner| {
103            if inner.online || inner.session != Session::Idle {
104                return Err(IoErrorKind::ResourceBusy);
105            }
106            self.closed.reset();
107            self.work.reset();
108            inner.online = true;
109            Ok(Running(self))
110        })
111    }
112
113    pub(crate) async fn wait_open(&self) {
114        while self.with(|inner| inner.session == Session::Idle) {
115            self.work.wait().await;
116        }
117    }
118
119    pub(crate) async fn wait_closed(&self) {
120        self.closed.wait().await;
121    }
122
123    pub(crate) fn finish_close(&self) {
124        self.with(|inner| {
125            inner.reset_session();
126            inner.session = Session::Idle;
127        });
128    }
129
130    pub(crate) async fn next_request(&self) -> (u8, Request) {
131        loop {
132            if let Some(request) = self.with(|inner| inner.work.take()) {
133                return request;
134            }
135            self.work.wait().await;
136        }
137    }
138
139    pub(crate) fn set_scanning(&self, scanning: bool) {
140        self.with(|inner| inner.state.scanning = u8::from(scanning));
141    }
142
143    pub(crate) fn set_advertising(&self, advertising: bool) {
144        self.with(|inner| inner.state.advertising = u8::from(advertising));
145    }
146
147    pub(crate) fn connected(&self) -> ConnectionHandle {
148        self.with(|inner| {
149            inner.next_handle = inner.next_handle.wrapping_add(1).max(1);
150            let handle = ConnectionHandle(inner.next_handle);
151            inner.state.connection = handle;
152            handle
153        })
154    }
155
156    pub(crate) fn disconnected(&self) {
157        self.with(|inner| inner.state.connection = ConnectionHandle::NONE);
158    }
159
160    pub(crate) fn complete(&self, command: u8, handle: ConnectionHandle, result: Result<()>) {
161        let mut event = Event::new(Event::COMPLETION, command, handle);
162        event.status = result.err().map_or(0, IoErrorKind::id);
163        self.emit(event);
164    }
165
166    pub(crate) fn emit(&self, event: Event) {
167        let (changed, reader) = self.with(|inner| {
168            if inner.session != Session::Open
169                || (event.kind == Event::SCAN_RESULT && inner.state.scanning == 0)
170            {
171                return (false, None);
172            }
173
174            // Keep one slot for the accepted command's completion. The next
175            // command cannot enter until the opening reads that completion.
176            let limit = if event.kind != Event::COMPLETION {
177                EVENT_CAPACITY - 1
178            } else {
179                EVENT_CAPACITY
180            };
181            if inner.events.len() >= limit {
182                inner.dropped = inner.dropped.saturating_add(1);
183            } else {
184                let _ = inner.events.push_back(event);
185            }
186            (true, inner.reader.take())
187        });
188        if let Some(reader) = reader {
189            reader.wake();
190        }
191        if changed {
192            notify_readiness();
193        }
194    }
195
196    fn submit(
197        &self,
198        command: u8,
199        request: Request,
200        handle: Option<ConnectionHandle>,
201    ) -> Result<()> {
202        self.with(|inner| {
203            if !inner.online {
204                return Err(IoErrorKind::DeviceUnavailable);
205            }
206            if let Some(handle) = handle
207                && (handle == ConnectionHandle::NONE || handle != inner.state.connection)
208            {
209                return Err(IoErrorKind::NotConnected);
210            }
211            if inner.busy {
212                return Err(IoErrorKind::ResourceBusy);
213            }
214            inner.busy = true;
215            inner.work = Some((command, request));
216            Ok(())
217        })?;
218        self.work.signal(());
219        Ok(())
220    }
221
222    fn dispatch(
223        &self,
224        command: ControlCommandIdentifier,
225        input: &AnyByLayout,
226        output: &mut AnyByLayout,
227    ) -> Result<()> {
228        let (request, handle) = match command {
229            GET_CAPABILITIES::IDENTIFIER => {
230                *GET_CAPABILITIES::cast_output(output)? = Capabilities {
231                    features: Capabilities::CENTRAL
232                        | Capabilities::OBSERVER
233                        | Capabilities::BROADCASTER
234                        | Capabilities::GATT_CLIENT,
235                    connection_limit: 1,
236                    value_capacity: VALUE_CAPACITY as u8,
237                };
238                return Ok(());
239            }
240            GET_STATE::IDENTIFIER => {
241                *GET_STATE::cast_output(output)? = self.with(|inner| inner.state);
242                return Ok(());
243            }
244            START_SCAN::IDENTIFIER => {
245                let configuration = *START_SCAN::cast_input(input)?;
246                if configuration.active > 1 || configuration.filter_duplicates > 1 {
247                    return Err(IoErrorKind::InvalidArgument);
248                }
249                (Request::StartScan(configuration), None)
250            }
251            STOP_SCAN::IDENTIFIER => (Request::StopScan, None),
252            START_ADVERTISING::IDENTIFIER => {
253                let data = *START_ADVERTISING::cast_input(input)?;
254                if data.as_slice().is_none_or(<[u8]>::is_empty) {
255                    return Err(IoErrorKind::InvalidArgument);
256                }
257                (Request::StartAdvertising(data), None)
258            }
259            STOP_ADVERTISING::IDENTIFIER => (Request::StopAdvertising, None),
260            CONNECT::IDENTIFIER => {
261                let request = *CONNECT::cast_input(input)?;
262                if request.peer.kind > Address::RANDOM
263                    || request.timeout_milliseconds == 0
264                    || request.reserved != 0
265                {
266                    return Err(IoErrorKind::InvalidArgument);
267                }
268                (Request::Connect(request), None)
269            }
270            DISCONNECT::IDENTIFIER => (Request::Disconnect, Some(*DISCONNECT::cast_input(input)?)),
271            DISCOVER_SERVICES::IDENTIFIER => (
272                Request::Services,
273                Some(*DISCOVER_SERVICES::cast_input(input)?),
274            ),
275            DISCOVER_CHARACTERISTICS::IDENTIFIER
276            | DISCOVER_DESCRIPTORS::IDENTIFIER
277            | READ_ATTRIBUTE::IDENTIFIER => {
278                let request = match command {
279                    DISCOVER_CHARACTERISTICS::IDENTIFIER => {
280                        DISCOVER_CHARACTERISTICS::cast_input(input)?
281                    }
282                    DISCOVER_DESCRIPTORS::IDENTIFIER => DISCOVER_DESCRIPTORS::cast_input(input)?,
283                    _ => READ_ATTRIBUTE::cast_input(input)?,
284                };
285                if request.reserved != 0 || request.handle == 0 {
286                    return Err(IoErrorKind::InvalidArgument);
287                }
288                let operation = match command {
289                    DISCOVER_CHARACTERISTICS::IDENTIFIER => {
290                        Request::Characteristics(request.handle)
291                    }
292                    DISCOVER_DESCRIPTORS::IDENTIFIER => Request::Descriptors(request.handle),
293                    _ => Request::Read(request.handle),
294                };
295                (operation, Some(request.connection))
296            }
297            WRITE_ATTRIBUTE::IDENTIFIER => {
298                let request = WRITE_ATTRIBUTE::cast_input(input)?;
299                if request.value.handle == 0 || request.value.as_slice().is_none() {
300                    return Err(IoErrorKind::InvalidArgument);
301                }
302                (Request::Write(request.value), Some(request.connection))
303            }
304            SET_NOTIFICATIONS::IDENTIFIER => {
305                let request = *SET_NOTIFICATIONS::cast_input(input)?;
306                if request.enabled > 1
307                    || request.characteristic.handle == 0
308                    || request.characteristic.reserved != 0
309                    || request.reserved != [0; 3]
310                {
311                    return Err(IoErrorKind::InvalidArgument);
312                }
313                (
314                    Request::Notifications(request),
315                    Some(request.characteristic.connection),
316                )
317            }
318            _ => return Err(IoErrorKind::Unsupported),
319        };
320        self.submit(command.get_number(), request, handle)
321    }
322}
323
324impl Inner {
325    fn reset_session(&mut self) {
326        self.state = State::default();
327        self.work = None;
328        self.events.clear();
329        self.busy = false;
330        self.dropped = 0;
331        self.reader = None;
332    }
333
334    fn pop_event(&mut self) -> Option<Event> {
335        if let Some(event) = self.events.pop_front() {
336            if event.kind == Event::COMPLETION {
337                self.busy = false;
338            }
339            return Some(event);
340        }
341        (self.dropped > 0).then(|| {
342            Event::new(Event::OVERFLOW, 0, ConnectionHandle::NONE)
343                .with_payload(core::mem::take(&mut self.dropped))
344        })
345    }
346}
347
348pub(crate) struct Running<'a>(&'a BluetoothDevice);
349
350impl Drop for Running<'_> {
351    fn drop(&mut self) {
352        let reader = self.0.with(|inner| {
353            inner.online = false;
354            let reader = inner.reader.take();
355            inner.reset_session();
356            if inner.session == Session::Closing {
357                inner.session = Session::Idle;
358            }
359            reader
360        });
361        if let Some(reader) = reader {
362            reader.wake();
363        }
364        notify_readiness();
365    }
366}
367
368impl BaseOperations for BluetoothDevice {
369    fn open(&self, context: &mut Context) -> Result<()> {
370        self.with(|inner| {
371            if !inner.online {
372                return Err(IoErrorKind::DeviceUnavailable);
373            }
374            if inner.session != Session::Idle {
375                return Err(IoErrorKind::ResourceBusy);
376            }
377            inner.session = Session::Open;
378            Ok(())
379        })?;
380        context.set_private_data(Box::new(Opening));
381        self.work.signal(());
382        Ok(())
383    }
384
385    fn close(&self, context: &mut Context) -> Result<()> {
386        if context.take_private_data_of_type::<Opening>().is_some() {
387            self.with(|inner| {
388                if inner.online {
389                    inner.session = Session::Closing;
390                    // Signal under the same lock used to publish the session state.
391                    self.closed.signal(());
392                } else {
393                    inner.session = Session::Idle;
394                }
395            });
396        }
397        Ok(())
398    }
399
400    fn clone_context(&self, _: &Context) -> Result<Context> {
401        Err(IoErrorKind::Unsupported)
402    }
403
404    fn read(
405        &self,
406        _: &mut Context,
407        context: &mut TaskContext<'_>,
408        buffer: &mut [u8],
409        _: Size,
410    ) -> Poll<Result<usize>> {
411        if buffer.len() < size_of::<Event>() {
412            return Poll::Ready(Err(IoErrorKind::MessageTooLarge));
413        }
414        self.with(|inner| {
415            if !inner.online {
416                return Poll::Ready(Err(IoErrorKind::DeviceUnavailable));
417            }
418            if let Some(mut event) = inner.pop_event() {
419                let bytes = event.as_mutable_bytes();
420                buffer[..bytes.len()].copy_from_slice(bytes);
421                return Poll::Ready(Ok(bytes.len()));
422            }
423            inner.reader = Some(context.waker().clone());
424            Poll::Pending
425        })
426    }
427
428    fn cancel_operation(&self, _: &mut Context, operation: Operation) {
429        if operation == Operation::Read {
430            self.with(|inner| inner.reader = None);
431        }
432    }
433
434    fn write(
435        &self,
436        _: &mut Context,
437        _: &mut TaskContext<'_>,
438        _: &[u8],
439        _: Size,
440    ) -> Poll<Result<usize>> {
441        Poll::Ready(Err(IoErrorKind::Unsupported))
442    }
443
444    fn control(
445        &self,
446        _: &mut Context,
447        _: &mut TaskContext<'_>,
448        command: ControlCommandIdentifier,
449        input: &AnyByLayout,
450        output: &mut AnyByLayout,
451    ) -> Poll<Result<()>> {
452        ready(|| self.dispatch(command, input, output))
453    }
454}
455
456impl MountOperations for BluetoothDevice {}
457
458impl CharacterDevice for BluetoothDevice {
459    fn readiness(&self, interests: ReadyEvents) -> Result<Option<ReadyEvents>> {
460        let events = self.with(|inner| {
461            if !inner.online {
462                return ReadyEvents::ERROR;
463            }
464            if inner.events.is_empty() && inner.dropped == 0 {
465                ReadyEvents::empty()
466            } else {
467                ReadyEvents::READ
468            }
469        });
470        Ok(Some(events & interests))
471    }
472}