Skip to main content

ch32_hal/usart/
ringbuffered.rs

1use core::future::poll_fn;
2use core::marker::PhantomData;
3use core::mem;
4use core::sync::atomic::{compiler_fence, Ordering};
5use core::task::Poll;
6
7use futures::future::{select, Either};
8
9use super::{Error, Instance, UartRx};
10use crate::dma::{ReadableRingBuffer, TransferOptions};
11use crate::gpio::{AnyPin, SealedPin};
12use crate::mode::Async;
13use crate::Peri;
14
15/// Rx-only UART driver that receives continuously into a DMA ring buffer.
16///
17/// Unlike [`UartRx::read`], no data is lost between reads, and dropping a `read` future
18/// doesn't stop reception.
19pub struct RingBufferedUartRx<'d, T: Instance> {
20    _phantom: PhantomData<T>,
21    rx: Option<Peri<'d, AnyPin>>,
22    rts: Option<Peri<'d, AnyPin>>,
23    ring_buf: ReadableRingBuffer<'d, u8>,
24}
25
26impl<'d, T: Instance> UartRx<'d, T, Async> {
27    /// Turn the `UartRx` into a buffered UART which can continuously receive in the background
28    /// without the possibility of losing bytes. The `dma_buf` is a buffer registered to the
29    /// DMA controller, and must be large enough to prevent overflows.
30    pub fn into_ring_buffered(mut self, dma_buf: &'d mut [u8]) -> RingBufferedUartRx<'d, T> {
31        assert!(!dma_buf.is_empty() && dma_buf.len() <= 0xFFFF);
32
33        let opts = TransferOptions {
34            half_transfer_ir: true,
35            ..Default::default()
36        };
37
38        let rx_dma = self.rx_dma.take().unwrap();
39        let ring_buf = unsafe {
40            ReadableRingBuffer::new(
41                rx_dma.channel,
42                rx_dma.request,
43                T::regs().datar().as_ptr() as _,
44                dma_buf,
45                opts,
46            )
47        };
48        let rx = self.rx.take();
49        let rts = self.rts.take();
50
51        // Dropping `self` would disable the peripheral.
52        mem::forget(self);
53
54        RingBufferedUartRx {
55            _phantom: PhantomData,
56            rx,
57            rts,
58            ring_buf,
59        }
60    }
61}
62
63impl<'d, T: Instance> RingBufferedUartRx<'d, T> {
64    /// Start receiving in the background into the previously passed buffer.
65    ///
66    /// This is done automatically by `read()` if required.
67    pub fn start_uart(&mut self) {
68        // Clear the buffer so that it is ready to receive data
69        compiler_fence(Ordering::SeqCst);
70        self.ring_buf.reset();
71        self.ring_buf.start();
72
73        let r = T::regs();
74        // enable interrupts
75        r.ctlr1().modify(|w| {
76            // disable RXNE interrupt
77            w.set_rxneie(false);
78            // enable parity interrupt if not ParityNone
79            w.set_peie(w.pce());
80            // enable idle line interrupt
81            w.set_idleie(true);
82        });
83        r.ctlr3().modify(|w| {
84            // enable Error Interrupt: (Frame error, Noise error, Overrun error)
85            w.set_eie(true);
86            // enable DMA Rx Request
87            w.set_dmar(true);
88        });
89    }
90
91    /// Stop DMA backed UART receiver
92    fn stop_uart(&mut self) {
93        // paused, not stopped: the next read restarts it after an error
94        self.ring_buf.request_pause();
95
96        let r = T::regs();
97        // clear all interrupts and DMA Rx Request
98        r.ctlr1().modify(|w| {
99            // disable RXNE interrupt
100            w.set_rxneie(false);
101            // disable parity interrupt
102            w.set_peie(false);
103            // disable idle line interrupt
104            w.set_idleie(false);
105        });
106        r.ctlr3().modify(|w| {
107            // disable Error Interrupt: (Frame error, Noise error, Overrun error)
108            w.set_eie(false);
109            // disable DMA Rx Request
110            w.set_dmar(false);
111        });
112
113        compiler_fence(Ordering::SeqCst);
114    }
115
116    /// Read bytes that are readily available in the ring buffer.
117    /// If no bytes are currently available in the buffer the call waits until some
118    /// bytes are available (at least one byte and at most half the buffer size), or the line
119    /// goes idle.
120    ///
121    /// Background receive is started if `start_uart()` has not been previously called.
122    ///
123    /// Receive in the background is terminated if an error is returned.
124    /// It must then manually be started again by calling `start_uart()` or by re-calling `read()`.
125    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
126        let r = T::regs();
127
128        // Start DMA and Uart if it was not already started,
129        // otherwise check for errors in status register.
130        let sr = clear_idle_flag::<T>();
131        if !r.ctlr3().read().dmar() {
132            self.start_uart();
133        } else {
134            check_for_errors(sr)?;
135        }
136
137        loop {
138            match self.ring_buf.read(buf) {
139                Ok((0, _)) => {}
140                Ok((len, _)) => {
141                    return Ok(len);
142                }
143                Err(_) => {
144                    self.stop_uart();
145                    return Err(Error::Overrun);
146                }
147            }
148
149            match self.wait_for_data_or_idle().await {
150                Ok(_) => {}
151                Err(err) => {
152                    self.stop_uart();
153                    return Err(err);
154                }
155            }
156        }
157    }
158
159    /// Wait for uart idle or dma half-full or full
160    async fn wait_for_data_or_idle(&mut self) -> Result<(), Error> {
161        compiler_fence(Ordering::SeqCst);
162
163        // The interrupt handler disables the idle interrupt once it fires.
164        critical_section::with(|_| T::regs().ctlr1().modify(|w| w.set_idleie(true)));
165
166        // Future which completes when idle line is detected
167        let s = T::state();
168        let uart = poll_fn(|cx| {
169            s.rx_waker.register(cx.waker());
170
171            compiler_fence(Ordering::SeqCst);
172
173            // Critical section is needed so that IDLE isn't set after
174            // our read but before we clear it.
175            let sr = critical_section::with(|_| clear_idle_flag::<T>());
176
177            check_for_errors(sr)?;
178
179            if sr.idle() {
180                // Idle line is detected
181                Poll::Ready(Ok(()))
182            } else {
183                Poll::Pending
184            }
185        });
186
187        let mut dma_init = false;
188        // Future which completes when there is dma is half full or full
189        let dma = poll_fn(|cx| {
190            self.ring_buf.set_waker(cx.waker());
191
192            let status = match dma_init {
193                false => Poll::Pending,
194                true => Poll::Ready(()),
195            };
196
197            dma_init = true;
198            status
199        });
200
201        match select(core::pin::pin!(uart), core::pin::pin!(dma)).await {
202            Either::Left((result, _)) => result,
203            Either::Right(((), _)) => Ok(()),
204        }
205    }
206}
207
208impl<T: Instance> Drop for RingBufferedUartRx<'_, T> {
209    fn drop(&mut self) {
210        self.stop_uart();
211        self.ring_buf.request_stop();
212        self.rx.as_ref().map(|x| x.set_as_disconnected());
213        self.rts.as_ref().map(|x| x.set_as_disconnected());
214        // This drop owns the RX half's refcount taken by `UartRx::new_inner`;
215        // `mem::forget` in `into_ring_buffered` transferred it here.
216        super::disable_peripheral::<T>();
217    }
218}
219
220/// Return the status register, and clear the IDLE flag (and the error flags): a status
221/// register read followed by a data register read.
222fn clear_idle_flag<T: Instance>() -> ch32_metapac::usart::regs::Statr {
223    let r = T::regs();
224    let sr = r.statr().read();
225    // DATAR is shared with the DMA: if a byte is pending there when the CPU
226    // reads it, the DMA request disappears and the byte is lost. Clear only
227    // when a flag is set; steady reception leaves none set, and the DMA keeps
228    // the byte (RM ยง17.10.1: IDLE and the error flags are cleared by a STATR
229    // read followed by a DATAR read).
230    if sr.idle() || sr.pe() || sr.fe() || sr.ne() || sr.ore() {
231        let _ = r.datar().read();
232    }
233    sr
234}
235
236fn check_for_errors(s: ch32_metapac::usart::regs::Statr) -> Result<(), Error> {
237    if s.pe() {
238        Err(Error::Parity)
239    } else if s.fe() {
240        Err(Error::Framing)
241    } else if s.ne() {
242        Err(Error::Noise)
243    } else if s.ore() {
244        Err(Error::Overrun)
245    } else {
246        Ok(())
247    }
248}