-
Notifications
You must be signed in to change notification settings - Fork 223
/
console.rs
35 lines (31 loc) · 1.08 KB
/
console.rs
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
use anyhow::Context as _;
use std::io::Read as _;
use std::io::Write as _;
pub fn open(port: &std::path::Path, baudrate: u32) -> anyhow::Result<()> {
let mut rx = serialport::new(port.to_string_lossy(), baudrate)
.timeout(std::time::Duration::from_secs(2))
.open_native()
.with_context(|| format!("failed to open serial port `{}`", port.display()))?;
let mut tx = rx.try_clone_native()?;
let mut stdin = std::io::stdin();
let mut stdout = std::io::stdout();
// Spawn a thread for the receiving end because stdio is not portably non-blocking...
std::thread::spawn(move || loop {
let mut buf = [0u8; 4098];
match rx.read(&mut buf) {
Ok(count) => {
stdout.write(&buf[..count]).unwrap();
stdout.flush().unwrap();
}
Err(e) => {
assert!(e.kind() == std::io::ErrorKind::TimedOut);
}
}
});
loop {
let mut buf = [0u8; 4098];
let count = stdin.read(&mut buf)?;
tx.write(&buf[..count])?;
tx.flush()?;
}
}