1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- #include "mqttthread.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)
- {
- if (mqttClient) {
- mqttClient->sendMessage(topic, message);
- }
- }
|