1
Fork 0

Convert keys to iterator

This commit is contained in:
Jake Howard 2024-09-21 11:56:04 +01:00
parent 205ad360a6
commit 6098ff699e
Signed by: jake
GPG key ID: 57AFB45680EDD477

View file

@ -1,5 +1,5 @@
use regex::Regex; use regex::Regex;
use serialport::{SerialPortInfo, SerialPortType}; use serialport::{SerialPort, SerialPortInfo, SerialPortType};
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::time::Duration; use std::time::Duration;
@ -19,6 +19,21 @@ fn get_board_port() -> Option<SerialPortInfo> {
None None
} }
fn get_keys(conn: Box<dyn SerialPort>) -> impl Iterator<Item = String> {
let reader = BufReader::new(conn);
let key_re = Regex::new(r"key '(?P<key>[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() { fn main() {
let board_port = match get_board_port() { let board_port = match get_board_port() {
Some(p) => p, Some(p) => p,
@ -34,26 +49,7 @@ fn main() {
.open() .open()
.unwrap(); .unwrap();
let reader = BufReader::new(conn); for key in get_keys(conn) {
println!("Key pressed: {}", key);
let key_re = Regex::new(r"key '(?P<key>[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);
}
}
} }
} }