【发布时间】:2017-09-13 15:37:08
【问题描述】:
问题陈述:- 我正在尝试自动化 MQTT 流,为此我需要按顺序发布和订阅多个主题。技巧部分是从第一次发布收到的消息有一些值,将在下一个 sub/pub 命令中传递。
例如。
- 子主题A/abc
- 发布到主题A/abc
- 在 topicA/abc 上收到的消息是 xyz
- 主题 topicA/xyz 的子主题
- 发布到主题 topicA/xyz
我能够接收关于第一个主题的消息,但我不知道如何在 main 方法中访问接收到的消息的有效负载并将其传递并附加到下一个主题的下一个主题。
有没有办法将检索到的消息负载从 messageArrived 回调方法获取到创建客户端实例的主要方法?
注意:- 我使用单个客户端进行发布和订阅。
请帮帮我,因为我已经用尽了这样做的选项和方法。
已编辑:-
代码sn-p
主类
public class MqttOverSSL {
String deviceId;
MqttClient client = null;
public MqttOverSSL() {
}
public MqttOverSSL(String deviceId) throws MqttException, InterruptedException {
this.deviceId = deviceId;
MqttConnection mqttConObj = new MqttConnection();
this.client = mqttConObj.mqttConnection();
}
public void getLinkCodeMethod() throws MqttException, InterruptedException {
client.subscribe("abc/multi/" + deviceId + "/linkcode", 0);
publish(client, "abc/multi/" + deviceId + "/getlinkcode", 0, "".getBytes());
}
}
Mqtt Claback impl:-
public class SimpleMqttCallBack implements MqttCallback {
String arrivedMessage;
@Override
public void connectionLost(Throwable throwable) {
System.out.println("Connection to MQTT broker lost!");
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
arrivedMessage = mqttMessage.toString();
System.out.println("Message received:\t" + arrivedMessage);
linkCode(arrivedMessage);
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("Delivery complete callback: Publish Completed "+ Arrays.toString(iMqttDeliveryToken.getTopics()));
}
public void linkCode(String arrivedMessage) throws MqttException {
System.out.println("String is "+ arrivedMessage);
Gson g = new Gson();
GetCode code = g.fromJson(arrivedMessage, GetCode.class);
System.out.println(code.getLinkCode());
}
}
发布者类:-
public class Publisher {
public static void publish(MqttClient client, String topicName, int qos, byte[] payload) throws MqttException {
String time = new Timestamp(System.currentTimeMillis()).toString();
log("Publishing at: "+time+ " to topic \""+topicName+"\" qos "+qos);
// Create and configure a message
MqttMessage message = new MqttMessage(payload);
message.setQos(qos);
// Send the message to the server, control is not returned until
// it has been delivered to the server meeting the specified
// quality of service.
client.publish(topicName, message);
}
static private void log(String message) {
boolean quietMode = false;
if (!quietMode) {
System.out.println(message);
}
}
}
【问题讨论】:
-
如果不与我们共享任何代码,我们真的无能为力
-
嗨,hardilib,在原帖中添加了相同的内容。请看一看。