#include "ft5216.h"
#include "tp.h"

u8 READ_BUFF[128];
u8 WRITE_BUFF[20];
UINT8  fingerNumber =0;
u8 ctp_active_index =0;

extern IOCTRL_I2CInitTypeDef IOI2CInit;
extern I2C_HandleTypeDef I2C1_Handle;

//#define     SDA_High                   	HAL_I2C_GPIOWritePin(I2C1, I2C_PIN_SDA, SET)
//#define     SDA_Low                     HAL_I2C_GPIOWritePin(I2C1, I2C_PIN_SDA, RESET)
//#define     SCL_High                    HAL_I2C_GPIOWritePin(I2C1, I2C_PIN_SCL, SET)
//#define     SCL_Low                     HAL_I2C_GPIOWritePin(I2C1, I2C_PIN_SCL, RESET)
//#define     GetSDABit                   HAL_I2C_GPIOReadPin(I2C1, I2C_PIN_SDA)

///*************配置SDA引脚为输出********************/
//void SCL_OUTPUT(void)
//{
//	GPIO_InitTypeDef I2CGPIOInitStruct;
////    GPIO_PinStateTypeDef PinState;

//    I2CGPIOInitStruct.Pin = I2C_PIN_SCL;
//    I2CGPIOInitStruct.Dir = GPIO_DIR_OUT;
//    I2CGPIOInitStruct.OutputMode = GPIO_OUTPUT_MODE_CMOS;
//    I2CGPIOInitStruct.PullMode = GPIO_PULL_MODE_UP;
//    HAL_I2C_GPIOInit(I2C1, &I2CGPIOInitStruct);
//}

///*************配置SDA引脚为输出********************/
//void SDA_OUTPUT(void)
//{
//	 GPIO_InitTypeDef I2CGPIOInitStruct;
////    GPIO_PinStateTypeDef PinState;

//    I2CGPIOInitStruct.Pin = I2C_PIN_SDA;
//    I2CGPIOInitStruct.Dir = GPIO_DIR_OUT;
//    I2CGPIOInitStruct.OutputMode = GPIO_OUTPUT_MODE_CMOS;
//    I2CGPIOInitStruct.PullMode = GPIO_PULL_MODE_UP;
//    HAL_I2C_GPIOInit(I2C1, &I2CGPIOInitStruct);
//}

///**************配置SDA引脚为输入*****************/
//void SDA_INPUT(void)
//{
//	GPIO_InitTypeDef I2CGPIOInitStruct;
////    GPIO_PinStateTypeDef PinState;
//		
//    I2CGPIOInitStruct.Pin = I2C_PIN_SDA;
//    I2CGPIOInitStruct.Dir = GPIO_DIR_IN;
//    I2CGPIOInitStruct.OutputMode = GPIO_OUTPUT_MODE_CMOS;
//    I2CGPIOInitStruct.PullMode = GPIO_PULL_MODE_UP;
//    HAL_I2C_GPIOInit(I2C1, &I2CGPIOInitStruct);
//}

//void CT_DELAY_US(UINT32 val)
//{
//	u32 time=200;
//	while(time--);
//}

///*****************************CTI2C启动函数***************************/
//static void CTI2C_start(void)
//{
//	SDA_OUTPUT();
//	SDA_High;
//	SCL_High;
//	CT_DELAY_US(1);
//	SDA_Low;
//	CT_DELAY_US(1);
//	SCL_Low;
//	CT_DELAY_US(1);
//}

///*****************************CTI2C停止函数**************************/
//static void CTI2C_stop(void)
//{
//	SDA_OUTPUT();
//	SCL_Low;
//	SDA_Low;

//	CT_DELAY_US(1);
//	SCL_High;
//	CT_DELAY_US(1);
//	SDA_High;
//	CT_DELAY_US(1);
//}

///********************CTI2C写1byte函数,S为需要写的内容*****************/
//u8 CTI2C_write_byte(u8 s)
//{
//	u8 ch_data,iii=0;

