#include "clightdriver_km.h"

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

}

CLightDriver_KM::~CLightDriver_KM()
{

}

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

int32_t CLightDriver_KM::exit_driver()
{
  //  int irtn= CLightDriver::exit_driver();
    m_pSerialPort->close();
    return 0;
}

int32_t CLightDriver_KM::setlight(int32_t iChid, int32_t ibright)
{
    CLight* pLight=(CLight*)FindChannel(iChid);
    Q_ASSERT(pLight);
    int isn=pLight->m_Variants.get_VData(Var_Base_SerialID_ID)->toInt();

    if(isn<1||isn>4)
    {
        MQT_THROW_STR(QObject::trUtf8("Light %1 SN: %2 err")
                      .arg(pLight->m_sName).arg(isn));
    }
    QMutexLocker locker(&m_CardMutex);
    byte pCommand[32]={0};
    byte pResponse[32]={0};
    int iSize=0;
    ibright=max(0,ibright);
    ibright=min(255,ibright);
    MakeCommand(pCommand, iSize, isn-1, ibright*4);
    m_pSerialPort->send((const char*)pCommand,iSize);
    int32_t irtn=m_pSerialPort->wait();
    m_pSerialPort->receive((char*)pResponse,irtn);
    checkResponse(iChid,pResponse);

 //   MqDebug()<<"SetLight:"<<pLight->m_sName<<ibright;
    return 0;
}

void CLightDriver_KM::MakeCommand(byte *pCommand, int &iSize, int iCHID, int data)
{
    pCommand[0]=0x40;
    pCommand[1]=0x06;
    pCommand[2]=0x01;
    pCommand[3]=0x00;
    pCommand[4]=0x1A;
    pCommand[5]=iCHID;
    pCommand[6]=data&0xFF;
    pCommand[7]=(data>>8)&0xFF;
    pCommand[8]=0;
    for(int i=0;i<8;i++)
    {
        pCommand[8]+=pCommand[i];
    }
    iSize=9;
}

void CLightDriver_KM::checkResponse(int32_t iChid, byte *pResponse)
{
    UNUSED(iChid);
    if(pResponse[0]!=0x40||pResponse[1]!=0x03||
       pResponse[2]!=0x01||pResponse[3]!=0x00||
       pResponse[4]!=0x00||pResponse[5]!=0x44)
    {
        MqDebug()<<pResponse[0]<<pResponse[1]
                <<pResponse[2]<<pResponse[3]
                <<pResponse[4]<<pResponse[5];
        MQT_THROW_STR(QObject::trUtf8("Light Driver KM Response err"));
    }
}
