From e02aaa1b4dc24f81dc49ef88d08b8df8417a6099 Mon Sep 17 00:00:00 2001 From: cziter15 Date: Fri, 19 Mar 2021 16:18:57 +0100 Subject: [PATCH] Fix esp32 timeout --- src/PubSubClient.cpp | 15 ++++++++++++++- src/PubSubClient.h | 8 ++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/PubSubClient.cpp b/src/PubSubClient.cpp index 2b48d2b6..9d03a72b 100755 --- a/src/PubSubClient.cpp +++ b/src/PubSubClient.cpp @@ -8,6 +8,10 @@ #include "PubSubClient.h" #include "Arduino.h" +#ifdef ESP32 +#include +#endif + PubSubClient::PubSubClient() { this->_state = MQTT_DISCONNECTED; this->_client = NULL; @@ -182,14 +186,23 @@ boolean PubSubClient::connect(const char *id, const char *user, const char *pass if (!connected()) { int result = 0; - if(_client->connected()) { result = 1; } else { if (domain != NULL) { +#ifdef ESP32 + WiFiClient* wfc = (WiFiClient*)_client; + result = wfc->connect(this->domain, this->port, ESP32_CONNECTION_TIMEOUT); +#else result = _client->connect(this->domain, this->port); +#endif } else { +#ifdef ESP32 + WiFiClient* wfc = (WiFiClient*)_client; + result = wfc->connect(this->ip, this->port, ESP32_CONNECTION_TIMEOUT); +#else result = _client->connect(this->ip, this->port); +#endif } } diff --git a/src/PubSubClient.h b/src/PubSubClient.h index c70d9fd3..2ee3e261 100755 --- a/src/PubSubClient.h +++ b/src/PubSubClient.h @@ -26,6 +26,14 @@ #define MQTT_MAX_PACKET_SIZE 256 #endif +// ESP32_CONNECTION_TIMEOUT : Specific case for ESP32, we need to manually provide timeout as default (-1) leads to WDT reset (after 5 seconds). +// By default (4500 milliseconds) 4,5 seconds to avoid reaching 5s default watchdog reset time. +// This is multiplied in WiFiClient.cpp (part of arduino-esp32) by 1000 inside [WiFiClient::connect] method. +// ESP8266 Arduino framework in contrast has fixed 5000ms timeout. No need to define it manually here. +#ifndef ESP32_CONNECTION_TIMEOUT +#define ESP32_CONNECTION_TIMEOUT 4500 +#endif + // MQTT_KEEPALIVE : keepAlive interval in Seconds. Override with setKeepAlive() #ifndef MQTT_KEEPALIVE #define MQTT_KEEPALIVE 15