jlibmodbus icon indicating copy to clipboard operation
jlibmodbus copied to clipboard

Setting timeout for jSerialComm don't work because of TIMEOUT_NONBLOCKING flag

Open VolmerM opened this issue 5 years ago • 1 comments

Hello

I am using in my project jSerialComm and tried to use this also for the modbus communication:

SerialPortFactoryJSerialComm factory = new SerialPortFactoryJSerialComm();
SerialUtils.setSerialPortFactory(factory);

But I get everytime a read timeout error com.fazecast.jSerialComm.SerialPortTimeoutException: The read operation timed out before any data was returned.

Looking in the source code I found this in SerialPortJSerialComm:

    @Override
    public void open() throws SerialPortException {
        SerialParameters sp = getSerialParameters();
        port = com.fazecast.jSerialComm.SerialPort.getCommPort(sp.getDevice());
        port.openPort();

        port.setComPortParameters(sp.getBaudRate(), sp.getDataBits(), sp.getStopBits(), sp.getParity().getValue());
        port.setFlowControl(com.fazecast.jSerialComm.SerialPort.FLOW_CONTROL_DISABLED);

        in = port.getInputStream();
        out = port.getOutputStream();

        port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_BLOCKING, getReadTimeout(), 0);

    }

    @Override
    public void setReadTimeout(int readTimeout) {
        super.setReadTimeout(readTimeout);

        if (isOpened()) {
            port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_NONBLOCKING, getReadTimeout(), getReadTimeout());
        }
    }

For me it was not clear why in the first setting TIMEOUT_READ_BLOCKING was used and in the second TIMEOUT_NONBLOCKING. So I change the TIMEOUT_NONBLOCKING to TIMEOUT_READ_BLOCKING. This changes working for me very fine.

    @Override
    public void open() throws SerialPortException {
        SerialParameters sp = getSerialParameters();
        port = com.fazecast.jSerialComm.SerialPort.getCommPort(sp.getDevice());
        port.openPort();

        port.setComPortParameters(sp.getBaudRate(), sp.getDataBits(), sp.getStopBits(), sp.getParity().getValue());
        port.setFlowControl(com.fazecast.jSerialComm.SerialPort.FLOW_CONTROL_DISABLED);

        in = port.getInputStream();
        out = port.getOutputStream();

        port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_BLOCKING, getReadTimeout(), getReadTimeout());

    }

    @Override
    public void setReadTimeout(int readTimeout) {
        super.setReadTimeout(readTimeout);

        if (isOpened()) {
            port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_BLOCKING, getReadTimeout(), getReadTimeout());
        }
    }

VolmerM avatar Mar 03 '20 06:03 VolmerM

What version of JSerialComm do you use? I get this error + subsequent "port not opened" on 2.8.2 JSerialComm.

emilm avatar Jan 24 '22 12:01 emilm