//	SDA_OUTPUT();			
//	ch_data=s;
//	SCL_Low;
//	for(iii=0;iii<8;iii++)
//	{
//		if(ch_data&0x80)
//						SDA_High;
//		else    SDA_Low;
//		CT_DELAY_US(1);
//		SCL_High;
//		CT_DELAY_US(1);
//		SCL_Low;                       
//		ch_data=ch_data<<1;
//	}
//	//Read ACK
//	SDA_INPUT();			
//	SDA_High;
//	CT_DELAY_US(1);
//	SCL_High;
//	CT_DELAY_US(1);
//	if(GetSDABit==0)
//	{
//		SCL_Low;
//		return 0;
//	}
//	else
//	{
//		SCL_Low;
//		return 1;
//	}
//}

/////****************CTI2C读1byte函数，返回值为所读数据*****************/
//u8 CTI2C_read_byte(uint8_t ack)
//{
//	u8 ch_data,iii=0;

//	SDA_INPUT();
//	ch_data=0x00;               
//	for(iii=0;iii<8;iii++)
//	{
//		ch_data=ch_data<<1;
//		SCL_Low;             
//		SDA_High;		
//		CT_DELAY_US(1);
//		SCL_High;
//		CT_DELAY_US(1);
//		if(GetSDABit==1)  ch_data=ch_data|0x01;
//	}
//	SCL_Low;
//	SDA_OUTPUT();
//	SCL_Low;
//	if(!ack)
//	{
//		SDA_Low;		
//		CT_DELAY_US(1);
//		SCL_High;
//		CT_DELAY_US(1);
//		SCL_Low;
//	}
//	else
//	{
//		SDA_High;		
//		CT_DELAY_US(1);
//		SCL_High;
//		CT_DELAY_US(1);
//		SCL_Low;
//	}

//	return ch_data;
//}

///******************************************************************************
// * FUNCTION: CT_Read_Nbyte ( )
// * DESCRIPTION: 从触摸屏中读出数据
// *    Input the description of function:
// * Input Parameters: 器件地址，待读寄存器地址，待读数据数量，存储待读出数据的地址
// * Output Parameters: 读取的数据
// * Returns Value:
// ******************************************************************************/
//u8 CT_Read_Nbyte(uint8_t sla_add,uint16_t add,uint16_t n,uint8_t *s)					//CTI2C读nbyte函数,所读数据放在形参数组中（由程序员设置合适的数组大小），成功返回1，失败返回0
//{
//	u8 temps;
//	u16 tempn;
//	CTI2C_start();																																				//启动CTI2C总线
//	CTI2C_write_byte(sla_add | CT_WRITE_MASK);
//	
//#if GT_TOUCH
//	CTI2C_write_byte(add>>8);
//#endif
//	
//	CTI2C_write_byte(add);
//	CTI2C_stop();
//	CTI2C_start();																																				//再次启动CTI2C总线
//	CTI2C_write_byte(sla_add | CT_READ_MASK);
//	for(tempn=0;tempn<n;tempn++)
//	{

//		if(tempn+1<n)																																				//如果已经读完所有数据了，就不要发应答信号，直接发非应答位和停止位
//		{
//			temps = CTI2C_read_byte(0);
//			*(s+tempn)=temps;
//		}
//	}
//	temps = CTI2C_read_byte(1);
//	*(s+tempn-1)=temps;
//	CTI2C_stop();

//	return CT_COM_OK;
//}

///******************************************************************************
// * FUNTPION: TP_Write_Nbyte ( )
// * DESCRIPTION: 写触摸屏寄存器
// *    Input the description of funTPion: 
// * Input Parameters: 器件地址，待写寄存器地址，待写数据数量，存储待写入数据的地址
// * Output Parameters: 无
// * Returns Value: 
// ******************************************************************************/
//uint8_t CT_Write_Nbyte(uint8_t sla_add,uint16_t add,uint16_t n,uint8_t *s)//TP写nbyte函数，写数据由形参数组传入，成功返回1，失败返回0
//{
//    uint8_t temps,ack=1;
//    uint16_t tempn;
//    uint16_t cack_time=0;
//    CTI2C_start();//启动TP总线
//    CTI2C_write_byte(sla_add | CT_WRITE_MASK);//发送寻址字节

