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);
}
}
}
}