我目前正在使用 RXTX 来处理我的 java 程序中的串行通信,并且我已经成功地能够连接/断开连接和读/写。
但是我无法弄清楚 RXTX 中是否有一种方法可以检测设备是否在其末端断开连接。如果不轮询串行端口,您将如何检测到此事件?因为如果它在轮询之间断开连接并重新连接,它不会被检测到,但在使用串行端口时仍然会导致错误。
如果在 RXTX 中不可能,是否有任何推荐的库可以检测断开连接事件?
说明:该设备通过 USB 连接并注册为串行设备。设备在重置或关闭时可能会断开连接。当它重置时,串行端口会暂时关闭,使 RXTX 创建的连接失效。
感谢您的帮助
最佳答案
我有同样的问题:我想知道设备何时从 USB 端口拔下。 然后,我发现每次从 USB 端口拔下设备时,它都会从 serialEvent 中获取 java.io.IOException。看看下面我的 serialEvent 代码:
@Override
public void serialEvent(SerialPortEvent evt) {
if(this.getConectado()){
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try {
byte singleData = (byte)input.read();
if (singleData == START_DELIMITER)
{
singleData = (byte)input.read();
if(singleData == (byte)0x00)
{
singleData = (byte)input.read(); //get the length
byte[] buffer = new byte[singleData+4];
for(byte i=0x0;i<singleData;i++)
buffer[i+3] = (byte)input.read();
buffer[buffer.length-1] = (byte)input.read();
buffer[0] = START_DELIMITER;
buffer[1] = 0x00;
buffer[2] = singleData; //length
this.addNaLista(buffer);
}
}
} catch (IOException ex) {
Logger.getLogger(Comunicador.class.getName()).log(Level.SEVERE, null, ex);
/* do something here */
//System.exit(1);
}
}
}
}
即使那一刻我没有接收到数据,我仍然会得到 java.io.IOException;这是异常跟踪:
Jun 21, 2014 10:57:19 AM inovale.serial.Comunicador serialEvent
SEVERE: null
java.io.IOException: No error in readByte
at gnu.io.RXTXPort.readByte(Native Method)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1250)
at inovale.serial.Comunicador.serialEvent(Comunicador.java:336)
at gnu.io.RXTXPort.sendEvent(RXTXPort.java:732)
at gnu.io.RXTXPort.eventLoop(Native Method)
at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1575)
我使用的唯一事件是:
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
这是我看到的检测断开(物理)事件的方式。
关于java - 我如何检测串行端口何时被java中的设备关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889507/