我有一个类试图从与Arduino板连接的其他Xbees中读取数据包。这是班级:
public class XbeeReceiver2 {
private XBee xbee;
private int[] payloadToSend;
private int[] payloadReceived;
private Queue<XBeeResponse> queue = new ConcurrentLinkedQueue<XBeeResponse>();
public XBeeResponse response;
private final static Logger LOGGER = Logger.getLogger(XbeeReceiver2.class .getName());
public XbeeReceiver2(){
xbee = new XBee();
}
public void openXbeeConnection(String portNumber){
try {
xbee.open(portNumber, 9600);
xbee.addPacketListener(new PacketHandler());
} catch (XBeeException e) {
System.out.println("" + portNumber + " - connection problems");
e.printStackTrace();
}
};
public void readPacket(){
System.out.println(queue.isEmpty());
while((response = queue.poll()) != null){
try {
response = xbee.getResponse();
LOGGER.info("received response " + response.toString());
if (response.getApiId() == ApiId.ZNET_RX_RESPONSE){
ZNetRxResponse rx = (ZNetRxResponse) response;
payloadReceived = rx.getData();
}
} catch (XBeeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void closeXbeeConnection(){
xbee.close();
};
private class PacketHandler implements PacketListener{
@Override
public void processResponse(XBeeResponse response) {
//if (response instanceof XBeeResponse){
queue.offer(response);
//}
}
}
}
在主程序中,我有以下代码:
XbeeReceiver2 xbeeReceiver = new XbeeReceiver2();
xbeeReceiver.openXbeeConnection("COM23");
xbeeReceiver.readPacket();
然而,当我运行它时,readPacket()
方法将在循环开始时卡住,因为队列中存在任何XbeeResponse实例。但是,当我将readPacket()方法中的while
条件从while((response = queue.poll()) != null)
更改为while(true)
时,它就可以正常工作。这意味着我得到了响应,但我不认为使用while(true)
是我在某些页面上阅读时的好解决方案。因此,我更喜欢使用PacketListener
。
如果有人有想法,为什么我的PacketListener
不起作用,那就太棒了。
答案 0 :(得分:-1)
好的,我找到了一个解决方案,并不是那么难。在开始循环之前,我收到了来自Xbee的响应并将其添加到队列中,因此它在开始时没有中断。我在while循环结束时做了同样的事情,在那里我添加了另一个响应。
这是我的openConnection
方法:
public void openXbeeConnection(String portNumber){
try {
xbee.open(portNumber, 57600);
xbee.addPacketListener(new PacketHandler());
response = xbee.getResponse();
queue.add(response);
} catch (XBeeException e) {
System.out.println("" + portNumber + " - connection problems");
e.printStackTrace();
}
};
在main方法的while循环中,它看起来像这样:
while ((response = queue.poll()) != null){
//LOGGER.info(response.toString());
int[] payload = xbeeReceiver.readPacket();
dbHandler.updateDB(payload);
int[] payloadToSend2 = dbHandler.retrieveDataFromFB();
xbeeReceiver.sendPacket(payloadToSend2);
try {
XBee xbee = xbeeReceiver.getXbee();
response = xbee.getResponse();
queue.add(response);
} catch (XBeeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}