Client.subscribe is not working while using client.disconnect() and client.connect() in main loop

Hello All,
I am using MQTT. h library for publish and subscribe data on MQTT broker. But getting stuck at one point, when I disconnect and connect client in the main loop, “client.subscribe(“Status”,MQTT::QOS1);” is stopped to work. I am using client.disconnect(); and
client.connect(“spark-client”, “user name”, “pass”); to reset message-id. If I will not do connect and disconnect then it works fine but all-time message-id is incremented by 2. so, is there any solution to solve this problem?
Thank in advance.

#include <MQTT.h>

void callback(char* topic, byte* payload, unsigned int length);

MQTT client(server1, 1883, callback,512);

// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;
    Serial.println("messageid_retrun");
    if (!strcmp(p, "RED"))
        RGB.color(255, 0, 0);
    else if (!strcmp(p, "GREEN"))
        RGB.color(0, 255, 0);
    else if (!strcmp(p, "BLUE"))
        RGB.color(0, 0, 255);
    else
        RGB.color(255, 255, 255);
    delay(1000);
}


void qoscallback(unsigned int messageid) {
    Serial.print("Ack Message Id:");
    Serial.println(messageid);
}
void setup() {
    RGB.control(true);

 // connect to the server
 client.connect("spark-client", "user name", "pass");

 if (client.isConnected()){
          client.subscribe("Status",MQTT::QOS1);
          Serial.println("connected");
      }
}

void loop() {
  
    // to reset message id so, always get 2 as a message id back
    client.disconnect(); 
    
    delay(2000);
    
    client.connect("spark-client", "user name", "pass");
    
    cl_func();
    
}

void cl_func(){
    uint16_t messageid;
    if (client.isConnected()){
           client.loop();
           client.publish("outTopic/message", "hello world ",MQTT::QOS1, &messageid);
           Serial.println(messageid);
    }
}
--------------------
Output on the serial :
2
2...
------------------

Just a quick note: It’s not best practice to have a long delay() inside a callback function of any kind.

I have also reformatted your post to first set the context and then post the code while also wrapping the code blocks into the appropriate format (can be done via this image smart icon).

For your issue at hand, when you actively disconnect from the broker you should resubscribe since you actively told the broker that you won’t be interested in the subscription anymore.
On the other hand when your client loses connection your subscriptions will still be intact when you reconnect in a timely fashion.

However, why would you need to reset the message ID?

Looking at the MQTT library it’s not surprising that the message ID always gets incremented by two

        if (qos == QOS2 || qos == QOS1) {
            nextMsgId += 1;
            buffer[length++] = (nextMsgId >> 8);
            buffer[length++] = (nextMsgId & 0xFF);
            if (messageid != NULL)
                *messageid = nextMsgId++;
        }

on entry nextMsgId is incremented and then when its value is requested (by passing in an out-parameter) it will be incremented again for the next time round.
Don’t ask me why that’s the case, it’s just how that library was written :wink:

Thanks for response. to get always same id from broker for particular packet, and that’s why I do connect and disconnect. Otherwise its increment by two for each packet

Let me rephrase: Why would this present a problem when the message ID increments?
That ID is meant to provide some chronological reference and shall not be reset on a mere whim.

e.g. by means of the message ID the receiver can discard outdated messages when a lower ID message is received after a higher ID (this can happen when lots of messages are sent in fast succession and the TCP packets travel different ways).

Ya you are right but not resetting id but disconnect network so it will connect again and provide same id back instead of every time increment by 2.
And I also checked library there is also not written anything to increment by 2 so from where I am getting 2 and increment by 2

I have explained that above already

Not sure why, but as it’s not compulsory to increment by 1 only this behaviour is still in specs.
The only thing that is defined is that for QoS1 & 2 the ID must increment unless it wraps around at 65535.

1 Like

Thanks a lot. but fro this, there is any solution.

For your issue at hand, when you  ***actively***  disconnect from the broker you  *should*  resubscribe since you actively told the broker that you won’t be interested in the subscription anymore.
On the other hand when your client  ***loses***  connection your subscriptions will still be intact when you reconnect in a timely fashion.

If I understand that (somewhat confusing) sentence correctly

That quote already contains the solution too :wink:

So now I knew that actually QOS1 is increment by 1 in MQTT.h library so if I publish that time it increment by 1 and when I get PUBACK then increment by 1 so getting 2.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.