MQTT library error, while using in electron

Hy,

#include "MQTT.h"

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

/**
 * if want to use IP address,
 * byte server[] = { XXX,XXX,XXX,XXX };
 * MQTT client(server, 1883, callback);
 * want to use domain name,
 * exp) iot.eclipse.org is Eclipse Open MQTT Broker: https://iot.eclipse.org/getting-started
 * MQTT client("iot.eclipse.org", 1883, callback);
 **/

byte server[] = { XXX.XXX.XXX.XXXX };//the IP of broker
void callback(char* topic, byte* payload, unsigned int length);

MQTT client(server, 1883, callback);


// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;

    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 setup() {
    RGB.control(true);

    // connect to the server
    client.connect("sparkclient");

    // publish/subscribe
    if (client.isConnected()) {
        client.publish("outTopic/message","hello world");
        client.subscribe("inTopic/message");
    }
}

void loop() {
    if (client.isConnected())
        client.loop();
}

i have used this Sample code test.
it works for 5 or 6 Publishing and stops responding afterwards and i have to hard reset.
Please help me out.

1 Like

Possibly the default keepalive time (15 seonds I believe) should be longer? Also, I suggest you rework the loop() function somewhat like:

void loop() {
  if (client.isConnected())
    client.loop();
  else {
    client.connect("sparkclient");
    if (client.isConnected()) {
      client.subscribe("topic");
      // other preparations to set up your connection
    }
  }
}

Have the exact same issue. Not sure how many publishes/receives mine works for, but it locks up. My code is different, but same library.

@netpex Have you tried what @joost suggested?

When you say it “locks up” what exactly do you mean? There are plenty of other possible causes of something locking up. It’s one thing if it just stops publishing, another if it doesn’t publish to serial, LED shows error states, etc. Have you isolated the code you suspect is problematic in a simple test program?