From cf8c624099d0f621f9662d35a7e81ab94fb1ccec Mon Sep 17 00:00:00 2001 From: Frederik Menke Date: Mon, 17 Oct 2022 22:56:46 +0200 Subject: [PATCH] Move printer code to lib --- red/src/lib.rs | 1 + red/src/main.rs | 70 ++-------------------------------------- red/src/printer/mod.rs | 73 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 68 deletions(-) create mode 100644 red/src/lib.rs create mode 100644 red/src/printer/mod.rs diff --git a/red/src/lib.rs b/red/src/lib.rs new file mode 100644 index 0000000..568ce22 --- /dev/null +++ b/red/src/lib.rs @@ -0,0 +1 @@ +pub mod printer; \ No newline at end of file diff --git a/red/src/main.rs b/red/src/main.rs index 075327e..7ed9230 100644 --- a/red/src/main.rs +++ b/red/src/main.rs @@ -1,76 +1,10 @@ #![warn(rust_2018_idioms)] -use futures::stream::StreamExt; -use futures::sink::SinkExt; -use std::{env, io, str, fmt::Write}; -use tokio_util::codec::{Decoder, Encoder}; - -use bytes::BytesMut; -use tokio_serial::SerialPortBuilderExt; - -#[cfg(unix)] -const DEFAULT_TTY: &str = "/dev/ttyUSB0"; -#[cfg(windows)] -const DEFAULT_TTY: &str = "COM1"; - -struct LineCodec; - -impl Decoder for LineCodec { - type Item = String; - type Error = io::Error; - - fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { - let newline = src.as_ref().iter().position(|b| *b == b'\n'); - if let Some(n) = newline { - let line = src.split_to(n + 1); - return match str::from_utf8(line.as_ref()) { - Ok(s) => Ok(Some(s.to_string())), - Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Invalid String")), - }; - } - Ok(None) - } -} - -impl Encoder for LineCodec { - type Error = io::Error; - - fn encode(&mut self, item: String, dst: &mut BytesMut) -> Result<(), Self::Error> { - dst.write_str(&item) - .map_err(|e| {io::Error::new(io::ErrorKind::InvalidData, e.to_string())})?; - Ok(()) - } -} +use red::printer; #[tokio::main] async fn main() -> tokio_serial::Result<()> { - let mut args = env::args(); - let tty_path = args.nth(1).unwrap_or_else(|| DEFAULT_TTY.into()); - - let mut port = tokio_serial::new(tty_path, 115200).open_native_async() - .expect("Unable to open serial port"); - - #[cfg(unix)] - port.set_exclusive(false) - .expect("Unable to set serial port exclusive to false"); - - let (mut writer, mut reader) = LineCodec.framed(port).split(); - println!("Starting read."); - let reader_task = async move { - let mut counter = 0; - while let Some(line_result) = reader.next().await { - let line = line_result.expect("Failed to read line"); - if line.contains("ok") || line.contains("Loaded") { - if let Err(e) = writer.send("M114\n".into()).await { - println!("{:?}", e); - break; - } - } - counter += 1; - println!("updates received: {}", counter); - } - }; - reader_task.await; + printer::communicate().await?; Ok(()) } \ No newline at end of file diff --git a/red/src/printer/mod.rs b/red/src/printer/mod.rs new file mode 100644 index 0000000..6e8d11d --- /dev/null +++ b/red/src/printer/mod.rs @@ -0,0 +1,73 @@ +use futures::stream::StreamExt; +use futures::sink::SinkExt; +use std::{env, io, str, fmt::Write}; +use tokio_util::codec::{Decoder, Encoder}; + +use bytes::BytesMut; +use tokio_serial::SerialPortBuilderExt; + +#[cfg(unix)] +const DEFAULT_TTY: &str = "/dev/ttyUSB0"; +#[cfg(windows)] +const DEFAULT_TTY: &str = "COM1"; + +struct LineCodec; + +impl Decoder for LineCodec { + type Item = String; + type Error = io::Error; + + fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { + let newline = src.as_ref().iter().position(|b| *b == b'\n'); + if let Some(n) = newline { + let line = src.split_to(n + 1); + return match str::from_utf8(line.as_ref()) { + Ok(s) => Ok(Some(s.to_string())), + Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Invalid String")), + }; + } + Ok(None) + } +} + +impl Encoder for LineCodec { + type Error = io::Error; + + fn encode(&mut self, item: String, dst: &mut BytesMut) -> Result<(), Self::Error> { + dst.write_str(&item) + .map_err(|e| {io::Error::new(io::ErrorKind::InvalidData, e.to_string())})?; + Ok(()) + } +} + +pub async fn communicate() -> tokio_serial::Result<()> { + let mut args = env::args(); + let tty_path = args.nth(1).unwrap_or_else(|| DEFAULT_TTY.into()); + + let mut port = tokio_serial::new(tty_path, 115200).open_native_async() + .expect("Unable to open serial port"); + + #[cfg(unix)] + port.set_exclusive(false) + .expect("Unable to set serial port exclusive to false"); + + let (mut writer, mut reader) = LineCodec.framed(port).split(); + println!("Starting read."); + let reader_task = async move { + let mut counter = 0; + while let Some(line_result) = reader.next().await { + let line = line_result.expect("Failed to read line"); + if line.contains("ok") || line.contains("Loaded") { + if let Err(e) = writer.send("M114\n".into()).await { + println!("{:?}", e); + break; + } + } + counter += 1; + println!("updates received: {}", counter); + } + }; + reader_task.await; + + Ok(()) +} \ No newline at end of file