- Newest
- Most votes
- Most comments
You can handle the onConnectionInterrupted callback by implementing a mechanism to wait for the connection to be resumed before attempting to publish again. You can use a std::mutex and std::condition_variable to achieve this.
Here's a high-level approach:
Create a std::mutex and a std::condition_variable in your mqttwrapper class. Modify the onConnectionInterrupted callback to lock the mutex and set a connectionInterrupted flag. Modify the onConnectionResumed callback to unset the connectionInterrupted flag, unlock the mutex, and notify the condition variable. Before attempting to publish a message, check the connectionInterrupted flag. If it's set, wait for the condition variable. Here's an example implementation:
#include <condition_variable>
#include <mutex>
class mqttwrapper {
// ...
std::mutex connectionMutex;
std::condition_variable connectionCV;
bool connectionInterrupted = false;
// ...
};
void mqttwrapper::onConnectionInterrupted([[maybe_unused]] Mqtt::MqttConnection &con, int errorCode) {
std::unique_lock<std::mutex> lock(connectionMutex);
connectionInterrupted = true;
cout << "Connection interrupted with error " << ErrorDebugString(errorCode);
}
void mqttwrapper::onConnectionResumed([[maybe_unused]] Mqtt::MqttConnection &con, [[maybe_unused]] Mqtt::ConnectReturnCode ret, bool sessionPresent) {
std::unique_lock<std::mutex> lock(connectionMutex);
connectionInterrupted = false;
cout << "Connection resumed. Session present: " << sessionPresent;
connectionCV.notify_all();
}
bool mqttwrapper::publish(/*...*/) {
// Before attempting to publish, wait for the connection to be resumed if it's interrupted.
std::unique_lock<std::mutex> lock(connectionMutex);
if (connectionInterrupted) {
connectionCV.wait(lock, [this]() { return !connectionInterrupted; });
}
lock.unlock();
// Proceed with publishing the message
// ...
}
This implementation will make the publish function wait for the connection to be resumed before attempting to publish again. This should help you gracefully handle the connection interruption scenario without shutting down and reopening everything.
Relevant content
- asked 5 years ago

Hello,
Thank you for the prompt reply. It would be acceptable except for the fact that we never seem to have the onConnectionResumed() handler called. We were expecting, as you posted above, that the connection would be re-established and the onConnectionResumed() callback called, but currently we have not seem this sequence of callbacks.
See in the sample code above we registered a callback to be called on connection resumed.