Эх сурвалжийг харах

V1.3.5
1、新增了MQTTBase一个新的发送函数,带有保留消息选项

Apple 1 өдөр өмнө
parent
commit
fcc3320d0c

+ 17 - 11
module/mqtt/MQTTBase.cpp

@@ -76,43 +76,49 @@ QMQTT::ConnectionState MQTTBase::connectState()
 }
 
 /* 发送消息 */
-void MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int qos)
+bool MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int qos)
 {
     if(m_isConnected == false)
     {
         SPDLOG_ERROR("MQTT未连接到服务器,发送消息失败");
-        return;
+        return false;
     }
     QMQTT::Message msg(0, topic, message, qos);
     auto ret = m_client.publish(msg);
     if(ret != 0)
     {
         SPDLOG_ERROR("发送消息失败:{}, 错误代码:{}", topic.toStdString(), ret);
+        return false;
     }
+
+    return true;
 }
 
-/* 发送消息,不检测是否连接了服务器 */
-bool MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int qos, int& errorCode)
+/* 发送消息,设置消息保留 */
+bool MQTTBase::sendMessage(const QString& topic, const QByteArray& message, int qos, bool retain)
 {
-    if(qos > 2)
+    if(m_isConnected == false)
     {
-        SPDLOG_ERROR("QoS值不合法:{}", qos);
-        errorCode = -1;
+        SPDLOG_ERROR("MQTT未连接到服务器,发送消息失败");
         return false;
     }
-    QMQTT::Message msg(0, topic, message, qos);
+    QMQTT::Message msg;
+    msg.setTopic(topic);
+    msg.setPayload(message);
+    msg.setQos(qos);
+    msg.setRetain(retain); // 设置消息保留
     auto ret = m_client.publish(msg);
     if(ret != 0)
     {
-        // SPDLOG_ERROR("发送消息失败:{}, 错误代码:{}", topic.toStdString(), ret);
-        errorCode = ret;
+        SPDLOG_ERROR("发送消息失败:{}, 错误代码:{}", topic.toStdString(), ret);
         return false;
     }
-    errorCode = 0;
+
     return true;
 }
 
 
+
 /* 连接成功 */
 void MQTTBase::do_connected()
 {

+ 3 - 3
module/mqtt/MQTTBase.h

@@ -35,9 +35,9 @@ public:
     /* 获取连接状态 */
     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);
+    bool sendMessage(const QString& topic, const QByteArray& message, int qos = 0);
+    /* 发送消息,设置消息保留 */
+    bool sendMessage(const QString& topic, const QByteArray& message, int qos = 0, bool retain = false);
     
     
 signals: