I'm using pubsub library.
void reconnect() {
/* Loop until we're reconnected */
while (!mqttClient.connected()) {
/*#ifdef SERIAL_DEBUG*/
Serial.print("Attempting MQTT broker connection...");
/*#endif*/
/* Attempt to connect */
if (mqttClient.connect(clientId.c_str(),mqttUser,mqttPassword)) {
/*#ifdef SERIAL_DEBUG*/
Serial.println("connected");
/*#endif*/
/* Once connected, resubscribe */
mqttClient.subscribe(command1_topic,1); // subscribe the topics here
}
else {
/*#ifdef SERIAL_DEBUG*/
Serial.print("Failed, rc=");
Serial.print(mqttClient.state());
Serial.println(". Trying again in 5 seconds...");
/*#endif
/* Wait 5 seconds between retries */
delay(5000);
}
}
}