diff --git a/soft/thermostat/inc/mainwindow.h b/soft/thermostat/inc/mainwindow.h index f3d883f..4ea9616 100644 --- a/soft/thermostat/inc/mainwindow.h +++ b/soft/thermostat/inc/mainwindow.h @@ -34,8 +34,6 @@ public: explicit MainWindow(QWidget *parent = NULL); ~MainWindow(); - MQTTClient *mqttclient; - private: QPushButton m_state_btn; BackgroundLoop m_backLoop; diff --git a/soft/thermostat/inc/mqttclient.h b/soft/thermostat/inc/mqttclient.h index 7390c93..96cb969 100644 --- a/soft/thermostat/inc/mqttclient.h +++ b/soft/thermostat/inc/mqttclient.h @@ -18,13 +18,15 @@ class MQTTClient: public QMQTT::Client { Q_OBJECT public: + void publish_msg(const QString& topic, const QString& payload); + static MQTTClient *getInstance(void); + +private: explicit MQTTClient(const QHostAddress& host = QHostAddress::LocalHost, const quint16 port = 1883, QObject* parent = NULL); virtual ~MQTTClient(); - void publish_msg(const QString& topic, const QString& payload); - -private: + static MQTTClient *_singleton; QTimer m_timer; public slots: diff --git a/soft/thermostat/src/mainwindow.cpp b/soft/thermostat/src/mainwindow.cpp index 6a67631..311e961 100644 --- a/soft/thermostat/src/mainwindow.cpp +++ b/soft/thermostat/src/mainwindow.cpp @@ -21,10 +21,8 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ZoneItem *zone; - Settings *s = Settings::getInstance(); - - mqttclient = new MQTTClient(QHostAddress(s->m_broker.address), s->m_broker.port); + MQTTClient *mqttclient = MQTTClient::getInstance(); for (int i = 0; i < s->nbZones(); i++) { zone = new ZoneItem(s->m_rooms.at(i).name, this); @@ -69,8 +67,6 @@ MainWindow::MainWindow(QWidget *parent) : setWindowTitle(tr("Sorico's thermostat")); m_backLoop.start(); - mqttclient->connectToHost(); - connect(&m_state_btn, SIGNAL(clicked()), this, SLOT(change_state())); } diff --git a/soft/thermostat/src/mqttclient.cpp b/soft/thermostat/src/mqttclient.cpp index c3c787f..5ce6f2f 100644 --- a/soft/thermostat/src/mqttclient.cpp +++ b/soft/thermostat/src/mqttclient.cpp @@ -16,6 +16,19 @@ #include "settings.h" #include "qmqtt.h" +MQTTClient *MQTTClient::_singleton = NULL; + +MQTTClient *MQTTClient::getInstance(void) +{ + if (!_singleton) { + Settings *s = Settings::getInstance(); + + _singleton = new MQTTClient(QHostAddress(s->m_broker.address), s->m_broker.port); + } + + return _singleton; +} + MQTTClient::MQTTClient(const QHostAddress& host, const quint16 port, QObject* parent) : QMQTT::Client(host, port, parent) { @@ -24,7 +37,8 @@ MQTTClient::MQTTClient(const QHostAddress& host, const quint16 port, connect(this, &MQTTClient::received, this, &MQTTClient::onReceived); connect(this, &MQTTClient::published, this, &MQTTClient::onPublished); connect(this, &MQTTClient::error, this, &MQTTClient::onError); - qDebug() << "created" << endl; + + connectToHost(); } MQTTClient::~MQTTClient() {