mqttdatathread.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "mqttdatathread.h"
  2. #include "../DataWriteDog/writeshm.h"
  3. MqttDataThread::MqttDataThread(QObject *parent) : QThread(parent)
  4. {
  5. timer = new QTimer(this);
  6. connect(timer,&QTimer::timeout,this,&MqttDataThread::time_out);
  7. }
  8. void MqttDataThread::run()
  9. {
  10. }
  11. void MqttDataThread::time_out()
  12. {
  13. dataWriteShm->processStatus[1].t_time = QDateTime::currentDateTime().toTime_t();
  14. if((m_client->connectionState()==QMQTT::STATE_DISCONNECTED)||(m_client->connectionState()==QMQTT::STATE_INIT)){
  15. m_client->connectToHost();
  16. }
  17. }
  18. void MqttDataThread::mqtt_conf(QString ip,QString port,QString username,QString password)
  19. {
  20. mqtt_ip = ip;
  21. mqtt_port = port;
  22. mqtt_username = username;
  23. mqtt_passwd = password;
  24. m_client = new QMQTT::Client(QHostAddress(mqtt_ip),static_cast<quint16>(mqtt_port.toInt()),this);
  25. m_client->setUsername(mqtt_username);
  26. m_client->setPassword(mqtt_passwd.toLatin1());
  27. m_client->setCleanSession(false);
  28. m_client->setAutoReconnect(true);
  29. m_client->setAutoReconnectInterval(60000);
  30. connect(m_client,&QMQTT::Client::connected,this,&MqttDataThread::onConnected);
  31. connect(m_client,&QMQTT::Client::received,this,&MqttDataThread::onReceived);
  32. m_client->connectToHost();
  33. timer->start(1000);
  34. }
  35. void MqttDataThread::onConnected()
  36. {
  37. emit mq_log(QString("[%1] WriteProcess mqttdatathread onConnected").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")));
  38. m_client->subscribe("data-collector",0);
  39. }
  40. void MqttDataThread::onReceived(const QMQTT::Message &message)
  41. {
  42. QString topic = message.topic();
  43. QByteArray data = message.payload();
  44. emit sendMqttData(topic,data);
  45. }