I am experimenting with libmosquitto-dev on Raspbian and having some issues.
My code works absolutely fine so far. I can connect to a broker and once the topic gets an update my programm prints the message as it should. It's just the point when the broker dies after connection and gets restarted. My code realize the connection dropped and tries to reconnect. Once the broker is back online my code reconnects. But from this on it does not print any updates on the channel.
Why not? I thought this would catch up the connection fine, but it does not.
Her's my code:
[...]
static int run = 1;
void connect_callback(struct mosquitto *mosq, void *obj, int result)
{
printf("connect callback, rc=%d\n", result);
}
void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
bool match = 0;
printf("got message '%.*s' for topic '%s'\n", message->payloadlen, (char*) message->payload, message->topic);
mosquitto_topic_matches_sub("Heizung", message->topic, &match);
if (match) {
printf("got message for HEIZUNG topic\n");
}
}
int main(int argc, char *argv[])
{
uint8_t reconnect = true;
char clientid[24];
struct mosquitto *mosq;
int rc = 0;
mosquitto_lib_init();
memset(clientid, 0, 24);
snprintf(clientid, 23, "mylog_%d", getpid());
mosq = mosquitto_new(clientid, true, 0);
if(mosq){
mosquitto_connect_callback_set(mosq, connect_callback);
mosquitto_message_callback_set(mosq, message_callback);
rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60);
mosquitto_subscribe(mosq, NULL, "Heizung", 0);
// rc = mosquitto_loop_forever(mosq,20,5); // Tried with this function but same issue.
while(run){
rc = mosquitto_loop(mosq, -1, 1);
if(run && rc){
printf("connection error!\n");
sleep(10);
mosquitto_reconnect(mosq);
}
}
mosquitto_destroy(mosq);
}
mosquitto_lib_cleanup();
return rc;
}
What I see as output is the following:
connect callback, rc=0
got message 'ON1' for topic 'Heizung'
got message for Heizung topic
got message 'ON2' for topic 'Heizung'
got message for Heizung topic
got message 'ON3' for topic 'Heizung'
got message for Heizung topic
connection error!
connect callback, rc=0
You see the connection error (where "systemctl stop mosquitto" took place). And you see reconnection appears to be successful once the broker is back again. But it does not print any of the new messages which are send by the subscriber after the broker is back. Running the mosquitto_sub command in parallel sees all messages!
Any idea what is wrong here? Thanks a lot!
/KNEBB
Move the call to mosquitto_subscribe
to the connect_callback
that way it will get called on a reconnect.
Since you are connecting with the CleanSession flag set to true
each time you reconnect there will be no persistent session so the broker will not know to keep the subscription.