Reputation: 81
I'm currently using RXTX to handle serial communication in my java program and I have successfully been able to connect/disconnect and read/write.
However I haven't be able to figure out if there is a way in RXTX to detect if a device disconnects on it's end. How would you detect this event without polling the serial ports? Since if it disconnects and reconnect between polls it wouldn't be detected but still cause errors when the serial port is used.
If it isn't possible in RXTX are there any libraries that would be recommend that can detect a disconnect event?
Clarification: The device is connected over USB and registers as a serial device. The device may disconnect when it either resets or turns off. When it resets the serial port is momentarily closed invalidation the connection RXTX created.
Thanks for any help
Upvotes: 8
Views: 4843
Reputation: 864
I have the same problem: I was trying to know when the device was unplugged from the USB port. Then, I found out that every time I unplugged the device from the USB port, it gets a java.io.IOException from the serialEvent. Take a look at my serialEvent code below:
@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);
}
}
}
}
Even if I am not receiving data at that moment, I still get the java.io.IOException; here is the exception trace:
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)
The only events I am using is:
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
This is the way I see to detect a disconnect (physically) event.
Upvotes: 1