ct-Open-Source / Basecamp

An Arduino library to ease the use of the ESP32 in IoT projects
GNU General Public License v3.0
254 stars 48 forks source link

Replace the polling task MqttHandling with a function called by Async-MQTT-Client KeepAlive #64

Closed obrain17 closed 5 years ago

obrain17 commented 6 years ago

Improvement of MQTT Re-Connect

Replace the polling task


xTaskCreatePinnedToCore(&MqttHandling, "MqttTask", defaultThreadStackSize, (void *)&mqtt, defaultThreadPriority, NULL, 0);

that is periodically calling the function


void Basecamp::MqttHandling(void *mqttPointer)

with a function that is called only on MQTT disconnect by the Async-MQTT-Client KeepAlive functionality.

Create a timer and register an onDisconnect callback function that manages the (re)connection of the MQTT client. It will be called by the Asyc-MQTT-Client KeepAlive function if a connection loss is detected. The timer is then started and will start a function to reconnect MQTT after 2 seconds

    mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)&mqtt, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
    mqtt.onDisconnect(onMqttDisconnect);

Async-MQTT-Client will call the callback

If WiFi is not available the timer will be restarted to try again after 2 seconds.

The functionality was successfully tested with

In both cases the MQTT connection was established again.

Tests with mqttGuard have yet to be done.