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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! UART peripheral control
//!
//! Controls the 3 uart peripherals (UART0, UART1, UART2).
//!
//! # Example
//!
//! Creation of the serial peripheral and writing formatted info.
//! ```
//! let serial: Serial<_, _, _> = Serial::new(
//!     dp.UART0,
//!     esp32_hal::serial::Pins {
//!         tx: gpios.gpio1,
//!         rx: gpios.gpio3,
//!         cts: None,
//!         rts: None,
//!     },
//!     config,
//!     clkcntrl_config,
//!     &mut dport,
//!     )
//!     .unwrap();
//!
//! writeln!(serial, "Serial output").unwrap();
//! ```
//!
//! # TODO
//! - Add all extra features esp32 supports (eg rs485, etc. etc.)
//! - Free APB lock when TX is idle (and no RX used)
//! - Address errata 3.17: UART fifo_cnt is inconsistent with FIFO pointer

use core::{convert::Infallible, marker::PhantomData};

use crate::gpio::{InputPin, OutputPin};
use crate::prelude::*;

use embedded_hal::serial;

const UART_FIFO_SIZE: u8 = 128;

/// Serial error
#[derive(Debug)]
pub enum Error {
    /// Framing error
    Framing,
    /// Noise error
    Noise,
    /// RX buffer overrun
    Overrun,
    /// Parity check error
    Parity,
    /// Baudrate too low
    BaudrateTooLow,
    /// Baudrate too high
    BaudrateTooHigh,
}

/// Interrupt event
pub enum Event {
    /// New data has been received
    Rxne,
    /// New data can be sent
    Txe,
    /// Idle line state detected
    Idle,
}

/// UART configuration
pub mod config {
    use crate::units::*;

    /// Number of data bits
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum DataBits {
        DataBits5,
        DataBits6,
        DataBits7,
        DataBits8,
    }

    /// Parity check
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum Parity {
        ParityNone,
        ParityEven,
        ParityOdd,
    }

    /// Number of stop bits
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    pub enum StopBits {
        /// 1 stop bit
        STOP1,
        /// 1.5 stop bits
        STOP1P5,
        /// 2 stop bits
        STOP2,
    }

    /// UART configuration
    #[derive(Debug, Copy, Clone)]
    pub struct Config {
        pub baudrate: Hertz,
        pub data_bits: DataBits,
        pub parity: Parity,
        pub stop_bits: StopBits,
    }

    impl Config {
        pub fn baudrate(mut self, baudrate: Hertz) -> Self {
            self.baudrate = baudrate;
            self
        }

        pub fn parity_none(mut self) -> Self {
            self.parity = Parity::ParityNone;
            self
        }

        pub fn parity_even(mut self) -> Self {
            self.parity = Parity::ParityEven;
            self
        }

        pub fn parity_odd(mut self) -> Self {
            self.parity = Parity::ParityOdd;
            self
        }

        pub fn data_bits(mut self, data_bits: DataBits) -> Self {
            self.data_bits = data_bits;
            self
        }

        pub fn stop_bits(mut self, stop_bits: StopBits) -> Self {
            self.stop_bits = stop_bits;
            self
        }
    }

    impl Default for Config {
        fn default() -> Config {
            Config {
                baudrate: Hertz(19_200),
                data_bits: DataBits::DataBits8,
                parity: Parity::ParityNone,
                stop_bits: StopBits::STOP1,
            }
        }
    }
}

/// Pins used by the UART interface
///
/// Note that any two pins may be used
pub struct Pins<
    TX: OutputPin,
    RX: InputPin,
    // default pins to allow type inference
    CTS: InputPin = crate::gpio::Gpio19<crate::gpio::Input<crate::gpio::Floating>>,
    RTS: OutputPin = crate::gpio::Gpio22<crate::gpio::Output<crate::gpio::PushPull>>,
> {
    pub tx: TX,
    pub rx: RX,
    pub cts: Option<CTS>,
    pub rts: Option<RTS>,
}

use private::Instance;

/// Serial abstraction
///
pub struct Serial<
    UART: Instance,
    TX: OutputPin,
    RX: InputPin,
    // default pins to allow type inference
    CTS: InputPin = crate::gpio::Gpio19<crate::gpio::Input<crate::gpio::Floating>>,
    RTS: OutputPin = crate::gpio::Gpio22<crate::gpio::Output<crate::gpio::PushPull>>,
> {
    uart: UART,
    pins: Pins<TX, RX, CTS, RTS>,
    clock_control: crate::clock_control::ClockControlConfig,
    rx: Rx<UART>,
    tx: Tx<UART>,
}

/// Serial receiver
pub struct Rx<UART: Instance> {
    _uart: PhantomData<UART>,
    apb_lock: Option<crate::clock_control::dfs::LockAPB>,
}

