2

在 SerialPort.java 中,我想了解有关 writeBytes 和 readBytes 方法的以下内容:

  • 那些会阻止吗?
  • 如何解释返回 --boolean-- 代码?
4

1 回答 1

3

对于阅读(我使用的是 2.8.0 版),还有一些方法readBytes(int byteCount, int timeout)可以指定超时。为了阅读更好的方法可能是注册一个SerialPortEventListener. 事实上,我从未尝试readBytes直接在它之外使用。

布尔返回码必须true用于编写方法。原因是来自后面的 C++ JNI 实现的返回码。JNI部分没有抛出异常,这里最好也是一个异常。

如果您查看例如writeBytes(byte[] buffer)只有第一行抛出 a的 Java 代码SerialPortException,则实际传输是使用布尔返回代码处理的:

this.checkPortOpened("writeBytes()");
return this.serialInterface.writeBytes(this.portHandle, buffer);

写入部分可能会阻塞,例如,如果串行端口没有响应。我使用了一个线程来防止这种情况,如下所示:

private static class BackgroundWriter implements Callable<Boolean> {

    private SerialPort serialPort;

    private String atCommand;

    public BackgroundWriter(SerialPort serialPort, String atCommand) {
        this.serialPort = serialPort;
        this.atCommand = atCommand;
    }

    @Override
    public Boolean call() throws Exception {
        // add carriage return
        boolean success = serialPort.writeString(atCommand+"\r");
        return success;
    }
}

然后超时调用它:

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Boolean> writeResult = executorService.submit(new BackgroundWriter(serialPort, atCommand));
boolean success;
try {
    success = writeResult.get(writeTimeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
    if (serialPort != null && serialPort.isOpened()) {
        try {
            serialPort.closePort();
        } catch (SerialPortException e2) {
            LOGGER.warn("Could not close serial port after timeout.", e2);
        }
    }
    throw new IOException("Could not write to serial port due to timeout.", e);
}
if (!success) {
    throw new IOException("Could not write to serial port [" + serialPort.getPortName() + "]");
}
于 2015-04-20T00:58:49.897 回答