从连接和定时器看起
这段摘自 mqtthandler.cpp,先建立 MQTT 客户端,把连接成功、订阅成功和收到消息接到对应处理函数上。
断线重连间隔设成 3000 ms,调用连接后再等 3 秒检查状态。模拟温湿度的定时器间隔是 1000 ms,下面可以看到它和发布函数怎么连起来。
底层用的是现成的 QMQTT 库,这段展示我整理的业务接线,数据来自模拟,硬件联调还没做。
源码摘录
cpp
#include "mqtthandler.h"
#include <QTimer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QRandomGenerator>
#include <qmqtt_client.h>
#define TOPIC_DATA_UP "/app/data/up"
#define TOPIC_DATA_DOWN "/app/data/down"
#define TOPIC_CTL_UP "/app/control/up"
#define TOPIC_CTL_DOWN "/app/control/down"
MqttHandler::MqttHandler(QObject *parent) : QObject(parent)
{
client = new QMQTT::Client();
client->setClientId("home-app");
//断线或连不上时自动重连,等 broker 启动后可自动接上
client->setAutoReconnect(true);
client->setAutoReconnectInterval(3000);
connect(client, SIGNAL(connected()), this, SLOT(doConnected()));
connect(client, SIGNAL(subscribed(QString, quint8)),\
this, SLOT(doSubscribed(QString, quint8)));
connect(client,SIGNAL(received(QMQTT::Message)),\
this,SLOT(doDataReceived(QMQTT::Message)));
//温湿度模拟定时器:连接成功后每隔1秒发布一条模拟数据
simTimer = new QTimer(this);
simTimer->setInterval(1000);
connect(simTimer, SIGNAL(timeout()), this, SLOT(publishSimulation()));
}
void MqttHandler::connectToHost()
{
client->connectToHost();
//3s后检测一下连接状态
QTimer::singleShot(3000, this, SLOT(detectState()));
}