From 27559a8d319c3621942c8a8c3dbab5b1a801f537 Mon Sep 17 00:00:00 2001 From: Jacob Weaver Date: Thu, 19 Dec 2024 09:52:40 -0600 Subject: [PATCH] added serial --- Cargo.toml | 1 + rfe/Cargo.toml | 3 ++- rfe/src/lib.rs | 1 + rfe/src/serial.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 rfe/src/serial.rs diff --git a/Cargo.toml b/Cargo.toml index e6a4fd3..cc888d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,3 +24,4 @@ bincode = { version = "2.0.0-rc.3", default-features = false, features = [ simple_logger = "5.0.0" rp2040-hal = "0.10.2" rp2040-pac = "0.6.0" +mio-serial = "=5.0.5" diff --git a/rfe/Cargo.toml b/rfe/Cargo.toml index a9e339e..6c034ad 100644 --- a/rfe/Cargo.toml +++ b/rfe/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [features] default = [] -std = ["dep:mio"] +std = ["dep:mio", "dep:mio-serial"] rp2040 = ["dep:rp2040-hal", "dep:rp2040-pac"] reflect = [] @@ -18,3 +18,4 @@ mio = { version = "1.0.2", features = ["net", "os-poll"], optional = true } rp2040-hal = { workspace = true, optional = true } rp2040-pac = { workspace = true, optional = true } macros.path = "macros" +mio-serial = { workspace = true, optional = true } diff --git a/rfe/src/lib.rs b/rfe/src/lib.rs index 93e0546..9a23f69 100644 --- a/rfe/src/lib.rs +++ b/rfe/src/lib.rs @@ -14,6 +14,7 @@ pub use rfe::*; pub mod reflect; pub use macros; +pub mod serial; pub mod time; pub mod utils; diff --git a/rfe/src/serial.rs b/rfe/src/serial.rs new file mode 100644 index 0000000..6197a80 --- /dev/null +++ b/rfe/src/serial.rs @@ -0,0 +1,55 @@ +use anyhow::Result; + +pub trait SerialPort { + fn open(&mut self) -> Result<()>; + fn write(&mut self, bytes: &[u8]) -> Result; + fn read(&mut self, bytes: &mut [u8]) -> Result; +} + +#[cfg(feature = "std")] +mod serial_std { + use std::io::{Read, Write}; + + use anyhow::anyhow; + use mio_serial::{SerialPortBuilder, SerialPortBuilderExt, SerialStream}; + pub struct StdSerialPort { + config: SerialPortBuilder, + serial: Option, + } + + impl StdSerialPort { + pub fn new(config: SerialPortBuilder) -> Self { + Self { + config, + serial: None, + } + } + } + + impl super::SerialPort for StdSerialPort { + fn open(&mut self) -> anyhow::Result<()> { + self.serial = None; + self.serial = Some(self.config.clone().open_native_async()?); + return Ok(()); + } + + fn write(&mut self, bytes: &[u8]) -> anyhow::Result { + Ok(self + .serial + .as_mut() + .ok_or(anyhow!("port not open"))? + .write(bytes)?) + } + + fn read(&mut self, bytes: &mut [u8]) -> anyhow::Result { + Ok(self + .serial + .as_mut() + .ok_or(anyhow!("port not open"))? + .read(bytes)?) + } + } +} + +#[cfg(feature = "std")] +pub use serial_std::*;