#include "cctrlsensoranalog.h"
#include "ui_cctrlsensoranalog.h"
#include "logic.h"
CCtrlSensorAnalog::CCtrlSensorAnalog(QWidget *parent, int iAnalogID) :
    CMWidget(parent),
    ui(new Ui::CCtrlSensorAnalog)
{
    ui->setupUi(this);
    m_iAnalogID=iAnalogID;
    m_iStateChanged=-1;
}

CCtrlSensorAnalog::~CCtrlSensorAnalog()
{
    delete ui;
}

void CCtrlSensorAnalog::MFresh()
{
    CIO* pIO=GET_CHDIRECT(IO_INPUT_ANALOG,CIO);
    ui->label_name->setText(pIO->m_io[m_iAnalogID].singlename);

    ui->lcdNumber_Thres->display(int(pIO->m_io[m_iAnalogID].fanalogThres));


}

void CCtrlSensorAnalog::MTimeFresh()
{
   CMotorDriver* pMotorDriver=GET_CARD(MOTOR_DRIVER,CMotorDriver);
   Q_ASSERT(pMotorDriver);
   int iData= pMotorDriver->get_iodata_analog(IO_INPUT_ANALOG,m_iAnalogID,false);
   //static int iData=0;iData=(iData++)%1000;
   ui->lcdNumber_Cur->display(iData);

   int iCurState=pMotorDriver->is_iodata_analog_high(IO_INPUT_ANALOG,m_iAnalogID,false);
   if(m_iStateChanged!=iCurState)
   {
       m_iStateChanged=iCurState;
       if(iCurState)
       {
           ui->lcdNumber_Cur->setStyleSheet("color:green");
       }
       else
       {
           ui->lcdNumber_Cur->setStyleSheet("color:red");
       }
   }

}

void CCtrlSensorAnalog::timerEvent(QTimerEvent *event)
{
    if(event->timerId()==m_iTimerID)
    {
        if(m_bAdd)
        {
            ChangeThres(+5,false);
        }
        else
        {
            ChangeThres(-5,false);
        }
    }
}

void CCtrlSensorAnalog::ChangeThres(double dstep, bool bsave)
{
    UNUSED(bsave);
    CIO* pIO=GET_CHDIRECT(IO_INPUT_ANALOG,CIO);
    pIO->m_io[m_iAnalogID].fanalogThres+=dstep;
    MFresh();
}


void CCtrlSensorAnalog::on_pushButton_Reduce_pressed()
{
    m_iTimerID=startTimer(200);m_bAdd=false;
}

void CCtrlSensorAnalog::on_pushButton_Add_pressed()
{
    m_iTimerID=startTimer(200);m_bAdd=true;
}

void CCtrlSensorAnalog::on_pushButton_Reduce_released()
{
    killTimer(m_iTimerID);
    ChangeThres(-1,true);
}

void CCtrlSensorAnalog::on_pushButton_Add_released()
{
    killTimer(m_iTimerID);
    ChangeThres(+1,true);
}

void CCtrlSensorAnalog::on_lcdNumber_Thres_overflow()
{

}
