/************************************************************************************
 * @Copyright (c)    :(C)2022, Qindao ieslab Co., Ltd
 * @FileName   	     :hdsc_nb_driver.c
 * @Author           :QDIES PLATFORM TEAM
 * @Version          :V1.0
 * @Date             :2022-02
 * @Description      : l660
 ************************************************************************************/
#include "sys_config.h"
#ifdef MODULE_BLE_USED
#include "ble14531_driver.h"
#include "ble14531_uart_driver.h"
#include "UWater_uart_driver.h"
#include "stdio.h"
#include <time.h>
#include "sys_processor.h"
#include "UWater_timer1uS_driver.h"
//#include "sys_processor.h"
#include "UWater_gpio_driver.h"
//#include "triple_pulse_driver.h"
//#include "adc_driver.h"
#include "UWater_DebugPrint.h"
#include "SOE.h"
#include "UWater_clktrim_driver.h"

#ifdef	__cplusplus
extern "C"
{
#endif

/********************************常量定义************************************/
//AT指令集
const BLE_STRUCT_AT_CMD AtCmdBuf[]={
/*****初始化指令********************/
	{AT_CODE_AT, BLE_cst_AT_AT, BLE_RETRY_2,"AT?", BLE_WT_1S},									//AT
	{AT_CODE_VER_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+VER?", BLE_WT_1S},						//查询版本
	{AT_CODE_NAME_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+NAME?", BLE_WT_2S},   				//查询广播名称
	{AT_CODE_NAME, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+NAME=JC", BLE_WT_1S},					//设置广播名称
	{AT_CODE_MAC_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+MAC?", BLE_WT_1S},						//查询MAC地址
	{AT_CODE_MAC, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+MAC=", BLE_WT_1S},						//设置MAC地址
	{AT_CODE_TXPOWER_CHK, BLE_cst_AT_QUERY, BLE_RETRY_0, "AT+TX_POWER?", BLE_WT_1S},			//查询发射功率
	{AT_CODE_TXPOWER, BLE_cst_AT_OK_ERROR, BLE_RETRY_0, "AT+TX_POWER=", BLE_WT_1S},				//设置发射功率
	{AT_CODE_ADVPARAM_CHK, BLE_cst_AT_QUERY, BLE_RETRY_0,"AT+ADV_PARAM?", BLE_WT_1S},			//查询广播间隔
	{AT_CODE_ADVPARAM, BLE_cst_AT_OK_ERROR, BLE_RETRY_0,"AT+ADV_PARAM=", BLE_WT_1S},			//设置广播间隔
	{AT_CODE_CONPARAM_CHK, BLE_cst_AT_QUERY, BLE_RETRY_0, "AT+CON_PARAM?", BLE_WT_1S},			//查询连接间隔
	{AT_CODE_CONPARAM, BLE_cst_AT_OK_ERROR, BLE_RETRY_0,"AT+CON_PARAM=", BLE_WT_1S},			//设置连接间隔
	{AT_CODE_ADVMFID, BLE_cst_AT_OK_ERROR, BLE_RETRY_2,"ADV", BLE_WT_1S},						//设置广播数据
	{AT_CODE_ADV1, BLE_cst_AT_OK_ERROR, BLE_RETRY_2, "AT+ADV=1", BLE_WT_1S},					//打开广播
	{AT_CODE_ADV0, BLE_cst_AT_OK_ERROR, BLE_RETRY_2, "AT+ADV=0", BLE_WT_1S},					//关闭广播
	{AT_CODE_DISCON, BLE_cst_AT_OK_ERROR, BLE_RETRY_2, "AT+DISCONNECT", BLE_WT_1S},				//断开连接
	{AT_CODE_SLAVE, BLE_cst_AT_OK_ERROR, BLE_RETRY_2, "AT+PER", BLE_WT_2S},						//设置为从机模式
#if BLE_CENTRAL_SLAVE_MOD
    {AT_CODE_CENTRAL, BLE_cst_AT_OK_ERROR, BLE_RETRY_2, "AT+CENTRAL", BLE_WT_1S},				//设置为主机模式
	{AT_CODE_SCAN, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+SCAN", BLE_WT_2S},						//扫描周围设备
	{AT_CODE_CONNECT, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+CONNECT=", BLE_WT_2S},				//连接指定从机
	{AT_CODE_STOP_SCAN, BLE_cst_AT_OK_ERROR, BLE_RETRY_1,"AT+STOPSCAN", BLE_WT_2S},				//停止扫描
	{AT_CODE_WHITE_LIST_SET, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+WHITEMAC=", BLE_WT_2S},		//设置MAC白名单
	{AT_CODE_WHITE_LIST_CLR, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+CLEARMAC", BLE_WT_2S},		//取消MAC白名单
	{AT_CODE_WHITE_LIST_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+WHITEMAC?", BLE_WT_2S},			//查询MAC白名单
#endif
	{AT_CODE_SCAN_TIMES, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+SCAN_CNT=", BLE_WT_2S},			//设置扫描次数	
	{AT_CODE_KEY_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+CMP_NAME?", BLE_WT_2S},				//查询关键字
	{AT_CODE_KEY_SET, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+CMP_NAME=", BLE_WT_2S},				//修改关键字
	{AT_CODE_KEY_CLR, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+EXIT_CMP_NAME", BLE_WT_2S},			//取消关键字
	{AT_CODE_RESET, BLE_cst_AT_OK_ERROR, BLE_RETRY_0, "AT+RESET", BLE_WT_0S},					//蓝牙复位
	{AT_CODE_SAVE, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+SAVE", BLE_WT_1S},						//蓝牙保存
	{AT_CODE_STATUS, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+STATUS?", BLE_WT_2S},					//蓝牙查询主从模式及连接状态
	{AT_CODE_SEC_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+SEC?", BLE_WT_2S},						//查询蓝牙加密配对
	{AT_CODE_SEC_SET, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+SEC=1", BLE_WT_2S},					//设置蓝牙加密配对
	{AT_CODE_SEC_CLR, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+SEC=3", BLE_WT_2S},					//取消蓝牙加密配对
	{AT_CODE_PIN_CHK, BLE_cst_AT_QUERY, BLE_RETRY_1, "AT+PIN?", BLE_WT_2S},						//查询蓝牙配对密码
	{AT_CODE_PIN, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+PIN=", BLE_WT_2S},						//设置蓝牙配对密码
	{AT_CODE_CLRBNDE, BLE_cst_AT_OK_ERROR, BLE_RETRY_1, "AT+CLRBNDE", BLE_WT_1S},				//加密配对启用时，建立连接前需发送清除命令
};
/********************************变量定义************************************/
BLE_STRUCT_AT_CMD cur_atcmdbuf;				//需要发送的AT指令
const BLE_STRUCT_AT_CMD *p_cur_atcmdbuf;

//状态变量(各个状态机运行的状态变量)
u8 s_BLE_main_state = S_BLE_IDLE;			//主状态机状态
u8 s_BLE_init_state = S_BLE_IDLE;				//上电初始化状态机状态
u8 s_BLE_conmgr_state = S_BLE_IDLE;				//主机连接管理状态
u8 s_BLE_chk_status_state =  S_BLE_IDLE;		//查询蓝牙主从模式及连接状态
u8 s_BLE_sec_status_state = S_BLE_IDLE;			//查询或设置加密配对
#if BLE_CENTRAL_SLAVE_MOD
u8 s_BLE_mode_switch_state = S_BLE_IDLE;		//主从模式切换状态
u8 s_BLE_scan_state = S_BLE_IDLE;				//主机模式扫描状态
u8 s_BLE_white_list_state =  S_BLE_IDLE;		//变更蓝牙MAC白名单
#endif

u8 s_BLE_change_mac_state = S_BLE_IDLE;			//变更蓝牙名称及MAC状态
u8 s_BLE_update_adv_data_state = S_BLE_IDLE;	//变更蓝牙广播数据
u8 s_BLE_change_adv_para_state =  S_BLE_IDLE;	//变更蓝牙广播参数
u8 s_BLE_change_key_word_state =  S_BLE_IDLE;	//变更蓝牙关键字
u8 s_BLE_at_requeset_state = S_BLE_IDLE;		//AT处理子状态机

//const u8 ble_key_word[] = {'J','C','B','T','-'};	//默认关键字
const u8 ble_key_word[] = {'J','C'};				//默认关键字
char ble_default_pin[] = {'3','3','7','8','0','0'};	//默认密码

u8 g_ble_task_flag = BLE_TASK_INIT;			//状态机运行结果
u8 g_ble_at_requestErrorCount;				//AT指令尝试次数变量
u8 ble_power_flag = FALSE;					//模组是否有电


char BLE_AT_BUF[BLE_AT_UP_BUF_SIZE];		//AT指令发送缓冲区
u8 g_ble_at_rcv_len;						//AT指令返回数据长度
u8 *p_ble_at_rcv_data;						//AT指令返回数据的地址
u8 ble_reset_flg;							//蓝牙初始化失败复位次数
BLE_STATE_ERR ble_state_error;
BLE_WORK_STATE ble_work_stat = {0};			//蓝牙运行期间的参数
u8 ble_temp_arr[12];						//临时数组
u8 ble_temp_len = 0;						//临时变量
u8 ble_white_MAC_set[6];					//单次设置蓝牙扫描白名单
mtype16_ ble_temp_data;						//临时变量
u8 ble_con_msg = 0;				//蓝牙断开或连接的消息
//u8 ble_tx_msg = 0;
u8 ble_reset_count=0;
TYP_POWER_STATUS flag_ble_force_power = BlePowerOk; //强制断电标志 
/*****************************内部功能状态机***********************************/
void BleInitMachine(void);
void BleConMgrMachine(void);
u8 CheckMetAddrIfInit(void);
///*****************************内部接口****************************************/

/***************************************************************************
 * @fun_name     void AT_Common_Requeset_Proc()
 * @brief        AT指令集通用查询函数
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other 
 ***************************************************************************/
int getAtCmdIndex(BLE_TYP_AT_CMDCODE atCode)
{
    for(int i = 0; i < AT_CODE_ALL; i++)
	{
	    if(AtCmdBuf[i].AtCode == atCode)
		{
		    return i;
		}
	}
	return 0;
}


/***************************************************************************
* @fun_name		u8 asc16num(char asc16)
* @brief		把字符数据转化为16进数据
* @param[in]	asc16：以字符表示的16进数据
* @param[out]	None
* @retval		转化后的数据
* @other		None
***************************************************************************/
u8 asc16_num(char asc16)
{
	u8 tempbyte=0;
	if(asc16 > 47 && asc16 < 58)
	{
		tempbyte = asc16 - 48;
	}
	else if(asc16 > 64 && asc16 < 71)
	{
		tempbyte = asc16 - 55;
	}
	else if(asc16 > 96 && asc16 < 103)
	{
		tempbyte = asc16 - 87;
	}
	else
	{
		tempbyte = 0;
	}
	return tempbyte;
}

/***************************************************************************
* @fun_name		u8 format_ascii2hex(u8 *dest, u8 *sour, u8 sourlen)
* @brief		把字符串数据转化为16进数据
* @param[in]	*sour：以字符串表示的16进数据，datalen：字符串长度，必须为偶数，不计\0
* @param[out]	*dest：转化后的数据
* @retval		转化后的长度
* @other		None
***************************************************************************/
u8 format_ascii2hex(u8 *dest, u8 *sour, u8 sourlen)
{
	u8 i;
	u8 destlen = sourlen / 2;
	for(i = 0; i < destlen; i++)
	{
		dest[i] = asc16_num(sour[i * 2]) << 4;
		dest[i] += asc16_num(sour[i * 2 + 1]);
	}
	if(sourlen % 2)
	{
		dest[i] = asc16_num(sour[i * 2]) << 4;
		dest[i] &= 0xF0; 
		destlen++;
	}
	return destlen;
}


u8 IntToHexChar(u8 c)
{
	if (c > 9)
		return (c + 0x37);
	else
		return (c + 0x30);
}
/***************************************************************************
* @fun_name		u8 format_Hex2ascii(u8 *dest, u8 *sour, u8 sourlen)
* @brief		把十六进数据转化为字符串数据
* @param[in]	*sour：16进数据，datalen：16进数据长度
* @param[out]	*dest：转化后的数据
* @retval		转化后的长度
* @other		None
***************************************************************************/
void format_Hex2ascii(u8 *dest, u8 *sour, u8 sourlen)
{
	u8 i = 0;
	u8 temp = 0;
	for (i=0; i<sourlen; i++) 
	{
		temp = sour[i]&0xf0;
		dest[2*i] = IntToHexChar(temp >> 4);
		temp = sour[i]&0x0f;
		dest[2*i+1] = IntToHexChar(temp);
	}
}

/***************************************************************************
* @fun_name		u8 format_Dec2ascii(u8 *dest, u16 src)
* @brief		把十进数据转化为字符串数据
* @param[in]	src：16进数据
* @param[out]	*dest：转化后的数据
* @retval		转化后的长度
* @other		None
***************************************************************************/
u8 format_Dec2ascii(u8 *dest, u16 src)
{
	u8 destlen = 0;
	u8 temp_flag = 0;
	u16 temp_i,temp_data,temp_rcv_data;
	
	temp_rcv_data = src;
	if(!temp_rcv_data)		//为0
	{
		dest[destlen++] =0x30;
	}
	else
	{
		for(temp_i = 10000; temp_i > 0; temp_i /= 10)
		{
			temp_data = temp_rcv_data / temp_i;
			if(temp_data || temp_flag)
			{
				dest[destlen++] = temp_data + 0x30;
				temp_rcv_data -= (temp_data * temp_i);
				temp_flag = 1;
			}
		}
	}
	return destlen;
}

//********************  蓝牙处理接口 ******************************//

/***************************************************************************
* @fun_name     void Ble_IOInit(void)
* @brief        模块供电IO、模块复位、电源、PSM唤醒引脚初始化
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
void Ble_IOInit(void)
{
	stc_gpio_cfg_t stcGpioCfg;
	DDL_ZERO_STRUCT(stcGpioCfg);
	
    stcGpioCfg.enDir = GpioDirOut;		///< 端口方向配置
    stcGpioCfg.enDrv = GpioDrvL;		///< 端口驱动能力配置->低驱动能力
    stcGpioCfg.enPu = GpioPuDisable;	///< 端口上下拉配置->无
    stcGpioCfg.enPd = GpioPdDisable;
    stcGpioCfg.enOD = GpioOdDisable;	///< 端口开漏输出配置
    stcGpioCfg.enCtrlMode = GpioAHB;	///< 端口输入/输出值寄存器总线控制模式配置->AHB
	stcGpioCfg.bOutputVal = TRUE;

	Gpio_Init(BLE_POW_PORT, BLE_POW_PIN, &stcGpioCfg);				//供电控制端口
	BlePowerOff();														//不上电
	
	stcGpioCfg.bOutputVal = FALSE;
	Gpio_Init(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN, &stcGpioCfg);	//蓝牙唤醒端口
	Gpio_ClrIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);					//高电平唤醒蓝牙模块
	
	stcGpioCfg.enDir = GpioDirIn;										///< 端口方向配置，输入
	Gpio_Init(BLE_CON_PORT, BLE_CON_PIN, &stcGpioCfg);   			//连接指示端口
	Gpio_EnableIrq(BLE_CON_PORT, BLE_CON_PIN, GpioIrqRising);			//上升沿中断，指示连接接入
	Gpio_EnableIrq(BLE_CON_PORT, BLE_CON_PIN, GpioIrqFalling);			//下降沿中断，指示连接断开
	EnableNvic(BLE_CON_IRQ, BLE_CON_PRIORITY, TRUE);		//
}

/***************************************************************************
* @fun_name     void Ble_IODeInit(void)
* @brief        模块供电IO、模块复位、电源、PSM唤醒引脚初始化
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
void Ble_IODeInit(void)
{
	stc_gpio_cfg_t stcGpioCfg;
    DDL_ZERO_STRUCT(stcGpioCfg);
    stcGpioCfg.enDir = GpioDirOut;		///< 端口方向配置
    stcGpioCfg.enDrv = GpioDrvL;		///< 端口驱动能力配置->低驱动能力
//    stcGpioCfg.enPu = GpioPuDisable;	///< 端口上下拉配置->无
//    stcGpioCfg.enPd = GpioPdDisable;
//    stcGpioCfg.enOD = GpioOdDisable;	///< 端口开漏输出配置
    stcGpioCfg.enCtrlMode = GpioAHB;	///< 端口输入/输出值寄存器总线控制模式配置->AHB

	Gpio_Init(BLE_POW_PORT, BLE_POW_PIN, &stcGpioCfg);				//供电控制端口
	BlePowerOff();						//不上电
	
	Gpio_Init(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN, &stcGpioCfg);	//蓝牙唤醒端口,高电平唤醒蓝牙模块
	
	Gpio_Init(BLE_TX_PORT, BLE_TX_PIN, &stcGpioCfg);			//TX也配置为输出低

	Gpio_Init(BLE_RX_PORT, BLE_RX_PIN, &stcGpioCfg);			//RX也配置为输出低
	
	stcGpioCfg.enDir = GpioDirIn;										///< 端口方向配置，输入
	stcGpioCfg.enPd = GpioPdEnable;
	Gpio_Init(BLE_CON_PORT, BLE_CON_PIN, &stcGpioCfg);   			//连接指示端口
	Gpio_DisableIrq(BLE_CON_PORT, BLE_CON_PIN, GpioIrqRising);			//上升沿中断，指示连接接入
	Gpio_DisableIrq(BLE_CON_PORT, BLE_CON_PIN, GpioIrqFalling);			//下降沿中断，指示连接断开
	EnableNvic(BLE_CON_IRQ, BLE_CON_PRIORITY, FALSE);		//
}
/***************************************************************************
 * @fun_name    void BlePowerOff(void)
 * @brief        蓝牙断电处理
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
void BlePowerOff(void)
{
	Gpio_ClrIO(BLE_POW_PORT, BLE_POW_PIN);				//不供电
	Gpio_ClrIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);	//不唤醒
	ble_work_stat.Ble_power_flag = FALSE;				//记录电源状态
}
/***************************************************************************
 * @fun_name    void BlePowerOn(void) 
 * @brief        蓝牙上电处理
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
void BlePowerOn(void)  
{
	Gpio_SetIO(BLE_POW_PORT, BLE_POW_PIN);				//供电
	ble_work_stat.Ble_power_flag = TRUE;				//记录电源状态
	Gpio_SetIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);	//保持唤醒
}

/***************************************************************************
 * @fun_name    u8 BleIfPowerOn(void)
 * @brief        查询蓝牙是否上电
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
u8 BleIfPowerOn(void)
{    
	return ble_work_stat.Ble_power_flag;    
}


/***************************************************************************
* @fun_name     BLE_TYP_RESULT_CODE AT_Requeset_Proc(const BLE_STRUCT_AT_CMD *atCmd, char* addBuf, int addLen)
* @brief        对不同的AT指令进行处理
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
BLE_TYP_RESULT_CODE AT_Requeset_Proc(const BLE_STRUCT_AT_CMD *atCmd, char* addBuf, int addLen)
{
	switch(s_BLE_at_requeset_state)
	{
		case S_BLE_IDLE:
		{
			g_ble_at_requestErrorCount = 0;
			if(UartSendMachineIfIdle(BLE_UART_COM))
			{
				Set100msTimer(TIMER_100MS_BLE, 5);
				s_BLE_at_requeset_state = BLE_AT_REQUEST_SEND;
			}
		}
		break;
		case BLE_AT_REQUEST_SEND:		//发送AT指令
		{
			if((Check100msTimer(TIMER_100MS_BLE) == 0) && (TASK_IDLE == UartIfIdle(BLE_UART_COM)))
			{
				memset(BLE_AT_BUF, 0, sizeof(BLE_AT_BUF));
				int i = 0;
				int all_len = 0;
				int str_len = strlen(atCmd->pAtCmdStr);
				const char *p;
				p = atCmd->pAtCmdStr;
				for(i = 0; i < str_len; i++)
				{
					BLE_AT_BUF[i] = *p++;
					all_len++;
				}
				if(addLen)
				{
					for(i = 0; i < addLen; i++)
					{
						BLE_AT_BUF[str_len + i] = *addBuf++;
						all_len++;
					}
				}
				BLE_AT_BUF[all_len++] = '\r';
				BLE_AT_BUF[all_len++] = '\n';
				
				BleUartSend((u8*)BLE_AT_BUF, all_len, atCmd->CaseAtNum);//不能用strlen(AT_BUF),否则只能发送到0x00
				Set100msTimer(TIMER_100MS_BLE, atCmd->WaitTime);
				s_BLE_at_requeset_state = BLE_AT_REQUEST_CHECK;
			}
		}
		break;
		case BLE_AT_REQUEST_CHECK:		//接收AT指令的结果
		{
			if (BleCheckAtAck() == BLE_UART_OK)//返回正确的应答
            {
				s_BLE_at_requeset_state = S_BLE_IDLE;
				return ResultOk;
            }
            else if ((Check100msTimer(TIMER_100MS_BLE) == 0) || (BleCheckAtAck() == BLE_UART_ERROR)) //应答超时或者错误
            {
                if (g_ble_at_requestErrorCount >= atCmd->ErrorLimit)
                {
					s_BLE_at_requeset_state = S_BLE_IDLE;
					return ResultFail;
                }
                else
                {
					g_ble_at_requestErrorCount++;
					if(BleCheckAtAck() == BLE_UART_ERROR)
					{
						Set100msTimer(TIMER_100MS_BLE, 2);
					}
					s_BLE_at_requeset_state = BLE_AT_REQUEST_SEND;
                }
            }
		}
		break;
		default:
		{
			s_BLE_at_requeset_state = S_BLE_IDLE;
			return ResultFail;
		}
	}
	return ResultBusy;
}

/***************************************************************************
 * @fun_name     void BleChkLowpowerState(void)
 * @brief        查询LowPower引脚是高或低电平，如果是低电平，认为是从休眠出来后尚未进行串口初始化
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
void BleChkLowpowerState(void)
{
	if(Gpio_ReadOutputIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN))	//lowpower为高电平
	{
		Set5msTimer(TIMER_5MS_LOWPOWER,0);
	}
	else
	{
		Gpio_SetIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);	//保持唤醒
		UartInit(BLE_UART_COM, BAUD38400, DATA_BIT_8, STOPBIT_1, UART_EVEN_PARITY, UART_LPUART_Disable);
		Set5msTimer(TIMER_5MS_LOWPOWER,10);
	}
}

/************************************************************************************************************************************
* 
*									蓝牙初始化
*
************************************************************************************************************************************/
/***************************************************************************
 * @fun_name     void BleInit(void)
 * @brief        BLE初始化
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
void BleInit(void)
{
	Ble_IOInit();
	ble_work_stat.Ble_scan_state = SCAN_END;
	ble_work_stat.Ble_cur_mode = SLAVE_MODE;
	ble_work_stat.Ble_con_state = CON_END;
	ble_work_stat.Ble_power_flag = FALSE;
}


/***************************************************************************
 * @fun_name     void BleInitMachine(void)
 * @brief        BLE初始化状态机
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
/*模组端串口调试配置*/
void NB_UartInitForGPIO(void)//debug
{
    stc_gpio_cfg_t stcGpioCfg;

	DDL_ZERO_STRUCT(stcGpioCfg);
    //PA0,PA1:配置为数字输入
    stcGpioCfg.enDir = GpioDirIn;    ///< 端口方向配置->输入
    stcGpioCfg.enDrv = GpioDrvL;     ///< 端口驱动能力配置->低驱动能力
    stcGpioCfg.enPu = GpioPuDisable; ///< 端口上下拉配置->无
    stcGpioCfg.enPd = GpioPdDisable;
    stcGpioCfg.enOD = GpioOdDisable; ///< 端口开漏输出配置->开漏输出关闭
    stcGpioCfg.enCtrlMode = GpioAHB; ///< 端口输入/输出值寄存器总线控制模式配置->AHB
    Gpio_Init(GpioPortA, GpioPin0, &stcGpioCfg);	
    Gpio_Init(GpioPortA, GpioPin1, &stcGpioCfg);
}


void BleInitMachine(void) 
{
	static u8 init_cnt,init_i;
	static u8 init_flag = FALSE;
	switch (s_BLE_init_state)			//NB模块供电
    {
		case S_BLE_IDLE:
		{
			break;
		}
		case S_BLEINIT_POWER_ON:
		{
			if(ClkTrimIfIdle()==TASK_IDLE)
			{
				if(ble_reset_count<Sys_data_object.P1.func_cfg_bytes[23])
				{
					ble_reset_count++;
					flag_ble_force_power=BlePowerOk;//清强制断电标志
					BleInit();
					UartInit(BLE_UART_COM, BAUD38400, DATA_BIT_8, STOPBIT_1, UART_EVEN_PARITY, UART_LPUART_Disable);			
					BlePowerOn();	//模块供电
					ble_reset_flg = 0;
					Set100msTimer(TIMER_100MS_BLE, 30);	//打开电源，延时3S,等待上电稳定
					s_BLE_init_state = S_BLEINIT_POWER_WAIT; 
					//NB_UartInitForGPIO();////////////debug
				}
				else
				{
					g_ble_task_flag = BLE_TASK_FAIL;//返回失败后,会强制断电
					s_BLE_init_state = S_BLE_IDLE;
				}
			}
		}
		break;

		case S_BLEINIT_POWER_WAIT:
		{
			if (!Check100msTimer(TIMER_100MS_BLE))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_AT)];
				s_BLE_init_state = S_BLEINIT_ATS;
			}	
		}
		break;
		
		case S_BLEINIT_POWER_DW:
		{
			if (!Check100msTimer(TIMER_100MS_BLE))
			{
				ble_reset_flg++;
				BlePowerOff();
				Set100msTimer(TIMER_100MS_BLE, 20);
				s_BLE_init_state = S_BLEINIT_POWER_DW_R;
			}
		}
		break;
		case S_BLEINIT_POWER_DW_R:
		{
			if (!Check100msTimer(TIMER_100MS_BLE))
			{
				BlePowerOn();
				Set100msTimer(TIMER_100MS_BLE, 2);
				s_BLE_init_state = S_BLEINIT_POWER_WAIT;
			}
		}
		break;

		case S_BLEINIT_ATS:			//发送AT，测试串口是否正常
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV0)];
					s_BLE_init_state = S_BLEINIT_ADV0_CTL;
					break;
				}
				case ResultFail:
				{
					if(ble_reset_flg)	//已经复位过一次，强制关机
					{
						ble_reset_flg = 0;
						g_ble_task_flag = BLE_TASK_FAIL;//返回失败后,会强制断电
						s_BLE_init_state = S_BLE_IDLE;	//断电复位后仍AT测试不通过，则断电
					}
					else //失败，执行一次复位
					{
						UartInit(BLE_UART_COM, BAUD38400, DATA_BIT_8, STOPBIT_1, UART_EVEN_PARITY, UART_LPUART_Disable);
						s_BLE_init_state = S_BLEINIT_POWER_DW;
					}
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_ADV0_CTL:	//关闭广播
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_VER_CHK)];
					s_BLE_init_state = S_BLEINIT_VER;
				}
				break;
				default:
					break;
			}
		}
		break;

		case S_BLEINIT_VER:			//查询模块软件版本
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{					
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len > 12)
					{
						g_ble_at_rcv_len = 12;
					}
					if(('V' == p_ble_at_rcv_data[0]) && ('.' == p_ble_at_rcv_data[3]))
					{
						ble_work_stat.Ble_softverson[0] = ((p_ble_at_rcv_data[1] - 0x30) << 4) | (p_ble_at_rcv_data[2] - 0x30);		//记录软件版本
						ble_work_stat.Ble_softverson[1] = ((p_ble_at_rcv_data[4] - 0x30) << 4) | (p_ble_at_rcv_data[5] - 0x30);
					}
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_NAME_CHK)];
					memset(ble_work_stat.Ble_name,0,12);
					s_BLE_init_state = S_BLEINIT_NAME;
					break;
				}
				default:
					break;
			}
		}
		break;

		case S_BLEINIT_NAME:		//查询蓝牙名称
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len > BLE_NAME_MAX_LEN)		//蓝牙名称不大于12字节
					{
						g_ble_at_rcv_len = BLE_NAME_MAX_LEN;
					}
					init_flag = TRUE;
					for(init_cnt = 0; init_cnt < sizeof(ble_key_word); init_cnt++)
					{
						if(p_ble_at_rcv_data[init_cnt] != ble_key_word[init_cnt])		//名称的开始不是关键字
						{
							init_flag = FALSE;
							break;
						}
					}
					if(TRUE == init_flag)
					{
						for(init_i = 0; init_cnt < g_ble_at_rcv_len; init_cnt++,init_i++)
						{
							ble_work_stat.Ble_name[init_i] = p_ble_at_rcv_data[init_cnt];	//只取非关键字部分
						}
					}
				case ResultError:
				case ResultFail:
				{					
					for(init_i = 0; init_i < 5; init_i++)
					{
						ble_temp_arr[init_i * 2] = (Sys_data_object.P1.met_addr[4 - init_i] >> 4) + 0x30;
						ble_temp_arr[init_i * 2 + 1] = (Sys_data_object.P1.met_addr[4 - init_i] & 0x0F) + 0x30;
					}
					init_flag = FALSE;
					for(init_i = 0; init_i < 10; init_i++)
					{
						if(ble_temp_arr[init_i] != ble_work_stat.Ble_name[init_i])
						{
							init_flag = TRUE;
							break;
						}
					}
					if(init_flag && CheckMetAddrIfInit())		//蓝牙名称与表地址不一致，且表地址非全0
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_NAME)];
						s_BLE_init_state = S_BLEINIT_NAME_SET;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_MAC_CHK)];
						memset(ble_work_stat.Ble_mac,0,6);
						s_BLE_init_state = S_BLEINIT_MAC;
					}
					break;
				}
				default:
					break;
			}	
		}
		break;
		
		case S_BLEINIT_NAME_SET:	//设置蓝牙广播名称
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char *)ble_temp_arr, 10))	//读表地址，要修改适应，或者在进来之前修改
			{
				case ResultOk:
					for(init_cnt = 0; init_cnt < 10; init_cnt++)
					{
						ble_work_stat.Ble_name[init_cnt] = ble_temp_arr[init_cnt];	//设置成功后，更新
					}
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_MAC_CHK)];
					memset(ble_work_stat.Ble_mac,0,6);
					s_BLE_init_state = S_BLEINIT_MAC;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_MAC:		//读取蓝牙MAC地址
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:	//读取成功
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len > BLE_NAME_MAX_LEN)
					{
						g_ble_at_rcv_len = BLE_NAME_MAX_LEN;
					}
					format_ascii2hex(ble_work_stat.Ble_mac, p_ble_at_rcv_data, g_ble_at_rcv_len);
				case ResultError:
				case ResultFail:
				{
					init_flag = FALSE;
					for(init_i = 0; init_i < 6; init_i++)
					{
						if(Sys_data_object.P1.met_addr[5 - init_i] != ble_work_stat.Ble_mac[init_i])
						{
							init_flag = TRUE;
							break;
						}
					}
					
					if(init_flag && CheckMetAddrIfInit())	//表地址不是初始化地址，即非全0
					{
						u8 i = 0;
						for(i = 0; i < 6; i++)
						{
							ble_white_MAC_set[i] = Sys_data_object.P1.met_addr[5 - i];//MAC
						}
						format_Hex2ascii(ble_temp_arr, &ble_white_MAC_set[0],6);
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_MAC)];
						init_flag = FALSE;
						s_BLE_init_state = S_BLEINIT_MAC_SET;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_TXPOWER_CHK)];
						s_BLE_init_state = S_BLEINIT_TXPOW;
					}
					break;
				}
				default:
					break;
			}		
		}
		break;
		
		case S_BLEINIT_MAC_SET:		//设置蓝牙MAC地址
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char *)ble_temp_arr, 12))
			{
				case ResultOk:
					for(init_cnt = 0; init_cnt < 6; init_cnt++)
					{
						ble_work_stat.Ble_mac[init_cnt] = ble_white_MAC_set[init_cnt];	//设置成功后，更新
					}
					init_flag = TRUE;
				case ResultError:
				case ResultFail:
				{
					if(init_flag)
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
						s_BLE_init_state = S_BLEINIT_MAC_SAVE;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_TXPOWER_CHK)];
						s_BLE_init_state = S_BLEINIT_TXPOW;
					}					
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_MAC_SAVE:	//保存设置的MAC
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_RESET)];
					s_BLE_init_state = S_BLEINIT_MAC_RESET;	
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_MAC_RESET:	//保存MAC后复位
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_init_state = S_BLE_IDLE;			//发送完复位，不用继续往下执行了
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_TXPOW:		//查询模块当前发射功率
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					init_flag = FALSE;
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if((g_ble_at_rcv_len == 1) && (Sys_data_object.P3.function_switch.ble_tx_power == (p_ble_at_rcv_data[0] - 0x30)))	//发射功率的返回值长度为1字节，且与规约配置一致,不进行设置操作
					{
						init_flag = TRUE;
					}					
					
					if(TRUE == init_flag)	//查询值与规约配置的参数一致，不进行设置操作
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADVPARAM_CHK)];					
						s_BLE_init_state = S_BLEINIT_ADVPERIOD;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_TXPOWER)];
						memset(ble_temp_arr,0,sizeof(ble_temp_arr));
						ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_tx_power);
						s_BLE_init_state = S_BLEINIT_TXPOW_SET;
					}
					
					break;
				}
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_TXPOWER)];
					memset(ble_temp_arr,0,sizeof(ble_temp_arr));
					ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_tx_power);
					s_BLE_init_state = S_BLEINIT_TXPOW_SET;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_TXPOW_SET:		//设置蓝牙发射功率
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char *)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADVPARAM_CHK)];
					s_BLE_init_state = S_BLEINIT_ADVPERIOD;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_ADVPERIOD:		//查询模块广播间隔
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					init_flag = TRUE;
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					ble_temp_data.to_uint16 = Sys_data_object.P3.function_switch.ble_adv_fre * 1000;		//转换为ms
					memset(ble_temp_arr,0,sizeof(ble_temp_arr));
					ble_temp_len = format_Dec2ascii(ble_temp_arr,ble_temp_data.to_uint16);
					if(ble_temp_len == g_ble_at_rcv_len)
					{
						for(init_cnt = 0; init_cnt < ble_temp_len; init_cnt++)
						{
							if(ble_temp_arr[init_cnt] != p_ble_at_rcv_data[init_cnt])
							{
								init_flag = FALSE;
								break;
							}
						}
					}
					else
					{
						init_flag = FALSE;
					}
					if(TRUE == init_flag)
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONPARAM_CHK)];
						s_BLE_init_state = S_BLEINIT_CONPERIOD;
					}
					else
					{
						ble_temp_data.to_uint16 = Sys_data_object.P3.function_switch.ble_adv_fre * 1000;		//转换为ms
						memset(ble_temp_arr,0,sizeof(ble_temp_arr));
						ble_temp_len = format_Dec2ascii(ble_temp_arr,ble_temp_data.to_uint16);
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADVPARAM)];
						s_BLE_init_state = S_BLEINIT_ADVPERIOD_SET;
					}
					break;
				}
				case ResultError:
				case ResultFail:
				{
					ble_temp_data.to_uint16 = Sys_data_object.P3.function_switch.ble_adv_fre * 1000;		//转换为ms
					memset(ble_temp_arr,0,sizeof(ble_temp_arr));
					ble_temp_len = format_Dec2ascii(ble_temp_arr,ble_temp_data.to_uint16);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADVPARAM)];
					s_BLE_init_state = S_BLEINIT_ADVPERIOD_SET;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_ADVPERIOD_SET:		//设置蓝牙广播间隔
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONPARAM_CHK)];
					s_BLE_init_state = S_BLEINIT_CONPERIOD;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_CONPERIOD:		//查询模块连接间隔，BLE间隔进行连接和通信
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					init_flag = TRUE;
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					memset(ble_temp_arr,0,sizeof(ble_temp_arr));
					ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_con_para);
					if(ble_temp_len == g_ble_at_rcv_len)
					{
						for(init_cnt = 0; init_cnt < ble_temp_len; init_cnt++)
						{
							if(ble_temp_arr[init_cnt] != p_ble_at_rcv_data[init_cnt])
							{
								init_flag = FALSE;
								break;
							}
						}
					}
					else
					{
						init_flag = FALSE;
					}
					if(TRUE == init_flag)
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
						s_BLE_init_state = S_BLEINIT_ADV_CTL;
					}
					else
					{
						memset(ble_temp_arr,0,sizeof(ble_temp_arr));
						ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_con_para);
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONPARAM)];
						s_BLE_init_state = S_BLEINIT_CONPERIOD_SET;
					}
					break;
				}
				case ResultError:
				case ResultFail:
				{
					memset(ble_temp_arr,0,sizeof(ble_temp_arr));
					ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_con_para);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONPARAM)];
					s_BLE_init_state = S_BLEINIT_CONPERIOD_SET;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_CONPERIOD_SET:		//设置蓝牙连接间隔
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
					s_BLE_init_state = S_BLEINIT_ADV_CTL;
					break;
				}
				default:
					break;
			}
		}
        break;
		
