upadte esp mqtt client
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <Ticker.h>
|
||||
#include <espMqttClientAsync.h>
|
||||
|
||||
#define WIFI_SSID "yourSSID"
|
||||
@@ -11,7 +10,6 @@
|
||||
WiFiEventHandler wifiConnectHandler;
|
||||
WiFiEventHandler wifiDisconnectHandler;
|
||||
espMqttClientAsync mqttClient;
|
||||
Ticker reconnectTimer;
|
||||
|
||||
void connectToWiFi() {
|
||||
Serial.println("Connecting to Wi-Fi...");
|
||||
@@ -30,8 +28,6 @@ void onWiFiConnect(const WiFiEventStationModeGotIP& event) {
|
||||
|
||||
void onWiFiDisconnect(const WiFiEventStationModeDisconnected& event) {
|
||||
Serial.println("Disconnected from Wi-Fi.");
|
||||
reconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
|
||||
reconnectTimer.once(5, connectToWiFi);
|
||||
}
|
||||
|
||||
void onMqttConnect(bool sessionPresent) {
|
||||
@@ -55,7 +51,7 @@ void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) {
|
||||
Serial.printf("Disconnected from MQTT: %u.\n", static_cast<uint8_t>(reason));
|
||||
|
||||
if (WiFi.isConnected()) {
|
||||
reconnectTimer.once(5, connectToMqtt);
|
||||
connectToMqtt();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +100,8 @@ void setup() {
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
|
||||
WiFi.setAutoConnect(false);
|
||||
WiFi.setAutoReconnect(true);
|
||||
wifiConnectHandler = WiFi.onStationModeGotIP(onWiFiConnect);
|
||||
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user