#include "drv_slave_iic.h"
#include "bsp_register_map.h"

#include <stdio.h>
#include "cola_os.h"

extern void logWrite(const char *fmt, ...);

static task_t *pSlaveRxTask = NULL;
ST_I2C_RX_TX drv_stRxTxBuf;

void IIC_callback(i2c_slave_event_t slaveEvent, void *userData)
{
//	/* Get instance number from userData */
	i2c_instance_t * instance;
	instance = (i2c_instance_t *) userData;

	if (slaveEvent == I2C_SLAVE_EVENT_RX_REQ)
	{
		if(drv_stRxTxBuf.rxbuf != NULL)
			I2C_SlaveSetRxBuffer(instance, drv_stRxTxBuf.rxbuf, drv_stRxTxBuf.rxlength);
		if(pSlaveRxTask != NULL)
			cola_set_event(pSlaveRxTask, 0x01);
	}
	if (slaveEvent == I2C_SLAVE_EVENT_TX_REQ)
	{
		if(drv_stRxTxBuf.txbuf != NULL)
			I2C_SlaveSetTxBuffer(instance, drv_stRxTxBuf.txbuf, drv_stRxTxBuf.txlength);
	}
}

void bsp_drv_slave_iic_init(void)
{
	i2c_pal_lpi2c0_SlaveConfig0.callbackParam = (uint32_t *) &lpi2c0_instance;
	I2C_SlaveInit(&lpi2c0_instance, &i2c_pal_lpi2c0_SlaveConfig0);

}

void bsp_drv_slave_iic_Deinit(void)
{
	I2C_SlaveDeinit(&lpi2c0_instance);
}

void bsp_drv_slave_iic_read(uint8_t *pBuf,int len)
{
	I2C_SlaveReceiveData(&lpi2c0_instance,pBuf,len);
}

void bsp_drv_slave_iic_write(const uint8_t *pBuf,int len)
{
	I2C_SlaveSendData(&lpi2c0_instance,pBuf,len);
}

void bsp_drv_slave_iic_cfg(uint8_t *pRxBuf,int *iRxLength)
{

}

void bsp_drv_slave_iic_ctrl_task(void *task)
{
	pSlaveRxTask = (task_t*)task;
}
void bsp_drv_slave_iic_ctrl_buf(void *task)
{
	uint32_t * p = task;
	drv_stRxTxBuf.rxbuf = *p;
	drv_stRxTxBuf.rxlength = *(p+1);
	drv_stRxTxBuf.txbuf = *(p+2);
	drv_stRxTxBuf.txlength = *(p+3);
}