//        case S_BLEINIT_ADVMFID_SET:		//设置广播数据
//		{
//			//设置前处理好数据
//			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_work_stat.Ble_adv_data, 13))
//			{
//				case ResultOk:
//				case ResultError:
//				case ResultFail:
//				{
//					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
//					s_BLE_init_state = S_BLEINIT_ADV_CTL;
//					break;
//				}
//				default:
//					break;
//			}
//			break;
//		}
			
		case S_BLEINIT_ADV_CTL:			//打开广播
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					s_BLE_init_state = S_BLEINIT_END;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLEINIT_END:		//初始化结束
        {
			BleUartChangeStyle(BLE_cst_AT_NOMAL_RCV);
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_init_state = S_BLE_IDLE;
        }
        break;

		default:
		{
			BleUartChangeStyle(BLE_cst_AT_NOMAL_RCV);
			g_ble_task_flag = BLE_TASK_SUCCESS;
            s_BLE_init_state = S_BLE_IDLE;
		}
        break;
    }
}

/***************************************************************************
* @fun_name		void BleStartInitTask(void)
* @brief		启动BLE初始化
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
u8 s_ble_is_initing = 0;
void BleStartInitTask(void)
{
	s_BLE_init_state = S_BLEINIT_POWER_ON;
	s_BLE_main_state = S_BLE_MAIN_INIT;
	
	ble_work_stat.Ble_cur_mode = SLAVE_MODE;
	ble_work_stat.Ble_scan_state = SCAN_END;
	ble_work_stat.Ble_con_state = CON_END;
	s_ble_is_initing = 1;
}

#if BLE_CENTRAL_SLAVE_MOD
/************************************************************************************************************************************
* 
*									蓝牙主从模式切换
*
************************************************************************************************************************************/

