How to determine when a serial port was closed by a device in java?

I am currently using RXTX to handle serial communications in my java program, and I was able to successfully connect / disconnect and read / write.

However, I cannot figure out if there is a way in RXTX to detect if a device is disconnected on it. How do you detect this event without polling serial ports? Because if it disconnects and reconnects between polls, it will not be detected, but it will still cause errors when using the serial port.

If this is not possible in RXTX, are there any libraries that might recommend detecting a disconnect event?

Specification: the device is connected via USB and registered as a serial device. The device may turn off if it is reset or turned off. When it is reset, the serial port instantly closes the cancellation of the RXTX connection.

Thanks for any help

+6
source share
1 answer

I have the same problem: I tried to find out when the device was disconnected from the USB port. Then I found out that every time I disconnect the device from the USB port, it gets a java.io.IOException from 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 do not receive data at this moment, I still get java.io.IOException; there is an exception trace here:

 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 use are:

 serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); 

So I see to detect a disconnect event (physically).

+1
source

Source: https://habr.com/ru/post/950390/


All Articles