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.