/***************************************************************************
* @fun_name		void BleCentralSwitchMachine(void)
* @brief		主从模式切换状态机
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		主机切换为从机的条件：1）当前为主机模式，2）断开连接
* @other		从机切换为主机的条件：1）当前为从机模式，2）断开连接，3）停止广播
***************************************************************************/
void BleCentralSwitchMachine(void)
{
	u8 bleswitchflag = FALSE;
	static u8 blecurmode = FALSE;
	switch(s_BLE_mode_switch_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		//切换为主机模式
		case S_BLE_SWITCH_CENTRAL:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_STATUS)];
				s_BLE_mode_switch_state = S_BLE_SWITCH_CENTRAL_CHK;
			}
		}
		break;
		
		case S_BLE_SWITCH_CENTRAL_CHK:	//查询当前的链接状态
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					bleswitchflag = FALSE;
					blecurmode = FALSE;
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len <= 3)
					{
						if((0x30 == p_ble_at_rcv_data[2]) && (',' == p_ble_at_rcv_data[1]))		//0为断开链接
						{
							bleswitchflag = TRUE;
						}
						if((0x31 == p_ble_at_rcv_data[0]) && (',' == p_ble_at_rcv_data[1]))		//1为主机模式
						{
							blecurmode = TRUE;
						}
					}
					
					if(bleswitchflag)		//当前已断开链接
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV0)];
						s_BLE_mode_switch_state = S_BLE_SWITCH_ADV0;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
						s_BLE_mode_switch_state = S_BLE_SWITCH_CENTRAL_DISCON;
					}
				}
				break;
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
					s_BLE_mode_switch_state = S_BLE_SWITCH_CENTRAL_DISCON;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SWITCH_CENTRAL_DISCON:	//断开连接
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV0)];
					s_BLE_mode_switch_state = S_BLE_SWITCH_ADV0;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SWITCH_ADV0:		//停止广播
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					if(blecurmode)		//当前已为主机模式
					{
						ble_work_stat.Ble_cur_mode = CENTRAL_MODE;
						g_ble_task_flag = BLE_TASK_SUCCESS;
						s_BLE_mode_switch_state = S_BLE_IDLE;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CENTRAL)];
						s_BLE_mode_switch_state = S_BLE_SWITCH_SET_CENTRAL;
					}
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SWITCH_SET_CENTRAL:	//切换为主机模式
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					ble_work_stat.Ble_cur_mode = CENTRAL_MODE;
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_mode_switch_state = S_BLE_IDLE;
				}
				break;
				case ResultError:
				case ResultFail:
				{
					ble_work_stat.Ble_cur_mode = MODE_ERROR;		//模式切换失败
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_mode_switch_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		//切换为从机模式
		case S_BLE_SWITCH_SLAVE:		
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_STATUS)];
				s_BLE_mode_switch_state = S_BLE_SWITCH_SLAVE_CHK;
			}
		}
		break;
		
		case S_BLE_SWITCH_SLAVE_CHK:	//查询当前链接状态
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					bleswitchflag = FALSE;
					blecurmode = FALSE;
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len <= 3)
					{
						if((0x30 == p_ble_at_rcv_data[2]) && (',' == p_ble_at_rcv_data[1]))		//0为断开链接
						{
							bleswitchflag = TRUE;
						}
						if((0x30 == p_ble_at_rcv_data[0]) && (',' == p_ble_at_rcv_data[1]))		//0为从机
						{
							blecurmode = TRUE;
						}
					}
					
					if(bleswitchflag)		//当前已断开链接
					{
						if(blecurmode)		//已是从机
						{
							p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
							s_BLE_mode_switch_state = S_BLE_SWITCH_ADV1;
						}
						else
						{
							p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SLAVE)];
							s_BLE_mode_switch_state = S_BLE_SWITCH_SET_SLAVE;
						}
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
						s_BLE_mode_switch_state = S_BLE_SWITCH_SLAVE_DISCON;
					}
				}
				break;
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
					s_BLE_mode_switch_state = S_BLE_SWITCH_SLAVE_DISCON;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SWITCH_SLAVE_DISCON:		//断开连接
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					if(blecurmode)		//已是从机
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
						s_BLE_mode_switch_state = S_BLE_SWITCH_ADV1;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SLAVE)];
						s_BLE_mode_switch_state = S_BLE_SWITCH_SET_SLAVE;
					}					
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SWITCH_SET_SLAVE:		//设置为从机
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
					ble_work_stat.Ble_cur_mode = SLAVE_MODE;
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
					s_BLE_mode_switch_state = S_BLE_SWITCH_ADV1;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SWITCH_ADV1:			//开启广播
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					ble_work_stat.Ble_cur_mode = SLAVE_MODE;
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_mode_switch_state = S_BLE_IDLE;
				}
				break;
				case ResultError:
				case ResultFail:
				{
					ble_work_stat.Ble_cur_mode = MODE_ERROR;		//模式切换失败
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_mode_switch_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}			
		break;			
		
		default:
		{
			ble_work_stat.Ble_cur_mode = MODE_ERROR;		//模式切换失败
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_mode_switch_state = S_BLE_IDLE;
		}
		break;
	}
}

