Skip to main content

bt_hci_serial/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3#![no_std]
4
5use bt_hci_transport::blocking::TryError;
6use bt_hci_transport::{PacketKind, PacketToController, PacketToHost, ReadHciError, Transport, WithIndicator};
7use embassy_sync::blocking_mutex::raw::RawMutex;
8use embassy_sync::mutex::Mutex;
9use embedded_io::{ErrorType, ReadExactError};
10
11/// HCI transport layer for a split serial bus using the UART transport layer protocol [📖](https://www.bluetooth.com/wp-content/uploads/Files/Specification/HTML/Core-54/out/en/host-controller-interface/uart-transport-layer.html)
12pub struct SerialTransport<M: RawMutex, R, W> {
13    reader: Mutex<M, R>,
14    writer: Mutex<M, W>,
15}
16
17/// Error type for HCI transport layer communication errors.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[cfg_attr(feature = "defmt", derive(defmt::Format))]
20pub enum Error<E: embedded_io::Error> {
21    /// Error reading HCI data.
22    Read(ReadHciError<E>),
23    /// Error writing data.
24    Write(E),
25}
26
27impl<E: embedded_io::Error> core::fmt::Display for Error<E> {
28    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
29        write!(f, "{:?}", self)
30    }
31}
32
33impl<E: embedded_io::Error> core::error::Error for Error<E> {}
34
35impl<E: embedded_io::Error> embedded_io::Error for Error<E> {
36    fn kind(&self) -> embedded_io::ErrorKind {
37        match self {
38            Self::Read(e) => e.kind(),
39            Self::Write(e) => e.kind(),
40        }
41    }
42}
43
44impl<E: embedded_io::Error> From<ReadExactError<E>> for Error<E> {
45    fn from(e: ReadExactError<E>) -> Self {
46        Self::Read(e.into())
47    }
48}
49
50// Required by `ExternalController`, which bounds its transport error type on
51// `From<ReadHciError<Infallible>>`. A blanket `From<ReadHciError<E>>` would
52// overlap with this impl at `E = Infallible`, so the conversion is widening
53// instead: an infallible read error maps into the equivalent `ReadHciError<E>`.
54impl<E: embedded_io::Error> From<ReadHciError<core::convert::Infallible>> for Error<E> {
55    fn from(e: ReadHciError<core::convert::Infallible>) -> Self {
56        Self::Read(match e {
57            ReadHciError::BufferTooSmall => ReadHciError::BufferTooSmall,
58            ReadHciError::InvalidValue => ReadHciError::InvalidValue,
59            ReadHciError::Read(ReadExactError::UnexpectedEof) => ReadHciError::Read(ReadExactError::UnexpectedEof),
60            ReadHciError::Read(ReadExactError::Other(e)) => match e {},
61        })
62    }
63}
64
65impl<M: RawMutex, R: embedded_io_async::Read, W: embedded_io_async::Write> SerialTransport<M, R, W> {
66    /// Create a new instance.
67    pub fn new(reader: R, writer: W) -> Self {
68        Self {
69            reader: Mutex::new(reader),
70            writer: Mutex::new(writer),
71        }
72    }
73}
74
75impl<
76        M: RawMutex,
77        R: embedded_io::ErrorType<Error = E>,
78        W: embedded_io::ErrorType<Error = E>,
79        E: embedded_io::Error,
80    > ErrorType for SerialTransport<M, R, W>
81{
82    type Error = Error<E>;
83}
84
85impl<
86        M: RawMutex,
87        R: embedded_io_async::Read<Error = E>,
88        W: embedded_io_async::Write<Error = E>,
89        E: embedded_io::Error,
90    > Transport for SerialTransport<M, R, W>
91{
92    async fn read<'a, P: PacketToHost<'a>>(&self, rx: &'a mut [u8]) -> Result<P, Self::Error> {
93        let mut r = self.reader.lock().await;
94        let kind = PacketKind::read_async(&mut *r).await.map_err(Error::Read)?;
95        P::read_hci_async(kind, &mut *r, rx).await.map_err(Error::Read)
96    }
97
98    async fn write<P: PacketToController>(&self, tx: &P) -> Result<(), Self::Error> {
99        let mut w = self.writer.lock().await;
100        WithIndicator::new(tx)
101            .write_hci_async(&mut *w)
102            .await
103            .map_err(|e| Error::Write(e))
104    }
105}
106
107impl<M: RawMutex, R: embedded_io::Read<Error = E>, W: embedded_io::Write<Error = E>, E: embedded_io::Error>
108    blocking::Transport for SerialTransport<M, R, W>
109{
110    fn read<'a, P: PacketToHost<'a>>(&self, rx: &'a mut [u8]) -> Result<P, TryError<Self::Error>> {
111        let mut r = self.reader.try_lock().map_err(|_| TryError::Busy)?;
112        let kind = PacketKind::read(&mut *r)
113            .map_err(Error::Read)
114            .map_err(TryError::Error)?;
115        P::read_hci(kind, &mut *r, rx)
116            .map_err(Error::Read)
117            .map_err(TryError::Error)
118    }
119
120    fn write<P: PacketToController>(&self, tx: &P) -> Result<(), TryError<Self::Error>> {
121        let mut w = self.writer.try_lock().map_err(|_| TryError::Busy)?;
122        WithIndicator::new(tx)
123            .write_hci(&mut *w)
124            .map_err(|e| Error::Write(e))
125            .map_err(TryError::Error)
126    }
127}
128
129pub mod blocking {
130    //! Blocking transport trait.
131    pub use bt_hci_transport::blocking::Transport;
132}
133
134#[cfg(test)]
135mod tests {
136    use embassy_sync::blocking_mutex::raw::NoopRawMutex;
137
138    use super::*;
139
140    struct FakeCmd;
141
142    impl PacketToController for FakeCmd {
143        const KIND: PacketKind = PacketKind::Cmd;
144
145        fn size(&self) -> usize {
146            3
147        }
148
149        fn write_hci<W: embedded_io::Write>(&self, mut writer: W) -> Result<(), W::Error> {
150            writer.write_all(&[0x03, 0x0c, 0x00])
151        }
152
153        async fn write_hci_async<W: embedded_io_async::Write>(&self, mut writer: W) -> Result<(), W::Error> {
154            writer.write_all(&[0x03, 0x0c, 0x00]).await
155        }
156    }
157
158    struct SliceWriter<'a> {
159        buf: &'a mut [u8],
160        pos: usize,
161    }
162
163    impl embedded_io::ErrorType for SliceWriter<'_> {
164        type Error = core::convert::Infallible;
165    }
166
167    impl embedded_io::Write for SliceWriter<'_> {
168        fn write(&mut self, data: &[u8]) -> Result<usize, Self::Error> {
169            let n = data.len().min(self.buf.len() - self.pos);
170            self.buf[self.pos..self.pos + n].copy_from_slice(&data[..n]);
171            self.pos += n;
172            Ok(n)
173        }
174
175        fn flush(&mut self) -> Result<(), Self::Error> {
176            Ok(())
177        }
178    }
179
180    impl embedded_io_async::Write for SliceWriter<'_> {
181        async fn write(&mut self, data: &[u8]) -> Result<usize, Self::Error> {
182            embedded_io::Write::write(self, data)
183        }
184
185        async fn flush(&mut self) -> Result<(), Self::Error> {
186            Ok(())
187        }
188    }
189
190    #[test]
191    fn write_prepends_packet_kind_indicator() {
192        let mut buf = [0u8; 4];
193        {
194            let transport: SerialTransport<NoopRawMutex, &[u8], SliceWriter<'_>> =
195                SerialTransport::new(&[][..], SliceWriter { buf: &mut buf, pos: 0 });
196            blocking::Transport::write(&transport, &FakeCmd).unwrap();
197        }
198        assert_eq!(buf, [0x01, 0x03, 0x0c, 0x00]);
199    }
200}