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
use serialport::SerialPort;
use log::*;
use std::thread;
use std::thread::JoinHandle;
use core::convert::TryFrom;
use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError};
use std::io::ErrorKind;
pub mod common_types;
pub use common_types::*;
#[derive(Debug)]
pub enum SerialFrameError {
CouldNotStart,
CouldNotSendStop,
SerialportDisconnected,
SerialThreadPaniced,
ReceiverDropped,
FailedConversion(Vec<u8>),
}
pub type Result<T> = core::result::Result<T, SerialFrameError>;
pub struct SerialFrameStopper {
handle: JoinHandle<()>,
stopsender: Sender<()>,
}
impl SerialFrameStopper {
pub fn stop(self) -> Result<()> {
self.stopsender
.send(())
.map_err(|_e| SerialFrameError::CouldNotSendStop)?;
self.handle
.join()
.map_err(|_e| SerialFrameError::SerialThreadPaniced)?;
Ok(())
}
}
pub struct SerialFrameSender {
separator: u8,
port: Box<dyn SerialPort>,
error_tx: Option<Sender<SerialFrameError>>,
}
impl SerialFrameSender {
pub fn new(separator: u8, port: Box<dyn SerialPort>) -> SerialFrameSender {
Self {
separator,
port,
error_tx: None,
}
}
pub fn add_error_channel(&mut self) -> Receiver<SerialFrameError> {
let (tx, rx) = unbounded();
self.error_tx = Some(tx);
rx
}
pub fn start<T: 'static + Send + TryFrom<Vec<u8>>>(
mut self,
type_send: Sender<T>,
) -> Result<SerialFrameStopper> {
let (stoptx, stoprx) = unbounded();
let handle = thread::Builder::new()
.name("SerialFrameSender".to_string())
.spawn(move || {
let mut buf: Vec<u8> = Vec::new();
let mut serial_byte = [0; 10240];
'thread: loop {
match stoprx.try_recv() {
Err(TryRecvError::Empty) => {
match self.port.read(&mut serial_byte[..]) {
Ok(n) => {
buf.extend_from_slice(&serial_byte[..n]);
}
Err(ref e) if e.kind() == ErrorKind::TimedOut => {
trace!("{}", e);
}
Err(e) => {
error!("{}", e);
if let Some(send) = &self.error_tx {
let res =
send.send(SerialFrameError::SerialportDisconnected);
if let Err(e) = res {
error!("Could not send error, quitting: {}", e);
}
}
break 'thread;
}
}
while let Some(end) = buf.iter().position(|&f| f == self.separator) {
trace!("end: {}", end);
let frame: Vec<u8> = buf.drain(..end + 1).collect();
trace!("frame: {:?}", frame);
if let Ok(framed) = T::try_from(frame.clone()) {
let res = type_send.send(framed);
if let Err(e) = res {
error!("Could not send frame, quitting: {}", e);
if let Some(send) = self.error_tx {
let _res = send.send(SerialFrameError::ReceiverDropped);
}
break 'thread;
}
} else {
if let Some(send) = &self.error_tx {
let res = send.send(SerialFrameError::FailedConversion(
frame.clone(),
));
if let Err(e) = res {
error!("Could not send frame, quitting: {}", e);
break 'thread;
}
}
}
}
}
Err(TryRecvError::Disconnected) => {
info!("Thread handle was dropped");
if let Some(panic) = &self.error_tx {
let _ = panic.send(SerialFrameError::ReceiverDropped);
}
}
_ => {
info!("Thread got stop request");
break 'thread;
}
}
}
});
let handle = handle.map_err(|_e| SerialFrameError::CouldNotStart)?;
let stopsend = SerialFrameStopper {
handle,
stopsender: stoptx,
};
Ok(stopsend)
}
pub fn stop(&mut self) -> () {}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}