如何收到针对特定主题发布的MQTT消息? 我可以在MQTT代理上发布消息,但我不知道如何接收消息?
这是我的组件xml:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" activate="activate" deactivate="deactivate" name="arduinoCommunicator">
<implementation class="arduinoCommunicator.ArduinoCommunicator"/>
<reference bind="setDataService" cardinality="1..1" interface="org.eclipse.kura.data.DataService" name="DataService" policy="static" unbind="unsetDataService"/>
<service>
<provide interface="org.eclipse.kura.data.DataServiceListener"/>
</service>
</scr:component>
这是我的bundle activator类,我只保留了所需的代码,我实现了DataServiceListener,我订阅了关于onConnectionEstablished()的主题,我想我在函数onMessageArrived上得到了消息,问题是我不知道#39;看到订阅已经完成的日志,并且没有执行onMessageArrived()函数:
public class ArduinoCommunicator implements DataServiceListener {
public static DataService dataService;
@Override
public void onConnectionEstablished() {
String topic="egmkey/device2/cmd/PING";
System.out.println("connection has been established");
try {
ArduinoCommunicator.dataService.subscribe(topic, 1);//egmkey/device2/cmd/PING
System.out.println("subscription done to topic"+topic);
} catch (KuraException e) {
System.out.println("failed to subscribe: "+ e);
}
}
@Override
public void onMessageArrived(String topic, byte[] payload, int qos, boolean retained) {
System.out.println("message received!!!!!!!!!!!!!!!!!!!!!!:"+topic);
}
}
我错过了能够在KURA上使用DataService接收MQTT消息的内容吗?感谢。
答案 0 :(得分:1)
您没有正确地将DataService服务注入到组件中。下面的代码应该更接近您实际需要的代码:
public class ArduinoCommunicator implements DataServiceListener {
public DataService dataService;
protected setDataService(DataService dataService) {
this.dataService = dataService;
}
@Override
public void onConnectionEstablished() {
String topic = "egmkey/device2/cmd/PING";
System.out.println("connection has been established");
try {
dataService.subscribe(topic, 1);//egmkey/device2/cmd/PING
System.out.println("subscription done to topic" + topic);
} catch (KuraException e) {
System.out.println("failed to subscribe: " + e);
}
}
@Override
public void onMessageArrived(String topic, byte[] payload, int qos, boolean retained) {
System.out.println("message received!!!!!!!!!!!!!!!!!!!!!!:" + topic);
}
}