一 编译QtMqtt库
Qt5.10才官方支持MQTT,但我用的Qt版本是5.8.0 Mingw_32BIT, 为了在Qt5.8.0上添加MQTT支持,需要自己编译源码

步骤:

(1) git clone https://github.com/qt/qtmqtt.git

(2) 使用Qt5.8.0自带的qtcreator打开qtmqtt的pro文件,然后切换到release模式编译

(3) 编译结束后会在工程生成的文件下生成如下一些文件

二 连接有人云
(1)首先按照有人云官方的教程添加一个透传设备,我添加的是“默认设备”(也可以是NBIOT等支持透传的设备),设备的ID为:00021153000000000001

(2)然后将这个设备使用有人虚拟串口软件映射为本地的虚拟串口,如下图所示

(3)创建Qt工程,主要代码如下:

#-------------------------------------------------
#
# Project created by QtCreator 2018-12-27T18:02:41
#
#-------------------------------------------------

QT += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = MQTTest
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0

LIBS += -LE:/EWorkSpace/20190109_mqtt/build-qtmqtt-Qt580_MINGW_32BIT-Release/bin -lQt5Mqtt

INCLUDEPATH += E:/EWorkSpace/20190109_mqtt/build-qtmqtt-Qt580_MINGW_32BIT-Release/include

SOURCES += main.cpp \
mainwidget.cpp \
mqttclient.cpp

HEADERS += \
mainwidget.h \
mqttclient.h

FORMS += \
mainwidget.ui
#ifndef MQTTCLIENT_H
#define MQTTCLIENT_H

#include <QObject>
#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttSubscription>

typedef QMqttSubscription::SubscriptionState SubscriptionState;

class MQTTClient : public QObject
{
Q_OBJECT
public:
explicit MQTTClient(const QString &userName, const QString &passwordMD5, const QString &deviceId, QObject *parent = nullptr);
~MQTTClient();

bool isOpened();
void open();
void close();
void write(const QByteArray &data);

private:
QString m_userName;
QString m_passwordMD5;
QString m_deviceId;
QMqttClient *m_client;
QByteArray m_buffer;

private slots:
void doConnected();
void doDisconnected();
void doMessageReceived(const QByteArray &message, const QMqttTopicName &topic);
void doQMqttSubscriptionStateChanged(SubscriptionState subscriptionState);

signals:
void log(const QString &text);

public slots:
};

#endif // MQTTCLIENT_H
#include "mqttclient.h"
#include <QDebug>

#define MQTT_HOSTNAME "clouddata.usr.cn"
#define MQTT_PORT 1883

#define MQTT_CLIENT_SUBSCRIBE_PREFIX "$USR/DevTx"
#define MQTT_CLIENT_PUBLISH_PREFIX "$USR/DevRx"

MQTTClient::MQTTClient(const QString &userName, const QString &passwordMD5, const QString &deviceId, QObject *parent) : QObject(parent)
{
m_client=NULL;
this->m_userName=userName;
this->m_passwordMD5=passwordMD5;
this->m_deviceId=deviceId;
}

MQTTClient::~MQTTClient()
{
if(m_client!=NULL)
{
if(m_client->state()==QMqttClient::Connected)
{
m_client->disconnectFromHost();
}
delete m_client;
m_client=NULL;
}
}

bool MQTTClient::isOpened()
{
if(m_client==NULL)
{
return false;
}
else if(m_client->state()==QMqttClient::Connected)
{
return true;
}
else
{
return false;
}
}

void MQTTClient::open()
{
if(m_client!=NULL)
{
return;
}
m_client = new QMqttClient(this);
m_client->setHostname(MQTT_HOSTNAME);
m_client->setPort(MQTT_PORT);
m_client->setUsername(m_userName);
m_client->setClientId(QString("APP:%1").arg(m_userName));
m_client->setPassword(m_passwordMD5);
m_client->setProtocolVersion(QMqttClient::MQTT_3_1_1);

connect(m_client, SIGNAL(connected()), this, SLOT(doConnected()));
connect(m_client, SIGNAL(disconnected()), this, SLOT(doDisconnected()));
connect(m_client, SIGNAL(messageReceived(QByteArray,QMqttTopicName)), this, SLOT(doMessageReceived(QByteArray,QMqttTopicName)));

m_client->connectToHost();
emit log("MQTTClient 正在连接...");
}

