#include "ytmqttsub.h"
#include "../AGBoxDog/boxshm.h"

YTMqttSub::YTMqttSub(QObject *parent) : QThread(parent)
{
    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&YTMqttSub::time_out);

}

void YTMqttSub::run()
{

}

void YTMqttSub::time_out()
{
    if(m_client->connectionState() == QMQTT::STATE_INIT || m_client->connectionState() == QMQTT::STATE_DISCONNECTED){
        m_client->connectToHost();
    }

}

void YTMqttSub::mqtt_conf(QString ip, QString port, QString username, QString passwd)
{
//    m_client = new QMQTT::Client(QHostAddress(ip),static_cast<quint16>(port.toInt()),this);
//    m_client->setUsername(username);
//    m_client->setPassword(passwd.toLatin1());
    m_client = new QMQTT::Client(QHostAddress("10.108.34.2"),1883,this);
    m_client->setUsername("usky");
    m_client->setPassword("usky");
    m_client->setCleanSession(true);
    connect(m_client,&QMQTT::Client::connected,this,&YTMqttSub::onConnected);
    connect(m_client,&QMQTT::Client::received,this,&YTMqttSub::onReceived);
    m_client->connectToHost();

    timer->start(1000);
}

void YTMqttSub::onConnected()
{
    printf("xfyt mqtt onConnected\n");
    m_client->subscribe("/edge/baInfo/818DBB40CD2D4494936A75C76E89542C/rtg",0);
    m_client->subscribe("/edge/baInfo/B3E523F1D0E8402F818C30833C4F1C6F/rtg",0);
    m_client->subscribe("/edge/baInfo/E68D8A289878474D963D43F5FC624E34/rtg",0);
    m_client->subscribe("/edge/baInfo/3CC454CC33B74714BB7B8D8C83C72304/rtg",0);
    m_client->subscribe("/edge/baInfo/3932C85C53964902A0A426B03A4EBB42/rtg",0);
    m_client->subscribe("/edge/baInfo/ED2059D345D145DCBEB6B5E3B4CFCAD8/rtg",0);
    m_client->subscribe("/edge/baInfo/E4C82427D44D40E5B398002CA5A1EF42/rtg",0);
    m_client->subscribe("/edge/baInfo/0344B9CD3B6A468E87551B25BC679A96/rtg",0);
    m_client->subscribe("/edge/baInfo/2F0C601E76E9444997F5E72EAB86856F/rtg",0);
    m_client->subscribe("/edge/baInfo/3B6CEDD977434B89AE9029938D673BB3/rtg",0);

}

void YTMqttSub::onReceived(const QMQTT::Message &message)
{
    agBoxShm->processStatus[11].t_time=QDateTime::currentDateTime().toTime_t();
    QString topic = message.topic();
    QByteArray data = message.payload();

    emit sendMqttData(topic,data);

}
