

#include "onechip_include_header.h"


char DeviceNum[64] = "mini7 2312230001 v1.1, ";
uint8_t pc_send_wait = 0;     //数据发送等待，0可以立即发送；>0正在发送请等待
uint8_t pc_send_cmd = 0;     //当前发送cmd
static unsigned char seq  =0;

void PackDeviceNum(void){		
	int len = 0;
	memset((uint8_t *)&DeviceNum, 0 ,sizeof(DeviceNum));
#ifdef ONECHIP_MINI_ONE
	my_sprintf(&DeviceNum[len],sizeof(DeviceNum), "Mini7-one,V%d.%d.%d.%d",SOFT_VERSION_1,SOFT_VERSION_2,SOFT_VERSION_3,SOFT_VERSION_4);	
#else 
#ifdef ONECHIP_MINI_PLUS
	my_sprintf(&DeviceNum[len],sizeof(DeviceNum), "Mini7-plus,V%d.%d.%d.%d",SOFT_VERSION_1,SOFT_VERSION_2,SOFT_VERSION_3,SOFT_VERSION_4);	
#else
	my_sprintf(&DeviceNum[len],sizeof(DeviceNum), "Mini7,V%d.%d.%d.%d",SOFT_VERSION_1,SOFT_VERSION_2,SOFT_VERSION_3,SOFT_VERSION_4);		
#endif //ONECHIP_MINI_PLUS
#endif //ONECHIP_MINI_ONE
	strcat(DeviceNum, ",");
	len = strlen(DeviceNum);
	// hex_to_ascii(get_uid(), &DeviceNum[len], 12);	//uid
	// strcat(DeviceNum, ",");
	strcat(DeviceNum, (const char *)sysinf.SN);
	strcat(DeviceNum, " ");
	Van_Device_Printf(VAN_LOG_INFO,"DeviceNum:%s\n", DeviceNum);
}

/********************************************************************
 * int handshake_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：握手命令处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int handshake_action(unsigned char cmd, unsigned char *parg)
{
    
    sysinf.system_OnlineFlag = true;
    return 0;
}

void char_replace(unsigned char *str, int size, unsigned char ch, unsigned char replace)
{
    for(int i = 0; i < size; i++)
    {
        if(str[i] == ch)
            str[i] = replace;
    }
}


/********************************************************************
 * int wifi_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：设置wifi命令处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int wifi_action(unsigned char cmd, unsigned char *parg)
{

    strcpy(sysinf.wifiname, (const char *)parg);
	strcpy(sysinf.password, (const char *)(parg + WIFI_AP_NAME_MAX_LEN));
    // wifi用户名和密码设置
    WIFI_set_ssid();
    return 1;
}
int setState_action(unsigned char cmd, unsigned char *parg)
{
	unsigned char block = *parg++;
	unsigned char nextState = *parg;
    if(SYS_STATE_WORKEND == nextState){
        if(block==0){
                sysinf.psmMaster.state = SW_move_card;
        }else{
            /*下发命令，改变从模块状态*/
            sysinf.psmSlave.state = SW_move_card;
        }
    }
    return 1;
}



