upgrad esp mqtt lib
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <Updater.h>
|
||||
#include <Ticker.h>
|
||||
|
||||
#include <espMqttClient.h>
|
||||
|
||||
#define WIFI_SSID "yourSSID"
|
||||
@@ -13,6 +15,8 @@
|
||||
WiFiEventHandler wifiConnectHandler;
|
||||
WiFiEventHandler wifiDisconnectHandler;
|
||||
espMqttClient mqttClient;
|
||||
bool reconnectMqtt = false;
|
||||
uint32_t lastReconnect = 0;
|
||||
bool disconnectFlag = false;
|
||||
bool restartFlag = false;
|
||||
|
||||
@@ -23,7 +27,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 onWiFiConnect(const WiFiEventStationModeGotIP& event) {
|
||||
@@ -53,7 +63,8 @@ void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) {
|
||||
}
|
||||
|
||||
if (WiFi.isConnected()) {
|
||||
connectToMqtt();
|
||||
reconnectMqtt = true;
|
||||
lastReconnect = millis();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,16 +136,22 @@ void setup() {
|
||||
}
|
||||
|
||||
void loop() {
|
||||
mqttClient.loop();
|
||||
|
||||
if (disconnectFlag) {
|
||||
// it's safe to call this multiple times
|
||||
mqttClient.disconnect();
|
||||
}
|
||||
|
||||
if (restartFlag) {
|
||||
Serial.println("Rebooting... See you next time!");
|
||||
Serial.flush();
|
||||
ESP.reset();
|
||||
}
|
||||
|
||||
static uint32_t currentMillis = millis();
|
||||
|
||||
mqttClient.loop();
|
||||
|
||||
if (!disconnectFlag && reconnectMqtt && currentMillis - lastReconnect > 5000) {
|
||||
connectToMqtt();
|
||||
}
|
||||
|
||||
if (disconnectFlag) {
|
||||
// it's safe to call this multiple times
|
||||
mqttClient.disconnect();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user