#include "usr_config.h"
#include "app_Authen.h"
#include "system.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "bsp_time.h"
#include "ble_comm.h"
#include "bll_imu.h"
#include "app_flash.h"
#include "app_connect_manage.h"
#include "app_detectIsHost.h"

/************************ 函数声明 ***********************************/
static BLE_Host_Tx_t m_Host_BLE_AUTHEN = {
	.n = 10,
	.t = 300,
};


static uint8_t TrenCnt = 0;
static void cb_BLE_Client_BLE_AUTHEN(void* handle){
	BLE_Client_Rx_t* target = (BLE_Client_Rx_t*)handle;
	TrenCnt = 0;
//	SEGGER_RTT_printf(0,"AUTHEN\r\n");
	
	if(target->datLen==1){ //SEGGER_RTT_printf(0,"target->pDat[0]=%d\r\n",target->pDat[0]);
		if(target->pDat[0]==1 ){	//是手机发的
//			SEGGER_RTT_printf(0,"=============LR==========\r\n");
			//固化左右鞋区分函数调用
			if('C' == mFlash.mClient.isConfig != mFlash.LR_FLAG){
					 app_detect_LR_process_stop();
					 mFlash.LR_FLAG = LR_FLAG_VALUE;
					 if(Flash_SaveInfomation() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_FLASH,"pwr save information fail");
					 mBackup.isHost= mFlash.isHost;
					 mBackup.LR_FLAG = mFlash.LR_FLAG;
					 if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_FLASH,"app_detect_LR save backup fail");
			}
		}
	}
	
	if(mFlash.isHost){
		BLE_Host_Tx_Send(&m_Host_BLE_AUTHEN,BLE_AUTHEN,target->pDat,target->datLen);
	}
}

static void app_Authen_Process(void){
	static uint8_t cnt = 0;
	static uint8_t HostAutodat =2;
	
	if(mFlash.isHost){ //
		if(host_isconnect()){
			if(cnt<30){ cnt++;
				BLE_Host_Tx_Send(0,BLE_AUTHEN,&HostAutodat,1);
			}
		}else{
			if(cnt>0) cnt = 0;
		}
	}
	
	if(slave_isconnect()){
//		SEGGER_RTT_printf(0,"1");
		if(TrenCnt>0){ 
			if(++TrenCnt>150){ TrenCnt = 150;
				slave_disconnect();
//				SEGGER_RTT_printf(0,"slave_disconnect %d\r\n");
			}
		}
	}else{
		if(TrenCnt!=1) TrenCnt = 1;
	}
}

void app_Authen_Init(void)
{
	Process_Start(100,"app_Authon",app_Authen_Process);
	BLE_Client_Rx_Regist(BLE_AUTHEN,cb_BLE_Client_BLE_AUTHEN);
}


