Skip to content

Commit

Permalink
Lock the serial port
Browse files Browse the repository at this point in the history
  • Loading branch information
lukipuki committed Oct 24, 2023
1 parent 0239627 commit f30e168
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions rust/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_serial::{SerialPortBuilderExt, SerialStream};

struct AsyncSerial {
serial: SerialStream,
serial: tokio::sync::Mutex<SerialStream>,
}

#[derive(thiserror::Error, Debug)]
Expand All @@ -21,25 +21,30 @@ impl AsyncSerial {
fn new(port: &str) -> Result<Self, serialport::Error> {
let builder = tokio_serial::new(port, 115200);
let serial = builder.open_native_async()?;
Ok(Self { serial })
Ok(Self {
serial: tokio::sync::Mutex::new(serial),
})
}

async fn call_with_timeout(
&mut self,
command: &str,
timeout: f64,
) -> Result<Vec<String>, AsyncSerialError> {
self.serial
let mut serial = self.serial.lock().await;
serial
.write(format!("{command}\r\n").as_bytes())
.await
.map_err(|e| AsyncSerialError::WriteError(Box::new(e)))?;

let mut buffer = Vec::with_capacity(256);
let result = tokio::time::timeout(
Duration::from_micros((timeout * 1_000_000.0).trunc() as u64),
self.serial.read_buf(&mut buffer),
serial.read_buf(&mut buffer),
)
.await;
std::mem::drop(serial);

match result {
Ok(read_result) => match read_result {
Ok(_) => {
Expand Down

0 comments on commit f30e168

Please sign in to comment.