/***************************************************************************
* @fun_name		void BleCentralSwitchTask(u8 switch_type)
* @brief		启动主从模式切换
* @param[in]	switch_type:CENTRAL_MODE主机模式,SLAVE_MODE从机模式
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleCentralSwitchTask(u8 switch_type)
{
	if((CENTRAL_MODE != switch_type) && (SLAVE_MODE != switch_type))		//模式错误时，默认为从机
	{
		switch_type = SLAVE_MODE;
	}
	BleChkLowpowerState();
	switch(switch_type)
	{
		case CENTRAL_MODE:
		{
//			if(CENTRAL_MODE != ble_work_stat.Ble_cur_mode)	//当前非主机模式
			{
				s_BLE_mode_switch_state = S_BLE_SWITCH_CENTRAL;
				s_BLE_main_state = S_BLE_MAIN_CENTRAL_SWITCH;
				ble_work_stat.Ble_cur_mode = MODE_ERROR;
			}
		}
		break;
		
		case SLAVE_MODE:
		{
//			if(CENTRAL_MODE == ble_work_stat.Ble_cur_mode)		//当前为主机模式
			{
				s_BLE_mode_switch_state = S_BLE_SWITCH_SLAVE;
				s_BLE_main_state = S_BLE_MAIN_CENTRAL_SWITCH;
				ble_work_stat.Ble_cur_mode = MODE_ERROR;
			}
		}
		break;
	}

}
/***************************************************************************
* @fun_name		u8 BleGetCurMode(void)
* @brief		获取当前工作模式
* @param[in]	NONE
* @param[out]	None
* @retval		SLAVE_MODE、CENTRAL_MODE、MODE_ERROR
* @other		None
***************************************************************************/
u8 BleGetCurMode(void)
{
	return ble_work_stat.Ble_cur_mode;
}

/************************************************************************************************************************************
*									            蓝牙开启扫描
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleScanMachine(void)
* @brief		蓝牙扫描状态机
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleScanMachine(void)
{
	switch(s_BLE_scan_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		case S_BLE_SCAN_START:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
				s_BLE_scan_state = S_BLE_SCAN_DISCON;
			}
		}
		break;
		
		case S_BLE_SCAN_DISCON:		//断开连接
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SCAN)];
					s_BLE_scan_state = S_BLE_SCAN_ING;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SCAN_ING:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					ble_work_stat.Ble_scan_state = SCAN_ING;		//扫描中
					Set100msTimer(TIMER_100MS_BLE_SCAN, 500);		//开启最大扫描时间	50s
					BleUartChangeStyle(BLE_cst_AT_SCAN_RCV);		//切换至扫描接收
					BleClrScanCompleteFlag();						//清扫描完成标志
					BleClrMacBuf();									//清扫描数据缓冲区
					s_BLE_scan_state = S_BLE_SCAN_OVERTIME;
					break;
				}
				default:
					break;
			}
		}
		break;		
		
		case S_BLE_SCAN_OVERTIME:
		{
			if((0 == Check100msTimer(TIMER_100MS_BLE_SCAN)) || (TRUE == BleGetScanCompleteFlag()))		//扫描超时
			{
				ble_work_stat.Ble_scan_state = SCAN_END;		//扫描结束
				g_ble_task_flag = BLE_TASK_SUCCESS;
				s_BLE_scan_state = S_BLE_IDLE;
			}
		}
		break;
		
		case S_BLE_SCAN_STOP:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_STOP_SCAN)];
				BleClrScanCompleteFlag();						//清扫描完成标志
				s_BLE_scan_state = S_BLE_SCAN_END;
			}
		}
		break;
		
		case S_BLE_SCAN_END:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					Set100msTimer(TIMER_100MS_BLE_SCAN, 80);		//开启最大扫描时间	8s
					s_BLE_scan_state = S_BLE_SCAN_END_OVERTIME;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SCAN_END_OVERTIME:
		{
			if((0 == Check100msTimer(TIMER_100MS_BLE_SCAN)) || (TRUE == BleGetScanCompleteFlag()))		//扫描超时
			{
				ble_work_stat.Ble_scan_state = SCAN_END;		//扫描结束
				Set100msTimer(TIMER_100MS_BLE_SCAN, 0);
				g_ble_task_flag = BLE_TASK_SUCCESS;
				s_BLE_scan_state = S_BLE_IDLE;
			}
		}
		break;
		
		default:
			ble_work_stat.Ble_scan_state = SCAN_END;		//扫描结束
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_scan_state = S_BLE_IDLE;
			break;
	}
}

/***************************************************************************
* @fun_name		u8 BleScanTask(u8 scan_order)
* @brief		启动或停止扫描
* @param[in]	scan_order:SACN_START_ORDER开启扫描,SACN_STOP_ORDER停止扫描
* @param[out]	None
* @retval		None
* @other		启动扫描的条件：1）处于主机状态，2）断开连接，3）当前未处于扫描状态
* @other		停止扫描的条件：1）当前处于扫描状态
***************************************************************************/
u8 BleScanTask(u8 scan_order)
{
	u8 re_result = FALSE;
	BleChkLowpowerState();
	switch(scan_order)
	{
		case SACN_START_ORDER:	//启动扫描
		{
			if((SCAN_END == ble_work_stat.Ble_scan_state) && (CENTRAL_MODE == ble_work_stat.Ble_cur_mode))
			{
				s_BLE_scan_state = S_BLE_SCAN_START;
				s_BLE_main_state = S_BLE_MAIN_SCAN;
				ble_work_stat.Ble_scan_state = SCAN_START;
				re_result = TRUE;
			}
		}
		break;
		
		case SACN_STOP_ORDER:	//结束扫描
		{
			if(SCAN_ING == ble_work_stat.Ble_scan_state)
			{
				s_BLE_scan_state = S_BLE_SCAN_STOP;
				s_BLE_main_state = S_BLE_MAIN_SCAN;
				re_result = TRUE;
			}
		}
		break;
	}
	return re_result;
}

