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
//
// Copyright (C) 2018 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#![deny(missing_docs)]

//! A generalized HAL for communicating over serial ports

mod error;
pub mod mock;
#[cfg(test)]
mod tests;

pub use crate::error::*;
#[cfg(feature = "nos3")]
use nosengine_rust::client::uart;
#[cfg(not(feature = "nos3"))]
use serial::prelude::*;
use std::cell::RefCell;
#[allow(unused_imports)]
use std::io::prelude::*;
use std::time::Duration;
#[cfg(feature = "nos3")]
use std::{sync, thread, time::Instant};

/// Wrapper for UART stream
pub struct Connection {
    /// Any boxed stream that allows for communication over serial ports
    pub stream: Box<dyn Stream>,
}

impl Connection {
    /// Constructor to creation connection with provided stream
    pub fn new(stream: Box<dyn Stream>) -> Connection {
        Connection { stream }
    }

    /// Convenience constructor to create connection from bus path
    pub fn from_path(
        bus: &str,
        settings: serial::PortSettings,
        timeout: Duration,
    ) -> UartResult<Connection> {
        Ok(Connection {
            stream: Box::new(SerialStream::new(bus, settings, timeout)?),
        })
    }

    /// Writes out raw bytes to the stream
    pub fn write(&self, data: &[u8]) -> UartResult<()> {
        self.stream.write(data)
    }

    /// Reads messages upto specified length recieved on the bus
    pub fn read(&self, len: usize, timeout: Duration) -> UartResult<Vec<u8>> {
        self.stream.read(len, timeout)
    }
}

/// This trait is used to represent streams and allows for mocking for api unit tests
pub trait Stream: Send {
    /// Write raw bytes to stream
    fn write(&self, data: &[u8]) -> UartResult<()>;

    /// Read upto a specified amount of raw bytes from the stream
    fn read(&self, len: usize, timeout: Duration) -> UartResult<Vec<u8>>;
}

// This is the actual stream that data is tranferred over
#[cfg(not(feature = "nos3"))]
struct SerialStream {
    port: RefCell<serial::SystemPort>,
    timeout: Duration,
}

#[cfg(not(feature = "nos3"))]
impl SerialStream {
    fn new(bus: &str, settings: serial::PortSettings, timeout: Duration) -> UartResult<Self> {
        let mut port = serial::open(bus)?;

        port.configure(&settings)?;

        Ok(SerialStream {
            port: RefCell::new(port),
            timeout,
        })
    }
}

// Read and write implementations for the serial stream
#[cfg(not(feature = "nos3"))]
impl Stream for SerialStream {
    fn write(&self, data: &[u8]) -> UartResult<()> {
        let mut port = self
            .port
            .try_borrow_mut()
            .map_err(|_| UartError::PortBusy)?;
        port.set_timeout(self.timeout)?;

        port.write_all(data)?;

        Ok(())
    }

    fn read(&self, len: usize, timeout: Duration) -> UartResult<Vec<u8>> {
        let mut port = self
            .port
            .try_borrow_mut()
            .map_err(|_| UartError::PortBusy)?;

        port.set_timeout(timeout)?;

        let mut response: Vec<u8> = vec![0; len];

        port.read_exact(response.as_mut_slice())?;

        Ok(response)
    }
}

#[cfg(feature = "nos3")]
struct SerialStream {
    port: sync::Arc<sync::Mutex<uart::UART>>,
    min_timeout: Duration,
}

#[cfg(feature = "nos3")]
impl SerialStream {
    fn new(bus: &str, _settings: serial::PortSettings, _timeout: Duration) -> UartResult<Self> {
        let mut config = (include_str!("../../SimConfig.toml"))
            .parse::<toml::Value>()?
            .try_into::<toml::value::Table>()?;

        let connection = config
            .remove("connection")
            .ok_or(UartError::GenericError)?
            .try_into::<String>()?;

        let nodename = config
            .remove("nodename")
            .ok_or(UartError::GenericError)?
            .try_into::<String>()?;

        let busname = config
            .remove("busnames")
            .ok_or(UartError::GenericError)?
            .try_into::<toml::value::Table>()?
            .remove("uart")
            .ok_or(UartError::GenericError)?
            .try_into::<toml::value::Table>()?
            .remove(bus)
            .ok_or(UartError::GenericError)?
            .try_into::<String>()?;

        let min_timeout = config
            .remove("min_timeout")
            .ok_or(UartError::GenericError)?
            .try_into::<i64>()?;

        let port = uart::UART::new(nodename.as_str(), connection.as_str(), busname.as_str(), 1)?;
        Ok(SerialStream {
            port: sync::Arc::new(sync::Mutex::new(port)),
            min_timeout: Duration::from_millis(min_timeout as u64),
        })
    }
}

#[cfg(feature = "nos3")]
impl Stream for SerialStream {
    fn write(&self, data: &[u8]) -> UartResult<()> {
        match self.port.lock() {
            Ok(port) => {
                port.write(data);
                Ok(())
            }
            Err(e) => Err(UartError::from(e)),
        }
    }

    fn read(&self, len: usize, timeout: Duration) -> UartResult<Vec<u8>> {
        let timeout = if timeout < self.min_timeout {
            self.min_timeout
        } else {
            timeout
        };

        let (tx, rx) = sync::mpsc::channel::<Vec<u8>>();
        let port = self.port.clone();

        // Because NOSEngine doesn't support timeouts, I have to roll my own timeout
        thread::spawn(move || {
            let port = port.lock().unwrap();
            let mut data: Vec<u8> = port.read(len);
            let start = Instant::now();
            // When reading from a NOSEngine port, it never blocks. This means it often returns
            // zero bytes. However, the real UART port blocks until it either reads the requested
            // number of bytes or times out. So to emulate that behavior, I poll the NOSEngine
            // port until I either get the requested number of bytes or time out.
            while data.len() < len && Instant::now() - start < timeout {
                let mut newdata = port.read(len);
                data.append(&mut newdata);
                thread::sleep(Duration::from_millis(100))
            }
            tx.send(data).unwrap();
        });

        let result = rx.recv()?;
        if result.len() < len {
            let description = String::from("UART Read timed out");
            Err(UartError::IoError {
                cause: std::io::ErrorKind::TimedOut,
                description,
            })
        } else {
            Ok(result)
        }
    }
}