After dropping lock serialport is still locked

I have a Tauri app that is opening a connection to a serial port over USB and am having problems with freeing up the port once I am done. I have this code to drop the connection:

pub async fn drop_connection<R: Runtime>(
    serial_state: State<'_, SerialState>,
    window: Window<R>,
) -> Result<String, SerialError> {
    let guard = serial_state.connection.lock().await;
    drop(guard);
}

The serial connection is defined here:

pub struct SerialState {
    pub port: Arc<Mutex<String>>,
    pub connection: Arc<Mutex<Option<Box<dyn serialport::SerialPort>>>>,
    pub baud_rate: u32,
    pub ports: Arc<Mutex<Vec<SerialPort>>>,
}

Everything works well on Mac but on Windows after dropping my connection and trying to re-connect I am seeing:

'COM4': Access is denied.

It looks like the port is still locked by my program. Are there any suggestions on where I am going wrong? Thanks!

The lock is not for the serial port, but for a Mutex that controls access to a handle to a connection. This handle stays there anyway, presumably still owning the port, after you unlock the mutex.

You could drop the handle by setting *guard = None;.

1 Like

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.