diff --git a/src/main.rs b/src/main.rs index e6ff267..db0d7f6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ use regex::Regex; -use serialport::{SerialPortInfo, SerialPortType}; +use serialport::{SerialPort, SerialPortInfo, SerialPortType}; use std::io::{BufRead, BufReader}; use std::time::Duration; @@ -19,6 +19,21 @@ fn get_board_port() -> Option { None } +fn get_keys(conn: Box) -> impl Iterator { + let reader = BufReader::new(conn); + let key_re = Regex::new(r"key '(?P[A-Z])' pressed").unwrap(); + + reader.lines().filter_map(move |l| { + if let Ok(msg) = l { + return key_re + .captures(&msg) + .and_then(|captures| captures.name("key")) + .map(|k| String::from(k.as_str())); + } + None + }) +} + fn main() { let board_port = match get_board_port() { Some(p) => p, @@ -34,26 +49,7 @@ fn main() { .open() .unwrap(); - let reader = BufReader::new(conn); - - let key_re = Regex::new(r"key '(?P[A-Z])' pressed").unwrap(); - - for l in reader.lines() { - match l { - Ok(msg) => { - let captures = match key_re.captures(&msg) { - None => continue, - Some(c) => c, - }; - - println!("Key pressed: {}", &captures["key"]); - } - // Ignore any timeouts - Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {} - // Show errors, but keep going - Err(e) => { - dbg!(e); - } - } + for key in get_keys(conn) { + println!("Key pressed: {}", key); } }