embassy_stm32/usart/
buffered.rs

1use core::future::poll_fn;
2use core::marker::PhantomData;
3use core::slice;
4use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};
5use core::task::Poll;
6
7use embassy_embedded_hal::SetConfig;
8use embassy_hal_internal::atomic_ring_buffer::RingBuffer;
9use embassy_hal_internal::{Peripheral, PeripheralRef};
10use embassy_sync::waitqueue::AtomicWaker;
11
12#[cfg(not(any(usart_v1, usart_v2)))]
13use super::DePin;
14use super::{
15    clear_interrupt_flags, configure, half_duplex_set_rx_tx_before_write, rdr, reconfigure, send_break, set_baudrate,
16    sr, tdr, Config, ConfigError, CtsPin, Duplex, Error, HalfDuplexConfig, HalfDuplexReadback, Info, Instance, Regs,
17    RtsPin, RxPin, TxPin,
18};
19use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed};
20use crate::interrupt::{self, InterruptExt};
21use crate::time::Hertz;
22
23/// Interrupt handler.
24pub struct InterruptHandler<T: Instance> {
25    _phantom: PhantomData<T>,
26}
27
28impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
29    unsafe fn on_interrupt() {
30        on_interrupt(T::info().regs, T::buffered_state())
31    }
32}
33
34unsafe fn on_interrupt(r: Regs, state: &'static State) {
35    // RX
36    let sr_val = sr(r).read();
37    // On v1 & v2, reading DR clears the rxne, error and idle interrupt
38    // flags. Keep this close to the SR read to reduce the chance of a
39    // flag being set in-between.
40    let dr = if sr_val.rxne() || cfg!(any(usart_v1, usart_v2)) && (sr_val.ore() || sr_val.idle()) {
41        Some(rdr(r).read_volatile())
42    } else {
43        None
44    };
45    clear_interrupt_flags(r, sr_val);
46
47    if sr_val.pe() {
48        warn!("Parity error");
49    }
50    if sr_val.fe() {
51        warn!("Framing error");
52    }
53    if sr_val.ne() {
54        warn!("Noise error");
55    }
56    if sr_val.ore() {
57        warn!("Overrun error");
58    }
59    if sr_val.rxne() {
60        let mut rx_writer = state.rx_buf.writer();
61        let buf = rx_writer.push_slice();
62        if !buf.is_empty() {
63            if let Some(byte) = dr {
64                buf[0] = byte;
65                rx_writer.push_done(1);
66            }
67        } else {
68            // FIXME: Should we disable any further RX interrupts when the buffer becomes full.
69        }
70
71        if !state.rx_buf.is_empty() {
72            state.rx_waker.wake();
73        }
74    }
75
76    if sr_val.idle() {
77        state.rx_waker.wake();
78    }
79
80    // With `usart_v4` hardware FIFO is enabled and Transmission complete (TC)
81    // indicates that all bytes are pushed out from the FIFO.
82    // For other usart variants it shows that last byte from the buffer was just sent.
83    if sr_val.tc() {
84        // For others it is cleared above with `clear_interrupt_flags`.
85        #[cfg(any(usart_v1, usart_v2))]
86        sr(r).modify(|w| w.set_tc(false));
87
88        r.cr1().modify(|w| {
89            w.set_tcie(false);
90        });
91
92        state.tx_done.store(true, Ordering::Release);
93        state.tx_waker.wake();
94    }
95
96    // TX
97    if sr(r).read().txe() {
98        let mut tx_reader = state.tx_buf.reader();
99        let buf = tx_reader.pop_slice();
100        if !buf.is_empty() {
101            r.cr1().modify(|w| {
102                w.set_txeie(true);
103            });
104
105            // Enable transmission complete interrupt when last byte is going to be sent out.
106            if buf.len() == 1 {
107                r.cr1().modify(|w| {
108                    w.set_tcie(true);
109                });
110            }
111
112            half_duplex_set_rx_tx_before_write(&r, state.half_duplex_readback.load(Ordering::Relaxed));
113
114            tdr(r).write_volatile(buf[0].into());
115            tx_reader.pop_done(1);
116        } else {
117            // Disable interrupt until we have something to transmit again.
118            r.cr1().modify(|w| {
119                w.set_txeie(false);
120            });
121        }
122    }
123}
124
125pub(super) struct State {
126    rx_waker: AtomicWaker,
127    rx_buf: RingBuffer,
128    tx_waker: AtomicWaker,
129    tx_buf: RingBuffer,
130    tx_done: AtomicBool,
131    tx_rx_refcount: AtomicU8,
132    half_duplex_readback: AtomicBool,
133}
134
135impl State {
136    pub(super) const fn new() -> Self {
137        Self {
138            rx_buf: RingBuffer::new(),
139            tx_buf: RingBuffer::new(),
140            rx_waker: AtomicWaker::new(),
141            tx_waker: AtomicWaker::new(),
142            tx_done: AtomicBool::new(true),
143            tx_rx_refcount: AtomicU8::new(0),
144            half_duplex_readback: AtomicBool::new(false),
145        }
146    }
147}
148
149/// Bidirectional buffered UART
150pub struct BufferedUart<'d> {
151    rx: BufferedUartRx<'d>,
152    tx: BufferedUartTx<'d>,
153}
154
155/// Tx-only buffered UART
156///
157/// Created with [BufferedUart::split]
158pub struct BufferedUartTx<'d> {
159    info: &'static Info,
160    state: &'static State,
161    kernel_clock: Hertz,
162    tx: Option<PeripheralRef<'d, AnyPin>>,
163    cts: Option<PeripheralRef<'d, AnyPin>>,
164    de: Option<PeripheralRef<'d, AnyPin>>,
165    is_borrowed: bool,
166}
167
168/// Rx-only buffered UART
169///
170/// Created with [BufferedUart::split]
171pub struct BufferedUartRx<'d> {
172    info: &'static Info,
173    state: &'static State,
174    kernel_clock: Hertz,
175    rx: Option<PeripheralRef<'d, AnyPin>>,
176    rts: Option<PeripheralRef<'d, AnyPin>>,
177    is_borrowed: bool,
178}
179
180impl<'d> SetConfig for BufferedUart<'d> {
181    type Config = Config;
182    type ConfigError = ConfigError;
183
184    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
185        self.set_config(config)
186    }
187}
188
189impl<'d> SetConfig for BufferedUartRx<'d> {
190    type Config = Config;
191    type ConfigError = ConfigError;
192
193    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
194        self.set_config(config)
195    }
196}
197
198impl<'d> SetConfig for BufferedUartTx<'d> {
199    type Config = Config;
200    type ConfigError = ConfigError;
201
202    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
203        self.set_config(config)
204    }
205}
206
207impl<'d> BufferedUart<'d> {
208    /// Create a new bidirectional buffered UART driver
209    pub fn new<T: Instance>(
210        peri: impl Peripheral<P = T> + 'd,
211        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
212        rx: impl Peripheral<P = impl RxPin<T>> + 'd,
213        tx: impl Peripheral<P = impl TxPin<T>> + 'd,
214        tx_buffer: &'d mut [u8],
215        rx_buffer: &'d mut [u8],
216        config: Config,
217    ) -> Result<Self, ConfigError> {
218        Self::new_inner(
219            peri,
220            new_pin!(rx, AfType::input(config.rx_pull)),
221            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)),
222            None,
223            None,
224            None,
225            tx_buffer,
226            rx_buffer,
227            config,
228        )
229    }
230
231    /// Create a new bidirectional buffered UART driver with request-to-send and clear-to-send pins
232    pub fn new_with_rtscts<T: Instance>(
233        peri: impl Peripheral<P = T> + 'd,
234        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
235        rx: impl Peripheral<P = impl RxPin<T>> + 'd,
236        tx: impl Peripheral<P = impl TxPin<T>> + 'd,
237        rts: impl Peripheral<P = impl RtsPin<T>> + 'd,
238        cts: impl Peripheral<P = impl CtsPin<T>> + 'd,
239        tx_buffer: &'d mut [u8],
240        rx_buffer: &'d mut [u8],
241        config: Config,
242    ) -> Result<Self, ConfigError> {
243        Self::new_inner(
244            peri,
245            new_pin!(rx, AfType::input(Pull::None)),
246            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)),
247            new_pin!(rts, AfType::output(OutputType::PushPull, Speed::Medium)),
248            new_pin!(cts, AfType::input(Pull::None)),
249            None,
250            tx_buffer,
251            rx_buffer,
252            config,
253        )
254    }
255
256    /// Create a new bidirectional buffered UART driver with only the RTS pin as the DE pin
257    pub fn new_with_rts_as_de<T: Instance>(
258        peri: impl Peripheral<P = T> + 'd,
259        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
260        rx: impl Peripheral<P = impl RxPin<T>> + 'd,
261        tx: impl Peripheral<P = impl TxPin<T>> + 'd,
262        rts: impl Peripheral<P = impl RtsPin<T>> + 'd,
263        tx_buffer: &'d mut [u8],
264        rx_buffer: &'d mut [u8],
265        config: Config,
266    ) -> Result<Self, ConfigError> {
267        Self::new_inner(
268            peri,
269            new_pin!(rx, AfType::input(Pull::None)),
270            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)),
271            None,
272            None,
273            new_pin!(rts, AfType::input(Pull::None)), // RTS mapped used as DE
274            tx_buffer,
275            rx_buffer,
276            config,
277        )
278    }
279
280    /// Create a new bidirectional buffered UART driver with only the request-to-send pin
281    pub fn new_with_rts<T: Instance>(
282        peri: impl Peripheral<P = T> + 'd,
283        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
284        rx: impl Peripheral<P = impl RxPin<T>> + 'd,
285        tx: impl Peripheral<P = impl TxPin<T>> + 'd,
286        rts: impl Peripheral<P = impl RtsPin<T>> + 'd,
287        tx_buffer: &'d mut [u8],
288        rx_buffer: &'d mut [u8],
289        config: Config,
290    ) -> Result<Self, ConfigError> {
291        Self::new_inner(
292            peri,
293            new_pin!(rx, AfType::input(Pull::None)),
294            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)),
295            new_pin!(rts, AfType::input(Pull::None)),
296            None, // no CTS
297            None, // no DE
298            tx_buffer,
299            rx_buffer,
300            config,
301        )
302    }
303
304    /// Create a new bidirectional buffered UART driver with a driver-enable pin
305    #[cfg(not(any(usart_v1, usart_v2)))]
306    pub fn new_with_de<T: Instance>(
307        peri: impl Peripheral<P = T> + 'd,
308        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
309        rx: impl Peripheral<P = impl RxPin<T>> + 'd,
310        tx: impl Peripheral<P = impl TxPin<T>> + 'd,
311        de: impl Peripheral<P = impl DePin<T>> + 'd,
312        tx_buffer: &'d mut [u8],
313        rx_buffer: &'d mut [u8],
314        config: Config,
315    ) -> Result<Self, ConfigError> {
316        Self::new_inner(
317            peri,
318            new_pin!(rx, AfType::input(config.rx_pull)),
319            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)),
320            None,
321            None,
322            new_pin!(de, AfType::output(OutputType::PushPull, Speed::Medium)),
323            tx_buffer,
324            rx_buffer,
325            config,
326        )
327    }
328
329    /// Create a single-wire half-duplex Uart transceiver on a single Tx pin.
330    ///
331    /// See [`new_half_duplex_on_rx`][`Self::new_half_duplex_on_rx`] if you would prefer to use an Rx pin
332    /// (when it is available for your chip). There is no functional difference between these methods, as both
333    /// allow bidirectional communication.
334    ///
335    /// The TX pin is always released when no data is transmitted. Thus, it acts as a standard
336    /// I/O in idle or in reception. It means that the I/O must be configured so that TX is
337    /// configured as alternate function open-drain with an external pull-up
338    /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict
339    /// on the line must be managed by software (for instance by using a centralized arbiter).
340    #[doc(alias("HDSEL"))]
341    pub fn new_half_duplex<T: Instance>(
342        peri: impl Peripheral<P = T> + 'd,
343        tx: impl Peripheral<P = impl TxPin<T>> + 'd,
344        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
345        tx_buffer: &'d mut [u8],
346        rx_buffer: &'d mut [u8],
347        mut config: Config,
348        readback: HalfDuplexReadback,
349        half_duplex: HalfDuplexConfig,
350    ) -> Result<Self, ConfigError> {
351        #[cfg(not(any(usart_v1, usart_v2)))]
352        {
353            config.swap_rx_tx = false;
354        }
355        config.duplex = Duplex::Half(readback);
356
357        Self::new_inner(
358            peri,
359            None,
360            new_pin!(tx, half_duplex.af_type()),
361            None,
362            None,
363            None,
364            tx_buffer,
365            rx_buffer,
366            config,
367        )
368    }
369
370    /// Create a single-wire half-duplex Uart transceiver on a single Rx pin.
371    ///
372    /// See [`new_half_duplex`][`Self::new_half_duplex`] if you would prefer to use an Tx pin.
373    /// There is no functional difference between these methods, as both allow bidirectional communication.
374    ///
375    /// The pin is always released when no data is transmitted. Thus, it acts as a standard
376    /// I/O in idle or in reception.
377    /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict
378    /// on the line must be managed by software (for instance by using a centralized arbiter).
379    #[cfg(not(any(usart_v1, usart_v2)))]
380    #[doc(alias("HDSEL"))]
381    pub fn new_half_duplex_on_rx<T: Instance>(
382        peri: impl Peripheral<P = T> + 'd,
383        rx: impl Peripheral<P = impl RxPin<T>> + 'd,
384        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
385        tx_buffer: &'d mut [u8],
386        rx_buffer: &'d mut [u8],
387        mut config: Config,
388        readback: HalfDuplexReadback,
389        half_duplex: HalfDuplexConfig,
390    ) -> Result<Self, ConfigError> {
391        config.swap_rx_tx = true;
392        config.duplex = Duplex::Half(readback);
393
394        Self::new_inner(
395            peri,
396            new_pin!(rx, half_duplex.af_type()),
397            None,
398            None,
399            None,
400            None,
401            tx_buffer,
402            rx_buffer,
403            config,
404        )
405    }
406
407    fn new_inner<T: Instance>(
408        _peri: impl Peripheral<P = T> + 'd,
409        rx: Option<PeripheralRef<'d, AnyPin>>,
410        tx: Option<PeripheralRef<'d, AnyPin>>,
411        rts: Option<PeripheralRef<'d, AnyPin>>,
412        cts: Option<PeripheralRef<'d, AnyPin>>,
413        de: Option<PeripheralRef<'d, AnyPin>>,
414        tx_buffer: &'d mut [u8],
415        rx_buffer: &'d mut [u8],
416        config: Config,
417    ) -> Result<Self, ConfigError> {
418        let info = T::info();
419        let state = T::buffered_state();
420        let kernel_clock = T::frequency();
421
422        state.half_duplex_readback.store(
423            config.duplex == Duplex::Half(HalfDuplexReadback::Readback),
424            Ordering::Relaxed,
425        );
426
427        let mut this = Self {
428            rx: BufferedUartRx {
429                info,
430                state,
431                kernel_clock,
432                rx,
433                rts,
434                is_borrowed: false,
435            },
436            tx: BufferedUartTx {
437                info,
438                state,
439                kernel_clock,
440                tx,
441                cts,
442                de,
443                is_borrowed: false,
444            },
445        };
446        this.enable_and_configure(tx_buffer, rx_buffer, &config)?;
447        Ok(this)
448    }
449
450    fn enable_and_configure(
451        &mut self,
452        tx_buffer: &'d mut [u8],
453        rx_buffer: &'d mut [u8],
454        config: &Config,
455    ) -> Result<(), ConfigError> {
456        let info = self.rx.info;
457        let state = self.rx.state;
458        state.tx_rx_refcount.store(2, Ordering::Relaxed);
459
460        info.rcc.enable_and_reset();
461
462        let len = tx_buffer.len();
463        unsafe { state.tx_buf.init(tx_buffer.as_mut_ptr(), len) };
464        let len = rx_buffer.len();
465        unsafe { state.rx_buf.init(rx_buffer.as_mut_ptr(), len) };
466
467        info.regs.cr3().write(|w| {
468            w.set_rtse(self.rx.rts.is_some());
469            w.set_ctse(self.tx.cts.is_some());
470            #[cfg(not(any(usart_v1, usart_v2)))]
471            w.set_dem(self.tx.de.is_some());
472            w.set_hdsel(config.duplex.is_half());
473        });
474        configure(info, self.rx.kernel_clock, &config, true, true)?;
475
476        info.regs.cr1().modify(|w| {
477            w.set_rxneie(true);
478            w.set_idleie(true);
479
480            if config.duplex.is_half() {
481                // The te and re bits will be set by write, read and flush methods.
482                // Receiver should be enabled by default for Half-Duplex.
483                w.set_te(false);
484                w.set_re(true);
485            }
486        });
487
488        info.interrupt.unpend();
489        unsafe { info.interrupt.enable() };
490
491        Ok(())
492    }
493
494    /// Split the driver into a Tx and Rx part (useful for sending to separate tasks)
495    pub fn split(self) -> (BufferedUartTx<'d>, BufferedUartRx<'d>) {
496        (self.tx, self.rx)
497    }
498
499    /// Split the Uart into a transmitter and receiver,
500    /// which is particularly useful when having two tasks correlating to
501    /// transmitting and receiving.
502    pub fn split_ref(&mut self) -> (BufferedUartTx<'_>, BufferedUartRx<'_>) {
503        (
504            BufferedUartTx {
505                info: self.tx.info,
506                state: self.tx.state,
507                kernel_clock: self.tx.kernel_clock,
508                tx: self.tx.tx.as_mut().map(PeripheralRef::reborrow),
509                cts: self.tx.cts.as_mut().map(PeripheralRef::reborrow),
510                de: self.tx.de.as_mut().map(PeripheralRef::reborrow),
511                is_borrowed: true,
512            },
513            BufferedUartRx {
514                info: self.rx.info,
515                state: self.rx.state,
516                kernel_clock: self.rx.kernel_clock,
517                rx: self.rx.rx.as_mut().map(PeripheralRef::reborrow),
518                rts: self.rx.rts.as_mut().map(PeripheralRef::reborrow),
519                is_borrowed: true,
520            },
521        )
522    }
523
524    /// Reconfigure the driver
525    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
526        reconfigure(self.rx.info, self.rx.kernel_clock, config)?;
527
528        self.rx.info.regs.cr1().modify(|w| {
529            w.set_rxneie(true);
530            w.set_idleie(true);
531        });
532
533        Ok(())
534    }
535
536    /// Send break character
537    pub fn send_break(&self) {
538        self.tx.send_break()
539    }
540
541    /// Set baudrate
542    pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
543        self.tx.set_baudrate(baudrate)?;
544        self.rx.set_baudrate(baudrate)?;
545        Ok(())
546    }
547}
548
549impl<'d> BufferedUartRx<'d> {
550    async fn read(&self, buf: &mut [u8]) -> Result<usize, Error> {
551        poll_fn(move |cx| {
552            let state = self.state;
553            let mut rx_reader = unsafe { state.rx_buf.reader() };
554            let data = rx_reader.pop_slice();
555
556            if !data.is_empty() {
557                let len = data.len().min(buf.len());
558                buf[..len].copy_from_slice(&data[..len]);
559
560                let do_pend = state.rx_buf.is_full();
561                rx_reader.pop_done(len);
562
563                if do_pend {
564                    self.info.interrupt.pend();
565                }
566
567                return Poll::Ready(Ok(len));
568            }
569
570            state.rx_waker.register(cx.waker());
571            Poll::Pending
572        })
573        .await
574    }
575
576    fn blocking_read(&self, buf: &mut [u8]) -> Result<usize, Error> {
577        loop {
578            let state = self.state;
579            let mut rx_reader = unsafe { state.rx_buf.reader() };
580            let data = rx_reader.pop_slice();
581
582            if !data.is_empty() {
583                let len = data.len().min(buf.len());
584                buf[..len].copy_from_slice(&data[..len]);
585
586                let do_pend = state.rx_buf.is_full();
587                rx_reader.pop_done(len);
588
589                if do_pend {
590                    self.info.interrupt.pend();
591                }
592
593                return Ok(len);
594            }
595        }
596    }
597
598    async fn fill_buf(&self) -> Result<&[u8], Error> {
599        poll_fn(move |cx| {
600            let state = self.state;
601            let mut rx_reader = unsafe { state.rx_buf.reader() };
602            let (p, n) = rx_reader.pop_buf();
603            if n == 0 {
604                state.rx_waker.register(cx.waker());
605                return Poll::Pending;
606            }
607
608            let buf = unsafe { slice::from_raw_parts(p, n) };
609            Poll::Ready(Ok(buf))
610        })
611        .await
612    }
613
614    fn consume(&self, amt: usize) {
615        let state = self.state;
616        let mut rx_reader = unsafe { state.rx_buf.reader() };
617        let full = state.rx_buf.is_full();
618        rx_reader.pop_done(amt);
619        if full {
620            self.info.interrupt.pend();
621        }
622    }
623
624    /// we are ready to read if there is data in the buffer
625    fn read_ready(&mut self) -> Result<bool, Error> {
626        let state = self.state;
627        Ok(!state.rx_buf.is_empty())
628    }
629
630    /// Reconfigure the driver
631    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
632        reconfigure(self.info, self.kernel_clock, config)?;
633
634        self.info.regs.cr1().modify(|w| {
635            w.set_rxneie(true);
636            w.set_idleie(true);
637        });
638
639        Ok(())
640    }
641
642    /// Set baudrate
643    pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
644        set_baudrate(self.info, self.kernel_clock, baudrate)
645    }
646}
647
648impl<'d> BufferedUartTx<'d> {
649    async fn write(&self, buf: &[u8]) -> Result<usize, Error> {
650        poll_fn(move |cx| {
651            let state = self.state;
652            state.tx_done.store(false, Ordering::Release);
653
654            let empty = state.tx_buf.is_empty();
655
656            let mut tx_writer = unsafe { state.tx_buf.writer() };
657            let data = tx_writer.push_slice();
658            if data.is_empty() {
659                state.tx_waker.register(cx.waker());
660                return Poll::Pending;
661            }
662
663            let n = data.len().min(buf.len());
664            data[..n].copy_from_slice(&buf[..n]);
665            tx_writer.push_done(n);
666
667            if empty {
668                self.info.interrupt.pend();
669            }
670
671            Poll::Ready(Ok(n))
672        })
673        .await
674    }
675
676    async fn flush(&self) -> Result<(), Error> {
677        poll_fn(move |cx| {
678            let state = self.state;
679
680            if !state.tx_done.load(Ordering::Acquire) {
681                state.tx_waker.register(cx.waker());
682                return Poll::Pending;
683            }
684
685            Poll::Ready(Ok(()))
686        })
687        .await
688    }
689
690    fn blocking_write(&self, buf: &[u8]) -> Result<usize, Error> {
691        loop {
692            let state = self.state;
693            let empty = state.tx_buf.is_empty();
694
695            let mut tx_writer = unsafe { state.tx_buf.writer() };
696            let data = tx_writer.push_slice();
697            if !data.is_empty() {
698                let n = data.len().min(buf.len());
699                data[..n].copy_from_slice(&buf[..n]);
700                tx_writer.push_done(n);
701
702                if empty {
703                    self.info.interrupt.pend();
704                }
705
706                return Ok(n);
707            }
708        }
709    }
710
711    fn blocking_flush(&self) -> Result<(), Error> {
712        loop {
713            let state = self.state;
714            if state.tx_buf.is_empty() {
715                return Ok(());
716            }
717        }
718    }
719
720    /// Reconfigure the driver
721    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
722        reconfigure(self.info, self.kernel_clock, config)?;
723
724        self.info.regs.cr1().modify(|w| {
725            w.set_rxneie(true);
726            w.set_idleie(true);
727        });
728
729        Ok(())
730    }
731
732    /// Send break character
733    pub fn send_break(&self) {
734        send_break(&self.info.regs);
735    }
736
737    /// Set baudrate
738    pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
739        set_baudrate(self.info, self.kernel_clock, baudrate)
740    }
741}
742
743impl<'d> Drop for BufferedUartRx<'d> {
744    fn drop(&mut self) {
745        if !self.is_borrowed {
746            let state = self.state;
747            unsafe {
748                state.rx_buf.deinit();
749
750                // TX is inactive if the the buffer is not available.
751                // We can now unregister the interrupt handler
752                if state.tx_buf.len() == 0 {
753                    self.info.interrupt.disable();
754                }
755            }
756
757            self.rx.as_ref().map(|x| x.set_as_disconnected());
758            self.rts.as_ref().map(|x| x.set_as_disconnected());
759            drop_tx_rx(self.info, state);
760        }
761    }
762}
763
764impl<'d> Drop for BufferedUartTx<'d> {
765    fn drop(&mut self) {
766        if !self.is_borrowed {
767            let state = self.state;
768            unsafe {
769                state.tx_buf.deinit();
770
771                // RX is inactive if the the buffer is not available.
772                // We can now unregister the interrupt handler
773                if state.rx_buf.len() == 0 {
774                    self.info.interrupt.disable();
775                }
776            }
777
778            self.tx.as_ref().map(|x| x.set_as_disconnected());
779            self.cts.as_ref().map(|x| x.set_as_disconnected());
780            self.de.as_ref().map(|x| x.set_as_disconnected());
781            drop_tx_rx(self.info, state);
782        }
783    }
784}
785
786fn drop_tx_rx(info: &Info, state: &State) {
787    // We cannot use atomic subtraction here, because it's not supported for all targets
788    let is_last_drop = critical_section::with(|_| {
789        let refcount = state.tx_rx_refcount.load(Ordering::Relaxed);
790        assert!(refcount >= 1);
791        state.tx_rx_refcount.store(refcount - 1, Ordering::Relaxed);
792        refcount == 1
793    });
794    if is_last_drop {
795        info.rcc.disable();
796    }
797}
798
799impl<'d> embedded_io_async::ErrorType for BufferedUart<'d> {
800    type Error = Error;
801}
802
803impl<'d> embedded_io_async::ErrorType for BufferedUartRx<'d> {
804    type Error = Error;
805}
806
807impl<'d> embedded_io_async::ErrorType for BufferedUartTx<'d> {
808    type Error = Error;
809}
810
811impl<'d> embedded_io_async::Read for BufferedUart<'d> {
812    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
813        self.rx.read(buf).await
814    }
815}
816
817impl<'d> embedded_io_async::Read for BufferedUartRx<'d> {
818    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
819        Self::read(self, buf).await
820    }
821}
822
823impl<'d> embedded_io_async::ReadReady for BufferedUart<'d> {
824    fn read_ready(&mut self) -> Result<bool, Self::Error> {
825        BufferedUartRx::<'d>::read_ready(&mut self.rx)
826    }
827}
828
829impl<'d> embedded_io_async::ReadReady for BufferedUartRx<'d> {
830    fn read_ready(&mut self) -> Result<bool, Self::Error> {
831        Self::read_ready(self)
832    }
833}
834
835impl<'d> embedded_io_async::BufRead for BufferedUart<'d> {
836    async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
837        self.rx.fill_buf().await
838    }
839
840    fn consume(&mut self, amt: usize) {
841        self.rx.consume(amt)
842    }
843}
844
845impl<'d> embedded_io_async::BufRead for BufferedUartRx<'d> {
846    async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
847        Self::fill_buf(self).await
848    }
849
850    fn consume(&mut self, amt: usize) {
851        Self::consume(self, amt)
852    }
853}
854
855impl<'d> embedded_io_async::Write for BufferedUart<'d> {
856    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
857        self.tx.write(buf).await
858    }
859
860    async fn flush(&mut self) -> Result<(), Self::Error> {
861        self.tx.flush().await
862    }
863}
864
865impl<'d> embedded_io_async::Write for BufferedUartTx<'d> {
866    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
867        Self::write(self, buf).await
868    }
869
870    async fn flush(&mut self) -> Result<(), Self::Error> {
871        Self::flush(self).await
872    }
873}
874
875impl<'d> embedded_io::Read for BufferedUart<'d> {
876    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
877        self.rx.blocking_read(buf)
878    }
879}
880
881impl<'d> embedded_io::Read for BufferedUartRx<'d> {
882    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
883        self.blocking_read(buf)
884    }
885}
886
887impl<'d> embedded_io::Write for BufferedUart<'d> {
888    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
889        self.tx.blocking_write(buf)
890    }
891
892    fn flush(&mut self) -> Result<(), Self::Error> {
893        self.tx.blocking_flush()
894    }
895}
896
897impl<'d> embedded_io::Write for BufferedUartTx<'d> {
898    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
899        Self::blocking_write(self, buf)
900    }
901
902    fn flush(&mut self) -> Result<(), Self::Error> {
903        Self::blocking_flush(self)
904    }
905}
906
907impl<'d> embedded_hal_02::serial::Read<u8> for BufferedUartRx<'d> {
908    type Error = Error;
909
910    fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
911        let r = self.info.regs;
912        unsafe {
913            let sr = sr(r).read();
914            if sr.pe() {
915                rdr(r).read_volatile();
916                Err(nb::Error::Other(Error::Parity))
917            } else if sr.fe() {
918                rdr(r).read_volatile();
919                Err(nb::Error::Other(Error::Framing))
920            } else if sr.ne() {
921                rdr(r).read_volatile();
922                Err(nb::Error::Other(Error::Noise))
923            } else if sr.ore() {
924                rdr(r).read_volatile();
925                Err(nb::Error::Other(Error::Overrun))
926            } else if sr.rxne() {
927                Ok(rdr(r).read_volatile())
928            } else {
929                Err(nb::Error::WouldBlock)
930            }
931        }
932    }
933}
934
935impl<'d> embedded_hal_02::blocking::serial::Write<u8> for BufferedUartTx<'d> {
936    type Error = Error;
937
938    fn bwrite_all(&mut self, mut buffer: &[u8]) -> Result<(), Self::Error> {
939        while !buffer.is_empty() {
940            match self.blocking_write(buffer) {
941                Ok(0) => panic!("zero-length write."),
942                Ok(n) => buffer = &buffer[n..],
943                Err(e) => return Err(e),
944            }
945        }
946        Ok(())
947    }
948
949    fn bflush(&mut self) -> Result<(), Self::Error> {
950        self.blocking_flush()
951    }
952}
953
954impl<'d> embedded_hal_02::serial::Read<u8> for BufferedUart<'d> {
955    type Error = Error;
956
957    fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
958        embedded_hal_02::serial::Read::read(&mut self.rx)
959    }
960}
961
962impl<'d> embedded_hal_02::blocking::serial::Write<u8> for BufferedUart<'d> {
963    type Error = Error;
964
965    fn bwrite_all(&mut self, mut buffer: &[u8]) -> Result<(), Self::Error> {
966        while !buffer.is_empty() {
967            match self.tx.blocking_write(buffer) {
968                Ok(0) => panic!("zero-length write."),
969                Ok(n) => buffer = &buffer[n..],
970                Err(e) => return Err(e),
971            }
972        }
973        Ok(())
974    }
975
976    fn bflush(&mut self) -> Result<(), Self::Error> {
977        self.tx.blocking_flush()
978    }
979}
980
981impl<'d> embedded_hal_nb::serial::ErrorType for BufferedUart<'d> {
982    type Error = Error;
983}
984
985impl<'d> embedded_hal_nb::serial::ErrorType for BufferedUartTx<'d> {
986    type Error = Error;
987}
988
989impl<'d> embedded_hal_nb::serial::ErrorType for BufferedUartRx<'d> {
990    type Error = Error;
991}
992
993impl<'d> embedded_hal_nb::serial::Read for BufferedUartRx<'d> {
994    fn read(&mut self) -> nb::Result<u8, Self::Error> {
995        embedded_hal_02::serial::Read::read(self)
996    }
997}
998
999impl<'d> embedded_hal_nb::serial::Write for BufferedUartTx<'d> {
1000    fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1001        self.blocking_write(&[char]).map(drop).map_err(nb::Error::Other)
1002    }
1003
1004    fn flush(&mut self) -> nb::Result<(), Self::Error> {
1005        self.blocking_flush().map_err(nb::Error::Other)
1006    }
1007}
1008
1009impl<'d> embedded_hal_nb::serial::Read for BufferedUart<'d> {
1010    fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1011        embedded_hal_02::serial::Read::read(&mut self.rx)
1012    }
1013}
1014
1015impl<'d> embedded_hal_nb::serial::Write for BufferedUart<'d> {
1016    fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1017        self.tx.blocking_write(&[char]).map(drop).map_err(nb::Error::Other)
1018    }
1019
1020    fn flush(&mut self) -> nb::Result<(), Self::Error> {
1021        self.tx.blocking_flush().map_err(nb::Error::Other)
1022    }
1023}