slowtec/tokio-modbus

Although disconnect the context, the SerialStream reopen error

ileon opened this issue · 1 comments

ileon commented
use anyhow::Result;
use tokio_modbus::prelude::*;
use tokio_modbus::{client::rtu, Slave};
use tokio_serial::SerialStream;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
    {
        let builder = tokio_serial::new("COM9", 9600);
        let port = SerialStream::open(&builder)?;
        let mut ctx1 = rtu::attach_slave(port, Slave(1));
        let rsp1 = ctx1.read_holding_registers(1, 2).await;
        println!("rsp1: {:?}", rsp1);
        ctx1.disconnect().await?;
    }
    let builder = tokio_serial::new("COM9", 9600);
    let port_try_open = SerialStream::open(&builder);
    let port = match port_try_open {
        Ok(p) => p,
        Err(err) => {
            println!("Re-open Error: {:?}", err);
            panic!();
        }
    };
    let mut ctx2 = rtu::attach_slave(port, Slave(2));
    let rsp2 = ctx2.read_holding_registers(1, 2).await;
    println!("rsp2: {:?}", rsp2);

    Ok(())
}

The error message is :

rsp1: Ok([250, 1])
Re-open Error: Error { kind: NoDevice, description: "Access is denied." }

Please help to check how to re-build another new Context after drop the previous one. and the disconnect method seems did not work.

ileon commented

I know there is a set_slave() method, but why in above code, it was panic ? the disconnect looks not work ? the SerialStream did not drop in the first {} block ? how to drop the SerialStream properly? I have tried, but can not get the right method to re-build Context