detect if device is connected to virtual serial port with jSerialComm

49 views Asked by At

i've created a virtual com port for a barcode reader, i'm using jSerialComm i was able to read data, but when the device is disconnected t code runs as if the device is still connected

here is the code

SerialPort com = AvailablePorts[1];

int BaudRate = 9600;
int DataBits = 8;
int StopBits = SerialPort.ONE_STOP_BIT;
int Parity   = SerialPort.NO_PARITY;

com.setComPortParameters(BaudRate, DataBits,StopBits,Parity);
com.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,1000,0);
com.openPort(); //open the port
Thread.sleep(2000);
com.setComPortParameters(BaudRate,DataBits,StopBits,Parity);
com.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,1000,0); 
String S="";

try 
{
    while (true)
    {
        byte[] readBuffer = new byte[300];
        int numRead = com.readBytes(readBuffer,
                         readBuffer.length);
        System.out.print("Read " + numRead + " bytes -");
                 
        S = new String(readBuffer, "UTF-8");
        System.out.println("Received -> "+ S);
        if(numRead!=0) {
            break;
        }
    }
} 
catch (Exception e) 
{
    e.printStackTrace(); 
}
com.closePort();
0

There are 0 answers