gpt4 book ai didi

java - JSSC 读写超时

转载 作者:行者123 更新时间:2023-11-30 08:20:17 25 4
gpt4 key购买 nike

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

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

最佳答案

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

写入方法的 boolean 返回码必须为true。其原因是来自后面的 C++ JNI 实现的返回码。 JNI部分没有抛出异常,最好在这里也抛出异常。

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

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() + "]");
}

关于java - JSSC 读写超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com