My project used JSSC library for linking PC and microcontroller.
Write method:
public void write(byte[] buffer) throws SerialPortException {
if (serialPort.isOpened())
serialPort.writeBytes(buffer);
}
Read method:
public byte[] read() throws SerialPortException {
byte[] result = null;
FutureTask<byte[]> task = new FutureTask<>(new PortReader());
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
result = (byte[]) executor.submit(task).get(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.err.println(getClass().getSimpleName() + " READ: Timeout exception!");
}
return result;
}
private class PortReader implements Callable<byte[]>, SerialPortEventListener {
private byte[] data = null;
@Override
public void serialEvent(SerialPortEvent event) {
if (event.isRXCHAR() && event.getEventValue() > 0) {
try {
data = serialPort.readBytes(event.getEventValue());
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
@Override
public byte[] call() throws Exception {
if (data == null)
Thread.sleep(200);
return data;
}
}
I tried to implement a synchronous write (immediately send data) to the port and asynchronous read (waiting for the input data at least 1000 ms) from port.
Is it correct decision? Maybe there are other ways of asynchronous data reading?
Thank you!