[Solved] [MQTT] disconnect problem after publishing

Hi guys

I am making MQTT code with MQTT libraries and bluemix quickstart

There is one problem.

After the my photon(client) connect and publish some data, the connection between server and client is broken.

This is my code

void loop() {
    
    
    if (client.isConnected()) {
        // client.loop();
        
        Serial.println("Connected");
        char buf[250];
        sprintf(buf, "{\"d\":{\"myName\":\"Photon\",\"potentiometer\": %d }}", analogRead(A0));
        
        client.publish("iot-2/evt/status/fmt/json",buf);
        delay(1000);

    }
    else {
        Serial.println("Disconnected");
        bool rc = client.connect("d:quickstart:Photon:00FFBBCCDE10");
        Serial.println(rc);
    }

}

And the result of serial is here

I don’t know why the connection was broken during publishing.

Are there some ideas to solve this problem?

Is it actually breaking off in the middle of one publish?
That would be odd, but a connection being closed might happen any time for a multitude of reasons, so testing for !client.isConnected() first, (re)connect if required and then publish (or return(); “prematurely” if the (re)connection fails).

loop() doesn’t actually loop but just finishes, then a lot of stuff happens and then loop() gets called again - and so on.
So rather be prepared for a closed connection.

Breaking appears between publishes.

After client.isConnected(), after 3 or 4 publishing, then the connection is broken.

I guess that the delay function may be reason of this problem.

As using interval timer, to avoid disconnection problem

Thank you guys

2 Likes