//#if GT_TOUCH
//	CTI2C_write_byte(add>>8);
//#endif		
//    CTI2C_write_byte(add);//发送要写入的起始地址
//	
//	for(tempn=0;tempn<n;tempn++) CTI2C_write_byte(s[tempn]);
// 
// /*
//    for(tempn=0;tempn<n;tempn++)
//    {
//        ack=1;//应答位
//        cack_time=0;
//        temps=*(s+tempn);
//        while(ack)
//        {
//           ack= CTI2C_write_byte(temps);
//            cack_time++;
//            if(cack_time>CT_CACK_TIMEOUT)//在规定时间cack_timeout内收不到应答信号，返回出错信号
//                return CT_ACK_FAIL;
//        }
//    }*/
//    CTI2C_stop();// TP停止
//    return CT_COM_OK;
//}

#if GT_TOUCH
unsigned char Config_BUFF[186] =
{
	0x41,0x00,0x04,0x58,0x02,0x0A,0x0D,0x00,0x01,0xC8,
	0x28,0x0F,0x50,0x32,0x03,0x05,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x29,0x77,
	0x17,0x15,0x31,0x0D,0x00,0x00,0x00,0x9A,0x03,0x2D,
	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x0F,0x37,0x94,0xC5,0x02,0x08,0x00,0x00,0x00,
	0x9B,0x11,0x00,0x7A,0x16,0x00,0x62,0x1C,0x00,0x4C,
	0x25,0x00,0x3D,0x30,0x00,0x3D,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x01,0x04,0x05,0x06,0x07,0x08,0x09,
	0x0C,0x0D,0x0E,0x0F,0x10,0x11,0xFF,0xFF,0xFF,0xFF,
	0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x02,0x04,0x06,0x07,0x08,0x0A,0x0C,
	0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x19,0x1B,
	0x1C,0x1E,0x1F,0x20,0x21,0x22,0x23,0xFF,0xFF,0xFF,
	0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x00,0xA4,0x01
};

void Checksum(unsigned char *p)     //配置信息校验 0x80ff  (已检查 算法无误)
{
	int i = 0;
    unsigned int sum_buffer = 0;

    for( ; i<184 ; i++ )
	{
	   sum_buffer += *(p+i);
	}

	*(p+184) =~sum_buffer + 1;
	printf("%x\r\n",*(p+184));
}

#endif

void I2C_ReadBytes(u16 addr,u8 addr_len,u8* buf,u16 buf_len)
{
	HAL_I2C_MemRead(&I2C1_Handle, CTP_SLAVE_ADDR, addr&0xffff, addr_len, buf, buf_len, 100);
}

void I2C_WriteBytes(u16 addr,u8 addr_len,u8* buf,u16 buf_len)
{
	HAL_I2C_MemWrite(&I2C1_Handle, CTP_SLAVE_ADDR, addr&0xffff, addr_len, buf, buf_len, 100);
}

/*****************电容触摸屏相关IO口初始化函数************************/
//void CTP_io_Init(void)
//{
//	u8 chip_id;
//	u16 version;
//	u8 firmware;
//	u8 buf[6];
//	
//#if FT_TOUCH
//	IOI2CInit.id=IOCTRL_I2C1;
//	HAL_IOCTRL_I2CInit(&IOI2CInit);

//	I2C1_Handle.Instance = I2C1;
//	I2C1_Handle.Init.Mode = I2C_MODE_MASTER;
//	I2C1_Handle.Init.AddBits = 0x00;
//	I2C1_Handle.Init.Add = 0x00;
//	I2C1_Handle.Init.HighSpeed = DISABLE;
//	//I2C1_Handle.Init.HighSpeed = ENABLE;
//	I2C1_Handle.Init.ClockMode = I2C_CLOCK_MODE_NORMAL;
//	I2C1_Handle.Init.Prescaler = 0;

