Anime Lover
Anime Lover

Reputation: 1

How MQTT QoS token work in Paho MQTT C code?

I have a difficult to understand how token QoS work in Paho MQTT C code. My idea is that I want to read the PUBACK when using the QoS =1, for publisher to know the delivery have complete.

Using mosquitto -v in linux

But from what I know that not possible, only setup a QoS token is. So from the example in https://github.com/eclipse/paho.mqtt.c/tree/master/src/samples.

So the code is: https://github.com/dinhnamvn123/TestMQTT/blob/main/TestMQTT.cpp

Adding delivered() and MQTTAsync_setCallbacks() to setup QoS token.

void delivered(void *context, MQTTAsync_token dt)
{
        printf("Message with token value %d delivery confirmed\n", dt);
        TOKEN_DEL = dt;
}

When running the code, delivered() will be call when QoS = 1 or 2, meaning the acknowledgement between Publisher and Broker are finishes. But there is one place I don't understand why there is an option for token be an attribute for MQTTAsync_sendMessage

MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
**MQTTAsync_token token;**

opts.onSuccess = onSend;
opts.onFailure = onSendFailure;
opts.context = client;
**opts.token = token;**
pubmsg.payload = &payload;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;

if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
    printf("Failed to start sendMessage, return code %d\n", rc);
    exit(EXIT_FAILURE);
}

I couldn't understand what it do?

Upvotes: 0

Views: 1024

Answers (1)

Létranger Jaylin
Létranger Jaylin

Reputation: 11

As Brits said, the token is for you to associate with the message you just sent. To be more specific, the "opts.token" refers to the packet identifier (packet ID) of your published message. You can find the detailed explanation in the following link: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc358219870. Basically, it is a unique identifier for each QoS message. Because MQTT guarantees your QoS message is delivered in sequence. What it does is: When you publish a QoS message, SDK gonna generate a unique ID for each message, and the MQTT broker will assure you that the message you published will be delivered in the sequence of the packet identifier. and client is going to acknowledge each QoS message with this token/PacketID.

Suppose you are working with MQTT solution. I recommend you an MQTT broker:https://github.com/emqx/nanomq. It is an excellent alternative to Mosquitto.

Upvotes: 1

Related Questions