Can't read from serial port immediately unless buffer size is 1

Hello, I am new to rust, I am trying to write a Tauri app that reads data from the serial port, writes it to a file. This much I have accomplished, but the data is only written to the file immediately if I have a buffer size of 1. I am receiving data from a proprietary radio and I was told that a buffer size of one will be too slow to keep up.

The second I make this buffer size any bigger, it waits until a certain amount of new bytes have come in before writing to the file (not even the same size as the buffer), so I always get data cutoff, until the next burst of data comes in from the serialport.

Any help is greatly appreciated!

TLDR; How do I make this code write to a file immediately even with a buffer size of [0,1024] (without waiting for the buffer to be full).


#[tauri::command]
fn read_from_port(port_name: String, baud_rate: u32) -> Result<(), String> {

  let running = RUNNING.clone();
  running.store(true, Ordering::Relaxed);

  thread::spawn(move || {
    let mut port = match serialport::new(&port_name, baud_rate).open() {
      Ok(port) => port,
      Err(e) => {
        println!("Error opening port: {}", e);
        return;
      }
    };

    let output_path = Path::new("A:/tauri/tauri-dev/output.txt");
    let mut file = match OpenOptions::new().write(true).append(true).open(&output_path) {
      Ok(file) => file,
      Err(e) => {
        println!("Error opening file: {}", e);
        return;
      }
    };

    let mut small_buffer: [u8; 1] = [0; 1];

    loop {

      if !running.load(Ordering::Relaxed) {
        break;
      }

      match port.read(&mut small_buffer) {
        Ok(n) => {
          if let Err(e) = file.write_all(&small_buffer[..n]) {
            println!("Error writing to file: {}", e);
            return;
          }
        },
        Err(e) => {
          println!("Error reading from port: {}", e);
          return;
        }
      }
    }
  });

  Ok(())
}

Is this on windows? Windows has very unusual serial port behavior due to default settings. The python serial port libraries all tend to configure windows to behave more like posix systems wrt how serial ports function. But serial port rust crates do not do this for the most part.

I know this one does however, or at least makes it easier to configure the behavior:

This issue goes into some of the insanity on windows serial ports:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.