/// Serial transmitter
pub struct Tx<UART: Instance> {
    _uart: PhantomData<UART>,
    apb_lock: Option<crate::clock_control::dfs::LockAPB>,
}

impl<UART: Instance, TX: OutputPin, RX: InputPin, CTS: InputPin, RTS: OutputPin>
    Serial<UART, TX, RX, CTS, RTS>
{
    /// Create a new serial driver
    pub fn new(
        uart: UART,
        pins: Pins<TX, RX, CTS, RTS>,
        config: config::Config,
        clock_control: crate::clock_control::ClockControlConfig,
    ) -> Result<Self, Error> {
        let mut serial = Serial {
            uart,
            pins,
            clock_control,
            rx: Rx {
                _uart: PhantomData,
                apb_lock: None,
            },
            tx: Tx {
                _uart: PhantomData,
                apb_lock: None,
            },
        };

        serial.uart.init_pins(&mut serial.pins);
        serial.uart.reset().enable();
        serial.reset_rx_fifo();
        serial.reset_tx_fifo();
        serial
            .change_stop_bits(config.stop_bits)
            .change_data_bits(config.data_bits)
            .change_parity(config.parity)
            .change_baudrate(config.baudrate)?;
        Ok(serial)
    }

    /// Change the number of stop bits
    pub fn change_stop_bits(&mut self, stop_bits: config::StopBits) -> &mut Self {
        //workaround for hardware issue, when UART stop bit set as 2-bit mode.
        self.uart
            .rs485_conf
            .modify(|_, w| w.dl1_en().bit(stop_bits == config::StopBits::STOP2));

        self.uart.conf0.modify(|_, w| match stop_bits {
            config::StopBits::STOP1 => w.stop_bit_num().stop_bits_1(),
            config::StopBits::STOP1P5 => w.stop_bit_num().stop_bits_1p5(),
            //workaround for hardware issue, when UART stop bit set as 2-bit mode.
            config::StopBits::STOP2 => w.stop_bit_num().stop_bits_1(),
        });

        self
    }

    /// Change the number of data bits
    pub fn change_data_bits(&mut self, data_bits: config::DataBits) -> &mut Self {
        self.uart.conf0.modify(|_, w| match data_bits {
            config::DataBits::DataBits5 => w.bit_num().data_bits_5(),
            config::DataBits::DataBits6 => w.bit_num().data_bits_6(),
            config::DataBits::DataBits7 => w.bit_num().data_bits_7(),
            config::DataBits::DataBits8 => w.bit_num().data_bits_8(),
        });

        self
    }

    /// Change the type of parity checking
    pub fn change_parity(&mut self, parity: config::Parity) -> &mut Self {
        self.uart.conf0.modify(|_, w| match parity {
            config::Parity::ParityNone => w.parity_en().clear_bit(),
            config::Parity::ParityEven => w.parity_en().set_bit().parity().clear_bit(),
            config::Parity::ParityOdd => w.parity_en().set_bit().parity().set_bit(),
        });

        self
    }

    /// Change the baudrate.
    ///
    /// Will automatically select the clock source. When possible the reference clock (1MHz) will
    /// be used, because this is constant when the clock source/frequency changes.
    /// However if one of the clock frequencies is below 10MHz or if the baudrate is above
    /// the reference clock or if the baudrate cannot be set within 1.5%
    /// then use the APB clock.
    pub fn change_baudrate<T: Into<Hertz> + Copy>(
        &mut self,
        baudrate: T,
    ) -> Result<&mut Self, Error> {
        let mut use_apb_frequency = false;

        // if APB frequency is <10MHz the ref clock is no longer accurate
        // or if the baudrate > Ref frequency then use the APB frequency
        if !self.clock_control.is_ref_clock_stable()
            || baudrate.into() > self.clock_control.ref_frequency()
        {
            use_apb_frequency = true;
        } else if baudrate.into() < self.clock_control.apb_frequency_apb_locked() / (1 << 20 - 1) {
            // if baudrate is lower then can be achieved via the APB frequency
            use_apb_frequency = false;
        } else {
            let clk_div =
                (self.clock_control.ref_frequency() * 16 + baudrate.into() / 2) / baudrate.into();
            // if baudrate too high use APB clock
            if clk_div == 0 {
                use_apb_frequency = true
            } else {
                // if baudrate cannot be reached within 1.5% use APB frequency
                // use 203 as multiplier (2*101.5), because 1Mhz * 16 * 203 still fits in 2^32
                let calc_baudrate = (self.clock_control.ref_frequency() * 16 * 200) / clk_div;
                if calc_baudrate > baudrate.into() * 203 || calc_baudrate < baudrate.into() * 197 {
                    use_apb_frequency = true;
                }
            }
        }

        self.change_baudrate_force_clock(baudrate, use_apb_frequency)
    }

    /// Change the baudrate choosing the reference or APB clock manually
    pub fn change_baudrate_force_clock<T: Into<Hertz> + Copy>(
        &mut self,
        baudrate: T,
        use_apb_frequency: bool,
    ) -> Result<&mut Self, Error> {
        if let None = self.rx.apb_lock {
            if use_apb_frequency {
                self.rx.apb_lock = Some(self.clock_control.lock_apb_frequency());
                self.tx.apb_lock = Some(self.clock_control.lock_apb_frequency());
            }
        } else {
            if !use_apb_frequency {
                self.rx.apb_lock = None;
                self.tx.apb_lock = None;
            }
        }

        // set clock source
        self.uart
            .conf0
            .modify(|_, w| w.tick_ref_always_on().bit(use_apb_frequency));

        let sclk_freq = if use_apb_frequency {
            self.clock_control.apb_frequency_apb_locked()
        } else {
            self.clock_control.ref_frequency()
        };

        // calculate nearest divider
        let clk_div = (sclk_freq * 16 + baudrate.into() / 2) / baudrate.into();

        if clk_div == 0 {
            return Err(Error::BaudrateTooHigh);
        }
        if clk_div > (1 << 24) - 1 {
            return Err(Error::BaudrateTooLow);
        }

        unsafe {
            self.uart.clkdiv.modify(|_, w| {
                w.clkdiv()
                    .bits(clk_div >> 4)
                    .clkdiv_frag()
                    .bits((clk_div & 0xf) as u8)
            })
        };

        Ok(self)
    }

    /// Returns if the reference or APB clock is used
    pub fn is_clock_apb(&self) -> bool {
        self.uart.conf0.read().tick_ref_always_on().bit_is_set()
    }

    /// Returns the current baudrate
    pub fn baudrate(&self) -> Hertz {
        let use_apb_frequency = self.uart.conf0.read().tick_ref_always_on().bit_is_set();
        let sclk_freq = if use_apb_frequency {
            self.clock_control.apb_frequency()
        } else {
            self.clock_control.ref_frequency()
        };
        let div = self.uart.clkdiv.read().clkdiv().bits() << 4
            | (self.uart.clkdiv.read().clkdiv_frag().bits() as u32);

        // round to nearest integer baudrate
        (sclk_freq * 16 + Hertz(div / 2)) / div
    }

    /// Starts listening for an interrupt event
    pub fn listen(&mut self, _event: Event) {
        unimplemented!();
    }

    /// Stop listening for an interrupt event
    pub fn unlisten(&mut self, _event: Event) {
        unimplemented!();
    }

    /// Return true if the receiver is idle
    pub fn is_rx_idle(&self) -> bool {
        self.uart.status.read().st_urx_out().is_rx_idle()
    }

    /// Return true if the transmitter is idle
    pub fn is_tx_idle(&self) -> bool {
        self.uart.status.read().st_utx_out().is_tx_idle()
    }

    /// Split the serial driver in separate TX and RX drivers
    pub fn split(self) -> (Tx<UART>, Rx<UART>) {
        (self.tx, self.rx)
    }

    /// Release the UART and GPIO resources
    pub fn release(self) -> (UART, Pins<TX, RX, CTS, RTS>) {
        (self.uart, self.pins)
    }

    pub fn reset_rx_fifo(&mut self) {
        // Hardware issue: rxfifo_rst does not work properly;
        while self.uart.status.read().rxfifo_cnt().bits() != 0
            || (self.uart.mem_rx_status.read().mem_rx_rd_addr().bits()
                != self.uart.mem_rx_status.read().mem_rx_wr_addr().bits())
        {
            self.rx.read().unwrap();
        }
    }

    pub fn reset_tx_fifo(&self) {
        self.uart.conf0.write(|w| w.txfifo_rst().set_bit());
        self.uart.conf0.write(|w| w.txfifo_rst().clear_bit());
    }
}