/***************************************************************************
* @fun_name		u8 BleGetCurScanState(void)
* @brief		获取当前的扫描状态
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		SCAN_END扫描结束或未启动扫描，SCAN_ING扫描中
***************************************************************************/
u8 BleGetCurScanState(void)
{
	return ble_work_stat.Ble_scan_state;
}
#endif
/************************************************************************************************************************************
*									            蓝牙连接状态管理
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleConMgrMachine(void)
* @brief		管理蓝牙连接状态机
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleConMgrMachine(void)
{
	//u8 temp_con_flag = FALSE;
    switch (s_BLE_conmgr_state)
    {
		case S_BLE_IDLE:
		{
			
		}
		break;
#if BLE_CENTRAL_SLAVE_MOD		
		case S_BLE_CON_START:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_STATUS)];
				s_BLE_conmgr_state = S_BLE_CON_STATE_CHEK;	
			}
		}
		break;
		
		case S_BLE_CON_STATE_CHEK:	//查询当前的连接状态
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					temp_con_flag = FALSE;
					if(g_ble_at_rcv_len <= 3)
					{
						if((0x31 == p_ble_at_rcv_data[2]) && (',' == p_ble_at_rcv_data[1]))		//1为连接
						{
							temp_con_flag = TRUE;
						}
					}
					if(temp_con_flag)		//当前为连接状态，需先断开；否则，直接区建立连接
					{			
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
						s_BLE_conmgr_state = S_BLE_CON_DISCON;
					}
					else
					{
//						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONNECT)];
//						s_BLE_conmgr_state = S_BLE_CON_RECON;
						s_BLE_conmgr_state = S_BLE_CON_DISCON_WAIT;		//先去判断当前是否为加密配对
					}
				}
				break;
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
					s_BLE_conmgr_state = S_BLE_CON_DISCON;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CON_DISCON:		//断开连接
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					Set5msTimer(TIMER_5MS_BLE_CON_WAIT,100);
					s_BLE_conmgr_state = S_BLE_CON_DISCON_WAIT;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CON_DISCON_WAIT:	//断开延时
		{
			if(0 == Check5msTimer(TIMER_5MS_BLE_CON_WAIT))
			{
				if(Sys_data_object.P1.function_switch.ies_double_switch.password_enable)	//开启了密码配对，需要先清一下蓝牙中的加密信息
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CLRBNDE)];
					s_BLE_conmgr_state = S_BLE_CON_CLRBNDE;
				}
				else
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONNECT)];
					s_BLE_conmgr_state = S_BLE_CON_RECON;
				}
			}
		}
		break;
		
		case S_BLE_CON_CLRBNDE:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONNECT)];
					s_BLE_conmgr_state = S_BLE_CON_RECON;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CON_RECON:		//重新建立连接
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_work_stat.Ble_con_MAC, 12))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					Set100msTimer(TIMER_100MS_BLE_CON,220);		//连接超时时间22s
					s_BLE_conmgr_state = S_BLE_CON_RECON_R;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CON_RECON_R:
		{
			if(0 == Check100msTimer(TIMER_100MS_BLE_CON))
			{
				ble_work_stat.Ble_con_state = CON_END;			//未连接
				g_ble_task_flag = BLE_TASK_SUCCESS;
				s_BLE_conmgr_state = S_BLE_IDLE;
			}
			else
			{
				if(Gpio_GetInputIO(BLE_CON_PORT, BLE_CON_PIN))		//连接高电平
				{
					Set5msTimer(TIMER_5MS_BLE_CON_WAIT,100);
					s_BLE_conmgr_state = S_BLE_CON_RECON_XIAODOU;
				}
			}
		}
		break;
		
		case S_BLE_CON_RECON_XIAODOU:		//高电平消抖
		{
			if(0 == Check5msTimer(TIMER_5MS_BLE_CON_WAIT))
			{
				ble_work_stat.Ble_con_state = CON_ING;				//连接中
				g_ble_task_flag = BLE_TASK_SUCCESS;
				s_BLE_conmgr_state = S_BLE_IDLE;
			}
			else
			{
				if(!Gpio_GetInputIO(BLE_CON_PORT, BLE_CON_PIN))		//低电平
				{
					s_BLE_conmgr_state = S_BLE_CON_RECON_R;
				}
			}
		}
		break;
#endif		
		case S_BLE_CON_STOP:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
				s_BLE_conmgr_state = S_BLE_CON_END;
			}
		}
		break;
		
		case S_BLE_CON_END:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					ble_work_stat.Ble_con_state = CON_END;		//只有返回ok才置连接结束
				}
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_conmgr_state = S_BLE_IDLE;
				}
				default:
					break;
			}
		}
		break;

		default:
		{
			ble_work_stat.Ble_con_state = CON_END;		//连接结束
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_conmgr_state = S_BLE_IDLE;
		}
		break;
	}
}

/***************************************************************************
* @fun_name		u8 BleConMacTask(u8 con_order,u8 *con_mac)
* @brief		Ble启动或断开连接
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
u8 BleConMacTask(u8 con_order,u8 *con_mac)
{
	u8 con_result = FALSE;
	BleChkLowpowerState();
#if BLE_CENTRAL_SLAVE_MOD
	if((CON_START_ORDER == con_order) && (CENTRAL_MODE == ble_work_stat.Ble_cur_mode))		//建立连接
	{
		format_Hex2ascii(ble_work_stat.Ble_con_MAC,con_mac,6);
		s_BLE_conmgr_state = S_BLE_CON_START;
		s_BLE_main_state = S_BLE_MAIN_CONNECT;
		ble_work_stat.Ble_con_state = CON_START;//未连接
		con_result = TRUE;
	}
	else if(CON_STOP_ORDER == con_order)		//断开连接
	{
		s_BLE_conmgr_state = S_BLE_CON_STOP;
		s_BLE_main_state = S_BLE_MAIN_CONNECT;
		con_result = TRUE;
	}
#else
	if(CON_STOP_ORDER == con_order)		//断开连接
	{
		s_BLE_conmgr_state = S_BLE_CON_STOP;
		s_BLE_main_state = S_BLE_MAIN_CONNECT;
		con_result = TRUE;
	}
#endif
	return con_result;
}

/***************************************************************************
* @fun_name		u8 BleGetCurConState(u8* ptr_con_mac)
* @brief		获取当前的连接状态
* @param[in]	None
* @param[out]	当前连接的MAC
* @retval		CON_START：开始连接，CON_END:未连接，CON_ING：连接中
* @other		None
***************************************************************************/
//u8 BleGetCurConState(u8* ptr_con_mac)
//{
//	memcpy(ptr_con_mac,ble_work_stat.Ble_con_MAC,12);
//	return ble_work_stat.Ble_con_state;
//}
u8 BleGetCurConState(void)
{
	return ble_work_stat.Ble_con_state;
}

