我想将从串口接收到的数据存储在一个字符串变量中,该变量将在另一个类中访问。我编写了打印从 com 端口接收到的数据的代码,但是当从它返回的方法中访问变量时null
..请帮帮我..我正在为此使用 RxTx 库。
public class ProtocolImpl implements Protocol {
byte[] buffer = new byte[1024];
int tail = 0;
public String message;
public void onReceive(byte b) {
// simple protocol: each message ends with new line
if (b=='\n') {
onMessage();
} else {
buffer[tail] = b;
tail++;
}
}
public void onStreamClosed() {
onMessage();
}
/*
* When message is recognized onMessage is invoked
*/
private void onMessage() {
if (tail!=0)
{
// constructing message
message = getMessage(buffer, tail);
//rmess = message;
System.out.println("RECEIVED MESSAGE: " + message);
if ("KITM".equalsIgnoreCase(message)) {
CommPortSender.send(getMessage("OK"));
}
tail = 0;
}
}
public String rmess() /*this method is returning null.. please help me out*/
{
if (tail!=0) {
message = getMessage(buffer, tail);
}
return message;
}
// helper methods
public byte[] getMessage(String message) {
return (message).getBytes();
}
public String getMessage(byte[] buffer, int len) {
return new String(buffer, 0, tail);
}
}