impl<UART: Instance, TX: OutputPin, RX: InputPin, CTS: InputPin, RTS: OutputPin> serial::Read<u8>
    for Serial<UART, TX, RX, CTS, RTS>
{
    type Error = Infallible;

    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        self.rx.read()
    }
}

impl<UART: Instance, TX: OutputPin, RX: InputPin, CTS: InputPin, RTS: OutputPin> serial::Write<u8>
    for Serial<UART, TX, RX, CTS, RTS>
{
    type Error = Infallible;

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

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        self.tx.write(byte)
    }
}

impl<UART: Instance, TX: OutputPin, RX: InputPin, CTS: InputPin, RTS: OutputPin> core::fmt::Write
    for Serial<UART, TX, RX, CTS, RTS>
{
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        use embedded_hal::serial::Write;
        s.as_bytes()
            .iter()
            .try_for_each(|c| nb::block!(self.write(*c)))
            .map_err(|_| core::fmt::Error)
    }
}

impl<UART: Instance> Rx<UART> {
    /// Get count of bytes in the receive FIFO
    pub fn count(&self) -> u8 {
        unsafe { (*UART::ptr()).status.read().rxfifo_cnt().bits() }
    }

    /// Check if the receivers is idle
    pub fn is_idle(&self) -> bool {
        unsafe { (*UART::ptr()).status.read().st_urx_out().is_rx_idle() }
    }
}

impl<UART: Instance> serial::Read<u8> for Rx<UART> {
    type Error = Infallible;

    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        if self.count() == 0 {
            Err(nb::Error::WouldBlock)
        } else {
            Ok(unsafe { (*UART::ptr()).rx_fifo.read().bits() })
        }
    }
}

impl<UART: Instance> Tx<UART> {
    /// Get count of bytes in the transmitter FIFO
    pub fn count(&self) -> u8 {
        unsafe { (*UART::ptr()).status.read().txfifo_cnt().bits() }
    }

    /// Check if the transmitter is idle
    pub fn is_idle(&self) -> bool {
        unsafe { (*UART::ptr()).status.read().st_utx_out().is_tx_idle() }
    }
}

impl<UART: Instance> serial::Write<u8> for Tx<UART> {
    type Error = Infallible;

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        if self.is_idle() {
            Ok(())
        } else {
            Err(nb::Error::WouldBlock)
        }
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        if self.count() < UART_FIFO_SIZE {
            unsafe { (*UART::ptr()).tx_fifo.write_with_zero(|w| w.bits(byte)) }
            Ok(())
        } else {
            Err(nb::Error::WouldBlock)
        }
    }
}

impl<UART: Instance> core::fmt::Write for Tx<UART>
where
    Tx<UART>: embedded_hal::serial::Write<u8>,
{
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        use embedded_hal::serial::Write;
        s.as_bytes()
            .iter()
            .try_for_each(|c| nb::block!(self.write(*c)))
            .map_err(|_| core::fmt::Error)
    }
}

mod private {

    use super::Pins;
    use crate::gpio::{InputPin, InputSignal, OutputPin, OutputSignal};
    use crate::prelude::*;
    use crate::target::{uart, UART0, UART1, UART2};
    use core::ops::Deref;

    pub trait Instance: Deref<Target = uart::RegisterBlock> {
        fn ptr() -> *const uart::RegisterBlock;
        /// Enable peripheral
        fn enable(&mut self) -> &mut Self;
        /// Disable peripheral
        fn disable(&mut self) -> &mut Self;
        /// Reset peripheral
        fn reset(&mut self) -> &mut Self;

        /// Initialize pins
        fn init_pins<TX: OutputPin, RX: InputPin, CTS: InputPin, RTS: OutputPin>(
            &mut self,
            pins: &mut Pins<TX, RX, CTS, RTS>,
        ) -> &mut Self;
    }

    macro_rules! halUart {
        ($(
            $UARTX:ident: ($txd:ident, $rxd:ident, $cts:ident, $rts:ident),
        )+) => {
            $(
                impl Instance for $UARTX {
                    fn ptr() -> *const uart::RegisterBlock {
                        $UARTX::ptr()
                    }

                    fn reset(&mut self) -> &mut Self {
                        dport::reset_peripheral(Peripheral::$UARTX);
                        self
                    }

                    fn enable(&mut self) -> &mut Self {
                        dport::enable_peripheral(Peripheral::$UARTX);
                        self
                    }

                    fn disable(&mut self) -> &mut Self {
                        dport::disable_peripheral(Peripheral::$UARTX);
                        self

                    }

                    fn init_pins<TX: OutputPin, RX: InputPin, CTS: InputPin, RTS: OutputPin>(
                        &mut self, pins: &mut Pins<TX,RX,CTS,RTS>
                    ) -> &mut Self {
                        pins
                            .tx
                            .set_to_push_pull_output()
                            .connect_peripheral_to_output(OutputSignal::$txd);

                        pins
                            .rx
                            .set_to_input()
                            .connect_input_to_peripheral(InputSignal::$rxd);

                        if let Some(cts) = pins.cts.as_mut() {
                            cts
                            .set_to_input()
                            .connect_input_to_peripheral(InputSignal::$cts);
                        }

                        if let Some(rts) = pins.rts.as_mut() {
                            rts
                            .set_to_push_pull_output()
                            .connect_peripheral_to_output(OutputSignal::$rts);
                        }
                        self
                    }
                }
            )+
        }
    }

    halUart! {
        UART0: (U0TXD, U0RXD, U0CTS, U0RTS),
        UART1: (U1TXD, U1RXD, U1CTS, U1RTS),
        UART2: (U2TXD, U2RXD, U2CTS, U2RTS),
    }
}