Convert keys to iterator
This commit is contained in:
parent
205ad360a6
commit
6098ff699e
1 changed files with 18 additions and 22 deletions
40
src/main.rs
40
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<SerialPortInfo> {
|
|||
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() {
|
||||
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<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);
|
||||
}
|
||||
}
|
||||
for key in get_keys(conn) {
|
||||
println!("Key pressed: {}", key);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue