I'm struggling with Mqtt paho driver...
I am using IMqttDeliveryToken to get an Acknowledge from the server whenever my publish has been received.
To compare it with the actual publish message, I set up an ID on the MqttMessage in order to retrieve it from the IMqttDeliveryToken... But it doesn't work... The IMqttDeliveryToken.getMessageId() returns an incorrect ID and when I try to get the ID after a IMqttDeliveryToken.getMessage() when the QoS is different from 0, it returns a NPE.
After reading the Javadoc, I read that it's the usual behavior :
Until the message has been delivered, the message being delivered will be returned. Once the message has been delivered null will be returned.
Which lead me to another question... Is the deliveryComplete() method really called after an Broker sent an Acknowledgement ?
Here is my code :
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable thrwbl) { }
@Override
public void messageArrived(String string, MqttMessage mm) throws Exception { }
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
try {
System.out.println("Message ID from getMessageId() method : " + token.getMessageId());
MqttMessage message = token.getMessage();
System.out.println("Message ID from getMessage() method : " + message.getId());
} catch (MqttException ex) {
System.out.println(ex);
} catch (Exception ex) {
System.out.println(ex);
}
}
});
MqttMessage message = new MqttMessage();
message.setId(76);
message.setPayload("pouet".getBytes());
message.setQos(0);
client.publish("TEST", message);
With QoS to 0 :
Message ID from getMessageId() method : 1
Message ID from getMessage() method : 76
With QoS to 1 :
Message ID from getMessageId() method : 1
java.lang.NullPointerException
As mentioned in the git MqttMessage.java
This is is no where used while publishing the message. Now To understand why Message ID from getMessageId() method : 1 happened have a look at following.
MqttDeliveryToken does not set the message id here .While publishing MqttPublish instance is created which internally extends multilevel to MqttWireMessage.java and the value is set to 0 by default.
When Final Send is called for mqtt publishing in ClientState.java , MqttWireMessage instance (Internally MqttPublish is send from above code) which had msgId = 0 is forwarded due to which the if condition is true and the getNextMessageId() is called which returns 1 (since it is a first message, else it would have returned subsequent value depending on last msg id) and is set to token which in your code you are tracking in deliveryComplete().