123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- #include "mqttthread.h"
- #include "logger.h"
- #include "./mqtt/mqttclient.h" // 假设 MqttClient 类的头文件是 mqttclient.h
- MqttThread::MqttThread(QObject *parent) : QThread(parent)
- {
- }
- MqttThread::~MqttThread()
- {
- m_stopFlag = true;
- quit();
- wait();
- if (mqttClient)
- {
- delete mqttClient;
- }
- }
- void MqttThread::setConnectionInfo(const QString &hostname, quint16 port, const QString &username, const QString &password, const QString &clientId, const QStringList &topicsToSubscribe)
- {
- m_hostname = hostname;
- m_port = port;
- m_username = username;
- m_password = password;
- m_clientId = clientId;
- m_topicsToSubscribe = topicsToSubscribe;
- }
- MqttClient *MqttThread::getMqttClient() const
- {
- return mqttClient;
- }
- void MqttThread::stopThread()
- {
- m_stopFlag = true;
- quit();
- }
- void MqttThread::run()
- {
- // mqttClient = new MqttClient();
- mqttClient = MqttClient::createNewInstance();
- mqttClient->connectToMqttBroker(m_hostname, m_port, m_username, m_password, m_clientId, m_topicsToSubscribe);
- connect(mqttClient, &MqttClient::connected, this, &MqttThread::mqttConnected);
- connect(mqttClient, &MqttClient::messageAndTopicReceived, this, &MqttThread::messageAndTopicReceived);
- connect(this, &MqttThread::sendMessageRequested, mqttClient, &MqttClient::sendMessage);
- while (!m_stopFlag)
- {
- exec();
- }
- }
- void MqttThread::sendMqttMessage(const QString &topic, const QByteArray &message, quint8 qos, bool isRetainedMsg)
- {
- if (mqttClient)
- {
- Logger::getInstance().info(QString("发送MQTT消息到主题: %1, 消息: %2, qos: %3, isRetainMsg: %4").arg(topic, QString(message), qos, isRetainedMsg ? "true" : "false"));
- mqttClient->sendMessage(topic, message, qos, isRetainedMsg);
- }
- }
|