void MQTTClient::close()
{
if(m_client!=NULL)
{
if(m_client->state()==QMqttClient::Connected)
{
m_client->disconnectFromHost();
}
delete m_client;
m_client=NULL;
}
}

void MQTTClient::write(const QByteArray &data)
{
if(m_client!=NULL)
{
m_client->publish(QString("%1/%2").arg(MQTT_CLIENT_PUBLISH_PREFIX).arg(this->m_deviceId), data);
emit log(QString("MQTTClient 正发布设备消息,设备ID: %1, 消息:%2").arg(this->m_deviceId).arg(QString::fromLatin1(data)));
}
}

void MQTTClient::doConnected()
{
emit log("MQTTClient 已建立连接!");
emit log(QString("MQTTClient 正订阅设备消息,设备ID: %1").arg(this->m_deviceId));
QMqttSubscription *subscription=m_client->subscribe(QString("%1/%2").arg(MQTT_CLIENT_SUBSCRIBE_PREFIX).arg(this->m_deviceId));
connect(subscription, SIGNAL(stateChanged(SubscriptionState)),
this, SLOT(doQMqttSubscriptionStateChanged(SubscriptionState)));
}

void MQTTClient::doDisconnected()
{
emit log("MQTTClient 已断开连接!");
this->close();
}

void MQTTClient::doMessageReceived(const QByteArray &message, const QMqttTopicName &topic)
{
emit log(QString("MQTTClient 接收到数据: %1").arg(QString::fromLatin1(message)));
}

void MQTTClient::doQMqttSubscriptionStateChanged(SubscriptionState subscriptionState)
{
if(subscriptionState==QMqttSubscription::Subscribed)
{
emit log("订阅设备消息成功!");
}
}
#ifndef MAINWIDGET_H
#define MAINWIDGET_H

#include <QWidget>
#include "mqttclient.h"

namespace Ui {
class MainWidget;
}

class MainWidget : public QWidget
{
Q_OBJECT

public:
explicit MainWidget(QWidget *parent = 0);
~MainWidget();

private slots:
void on_buttonConnect_clicked();

void on_buttonWrite_clicked();

void on_buttonClear_clicked();

void doLog(const QString &text);

private:
Ui::MainWidget *ui;

MQTTClient *m_mqttClient;
};

#endif // MAINWIDGET_H
#include "mainwidget.h"
#include "ui_mainwidget.h"

MainWidget::MainWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWidget)
{
ui->setupUi(this);
m_mqttClient=NULL;
}

MainWidget::~MainWidget()
{
delete ui;
}

void MainWidget::on_buttonConnect_clicked()
{
if(m_mqttClient!=NULL)
{
m_mqttClient->close();
m_mqttClient=NULL;
}
m_mqttClient=new MQTTClient(ui->lineUsername->text(), ui->linePasswordMD5->text(), ui->lineDeviceId->text());
connect(m_mqttClient, SIGNAL(log(QString)), this, SLOT(doLog(QString)));
m_mqttClient->open();
}

void MainWidget::on_buttonWrite_clicked()
{
if((m_mqttClient==NULL) || (!m_mqttClient->isOpened()))
{
ui->textLog->append("MQTT客户端未打开!");
return;
}
m_mqttClient->write(ui->lineWrite->text().toLatin1());
}

void MainWidget::on_buttonClear_clicked()
{
ui->textLog->clear();
}

void MainWidget::doLog(const QString &text)
{
ui->textLog->append(text);
}
然后运行测试:

(------- 完 -------)
---------------------
作者:Keycer
来源:CSDN
原文:https://blog.csdn.net/zgrjkflmkyc/article/details/86159661
版权声明:本文为博主原创文章,转载请附上博文链接!

