0
votes

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!

1
I'm sorry about the broken comment on my edit. I accidentally hit the enter key before finishing and I can't edit that comment anymore, so I'll type it here instead: "Please use the [com] tag only for questions about Microsoft's "Component Object Model". Questions about COM serial ports should be tagged with [serial-port] instead". Good luck. - Euro Micelli

1 Answers

0
votes

Better to use the wait event as used inside serialport class. This way makes the port to wait until a command is equecuted.

serialPort.writeBytes(buffer);//Write data to port
serialPort.addEventListener(new PortReader(serialPort), SerialPort.MASK_RXCHAR);
int[][] eventArray=serialPort.waitEvents()
for (int i = 0; i < eventArray.length; i++) {
    if ((eventArray[i][0] > 0) ) {
     serialPort.eventListener.serialEvent(new SerialPortEvent("COM1", eventArray[i][0], eventArray[i][1])); //give your port name and the events got.
                    }
                  }