/************************************************************************************************************************************
*									            蓝牙变更蓝牙名称及MAC
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleChangeMACMachine(void)
* @brief		Ble修改蓝牙名称及MAC地址
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleChangeMACMachine(void)
{
	switch(s_BLE_change_mac_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		case S_BLE_MAC_SET_START:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_DISCON)];
				s_BLE_change_mac_state = S_BLE_MAC_DISCON;	//先断开连接,才能修改MAC地址
			}
		}
		break;
		
		case S_BLE_MAC_DISCON:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					ble_work_stat.Ble_con_state = CON_END;			//连接结束
					if(CENTRAL_MODE != ble_work_stat.Ble_cur_mode)	//非主机模式
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV0)];
						s_BLE_change_mac_state = S_BLE_MAC_ADV0;
					}
					else
					{
						p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_NAME)];
						s_BLE_change_mac_state = S_BLE_MAC_NAME;
					}
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_MAC_ADV0:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_NAME)];
					s_BLE_change_mac_state = S_BLE_MAC_NAME;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_MAC_NAME:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_work_stat.Ble_name, 10))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					format_Hex2ascii(ble_temp_arr,ble_work_stat.Ble_mac,6);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_MAC)];
					s_BLE_change_mac_state = S_BLE_MAC_MAC;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_MAC_MAC:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, 12))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_change_mac_state = S_BLE_MAC_SAVE;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_MAC_SAVE:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_RESET)];
					s_BLE_change_mac_state = S_BLE_MAC_RESET;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_MAC_RESET:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_change_mac_state = S_BLE_IDLE;
				}
				default:
					break;
			}
		}
		break;
		
//		case S_BLE_MAC_ADV1:
//		{
//			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
//			{
//				case ResultOk:
//				case ResultError:
//				case ResultFail:
//				{
//					g_ble_task_flag = BLE_TASK_SUCCESS;
//					s_BLE_change_mac_state = S_BLE_IDLE;
//				}
//				default:
//					break;
//			}
//		}
//		break;
		
		//查询
		case S_BLE_MAC_CHK_START:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_NAME_CHK)];
				s_BLE_change_mac_state = S_BLE_MAC_NAME_CHK;
			}
		}
		break;
		case S_BLE_MAC_NAME_CHK:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_MAC_CHK)];
					s_BLE_change_mac_state = S_BLE_MAC_MAC_CHK;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_MAC_MAC_CHK:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_change_mac_state = S_BLE_IDLE;
				}
				default:
					break;
			}
		}
		break; 
		
		default:
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_change_mac_state = S_BLE_IDLE;
			break;
	}
}

/***************************************************************************
* @fun_name		void BleNameMacTask(u8 opr_type,u8 src_len)
* @brief		Ble修改蓝牙名称及MAC地址
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleNameMacTask(u8 opr_type,u8* name_src)
{
	BleChkLowpowerState();
	switch(opr_type)
	{
		case CHK_NAME_MAC:
		{
			s_BLE_change_mac_state = S_BLE_MAC_CHK_START;
			s_BLE_main_state = S_BLE_MAIN_NAME_MAC;
		}
		break;
		
		case SET_NAME_MAC:
		{
			u8 nme_temp_i = 0;
			//NAME
			for(nme_temp_i = 0; nme_temp_i < 5; nme_temp_i++)
			{
				ble_work_stat.Ble_name[nme_temp_i * 2] = (name_src[4 - nme_temp_i] >> 4) + 0x30;
				ble_work_stat.Ble_name[nme_temp_i * 2 + 1] = (name_src[4 - nme_temp_i] & 0x0F) + 0x30;
			}

			//MAC
			for(nme_temp_i = 0; nme_temp_i < 6; nme_temp_i++)
			{
				ble_work_stat.Ble_mac[nme_temp_i] =  *(name_src + 5 - nme_temp_i);
			}
			s_BLE_change_mac_state = S_BLE_MAC_SET_START;
			s_BLE_main_state = S_BLE_MAIN_NAME_MAC;
		}
		break;
	}
	
}

/************************************************************************************************************************************
*									            蓝牙变更广播数据
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleUpdateAavDataMachine(void)
* @brief		Ble更新广播数据
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleUpdateAavDataMachine(void)
{
	switch(s_BLE_update_adv_data_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		case S_BLE_UPDATE_ADV_START:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADVMFID)];
				s_BLE_update_adv_data_state = S_BLE_UPDATE_ADV;
			}
		}
		break;
		
		case S_BLE_UPDATE_ADV:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_work_stat.Ble_adv_data, 13))
			{
				case ResultOk:
				case ResultError:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_MAC_CHK)];
					memset(ble_temp_arr,0,sizeof(ble_temp_arr));
					s_BLE_update_adv_data_state = S_BLE_UPDATE_ADV_RD_MAC;
				}
				break;
				case ResultFail:
				{	
					g_ble_task_flag = BLE_TASK_FAIL;//更新广播数据异常时，提示进行蓝牙的复位
					s_BLE_update_adv_data_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_UPDATE_ADV_RD_MAC:			//更新广播数据时，同时读取一下MAC，判断是否与表地址一致，用来决定是否对蓝牙进行复位
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				{
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len > BLE_NAME_MAX_LEN)
					{
						g_ble_at_rcv_len = BLE_NAME_MAX_LEN;
					}
					format_ascii2hex(ble_temp_arr, p_ble_at_rcv_data, g_ble_at_rcv_len);
				}
				case ResultError:
				case ResultFail:
				{
					u8 temp_num;
					
					if(CheckMetAddrIfInit())		//表地址已设置
					{
						for(temp_num = 0; temp_num < 6; temp_num++)
						{
							if(ble_temp_arr[temp_num] != Sys_data_object.P1.met_addr[5 - temp_num])
							{
								break;
							}
						}
					}
					if(temp_num>=6)
					{
						g_ble_task_flag = BLE_TASK_SUCCESS;
						s_BLE_update_adv_data_state = S_BLE_IDLE;
					}
					else//MAC地址与表地址不一致,返回失败进行重启
					{
						g_ble_task_flag = BLE_TASK_FAIL;
						s_BLE_update_adv_data_state = S_BLE_IDLE;
					}
				}
				break;
				default:
					break;
			}
		}
		break;
		
		default:
		{
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_update_adv_data_state = S_BLE_IDLE;
		}
		break;
	}
}

/***************************************************************************
* @fun_name		u8 BleUpdataAdvDataTask(u8* snd_data)
* @brief		启动Ble更新广播数据
* @param[in]	待更新的数据
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
u8 BleUpdataAdvDataTask(u8* snd_data)
{
	u8 adv_data_result = FALSE;
	u8 adv_data_len = 0;
	BleChkLowpowerState();
	if((CENTRAL_MODE != ble_work_stat.Ble_cur_mode) && (CON_ING != ble_work_stat.Ble_con_state))	//非主机模式，非连接状态
	{
		for(adv_data_len = 0; adv_data_len < 13; adv_data_len++)
		{
			ble_work_stat.Ble_adv_data[adv_data_len] = *(snd_data + adv_data_len);
		}
		s_BLE_update_adv_data_state = S_BLE_UPDATE_ADV_START;
		s_BLE_main_state = S_BLE_MAIN_ADV_DATA;
		adv_data_result = TRUE;
	}
	return adv_data_result;
}

/************************************************************************************************************************************
*									            蓝牙变更参数
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleChangeAdvParasMachine(void)
* @brief		Ble更新参数
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleChangeAdvParasMachine(void)
{
	switch(s_BLE_change_adv_para_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		case S_BLE_CHANGE_ADV_START:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV0)];
				s_BLE_change_adv_para_state = S_BLE_CHANGE_ADV0;
			}	
		}
		break;
		
		case S_BLE_CHANGE_ADV0:				//停止广播
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					ble_temp_data.to_uint16 = Sys_data_object.P3.function_switch.ble_adv_fre * 1000;
					ble_temp_len = format_Dec2ascii(ble_temp_arr,ble_temp_data.to_uint16);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADVPARAM)];
					s_BLE_change_adv_para_state = S_BLE_CHANGE_ADV_PARAM;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CHANGE_ADV_PARAM:			//修改广播间隔
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_con_para);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_CONPARAM)];
					s_BLE_change_adv_para_state = S_BLE_CHANGE_CON_PARAM;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CHANGE_CON_PARAM:		//修改连接间隔
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_tx_power);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_TXPOWER)];
					s_BLE_change_adv_para_state = S_BLE_CHANGE_TX_POWER;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CHANGE_TX_POWER:			//修改发射功率
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					ble_temp_len = format_Dec2ascii(ble_temp_arr,(u16)Sys_data_object.P3.function_switch.ble_scan_times);
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SCAN_TIMES)];
					s_BLE_change_adv_para_state = S_BLE_CHANGE_SCAN_TIMES;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CHANGE_SCAN_TIMES:			//修改扫描次数
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, ble_temp_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_change_adv_para_state = S_BLE_CHANGE_SAVE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CHANGE_SAVE:				//修改完成后保存
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
					s_BLE_change_adv_para_state = S_BLE_CHANGE_ADV1;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CHANGE_ADV1:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_change_adv_para_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		default:
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_change_adv_para_state = S_BLE_IDLE;
			break;
	}
}

/***************************************************************************
* @fun_name     void BleChangeAdvParaTask()
* @brief        启动Ble修改广播参数
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
void BleChangeAdvParaTask(void)
{
	BleChkLowpowerState();
	s_BLE_change_adv_para_state = S_BLE_CHANGE_ADV_START;
	s_BLE_main_state = S_BLE_MAIN_ADV_PARAM;
}

/************************************************************************************************************************************
*									            蓝牙变更关键字
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleSetClearKeyWordMachine(void)
* @brief		Ble修改或取消关键字
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleSetClearKeyWordMachine(void)
{
	switch(s_BLE_change_key_word_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		case S_BLE_CHK_KEY_WORD:		//查询关键字
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_KEY_CHK)];
				s_BLE_change_key_word_state = S_BLE_CHK_KEY_WORD_R;
			}
		}
		break;
		
		case S_BLE_CHK_KEY_WORD_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_change_key_word_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SET_KEY_WORD:	//修改关键字
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_KEY_SET)];
				s_BLE_change_key_word_state = S_BLE_SET_KEY_WORD_R;
			}
		}
		break;
		
		case S_BLE_SET_KEY_WORD_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf,(char*)ble_work_stat.Ble_key_word, ble_work_stat.Ble_key_word_len))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_change_key_word_state = S_BLE_KEY_WORD_SAVE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_CLEAR_KEY_WORD:	//取消关键字
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_KEY_CLR)];
				s_BLE_change_key_word_state = S_BLE_CLEAR_KEY_WORD_R;
			}
		}
		break;
		
		case S_BLE_CLEAR_KEY_WORD_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_change_key_word_state = S_BLE_KEY_WORD_SAVE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_KEY_WORD_SAVE:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_change_key_word_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;

		default:
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_change_key_word_state = S_BLE_IDLE;
			break;
	}
}

/***************************************************************************
* @fun_name		void BleKeyWordTask(u8 type,u8* key_word)
* @brief		启动Ble修改、查询或取消关键字
* @param[in]	type:操作类型，key_word待修改的关键字，查询与取消时填NULL,key_len关键字长度
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleKeyWordTask(u8 type,u8* key_word,u8 key_len)
{
	u8 key_temp = 0;
	BleChkLowpowerState();
	switch(type)
	{
		case CHK_KEY_WORD:
		{
			s_BLE_change_key_word_state = S_BLE_CHK_KEY_WORD;
			s_BLE_main_state = S_BLE_MAIN_KEY_WORD;
		}
		break;
		
		case SET_KEY_WORD:
		{
			if((0 == key_len) || (12 <= key_len))
			{
				break;
			}
			ble_work_stat.Ble_key_word_len = key_len;
			for(key_temp = 0; key_temp < key_len; key_temp++)
			{
				ble_work_stat.Ble_key_word[key_temp] = *(key_word + key_temp);
			}
			s_BLE_change_key_word_state = S_BLE_SET_KEY_WORD;
			s_BLE_main_state = S_BLE_MAIN_KEY_WORD;
		}
		break;
		
		case CLR_KEY_WORD:
		{
			s_BLE_change_key_word_state = S_BLE_CLEAR_KEY_WORD;
			s_BLE_main_state = S_BLE_MAIN_KEY_WORD;
		}
		break;
	}
}

/***************************************************************************
* @fun_name     u8 BleGetCurKeyWord(u8* key_addr)
* @brief        获取Ble的关键字
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        先查询，再调用该接口
***************************************************************************/
u8 BleGetCurKeyWord(u8* key_addr)
{
	u8 temp_i = 0;
	if(0 != ble_work_stat.Ble_key_word_len)
	{
		for(temp_i = 0; temp_i < ble_work_stat.Ble_key_word_len; temp_i++)
		{
			*(key_addr + temp_i) = ble_work_stat.Ble_key_word[temp_i];
		}
		return ble_work_stat.Ble_key_word_len;
	}
	return 0;
}

