From 090b7d8df6b9f9c4fd0e2feec5a5ccbbfdc03500 Mon Sep 17 00:00:00 2001 From: Federico Lolli <federico.lolli@skywarder.eu> Date: Mon, 22 Jan 2024 16:04:50 +0100 Subject: [PATCH] fixed workflow and implemented RTC and CTS control over communication availability --- src/main.rs | 61 +++++++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 21 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3b1706e..47d4b0c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,17 +2,17 @@ mod ffi; use std::fs::File; use std::io; -use std::io::{Read, Write}; +use std::io::Read; use std::path::PathBuf; use std::time::{Duration, Instant}; use clap::Parser; -use log::{debug, error, info, trace}; +use log::{debug, error, info, warn}; use serialport::SerialPort; use ffi::MavlinkPayloadFlightTM; -const EOT: u8 = 0x04; +const ACK: u8 = 0x06; #[derive(Debug, Parser)] struct Cli { @@ -72,29 +72,48 @@ fn main() { let mut buffer = [0u8; 1000]; let mut start: Option<Instant> = None; let mut times = Vec::new(); + loop { - match port.read(&mut buffer) { - Ok(t) => { - // check if we got the signal to start sending data - let eot_f = buffer[..t].contains(&EOT); - - // if we got the signal to start sending data, send it - if eot_f { - trace!("got EOT, sending data"); - if let Some(packet) = packets.wait_next() { - if let Some(t) = start { - times.push(t.elapsed().as_millis()); - } - start = Some(Instant::now()); - write_port.write_packet(packet.to_owned()); - debug!("sent packet ({}/{})", packets.index, packets.packets.len()); - } else { + // wait clear to send + port.write_request_to_send(true).expect("Unable to set RTS"); + while !port.read_clear_to_send().expect("Unable to read CTS") { + std::thread::sleep(Duration::from_millis(100)); + debug!("waiting for CTS"); + } + + // send packet if there is one + if let Some(packet) = packets.wait_next() { + if let Some(t) = start { + times.push(t.elapsed().as_millis()); + } + start = Some(Instant::now()); + write_port.write_packet(packet.to_owned()); + debug!("sent packet ({}/{})", packets.index, packets.packets.len()); + port.write_request_to_send(false) + .expect("Unable to set RTS"); + } else { + break; + } + + // wait ACK + loop { + match port.read(&mut buffer) { + Ok(t) => { + // if didn't get the signal then print the buffer and exit with error + if buffer[..t].contains(&ACK) { break; + } else { + warn!("didn't get the signal"); + std::thread::sleep(Duration::from_millis(100)); + // eprintln!("{}", String::from_utf8_lossy(&buffer[..t])); } } + Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (), + Err(e) => { + error!("FATAL: {:?}", e); + std::process::exit(1); + } } - Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (), - Err(e) => error!("{:?}", e), } } -- GitLab