#include "clightdriver_gr.h"
#include "clight.h"
#include "cmakepath.h"
#include "cmserialport.h"
CLightDriver_GR::CLightDriver_GR(const QString &name, int32_t id)
    :CLightDriver(name,id)
{

}

CLightDriver_GR::~CLightDriver_GR()
{

}

int32_t CLightDriver_GR::setlight(int32_t iChid, int32_t ibright)
{
    QMutexLocker locker(&m_CardMutex);
    CLight* pLight=(CLight*)FindChannel(iChid);
    Q_ASSERT(pLight);
    int isn=pLight->m_Variants.get_VData(Var_Base_SerialID_ID)->toInt();
    Q_ASSERT(isn>0&&isn<=4);
    byte bylight=ibright;
    char Command[6]={0};
    MakeCommand(Command, 0x5A, isn, bylight);
    char ch_response[RESPONSELENGTH]={0};
    SendCommand(Command,ch_response);
    checkResponse( iChid,ch_response);
    return CLightDriver::setlight(iChid,ibright);
}

int32_t CLightDriver_GR::init_driver()
{
    m_pSerialPort->open();
    return CLightDriver::init_driver();
}

int32_t CLightDriver_GR::exit_driver()
{
    int irtn= CLightDriver::exit_driver();
    m_pSerialPort->close();
    return irtn;

}


void CLightDriver_GR::SendCommand(const char *pCommand,char* pResponse)
{
    QMutexLocker locker(&m_CardMutex);
    int isize=strlen(pCommand);

    qDebug()<<pCommand;
    m_pSerialPort->send(pCommand,isize);
    int32_t irtn=m_pSerialPort->wait();
    m_pSerialPort->receive(pResponse,irtn);

    MSleep(100);
}

void CLightDriver_GR::MakeCommand(char *pCommand, byte byComm, byte byCh, byte byData)
{
    pCommand[0]=0x3D;
    pCommand[1]=byComm;
    pCommand[2]=byCh;
    pCommand[3]=byData;
    pCommand[4]=byte(pCommand[1]+pCommand[2]+pCommand[3]);
    pCommand[5]=0x0D;
}

void CLightDriver_GR::checkResponse(int32_t iChid,char* pResponse)
{
    CLight* pLight=(CLight*)FindChannel(iChid);
    Q_ASSERT(pLight);
    qDebug()<<pResponse;
    if(strcmp(pResponse,"OK"))
    {
        MQT_THROW_STR(QObject::trUtf8("Light %1: set Err")
                      .arg(pLight->m_sName));

    }
}
