#include "mqtteventdatathread.h"
#include "../DataWriteDog/writeshm.h"

MqttEventDataThread::MqttEventDataThread(QObject *parent) : QThread(parent)
{

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&MqttEventDataThread::time_out);
}

void MqttEventDataThread::run()
{

}

void MqttEventDataThread::time_out()
{
    dataWriteShm->processStatus[1].t_time = QDateTime::currentDateTime().toTime_t();
    if((m_client->connectionState()==QMQTT::STATE_DISCONNECTED)||(m_client->connectionState()==QMQTT::STATE_INIT)){
        m_client->connectToHost();
    }
}

void MqttEventDataThread::mqtt_conf(QString ip,QString port,QString username,QString password)
{
    mqtt_ip = ip;
    mqtt_port = port;
    mqtt_username = username;
    mqtt_passwd = password;


    m_client = new QMQTT::Client(QHostAddress(mqtt_ip),static_cast<quint16>(mqtt_port.toInt()),this);
    m_client->setUsername(mqtt_username);
    m_client->setPassword(mqtt_passwd.toLatin1());
    m_client->setCleanSession(true);
    connect(m_client,&QMQTT::Client::connected,this,&MqttEventDataThread::onConnected);
    connect(m_client,&QMQTT::Client::received,this,&MqttEventDataThread::onReceived);
    m_client->connectToHost();


    timer->start(1000);
}

void MqttEventDataThread::onConnected()
{
    emit mq_log(QString("[%1] WriteProcess MqttEventDataThread onConnected").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")));

    m_client->subscribe("event-collector",0);

}

void MqttEventDataThread::onReceived(const QMQTT::Message &message)
{

    QString topic = message.topic();
    QByteArray data = message.payload();


    emit sendMqttData(topic,data);
}
