当前位置:网站首页>QT connect to Alibaba cloud using mqtt protocol
QT connect to Alibaba cloud using mqtt protocol
2022-06-22 06:40:00 【Xiao Xu trying to move forward】
Compile source code
Refer to the following article for source code compilation , There may be some errors in the compilation process , You can refer to the article for solutions
Qt5 Use Qt official Qt MQTT_ Xiaohai's blog -CSDN Blog
Interface design
main interface

History connection interface

listWidget Item Interface

Code design
main interface .cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Set up label Display state
ui->lbShowState->setText(" Connection status :Disconnected");
// Create a new client
this->m_client = new QMqttClient(this);
// Open data file The file location is the current project
QFile file(".//historyData.json");
// Open the file read-only
bool isOpened = file.open(QIODevice::ReadOnly);
// When you first set up the program The file does not exist Therefore, it is necessary to determine whether the file can be opened in a read-only way
// But when writing a file, if the file does not exist, it will automatically create a file
if(isOpened)
{
// establish json file , Read all data from the data text
QJsonDocument historyJDocument = QJsonDocument::fromJson(file.readAll());
// adopt json Document access json Array
this->historyJArray = historyJDocument.array();
// Close file
file.close();
}
else
{
qDebug() << " File not open ";
}
// Click the connect button to execute
connect(ui->btnConnect,&QPushButton::clicked,[=](){
if(ui->btnConnect->text() == " Connect ")
{
// Set domain name
this->m_client->setHostname(ui->leHostname->text());
// Set port
this->m_client->setPort(ui->lePort->text().toInt());
// Set the username
this->m_client->setUsername(ui->leUsername->text());
// Set the password
this->m_client->setPassword(ui->lePassword->text());
// Set user Id
this->m_client->setClientId(ui->leClientId->text());
// Connect
this->m_client->connectToHost();
}
else
{
// disconnect
this->m_client->disconnectFromHost();
}
});
// Monitor status change
// After successful connection Store connection information , If the password of the information is the same as that of the existing information , Do not store
connect(this->m_client,&QMqttClient::stateChanged,[=](QMqttClient::ClientState state){
QString str = "";
switch (state){
case QMqttClient::Disconnected:
str = "Disconnected";
// The setting button displays
ui->btnConnect->setText(" Connect ");
break;
case QMqttClient::Connecting:
str = "Connecting";
break;
case QMqttClient::Connected:
str = "Connected";
//
bool isAdd = true;
for(int i=0;i<this->historyJArray.size();i++)
{
// use json The array is converted to json The value is then converted to json object
QJsonObject jObject = historyJArray.at(i).toObject();
QJsonValue jValue = jObject.value("Password");
if(jValue.toString() == ui->lePassword->text())
{
isAdd = false;
break;
}
}
if(isAdd)
{
// Create a file object
QFile file(".//historyData.json");
// Open the file as read Because the previous data is read and stored every time
// So open the text by overwriting
file.open(QIODevice::WriteOnly);
// Insert data into json Array
QJsonObject jObject;
jObject.insert("Hostname",ui->leHostname->text());
jObject.insert("Port",ui->lePort->text());
jObject.insert("ClientId",ui->leClientId->text());
jObject.insert("Username",ui->leUsername->text());
jObject.insert("Password",ui->lePassword->text());
this->historyJArray.append(jObject);
// establish json Document object And set up json Document object content
QJsonDocument jDocument;
jDocument.setArray(this->historyJArray);
// take json The document object is written to the document
file.write(jDocument.toJson());
// Close file
file.close();
}
// Set the button text display
ui->btnConnect->setText(" To break off ");
break;
}
ui->lbShowState->setText(" Connection status :"+str);
qDebug() << state;
});
// Listen for message changes on the client
connect(this->m_client,&QMqttClient::messageReceived,[=](const QByteArray &message, const QMqttTopicName &topic = QMqttTopicName()){
ui->tbRevMag->append("-------------------------------------");
ui->tbRevMag->append("topic:" + topic.name());
ui->tbRevMag->append("message:" + message);
});
// An error occurred while listening to the client
connect(m_client,&QMqttClient::errorChanged,[=](QMqttClient::ClientError error){
qDebug() << error;
});
// Post message button event
connect(ui->btnPubTopic,&QPushButton::clicked,[=](){
QMqttTopicName name = QMqttTopicName(ui->lePubTopic->text());
QMqttPublishProperties pro = QMqttPublishProperties();
QString publishMessage = ui->tePubMag->toPlainText();
m_client->publish(name,pro,publishMessage.toUtf8());
});
// Unsubscribe button event
connect(ui->btnUnSubTopic,&QPushButton::clicked,[=](){
m_client->unsubscribe(QMqttTopicFilter(ui->leUnSubTopic->text()));
});
// Subscribe to button events
connect(ui->btnSubTopic,&QPushButton::clicked,[=](){
m_client->subscribe(QMqttTopicFilter(ui->leSubTopic->text()));
});
// Select... In the listening history information interface
// Get the text data again before entering the historical information Because changes may occur in the history information interface
connect(ui->actioncheck,&QAction::triggered,[=](){
// Open data file The file location is the current project
QFile file(".//historyData.json");
// Open the file read-only
bool isOpened = file.open(QIODevice::ReadOnly);
// When you first set up the program The file does not exist Therefore, it is necessary to determine whether the file can be opened in a read-only way
// But when writing a file, if the file does not exist, it will automatically create a file
if(isOpened)
{
// establish json file , Read all data from the data text
QJsonDocument historyJDocument = QJsonDocument::fromJson(file.readAll());
// adopt json Document access json Array
this->historyJArray = historyJDocument.array();
// Close file
file.close();
}
else
{
qDebug() << " File not open ";
}
historyImfor = new HistoryImfor(this->historyJArray);
historyImfor->show();
connect(this->historyImfor,&HistoryImfor::selHistoryImfors,this,&MainWindow::getHisttoryImfors);
});
}
// Information storage Elements 0 hostname Elements 1 port Elements 2 clientId Elements 3 username Elements 4 password
void MainWindow::getHisttoryImfors(QString imfors[])
{
// Fill the selected history information into the text box
ui->leHostname->setText(imfors[0]);
ui->lePort->setText(imfors[1]);
ui->leClientId->setText(imfors[2]);
ui->leUsername->setText(imfors[3]);
ui->lePassword->setText(imfors[4]);
}
MainWindow::~MainWindow()
{
delete ui;
}
main interface .h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "QtMqtt/qmqttclient.h"
#include "QDebug"
#include "QLabel"
#include "QFile"
#include "QJsonObject"
#include "QJsonDocument"
#include "QJsonArray"
#include "historyimfor.h"
#include "QMessageBox"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
QMqttClient *m_client;
QJsonArray historyJArray;
HistoryImfor *historyImfor;
void getHisttoryImfors(QString imfors[]);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
History interface .cpp
#include "historyimfor.h"
#include "ui_historyimfor.h"
//HistoryImfor::HistoryImfor(QWidget *parent) :
// QMainWindow(parent),
// ui(new Ui::HistoryImfor)
//{
// ui->setupUi(this);
//}
// Custom constructors
HistoryImfor::HistoryImfor(QJsonArray historyJArray):
ui(new Ui::HistoryImfor)
{
ui->setupUi(this);
// Save the text message For choice
this->historyJArray = historyJArray;
// Set up listwidget Of item interval
ui->lwHistImfor->setSpacing(5);
//qDebug() << historyJArray;
// obtain json The value in Then put it into the listwidget
for(int i=0;i<historyJArray.size();i++)
{
QListWidgetItem *item = new QListWidgetItem();
historyCell *cell = new historyCell();
// use json The array is converted to json The value is then converted to json object
QJsonObject jObject = historyJArray.at(i).toObject();
QJsonValue jValue;
// obtain json value
jValue = jObject.value("Hostname");
// Set to label in
cell->lbHostname->setText(jValue.toString());
// obtain json value
jValue = jObject.value("Port");
// Set to label in
cell->lbPort->setText(jValue.toString());
// obtain json value
jValue = jObject.value("ClientId");
// Set to label in
cell->lbClientId->setText(jValue.toString());
// obtain json value
jValue = jObject.value("Username");
// Set to label in
cell->lbUsername->setText(jValue.toString());
// obtain json value
jValue = jObject.value("Password");
// Set to label in
cell->lbPassword->setText(jValue.toString());
// Set up item Size
item->setSizeHint(QSize(ui->lwHistImfor->width(),cell->height()));
// Will be empty item First add to listwidget in
ui->lwHistImfor->addItem(item);
// And then set item The window of
ui->lwHistImfor->setItemWidget(item,cell);
}
connect(ui->lwHistImfor,&QListWidget::itemClicked,[=](QListWidgetItem *item){
});
connect(ui->btnDel,&QPushButton::clicked,[=](){
ui->lwHistImfor->removeItemWidget(ui->lwHistImfor->currentItem());
delete ui->lwHistImfor->currentItem();
int row = ui->lwHistImfor->row(ui->lwHistImfor->currentItem());
this->historyJArray.removeAt(row);
QJsonDocument jDocument;
jDocument.setArray(this->historyJArray);
QFile file(".//historyData.json");
file.open(QIODevice::WriteOnly);
file.write(jDocument.toJson());
file.close();
});
connect(ui->btnOpen,&QPushButton::clicked,[=](){
// Information storage Elements 0 hostname Elements 1 port Elements 2 clientId Elements 3 username Elements 4 password
QString imfors[5];
int row = ui->lwHistImfor->row(ui->lwHistImfor->currentItem());
QJsonObject jObject = historyJArray.at(row).toObject();
QJsonValue jValue;
// obtain json value
jValue = jObject.value("Hostname");
// Store values in an array
imfors[0] = jValue.toString();
// obtain json value
jValue = jObject.value("Port");
// Store values in an array
imfors[1] = jValue.toString();
// obtain json value
jValue = jObject.value("ClientId");
// Store values in an array
imfors[2] = jValue.toString();
// obtain json value
jValue = jObject.value("Username");
// Store values in an array
imfors[3] = jValue.toString();
// obtain json value
jValue = jObject.value("Password");
// Store values in an array
imfors[4] = jValue.toString();
// After selecting the information Send a signal to a main window
emit selHistoryImfors(imfors);
this->close();
});
}
HistoryImfor::~HistoryImfor()
{
delete ui;
}
History interface .h
#ifndef HISTORYIMFOR_H
#define HISTORYIMFOR_H
#include <QMainWindow>
#include "QJsonDocument"
#include "QJsonArray"
#include "QJsonObject"
#include "QJsonValue"
#include "historycell.h"
#include "QListWidgetItem"
#include "QDebug"
#include "QPainter"
#include "QFile"
namespace Ui {
class HistoryImfor;
}
class HistoryImfor : public QMainWindow
{
Q_OBJECT
public:
// explicit HistoryImfor(QWidget *parent = nullptr);
HistoryImfor(QJsonArray historyJArray);
~HistoryImfor();
// Store historical information
QJsonArray historyJArray;
private:
Ui::HistoryImfor *ui;
signals:
// Send a signal after selecting the history information
void selHistoryImfors(QString imfors[]);
};
#endif // HISTORYIMFOR_H
listWidget Item Interface .cpp
#include "historycell.h"
#include "ui_historycell.h"
historyCell::historyCell(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::historyCell)
{
ui->setupUi(this);
this->lbHostname = ui->lbHostname;
this->lbPort = ui->lbPort;
this->lbClientId = ui->lbClient;
this->lbUsername = ui->lbUsername;
this->lbPassword = ui->lbPassword;
}
historyCell::~historyCell()
{
delete ui;
}
listWidget Item Interface .h
#ifndef HISTORYCELL_H
#define HISTORYCELL_H
#include <QMainWindow>
#include "QLabel"
namespace Ui {
class historyCell;
}
class historyCell : public QMainWindow
{
Q_OBJECT
public:
explicit historyCell(QWidget *parent = nullptr);
~historyCell();
QLabel *lbHostname;
QLabel *lbPort;
QLabel *lbUsername;
QLabel *lbPassword;
QLabel *lbClientId;
private:
Ui::historyCell *ui;
};
#endif // HISTORYCELL_H
Run Demo






