如何访问主要方法Eclipse Paho中回调方法(Messagearrived)到达消息的有效载荷



问题语句: - 我正在尝试自动化mqtt流,因为我需要发布并订阅多个主题,但按顺序订购。诀窍是,从第一个发布中收到的消息具有一些值,该值将在下一个子/酒吧命令中传递。

例如。

  1. sub to topica/abc
  2. topeca/abc
  3. 的酒吧
  4. 在主题/ABC上收到的消息是xyz
  5. sub to topic topica/xyz
  6. 酒吧主题aporiona/xyz

我能够在第一个主题上接收消息,但是我没有得到如何在主方法中访问接收到的消息的有效载荷,然后将其通过并将其连接到下一个sub的下一个主题。

是否有一种方法可以从MessageArrived回调方法中获取消息有效负载到主要方法是在哪里创建客户端实例?

注意: - 我正在使用单个客户端进行发布和订阅。

当我用完的选择和方法时,请帮助我。

编辑: -

代码片段

主类

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 Ingl: -

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);
        }
    }
}

好吧,您现在要做的事情要清楚一些。

简短的答案否,您无法将值传递回"主要方法"。MQTT是异步的,这意味着您不知道何时会订阅的主题到达消息。

您需要更新代码以进行检查,请检查传入的消息主题是什么,然后处理您想在messageArrived()处理程序中使用该响应的任何操作。如果您有一系列任务要执行,则可能需要实现已知的状态机器,以跟踪您的位置。

相关内容

最新更新