From 70d55e909de6b29ff179750b5742d01c17b39f48 Mon Sep 17 00:00:00 2001 From: finga Date: Fri, 22 Apr 2022 00:16:22 +0200 Subject: [PATCH] Read linewise from serial port --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + src/main.rs | 33 ++++++++++----------------------- 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab9d474..9a86816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "anyhow" +version = "1.0.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" + [[package]] name = "autocfg" version = "1.1.0" @@ -119,6 +125,7 @@ dependencies = [ name = "mightyohm-gc-exporter" version = "0.1.0-dev" dependencies = [ + "anyhow", "serialport", ] diff --git a/Cargo.toml b/Cargo.toml index d46d6a9..69355f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,4 +9,5 @@ keywords = ["prometheus", "metrics"] categories = ["api-bindings", "command-line-utilities", "visualization"] [dependencies] +anyhow = "1.0" serialport = "4.1" diff --git a/src/main.rs b/src/main.rs index fdcda0a..2b4638e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,34 +1,21 @@ +use anyhow::Result; use std::{ - io::{self, Write}, + io::{BufRead, BufReader}, time::Duration, }; -fn main() { +fn main() -> Result<()> { let port_name = "/dev/serial0"; let baud_rate = 9600; let port = serialport::new(port_name, baud_rate) - .timeout(Duration::from_millis(100)) - .open(); + .timeout(Duration::from_millis(1000)) + .open()?; - match port { - Ok(mut port) => { - let mut serial_buf: Vec = vec![0; 1000]; - println!("Receiving data on {} at {} baud:", &port_name, &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) => { - eprintln!("Failed to read \"{}\". Error: {}", port_name, e); - ::std::process::exit(1); - } - } - } - } - Err(e) => { - eprintln!("Failed to open \"{}\". Error: {}", port_name, e); - ::std::process::exit(1); - } + let mut port = BufReader::new(port); + loop { + let mut line = String::new(); + port.read_line(&mut line)?; + println!("{:?}", line); } }