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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use std::io::{self, Read};
use std::rc::Rc;
use std::time::Duration;

use anyhow::Result;
use clap::Args;
use serde::{Deserialize, Serialize};
pub use serialport::Parity;
use thiserror::Error;

use super::nonblocking_help::{NoNonblockingHelp, NonblockingHelp};
use crate::app::TransportWrapper;
use crate::impl_serializable_error;
use crate::io::console::ConsoleDevice;
use crate::transport::TransportError;

#[derive(Clone, Debug, Args, Serialize, Deserialize)]
pub struct UartParams {
    /// UART instance.
    #[arg(long, default_value = "CONSOLE")]
    uart: String,

    /// UART baudrate.
    #[arg(long)]
    baudrate: Option<u32>,

    /// Enable software flow control.
    #[arg(long)]
    flow_control: bool,
}

impl UartParams {
    pub fn create(&self, transport: &TransportWrapper) -> Result<Rc<dyn Uart>> {
        let uart = transport.uart(&self.uart)?;
        if let Some(baudrate) = self.baudrate {
            uart.set_baudrate(baudrate)?;
        }
        log::info!("set_flow_control to {}", self.flow_control);
        uart.set_flow_control(self.flow_control)?;
        Ok(uart)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum FlowControl {
    // No flow control.
    None = 0,
    // Pause aka XOFF aka Ctrl-S ("Stop")
    Pause = 19,
    // Resume aka XON aka Ctrl-Q ("Quit Stopping")
    Resume = 17,
}

/// A trait which represents a UART.
pub trait Uart {
    /// Returns the UART baudrate.  May return zero for virtual UARTs.
    fn get_baudrate(&self) -> Result<u32>;

    /// Sets the UART baudrate.  May do nothing for virtual UARTs.
    fn set_baudrate(&self, baudrate: u32) -> Result<()>;

    /// Enables software flow control for `write`s.
    fn set_flow_control(&self, flow_control: bool) -> Result<()> {
        if flow_control {
            unimplemented!();
        }
        Ok(())
    }

    /// Reads UART receive data into `buf`, returning the number of bytes read.
    /// This function _may_ block.
    fn read(&self, buf: &mut [u8]) -> Result<usize>;

    /// Reads UART receive data into `buf`, returning the number of bytes read.
    /// The `timeout` may be used to specify a duration to wait for data.
    /// If timeout expires without any data arriving `Ok(0)` will be returned, never `Err(_)`.
    fn read_timeout(&self, buf: &mut [u8], timeout: Duration) -> Result<usize>;

    /// Writes data from `buf` to the UART.
    fn write(&self, buf: &[u8]) -> Result<()>;

    /// Clears the UART RX buffer.
    fn clear_rx_buffer(&self) -> Result<()> {
        // Keep reading while until the RX buffer is empty.
        // Note: This default implementation is overriden in backends where we can do better.
        const TIMEOUT: Duration = Duration::from_millis(5);
        let mut buf = [0u8; 256];
        while self.read_timeout(&mut buf, TIMEOUT)? > 0 {}
        Ok(())
    }

    fn set_break(&self, _enable: bool) -> Result<()> {
        Err(TransportError::UnsupportedOperation.into())
    }

    fn set_parity(&self, _parity: Parity) -> Result<()> {
        Err(TransportError::UnsupportedOperation.into())
    }

    /// Query if nonblocking mio mode is supported.
    fn supports_nonblocking_read(&self) -> Result<bool> {
        Ok(false)
    }

    /// Switch this `Uart` instance into nonblocking mio mode.  Going forward, `read()` should
    /// only be called after `mio::poll()` has indicated that the given `Token` is ready.
    fn register_nonblocking_read(
        &self,
        _registry: &mio::Registry,
        _token: mio::Token,
    ) -> Result<()> {
        unimplemented!();
    }

    /// Get the same single `NonblockingHelp` object as from top level `Transport.nonblocking_help()`.
    fn nonblocking_help(&self) -> Result<Rc<dyn NonblockingHelp>> {
        Ok(Rc::new(NoNonblockingHelp))
    }
}

impl Read for &dyn Uart {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        Uart::read(&**self, buf).map_err(io::Error::other)
    }
}

impl<'a> ConsoleDevice for dyn Uart + 'a {
    fn console_read(&self, buf: &mut [u8], timeout: Duration) -> Result<usize> {
        self.read_timeout(buf, timeout)
    }

    fn console_write(&self, buf: &[u8]) -> Result<()> {
        self.write(buf)
    }

    fn set_break(&self, enable: bool) -> Result<()> {
        <Self as Uart>::set_break(self, enable)
    }

    fn supports_nonblocking_read(&self) -> Result<bool> {
        self.supports_nonblocking_read()
    }

    fn register_nonblocking_read(&self, registry: &mio::Registry, token: mio::Token) -> Result<()> {
        self.register_nonblocking_read(registry, token)
    }

    fn nonblocking_help(&self) -> Result<Rc<dyn NonblockingHelp>> {
        self.nonblocking_help()
    }
}

/// Errors related to the UART interface.
#[derive(Error, Debug, Serialize, Deserialize)]
pub enum UartError {
    #[error("Enumerating: {0}")]
    EnumerationError(String),
    #[error("Opening: {0}")]
    OpenError(String),
    #[error("Invalid option: {0}")]
    InvalidOption(String),
    #[error("Invalid speed: {0}")]
    InvalidSpeed(u32),
    #[error("Reading: {0}")]
    ReadError(String),
    #[error("Writing: {0}")]
    WriteError(String),
    #[error("{0}")]
    GenericError(String),
}
impl_serializable_error!(UartError);