javasocketsserial-portrxtxjssc

Serial port communication after port is closed and reopen


I am writing a serial port communication application in Java using a library called jSSC (java-simple-serial-connector) with an external device.

After sending a message and waiting for its return, I have a timeout that will abort the reading if there is no reading after certain time (2 second). If that happens, the port is closed and re-opened for further message exchange.

What I noticed is that, if for some reason, the timeout happens, and the port is closed and reopened, further message reading from the port will be interfered (i.e., the message read cannot be decoded). It looks as if previous message from the device is still on the line and continue to come in for the next reading operation.

I'm not very familiar with serial port so I'm not totally sure if this is the case. I would think (but may well be wrong) the previous message sending by the other part is discarded after I close the connection from my side (as in a TCP/IP communication).

Can anyone shed some light on this topic as to how exactly the serial port behave after close/re-open? Is it possible for the other part (a device) to continue sending the old message even after I close the connection in the application?


Solution

  • In your case I think in case of time out you should perform a purge then closing Port before you try to reopen it again.

    if (serialPort! = null && serialPort.isOpened ()) {
      serialPort.purgePort (1);
      serialPort.purgePort (2);
      serialPort.closePort ();
    }