aboutsummaryrefslogtreecommitdiff
path: root/embassy-nrf/src/uarte.rs
blob: b5e4da862c7bf6540b36ea044b0e83b3cc6a3159 (plain)
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Async low power UARTE.
//!
//! The peripheral is automatically enabled and disabled as required to save power.
//! Lowest power consumption can only be guaranteed if the send receive futures
//! are dropped correctly (e.g. not using `mem::forget()`).

use core::future::Future;
use core::ops::Deref;
use core::sync::atomic::{compiler_fence, Ordering};
use core::task::{Context, Poll};

use embassy::interrupt::InterruptExt;
use embassy::util::Signal;

use crate::fmt::{assert, *};
use crate::hal::pac;
use crate::hal::prelude::*;
use crate::hal::target_constants::EASY_DMA_SIZE;
use crate::interrupt;
use crate::interrupt::Interrupt;

pub use crate::hal::uarte::Pins;
// Re-export SVD variants to allow user to directly set values.
pub use pac::uarte0::{baudrate::BAUDRATE_A as Baudrate, config::PARITY_A as Parity};

/// Interface to the UARTE peripheral
pub struct Uarte<T>
where
    T: Instance,
{
    instance: T,
    irq: T::Interrupt,
    pins: Pins,
}

pub struct State {
    tx_done: Signal<()>,
    rx_done: Signal<u32>,
}

impl<T> Uarte<T>
where
    T: Instance,
{
    /// Creates the interface to a UARTE instance.
    /// Sets the baud rate, parity and assigns the pins to the UARTE peripheral.
    ///
    /// # Safety
    ///
    /// The returned API is safe unless you use `mem::forget` (or similar safe mechanisms)
    /// on stack allocated buffers which which have been passed to [`send()`](Uarte::send)
    /// or [`receive`](Uarte::receive).
    #[allow(unused_unsafe)]
    pub unsafe fn new(
        uarte: T,
        irq: T::Interrupt,
        mut pins: Pins,
        parity: Parity,
        baudrate: Baudrate,
    ) -> Self {
        assert!(uarte.enable.read().enable().is_disabled());

        uarte.psel.rxd.write(|w| {
            unsafe { w.bits(pins.rxd.psel_bits()) };
            w.connect().connected()
        });

        pins.txd.set_high().unwrap();
        uarte.psel.txd.write(|w| {
            unsafe { w.bits(pins.txd.psel_bits()) };
            w.connect().connected()
        });

        // Optional pins
        uarte.psel.cts.write(|w| {
            if let Some(ref pin) = pins.cts {
                unsafe { w.bits(pin.psel_bits()) };
                w.connect().connected()
            } else {
                w.connect().disconnected()
            }
        });

        uarte.psel.rts.write(|w| {
            if let Some(ref pin) = pins.rts {
                unsafe { w.bits(pin.psel_bits()) };
                w.connect().connected()
            } else {
                w.connect().disconnected()
            }
        });

        uarte.baudrate.write(|w| w.baudrate().variant(baudrate));
        uarte.config.write(|w| w.parity().variant(parity));

        // Enable interrupts
        uarte.events_endtx.reset();
        uarte.events_endrx.reset();
        uarte
            .intenset
            .write(|w| w.endtx().set().txstopped().set().endrx().set().rxto().set());

        // Register ISR
        irq.set_handler(Self::on_irq);
        irq.unpend();
        irq.enable();

        Uarte {
            instance: uarte,
            irq,
            pins,
        }
    }

    pub fn free(self) -> (T, T::Interrupt, Pins) {
        // Wait for the peripheral to be disabled from the ISR.
        while self.instance.enable.read().enable().is_enabled() {}
        (self.instance, self.irq, self.pins)
    }

    fn enable(&mut self) {
        trace!("enable");
        self.instance.enable.write(|w| w.enable().enabled());
    }

    fn tx_started(&self) -> bool {
        self.instance.events_txstarted.read().bits() != 0
    }

    fn rx_started(&self) -> bool {
        self.instance.events_rxstarted.read().bits() != 0
    }

    unsafe fn on_irq(_ctx: *mut ()) {
        let uarte = &*pac::UARTE0::ptr();

        let mut try_disable = false;

        if uarte.events_endtx.read().bits() != 0 {
            uarte.events_endtx.reset();
            trace!("endtx");
            compiler_fence(Ordering::SeqCst);

            if uarte.events_txstarted.read().bits() != 0 {
                // The ENDTX was signal triggered because DMA has finished.
                uarte.events_txstarted.reset();
                try_disable = true;
            }

            T::state().tx_done.signal(());
        }

        if uarte.events_txstopped.read().bits() != 0 {
            uarte.events_txstopped.reset();
            trace!("txstopped");
            try_disable = true;
        }

        if uarte.events_endrx.read().bits() != 0 {
            uarte.events_endrx.reset();
            trace!("endrx");
            let len = uarte.rxd.amount.read().bits();
            compiler_fence(Ordering::SeqCst);

            if uarte.events_rxstarted.read().bits() != 0 {
                // The ENDRX was signal triggered because DMA buffer is full.
                uarte.events_rxstarted.reset();
                try_disable = true;
            }

            T::state().rx_done.signal(len);
        }

        if uarte.events_rxto.read().bits() != 0 {
            uarte.events_rxto.reset();
            trace!("rxto");
            try_disable = true;
        }

        // Disable the peripheral if not active.
        if try_disable
            && uarte.events_txstarted.read().bits() == 0
            && uarte.events_rxstarted.read().bits() == 0
        {
            trace!("disable");
            uarte.enable.write(|w| w.enable().disabled());
        }
    }
}