//	HAL_I2C_Init(&I2C1_Handle);
//	
//	HAL_IOCTRL_Swapint(IOCTRL_SWAP10, ENABLE);
//	
//	INT_INPUT;
//	RESET_OUTPUT;	
//	RESET_LOW;
//	DelayMS(20);
//	RESET_HIGH;
//	DelayMS(50);

//	NVIC_Init(3, 3, EPORT0_5_IRQn, 2);
//	DRV_EPORT_SetTriggerMode(EPORT, EPORT_PIN5, EPORT_FALLING_TRIGGER);
//	DRV_EPORT_SetIT(EPORT, EPORT_PIN5, ENABLE);

//	I2C_ReadBytes(0xA3,1,buf,1);	
//	
//#endif
//	
//#if GT_TOUCH
//	unsigned int   Product_ID;
//	
//	IOI2CInit.id=IOCTRL_I2C1;
//	HAL_IOCTRL_I2CInit(&IOI2CInit);

//	I2C1_Handle.Instance = I2C1;
//	I2C1_Handle.Init.Mode = I2C_MODE_MASTER;
//	I2C1_Handle.Init.AddBits = 0x00;
//	I2C1_Handle.Init.Add = 0x00;
//	I2C1_Handle.Init.HighSpeed = DISABLE;
//	//I2C1_Handle.Init.HighSpeed = ENABLE;
//	I2C1_Handle.Init.ClockMode = I2C_CLOCK_MODE_NORMAL;
//	I2C1_Handle.Init.Prescaler = 0;

//	HAL_I2C_Init(&I2C1_Handle);
//	
//	HAL_IOCTRL_Swapint(IOCTRL_SWAP10, ENABLE);
//	
//	INT_INPUT;
//	RESET_OUTPUT;	
//	RESET_LOW;
//	DelayMS(20);
//	RESET_HIGH;
//	DelayMS(50);

//	INT_OUTPUT;
//	RESET_OUTPUT;

//	INT_LOW;   //INT = 0,For GT911 Addr = 0xBB
//	RESET_LOW; //RESET = 0;
//	DelayMS(2);
//	INT_HIGH; //INT  = 1;
//	DelayMS(2);
//	RESET_HIGH;
//	DelayMS(10);
//	INT_LOW;
//	DelayMS(60);
//	INT_INPUT;
//	DelayMS(20);
//	
//	I2C_ReadBytes(0x4081,2, buf, 6);

//	Product_ID = buf[3];
//	Product_ID = Product_ID << 8 | buf[2];
//	Product_ID = Product_ID << 8 | buf[1];
//	Product_ID = Product_ID << 8 | buf[0];

////	printf("\r\nID:%x \r\n", Product_ID);	

//	NVIC_Init(3, 3, EPORT0_5_IRQn, 2);
//	DRV_EPORT_SetTriggerMode(EPORT, EPORT_PIN5, EPORT_FALLING_TRIGGER);
//	DRV_EPORT_SetIT(EPORT, EPORT_PIN5, ENABLE);
//	
//#endif

//}

