fgalan
fgalan

Reputation: 12294

How can I disable retries in mosquitto_connect() function?

Using this program:

/*
  compile using:
  $ gcc -o libmosq libmosq.c -lmosquitto
*/
#include <stdio.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <unistd.h>

void connection_callback(struct mosquitto* mosq, void *obj, int rc)
{
  if (rc) {
    printf("connection error: %d (%s)\n", rc, mosquitto_connack_string(rc));
  }
  else {
    printf("connection success\n");
  }
}

int main(int argc, char *argv[])
{
  struct mosquitto *mosq = NULL;
  
  mosquitto_lib_init();
  mosq = mosquitto_new(NULL, true, NULL);
  if(!mosq) {
     fprintf(stderr, "Error: Out of memory.\n");
     exit(1);
  }

  mosquitto_connect_callback_set(mosq, connection_callback);
  mosquitto_username_pw_set(mosq, "user1", "passwd1");

  int resultCode = mosquitto_connect(mosq, "localhost", 1883, 60);
  if (resultCode != MOSQ_ERR_SUCCESS) {
    fprintf(stderr, "error calling mosquitto_connect\n");
    exit(1);
  }

  int loop = mosquitto_loop_start(mosq);
  if(loop != MOSQ_ERR_SUCCESS){
    fprintf(stderr, "Unable to start loop: %i\n", loop);
    exit(1);
  }

  // hang until control+C is done
  sleep(1000000);
}

(It's the same one published in this post with a little difference: exit(1) removed in the connection callback for the fail case)

In case of wrong user/pass I'm getting a loop of error messages:

connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
...

one per second, more or less.

Thus, I guess that mosquitto_connect() retries connection in case of fail so the connection callback is called on each attemp. This could make sense in the case of problems due to the network but in this case (wrong user/pass) it doesn't make sense to retry.

Thus, I'll prefer to manage connection errors and retries in my program logic. Is there any way to disable retries in mosquitto_connect()? I have looked library documentation but I haven't found any parameter for that...

Upvotes: 1

Views: 598

Answers (1)

hardillb
hardillb

Reputation: 59628

If you stop the client network loop (mosquitto_loop_stop(mosq);) it won't attempt to reconnect as it's this loop that handles the reconnection cycle.

Upvotes: 2

Related Questions