Qt5.8.0编译QtMqtt库并使用该库连接有人云的例子的更多相关文章

  1. qt5.4.0编译错误

    error1: 进程"C:\Qt\Qt5.4.0\Tools\QtCreator\bin\jom.exe"退出,退出代码 2 solution:去工具->选项->构建和 ...

  2. VS2013编译Qt5.6.0静态库

    获取qt5.6.0源码包 直接去www.qt.io下载就好了,这里就不详细说了. 这里是我已经编译好的** 链接:http://pan.baidu.com/s/1pLb6wVT 密码: ak7y ** ...

  3. VS2015编译Qt5.7.0生成支持XP的静态库(很不错)

    一.编译工具 1.VS2015 编译Qt5.7.0的所需VS版本:Visual Studio 2013 (Update1)或Visual Studio 2015 (Update2).因为Update补 ...

  4. linux下编译qt5.6.0静态库——configure配置

    linux下编译qt5.6.0静态库 linux下编译qt5.6.0静态库 configure生成makefile 安装选项 Configure选项 第三方库: 附加选项: QNX/Blackberr ...

  5. VS2013编译Qt5.6.0静态库(乌合之众)

    获取qt5.6.0源码包 直接去www.qt.io下载就好了,这里就不详细说了. 这里是我已经编译好的** 链接:http://pan.baidu.com/s/1pLb6wVT 密码: ak7y ** ...

  6. VS2010编译Qt5.4.0静态库

    http://www.kavenblog.com/?p=375 1.Qt的跨平台十分优秀,但是在Windows上是还是会有许多问题,其中之一就是动态链接库的问题,Qt程序的发布必须带一个体积不小的DL ...

  7. linux下编译qt5.6.0静态库——configure配置(超详细,有每一个模块的说明)(乌合之众)

    linux下编译qt5.6.0静态库 linux下编译qt5.6.0静态库 configure生成makefile 安装选项 Configure选项 第三方库: 附加选项: QNX/Blackberr ...

  8. linux下编译qt5.6.0静态库(使用./configure --help来看看都有哪些参数。超详细,有每一个模块的说明。如果改变了安装的目录,需要到安装目录下的bin目录下创建文件qt.conf)(乌合之众)good

    linux下编译qt5.6.0静态库 linux下编译qt5.6.0静态库 configure生成makefile 安装选项 Configure选项 第三方库: 附加选项: QNX/Blackberr ...

  9. VS2013编译Qt5.6.0静态库,并提供了百度云下载(乌合之众)good

    获取qt5.6.0源码包 直接去www.qt.io下载就好了,这里就不详细说了. 这里是我已经编译好的** 链接:http://pan.baidu.com/s/1pLb6wVT 密码: ak7y ** ...

随机推荐

  1. Linux孤儿进程与僵尸进程

    1. 基本概念: 孤儿进程:父进程退出,但是其子进程仍然在运行,那么这些子进程被称为孤儿进程:孤儿进程会被init进程收养,并作善后处理: 僵尸进程:一个已经终止,但是其父进程尚未对齐进行善后处理的进 ...

  2. 笔记:YSmart: Yet Another SQL-to-MapReduce Translator

    http://web.cse.ohio-state.edu/hpcs/WWW/HTML/publications/papers/TR-11-7.pdf  Introduce样例sql语句:" ...

  3. 使用 docker 快速安装 oracle 11g

    前言 我们在手动安装oracle数据库时,安装步骤纷繁复杂,耗时较长 在此介绍如何使用docker快速安装oracle 11g 一.docker 及其安装环境 操作系统: [root@centos7 ...

  4. P4127 [AHOI2009]同类分布

    P4127 [AHOI2009]同类分布 题解 好的,敲上数位DP  DFS板子 记录一下填的各位数字之和 sum ,然后记录一下原数 yuan 最后判断一下  yuan%sum==0 不就好啦??? ...

  5. <JavaScript>“浏览器模式”和“文档模式”之间的区别

    只有IE浏览器中才会有“浏览器模式”和“文档模式”,兼容性视图涉及两个重要的功能便是“浏览器模式[browser mode]”和“文档模式[document mode]”,在IE8/IE9中按F12键 ...

  6. LC 583. Delete Operation for Two Strings

    Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 t ...

  7. python之crawlscrapy爬取某集团招聘信息以及招聘详情

    针对这种招聘信息,使用crawlscrapy很适合. 1.settings.py # -*- coding: utf-8 -*- # Scrapy settings for gosuncn proje ...

  8. Python实现的寻找前5个默尼森数算法示例

    Python实现的寻找前5个默尼森数算法示例 本文实例讲述了Python实现的寻找前5个默尼森数算法.分享给大家供大家参考,具体如下: 找前5个默尼森数. 若P是素数且M也是素数,并且满足等式M=2* ...

  9. TOMCAT web.xml 整理说明

    JavaWeb项目中web.xml有关servlet的基本配置: 我们注意到,tomcat下的conf中也有一个web.xml文件,没错的,所有的JavaWeb项目中web.xml都继承自服务器下的w ...

  10. FlexBox布局的重要属性

    /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { ...