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

#define HostName  "47.111.81.118"
#define HostPort 13307
#define UserName "usky"
#define PassWord "Yt#75Usky"
#define DatabaseName "usky-cloud"


DatabaseThread::DatabaseThread(QObject *parent) :
    QThread(parent)
{
    hour = 255;
    db = QSqlDatabase::addDatabase("QMYSQL","smokerdevicesensor_db");
    db.setHostName(QString(HostName));
    db.setPort(HostPort);
    db.setUserName(QString(UserName));
    db.setPassword(QString(PassWord));
    db.setDatabaseName(QString(DatabaseName));
    db.open();
}

void DatabaseThread::check_devicelist()
{
    QSqlQuery qry = db.exec("select distinct company_code,device_type,product_code from dmp_device where company_code is not null");
    int nrow= 0;
    while(qry.next()){
        printf("---nrow = %d, Device_Code = %s, Device_Name = %s,Company_Code = %s\n",nrow,qry.value(0).toString().toUtf8().data(),qry.value(1).toString().toUtf8().data(),qry.value(2).toString().toUtf8().data());
        sprintf(smokerDeviceList->sensors[nrow].Company_Code,"%s",qry.value(0).toString().toUtf8().data());
        smokerDeviceList->sensors[nrow].Device_Type=qry.value(1).toInt();
        sprintf(smokerDeviceList->sensors[nrow].product_code,"%s",qry.value(2).toString().toUtf8().data());
        nrow++;
    }
    qry.clear();
}

void DatabaseThread::run()
{
    printf("database thread start\n");

    while(1){
        if(!db.isOpen()){
            db.open();
        }else{
            if(QTime::currentTime().hour()!=hour){
                hour=QTime::currentTime().hour();
               check_devicelist();
            }
            db.close();
        }
        usleep(50000);
    }
    //if(db.isOpen())
        //db.close();
}
