/*
 * ALS308.c
 *
 *  Created on: 2022年4月11日
 *      Author: amos
 */
#include "rgb381.h"
#include "TCA9548A.h"
#include <string.h>
#define I2C_TIMEOUT_1000MS  16000000  // 定义超时时间（毫秒）
#define CARD_NO_ALIGN 3
#define CARD_NO_MIN 10
ColorSensor CS[CS_MAX] = {0};	//检测孔

uint8_t SensorState1=0,SensorState2=0,SensorState3=0,SensorState4=0,SensorState5=0,
		SensorState6=0,SensorState7=0,SensorState8=0,SensorState9=0,SensorState10=0;
//extern uint8_t I2C_data;

int8_t I2CWriteOneByte(I2C_HandleTypeDef *hi2c, uint8_t u8SlaveAddr, uint8_t u8DataAddr, uint8_t data)
{
    // HAL 库返回值：HAL_OK 表示成功
    HAL_StatusTypeDef status = HAL_I2C_Mem_Write(hi2c,
                                                  (uint16_t)(u8SlaveAddr << 1),  // 7位地址左移1位，HAL内部会处理读写位
                                                  (uint16_t)u8DataAddr,          // 寄存器地址（8位）
                                                  I2C_MEMADD_SIZE_8BIT,          // 寄存器地址宽度 8 位
                                                  &data,                         // 要写入的数据
                                                  1,                             // 数据长度（字节）
                                                  100);                          // 超时时间 ms
    if (status == HAL_OK)
        return 0;   // 成功
    else
        return 3;   // 统一返回 3（或按原函数错误码细化）
}
uint8_t I2CReadOneByte(I2C_HandleTypeDef *hi2c, uint8_t u8SlaveAddr, uint8_t u8DataAddr)
{
    uint8_t rdata = 0;
    HAL_StatusTypeDef status = HAL_I2C_Mem_Read(hi2c,
                                                 (uint16_t)(u8SlaveAddr << 1),
                                                 (uint16_t)u8DataAddr,
                                                 I2C_MEMADD_SIZE_8BIT,
                                                 &rdata,
                                                 1,
                                                 100);
    if (status == HAL_OK)
        return rdata;
    else
        return 0;   // 失败返回 0（与原函数一致）
}


    uint8_t I2C_data = 0;
void TCA9548A_SetChannel(uint8_t ID)
{
	/********************************************************/
	/**************background light--PA0*********************/
	/*********************WIFI_EN--PA12**********************/
	/**********************I2C_S0--PB3***********************/
	/***********************I2C_S1--PB2**********************/
	/**********************I2C_S2--PB1***********************/
	/**********************I2C_S3--PB0***********************/
	/**********************I2C_S4--PF5***********************/
	/******************Device_num1--PB15*********************/
    /******************Device_num2--PB14*********************/
    /******************Device_num3--PB13*********************/
    /******************Device_num4--PB12*********************/
    /***********************LED--PF4*************************/
    /***********************DEC--PB15************************/

    switch(ID)
    {
        case 0:
        	I2C_data = TCA9548A_CHANNEL_0;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,ID);
            break;
        case 1:
        	I2C_data = TCA9548A_CHANNEL_0;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            HAL_Delay(50);
        	I2C_data = TCA9548A_CHANNEL_2;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 2:
        	I2C_data = TCA9548A_CHANNEL_3;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 3:
        	I2C_data = TCA9548A_CHANNEL_4;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 4:
        	I2C_data = TCA9548A_CHANNEL_5;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 5:
        	I2C_data = TCA9548A_CHANNEL_6;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 6:
        	I2C_data = TCA9548A_CHANNEL_7;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 7:
        	I2C_data = TCA9548A_CHANNEL_8;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            break;
        case 8:

        	I2C_data = TCA9548A_CHANNEL_1;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR,I2C_data,I2C_data);
            HAL_Delay(50);
        	I2C_data = TCA9548A_CHANNEL_0;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR1,I2C_data,I2C_data);
            HAL_Delay(50);
            I2C_data = TCA9548A_CHANNEL_2;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR1,I2C_data,I2C_data);
            break;
        case 9:
//        	I2C_data = TCA9548A_CHANNEL_0;
//            I2CWriteOneByte(I2C0,TCA9548A_SLAVE_ADDR1,I2C_data,I2C_data);
//            DelayMS(100);
        	I2C_data = TCA9548A_CHANNEL_3;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR1,I2C_data,I2C_data);
            break;
        case 10:
//        	I2C_data = TCA9548A_CHANNEL_0;
//            I2CWriteOneByte(I2C0,TCA9548A_SLAVE_ADDR1,I2C_data,I2C_data);
//            DelayMS(100);
        	I2C_data = TCA9548A_CHANNEL_4;
            I2CWriteOneByte(&hi2c1,TCA9548A_SLAVE_ADDR1,I2C_data,I2C_data);
            break;
        default:
            break;
    }
}

