qt的mqtt编译及使用方法

在qt5.10之前,mqtt需要自己编译库,

1.源码路径

下载地址:https://github.com/emqx/qmqtt,注意要下载qmqtt-master版本的,不要下载qtmqtt-dev

 

2.生成库文件

使用qtcreator打开qmqtt.pro文件,构建src工程,

编译报错:Could not create directory "...\qmqtt\Error in " Util.asciify("build-qmqtt-Qt_5_6_3_msvc2013-Debug")": TypeError: Property 'asciify' of object Core::Internal::UtilsJsExtension(0x34bb080) is not a function\src"

Error while building/deploying project qmqtt (kit: Qt 5.6.3 (msvc2013))

When executing step "qmake"

解决方法:

左边树,选择项目,将影子构建取消勾选。

 

再次构建src工程,可生成lib文件夹,里面含debug和Release版本的dll和lib文件。

Qt5Qmqtt.dll、Qt5Qmqtt.lib、Qt5Qmqttd.dll、Qt5Qmqttd.lib

3.文件拷贝

将文件拷贝到qt的安装目录指定文件夹下,这样就当作了qt自己的文件来使用了。

3.1.h文件拷贝

在qt的安装目录include文件夹下(如D:\Qt\Qt5.6.3_2013\5.6.3\msvc2013\include),创建文件夹QtMqtt,并将文件夹qmqtt-master\src\mqtt下的.h文件拷贝到QtMqtt文件夹下。

​​​​​​​3.2Lib和dll文件拷贝

Lib文件:将Qt5Qmqtt.lib和Qt5Qmqttd.lib文件拷贝到qt的安装目录的lib文件夹下(如D:\Qt\Qt5.6.3_2013\5.6.3\msvc2013\lib)。

Dll文件:将Qt5Qmqtt.dll和Qt5Qmqttd.dll文件拷贝到qt的安装目录的bin文件夹下(如D:\Qt\Qt5.6.3_2013\5.6.3\msvc2013\bin)。

3.3调用方法

在vs2013工程--右键--属性,C/C++--常规--附加包含目录,添加$(QTDIR)\include\QtMqtt;链接器--输入--附加依赖项,添加$(QTDIR)\lib\Qt5Qmqttd.lib(Release为$(QTDIR)\lib\Qt5Qmqtt.lib)。在使用时,#include <qmqtt.h>即可。

4.Demo演示

关键方法:

m_client = new QMQTT::Client(QHostAddress(ip), port, this);

m_client->setUsername(Username);

m_client->setPassword(Password);

m_client->setClientId(clientid);

m_client->connectToHost();

 

//m_client->setAutoReconnect(true);

 

connect(m_client, &QMQTT::Client::connected, this, [this]() {

const QString content = QLatin1String(" connected");

});

connect(m_client, &QMQTT::Client::disconnected, this, [this]() {

const QString content = QLatin1String(" disconnected");

});

 

connect(m_client, &QMQTT::Client::received, this, [this](const QMQTT::Message& message) {

const QString content = QString("received, Topic: %1, Message: %2").arg(message.topic()).arg(QString(message.payload()));

    });

 

connect(m_client, &QMQTT::Client::pingresp, this, [this]() {

        const QString content = QLatin1String(" pingresp");

    });

connect(m_client, &QMQTT::Client::subscribed, this, [this](const QString& topic, const quint8 qos) {

const QString content = QString("subscribed, Topic: %1, qos: %2").arg(topic).arg(qos);

});

connect(m_client, &QMQTT::Client::unsubscribed, this, [this](const QString& topic) {

const QString content = QString("unsubscribed, Topic: %1").arg(topic);

});

connect(m_client, &QMQTT::Client::published, this, [this](const QMQTT::Message& message, quint16 msgid) {

const QString content = QString("published, Topic: %1, Message: %2, msgid:%3").arg(message.topic()).arg(QString(message.payload())).arg(msgid);

});

connect(m_client, &QMQTT::Client::error, this, [this](const QMQTT::ClientError error) {

const QString content = QString("error, value: %1").arg(error);

});

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章