mqttthread.cpp 1.9 KB

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