RichardLiu
RichardLiu

Reputation: 1962

How to set timeout in Java when reading from SerialPort?

I'm new to JAVA programming. I was assigned with the task to write a JAVA GUI application that will interact with external devices via serial port. I've managed to make my code compile and run with jSSC (Java Simple Serial Connector) package under both Mac OS X and Win32 platform. The jSSC project provides decent sample codes and it's fairly easy to implement with javax.comm style SerialPortEventListener interface.

But soon I've learned that I'd need to add "ACK timeout" feature to my implementation, for error prevention. In C language this can easily be achieved via select() API call with 5th parameter set to desired duration dynamically. But in JAVA, I've no single clue how to do it.

Should I setup another time thread and fire timer-generated event by directly calling serialEvent() method ? It may lead to some racing condition though.


(03/27 10:43 Edit): OK, I've traced source code of jSSC. It seemed that jSSC just creates a new Runnable thread in JVM, when a Listener is registered to it; and that thread will continuously polling status with native function call, which will invoke system api calls like ioctl(). So it would be impossible to add timeout event without modifying the native library.

Guess that I have to change the way for serial port event handling. I'll need to create another Runnable thread to handle the incoming data process, instead of directly parsing data within serialEvent() method call from jSSC event thread. And I can setup a timer to throw timeout event into that thread.

I that case, I'd need to setup an event dispatching thread, just like SwingUtility.invokelater(). But I've no idea whether I should implement one from the bottom-up, or I can just use the AWT EDT to handle it.

Can anyone give me some advice ?

Upvotes: 0

Views: 6125

Answers (2)

Fabian Barney
Fabian Barney

Reputation: 14559

I am not familiar with jSSC, but when there is no possibility to pass a timeout through the API and you've to do it yourself, then ThreadMonitor from Apache may be of your interest.

Usage looks like this:

long timeoutInMillis = 1000;
try {
    Thread monitor = ThreadMonitor.start(timeoutInMillis);
    // do some work here
    ThreadMonitor.stop(monitor);
} catch (InterruptedException e) {
    // timed amount was reached
}

We are using RXTX here for serial port communication. We have barcode scanners connected via serial port and modems sending SMS to our admins when critical system states occur in monitoring. Works flawless.

Upvotes: 1

ab_dev86
ab_dev86

Reputation: 1982

I have worked with java comm, never with jssc. JavaComm provide an open method were a timeout can be configured:

serialPort1 = (SerialPort) portId1.open("ComControl", 2000);

From jssc javadoc the open method doesn't manage a timeout mechanism.

Upvotes: 1

Related Questions