 }
 
 void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
-  Serial.println("** Disconnected from the broker **");
-  Serial.println("Reconnecting to MQTT...");
-  mqttClient.connect();
+  Serial.println("Disconnected from MQTT.");
+
+  if (WiFi.isConnected()) {
+    Serial.println("Connecting to MQTT...");
+    mqttReconnectTimer.attach(2, connectToMqtt);
+  }
 }
 
 void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
-  Serial.println("** Subscribe acknowledged **");
+  Serial.println("Subscribe acknowledged.");
   Serial.print("  packetId: ");
   Serial.println(packetId);
   Serial.print("  qos: ");

  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onMessage(onMqttMessage);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(IPAddress(192, 168, 1, 20), 1883);
  mqttClient.setKeepAlive(5).setCleanSession(false).setWill("topic/online", 2, true, "no").setCredentials("username", "password").setClientId("myDevice");
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void loop() {
}

}

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println("Publish received.");
  Serial.print("  topic: ");
  Serial.println(topic);
  Serial.print("  qos: ");
