mqttthread.cpp 1.5 KB

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