Created
August 23, 2020 00:54
-
-
Save alairock/2886f72e309a0970c548f78543374288 to your computer and use it in GitHub Desktop.
Serial Reader in Rust with cli for selecting open ports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [dependencies] | |
// serialport = "3.3.0" | |
// dialoguer = "0.6.2" | |
use serialport::{available_ports, SerialPortType}; | |
use crate::serial; | |
use dialoguer::theme::ColorfulTheme; | |
use dialoguer::Select; | |
use std::io; | |
pub fn get_avail_ports() -> Vec<String> { | |
let avail_ports: Vec<String> = match available_ports() { | |
Ok(ports) => { | |
let mut avail_port_paths = Vec::new(); | |
for p in ports { | |
match p.port_type { | |
SerialPortType::UsbPort(_info) => { | |
avail_port_paths.push(p.port_name.clone()); | |
} | |
_ => {} | |
} | |
} | |
match avail_port_paths.len() { | |
0 => println!("No ports found."), | |
1 => println!("Found 1 port:"), | |
n => println!("Found {} ports:", n), | |
}; | |
avail_port_paths | |
} | |
Err(e) => { | |
eprintln!("{:?}", e); | |
eprintln!("Error listing serial ports"); | |
Vec::new() | |
} | |
}; | |
avail_ports | |
} | |
fn serial_reader() { | |
let baud_rate = 115200; | |
let available_ports = &serial::get_avail_ports(); | |
let mut selections = Vec::new(); | |
for s in available_ports{ | |
selections.push(String::from(s)); | |
} | |
selections.push(String::from("/dev/null")); | |
let selection = Select::with_theme(&ColorfulTheme::default()) | |
.with_prompt("Pick your flavor") | |
.default(0) | |
.items(&selections[..]) | |
.interact() | |
.unwrap(); | |
println!("I picked: {}", selections[selection]); | |
let mut settings: serialport::SerialPortSettings = Default::default(); | |
settings.baud_rate = baud_rate; | |
match serialport::open_with_settings(&selections[selection], &settings) { | |
Ok(mut port) => { | |
let mut serial_buf: Vec<u8> = vec![0; 1000]; | |
println!("Receiving data on {} at {} baud:", &selections[selection], &baud_rate); | |
loop { | |
match port.read(serial_buf.as_mut_slice()) { | |
Ok(t) => io::stdout().write_all(&serial_buf[..t]).unwrap(), | |
Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (), | |
Err(e) => { | |
if e.kind() == BrokenPipe { | |
eprintln!("It appears the device is no longer connected."); | |
std::process::exit(1); | |
} | |
eprintln!("{:?}", e); | |
}, | |
} | |
} | |
} | |
Err(e) => { | |
eprintln!("Failed to open \"{}\". Error: {}", selections[selection], e); | |
std::process::exit(1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment