arduino-libraries / ArduinoMqttClient

ArduinoMqttClient Library for Arduino
GNU Lesser General Public License v2.1
192 stars 75 forks source link

Reconnect #29

Closed fabltd closed 2 years ago

fabltd commented 4 years ago

Hi

I am using the Google Cloud IoT core example. This requires the broker to reconnect on expiry of the JWT token.

Is there a reconnect option? It seems disconnect() is a private function? I have not dug to far into the code as yet.

aentinger commented 4 years ago

Hi @fabltd :wave: On the very basic level you could try something like this

void loop()
{
  /* ... */
  if (!mqttClient.connected()) {
    Serial.println("MQTT connection lost");
    if (!mqttClient.connect(broker, port)) {
      Serial.print("MQTT reconnection error ");
      Serial.println(mqttClient.connectError());
    }
  }
}
jason-a-alexander commented 2 years ago

@aentinger This was very helpful. I had searched for a while before I found this. I built out this in my main loop to make sure that I'm always connected. It will block the main loop if it can't connect but in my case if I can't connect to the MQTT broker then the rest of my code is not useful anyway as the sensor data has no where to go.

if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;

    if (!mqttClient.connected()) {
      mySerial.println("MQTT Not Connected");
      while (!mqttClient.connect(broker, port)) {
        mySerial.print("MQTT connection failed! Error code = ");
        mySerial.println(mqttClient.connectError());
        delay (10000);
      }
      mySerial.println("You're connected to the MQTT broker!");
      mySerial.println();

      mqttClient.onMessage(onMqttMessage);

      mySerial.println("Getting Inital Subscriptions");
      mqttClient.subscribe(commandUpdate);
      mqttClient.subscribe(commandStartOffset);
      mqttClient.subscribe(commandHouseOffset);
      delay(1000);

    }
aentinger commented 2 years ago

I'm glad to hear this was of help to you @jason-a-alexander 😉

I'm closing this issue, since the OP has disappeared.