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
use radio_api::{Connection, RadioResult, Stream};
use serial;
use std::io;
use std::time::Duration;
pub fn serial_connection() -> Connection {
Connection::new(Box::new(SerialStream {}))
}
struct SerialStream {}
impl Stream for SerialStream {
fn write(&self, data: &[u8]) -> RadioResult<()> {
Ok(serial_send(data)?)
}
fn read(&self) -> RadioResult<Vec<u8>> {
Ok(serial_receive()?)
}
}
fn serial_send(data: &[u8]) -> io::Result<()> {
use serial::prelude::*;
use std::io::prelude::*;
let mut port = try!(serial::open("/dev/ttyUSB0"));
let settings: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud38400,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
try!(port.configure(&settings));
try!(port.set_timeout(Duration::from_secs(1)));
let be_data = {
let mut v = Vec::<u8>::new();
for i in 0..data.len() {
v.push(data[i].to_be());
}
v
};
try!(port.flush());
try!(port.write(&be_data[..]));
Ok(())
}
fn serial_receive() -> io::Result<Vec<u8>> {
use serial::prelude::*;
use std::io::prelude::*;
let mut ret_msg: Vec<u8> = Vec::new();
let mut port = try!(serial::open("/dev/ttyUSB0"));
let settings: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud38400,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
try!(port.configure(&settings));
try!(port.set_timeout(Duration::from_millis(100)));
let mut tries = 0;
loop {
let mut read_buffer: Vec<u8> = vec![0; 1];
match port.read(&mut read_buffer[..]) {
Ok(c) => {
if c > 0 {
ret_msg.extend(read_buffer);
} else {
tries = tries + 1;
}
}
Err(_) => break,
};
if tries > 5 {
break;
}
}
Ok(ret_msg)
}