在SerialPort.java中,我想了解关于writeBytes和readBytes方法的以下内容:
发布于 2015-04-20 00:58:49
对于阅读(我使用的是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() + "]");
}https://stackoverflow.com/questions/26184226
复制相似问题