我需要修改 RXTX“基于事件的双向通信”(请参阅 http://rxtx.qbang.org/wiki/index.php/Event_based_two_way_Communication),以便我能够将特定响应写回串行设备关于其上一条消息。
我通过发送第一个命令开始通信。到目前为止一切正常。现在我从串行设备得到答案。我用进一步的命令对答案做出反应。但是我不能再写了,因为写线程已经结束了。
有人知道如何处理吗?非常感谢!
public class TwoWaySerialComm {
public TwoWaySerialComm() {
super();
}
public static void main(String[] args) {
try {
// 0. call connect()
(new TwoWaySerialComm()).connect("COM1");
} catch (Exception e) {
e.printStackTrace();
}
}
void connect(String portName) throws Exception {
// 1. get CommPortIdentifier, open etc...
// 2. then do
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
// 4. start writer thread
(new Thread(new SerialWriter(out))).start();
// 5. instantiate SerialReader
serialPort.addEventListener(new SerialReader(in));
serialPort.notifyOnDataAvailable(true);
}
public static class SerialWriter implements Runnable {
OutputStream out;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
try {
// establish a communication by sending the first command. the serial device will answer!
String toSend = "blablabla";
this.out.write(toSend);
// thread ended???
}
public static class SerialReader implements SerialPortEventListener {
private InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void serialEvent(SerialPortEvent arg0) {
// event occurs beacause device answers after writing.
int data;
try {
StringBuffer sb = new StringBuffer();
String LineOfData=null;
while ((data = in.read()) > -1) {
if (data == '\n') {
break;
}
sb.append(Integer.toHexString(data));
LineOfData = sb.toString();
}
// I store the answer and send it to an EventIterpreter. Regarding the answer, it creates an appropriate response itselves.
EventInterpreter e = new EventInterpreter(LineOfData);
String result = e.getData
HERE >> // Now I want to send this response back to the device. But the thread is already ended.
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}