/*********************************************************************
 * INCLUDES
 */
#include "ble_comm.h"
#include "ble_gap.h"
#include "nrf_gpio.h"
#include "bsp_time.h"
#include "app_flash.h"
#include "hal_ble_uart0.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "hal_led.h"
#include "app_charge.h"
#include "app_pair.h"
#include "hal_mt.h"

/*********************************************************************
* LOCAL DEFINETION
*/

/*********************************************************************
* LOCAL VARIABLES
*/
static ble_gap_addr_t mAddr;
static uint16_t isConfigcnt = 0;
static uint8_t PairFlagHost =0;

/*********************************************************************
* LOCAL FUNCTIONS
*/

static pair_reslt_t  Pair_result_t_head ={
	.next =NULL,
};

void app_UartPair_Regist(pair_reslt_t *cb){
	pair_reslt_t *target = &Pair_result_t_head;
	while(NULL != target->next){
		if(target->next == cb)return;//检查是否已经存在
		target = target->next;
	}
	cb->next = NULL;
	target->next = cb; 
}

void app_UartPair_Clear(pair_reslt_t *cb){
	pair_reslt_t *target = &Pair_result_t_head;
	while(NULL != target->next){
		if(cb == target->next){
			target->next = cb->next;
			return;
		}
		target = target->next;
	}
}

static void app_UartPair_Result_Add(void){
	 pair_reslt_t *target = &Pair_result_t_head;
	 while(NULL != target->next){
			target->next->flag =1;
			target = target->next;
	 }
}


void UART0_Config_Send(uint8_t cmd)
{
	uint8_t buf[32];
	uint8_t L = 0;
	//MAC 地址
	for(int i=0;i<6;i++){
		buf[L++] = mAddr.addr[5-i];
	}
	//硬件版本
	buf[L++] = (uint8_t)(HARDWARE_VERSION>>24);
	buf[L++] = (uint8_t)(HARDWARE_VERSION>>16);
	buf[L++] = (uint8_t)(HARDWARE_VERSION>>8);
	buf[L++] = (uint8_t)(HARDWARE_VERSION>>0);
	//软件版本
	buf[L++] = (uint8_t)(SOFTWARE_VERSION>>8);
	buf[L++] = (uint8_t)(SOFTWARE_VERSION>>0);
	
	UART0_Tx_Send(0,cmd,buf,L);
}

