双向串行通信-无法访问从串行读取器线程读取的字符串



我向声明了一个twoWaySerialComm对象来配置端口连接。在twoWaySerialComm类中,我创建了一个线程来读取一个名为"SerialReader"的类中传入的串行数据。如何从主线程"twoWaySerialComm"访问串行数据?

我已经在while循环中将传入的串行数据读取到"SerialReader"类中的"hex"字符串中。我可以在while循环中打印传入的数据,但我无法访问"twoWaySerialComm"类中的"hex"字符串。为什么我不能访问while循环之外的"hex"字符串?如何做到这一点?

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author asanka
*/
public class TwoWaySerialComm {
private static TwoWaySerialComm twoWaySerialComm;
String read;
private TwoWaySerialComm() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
String portName = "/dev/ttyUSB0";
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
SerialReader reader;
(new Thread(reader = new SerialReader(in))).start();
read = reader.readHex();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static TwoWaySerialComm getTwoWaySerialComm() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
if (twoWaySerialComm == null) {
twoWaySerialComm = new TwoWaySerialComm();
}
return twoWaySerialComm;
}
public String data() {
return read;
}
/**
*
*/
public static class SerialReader implements Runnable {
String hex;
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len;
try {
while ((len = this.in.read(buffer)) > -1) {
hex = new String(buffer, 0, len).replaceAll("\s", "");
Thread.sleep(1000);
System.out.println(hex);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ex) {
Logger.getLogger(TwoWaySerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String readHex() {
return hex;
}
}
/**
*
*/
public static class SerialWriter implements Runnable {
OutputStream out;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
try {
int c = 0;
while ((c = System.in.read()) > -1) {
this.out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

据我所见,您正在另一个线程中运行读取操作。当调用readHex()方法时,该线程可能还没有填充十六进制字段。

您需要首先在新线程上调用join(),以确保它已经完成。或者使用java.util.courrent包中的CompletableFuture。

最新更新