From 3ec62449c85853f01fc7a524cd69eb9dcc098243 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" <5425387+Ralim@users.noreply.github.com> Date: Sun, 26 Nov 2023 12:44:53 +1100 Subject: [PATCH] Remove wait on serial port monitor (#11) --- bestool/src/cmds/serial_monitor.rs | 1 + bestool/src/serial_monitor/monitor.rs | 25 +++++++++++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/bestool/src/cmds/serial_monitor.rs b/bestool/src/cmds/serial_monitor.rs index 78e7fe8..d881742 100644 --- a/bestool/src/cmds/serial_monitor.rs +++ b/bestool/src/cmds/serial_monitor.rs @@ -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); diff --git a/bestool/src/serial_monitor/monitor.rs b/bestool/src/serial_monitor/monitor.rs index 5302b90..56c2d34 100644 --- a/bestool/src/serial_monitor/monitor.rs +++ b/bestool/src/serial_monitor/monitor.rs @@ -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) -> Result<(), Box> { // 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)); } } }