#define PAIR_TIMES								50					//配对次数
static void app_pair_Process(void)
{
	static uint8_t flag = 0;
	if(app_charge_Getstate()!=BLE_CHARGE_PULLOUT){
		if(flag != 1){flag = 1;
			if(mFlash.isHost)UART0_Initialize(PIN_TXD_BLE,PIN_RXD_BLE,UART_HZ);
			else UART0_Initialize(UART0_INVALID_PIN,PIN_RXD_BLE,UART_HZ);
			
		}
		else if(isConfigcnt<PAIR_TIMES){ isConfigcnt++;
			if(mFlash.isHost){ //充电模式下主机主机申请配对
				UART0_Initialize(PIN_TXD_BLE,PIN_RXD_BLE,UART_HZ);
				UART0_Config_Send(UART0_T_CONFIG_ASK);
				UART0_Initialize(UART0_INVALID_PIN,PIN_RXD_BLE,UART_HZ);
			}
		}
	}else{
		if(flag != 2){flag = 2;
			UART0_unInit(PIN_TXD_BLE,PIN_RXD_BLE);
		}
		else if(isConfigcnt>0) isConfigcnt = 0;
	}
	
	static uint8_t Pair_state =0;
	static uint32_t tim =0;
	char buf[16];
	switch(Pair_state){
				case 0:
					    if(PairFlagHost){PairFlagHost =0;
								 MT_Run(500);
								
								 //配对时候清空所有的步数
								 if(Flash_DeleteAllStep() != ZONE_OP_SUCCESS){Except_TxError(EXCEPT_DATEStep,"clear step fail");break;}
								 memset(&mFlash.mStep,0,sizeof(FlashStep_t));
								 mFlash.mClient.isConfig = 'C';
								 if(Flash_SaveStep() != ZONE_OP_SUCCESS){
									 Except_TxError(EXCEPT_DATEStep,"save step fail");
									 DEBUG_LOG("EXCEPT_DATEStep save step fail\r\n");
								 }
								 
								 DEBUG_LOG("mFlash.mClient.macAddr:%02X %02X %02X %02X %02X %02X\n",mFlash.mClient.macAddr[0],mFlash.mClient.macAddr[1],mFlash.mClient.macAddr[2],
								 mFlash.mClient.macAddr[3],mFlash.mClient.macAddr[4],mFlash.mClient.macAddr[5]);
								 
								 Pair_state =1;
								 tim = TIME_GetTicks();
							}
							break;
				case 1:
					    if(TIME_GetTicks()-tim>=10000){tim = TIME_GetTicks();//10秒超时退出
								 Pair_state =0;
								 DEBUG_LOG("Pair_state =0 \r\n");
							}
							if(mFlash.isHost){//主机处理
									if(host_isconnect()){
										 host_disconnect();
									}else{
										 DEBUG_LOG(">>>>>ST_scan_start =0 \r\n");
										 memset(buf,0,sizeof(buf));
										 sprintf(buf,"%02X%02X%02X%02X%02X%02X",mFlash.macHost[0],mFlash.macHost[1],mFlash.macHost[2],mFlash.mClient.macAddr[3],mFlash.mClient.macAddr[4],mFlash.mClient.macAddr[5]);
										 DEBUG_LOG("scanName(%d):%s\n",strlen(buf),buf);
										 host_set_scan_name(buf,strlen(buf));
										 ST_scan_stop();
										 ST_scan_start();
										 Pair_state = 0;
									}
							}else{//从机处理
								 if(slave_isconnect()) slave_disconnect();
								 else {
										 memset(buf,0,sizeof(buf));
										 sprintf(buf,"%02X%02X%02X%02X%02X%02X",mFlash.macHost[0],mFlash.macHost[1],mFlash.macHost[2],mFlash.mClient.macAddr[3],mFlash.mClient.macAddr[4],mFlash.mClient.macAddr[5]);
										 DEBUG_LOG("advName(%d):%s\n",strlen(buf),buf);
										 slave_set_adv_name(buf,strlen(buf));
										 advertising_stop();
										 slave_adv_init();
										 DEBUG_LOG(">>>>>>>>advertising_start =0 \r\n");
										 advertising_start();
										 Pair_state = 0;
								 }
							}
							break;
			default:Pair_state = 0;break; 			
	}
}

#if BLUE_LED_TEST_ENANBLE
void app_config_LED(void)
{
	static uint8_t state = 0;
	switch(state){
		case 0:
			Process_SetHoldOn(app_config_LED,1);
			LED_Start(LED_CONFIG,COLOR_BLUE);
			state = 1;
			Process_UpdatePeroid(app_config_LED,2000);
			break;
		case 1:
			Process_UpdatePeroid(app_config_LED,0);
			LED_Stop(LED_CONFIG);
			state = 0;
			Process_SetHoldOn(app_config_LED,0);
			Process_Stop(app_config_LED);
			break;
		default:state=0;Process_UpdatePeroid(app_config_LED,0);break;
	}
}
#endif

