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
use crate::common::atomic_ring_buffer::RingBuffer;
use crate::ll_api::ll_cmd::*;
#[cfg(feature = "_usart_impl")]
use paste::paste;

pub use crate::ll_api::{
    UsartDataBits, UsartHwFlowCtrl, UsartId, UsartMode, UsartParity, UsartStopBits,
};

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
/// Config
pub struct Config {
    /// Baud rate
    pub baudrate: u32,
    /// Number of data bits
    pub data_bits: UsartDataBits,
    /// Number of stop bits
    pub stop_bits: UsartStopBits,
    /// Parity type
    pub parity: UsartParity,
    /// Hardware Flow Control
    pub hw_flow: UsartHwFlowCtrl,
    /// Tx Rx mode
    pub tx_rx_mode: UsartMode,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            baudrate: 115200,
            data_bits: UsartDataBits::DataBits8,
            stop_bits: UsartStopBits::STOP1,
            parity: UsartParity::ParityNone,
            hw_flow: UsartHwFlowCtrl::None,
            tx_rx_mode: UsartMode::TxRx,
        }
    }
}

impl Config {
    pub fn flags(&self) -> u32 {
        let mut flags: u32;

        flags = self.data_bits as u32;
        flags |= self.stop_bits as u32;
        flags |= self.parity as u32;
        flags |= self.hw_flow as u32;
        flags |= self.tx_rx_mode as u32;

        flags
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Error {
    Code(i32),
}

pub struct UsartInner {
    id: UsartId,
    rx_buf: RingBuffer<u8>,
}

#[derive(Clone)]
pub struct Usart<'a> {
    inner: &'a UsartInner,
}

impl<'a> Usart<'a> {
    /// Creates a new Usart instance wrapping around the given UsartInner reference.
    ///
    /// # Arguments
    /// * `usart` - A reference to the inner Usart implementation.
    ///
    /// # Returns
    /// * A new Usart instance.
    pub fn new(usart: &'a UsartInner) -> Self {
        Usart { inner: usart }
    }

    /// Initializes the USART with the provided configuration.
    ///
    /// # Arguments
    /// * `config` - A reference to the configuration settings for the USART.
    ///
    /// # Returns
    /// * An i32 indicating the status of the initialization.
    pub fn init(&self, config: &Config) -> i32 {
        ll_invoke_inner!(
            INVOKE_ID_USART_INIT,
            self.inner.id,
            config.flags(),
            config.baudrate
        )
    }

    /// Sets the receive buffer for the USART.
    ///
    /// # Arguments
    /// * `rx_buffer` - A mutable slice representing the receive buffer.
    pub fn set_rx_buf(&self, rx_buffer: &mut [u8]) {
        let len = rx_buffer.len();
        unsafe { self.inner.rx_buf.init(rx_buffer.as_mut_ptr(), len) };
    }

    /// Writes a buffer to the USART in a blocking manner.
    ///
    /// # Arguments
    /// * `buf` - A slice containing the data to write.
    ///
    /// # Returns
    /// * An i32 indicating the status of the write operation.
    pub fn blocking_write(&self, buf: &[u8]) -> i32 {
        ll_invoke_inner!(
            INVOKE_ID_USART_WRITE,
            self.inner.id,
            buf.as_ptr(),
            buf.len()
        )
    }

    /// Reads into a buffer from the USART in a blocking manner.
    ///
    /// # Arguments
    /// * `buffer` - A mutable slice representing the read buffer.
    pub fn blocking_read(&self, buffer: &mut [u8]) {
        let rx_buf = &self.inner.rx_buf;
        let mut reader = unsafe { rx_buf.reader() };

        for b in buffer {
            while rx_buf.is_empty() {}
            *b = reader.pop_one().unwrap_or(0);
        }
    }

    /// Attempts to read a byte from the USART in a non-blocking manner.
    ///
    /// # Returns
    /// * A Result containing the read byte or an error if the buffer is empty.
    pub(crate) fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
        let rx_buf = &self.inner.rx_buf;

        if !rx_buf.is_empty() {
            let mut reader = unsafe { rx_buf.reader() };
            Ok(reader.pop_one().unwrap_or(0))
        } else {
            Err(nb::Error::WouldBlock)
        }
    }
}

impl Drop for Usart<'_> {
    fn drop(&mut self) {
        ll_invoke_inner!(INVOKE_ID_USART_DEINIT, self.inner.id);
    }
}

impl embedded_io::Error for Error {
    fn kind(&self) -> embedded_io::ErrorKind {
        embedded_io::ErrorKind::Other
    }
}

impl embedded_io::ErrorType for Usart<'_> {
    type Error = Error;
}

impl<'d> embedded_io::Read for Usart<'_> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.blocking_read(buf);
        Ok(buf.len())
    }
}

impl embedded_io::Write for Usart<'_> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        let result = self.blocking_write(buf);
        if result == 0 {
            return Ok(buf.len());
        }
        return Err(Error::Code(result));
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl embedded_hal_nb::serial::Error for Error {
    fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
        embedded_hal_nb::serial::ErrorKind::Other
    }
}
impl<'d> embedded_hal_nb::serial::ErrorType for Usart<'_> {
    type Error = Error;
}

impl<'d> embedded_hal_nb::serial::Read for Usart<'_> {
    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        self.nb_read()
    }
}

impl<'d> embedded_hal_nb::serial::Write for Usart<'_> {
    fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
        let result = self.blocking_write(&[char]);
        if result == 0 {
            return Ok({});
        }
        return Err(nb::Error::Other(Error::Code(result)));
    }

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        Ok(())
    }
}

#[cfg(feature = "_usart_impl")]
macro_rules! impl_usart {
    ($USART_id:ident) => {
        pub static $USART_id: UsartInner = UsartInner {
            id: UsartId::$USART_id,
            rx_buf: RingBuffer::new(),
        };

        paste! {
            #[allow(non_snake_case)]
            #[no_mangle]
            #[inline]
            unsafe extern "C" fn [<$USART_id _rx_hook_rs>] (val: u8) {
                $USART_id.rx_buf.writer().push_one(val);
            }
        }
    };
}

#[cfg(feature = "USART-0")]
impl_usart!(USART0);

#[cfg(feature = "USART-1")]
impl_usart!(USART1);

#[cfg(feature = "USART-2")]
impl_usart!(USART2);

#[cfg(feature = "USART-3")]
impl_usart!(USART3);

#[cfg(feature = "USART-4")]
impl_usart!(USART4);

#[cfg(feature = "USART-5")]
impl_usart!(USART5);

#[cfg(feature = "USART-6")]
impl_usart!(USART6);

#[cfg(feature = "USART-7")]
impl_usart!(USART7);