upgrad esp mqtt lib
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
#include <WiFi.h>
|
||||
#include <Ticker.h>
|
||||
|
||||
#include <espMqttClientAsync.h>
|
||||
|
||||
#define WIFI_SSID "yourSSID"
|
||||
@@ -8,6 +10,8 @@
|
||||
#define MQTT_PORT 1883
|
||||
|
||||
espMqttClientAsync mqttClient;
|
||||
bool reconnectMqtt = false;
|
||||
uint32_t lastReconnect = 0;
|
||||
|
||||
void connectToWiFi() {
|
||||
Serial.println("Connecting to Wi-Fi...");
|
||||
@@ -16,7 +20,13 @@ void connectToWiFi() {
|
||||
|
||||
void connectToMqtt() {
|
||||
Serial.println("Connecting to MQTT...");
|
||||
mqttClient.connect();
|
||||
if (!mqttClient.connect()) {
|
||||
reconnectMqtt = true;
|
||||
lastReconnect = millis();
|
||||
Serial.println("Connecting failed.");
|
||||
} else {
|
||||
reconnectMqtt = false;
|
||||
}
|
||||
}
|
||||
|
||||
void WiFiEvent(WiFiEvent_t event) {
|
||||
@@ -57,7 +67,8 @@ void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) {
|
||||
Serial.printf("Disconnected from MQTT: %u.\n", static_cast<uint8_t>(reason));
|
||||
|
||||
if (WiFi.isConnected()) {
|
||||
connectToMqtt();
|
||||
reconnectMqtt = true;
|
||||
lastReconnect = millis();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,5 +133,9 @@ void setup() {
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// nothing to do here
|
||||
static uint32_t currentMillis = millis();
|
||||
|
||||
if (reconnectMqtt && currentMillis - lastReconnect > 5000) {
|
||||
connectToMqtt();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user