mqttthread.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "mqttthread.h"
  2. #include "./mqtt/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, m_topicsToSubscribe);
  32. connect(mqttClient, &MqttClient::connected, this, &MqttThread::mqttConnected);
  33. connect(mqttClient, &MqttClient::messageReceived, this, &MqttThread::projectMqttMessageReceived);
  34. connect(this, &MqttThread::sendMessageRequested, mqttClient, &MqttClient::sendMessage);
  35. while (!m_stopFlag) {
  36. exec();
  37. }
  38. }
  39. void MqttThread::sendMqttMessage(const QString &topic, const QByteArray &message, quint8 qos, bool isRetainedMsg) {
  40. if (mqttClient) {
  41. Logger::getInstance().info(QString("Mqtt thread 发送MQTT消息到主题: %1, 消息: %2, qos: %3, isRetainMsg: %4")
  42. .arg(topic, QString(message), qos, isRetainedMsg ? "true" : "false"));
  43. mqttClient->sendMessage(topic, message, qos, isRetainedMsg);
  44. }
  45. }