impl<T: Instance> embassy::traits::uart::Uart for Uarte<T> {
    type ReceiveFuture<'a> = ReceiveFuture<'a, T>;
    type SendFuture<'a> = SendFuture<'a, T>;

    /// Sends serial data.
    ///
    /// `tx_buffer` is marked as static as per `embedded-dma` requirements.
    /// It it safe to use a buffer with a non static lifetime if memory is not
    /// reused until the future has finished.
    fn send<'a>(&'a mut self, tx_buffer: &'a [u8]) -> SendFuture<'a, T> {
        // Panic if TX is running which can happen if the user has called
        // `mem::forget()` on a previous future after polling it once.
        assert!(!self.tx_started());

        T::state().tx_done.reset();

        SendFuture {
            uarte: self,
            buf: tx_buffer,
        }
    }

    /// Receives serial data.
    ///
    /// The future is pending until the buffer is completely filled.
    /// A common pattern is to use [`stop()`](ReceiveFuture::stop) to cancel
    /// unfinished transfers after a timeout to prevent lockup when no more data
    /// is incoming.
    ///
    /// `rx_buffer` is marked as static as per `embedded-dma` requirements.
    /// It it safe to use a buffer with a non static lifetime if memory is not
    /// reused until the future has finished.
    fn receive<'a>(&'a mut self, rx_buffer: &'a mut [u8]) -> ReceiveFuture<'a, T> {
        // Panic if RX is running which can happen if the user has called
        // `mem::forget()` on a previous future after polling it once.
        assert!(!self.rx_started());

        T::state().rx_done.reset();

        ReceiveFuture {
            uarte: self,
            buf: rx_buffer,
        }
    }
}

/// Future for the [`Uarte::send()`] method.
pub struct SendFuture<'a, T>
where
    T: Instance,
{
    uarte: &'a mut Uarte<T>,
    buf: &'a [u8],
}

impl<'a, T> Drop for SendFuture<'a, T>
where
    T: Instance,
{
    fn drop(self: &mut Self) {
        if self.uarte.tx_started() {
            trace!("stoptx");

            // Stop the transmitter to minimize the current consumption.
            self.uarte.instance.events_txstarted.reset();
            self.uarte
                .instance
                .tasks_stoptx
                .write(|w| unsafe { w.bits(1) });

            // TX is stopped almost instantly, spinning is fine.
            while !T::state().tx_done.signaled() {}
        }
    }
}