/********************************************************************
 * int wifi_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：设置wifi命令处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int SN_action(unsigned char cmd, unsigned char *parg)
{
    
	parg[15] = 0;
	strcpy((char *)sysinf.SN, (const char *)parg);	
	// PackDeviceNum();
	return cfg_save_cfg_param();
}


/********************************************************************
 * int dev_check_start_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：设备检测开始上报命令处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
// int check_start_action(unsigned char cmd, unsigned char *parg)
//{
//
//	return 0;
// }

/********************************************************************
 * int check_result_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：设备检测结果上报命令处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
// int check_result_action(unsigned char cmd, unsigned char *parg)
//{
//
//	return 0;
// }

/********************************************************************
 * int seq_selftest_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：设备自检处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int seq_selftest_action(unsigned char cmd, unsigned char *parg)
{
    return 0;
}

/********************************************************************
 * int confirm_result_action(unsigned char cmd, unsigned char *parg)
 *
 *描述：设备收到pc的结果响应
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int confirm_result_action(unsigned char cmd, unsigned char *parg)
{
    if(0 == memcmp(parg,sysinf.psmMaster.card_param_info.pid, 10 )){
         sysinf.psmMaster.state  = SW_move_card;
    }else if (0 == memcmp(parg,sysinf.psmSlave.card_param_info.pid, 10 ))
    {
         sysinf.psmSlave.state  = SW_move_card;
    }
    return 0;
}


/********************************************************************
 * int default_pc_response(struct CmdMessage *pMsg, unsigned char result)
 *
 *描述：默认回应PC
 *参数：无
 *返回：成功->0 失败->-1
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int default_pc_response(CmdMessage *pMsg, unsigned char result)
{
   	return data_send_to_pc((pc_cmd_type)pMsg->cmd, (char *)&result, 1);
}

/********************************************************************
 * int handshake_response(struct CmdMessage *pMsg, unsigned char result)
 *
 *描述：握手回应
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int handshake_response(CmdMessage *pMsg, unsigned char result)
{
	int len = 0;
	PackDeviceNum();
	len = strlen(DeviceNum);
	return data_send_to_pc((pc_cmd_type)pMsg->cmd, (char*)DeviceNum, len);
}

	
int AskState_response(CmdMessage *pMsg, unsigned char result)
{
   	data_send_to_pc(PC_CMD_ASKSTATE, (char *)sysinf.SN, sizeof(stateinfDef));  
    return 0;  
}

int set_response(CmdMessage *pMsg, unsigned char result)
{
//    char wifi_result = 1;
//    data_send_to_pc(PC_CMD_SETWIFI, &wifi_result, 1);
    return 0;
}

int setState_response(CmdMessage *pMsg, unsigned char result)
{
//    char result = 1;
    data_send_to_pc(PC_CMD_SETSTATE, (char *)&result, 1);
    return 0;
}


int ans_response(CmdMessage *pMsg, unsigned char result)
{	
	/*清空需要上位机应答的消息*/
	switch(pMsg->cmd){
		case PC_CMD_REPORT_REEOR:
			sysinf.updateError = 0;
			break;
		case PC_CMD_UPDATESTATE:
			sysinf.updateSt = 0;
			break;
		case PC_CMD_QRCODE:
			sysinf.updateQR = 0;                
			break;
		case PC_CMD_DATA_UPLOAD:{
			unsigned char *data = (unsigned char *)pMsg->data;			
			unsigned int recdex = 0xfffffff;
//			unsigned char result = *data;
//			unsigned char part = *(data+1);
			if( pMsg->len == 6){
				recdex = *(data+5);
			    recdex = recdex<<8;
				recdex += *(data+4);
			    recdex = recdex<<8;
				recdex += *(data+3);
			    recdex = recdex<<8;
				recdex += *(data+2);
			}else{
				if(seq == pMsg->seq){
					recdex = 0;
				}
			}
			updateData_next(recdex,data);
	    	
		}
			break;	
		case PC_CMD_REPORT_RESULT:{

//			unsigned char result = *data;
//			unsigned char part = *(data+1);	
			clean_reult_next((unsigned char *)pMsg->data);
//			if(result){		
//				/*消息成功，进行跟新*/		
//				clean_reult_next(part);
//			}
		}
			break;		
	}
    return 0;
}

int confirm_qrcode_action(unsigned char cmd, unsigned char *parg)
{
    //先判断主模块，优先给主模块，扫描上报上报也是相同处理    
    svanner_receive_Rec_IDLE(sysinf.scannerUart);
    if(*parg == 1)
    {
        if((sysinf.psmMaster.state == SW_Scan_Qrcode || sysinf.psmMaster.state == SW_Chip_Id  ))   //主机空闲，给自己
        {
            sysinf.psmMaster.controlword = Scan_Qrcode_cmd;            
		    Van_Device_Printf(VAN_LOG_INFO,"Master rec start\n\r:");
    	    return 0;
        }else {   
#ifdef ONECHIP_MINI_PLUSE         
            if((sysinf.psmSlave.state == SW_Scan_Qrcode || sysinf.psmSlave.state == SW_Chip_Id  )){
                sysinf.psmSlave.controlword = Scan_Qrcode_cmd;                
                Van_Device_Printf(VAN_LOG_INFO,"Slave rec start\n\r:");
                return 0;
            }
#endif
        }
        Van_Device_Printf(VAN_LOG_INFO, "master:%d slave:%d Not in startState\n\r:",sysinf.psmMaster.state,sysinf.psmSlave.state );
        return -1;
    }
	Van_Device_Printf(VAN_LOG_INFO, "rec no macth\n\r:");
    return -1;
}


int confirm_error_action(unsigned char cmd, unsigned char *parg)
{
    return 0;
}


int confirm_data_action(unsigned char cmd, unsigned char *parg)
{
    return 0;
}

