Mqtt client multiple configurations can be set


Recent projects mqtt to use, of course, now mqtt are already standard components era of things, and before the use of the C-terminal-based interface mosquitto library is not done, now based on qmqtt开源库14.2 written ui interface, of course, the future may often call , Has been encapsulated in the form of a library.

Effect picture

Insert picture description here

The main function

Configuration function

When the software starts, it will first find the configuration file and MQTT_CONFIG.jsongenerate a new default configuration.

The windows side looks for the program startup by default, the
linux side looks for it in the /etc directory
Insert picture description here

The content format is as follows:

  • Why there are four configurations, because it was originally envisaged to start with multiple configurations or connect to multiple platforms
  • At present, the multi-configuration function is available, but there is no place for the interface of the interface, so there is no interface for switching configuration on the ui
{
    
    
    "MQTT_CONFIG": [
        {
    
    
            "MqttConfigNum": "Client_0",
            "MqttKeepAlive": 300,
            "MqttServerAddr": "broker.hivemq.com",
            "MqttServerIp": "192.168.50.128",
            "MqttServerPort": 1883,
            "MqttUserKey": "123456",
            "MqttUserName": "admin",
            "PublishTopic": [
                {
    
    
                    "MqttPUBQos": 0,
                    "MqttPublishTopic": ""
                }
            ],
            "SubscribeTopic": [
                {
    
    
                    "MqttSUBQos": 0,
                    "MqttSubscribeTopic": ""
                }
            ]
        },
        {
    
    
            "MqttConfigNum": "Client_1",
            "MqttKeepAlive": 300,
            "MqttServerAddr": "broker.hivemq.com",
            "MqttServerIp": "192.168.50.128",
            "MqttServerPort": 1883,
            "MqttUserKey": "123456",
            "MqttUserName": "admin",
            "PublishTopic": [
                {
    
    
                    "MqttPUBQos": 0,
                    "MqttPublishTopic": ""
                }
            ],
            "SubscribeTopic": [
                {
    
    
                    "MqttSUBQos": 0,
                    "MqttSubscribeTopic": ""
                }
            ]
        },
        {
    
    
            "MqttConfigNum": "Client_2",
            "MqttKeepAlive": 300,
            "MqttServerAddr": "broker.hivemq.com",
            "MqttServerIp": "192.168.50.128",
            "MqttServerPort": 1883,
            "MqttUserKey": "123456",
            "MqttUserName": "admin",
            "PublishTopic": [
                {
    
    
                    "MqttPUBQos": 0,
                    "MqttPublishTopic": ""
                }
            ],
            "SubscribeTopic": [
                {
    
    
                    "MqttSUBQos": 0,
                    "MqttSubscribeTopic": ""
                }
            ]
        },
        {
    
    
            "MqttConfigNum": "Client_3",
            "MqttKeepAlive": 300,
            "MqttServerAddr": "broker.hivemq.com",
            "MqttServerIp": "192.168.50.128",
            "MqttServerPort": 1883,
            "MqttUserKey": "123456",
            "MqttUserName": "admin",
            "PublishTopic": [
                {
    
    
                    "MqttPUBQos": 0,
                    "MqttPublishTopic": ""
                }
            ],
            "SubscribeTopic": [
                {
    
    
                    "MqttSUBQos": 0,
                    "MqttSubscribeTopic": ""
                }
            ]
        }
    ]
}

Network detection

There is nothing to say about this. Most of the detections on the Internet are that blocking is not suitable for interface operation. Here, I am changed to asynchronous non-blocking, which is an optimized function item.

  • When the network is abnormal, an abnormal signal will be sent for asynchronous notification.

Debug function

  • After the debugging function is turned on, a small input box will appear at the bottom of the message area to edit the content to be sent. At this time, fill in the topic to be sent on the topic of the publishing area, qos is 0, and click Send.
  • If you have subscribed to the same topic as the sending topic, you can receive the sent message and display it in the message area.

Publish topic

Currently, publishing messages are restricted (consistent with the subscription operation logic), that is, only when the topic in the publish column calls the sending interface will it be allowed to be sent.

Port this client

Precondition

Download the source code
download address of this client The point is set to 3, it is not my pot that it is high.

Modification confirmation before compilation

  • Windows compiles the source code, the compiler uses it by defaultmingw64
  • SSL encryption function , the ssl encryption function is not enabled in Linux by default in the source code. Because most of the linux-side development is embedded, most of the qt source code compilation and clipping items cancel the openssl join link, if you need to enable it, modify the source code yourself and cancel Macro judgment.
    Insert picture description here

Compile

Here, take the windows side as an example
1. UseqtcreatorOpen the libmqttclient.profile of the source project , configure the compiler to mingw64, and select the release version to compile.

Compilation results are as follows:
Insert picture description here
Compile and generate two library files: 1. Client library filesmqttclient 2. The qmqtt14.2 library file that the client depends onQt5Mqtt

  • Which libfolder has the library file qmqtt14.2
  • src/mqttclient/releaseThere are library files of UI interface client in the directory
  • includeThere are qmqtt14.2 header files

