#include "drv_tp_iic.h"

#define I2C_TIMEOUT                         (0x1800U)
#define I2C_BUFFER_LENGTH                   (8U)

static uint32_t s_timeout = I2C_TIMEOUT;
static status_t status = STATUS_SUCCESS;
static uint32_t s_byteRemaining = 8U;
static bool ACK;

void bsp_drv_tp_iic_init(void)
{
    /* Configure I2C  */
	I2C_MasterInit(&lpi2c0_instance, &i2c_pal_lpi2c0_MasterConfig0);
}

void bsp_drv_tp_iic_deinit(void)
{
	I2C_MasterDeinit(&lpi2c0_instance);
}

int bsp_drv_tp_iic_set_slave_address(uint16_t address)
{
	return I2C_MasterSetSlaveAddress(&lpi2c0_instance, address, false);
}

bool bsp_drv_tp_iic_read(uint8_t *pBuf,int len ,bool sendstop)
{
	 s_timeout = I2C_TIMEOUT;
	 status = I2C_MasterReceiveData(&lpi2c0_instance, pBuf, len, sendstop);
	 if (status == STATUS_SUCCESS)
	 {
	     do
	     {
	         s_timeout--;
	         status = I2C_MasterGetTransferStatus(&lpi2c0_instance, &s_byteRemaining);
	     } while ((s_timeout != 0U) && (status != STATUS_SUCCESS));
	     if ((s_byteRemaining != 0U) || (s_timeout == 0U))
	     {
	         return false;
	     }
	     else
	     {
	         return true;
	     }
	 }
	 else
	 {
	     return false;
	 }
}

bool bsp_drv_tp_iic_write(const uint8_t *pBuf,int len, bool sendstop)
{
    s_timeout = I2C_TIMEOUT;
    status = I2C_MasterSendData(&lpi2c0_instance, pBuf, len, sendstop);
    if (status == STATUS_SUCCESS)
    {
        do
        {
            s_timeout--;
            status = I2C_MasterGetTransferStatus(&lpi2c0_instance, &s_byteRemaining);
        } while ((s_timeout != 0U) && (status != STATUS_SUCCESS));
        if ((s_byteRemaining != 0U) || (s_timeout == 0U))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        return false;
    }
}