/********************************************************************
 * int set_IP_action(uint8_t cmd, uint8_t *parg)
 *
 *描述：设置IP
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int set_IP_action(uint8_t cmd, uint8_t *parg)
{
	if(sysinf.connectTcpFlag == 0){
		/*TCP 链接状态下，不跟新IP地址*/
		memset(sysinf.TCP_IP_Addr,0,sizeof(sysinf.TCP_IP_Addr));
		memset(sysinf.TCP_IP_PORT,0,sizeof(sysinf.TCP_IP_PORT));
		unsigned int data_len = strlen((const char *)parg);
		unsigned int i=0;
		if(parg[i]<'0' || parg[i]>'9'){
			 return 0;
		}
		for(;i<data_len;i++){
			 if(parg[i] != ':'){
				 sysinf.TCP_IP_Addr[i] = parg[i];
			 }else{
				 break;
			 }
		}
		i++;
		unsigned int j =0;
		if(parg[i]<'0' || parg[i]>'9'){
			 return 0;
		}
		for(;i<data_len;i++){
			 if(parg[i] != ':'){
				 sysinf.TCP_IP_PORT[j++] = parg[i];
			 }else{
				 break;
			 }
		}
		if(sysinf.TCP_IP_Addr[0]){		
			sysinf.connectTcpFlag = 1; 
		}
		
		WIFI_set_CloseConnect();
	}


	return 0;

}
int send_temp_parm(uint8_t cmd, uint8_t *parg)
{
	/*设置温度*/
	return 1;
		
	
}
int setTemp_response(CmdMessage *pMsg, uint8_t result)
{
//    char result = 1;
    data_send_to_pc(PC_CMD_SETRUNTEMP, (char *)&result, 1);
    return 0;
}
const struct PCActionPack mPCActionPack[] =
    {
        {
            .cmd = PC_CMD_HANDSHAKE,
            .action = handshake_action,
            .response = handshake_response,
            .datalen = 0,
        },
        {
            .cmd = PC_CMD_SETWIFI,
            .action = wifi_action,
            .response = set_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_SETSN,
            .action = SN_action,
            .response = handshake_response,
            .datalen = 7,
        },
        {
            .cmd = PC_CMD_QRCODE,
            .action = confirm_qrcode_action,
            .response = ans_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_SNANDCARD,
            .action = confirm_error_action,
            .datalen = 1,
        },
        {
            .cmd = PC_CMD_REPORT_RESULT,
            .action = confirm_result_action,
            .response = ans_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_REPORT_REEOR,
            .action = confirm_error_action,
            .response = ans_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_DATA_UPLOAD,
            .action = confirm_data_action,
            .response = ans_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_SETIP,
            .action = set_IP_action,
            .response = NULL,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_UPDATESTATE,
            .action = confirm_data_action,
            .response = ans_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_ASKSTATE,
            .action = confirm_data_action,
            .response = AskState_response,
            .datalen = 0xff,
        },
        {
            .cmd = PC_CMD_SETSTATE,
            .action = setState_action,
            .response = setState_response,
            .datalen = 0xff,
        },

        {
            .cmd = PC_CMD_SETRUNTEMP,
            .action = send_temp_parm,
            .response = setTemp_response,
            .datalen = 0xff,
        },

};

void pc_resend_del(uint8_t seq){
	// struct CmdMessage *pMessage = (struct CmdMessage *)wifi_tx_buf;
	// if(pMessage->seq == seq){
	// 	wifi_tx_len = 0;
	// 	memset(wifi_tx_buf, 0, sizeof(wifi_tx_buf));
	// }
}

/********************************************************************
 * void query_pc_cmd(struct CmdMessage *pMsg)
 *
 *描述：处理PC命令
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
void query_pc_cmd(CmdMessage *pMsg)
{
    for (unsigned char i = 0; i < sizeof(mPCActionPack)/sizeof(mPCActionPack[0]); i++)
    {
        if (mPCActionPack[i].cmd == pMsg->cmd && (mPCActionPack[i].datalen == pMsg->len || mPCActionPack[i].datalen == 0xff)) //防止接收到其他设备的数据帧
        {
            if(pc_send_cmd == mPCActionPack[i].cmd)
                pc_send_wait = 0;
            if(mPCActionPack[i].cmd != 1)
            {
            	pc_resend_del(pMsg->seq);
                Van_Device_Printf(VAN_LOG_INFO,"\n<-- pc cmd %x %d \n", pMsg->cmd, pMsg->seq);
            }
			pMsg->data[pMsg->len] = 0;
            unsigned char ret = mPCActionPack[i].action(mPCActionPack[i].cmd, (unsigned char *)pMsg->data);
            if (mPCActionPack[i].response)
            {
                mPCActionPack[i].response(pMsg, ret);
            }
			if(!(sysinf.pc_channel_recv == 1 && !sysinf.connectTcpFlag)){				
    			sysinf.pc_link_timeout = 0;    //确保TCP通信上在变灯
			}
            break;
        }
    }
}

unsigned int check_to_pc_busy(void){
	return 0;
	
}




/********************************************************************
 *    uint16_t data_send_to_pc(enum pc_cmd_type cmd, char *data, uint16_t len)
 *
 *描述：发生数据到PC
 *参数：Devicenum 0-发至主机，1发至从机
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
unsigned short data_send_to_pc(pc_cmd_type cmd, char *data, unsigned short len)
{
   return 0;
}


/********************************************************************
 * int handshake_action(uint8_t cmd, uint8_t *parg)
 *
 *描述：握手命令处理
 *参数：无
 *返回：无
 *其他：无
 *--------------------------------------------------------------------
 *记录：
 ********************************************************************/
