瀏覽代碼

V1.2.7
1、完善了mqtt的基类

Apple 2 天之前
父節點
當前提交
3af8eba1af
共有 2 個文件被更改,包括 35 次插入0 次删除
  1. 27 0
      module/mqtt/MQTTBase.cpp
  2. 8 0
      module/mqtt/MQTTBase.h

+ 27 - 0
module/mqtt/MQTTBase.cpp

@@ -69,6 +69,12 @@ void MQTTBase::connectToServer()
     m_client.connectToHost();
 }
 
+/* 获取连接状态 */
+QMQTT::ConnectionState MQTTBase::connectState()
+{
+    return m_client.connectionState();
+}
+
 /* 发送消息 */
 void MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int qos)
 {
@@ -85,6 +91,27 @@ void MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int
     }
 }
 
+/* 发送消息,不检测是否连接了服务器 */
+bool MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int qos, int& errorCode)
+{
+    if(qos > 2)
+    {
+        SPDLOG_ERROR("QoS值不合法:{}", qos);
+        errorCode = -1;
+        return false;
+    }
+    QMQTT::Message msg(0, topic, message, qos);
+    auto ret = m_client.publish(msg);
+    if(ret != 0)
+    {
+        // SPDLOG_ERROR("发送消息失败:{}, 错误代码:{}", topic.toStdString(), ret);
+        errorCode = ret;
+        return false;
+    }
+    errorCode = 0;
+    return true;
+}
+
 
 /* 连接成功 */
 void MQTTBase::do_connected()

+ 8 - 0
module/mqtt/MQTTBase.h

@@ -3,6 +3,7 @@
 
 #include <QObject>
 #include <QMap>
+#include <qt5/QtCore/qchar.h>
 
 #include "qmqtt.h"
 
@@ -29,8 +30,15 @@ public:
     void setAutoReconnect(bool isAuto = true);
     /* 连接到服务器 */
     void connectToServer();
+    /* 断开连接 */
+    void disconnectFromServer() {m_client.disconnectFromHost();}
+    /* 获取连接状态 */
+    QMQTT::ConnectionState connectState();
     /* 发送消息 */
     void sendMessage(const QString& topic, const QByteArray& message, int qos = 0);
+    /* 发送消息,不检测是否连接了服务器 */
+    bool sendMessage(const QString& topic, const QByteArray& message, int qos, int& errorCode);
+    
     
 signals:
     /* 接收到消息,对消息进行了转发 */