Skip to content

Event Based Reading Usage Example

Will Hedgecock edited this page Mar 12, 2015 · 27 revisions

If you would like to use the jSerialComm library in a completely asynchronous fashion, you can enable event-based callbacks via the addDataListener() method. This method takes as a parameter your own custom callback object which must implement the SerialPortDataListener interface.

There are many times when it could prove beneficial to ensure that a read call always returns at least 1 byte of valid data. It is also generally preferably that a single function call never block indefinitely. Both of these behaviors may be enabled through the semi-blocking read mode of the jSerialComm library. This mode can be enabled and used as follows:

SerialPort comPort = SerialPort.getCommPorts()[0];
comPort.openPort();
comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
try {
   while (true)
   {
      byte[] readBuffer = new byte[1024];
      int numRead = comPort.readBytes(readBuffer, readBuffer.length);
      System.out.println("Read " + numRead + " bytes.");
   }
} catch (Exception e) { e.printStackTrace(); }

If you would like to ensure that the readBytes() call never returns until at least a single data byte has been read, simply replace the setComPortTimeouts() line with the following:

comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);

Clone this wiki locally