Read & Write simultaneously on same JAVA RXTX Serial Port within same thread
Is it possible to read and write from same serial port within same Java thread in real time.Actually I am reading data from Arduino and I need to send same data to Arduino in realtime. Im using while true condition inside my Runnable that's why unable to get data inside EventListner.
Code Snippet
public void initialize()
{
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId
= (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
logText="Could not find COM Port. Please Change your device port to COM3.";
isconnected=false;
return;
} else {
System.out.println("Port Name: " + portId.getName() + "\n"
+ "Current Owner: " + portId.getCurrentOwner() + "\n"
+ "Port Type: " + portId.getPortType());
logText = portId.getName()+ " Successfully Connected!";
isconnected=true;
isRunning=true;
//Controller.labelStatus.setText(" Successfully Connected!");
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIMEOUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
inputstream = serialPort.getInputStream();
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
thread = new Thread(){
public void run(){
while(isRunning) {
System.out.println("Thread Running "+bytesToHexString(BtnHexData.getInstance().getSendingPack()));
try {
output.write(BtnHexData.getInstance().getSendingPack());
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(200);
//System.out.println("\t\t Thread Receiving "+bytesToHexString(input.readAllBytes()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
} catch (Exception e) {
serialPort.close();
System.err.println(e.toString());
logText="Error: "+e.toString();
}
}