Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove busy wait on serial port monitor #11

Merged
merged 1 commit into from
Nov 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bestool/src/cmds/serial_monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub fn cmd_serial_port_monitor(port_name: String, baud_rate: u32) {
// Eventually we will hook in extra utility commands
println!("Opening serial monitor to {port_name} @ {baud_rate}");
let serial_port = serialport::new(port_name, baud_rate);

match serial_port.open() {
Ok(port) => {
let _ = run_serial_monitor(port);
Expand Down
25 changes: 15 additions & 10 deletions bestool/src/serial_monitor/monitor.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
use serialport::SerialPort;
use std::cmp::min;
use std::error::Error;
use std::io::{stdout, Read, Write};
use std::thread::sleep;
use std::{error::Error, time::Duration};
use std::time::Duration;

pub fn run_serial_monitor(mut port: Box<dyn SerialPort>) -> Result<(), Box<dyn Error>> {
// Until exit, read from the port and display; and send back anything the user types to the uart
// Except we catch an exit combo
port.set_timeout(Duration::from_millis(1000))
.expect("Setting port read timeout failed");
const BUFFER_SIZE: usize = 128;
let mut read_buffer = [0; BUFFER_SIZE];
loop {
if port.bytes_to_read()? > 0 {
match port.read(&mut read_buffer) {
Ok(bytes_read) => {
let mut out = stdout();
let _ = out.write(&read_buffer[0..min(bytes_read, BUFFER_SIZE)])?;
match port.read(&mut read_buffer) {
Ok(bytes_read) => {
let mut out = stdout();
let _ = out.write(&read_buffer[0..min(bytes_read, BUFFER_SIZE)])?;
}
Err(e) => {
match e.kind() {
std::io::ErrorKind::TimedOut => { /*No-op for timeouts */ }
_ => {
println!("Error reading from port {e:?}")
}
}
Err(e) => println!("Error reading from port {e:?}"),
}
} else {
sleep(Duration::from_millis(50));
}
}
}