Porting mqtt client to your project

Source method

1, based on the root directory of your project source mqttdirectory, then create the next mqtt directory lib, QtMqtttwo directories.
2, the compiler-generated qmqtt library files (source code lib directory compiler-generated): Qt5Mqtt.dll, Qt5Mqtt.acopied to your project mqtt/libdirectory
3, copy (under the include directory (source compiler-generated)) qmqtt all the header files, to your 4. In the project mqtt/QtMqttdirectory,
add the following to your project .pro file:

# qmqtt windows
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/mqtt/lib/ -lQt5Mqtt
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/mqtt/lib/ -lQt5Mqttd

INCLUDEPATH += $$PWD/mqtt/QtMqtt/ $$PWD/mqtt/
DEPENDPATH += $$PWD/mqtt/QtMqtt/

win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/libQt5Mqtt.a
else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/libQt5Mqttd.a
else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/Qt5Mqtt.lib
else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/Qt5Mqttd.lib

# qmqtt linux
unix:!macx: LIBS += -L$$PWD/mqtt/lib/
unix:!macx: LIBS += -lQt5Mqtt

5. mqttCreate a mqttclient.prifile in your project directory and
fill in the following:

SOURCES += \
    customerwidgetitem.cpp \
    libmqttclient.cpp

HEADERS += \
    customerwidgetitem.h \
    libmqttclient_global.h \
    libmqttclient.h \
    ui_libmqttclient.h

6. Copy the files involved in the source code directory ( libmqttclient\src\mqttclient) mqttclient.prito the directory created in the root directory of your project source code mqtt.
7. .proAdd the following in your project file

# mqttclient
include(mqtt/mqttclient.pri)

After the above steps are completed, the interface provided by mqttClient can be called.
For example:
1. The header file containing the client

#include <mqtt/libmqttclient.h>             /**< mqttclient*/

2. Instantiation

Libmqttclient *MqttWindow;

/*mqttclient设置窗口显示*/
MqttWindow = new Libmqttclient(800 ,600 ,QString("192.168.50.128"));
/*连接mqttclient窗口关闭信号*/
connect(MqttWindow ,&Libmqttclient::MqttwindowIsClose ,this ,&MainWindow::slotShowMainWindow);
/*连接mqttclient自启动连接服务器异常信号*/
connect(MqttWindow ,&Libmqttclient::NetworkPingError ,this ,&MainWindow::slotShowNetErrDialog);
/*连接mqttclient窗口要求显示键盘的信号*/
connect(MqttWindow ,&Libmqttclient::show_keyboard ,this ,&MainWindow::slotprocessedit);

3. Call display

MqttWindow->show();

Library way

1. Confirm that the source code compilation has been successfully completed (relevant library files are generated as expected).
2, built on the root directory of your project source mqttdirectory, then create the next mqtt directory lib, QtMqtttwo directories.
3, will compile the generated qmqtt library files (source code lib directory compiler-generated): Qt5Mqtt.dll, Qt5Mqtt.acopied to your project mqtt/libdirectory
4, copy qmqtt all header files (under (source compiler generated include directory)), to your mqtt/QtMqttUnder the project directory
5. Copy the compiled mqttclient library file (under the src/mqttclient/release directory generated by source code compilation): mqttclient.dllcopy it to your project mqtt/libdirectory.
6. Add the following to your project .pro file:

# qmqtt windows
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/mqtt/lib/ -lQt5Mqtt
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/mqtt/lib/ -lQt5Mqttd

INCLUDEPATH += $$PWD/mqtt/QtMqtt/ $$PWD/mqtt/
DEPENDPATH += $$PWD/mqtt/QtMqtt/

win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/libQt5Mqtt.a
else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/libQt5Mqttd.a
else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/Qt5Mqtt.lib
else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/mqtt/lib/Qt5Mqttd.lib

# qmqtt linux
unix:!macx: LIBS += -L$$PWD/mqtt/lib/
unix:!macx: LIBS += -lQt5Mqtt

#mqttclient
LIBS += -L$$PWD/mqtt/lib/
LIBS += -lmqttclient     

7. mqttCreate a mqttclient.prifile in your project directory (Can not do)
Fill in the following content: (Can not do)

HEADERS += \
    $$PWD/customerwidgetitem.h \
    $$PWD/libmqttclient.h \
    $$PWD/libmqttclient_global.h \
    $$PWD/ui_libmqttclient.h

.proAdd the following in your project file:(Can not do)

# mqttclient
include(mqtt/mqttclient.pri)

8. Copy libmqttclient\src\mqttclientall the files with the .h suffix under the source code directory ( ) to the directory created in the root directory of your project source code mqtt.

After completing the above steps, you can call the interface.

Interface Description

See the libmqttclient.hfile for details

