serialport-rs icon indicating copy to clipboard operation
serialport-rs copied to clipboard

Windows: write() blocks if nothing is connected to the port

Open jessebraham opened this issue 3 years ago • 1 comments

This issue was migrated from GitLab. The original issue can be found here: https://gitlab.com/susurrus/serialport-rs/-/issues/84

Thank you for your work on this library. But I ran into a small showstopper :(

I've only tested this on windows so far, so maybe the situation is different on Linux.

I have set up a virtual port pair COM10 <-> COM20 via com0com. I'm trying to write some bytes to COM10. When nothing is connected to COM20 write() just blocks forever. As soon as I connect to COM20 with HTerm I receive the bytes and my rust program continues running.

I would expect write() to either fail with an error or return with Ok(0) if nothing is connected to COM20. Otherwise there is no way for me to handle the case that the device isn't plugged in.

edit: Serial port settings:

  • timout: 500 ms
  • baud rate: 9600
  • parity: None
  • data bits: Eight
  • stop bits: One
  • flow control: Software
let buffer_size = buffer.len();
let mut total_bytes_written = 0;

loop {
    let bytes_written = serial_port_guard.write(&buffer[total_bytes_written..buffer_size]).map_err(|e| {
        log::error!("Failed to write bytes to serial port: {}", e);
        TokioError::new(TokioErrorKind::NotFound, e.to_string())
    })?;
    if bytes_written == 0 {
        let msg = "Can't write to serial port";
        log::error!("{}", msg);
        return Err(TokioError::new(TokioErrorKind::NotConnected, msg));
    }
    total_bytes_written += bytes_written;
    if total_bytes_written >= buffer_size {
        break;
    }
}

jessebraham avatar Feb 07 '22 21:02 jessebraham

@jessebraham, this was causing an issue for me too. I resolved by updating set_timeout to set both the read and write timeouts. Probably better to update api to set these independently tho

ThomasRizzo avatar May 19 '23 11:05 ThomasRizzo