Skip to content

Blocking and Semiblocking Reading Usage Example

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

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

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

Similarly, there are times when you know a priori the amount of data you expect to read at any given time. In these cases, you would not like a read() call to return before all of the expected data bytes have been read. This behavior can be coupled with a read timeout to ensure that the call does not block indefinitely, like so:

SerialPort comPort = SerialPort.getCommPorts()[0];
comPort.openPort();
comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 1000, 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(); }
comPort.closePort();

In this case, the readBytes() call should always return the requested 1024 bytes unless this number of bytes has not been transmitted over the serial port for a full second (1000 milliseconds), as specified in the setComPortTimeouts() method.

If you would like to ensure that the readBytes() call never returns until the full expected read size has been fulfilled, simply replace the setComPortTimeouts() line with the following:

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