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
#![deny(missing_docs)]
mod error;
pub mod mock;
#[cfg(test)]
mod tests;
pub use crate::error::*;
use serial::prelude::*;
use std::cell::RefCell;
use std::io::prelude::*;
use std::time::Duration;
pub struct Connection {
pub stream: Box<Stream>,
}
impl Connection {
pub fn new(stream: Box<Stream>) -> Connection {
Connection { stream }
}
pub fn from_path(
bus: &str,
settings: serial::PortSettings,
timeout: Duration,
) -> UartResult<Connection> {
Ok(Connection {
stream: Box::new(SerialStream::new(bus, settings, timeout)?),
})
}
pub fn write(&self, data: &[u8]) -> UartResult<()> {
self.stream.write(data)
}
pub fn read(&self, len: usize, timeout: Duration) -> UartResult<Vec<u8>> {
self.stream.read(len, timeout)
}
}
pub trait Stream: Send {
fn write(&self, data: &[u8]) -> UartResult<()>;
fn read(&self, len: usize, timeout: Duration) -> UartResult<Vec<u8>>;
}
struct SerialStream {
port: RefCell<serial::SystemPort>,
timeout: Duration,
}
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,
})
}
}
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)
}
}