impl<'a, T> Future for SendFuture<'a, T>
where
    T: Instance,
{
    type Output = Result<(), embassy::traits::uart::Error>;

    fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let Self { uarte, buf } = unsafe { self.get_unchecked_mut() };

        if T::state().tx_done.poll_wait(cx).is_pending() {
            let ptr = buf.as_ptr();
            let len = buf.len();
            assert!(len <= EASY_DMA_SIZE);
            // TODO: panic if buffer is not in SRAM

            uarte.enable();

            compiler_fence(Ordering::SeqCst);
            uarte
                .instance
                .txd
                .ptr
                .write(|w| unsafe { w.ptr().bits(ptr as u32) });
            uarte
                .instance
                .txd
                .maxcnt
                .write(|w| unsafe { w.maxcnt().bits(len as _) });

            trace!("starttx");
            uarte.instance.tasks_starttx.write(|w| unsafe { w.bits(1) });
            while !uarte.tx_started() {} // Make sure transmission has started

            Poll::Pending
        } else {
            Poll::Ready(Ok(()))
        }
    }
}

/// Future for the [`Uarte::receive()`] method.
pub struct ReceiveFuture<'a, T>
where
    T: Instance,
{
    uarte: &'a mut Uarte<T>,
    buf: &'a mut [u8],
}

impl<'a, T> Drop for ReceiveFuture<'a, T>
where
    T: Instance,
{
    fn drop(self: &mut Self) {
        if self.uarte.rx_started() {
            trace!("stoprx (drop)");

            self.uarte.instance.events_rxstarted.reset();
            self.uarte
                .instance
                .tasks_stoprx
                .write(|w| unsafe { w.bits(1) });

            embassy_extras::low_power_wait_until(|| T::state().rx_done.signaled())
        }
    }
}

impl<'a, T> Future for ReceiveFuture<'a, T>
where
    T: Instance,
{
    type Output = Result<(), embassy::traits::uart::Error>;

    fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let Self { uarte, buf } = unsafe { self.get_unchecked_mut() };

        match T::state().rx_done.poll_wait(cx) {
            Poll::Pending if !uarte.rx_started() => {
                let ptr = buf.as_ptr();
                let len = buf.len();
                assert!(len <= EASY_DMA_SIZE);

                uarte.enable();

                compiler_fence(Ordering::SeqCst);
                uarte
                    .instance
                    .rxd
                    .ptr
                    .write(|w| unsafe { w.ptr().bits(ptr as u32) });
                uarte
                    .instance
                    .rxd
                    .maxcnt
                    .write(|w| unsafe { w.maxcnt().bits(len as _) });

                trace!("startrx");
                uarte.instance.tasks_startrx.write(|w| unsafe { w.bits(1) });
                while !uarte.rx_started() {} // Make sure reception has started

                Poll::Pending
            }
            Poll::Pending => Poll::Pending,
            Poll::Ready(_) => Poll::Ready(Ok(())),
        }
    }
}

/// Future for the [`receive()`] method.
impl<'a, T> ReceiveFuture<'a, T>
where
    T: Instance,
{
    /// Stops the ongoing reception and returns the number of bytes received.
    pub async fn stop(self) -> usize {
        let len = if self.uarte.rx_started() {
            trace!("stoprx (stop)");

            self.uarte.instance.events_rxstarted.reset();
            self.uarte
                .instance
                .tasks_stoprx
                .write(|w| unsafe { w.bits(1) });
            T::state().rx_done.wait().await
        } else {
            // Transfer was stopped before it even started. No bytes were sent.
            0
        };
        len as _
    }
}

mod private {
    pub trait Sealed {}
}

pub trait Instance:
    Deref<Target = pac::uarte0::RegisterBlock> + Sized + private::Sealed + 'static
{
    type Interrupt: Interrupt;

    #[doc(hidden)]
    fn state() -> &'static State;
}

static UARTE0_STATE: State = State {
    tx_done: Signal::new(),
    rx_done: Signal::new(),
};
impl private::Sealed for pac::UARTE0 {}
impl Instance for pac::UARTE0 {
    type Interrupt = interrupt::UARTE0_UART0;

    fn state() -> &'static State {
        &UARTE0_STATE
    }
}

#[cfg(any(feature = "52833", feature = "52840", feature = "9160"))]
static UARTE1_STATE: State = State {
    tx_done: Signal::new(),
    rx_done: Signal::new(),
};
#[cfg(any(feature = "52833", feature = "52840", feature = "9160"))]
impl private::Sealed for pac::UARTE1 {}
#[cfg(any(feature = "52833", feature = "52840", feature = "9160"))]
impl Instance for pac::UARTE1 {
    type Interrupt = interrupt::UARTE1;

    fn state() -> &'static State {
        &UARTE1_STATE
    }
}