Skip to content

Instantly share code, notes, and snippets.

@depperson
Created August 4, 2020 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save depperson/2336584e6a31b7209da08e96f87cbe43 to your computer and use it in GitHub Desktop.
Save depperson/2336584e6a31b7209da08e96f87cbe43 to your computer and use it in GitHub Desktop.
// thanks Adafruit!
void loop()
{
// publish temp
MQTT_connect();
...
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) return;
Serial.print("Connecting to MQTT...");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("done.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment