 Ticker wifiReconnectTimer;
 
 void connectToWifi() {
-  wifiReconnectTimer.detach();
   Serial.println("Connecting to Wi-Fi...");
   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
 }


  if (WiFi.isConnected()) {
    Serial.println("Connecting to MQTT...");
    mqttReconnectTimer.attach(2, connectToMqtt);
  }
}


void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  Serial.println("Disconnected from Wi-Fi.");
  mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  wifiReconnectTimer.once(2, connectToWifi);
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

