


#include "onechip_include_header.h"


#define CardON 1
#define CardOFF 0

uint32_t g_card_tick_s = 0;	//插卡计时S
uint8_t cardonsta = 0;
int samp_time = 0;
int samp_num = 0;
uint8_t datasope_flag = 0;

str_error_info_t error_info = {0};    //错误信息
uint32_t error_delay = 0;    //错误持续时长
test_result_struct result = {0};
heat_ctrl_struct g_heat_ctrl = {0};
CFG_PARAM_STRUCT g_cfg = {0};
ProcessStateMachine_t psm;
int TrigStateCheck(void)
{
	 return (HAL_GPIO_ReadPin(MINI7_V2_BCK_S1_GPIO_Port,MINI7_V2_BCK_S1_Pin)) ? 1 : 0; // 检查PF5引脚值
}


uint8_t is_command(uint16_t controlword, Controlword_t command_to_check)
{
    return (controlword) == command_to_check;
}
void updateData(ProcessStateMachine_t *psm)
{ 

	if(psm->cursendok == 0){
		return;
	}
	if (check_to_pc_busy()){		
		psm->cursendok = 0;
		psm->sendTime = 3;
		if(psm->DataSendHeader != psm->DataSendLast){ 
			if(psm->sendTime >15 ){
				/*1.5s 无应答，或者当前发送完成*/
				uint8_t data[55] = {0};
				memcpy(&data[1], psm->card_param_info.pid, 10);
				memcpy(&data[11],&psm->DataBufRDR[psm->DataSendHeader], 40);
				memcpy(&data[51],&psm->sendconter, 4);
				if(0 == data_send_to_pc(PC_CMD_DATA_UPLOAD, data, sizeof(data))){
					Van_Device_Printf(VAN_LOG_NOTICE, "send Header:%d last:%d  sendconter:0x%x \n",psm->DataSendHeader, psm->DataSendLast,psm->sendconter);
					psm->sendTime = 0;
				}
				
                
			}		
		}else{
			/*无数据，有结果*/
			if(psm->updateresult){
				data_send_to_pc(PC_CMD_REPORT_RESULT, (char *)&result, sizeof(test_result_struct));              				
			}			
		}
	}
}
ProcessStateMachine_t * matchPid(unsigned char * part){
    if( 0 == memcmp(sysinf.psmMaster.card_param_info.pid, part, sizeof(sysinf.psmMaster.card_param_info.pid))){
        return &sysinf.psmMaster;        
    }
    
    if( 0 == memcmp(sysinf.psmSlave.card_param_info.pid, part, sizeof(sysinf.psmSlave.card_param_info.pid))){
        return &sysinf.psmSlave;        
    }
	return 0;
}

void updateData_next(unsigned int recdex,unsigned char * part)
{ 
    ProcessStateMachine_t *psm = matchPid(part);
	if(psm){				
		psm->cursendok = 1;
		if(psm->DataSendHeader != psm->DataSendLast){ 
			psm->sendconter++;		
			Van_Device_Printf(VAN_LOG_NOTICE,"send ok Header:%d sendconter:0x%x \n",psm->DataSendHeader, psm->sendconter);
			/*主模块又消息，更新头，发下一条*/
			psm->DataSendHeader++;
			if(psm->DataSendHeader == MAX_DATA_BUF_SIZE){
				psm->DataSendHeader = 0;
			}
		}
	}
}
void resetSampleData(void){
	if(sysinf.psmMaster.sendTime){
		sysinf.psmMaster.sendTime--;
		if(sysinf.psmMaster.sendTime==0){						
			sysinf.psmMaster.cursendok = 1;
		}
	}else if(sysinf.psmSlave.sendTime){
		sysinf.psmSlave.sendTime--;
		if(sysinf.psmSlave.sendTime==0){						
			sysinf.psmSlave.cursendok = 1;
		}
	}
}

void clean_reult_next(unsigned char * part)
{ 
	ProcessStateMachine_t *psm = matchPid(part);
	if(psm){			
		psm->updateresult = 0;			
		psm->cursendok = 1;
	}
}



/********************************************************************
 *      uint8_t error_set(uint8_t error)
 *
 *描述：设置错误位，并上报主机，灯带显示
 *参数：error： 错误位
 *返回：错误码
 *其他：无
 ********************************************************************/
