From a21f65fa00988ebb86a73b1eb4ba5c8bf80c1da6 Mon Sep 17 00:00:00 2001 From: Richard Genoud Date: Tue, 11 Feb 2020 11:03:36 +0100 Subject: [PATCH] thermostat: monitor the mqtt connection --- soft/thermostat/inc/mqttclient.h | 1 + soft/thermostat/src/mqttclient.cpp | 44 ++++++++++++++++++++++++++++++++------ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/soft/thermostat/inc/mqttclient.h b/soft/thermostat/inc/mqttclient.h index 8de4bf2..4077b7e 100644 --- a/soft/thermostat/inc/mqttclient.h +++ b/soft/thermostat/inc/mqttclient.h @@ -33,6 +33,7 @@ public slots: void onStateChanged(ClientState state); void onDisconnected(void); void allHeatersOn(bool on); + void onConnectTimeout(void); signals: void new_temperature(int idx, double val); diff --git a/soft/thermostat/src/mqttclient.cpp b/soft/thermostat/src/mqttclient.cpp index 2a0b70a..5fb9f60 100644 --- a/soft/thermostat/src/mqttclient.cpp +++ b/soft/thermostat/src/mqttclient.cpp @@ -16,6 +16,8 @@ #include "mqttclient.h" #include "settings.h" +#define TIMER_PERIOD_MS 30000 + MQTTClient::MQTTClient(const QString& host, int port, QObject* parent) : QMqttClient(parent) { @@ -32,19 +34,48 @@ MQTTClient::MQTTClient(const QString& host, int port, QObject* parent) connect(this, SIGNAL(stateChanged(ClientState)), this, SLOT(onStateChanged(ClientState))); + connect(&m_timer, SIGNAL(timeout()), this, SLOT(onConnectTimeout())); + m_timer.start(TIMER_PERIOD_MS); } MQTTClient::~MQTTClient() { } +/* + * the QMqttClient doesn't handle auto-reconnection. + * It can stay in the connecting state for ever, even + * if the server is back on. + */ +void MQTTClient::onConnectTimeout(void) +{ + switch (state()) { + case Connecting: + qDebug() << "force to disconnect"; + disconnectFromHost(); + /* fall through */ + case Disconnected: + qDebug() << "re-try do connect"; + connectToHost(); + break; + case Connected: + break; + } +} + void MQTTClient::onStateChanged(ClientState state) { - qDebug() << "mqtt state " << state; + qDebug() << "mqtt state: "; + switch (state) { - case Disconnected: break; - case Connecting: break; - case Connected: break; - default: break; + case Disconnected: + qDebug() << "disconnected"; + break; + case Connecting: + qDebug() << "Connecting"; + break; + case Connected: + qDebug() << "Connected"; + break; } } @@ -68,7 +99,7 @@ void MQTTClient::onError(ClientError error) void MQTTClient::onConnected() { - qDebug() << "connected"; + qDebug() << "subscribe"; this->subscribe(QString("sensors/#"), 1); } @@ -151,7 +182,6 @@ void MQTTClient::allHeatersOn(bool on) { for (int j = 0; j < r->heaters.count(); j++) { const struct Heater *h = &(r->heaters.at(j)); - /* TODO: check if connected */ publish_msg(h->ctrl_topic, payload); } }