Attempt to fix blocking mqtt reconnect
This commit is contained in:
parent
fd787a05b2
commit
6474447e53
55
buttons.cpp
55
buttons.cpp
|
@ -17,11 +17,13 @@ int input3_value = 0;
|
|||
int input4_value = 0;
|
||||
|
||||
int led_timeout = 1000;
|
||||
|
||||
long led_time = 0;
|
||||
|
||||
long last_wifi_check_time = 0;
|
||||
|
||||
long lastReconnectAttempt = 0;
|
||||
long reconnectAttempts = 0;
|
||||
|
||||
long debouncing_time = 1000;
|
||||
volatile unsigned long last_micros;
|
||||
|
||||
|
@ -94,25 +96,21 @@ void setup_wifi() {
|
|||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
|
||||
void reconnect() {
|
||||
// Loop until we're reconnected
|
||||
while (!client.connected()) {
|
||||
Serial.print("Attempting MQTT connection...");
|
||||
// Create a random client ID
|
||||
String clientId = "ESP8266Client-";
|
||||
clientId += String(random(0xffff), HEX);
|
||||
// Attempt to connect
|
||||
if (client.connect(clientId.c_str())) {
|
||||
Serial.println("connected");
|
||||
// Once connected, publish an announcement...
|
||||
boolean reconnect() {
|
||||
reconnectAttempts++;
|
||||
#
|
||||
String clientID = "ESP8266Client-";
|
||||
clientID += String(random(0xffff), HEX);
|
||||
|
||||
if (client.connect(clientID.c_str())) {
|
||||
Serial.println("MQTT Connected");
|
||||
} else {
|
||||
Serial.print("failed, rc= ");
|
||||
Serial.print("failed, rc = ");
|
||||
Serial.print(client.state());
|
||||
Serial.println(" try again in 1 second");
|
||||
// Wait 1 seconds before retrying
|
||||
delay(1000);
|
||||
}
|
||||
Serial.println("Trying again");
|
||||
}
|
||||
|
||||
return client.connected();
|
||||
}
|
||||
|
||||
void setup() {
|
||||
|
@ -191,10 +189,6 @@ void Interrupt4() {
|
|||
void loop() {
|
||||
long now = millis();
|
||||
|
||||
if (!client.connected()) {
|
||||
reconnect(); // mqtt
|
||||
}
|
||||
|
||||
if (now - last_wifi_check_time > WIFI_TIMEOUT) {
|
||||
Serial.print("Checking WiFi... ");
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
|
@ -206,10 +200,27 @@ void loop() {
|
|||
last_wifi_check_time = now;
|
||||
}
|
||||
|
||||
if (!client.connected()) {
|
||||
if (now - lastReconnectAttempt > 5000) {
|
||||
lastReconnectAttempt = now;
|
||||
// Attempt to reconnect
|
||||
Serial.println("Attempting MQTT reconnect");
|
||||
if (reconnect()) {
|
||||
reconnectAttempts = 0;
|
||||
lastReconnectAttempt = 0;
|
||||
}
|
||||
if (reconnectAttempts > 5) {
|
||||
Serial.println("mqtt failed too many times, restarting wifi");
|
||||
setup_wifi();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
client.loop();
|
||||
}
|
||||
|
||||
if (now - led_time > led_timeout) {
|
||||
digitalWrite(LED_PIN, 0);
|
||||
}
|
||||
|
||||
client.loop(); // mqtt client
|
||||
ArduinoOTA.handle();
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user