Are there any MQTT libraries that do not block while connecting?
I'm currently using PubSubClient, and the connection part contains this code: https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.cpp
while (!_client->available()) {
unsigned long t = millis();
if (t-lastInActivity >= ((int32_t) MQTT_SOCKET_TIMEOUT*1000UL)) {
_state = MQTT_CONNECTION_TIMEOUT;
_client->stop();
return false;
}
}
I'd like my main loop to continue, or a callback to be called, while the MQTT connection is established, rather than waiting for ages if the MQTT server is unavailable.
Update:
I wrote a modification to take a callback function, and called it in an else clause added to that if statement, and discovered that the blocking delay is not this while loop. I think it's in the _client->connect at the start of the method.
1 Answer 1
I had the same question and found an mqtt library that is completely non-blocking.
You need to manually install it and the docs give instructions:
It requires one additional library:
- for esp8266: https://github.com/me-no-dev/ESPAsyncTCP
- for esp32: https://github.com/me-no-dev/AsyncTCP
I also liked the example's use of the Ticker library as a general tool for non-blocking code.