void cb_UART0_R_CONFIG_ASK(void* handle)
{	//从机接收到配对申请
	UART0_Rx_t* target = handle;
	uint8_t mac[6];
	uint8_t ret = 0;
  uint8_t i =0;
	if(app_charge_Getstate()==BLE_CHARGE_PULLOUT) return; //非充电模式不匹配
	if(mFlash.isHost)return; //防止主机自发自收
	
	for(i=0;i<6;i++) mac[i] = target->pDat[i];
	
  uint32_t hv = ((uint32_t)target->pDat[6]<<24)| ((uint32_t)target->pDat[7]<<16) | ((uint32_t)target->pDat[8]<<8) | ((uint32_t)target->pDat[9]<<0);
	uint16_t  sv = ((uint16_t)target->pDat[10]<<8) | ((uint16_t)target->pDat[11]<<0);
	
	UART0_Initialize(PIN_TXD_BLE,UART0_INVALID_PIN,UART_HZ);
	for(i=0; i < 10; i++){
	  UART0_Config_Send(UART0_T_CONFIG_ACK);//应答主机申请
	}
	UART0_Initialize(UART0_INVALID_PIN,PIN_RXD_BLE,UART_HZ);
	
	for(i=0;i<6;i++){
		if(mFlash.macHost[i] != mac[i]){						        //检验主机发过来的mac地址是否上次的一样
			 ret =1;
			 break;
		}
	}

	if(mFlash.mClient.hardVersion != hv || mFlash.mClient.sotfVersion != sv \
	   || ret !=0
	){
		  DEBUG_LOG("host config:%d %d %d %d\n",hv,sv,ret);
		  DEBUG_LOG("mFlash.mClient:%d %d %d %d\n\n",mFlash.mClient.hardVersion,mFlash.mClient.sotfVersion,mFlash.mClient.isConfig,ret);
		  
		  mFlash.mClient.hardVersion = hv;
	    mFlash.mClient.sotfVersion = sv;

		  for(i=0;i<6;i++){
				 mFlash.mClient.macAddr[i] = mAddr.addr[5-i];	//从机自身mac地址
				 mFlash.macHost[i] = mac[i];						      //主机发过来的mac地址
	    }
			PairFlagHost =1;
	}
	
	app_UartPair_Result_Add();
	#if BLUE_LED_TEST_ENANBLE
	Process_Start(0,"config_LED",app_config_LED);
	#endif
}

void cb_UART0_R_CONFIG_ACK(void* handle)
{	//主机接收到配对应答
	UART0_Rx_t* target = handle;
	uint8_t mac[6];
	uint8_t ret = 0;
	uint8_t i=0;
	if(app_charge_Getstate()==BLE_CHARGE_PULLOUT) return; //非充电模式不匹配
	if(!mFlash.isHost) return; //从机自发自收
	
	for(i=0;i<6;i++) mac[i] = target->pDat[i];
	uint32_t hv = ((uint32_t)target->pDat[6]<<24)| ((uint32_t)target->pDat[7]<<16) | ((uint32_t)target->pDat[8]<<8) | ((uint32_t)target->pDat[9]<<0);
	uint16_t  sv = ((uint16_t)target->pDat[10]<<8) | ((uint16_t)target->pDat[11]<<0);
	
	isConfigcnt = PAIR_TIMES+1;			//已配对,停止配对发送
	
	for(i=0;i<6;i++){
		if(mFlash.mClient.macAddr[i] != mac[i]){						        //检验主机发过来的mac地址是否上次的一样
			 ret =1;
			 break;
		}
	}
	
	if(mFlash.mClient.hardVersion != hv || mFlash.mClient.sotfVersion != sv \
	   || ret !=0
	){
		  DEBUG_LOG("mFlash config:%d %d %d %d\n\n",mFlash.mClient.hardVersion,mFlash.mClient.sotfVersion,mFlash.mClient.isConfig,ret);
		  mFlash.mClient.hardVersion = hv;
	    mFlash.mClient.sotfVersion = sv;
		
		  for(i=0;i<6;i++){
				 mFlash.mClient.macAddr[i] = mac[i]; 	//收到的从机mac地址
		     mFlash.macHost[i] = mAddr.addr[5-i];	//主机本身mac地址
	    }
		  PairFlagHost =1;
			
	}
	
	app_UartPair_Result_Add();
	#if BLUE_LED_TEST_ENANBLE
	Process_Start(0,"config_LED",app_config_LED);
	#endif
}

void app_pair_Init(void)
{
	uint32_t err_code = sd_ble_gap_addr_get(&mAddr); APP_ERROR_CHECK(err_code);
	Process_Start(100,"app_pair_Process",app_pair_Process);
	UART0_Rx_Regist(UART0_R_CONFIG_ASK,cb_UART0_R_CONFIG_ASK);
	UART0_Rx_Regist(UART0_R_CONFIG_ACK,cb_UART0_R_CONFIG_ACK);
}

 