int con_heat_action(uint8_t cmd, uint8_t *parg )
{
//    CmdMessage *pMsg = (CmdMessageDef *)parg;
    CmdMessage *pMsg = (CmdMessage *)parg;;
    miniConfigPram *pram = (miniConfigPram *)pMsg->data;
    switch(pMsg->cmd){
        case UINON_CMD_THEROM_GET:{		
            char data[28];
            *(float *)(data+0) = 0;
            *(float *)(data+4) = sysinf.lysis_offset;	
            *(float *)(data+8) = sysinf.lysis_overHeat;	
            *(float *)(data+12) = sysinf.lysis_overHeatTime;	
            *(float *)(data+16) = sysinf.lysis_Kp;	
            *(float *)(data+20) = sysinf.lysis_Ki;	
            *(float *)(data+24) = sysinf.lysis_Kd;	
            pMsg->data = data;
            pMsg->len = sizeof(data);
            data_send_to_pc( (pc_cmd_type)pMsg->cmd, pMsg->data,	pMsg->len);
        }break;			
        case UINON_CMD_THEROM_OFFSET:{					
            sysinf.lysis_offset =  *(float *)(pMsg->data+4);	
            
            sysinf.lysis_Kp  = *(float *)(parg+4);
            sysinf.lysis_Ki = *(float *)(parg+8);
            sysinf.lysis_Kd     = *(float *)(parg+12);
            sysinf.lysis_overHeat  = *(float *)(parg+16);
            sysinf.lysis_overHeatTime = *(float *)(parg+20);
            sysinf.lysis_offset  = *(float *)(parg+24);

            data_send_to_pc((pc_cmd_type)pMsg->cmd, pMsg->data,	pMsg->len);
            updatParm_therm();
            cfg_save_cfg_param();
        }break;
        case UINON_CMD_THEROM_GOAL:{					
            float goal =  *(float *)(pMsg->data+4) ;
            Set_therm(goal);
            data_send_to_pc((pc_cmd_type)pMsg->cmd, pMsg->data,	pMsg->len);
        }break;
        // case UINON_CMD_THEROM_CHECK:{
        //         pMsg->data[0] =Therm_Check();
        //     data_send_to_pc((pc_cmd_type)pMsg->cmd, pMsg->data,  pMsg->len);
        // }break;
    }
    return 0;
}
const struct PCActionPack mUnionActionPack[] =
    {
        {
            .cmd = UINON_CMD_TEMP_ADJ,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_TEMP_PID,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_TEMP_ADJ_GET,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_TEMP_PID_GET,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_TEMP_START,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_TEMP_STOP,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_THEROM_GOAL,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_THEROM_OFFSET,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_THEROM_GET,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_THEROM_PID,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_THEROM_OVERHEAT,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_THEROM_OVERCOOL,
            .action = con_heat_action,
        },
        {
            .cmd = UINON_CMD_TEMP_DEBUG,
            .response = handshake_response,
        },

};






void deal_mUnion_cmd(CmdMessage *pMsg)
{
	for (uint8_t i = 0; i < sizeof(mUnionActionPack)/sizeof(mUnionActionPack[0]); i++)
	{
		if (mUnionActionPack[i].cmd == pMsg->cmd ) 
		{			
			uint8_t ret = mUnionActionPack[i].action( pMsg->cmd,(uint8_t *)pMsg);
			if (mUnionActionPack[i].response)
			{
				mUnionActionPack[i].response(pMsg, ret);
			}
			break;
		}
	}
}
