一、下载QtMqtt交叉编译包
https://github.com/qt/qtmqtt
本文用的是5.12版本
二、交叉编译QtMqtt
使用QtCreator打开下载的交叉编译包
先编译一下
进入这个文件夹,复制一下的这些头文件
然后进入工程目录的编译文件夹中Debug或者Release都行
复制一份到这里
然后QtMqtt文件夹里面也复制一份
最后编译一次
三、使用编译成功的QtMqtt动态链接库
进入Debug或者Release中的lib文件夹复制下面的文件
到你自己的QT项目
建立这两个文件夹
把刚刚复制的那几个文件复制进lib里面去
然后复制之前那些头文件进include/QtMqtt
四、引入库
在工程的pro文件中这里需要加一个network
添加QtMqtt库
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/lib/ -lQt5Mqtt
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/lib/ -lQt5Mqttd
添加头文件inlcude
INCLUDEPATH += $$PWD/include
DEPENDPATH += $$PWD/include
最终成果
五、使用QMqttClient连接MQTT服务器
引入头文件
#include "QtMqtt/qmqttclient.h"
初始化QMqttClient对象、异步连接回调、接收消息异步回调
protected:
QMqttClient *pMqttClient;//mqtt服务器对象
protected slots:
void connected_isr();//连接回调函数
private slots:
void recv_message(QByteArray message);//接收消息回调
实例化QMqttClient对象
pMqttClient=new QMqttClient(this);
连接mqtt服务器
pMqttClient->setHostname(IP地址);
pMqttClient->setPort(1883);
pMqttClient->connectToHost();
连接异步槽
connect(pMqttClient,&QMqttClient::connected,
this,&Widget::connected_isr);
connect(pMqttClient,&QMqttClient::messageReceived,
this,&Widget::recv_message);
编写异步函数
//成功连接回调
void Widget::connected_isr()
{
qDebug()<<"Connected successfully!";
pMqttClient->subscribe(QMqttTopicFilter("test"));//订阅频道
}
//收到消息回调
void Widget::recv_message(QByteArray message)
{
qDebug()<<message;
}
需要发布消息的时候这样发布消息
QString topic="test";//发布的频道
QString payload="123456";//消息内容体
pMqttClient->publish(QMqttTopicName(topic),payload.toLocal8Bit());//发布消息
效果
结束