static bool NetworkConnectCheck(QString netaddr);   /**< 检测与指定外网的连接*/
void SetReconnectInterval(qint32 msec);             /**< 设置重连检测周期*/
void NetworkPingCheck(QString netaddr);             /**< 检测指定ip是否能够ping通*/
void SwitchClientConfig(quint8 clientNum = 0);      /**< 切换客户端配置*/
void setUsername(QString &user ,QString &Key ,bool Writeflash = false ,quint8 configindex = 0);      /**< 设置用户名和密码*/
void setHostIPAddr(QString &addr ,bool Writeflash = false ,quint8 configindex = 0);/**< 设置主机IP地址*/
void setHostRealmAddr(QString &addr ,bool Writeflash = false ,quint8 configindex = 0);/**< 设置主机域名地址*/
void setHostPort(quint16 port ,bool Writeflash = false ,quint8 configindex = 0);/**< 设置主机端口地址*/
void setProtocolVersion(QMqttClient::ProtocolVersion protocolVersion);/**< 设置版本*/
void setWillMsgConfig(const QString &willTopic ,const QByteArray &willMessage ,quint8 willQoS = 0 ,bool willRetain = false);/**< 设置遗属消息*/
void setCleanSession(bool cleanSession = true);/**< false表示创建一个持久会话,在客户端断开连接时,会话仍然保持并保存离线消息,直到会话超时注销*/
QMqttClient::ClientState GetMqttConnectState()const;/**< 获取mqtt连接状态 0未连接 1连接中 2已连接*/
void UNsubscribe_all();                             /**< 取消全部订阅*/
void UNpublish_all();                               /**< 取消全部发布*/
qint32 PublishMsg(QString topicStr ,QByteArray msg);/**< 发布消息*/
bool RemoveSubscribeToic(QString topic ,bool Writeflash = false ,quint8 configindex = 0);               /**< 删除指定订阅,选择是否写入到配置*/
bool RemovePublishToic(QString topic ,bool Writeflash = false ,quint8 configindex = 0);                 /**< 删除指定发布,选择是否写入到配置*/
bool AddSubscribeToic(QString topic ,qint32 qosvalue ,bool Writeflash = false ,quint8 configindex = 0); /**< 新增指定订阅,选择是否写入到配置*/
bool AddPublishToic(QString topic ,qint32 qosvalue ,bool Writeflash = false ,quint8 configindex = 0);   /**< 新增指定发布,选择是否写入到配置*/

Signal provided:

void MqttwindowIsClose();                                    /**< 通知父窗口显示*/
void show_keyboard(QWidget * ,QLineEdit *,QString,QString);  /**< 通知显示键盘*/
void NetworkPingError();                                     /**< 网络连接错误*/
void MessageReceived(const QByteArray &message, const QMqttTopicName &topic = QMqttTopicName());/**< 接收到新消息信号*/
void StartReconnectTimer();/**< 重新连接启动*/

Interactive example

Use qtcreator to create a mainwindow window

Contains interface header files

#include <mqtt/libmqttclient.h>

Create a private member mqttclient window pointer

private:
	Libmqttclient *MqttWindow;

Instantiate, specify the size of the mqttclient client window 800*600, the default connection mqtt server ip is192.168.50.128

/*mqttclient设置窗口显示*/
MqttWindow = new Libmqttclient(800 ,600 ,QString("192.168.50.128"));

Connect mqttclient related signals

/*连接mqttclient窗口关闭信号*/
connect(MqttWindow ,&Libmqttclient::MqttwindowIsClose ,this ,&MainWindow::slotShowMainWindow);
/*连接mqttclient自启动连接服务器异常信号*/
connect(MqttWindow ,&Libmqttclient::NetworkPingError ,this ,&MainWindow::slotShowNetErrDialog);
/*连接mqttclient窗口要求显示键盘的信号*/
connect(MqttWindow ,&Libmqttclient::show_keyboard ,this ,&MainWindow::slotprocessedit);

Main window processing related signals

/*显示主窗口*/
void MainWindow::slotShowMainWindow()
{
    
    
    this->show();
}

/*显示网络错误*/
void MainWindow::slotShowNetErrDialog()
{
    
    
    QMessageBox::critical(this,tr("Error"),tr("<p><span style='color: rgb(255, 0, 80);font-size: 24px;'>初始连通mqtt服务器失败.</span></p>"));
}

/*显示键盘信号*/
void MainWindow::slotprocessedit(QWidget *pObject ,QLineEdit *pwidget ,QString title ,QString edittext)
{
    
    
    if(KeyboardUI->isHidden() == false)
    {
    
    
        return;
    }
    pLastCallobj = pObject;
    pLastCallwidget = pwidget;
    KeyboardUI->showKeyboard(title ,edittext);
}

Okay, just write so much. The interface has comments in the source code for flexible use.

Guess you like

Origin blog.csdn.net/weixin_42892101/article/details/108301272