Get Publish Response/PubAck latency with paho org.eclipse.paho.client.mqttv3.MqttClient publish

484 views Asked by At

I am using paho library Classes for Mqtt Connections org.eclipse.paho.client.mqttv3.MqttClient. (not MqttAsyncClient)

In my case when I publish using

mqttClient.publish(uid + "/p", new MqttMessage(payload.toString().getBytes()));

This method does the task for me but doesn't return anything so I can't check the latency between publish and pubAck.

To get the latency I use the following instead of directly calling publish function of mqttClient.

    public long publish(JsonObject payload , String uid, int qos) {
    try {
        MqttTopic topic = mqttClient.getTopic(uid + "/p");
        MqttMessage message = new MqttMessage(payload.toString().getBytes());
        message.setQos(qos);
        message.setRetained(true);
        long publishTime = System.currentTimeMillis();            
        MqttDeliveryToken token = topic.publish(message);           
        token.waitForCompletion(10000);
        long pubCompleted = System.currentTimeMillis();
        if (token.getResponse() != null && token.getResponse() instanceof MqttPubAck) {
            return pubCompleted-publishTime;
        }
        return -1;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

This gets the work done, but I am not sure whether this is the right approach or not. Please let me know in case there is some other way to to do this.

0

There are 0 answers