tags:

views:

195

answers:

4

Hi All, my app uses the Java serial comm api. From reading the docs the inputstream.read() method blocks if there is no data available.

I tried setting a timeout on the serialport object but the isReceiveTimeoutEnabled() methods returns false, indicating my driver does not natively support timeouts.

So what's the best way to implement a read timeout given the above?

Thanks, Fred

A: 

If its not working for you just toss that inputstream into a thread and implement your own time out. If it times out call close() on the stream to unblock and close that thread

Pyrolistical
A: 

You will need two threads.

A watchdog thread will monitor a reading thread and interrupt it when a timeout is detected.

Have the reading thread tell the watchdog thread that it's about to start reading, and when it completed a read.

Have the watchdog thread start a timer when a read begins and interrupt the reading thread when it times out or stop listening for a time out when the reading is complete.

Read up on Java threading if you're not familiar with it. It's easy to have multi-threading bugs.

Ben S
+1  A: 

You can check with the InputStream.available() method if the next read() will block or not.

Progman
A: 

You can also use a SerialPortEventListener as a callback to get notified of newly available data and only call read when there is something to do.

final SerialPort serialPort = ...;
final InputStream in = serialPort.getInputStream();
serialPortal.notifyOnDataAvailable(true);
serialPort.addEventListener(new SerialPortEventListener() {
    public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            // read from InputSteam
        }
    }
});
Jörn Horstmann