kochedykov / jlibmodbus

JLibModbus - is an implementation of the Modbus protocol v1.1b in java language. Java modbus library. It works. Welcome.
http://kochedykov.github.io/jlibmodbus/
Apache License 2.0
299 stars 128 forks source link

Using jSerialComm Serial Communication is not working with stop bit 2. #84

Closed ramen2k10 closed 4 months ago

ramen2k10 commented 1 year ago

I am performing Event based serial communication using jSerialComm, now when I am setting the numStopBits = 2 the port is not able to connect. is jSerialComm doesn't support for StopBits = 2?

protected boolean openConnecton() {
    boolean status = false;
    serialPort.setBaudRate(baudRate);//set BaudRate
    serialPort.setNumDataBits(numDataBits); // set NumDataBits
    serialPort.setNumStopBits(numStopBits); //set NumStopBits
    serialPort.setParity(parity); 
    serialPort.openPort();

    if(serialPort.isOpen()) {
        txtStatus.setText(STATUS_SUCCESS);
        status = true;
        byte[] readBuffer = null;
        messages.add("Port Open successfully");
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
        try {

            do   {
                  while (serialPort.bytesAvailable() == 0) {
                      Thread.sleep(20);
                      break;
                  }

                  readBuffer = new byte[serialPort.bytesAvailable()];
                  int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
                  System.out.println("Read " + numRead + " bytes.");
               }while(readBuffer.length == 3);
        } catch (Exception e) { e.printStackTrace(); }
        Serial_EventBasedReading(this.serialPort);
    }else {
        txtStatus.setText(STATUS_FAIL);
    }   
    return status;
}

private void Serial_EventBasedReading(SerialPort activePort) {

    activePort.addDataListener(new SerialPortDataListener() {

        @Override
        public void serialEvent(SerialPortEvent event) {
            byte[] data = event.getReceivedData();
            for(int i = 0; i<data.length ;i++) {
                dataBuffer += (char)data[i];
            }
        }

        @Override
        public int getListeningEvents() {
            return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
        }
    });

}