#if BLE_CENTRAL_SLAVE_MOD
/************************************************************************************************************************************
*									            变更主机扫描时的MAC白名单
************************************************************************************************************************************/
/***************************************************************************
* @fun_name		void BleMacWhiteListMachine(void)
* @brief		变更MAC白名单
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleMacWhiteListMachine(void)
{
	switch(s_BLE_white_list_state)
	{
		case S_BLE_IDLE:
		{
		}
		break;
		
		case S_BLE_WHITE_LIST:		//设置白名单
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				format_Hex2ascii(ble_temp_arr,ble_white_MAC_set,6);
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_WHITE_LIST_SET)];
				s_BLE_white_list_state = S_BLE_WHITE_LIST_R;
			}
		}
		break;
		
		case S_BLE_WHITE_LIST_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, (char*)ble_temp_arr, 12))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_white_list_state = S_BLE_WHITE_LIST_SAVE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_WHITE_LIST_CLR:	//清除白名单
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_WHITE_LIST_CLR)];
				s_BLE_white_list_state = S_BLE_WHITE_LIST_CLR_R;
			}
		}
		break;
		
		case S_BLE_WHITE_LIST_CLR_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_white_list_state = S_BLE_WHITE_LIST_SAVE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_WHITE_LIST_CHK:	//查询白名单
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_WHITE_LIST_CHK)];
				s_BLE_white_list_state = S_BLE_WHITE_LIST_CHK_R;
			}
		}
		break;
		
		case S_BLE_WHITE_LIST_CHK_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_white_list_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_WHITE_LIST_SAVE:		//保存
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_white_list_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		default:
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_white_list_state = S_BLE_IDLE;
			break;
	}
}

/***************************************************************************
* @fun_name     void BleMacWhiteListTask(u8 type,u8* list_addr)
* @brief        扫描MAC白名单
* @param[in]    type:设置或取消白名单，list_addr待设定的白名单内容，取消时填NULL
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
void BleMacWhiteListTask(u8 type,u8* list_addr)
{
	u8 list_temp = 0;
	BleChkLowpowerState();
	switch(type)
	{
		case SET_WHITE_LIST:
		{
			for(list_temp = 0; list_temp < 6; list_temp++)
			{
				ble_white_MAC_set[list_temp] = *(list_addr + list_temp);
			}
			s_BLE_white_list_state = S_BLE_WHITE_LIST;
			s_BLE_main_state = S_BLE_MAIN_WHITE_LIST;
		}
		break;
		
		case CLR_WHITE_LIST:
		{
			s_BLE_white_list_state = S_BLE_WHITE_LIST_CLR;
			s_BLE_main_state = S_BLE_MAIN_WHITE_LIST;
		}
		break;
		
		case CHK_WHITE_LIST:
		{
			s_BLE_white_list_state = S_BLE_WHITE_LIST_CHK;
			s_BLE_main_state = S_BLE_MAIN_WHITE_LIST;
		}
		break;
	}
}
#endif

/************************************************************************************************************************************
*									            查询蓝牙当前的主从模式及连接状态
************************************************************************************************************************************/
/***************************************************************************
* @fun_name     void BleChkStatusMachine(void)
* @brief        查询蓝牙当时的主从模式及连接状态
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        正常应返回OK+STATUS=A,B，其中A表示主从模式（0-从，1-主），B表示连接状态（0-断开，1-连接）
***************************************************************************/
void BleChkStatusMachine(void)
{
	switch(s_BLE_chk_status_state)
	{
		case S_BLE_IDLE:
		{
			;
		}
		break;
		
		case S_BLE_CHK_STATUS:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_STATUS)];
				s_BLE_chk_status_state = S_BLE_CHK_STATUS_R;
			}
		}
		break;
		
		case S_BLE_CHK_STATUS_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))	
			{
				case ResultOk:
				{
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len <= 3)
					{
						if((0x31 == p_ble_at_rcv_data[0]) && (',' == p_ble_at_rcv_data[1]))		//1为主机
						{
							ble_work_stat.Ble_cur_mode = CENTRAL_MODE;
						}
						else if((0x30 == p_ble_at_rcv_data[0]) && (',' == p_ble_at_rcv_data[1]))
						{
							ble_work_stat.Ble_cur_mode = SLAVE_MODE;
						}
						else
						{
							ble_work_stat.Ble_cur_mode = MODE_ERROR;
						}
						
						if((0x31 == p_ble_at_rcv_data[2]) && (',' == p_ble_at_rcv_data[1]))		//1为连接
						{
							ble_work_stat.Ble_con_state = CON_ING;
						}
						else if((0x30 == p_ble_at_rcv_data[2]) && (',' == p_ble_at_rcv_data[1]))
						{
							ble_work_stat.Ble_con_state = CON_END;
						}
						else 
						{
							ble_work_stat.Ble_con_state = CON_START;
						}
					}
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_chk_status_state = S_BLE_IDLE;
				}
				break;
				case ResultError:
				case ResultFail:
				{
					ble_work_stat.Ble_con_state = CON_START;
					ble_work_stat.Ble_cur_mode = MODE_ERROR;
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_chk_status_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		default:
		{
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_chk_status_state = S_BLE_IDLE;
		}
		break;
	}
}
/***************************************************************************
* @fun_name     void BleChkStatusTask(void)
* @brief        启动查询蓝牙当时的主从模式及连接状态
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
void BleChkStatusTask(void)
{
	BleChkLowpowerState();
	s_BLE_main_state = S_BLE_MAIN_CHK_STATUS;
	s_BLE_chk_status_state = S_BLE_CHK_STATUS;
}

/************************************************************************************************************************************
*									            查询或设置蓝牙加密配对的命令
************************************************************************************************************************************/
/***************************************************************************
* @fun_name    	void BleSecPinMachine(void)
* @brief        查询或设置蓝牙加密配对的命令状态机
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        模式0：AT+SEC=0
* @other        模式1：AT+SEC=1
* @other        取消：AT+SEC=3
***************************************************************************/
void BleSecPinMachine(void)
{
	switch(s_BLE_sec_status_state)
	{
		case S_BLE_IDLE:
		{
			
		}
		break;
		//查询-同时查询SEC状态与密码PIN
		case S_BLE_CHK_SEC:	//查询SEC
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SEC_CHK)];
				s_BLE_sec_status_state = S_BLE_CHK_SEC_R;
			}
		}
		break;
		case S_BLE_CHK_SEC_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				{
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len == 1)		//SEC查询的返回值只有1字节
					{
						if('0' == p_ble_at_rcv_data[0] || '1' == p_ble_at_rcv_data[0] || '3' == p_ble_at_rcv_data[0])
						{
							ble_work_stat.Ble_cur_sec = *p_ble_at_rcv_data - 0x30;
						}
					}
				}
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_PIN_CHK)];
					s_BLE_sec_status_state = S_BLE_CHK_PIN;
					break;
				}
				default:
					break;
			}
		}
		break;
		case S_BLE_CHK_PIN:	//查询PIN
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				{
					g_ble_at_rcv_len = BleRcvAtData(&p_ble_at_rcv_data);
					if(g_ble_at_rcv_len <= 6)		//PIN查询的返回值最大为6字节,返回的是ascii
					{
						format_ascii2hex(ble_work_stat.Ble_cur_pin,p_ble_at_rcv_data,g_ble_at_rcv_len);
					}
				}
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_sec_status_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;		
		
		//设置--SEC与PIN同时设置，设置前关闭广播，完成或失败后均开启广播
		case S_BLE_SET_SEC_ADV0:	//关闭广播
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV0)];
				s_BLE_sec_status_state = S_BLE_SET_SEC_ADV0_R;
			}
		}
		break;
		case S_BLE_SET_SEC_ADV0_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_PIN)];
					s_BLE_sec_status_state = S_BLE_SET_PIN;
					break;
				}
				default:
					break;
			}
		}
		break;
		case S_BLE_SET_PIN:	//设置PIN
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, ble_default_pin,6))
			{
				case ResultOk:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SEC_SET)];
					s_BLE_sec_status_state = S_BLE_SET_SEC;
				}
				break;
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
					s_BLE_sec_status_state = S_BLE_SET_SEC_ADV1;
					break;
				}
				default:
					break;
			}
		}
		break;
		case S_BLE_SET_SEC:	//设置SEC
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_ADV1)];
					s_BLE_sec_status_state = S_BLE_SET_SEC_ADV1;
					break;
				}
				default:
					break;
			}
		}
		break;
		case S_BLE_SET_SEC_ADV1:	//开启广播
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SAVE)];
					s_BLE_sec_status_state = S_BLE_SEC_SAVE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		//取消
		case S_BLE_CLR_SEC:
		{
			if(0 == Check5msTimer(TIMER_5MS_LOWPOWER))
			{
				p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_SEC_CLR)];
				s_BLE_sec_status_state = S_BLE_CLR_SEC_R;
			}
		}
		break;
		case S_BLE_CLR_SEC_R:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					p_cur_atcmdbuf = &AtCmdBuf[getAtCmdIndex(AT_CODE_RESET)];
					s_BLE_sec_status_state = S_BLE_SEC_RESET;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SEC_RESET:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL, 0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_sec_status_state = S_BLE_IDLE;			//发送完复位，不用继续往下执行了
				}
				default:
					break;
			}
		}
		break;
		
		case S_BLE_SEC_SAVE:
		{
			switch(AT_Requeset_Proc(p_cur_atcmdbuf, NULL,0))
			{
				case ResultOk:
				case ResultError:
				case ResultFail:
				{
					g_ble_task_flag = BLE_TASK_SUCCESS;
					s_BLE_sec_status_state = S_BLE_IDLE;
					break;
				}
				default:
					break;
			}
		}
		break;
		
		default:
		{
			g_ble_task_flag = BLE_TASK_SUCCESS;
			s_BLE_sec_status_state = S_BLE_IDLE;
			break;
		}
	}
}

/***************************************************************************
* @fun_name    	u8 BleSecChkOrSetTask(u8 sec_type)
* @brief        查询或设置蓝牙加密配对的启动接口
* @param[in]    sec_type:查询、启用、取消
* @param[out]   None
* @retval       TRUE:启动成功，FALSE：启动失败
* @other        调用前，判bleifidle
***************************************************************************/
u8 BleSecChkOrSetTask(u8 sec_type)
{
	if(CHK_BLE_SEC == sec_type || SET_BLE_SEC == sec_type || CLR_BLE_SEC == sec_type)
	{
		BleChkLowpowerState();
		if(CHK_BLE_SEC == sec_type)		//查询
		{
			s_BLE_main_state = S_BLE_MAIN_SEC_PIN;
			s_BLE_sec_status_state = S_BLE_CHK_SEC;
		}
		else if(SET_BLE_SEC == sec_type)//开启
		{
			s_BLE_main_state = S_BLE_MAIN_SEC_PIN;
			s_BLE_sec_status_state = S_BLE_SET_SEC_ADV0;
		}
		else if(CLR_BLE_SEC == sec_type)//取消
		{
			s_BLE_main_state = S_BLE_MAIN_SEC_PIN;
			s_BLE_sec_status_state = S_BLE_CLR_SEC;
		}
		return TRUE;
	}
	return FALSE;
}

/***************************************************************************
* @fun_name    	u8 BleChkCurSecState(u8 **cur_pin)
* @brief        查询当前的加密配对状态和PIN
* @param[in]    接收pin的数组地址
* @param[out]   当前的密码
* @retval       返回SEC的状态，0-取消，1-开启
* @other        如掉用该接口，需先调用查询接口BleSecChkOrSetTask
***************************************************************************/
u8 BleChkCurSecState(u8 **cur_pin)
{
	*cur_pin = ble_work_stat.Ble_cur_pin;
	return ble_work_stat.Ble_cur_sec;
}

/***************************************************************************
* @fun_name     void BleMainMachine()
* @brief        Ble主任务机，放在主程序空间的主循环中，进行Ble任务处理
* @param[in]    None
* @param[out]   None
* @retval       None
* @other        None
***************************************************************************/
void BleMainMachine(void)
{
	if(ble_con_msg == BLE_DISCON_MSG)//蓝牙断开
	{
		ble_con_msg = BLE_CON_NOMSG;
		ble_work_stat.Ble_con_state = CON_END;
	}
	switch(s_BLE_main_state)
	{
		case S_BLE_IDLE:
		{
			if(ble_con_msg == BLE_CON_MSG)	//蓝牙连接消息
			{
				ble_con_msg = BLE_CON_NOMSG; 
				Gpio_SetIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);	//保持唤醒
				UartInit(BLE_UART_COM, BAUD38400, DATA_BIT_8, STOPBIT_1, UART_EVEN_PARITY, UART_LPUART_Disable);
				Set5msTimer(TIMER_5MS_LOWPOWER,20);//中断后延时100ms，防止无任务直接进入休眠(测试能否收到异常复位字符)
				if(Gpio_GetInputIO(BLE_CON_PORT, BLE_CON_PIN)==TRUE)//蓝牙连接
				{
					ble_work_stat.Ble_con_state = CON_ING;	//连接中
				}
			}
		}
		break;
		
		case S_BLE_MAIN_INIT:	//上电复位初始化
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleInitMachine();
			}
			else 
			{
				s_BLE_main_state = S_BLE_IDLE;
				if(g_ble_task_flag == BLE_TASK_SUCCESS)//防止蓝牙故障导致循环重启
				{
					SaveNewSoe(SOE_20_BLE_INIT, 0x50);//初始化正常
					FrameSetMsgApp(MsgBLE_AdvChange);//初始化成功,更新广播数据
					if(Sys_data_object.P3.function_switch.password_enable)	//配对密码功能是否开启
					{ 
						g_ble_task_flag = BLE_TASK_INIT;
						BleSecChkOrSetTask(SET_BLE_SEC);
					}
				}
				else
				{
					SaveNewSoe(SOE_20_BLE_INIT, 0xE0);//初始化异常
					BleForcePowerOff(BlePowerWrong);
					if(ble_reset_count<10)
					{
						FrameSetMsgApp(MsgBLE_Clktrim);//时钟校准
					}
				}
				g_ble_task_flag = BLE_TASK_INIT;			
			}
		}
		break;