void SensorMeasurementFactor(uint8_t measfactor)
{
	I2CWriteOneByte(&hi2c1,RGB381_ADDR,RGB381_MeasRate,measfactor);
}

void SensorSetGain(uint8_t gain)
{
	I2CWriteOneByte(&hi2c1,RGB381_ADDR,RGB381_Gain,gain);
}

uint8_t SensorGetID(uint8_t ID)
{
	TCA9548A_SetChannel(ID);
	HAL_Delay(100);
	return I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_PartID);
//	return I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_PartID);
}

void SensorGetRawData(ColorSensor *CS)
{

	uint32_t u32Timeout = I2C_TIMEOUT_1000MS;  // 转换为时钟周期数
  uint32_t u32StartTick = sysinf.ms_conter;

	uint32_t u32LastTick;
	uint32_t time;

	TCA9548A_SetChannel(CS->ID);
	HAL_Delay(40);
	u32LastTick = sysinf.ms_conter;
	time = u32LastTick - u32StartTick;
	while((I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_MainState)&0x08)==0x08){
	        // 超时检测
	      u32LastTick = sysinf.ms_conter;
			 time = u32LastTick - u32StartTick;
	
 			if(u32LastTick < u32StartTick){
 					time = u32LastTick + 0x1000000 - u32StartTick;
 			}
	        if ((time) > u32Timeout) {
	            CS->RDR = 0;
							Van_Device_Printf(VAN_LOG_ERROR, "error_state :%d\n",time);
	            return;  // 返回超时错误码
	        }

	};
	HAL_Delay(10);
//	LOG_E("error_state :%d\n",time);
	CS->RDR=(I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_R_DataLow)|
			(I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_R_DataMid)<<8)|
			(I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_R_DataHIG)<<16));
	if(CS->RDR == 0){
		HAL_Delay(10);
		CS->RDR=(I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_R_DataLow)|
				(I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_R_DataMid)<<8)|
				(I2CReadOneByte(&hi2c1,RGB381_ADDR,RGB381_R_DataHIG)<<16));
		if(CS->RDR == 0){
			Van_Device_Printf(VAN_LOG_ERROR, "error_Data\n");
		}
		 
	}
//	CS->RDG=(I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_G_DataLow)|
//			(I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_G_DataMid)<<8)|
//			(I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_G_DataHIG)<<16));
//	CS->RDB=(I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_B_DataLow)|
//			(I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_B_DataMid)<<8)|
//			(I2CReadOneByte(I2C0,RGB381_ADDR,RGB381_B_DataHIG)<<16));

}

void SensorEnable(void)
{
	 I2CWriteOneByte(&hi2c1,RGB381_ADDR,RGB381_MainCtrl,CS_Modle|ALS_Active);
	 HAL_Delay(10);
}

uint8_t SensorInit(ColorSensor *CS)
{
	if(SensorGetID(CS->ID)==0xC2)// device id is 0xC2
	{
		SensorEnable();
		SensorMeasurementFactor(ALS_MeasRes_17B|ALS_MeasRate_50ms);
		SensorSetGain(ALS_Gain_9X);
		CS->TtMax=0.0;
//		CS->TtNow=0.0;
//		CS->ColDifInit=0.0;
//		CS->ColDifNow=0.0;
//		CS->ColDifMax=0.0;
		CS->Tt=30.0;
		CS->STD=0.0;
		CS->average=0.0;
		memset(CS->SAMP, 0, sizeof(CS->SAMP));
		CS->std_num=0;
		CS->gain=0;
        SensorGetRawData(CS);

        for(int i = 0; i < 10; i++)
        {
            if(CS->RDR > CS_RDR_MIN)
                return 0;
            HAL_Delay(100);
            SensorGetRawData(CS);
        }
        return 1;

	}
	else
		return 1;
}

int SensorSelfCheck(void)
{
	SensorState1=SensorInit(&CS[0]);
	SensorState2=SensorInit(&CS[1]);
	SensorState3=SensorInit(&CS[2]);
	SensorState4=SensorInit(&CS[3]);
	SensorState5=SensorInit(&CS[4]);
	SensorState6=SensorInit(&CS[5]);
	SensorState7=SensorInit(&CS[6]);
	SensorState8=SensorInit(&CS[7]);
	SensorState9=SensorInit(&CS[8]);
	SensorState10=SensorInit(&CS[9]);

    if(SensorState1|SensorState2|SensorState3|SensorState4|SensorState5|SensorState6|SensorState7|SensorState8|SensorState9|SensorState10)
    	 return -1;
    else return 0;
}

void SensorGetCalData(ColorSensor *CS)
{
//	SensorGetRawData(CS);
	//CS->AccArea+=CS->RtR;
}