边栏推荐
- Record of problems caused by WPS document directory update
- Reflection operation annotation
- iframe框架,,原生js路由
- MySQL ifnull processing n/a
- 《数据安全实践指南》- 数据采集安全实践-数据分类分级
- Usage of trim, ltrim and rtrim functions of Oracle
- The song of cactus - marching into to C live broadcast (1)
- laravel Excel 3.1 列宽设置不起作用
- Why did I choose rust
- 【OpenAirInterface5g】ITTI消息收发机制
猜你喜欢

ForkJoinPool

Producer and consumer issues

Single cell literature learning (Part3) -- dstg: deconvoluting spatial transcription data through graph based AI

关于solidity的delegatecall的坑

Logback custom pattern parameter resolution

SQL 注入漏洞(十)二次注入

【5G NR】RRC连接重建解析

Tableau 连接mysql详细教程

OpenGL - Textures

【OpenAirInterface5g】RRC NR解析之RrcSetupRequest
随机推荐
迪进面向ConnectCore系统模块推出Digi ConnectCore语音控制软件
Chrome install driver
[CPU design practice] fundamentals of digital logic circuit design (I)
OpenGL - Textures
SQL 注入漏洞(十一)宽字节注入
Geoswath plus technology and data acquisition and processing
SQL injection vulnerability (XIV) XFF injection attack
Great progress in code
[PHP] composer 安装
【OpenAirInterface5g】高层模块接口及itti实体线程创建
OpenGL - Draw Triangle
Surfer grid file clipping
Record of problems caused by WPS document directory update
SQL injection vulnerability (x) secondary injection
Advanced usage of setting breakpoints during keil debugging
Dynamically create object execution methods
College entrance examination is a post station on the journey of life
Reprint the Alibaba open source project egg JS technical documents cause "copyright disputes". How to use the loose MIT license?
DL and alignment of spatially resolved single cell transcriptomes with Tangram
leetcode:面试题 08.12. 八皇后【dfs + backtrack】