[英]Java - Serial port data extraction
我对 Java 和一般编程相当陌生。 我正在 Java Swing 中制作一个应用程序,该应用程序从连接到点钞机的串行端口读取数据。 当机器计数某物时,它通过RS232-USB转换器将计数数据发送到PC。 我设法制作了一个应用程序,可以找到并打开 COM 端口,并从机器中读取数据。 这是我得到的数据:
是否可以仅从 output 中提取某些信息? 例如只有 D10 的单元数? 如果是这样,我该怎么做?
想法是将所有信息分别写入已经定义的JTextfields
。
我试过这样的事情:
while ((line = portReader.readLine()) != null) {
//window.ta_logs.append(line + "\n");
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreElements()) {
String token = st.nextToken();
if (token.contains("D50")) {
data.put("D50", token.substring(2));
}
window.ta_logs.append(token);
}
System.out.println(line);
System.out.println(data);
}
提前致谢。
"是否可以从这个 output 中只提取某些信息? "
当然这是可能的。 您已经从串行端口读取数据。 您可以标记数据并存储在 map 中。
// Get the data from serial port and tokenize it
Map<String, Whatever> data = new HashMap<>();
data.put("D10", XXX);
data.put("D20", YYY);
...
然后,您可以在相应的文本框中设置文本
d10TextField.setText(data.get("D10"));
d20TextField.setText(data.get("D20"));
...
您只需要让这个 map 可访问。
while (input.available() > 0) {
input = serialPort.getInputStream();
int nBytes = input.available();
int c = input.read();
System.out.println("nBytes = " + nBytes);
System.out.println("read " + (char) c);
if (nBytes == 376) {
data.put("D10", (char) c);
} else if (nBytes == 344) {
data.put("D20", (char) c);
} else if (nBytes == 312) {
data.put("D50", (char) c);
} else if (nBytes == 280) {
data.put("D100", (char) c);
} else if (nBytes == 248) {
data.put("D200", (char) c);
} else if (nBytes == 216) {
data.put("D500", (char) c);
} else if (nBytes == 184) {
data.put("D1000", (char) c);
} else if (nBytes == 152) {
data.put("D2000", (char) c);
} else if (nBytes == 120) {
data.put("D5000", (char) c);
}
我这样做并得到了想要的结果。
我的第二个问题是,例如,如果 D10 的数量超过 9 个,我该如何获取数据。 在这种情况下,我必须考虑两个字节,或者如果数字是 100 或更多,则考虑三个字节。
有任何想法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.