#include "datacollectorsub.h"
#include "../ytDataCollectorDog/datacollector.h"

DataCollectorSub::DataCollectorSub(QObject *parent) : QThread(parent)
{
    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&DataCollectorSub::time_out);
    timer->start(1000);

    m_client = new QMQTT::Client(QHostAddress("47.98.201.73"),1883,this);
    m_client->setUsername("usky");
    m_client->setPassword("usky");
    m_client->setCleanSession(true);
    connect(m_client,&QMQTT::Client::connected,this,&DataCollectorSub::onConnected);
    connect(m_client,&QMQTT::Client::received,this,&DataCollectorSub::onReceived);
    m_client->connectToHost();

}

void DataCollectorSub::run()
{

}

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

void DataCollectorSub::onConnected()
{
    m_client->subscribe("/usky/ytDP0001/+/+/info",0);
    m_client->subscribe("/usky/ytDP0002/+/+/info",0);
    m_client->subscribe("/usky/ytDP0003/+/+/info",0);
    m_client->subscribe("/usky/ytDP0006/+/+/info",0);
    m_client->subscribe("/usky/ytDP0007/+/+/info",0);
    m_client->subscribe("/usky/ytDP0008/+/+/info",0);
    m_client->subscribe("/usky/ytDP00033/+/+/info",0);

}

void DataCollectorSub::onReceived(const QMQTT::Message &message)
{
    dataColShm->time = QDateTime::currentDateTime().toTime_t();

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

    //printf("data_collector topic: %s, commData: %s\n",topic.toUtf8().data(),data.data());

    emit sendDevData(topic,data);
}