#if BLE_CENTRAL_SLAVE_MOD		
		case S_BLE_MAIN_CENTRAL_SWITCH:	//切换主从模式
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleCentralSwitchMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
		
		case S_BLE_MAIN_SCAN:			//启动或停止扫描
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleScanMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
#endif
		
		case S_BLE_MAIN_CONNECT:			//建立或断开连接
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleConMgrMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
		
		case S_BLE_MAIN_NAME_MAC:		//修改蓝牙名称及mAC
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleChangeMACMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
		
		case S_BLE_MAIN_ADV_DATA:		//更新广播数据
		{
			if(flag_ble_force_power!=BlePowerOk)//断电状态
			{
				s_BLE_main_state = S_BLE_IDLE;	
				BleStartInitTask();//上电初始化蓝牙
				g_ble_task_flag = BLE_TASK_INIT;
			}
			else
			{
				if(BLE_TASK_INIT == g_ble_task_flag)
				{
					BleUpdateAavDataMachine();
				}
				else  
				{
					s_BLE_main_state = S_BLE_IDLE;
					if(g_ble_task_flag==BLE_TASK_FAIL)
					{
						SaveNewSoe(SOE_17_BLE_ADV_ERR, 0xE0);//更新广播异常
						FrameSetMsgApp(MsgBLE_Clktrim);//时钟校准完之后再重启蓝牙
					}
					g_ble_task_flag = BLE_TASK_INIT;
				}
			}
		}
		break;
		
		case S_BLE_MAIN_ADV_PARAM:		//更新广播参数
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleChangeAdvParasMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
		
		case S_BLE_MAIN_KEY_WORD:		//更新关键字
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleSetClearKeyWordMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
#if BLE_CENTRAL_SLAVE_MOD		
		case S_BLE_MAIN_WHITE_LIST:		//更新MAC白名单
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleMacWhiteListMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
#endif
		case S_BLE_MAIN_CHK_STATUS:	//查询主从模式及连接状态
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleChkStatusMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break;
		
		case S_BLE_MAIN_SEC_PIN:	//查询或设置SEC及PIN
		{
			if(BLE_TASK_INIT == g_ble_task_flag)
			{
				BleSecPinMachine();
			}
			else 
			{
				g_ble_task_flag = BLE_TASK_INIT;
				s_BLE_main_state = S_BLE_IDLE;
			}
		}
		break; 
		
		default:
			g_ble_task_flag = BLE_TASK_INIT;
			s_BLE_main_state = S_BLE_IDLE;
			break;
	}
}

/***************************************************************************
* @fun_name		void BleForcePowerOff(void)
* @brief		BLE强制断电
* @param[in]	None
* @param[out]	None
* @retval		None
* @other		None
***************************************************************************/
void BleForcePowerOff(TYP_POWER_STATUS data)
{
	stc_gpio_cfg_t stcGpioCfg;

	DDL_ZERO_STRUCT(stcGpioCfg);
    //串口引脚下拉输入
    stcGpioCfg.enDir = GpioDirIn;    ///< 端口方向配置->输入
    stcGpioCfg.enDrv = GpioDrvL;     ///< 端口驱动能力配置->低驱动能力
    stcGpioCfg.enPu = GpioPuDisable; 
    stcGpioCfg.enPd = GpioPdEnable;  //端口下拉使能
    stcGpioCfg.enOD = GpioOdDisable; ///< 端口开漏输出配置->开漏输出关闭
    stcGpioCfg.enCtrlMode = GpioAHB; ///< 端口输入/输出值寄存器总线控制模式配置->AHB
    Gpio_Init(LPUART1_TX_PORT, LPUART1_TX_PIN, &stcGpioCfg);	
    Gpio_Init(LPUART1_RX_PORT, LPUART1_RX_PIN, &stcGpioCfg);
	
	Gpio_ClrIO(LPUART1_TX_PORT, LPUART1_TX_PIN);
	Gpio_ClrIO(LPUART1_RX_PORT, LPUART1_RX_PIN);
	//唤醒引脚下拉输入
	Gpio_Init(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN, &stcGpioCfg);
	Gpio_ClrIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);	//不唤醒
	//连接状态引脚下拉输入
	Gpio_Init(BLE_CON_PORT, BLE_CON_PIN, &stcGpioCfg);
	Gpio_ClrIO(BLE_CON_PORT, BLE_CON_PIN);	
	//供电引脚开漏输出低
    stcGpioCfg.enDir = GpioDirOut;    ///< 端口方向配置->输出
    stcGpioCfg.enDrv = GpioDrvL;      ///< 端口驱动能力配置->低驱动能力
    stcGpioCfg.enPu = GpioPuDisable;  ///< 端口上下拉配置->无
    stcGpioCfg.enPd = GpioPdDisable;
    stcGpioCfg.enOD = GpioOdDisable;  ///< 端口开漏输出配置->开漏输出关闭
    stcGpioCfg.enCtrlMode = GpioAHB;  ///< 端口输入/输出值寄存器总线控制模式配置->AHB
	Gpio_Init(BLE_POW_PORT, BLE_POW_PIN, &stcGpioCfg);	//供电控制端口
	Gpio_ClrIO(BLE_POW_PORT, BLE_POW_PIN);	//不供电
	
////////////////////////////////////////////
	ble_work_stat.Ble_cur_mode = SLAVE_MODE;
	ble_work_stat.Ble_scan_state = SCAN_END;
	ble_work_stat.Ble_con_state = CON_END;
	s_BLE_init_state = S_BLE_IDLE;			//上电初始化状态机状态
	s_BLE_conmgr_state = S_BLE_IDLE;		//连接管理状态
#if BLE_CENTRAL_SLAVE_MOD	
	s_BLE_scan_state = S_BLE_IDLE;			//扫描状态机
	s_BLE_mode_switch_state = S_BLE_IDLE;
	s_BLE_white_list_state =  S_BLE_IDLE;
#endif
	s_BLE_at_requeset_state = S_BLE_IDLE;
	s_BLE_change_key_word_state = S_BLE_IDLE;
	s_BLE_update_adv_data_state = S_BLE_IDLE;
	s_BLE_change_mac_state = S_BLE_IDLE;
	s_BLE_change_adv_para_state =  S_BLE_IDLE;
	s_BLE_chk_status_state =  S_BLE_IDLE;
	s_BLE_sec_status_state = S_BLE_IDLE;
	
	flag_ble_force_power=data;//断电状态
}




///*************************************************
//Function:void Ble_TX_Sleep_Init(void)
//Description: 睡眠时TX初始化为外部中断
//Input:  None
//Return: None
//Others:	处于MainSpace，第一类接口：上电初始化接口。
//*************************************************/
//void Ble_TX_Sleep_Init(void)
//{
//	#if HDSC_HC32_TYPE == HDSC_HC32L13x
//	gpio_cfg_t stcGpioCfg;
//	#else
//	stc_gpio_cfg_t stcGpioCfg;
//	#endif
//    DDL_ZERO_STRUCT(stcGpioCfg);
//    stcGpioCfg.enDir = GpioDirIn;		///< 端口方向配置，输入
//    stcGpioCfg.enDrv = GpioDrvL;		///< 端口驱动能力配置->低驱动能力
//    stcGpioCfg.enPu = GpioPuEnable;		///< 端口上下拉配置->上拉
//    stcGpioCfg.enPd = GpioPdDisable;
//    stcGpioCfg.enOD = GpioOdDisable;	///< 端口开漏输出配置
//    stcGpioCfg.enCtrlMode = GpioAHB;	///< 端口输入/输出值寄存器总线控制模式配置->AHB
//	
//	GpioDriverInit(BLE_RX_PORT, BLE_RX_PIN, &stcGpioCfg);
//	Gpio_SetAfMode(BLE_RX_PORT, BLE_RX_PIN, GpioAf0);			//GPIO初始化里有
//	Gpio_ClearIrq(BLE_RX_PORT, BLE_RX_PIN);
//	Gpio_EnableIrq(BLE_RX_PORT, BLE_RX_PIN, GpioIrqFalling);	//下降沿中断，指示连接断开
////	EnableNvic(BLE_RXPORT_IRQ, BLE_RXPORT_PRIORITY, TRUE);		//
//}

/***************************************************************************
 * @fun_name     void BlePreSleep()
 * @brief        休眠前操作
 * @param[in]    None
 * @param[out]   None
 * @retval       None
 * @other        None
 ***************************************************************************/
void BlePreSleep(void)
{
	if(flag_ble_force_power==BlePowerOk)//正常工作供电状态
	{
		Gpio_ClrIO(BLE_LOWPOWER_PORT, BLE_LOWPOWER_PIN);	//lowpower引脚拉低
		UartPreSleep(BLE_UART_COM);
	}
}

/***************************************************************************
 * @fun_name    void BleWakeSleep()
 * @brief        休眠后唤醒
 * @param[in]    None
 * @param[out]   None
 * @retval       None
 * @other        None
 ***************************************************************************/
void BleWakeSleep(void)
{
}

/***************************************************************************
 * @fun_name     u8 BleIfIdle(void)
 * @brief        查询模块的空闲状态
 * @param[in]    None
 * @param[out]   None
 * @retval       None
 * @other        g_s_Nbiot_main_state(TASK_IDLE:空闲, TASK_IDLE：忙)
 ***************************************************************************/
u8 BleIfIdle(void)
{
    if (s_BLE_main_state == S_BLE_IDLE)
    {
        return TASK_IDLE;
    }
    else
    {
        return TASK_BUSY;
    }
}

/***************************************************************************
* @fun_name     u8 BleIfSleep(void)
* @brief        是否允许休眠
* @param[in]    None
* @param[out]   None
* @retval       TRUE: 允许  FALSE:不允许
* @other        None
***************************************************************************/
u8 BleIfSleep(void)
{
	//主状态机IDLE、未连接、未广播、非主机模式、连接引脚电平为低，允许休眠
    if ((s_BLE_main_state == S_BLE_IDLE) && (FALSE == Gpio_GetInputIO(BLE_CON_PORT, BLE_CON_PIN)))
    {
        return TASK_IDLE;
    }
    else
    {
        return TASK_BUSY;
    }
}

/***************************************************************************
* @fun_name     u8 CheckMetAddrIfInit(void)
* @brief        查询表地址是否已设置
* @param[in]    None
* @param[out]   None
* @retval       TRUE: 允许  FALSE:不允许
* @other        未设置表地址前，默认全部为0，蓝牙初始化时不改变蓝牙名称和MAC
***************************************************************************/
u8 CheckMetAddrIfInit(void)
{
	u8 temp_i = 0;
	for(temp_i = 0; temp_i < 7; temp_i++)
	{
		if(0 !=Sys_data_object.P1.met_addr[temp_i])
		{
			 return TRUE;
		}
	}
	return FALSE;
}

void BleGetFirmVerson(u8* verson_addr)
{
	*(verson_addr) = ble_work_stat.Ble_softverson[0];
	*(verson_addr + 1) = ble_work_stat.Ble_softverson[1];
}

void BleGetCurMacAddr(u8 *cur_mac)
{
	u8 i = 0;
	for(i = 0; i < 6; i++)
	{
		*(cur_mac + i) = ble_work_stat.Ble_mac[i];
	}
}
void BleClearResetCount(void)
{
	ble_reset_count=0;
}
TYP_POWER_STATUS BleGetPowerState(void)
{
	return flag_ble_force_power;
}
/****************************************************************************
//以下中断函数内容根据实际需要选择使用，如PORT口与其他功能共用，可移至其他地方
//中断接口
****************************************************************************/
///*************************************************
//Function:void BLE_CONorRX_IRQHandler(void)
//Description: 蓝牙连接和接收中断函数
//Input:  None
//Return: None
//Others:
// *************************************************/
void BLE_CONorRX_IRQHandler(void)
{
	if (TRUE == Gpio_GetIrqStatus(BLE_CON_PORT, BLE_CON_PIN))	//蓝牙连接Connect_Detect
	{
		Gpio_ClearIrq(BLE_CON_PORT, BLE_CON_PIN);
		if(Gpio_GetInputIO(BLE_CON_PORT, BLE_CON_PIN))			//高电平表示有连接
		{
			ble_con_msg = BLE_CON_MSG;
		}
		else
		{
			ble_con_msg = BLE_DISCON_MSG;
		}
	}
}

UNION_4U8TOU32 net_state_data;
u32 sys_get_net_state(void)
{
	net_state_data.data_buf[0] = 4;//蓝牙状态标志
	net_state_data.data_buf[1] = flag_ble_force_power;//供电状态:0,正常供电;1,故障强制断电;2,厂区模式断电状态
	net_state_data.data_buf[2] = ble_reset_count;//蓝牙当日已复位次数
	return net_state_data.datas;;
}

#ifdef	__cplusplus
}
#endif
#endif