uint8_t error_set(uint8_t error)
{
       
    if(error_info.error_code == error)
        return error;

    if(error == ERROR_SAMP_MOVE_CARD)   //检测中拔卡，需等待60S才能消除
        error_delay = 60;

    error_info.error_code = error;
    error_info.id = 0;

    Van_Device_Printf(VAN_LOG_ERROR, "error_set: %d %d %d\n", 0, error, psm.state);
    memcpy(error_info.SN, &sysinf.SN, 7);
	error_info.SN[7] = 0;
    error_info.error_report = 1;
    data_send_to_pc(PC_CMD_REPORT_REEOR, (char*)&error_info, sizeof(str_error_info_t));
    
   if(error != ERROR_MOTOR_FIALED){
	   psm.state = SW_Fault;
	//    mcu_ack_ctrl.re_send_card = ACK_TIMEOUT;
	//    Card_State_Send(HEAT_OFF);			  //降温至40°C,不开风扇
   }  

    return 0;
}
/********************************************************************
 *       void error_clear()
 *
 *描述：清除错误
 *参数：error： 错误
 *返回：错误码
 *其他：无
 ********************************************************************/
void error_clear(void)
{
    error_info.error_code = 0;
	error_info.error_report = 0;
}

void usr_state_machine(ProcessStateMachine_t *sts)
{
    sts->statusword = 0x0000;
    static uint8_t state = 0;
    static uint32_t delay = 0;
    //采样前，3秒发一次加热指令

    switch (sts->state)
    {
    // 所有板卡准备自检，包含通道预加热
    case SW_Read_To_Board_Selftest:
    {
        if (is_command(sts->controlword, Board_Selftest_cmd))
        {    
            sts->state = SW_Target_reached;
            sts->statusword |= SW_Target_reached;
            
        }

        break;
    }
    // // 跳过握手准备阶段
    // case SW_Ready_To_Shake_On:
    // {
    //     //从机直接进入等待温度
    //     if (Devicenum)  
    //     {
    //         controlword = Hand_Shake_cmd;
    //     }

    //     //主机需等待PC握手
    //     if (is_command(controlword, Hand_Shake_cmd))
    //     {
    //         *(sts->statusword) |= SW_Target_reached;
    //         sts->state = SW_Target_reached;
    //     }

    //     break;
    // }
    // 故障
    case SW_Fault:
    {
        // 没有预热完成前插卡检测
        // 采样没有完成，拔卡检测
        
        sts->sampleStart = 0;

        if(error_info.error_code < ERROR_SENSOR_SELF_CHECK && error_delay == 0)
        {
            //拔卡消除故障
            if (TrigStateCheck() == CardOFF)
            {
                sts->statusword |= SW_move_card;
                sts->state = SW_move_card;
                error_clear();
				memset(&sts->card_param_info, 0 , sizeof(str_card_param_info_t));
            }
        }
		if(error_info.error_code == ERROR_SENSOR_SELF_CHECK){
			if(check_first_zero() == 0){ 
				sts->statusword |= SW_Chip_Id;
            	sts->state = SW_Chip_Id;
                error_clear();
				}
		}
        break;
    }
    // 快速停止
    case SW_Quick_stop:
    {
        break;
    }
    // 获取温度，两通道加热
    // 等温度稳定后
    case SW_Target_reached:
    {
        if (g_heat_ctrl.temp_stable_sta == 1)
        {
            sts->controlword = Target_reached_cmd;

        	/*************lxx-add-20232.11.30****************/
            if (SensorSelfCheck() == SystemError)
        	{
                error_set(ERROR_SENSOR_SELF_CHECK);
        	}
        }
		if ((g_cfg.skip_CheckOrRun & SKIP_HEATONCHECK_OK))
        {
           /*跳过温度判断*/
            sts->controlword = Target_reached_cmd;
            if (SensorSelfCheck() == SystemError)
        	{
                error_set(ERROR_SENSOR_SELF_CHECK);
        	}
			// Card_State_Send(HEAT_STOP);
        }

        if (is_command(sts->controlword, Target_reached_cmd))
        {
            sts->statusword |= SW_Scan_Qrcode;
            sts->state = SW_Scan_Qrcode;
            sts->heat_timeout = 0;
        }
        break;
    }
    
    // 扫码
    case SW_Scan_Qrcode:
    {
        // if (scan_qrcode_done)
        // {
        //     // calc_balance();
        //     controlword = Scan_Qrcode_cmd;
        // }
        if (is_command(sts->controlword, Scan_Qrcode_cmd))
        {
            sts->statusword |= SW_Chip_Id;
            sts->state = SW_Chip_Id;
        }
		if((g_cfg.skip_CheckOrRun & SKIP_SCANQRCODE)){
	            sts->statusword |= SW_Chip_Id;
	            sts->state = SW_Chip_Id;
		}
        break;
    }
    // 插卡，通道检测
    case SW_Chip_Id:
    {
        if (TrigStateCheck() == CardON)
        {
			// DelayMS(1000);/*插卡后延时1s检测*/
			if(!(g_cfg.skip_CheckOrRun & SKIP_CHECK_CARDINSERT)){
				if(check_first_zero() == 1)break;
			}
			{				
	            sts->controlword = Qrcode_publish_cmd;
	            // mcu_ack_ctrl.re_send_card = ACK_TIMEOUT;
	            // Card_State_Send(HEAT_ON);
	            g_heat_ctrl.temp_stable_sta=0;
	            g_card_tick_s = 0;
				if (is_command(sts->controlword, Qrcode_publish_cmd))
				{
					sts->statusword |= SW_Sample_timeout;
					sts->state = SW_Sample_timeout;
				}
				};
        }
        break;
    }
    // 采样，30min定时
    case SW_Sample_timeout:
    {
    	if(((g_heat_ctrl.temp_stable_sta==2)||(g_cfg.skip_CheckOrRun & SKIP_HEATONCHECK_OK))&& sts->sampleStart == 0)
    	{
			// 启动定时器计时
			sts->sampleTimes = 0;
			sts->sampleStart = 1;
    	}
     	if(sysinf.samp_flag == 1 && sts->sampleStart)
    	{
			sysinf.samp_flag = 0;
		
			if (sts->sampleTimes == 0)
			{
				sample_first_zero();    //计算校零值	
				// sts->samp_num = 0;
				sts->cursendok = 1;
			}
			else
			{
				sample_calibrate_calc(sts->sampleTimes);     //采样，前18组计算均值
                //输出原始数据
                // DatascopeSend(CS[0].RDR,CS[1].RDR,CS[2].RDR,CS[3].RDR,CS[4].RDR,CS[5].RDR,CS[6].RDR,CS[7].RDR,CS[8].RDR,CS[9].RDR, g_card_tick_s/60.0f);
			}


            //上报采样数据
//            sample_send_rt_data();
			if(((sts->DataSendLast+ 1)%MAX_DATA_BUF_SIZE) != sts->DataSendHeader){
				for (int i = 0; i < CS_MAX; i++)
				{
					memcpy(&sts->DataBufRDR[sts->DataSendLast][i], &CS[i].RtR, 4);
				}
				sts->DataSendLast++;
				if(sts->DataSendLast == MAX_DATA_BUF_SIZE){
					sts->DataSendLast = 0;
				}
			}

			if (sts->sampleTimes == 19)
			{
				// sample_calc_avg_std();      //计算均值标准差
			}
			if (sts->sampleTimes > 19)
			{
				// sample_calc_tt();      //计算Tt
			}
//			if ((!(g_cfg.skip_CheckOrRun & SKIP_HEATONCHECK_OK) || g_cfg.skip_CheckOrRun & SKIP_FARSTRUN)){		
//			}		
			if (!(g_cfg.skip_CheckOrRun & SKIP_FARSTRUN)){
				sts->sampleTimes++;
			}
			
			Van_Device_Printf(VAN_LOG_INFO,"SendLast:%d Times:%d \n",sts->DataSendLast,sts->sampleTimes);
			if (sts->sampleTimes >= sampleTotalTimes)
			{
//				sampleTimes = 0;
				if(0==(g_cfg.skip_CheckOrRun & SKIP_FARSTRUN)){
					sts->sampleStart = 0;
					sts->controlword = result_report_cmd;
				}

			}

			
    	}
        if (is_command(sts->controlword, result_report_cmd))
        {
            sts->statusword |= SW_result_report;
            sts->state = SW_result_report;
            // sample_calc_result();
            delay = 0;
            // datasope_flag = 0;
            
            // mcu_ack_ctrl.re_send_card = ACK_TIMEOUT;
        	// Card_State_Send(HEAT_OFF);              //降温至40°C,不开风扇
        	sts->updateresult = 1;
			
        }

        break;
    }
    // 计算，阈值范围，所有孔的结果（阴阳性、无效）
    // 结果上传&数据上传
    case SW_result_report:
    {
        if(0 == datasope_flag)
        {
            datasope_flag = 1;
            // DatascopeSend(CS[0].Tt,CS[1].Tt,CS[2].Tt,CS[3].Tt,CS[4].Tt,CS[5].Tt,CS[6].Tt,CS[7].Tt,CS[8].Tt,CS[9].Tt, 101);                                                     //Tt值
            // DatascopeSend(CS[0].average,CS[1].average,CS[2].average,CS[3].average,CS[4].average,CS[5].average,CS[6].average,CS[7].average,CS[8].average,CS[9].average, 102);   //均值
            // DatascopeSend(CS[0].STD,CS[1].STD,CS[2].STD,CS[3].STD,CS[4].STD,CS[5].STD,CS[6].STD,CS[7].STD,CS[8].STD,CS[9].STD, 103);                                           //方差
            // DatascopeSend(CS[0].CDR, CS[1].CDR, CS[2].CDR, CS[3].CDR, CS[4].CDR, CS[5].CDR, CS[6].CDR, CS[7].CDR, CS[8].CDR, CS[9].CDR, 104);                                  //校零值
            // DatascopeSend(CS[0].Result,CS[1].Result,CS[2].Result,CS[3].Result,CS[4].Result,CS[5].Result,CS[6].Result,CS[7].Result,CS[8].Result,CS[9].Result, 105);             //结果
            // DatascopeSend(CS[0].gain, CS[1].gain, CS[2].gain, CS[3].gain, CS[4].gain, CS[5].gain, CS[6].gain, CS[7].gain, CS[8].gain, CS[9].gain, 106);                        //gain值
            // DatascopeSend(CS[0].RDC, CS[1].RDC, CS[2].RDC, CS[3].RDC, CS[4].RDC, CS[5].RDC, CS[6].RDC, CS[7].RDC, CS[8].RDC, CS[9].RDC, 107);                                  //gain基值
            // DatascopeSend(CS[0].TtMax, CS[1].TtMax, CS[2].TtMax, CS[3].TtMax, CS[4].TtMax, CS[5].TtMax, CS[6].TtMax, CS[7].TtMax, CS[8].TtMax, CS[9].TtMax, 108);              //TtMax
            // DatascopeSend(CS[0].TtMin, CS[1].TtMin, CS[2].TtMin, CS[3].TtMin, CS[4].TtMin, CS[5].TtMin, CS[6].TtMin, CS[7].TtMin, CS[8].TtMin, CS[9].TtMin, 109);              //TtMin
        }

//        if(g_sys_tick > delay)
//        {
//            if (Devicenum == 0)
//            {
//                data_send_to_pc(PC_CMD_REPORT_RESULT, (char *)&result, sizeof(test_result_struct));
//            }
//            else
//            {
//                b2b_send_device(B2B_CMD_REQ_RESULT, (char *)&result, sizeof(test_result_struct),0);
//            }
//            delay = g_sys_tick + 10;
//        }

        if (is_command(sts->controlword, result_move_card))
        {
            sts->statusword |= SW_move_card;
            sts->state = SW_move_card;
        }
        break;
    }

    case SW_move_card:
    {
        //等待拔卡进入下一次循环
        if (TrigStateCheck() != CardON)
        {
            //跳转到等待扫码状态
            sts->statusword = SW_Target_reached;
            sts->state = SW_Target_reached;            
		
			sts->sampleTimes = 0;
			sts->sampleStart = 0;
            g_heat_ctrl.temp_stable_sta = 0;
            datasope_flag = 0;
            sts->heat_timeout = 0;
            memset(&sts->card_param_info, 0 ,sizeof(sts->card_param_info));
        	// Card_State_Send(HEAT_OFF);              //降温至40°C,不开风扇
            sts->controlword = Board_Selftest_cmd;
        }
        break;
    }
    default:
        break;
    }
    switch (sts->state)
    {
    case SW_Read_To_Board_Selftest:
        sts->flags.selftest_allowed = 1;
        sts->flags.scan_qrcode_allowed = 0;
        sts->flags.pre_heat_enabled = 0;
        sts->flags.target_reached = 0;
        sts->flags.check_chipid_enabled = 0;
        sts->flags.qrcode_info_applied = 0;
        break;

    default:
        break;
    }

    if(state != sts->state)
    {
        state = sts->state;
        Van_Device_Printf(VAN_LOG_NOTICE,"\nstate:%d \n", state);
    }
}