void SensorInitial(void)
{
	CS[0].ID = Sensor1;
	CS[1].ID = Sensor2;
	CS[2].ID = Sensor3;
	CS[3].ID = Sensor4;
	CS[4].ID = Sensor5;
	CS[5].ID = Sensor6;
	CS[6].ID = Sensor7;
	CS[7].ID = Sensor8;
	CS[8].ID = Sensor9;
	CS[9].ID = Sensor10;
}
int Returntozero(ColorSensor *CS)                                     //lxx-add-2022.12.26
{
	//lxx-add-2023.03.27
	SensorGetRawData(CS);
	CS->CDR = (float)CS->RDR;
	if(CS->RDR < CARD_NO_MIN){
		return 1;
	}
	if(CS->RDC/CS->RDR > CARD_NO_ALIGN){
		return 1;
	}
	return 0;
}

void Get_SAMP_DATA(ColorSensor *CS)
{
	CS->SAMP[0] = CS->RtR;
//	CS->CALCU_SAMP[samp_num] = (uint16_t)CS->RtR;
}
void Get_Tt(ColorSensor *CS)
{
	if(CS->Tt == 30.0)
	{
		if(CS->RtR>(10*fabs(CS->STD)+CS->average))
		{
			CS->std_num++;
			if(CS->std_num==5)	//连续5次
			{
				// CS->Tt = (sampleTimes-(5-1))/6.0f;	//每分钟6次;
			}
		}
		else
		{
			CS->std_num=0;
		}
	}
}
void Get_average(ColorSensor *CS)
{
	float sum= 0;
	int i = 0;

	for(i=0;i<SAMP_SIZE;i++)
	{
		sum += CS->SAMP[i];
	}
	CS->average = sum/(SAMP_SIZE);
}
void Get_STD(ColorSensor *CS)
{
	int i = 0;
	float sum = 0;

	for(i=0;i<SAMP_SIZE;i++)
	{
		sum += (CS->SAMP[i]-CS->average)*(CS->SAMP[i]-CS->average);
	}
	CS->STD = sqrtf(sum / (SAMP_SIZE - 1));
}
void Get_GAIN(ColorSensor *CS)        //lxx_add_2023.07.27
{
	SensorGetRawData(CS);
	CS->RDC = (float)CS->RDR;
	if(CS->RDC < CS_RDR_MIN)
	{
		// error_set(ERROR_SENSOR_SELF_CHECK);
		return;
	}
	CS->gain = 1000.0/(float)CS->RDC;
}

void Sensor_calibration_data(ColorSensor *CS)        //lxx_add_2023.07.27
{
	CS->RtR = (CS->CDR-CS->RDR)*CS->gain;
}

void sample_first_zero(void)
{
	for (int i = 0; i < CS_MAX; i++)
	{
		Returntozero(&CS[i]);
		//从零点输出
		Sensor_calibration_data(&CS[i]);
	}
}
int check_first_zero(void)
{
	int noAlignNum = 0;
   
	for (int i = 0; i < CS_MAX; i++)
	{
		if(Returntozero(&CS[i]) == 1){			
			noAlignNum ++;
		}
	}
	if(noAlignNum == 0){		
		error_clear();
   		return 0;
	}else{
		error_set(ERROR_SENSOR_SELF_CHECK);
		return 1;
	}
}

void sample_calibrate_calc(uint32_t times)
{
	for (int i = 0; i < CS_MAX; i++)
	{
		SensorGetRawData(&CS[i]); // get the original data every 1S
		if(CS->RDR == 0){
			// if(!(g_cfg.skip_CheckOrRun & SKIP_CHECK_CARDINSERT)){				
			// 	error_set(ERROR_SENSOR_SELF_CHECK);
			// 	return;
			// }
		}
		Sensor_calibration_data(&CS[i]);
	}

	if (times < 19)
	{
		for (int i = 0; i < CS_MAX; i++)
		{
			Get_SAMP_DATA(&CS[i]);// save the returntozero data in 30minutes
		}
		// samp_num++;
	}
}

void sample_calc_avg_std(void)
{
	for (int i = 0; i < CS_MAX; i++)
	{
		Get_average(&CS[i]);
		Get_STD(&CS[i]);
	}
}

void sample_calc_tt(void)
{
	for (int i = 0; i < CS_MAX; i++)
	{
		Get_Tt(&CS[i]);
	}
}

void sample_calc_result(void)
{
	// for (int i = 0; i < CS_MAX; i++)
	// {	
	// 	//从二维码获取Tt范围	
	// 	CS[i].TtMax = card_param_info.hole_info[i].TtMax[0] + card_param_info.hole_info[i].TtMax[1] / 100.0f;
	// 	CS[i].TtMin = card_param_info.hole_info[i].TtMin[0] + card_param_info.hole_info[i].TtMin[1] / 100.0f;
	// }

	// SystemResaultJudge();
}
