I've tried to solve the following Problem the last three days. I spend three days reading through various threads in many forums.
This is my problem: I try to send commands to a Bluetooth HC-05 device connected via a virtual Com-Port. In my case "COM4".
I used RXTX to establish a Connection to the Serial port. This works fine.
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
boolean portFound = false;
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM4")) {
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
}
@SuppressWarnings("restriction")
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
serialPort.setOutputBufferSize(15);
serialPort.setEndOfInputChar((byte)'\n');
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {System.out.println(e);} catch (UnsupportedCommOperationException e)
e.printStackTrace();
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {System.out.println(e);}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(300,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException e) {System.out.println(e);}
serialPort.setRTS(true);
serialPort.setDTR(true);
serialPort.notifyOnDataAvailable(true);
serialPort.setInputBufferSize(8192);
serialPort.setOutputBufferSize(8192);
writeThread = new Thread(new SerialWriter(outputStream));
writeThread.start();
readThread = new Thread(this);
readThread.start();
}
The Problem occures in the writer thread. When the writeTo()
method of the ByteArrayOutputStream gets called the program hangs up without throwing an exception.
public class SerialWriter implements Runnable {
OutputStream out;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
try {
Thread.sleep(500);
while (true) {
out.flush();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write("AT\n".getBytes(Charset.forName("ASCII")));
baos.writeTo(out); // <-- Here is my Problem. The program just
// hangs up
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
My OS is Windows 8.1 64bit.
I'm able to connect to the Bluetooth device with the console application hterm.
I appreciate any help or tip you can give me to solve this annoying problem!!