void CTP_io_Init(void)
{
//	u8 chip_id;
//	u16 version;
//	u8 firmware;
	u8 buf[6];
	
#if FT_TOUCH
	#if	Hardware_IIC
	IOI2CInit.id=IOCTRL_I2C1;
	HAL_IOCTRL_I2CInit(&IOI2CInit);

	I2C1_Handle.Instance = I2C1;
	I2C1_Handle.Init.Mode = I2C_MODE_MASTER;
	I2C1_Handle.Init.AddBits = 0x00;
	I2C1_Handle.Init.Add = 0x00;
	I2C1_Handle.Init.HighSpeed = DISABLE;
	//I2C1_Handle.Init.HighSpeed = ENABLE;
	I2C1_Handle.Init.ClockMode = I2C_CLOCK_MODE_NORMAL;
	I2C1_Handle.Init.Prescaler = 0;

	HAL_I2C_Init(&I2C1_Handle);	
	#else 
	SCL_OUTPUT();
	SDA_OUTPUT();
	#endif
	HAL_IOCTRL_Swapint(IOCTRL_SWAP10, ENABLE);
	INT_INPUT;
	RESET_OUTPUT;	
	RESET_LOW;
	DelayMS(20);
	RESET_HIGH;
	DelayMS(50);

	NVIC_Init(3, 3, EPORT0_5_IRQn, 2);
	DRV_EPORT_SetTriggerMode(EPORT, EPORT_PIN5, EPORT_FALLING_TRIGGER);
	DRV_EPORT_SetIT(EPORT, EPORT_PIN5, ENABLE);

	#if	Hardware_IIC
	I2C_ReadBytes(0xA3,1,buf,1);	
	#else
	CT_Read_Nbyte(CTP_SLAVE_ADDR,1,0xA3,1,buf);
	#endif
#endif
	
#if GT_TOUCH
	unsigned int   Product_ID;
	
	#if	Hardware_IIC
	IOI2CInit.id=IOCTRL_I2C1;
	HAL_IOCTRL_I2CInit(&IOI2CInit);

	I2C1_Handle.Instance = I2C1;
	I2C1_Handle.Init.Mode = I2C_MODE_MASTER;
	I2C1_Handle.Init.AddBits = 0x00;
	I2C1_Handle.Init.Add = 0x00;
	I2C1_Handle.Init.HighSpeed = DISABLE;
	//I2C1_Handle.Init.HighSpeed = ENABLE;
	I2C1_Handle.Init.ClockMode = I2C_CLOCK_MODE_NORMAL;
	I2C1_Handle.Init.Prescaler = 0;

	HAL_I2C_Init(&I2C1_Handle);	
	#else 
	SCL_OUTPUT();
	SDA_OUTPUT();
	#endif
	
	HAL_IOCTRL_Swapint(IOCTRL_SWAP10, ENABLE);
	
	INT_INPUT;
	RESET_OUTPUT;	
	RESET_LOW;
	DelayMS(20);
	RESET_HIGH;
	DelayMS(50);

	INT_OUTPUT;
	RESET_OUTPUT;

	INT_LOW;   //INT = 0,For GT911 Addr = 0xBB
	RESET_LOW; //RESET = 0;
	DelayMS(2);
	INT_HIGH; //INT  = 1;
	DelayMS(2);
	RESET_HIGH;
	DelayMS(10);
	INT_LOW;
	DelayMS(60);
	INT_INPUT;
	DelayMS(20);
	
#if	Hardware_IIC
	I2C_ReadBytes(0x4081,2, buf, 6);
#else
	CT_Read_Nbyte(CTP_SLAVE_ADDR,2,0x8140,6,buf);
#endif

	Product_ID = buf[3];
	Product_ID = Product_ID << 8 | buf[2];
	Product_ID = Product_ID << 8 | buf[1];
	Product_ID = Product_ID << 8 | buf[0];

//	printf("\r\nID:%x \r\n", Product_ID);	

	NVIC_Init(3, 3, EPORT0_5_IRQn, 2);
	DRV_EPORT_SetTriggerMode(EPORT, EPORT_PIN5, EPORT_FALLING_TRIGGER);
	DRV_EPORT_SetIT(EPORT, EPORT_PIN5, ENABLE);
	
#endif

}

void EPORT0_5_IRQHandler(void)
{
	EPORT->EPFR |= EPORT_PIN5;			//clear flag by writing 1 to it.
	ctp_active_index = 1;	
}

/*****************电容触摸屏相关IO口初始化函数************************/
void CTP_Init(void)
{
	CTP_io_Init();
	gTpInfo.scan = FT5216_Scan;
}

