plapointe6 / EspMQTTClient

Wifi and MQTT handling for ESP8266 and ESP32
GNU General Public License v3.0
451 stars 135 forks source link

loop blocked if MQTT broker no available #21

Open khriss75 opened 5 years ago

khriss75 commented 5 years ago

Library tested on ESP32 Dev Module. Very smart and powerful library,but (for me) a big issue: If the esp32 boot and no broker MQTT available loop is blocked during mqtt server connecting tentative. During connection mqtt tentative, I use a button that don't react (led stay off or on). No problem during wifi connection.

plapointe6 commented 5 years ago

Hi,

Currently, EspMQTTClient rely on the PubSubClient library to handle MQTT communication. Unfortunatly, the mqtt connect function of PubSubClient block the execution until the timeout is reached. The timount is 15 seconds by default if there is no broker available.

So, this is the cause of the loop blocking when the broker is not available.

I will try to find a solution for this, but it can take time.

I suggest you to look at some alternative like Interrupts : https://lastminuteengineers.com/handling-esp32-gpio-interrupts-tutorial/

You can also take advantage of the two cores of the ESP32 to run two parts of code simultanously.

abqmichael commented 4 years ago

I think that patch I provided to address the reconnection bug has some features to deal with this problem. Though imperfect, the code does service user code while it's working on the reconnection.

ajaybnl commented 4 years ago

Add a timer to periodically connect to mqtt server, not always (in loop of espmqttclient.cpp)

plapointe6 commented 4 years ago

The main issue here is that when _mqttClient.connect() is called in ESPMQTTClient, PubsubClient block the loop completly until a connection is established. The issue does not come from this lib. With ESP32 it may be possible to take advantage of the two cores, but with ESP8266 we are stuck.

Add a timer to periodically connect to mqtt server, not always (in loop of espmqttclient.cpp)

I am not always connecting to MQTT server in the loop, but because of the blocking _mqttClient.connect(), the loop is blocked the first time I try to do it if the server is not available.