一, 需求
Qt使用mqtt协议与服务端进行通信。
二,使用
- 所有源码加入到工程里,我比较喜欢源码引用,这样在跨平台时,省去了路径的配置。
https://github.com/emqx/qmqtt - 写一个单例,建立连接,并在连接成功时,订阅 主题。
#ifndef MQTTMANAGERT_H
#define MQTTMANAGERT_H
#include <iostream>
#include <mqtt/qmqtt.h>
class MQTTManager:public QObject
{
Q_OBJECT
public:
static MQTTManager* instance();
void setInTemperature(QString newInTemperature);
private:
~MQTTManager();
MQTTManager();
public slots:
void doConnected();
void onSubscribed(const QString& topic);
void doDisconnected();
void doDataReceived(QMQTT::Message message);
signals:
void inTemperatureChanged();
private:
//mqtt客户端
QMQTT::Client *client;
static MQTTManager *manager;
//室内温度
QString inTemperature;
};
#endif // MQTTMANAGERT_H
#include "mqttManagert.h"
MQTTManager* MQTTManager::manager=nullptr;
const QString HOST= "127.0.0.1";
//温度和湿度
const QString TOPIC_IN_TEMPERATURE_HUMIDITY ="qmqtt/in_temperature_humidity";
MQTTManager::MQTTManager(){
client = new QMQTT::Client(QHostAddress(HOST),1883,this);
connect(client,&QMQTT::Client::connected,this,&MQTTManager::doConnected);
connect(client,&QMQTT::Client::disconnected,this,&MQTTManager::doDisconnected);
connect(client,&QMQTT::Client::received,this,&MQTTManager::doDataReceived);
connect(client, &QMQTT::Client::subscribed, this, &MQTTManager::onSubscribed);
client->connectToHost();
}
MQTTManager::~MQTTManager(){
client->disconnected();
}
MQTTManager* MQTTManager::instance(){
if(!manager){
manager = new MQTTManager();
}
return manager;
}
void MQTTManager::doConnected(){
qDebug()<<"doConnected ok";
client->subscribe(TOPIC_IN_TEMPERATURE_HUMIDITY);
}
void MQTTManager::onSubscribed(const QString& topic)
{
qDebug() << "onSubscribed " << topic;
}
//解析数据
void MQTTManager::doDataReceived(QMQTT::Message message){
QString mes = QString(message.id())+" "+QString(message.qos())+" "+message.topic()+" "+message.payload()+"\n";
if(message.topic()==TOPIC_IN_TEMPERATURE_HUMIDITY){
QStringList dataList = QString(message.payload()).split(",");
if(dataList.size()==2){
setInTemperature(dataList[0]);
}
}
}
void MQTTManager::doDisconnected(){
qDebug()<<"doDisconnected ok";
}
void MQTTManager::setInTemperature(QString newInTemperature)
{
if (inTemperature == newInTemperature)
return;
inTemperature = newInTemperature;
emit inTemperatureChanged();
}
- 发布主题,直接调用publish函数
publish(const QMQTT::Message& message)