Wudong
Wudong

Reputation: 2360

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?

Upvotes: 0

Views: 3946

Answers (2)

samuel05051980
samuel05051980

Reputation: 399

You should purge the port not at the time of closing but at the time when serial port is opened. Operating systems and drivers maintain their own buffers for serial port data. When purge is called it actually calls flush function of operating system (and driver) and that is where data received previously gets discarded (deleted). Also try to use any other library like serial communication manager.

Upvotes: 0

Ahmed Gawad
Ahmed Gawad

Reputation: 135

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 ();
} 

Upvotes: 1

Related Questions