/*********************************读XY轴函数***************************************/
void TP_read_XY(void)
{
	u16 x,y;
	
#if FT_TOUCH
	#if	Hardware_IIC
	I2C_ReadBytes(0x02,1,READ_BUFF,5);	
	#else
	CT_Read_Nbyte(CTP_SLAVE_ADDR,1,0x02,5,READ_BUFF);	
	#endif

	fingerNumber = READ_BUFF[0]&0xF;
	
	if(READ_BUFF[1]&0x80)
	{
		x  = READ_BUFF[1]&0xF;  //计算X轴
		x  = x<<8;
		x += READ_BUFF[2];
		
		y  = READ_BUFF[3]&0xF;
		y  = y<<8;
		y += READ_BUFF[4];
		gTpInfo.sta =1;
		gTpInfo.x[0] = x;
		gTpInfo.y[0] = y;	

		if(gTpInfo.x[0]>LCD_XSIZE_TFT)	gTpInfo.x[0] = LCD_XSIZE_TFT;
		if(gTpInfo.y[0]>LCD_YSIZE_TFT)	gTpInfo.y[0] = LCD_YSIZE_TFT;

		if(First_press==0)
		{
			First_press=1;
			First_pressX= gTpInfo.x[0];
			First_pressY= gTpInfo.y[0];			
		}	
	}
	else if(READ_BUFF[1]&0x40)
	{
		gTpInfo.sta =0;
		First_press=0;
	}
#endif
	
	#if GT_TOUCH
	u16 X_Max,Y_Max;
	u8 writedata[1]={0};
	
	#if	Hardware_IIC
	I2C_ReadBytes(0x4e81,2,READ_BUFF,9);
	#else
	CT_Read_Nbyte(CTP_SLAVE_ADDR,2,0x814e,9,READ_BUFF);	
	#endif

	if(READ_BUFF[0]&0x80)   //buffer status 为1时才是数据有效
	{
		x = READ_BUFF[3];
		x = x<<8 |READ_BUFF[2];		
		
		y = READ_BUFF[5];
		y = y<<8 |READ_BUFF[4];
		
		gTpInfo.x[0] = x;
		gTpInfo.y[0] = y;
		gTpInfo.sta = READ_BUFF[0]&0x0F;

		#if	Hardware_IIC		
		I2C_ReadBytes(0x4880,2,READ_BUFF,4);
		#else
		CT_Read_Nbyte(CTP_SLAVE_ADDR,2,0x8048,4,READ_BUFF);
		#endif
		
		X_Max = READ_BUFF[1];
		X_Max = X_Max<<8 |READ_BUFF[0];		
		Y_Max = READ_BUFF[3];
		Y_Max = Y_Max<<8 |READ_BUFF[2];
//		printf("x_max:%d y_max:%d\r\n",X_Max,Y_Max);		

		gTpInfo.x[0] = (u32)(x*1023/(X_Max-1));
		gTpInfo.y[0] = (u32)(y*599/(Y_Max-1));			
		
//		printf("x:%d y%d\r\n",gTpInfo.x[0],gTpInfo.y[0]);	
//		if(gTpInfo.x[0]>LCD_XSIZE_TFT)	gTpInfo.x[0] = LCD_XSIZE_TFT;
//		if(gTpInfo.y[0]>LCD_YSIZE_TFT)	gTpInfo.y[0] = LCD_YSIZE_TFT;
		if(gTpInfo.sta==1)
		{
			if(First_press==0)
			{
				First_press=1;
				First_pressX= gTpInfo.x[0];
				First_pressY= gTpInfo.y[0];	
			}						
		}
		else First_press=0;
		
		#if	Hardware_IIC		
		I2C_WriteBytes(0x4e81,2,writedata,1);
		#else
		CT_Write_Nbyte(CTP_SLAVE_ADDR,2,0x814e,1,writedata);
		#endif

	}
#endif
}

u8 FT5216_Scan(void)
{
#if FT_TOUCH
	if(ctp_active_index ==1)
	{
		TP_read_XY();
		ctp_active_index=0;
//		printf("x:%d  y:%d\r\n",gTpInfo.x[0],gTpInfo.y[0]);
		return 1;
	}
	else 
	{
		return 0;
	}

#endif
	
#if GT_TOUCH


	if(ctp_active_index==1)
	{	
		TP_read_XY();
//		printf("x:%d y%d\r\n",gTpInfo.x[0],gTpInfo.y[0]);
		ctp_active_index = 0;
		return 1;
	}
	else
	{
		return 0;
	}
	
#endif
}
