mqttthread.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "mqttthread.h"
  2. #include "logger.h"
  3. #include "./mqtt/mqttclient.h" // 假设 MqttClient 类的头文件是 mqttclient.h
  4. MqttThread::MqttThread(QObject *parent) : QThread(parent)
  5. {
  6. }
  7. MqttThread::~MqttThread()
  8. {
  9. m_stopFlag = true;
  10. quit();
  11. wait();
  12. if (mqttClient)
  13. {
  14. delete mqttClient;
  15. }
  16. }
  17. void MqttThread::setConnectionInfo(const QString &hostname, quint16 port, const QString &username, const QString &password, const QString &clientId, const QStringList &topicsToSubscribe)
  18. {
  19. m_hostname = hostname;
  20. m_port = port;
  21. m_username = username;
  22. m_password = password;
  23. m_clientId = clientId;
  24. m_topicsToSubscribe = topicsToSubscribe;
  25. }
  26. MqttClient *MqttThread::getMqttClient() const
  27. {
  28. return mqttClient;
  29. }
  30. void MqttThread::stopThread()
  31. {
  32. m_stopFlag = true;
  33. quit();
  34. }
  35. void MqttThread::run()
  36. {
  37. // mqttClient = new MqttClient();
  38. mqttClient = MqttClient::createNewInstance();
  39. mqttClient->connectToMqttBroker(m_hostname, m_port, m_username, m_password, m_clientId, m_topicsToSubscribe);
  40. connect(mqttClient, &MqttClient::connected, this, &MqttThread::mqttConnected);
  41. connect(mqttClient, &MqttClient::messageAndTopicReceived, this, &MqttThread::messageAndTopicReceived);
  42. connect(this, &MqttThread::sendMessageRequested, mqttClient, &MqttClient::sendMessage);
  43. while (!m_stopFlag)
  44. {
  45. exec();
  46. }
  47. }
  48. void MqttThread::sendMqttMessage(const QString &topic, const QByteArray &message, quint8 qos, bool isRetainedMsg)
  49. {
  50. if (mqttClient)
  51. {
  52. Logger::getInstance().info(QString("发送MQTT消息到主题: %1, 消息: %2, qos: %3, isRetainMsg: %4").arg(topic, QString(message), qos, isRetainedMsg ? "true" : "false"));
  53. mqttClient->sendMessage(topic, message, qos, isRetainedMsg);
  54. }
  55. }