在SerialPort.java中,我想了解以下关于writeBytes和readBytes方法的信息:
- 这些会挡住吗
- 如何解释返回的布尔代码
对于读取(我使用的是2.8.0版本),还有一些方法,如readBytes(int byteCount, int timeout)
,您可以在其中指定超时。对于读取,更好的方法可能是注册SerialPortEventListener
。事实上,我从未尝试过直接在它之外使用readBytes
对于写入方法,布尔返回代码必须是true
。原因是返回代码来自后面的C++JNI实现。在JNI部分没有抛出任何异常,这里最好也是一个异常。
如果你查看例如writeBytes(byte[] buffer)
的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() + "]");
}