#include "ledcontrol.h"

ledcontrol::ledcontrol(QObject *parent) : QObject(parent)
{
    fd = open("/dev/i2c-1", O_RDWR);	//打开i2c-0的节点
    if(fd < 0)
    {
        qDebug()<<"open error";
        perror("open error\n");
    }

    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutSilencer()));
}

ledcontrol::~ledcontrol()
{
    close(fd);
}

void ledcontrol::onTimerTimeOutSilencer()
{
    __u8 TD_STATUS;
    int ret = 0;
    unsigned char rd_buf[13] = {0x10};
    unsigned char wr_buf[13] = {0};

    /*设置eeprom的I2C设备地址*/
    if (ioctl(fd,I2C_SLAVE_FORCE, 0x27) < 0)
    {
        qDebug()<<"set slave address failed";
        printf("set slave address failed \n");
    }
    /* 将要操作的寄存器首地址赋给wr_buf[0] */
    wr_buf[0] = 0x01;

    write(fd, wr_buf, 1);

    ledWrite(0x27,0x01,1);

    sleep(1);

    ret=read(fd, rd_buf, 1);

    TD_STATUS = rd_buf[0];
    //qDebug()<<"格式化16进制小写输出"<<QString().sprintf("%04x",TD_STATUS);
    if(TD_STATUS == 0x64)
    {
        emit SilencingKeyClick();
    }else{

    }

    QTimer::singleShot(1000, this, SLOT(onTimerTimeOutSilencer()));
}

void ledcontrol::onLedControl(int arr)
{
    unsigned char wr_buf[13] = {0};

    /*设置eeprom的I2C设备地址*/
    if (ioctl(fd,I2C_SLAVE_FORCE, 0x34) < 0)
    {
        qDebug()<<"set slave address failed";
        printf("set slave address failed \n");
    }
    /* 将要操作的寄存器首地址赋给wr_buf[0] */
    wr_buf[0] = arr;

    if(write(fd, wr_buf, 1))
    {

    }else{
        qDebug()<<"write write write failed";
    }
    ledWrite(0x34,arr,1);
}

void ledcontrol::ledWrite(int slave_addr,int w_b,int len)
{
    unsigned char wr_buf[13] = {0};

    /*设置eeprom的I2C设备地址*/
    if (ioctl(fd,I2C_SLAVE_FORCE, slave_addr) < 0)
    {
        qDebug()<<"set slave address failed";
    }
    /* 将要操作的寄存器首地址赋给wr_buf[0] */
    wr_buf[0] = w_b;

    if(write(fd, wr_buf, len))
    {

    }else{
        qDebug()<<"write write write failed";
    }
}

