} // is port already in use?
if (port.isCurrentlyOwned()) {
System.out.println("Port \"" + port.getName() + "\" in use.");
return null;
} // open the port
SerialPort serialPort = null;
try {
CommPort cPort = port.open(APP_ID, PORT_OPENTIME);//2 seconds wait
if (cPort instanceof SerialPort) {
serialPort = (SerialPort) cPort;
} else {
System.out.println("Port \"" + port.getName() + "\" is not a serial port.");
cPort.close();
return null;
}
} catch (PortInUseException e) {
System.out.println("Port \"" + port.getName() + "\" in use.");
return null;
}
//setting connection parameters
try {
serialPort.setSerialPortParams(PORT_BAUDRATE, PORT_DATABITS, PORT_STOPBITS, PORT_PARITY);
serialPort.enableReceiveTimeout(PORT_IN_TIMEOUT);
serialPort.enableReceiveThreshold(PORT_IN_THRESHOLD);
} catch (UnsupportedCommOperationException e) {
System.out.println("Parameters not allowed for port \"" + port.getName() + "\".");
serialPort.close();
return null;
}
// opening streams
// InputStream inStream = null;
// OutputStream outStream = null;
try {
this.in = serialPort.getInputStream();
this.out = serialPort.getOutputStream();
} catch (IOException e) {
System.out.println("Can't open streams of the port \"" + port.getName() + "\".");
serialPort.close();
return null;
}
isConnected = true;
return serialPort;
}