/************************************************************************************
 * @Copyright (c)    :(C)2017, Qindao ieslab Co., Ltd
 * @FileName   	     :pic24_nb_driver.c
 * @Author           :QDIES PLATFORM TEAM
 * @Version          :V1.0
 * @Date             :2017-03-01
 * @Description     :
 ************************************************************************************/
#include "sys_config.h"
#ifdef NB_MODULE_BC25
#ifdef	__cplusplus
extern "C"
{
#endif

#include "nb_uart_driver_bc25.h"
#include "nb_driver_bc25.h"
#include "stdio.h"
#include <time.h>
#include "UWater_timer1uS_driver.h"
#include "UWater_uart_driver.h"
#include "UWater_Rtcc_Driver.h"
#include "UWater_frame_app.h"
#include "UWater_Adc_driver.h"
#include "nb_upload_monitor.h"
/********************************变量定义************************************/
NBIOT_PARA Nbiot_Para;
NBIOT_MSG Nbiot_Msg;
static NBIOT_SEND_DATA Nbiot_Send_Data;
//static u8 *g_s_csq_value;

//状态变量(各个状态机运行的状态变量)
u8 g_s_nbiot_main_state = NBIOT_S_IDLE;
//u8 s_send_state;

//任务标志位
u8 g_s_nbiot_task_flag = TASK_INIT;
u8 g_s_nbiot_mode_flag = NO_NBIOT_TASK;
u8 g_s_nbiot_send_type;
u8 g_s_nbiot_read_ccid_flag = FALSE;
u8 g_s_nbiot_read_ECL_flag = FALSE;
u8 flag_clear_ncsearfcn = 0;
u8 nb_power_flag = FALSE;
u8 s_init_state = S_INIT_POWER_ON;
u8 s_coap_connect_state = S_COAP_CONNECT_START;
u8 s_udp_connect_state = S_UDP_CONNECT_START;
u8 s_coap_send_state = S_SEND_START;
u8 s_udp_send_state = S_SEND_START;
u8 s_power_off_state = S_START;
char c_AT_NMGS[40 + UP_BUF_SIZE*2];//发送数据长度较小

static const char* c_AT_NUESTATS = "AT+QENG=0\r";
static const char* c_AT_CCLK = "AT+CCLK?\r"; //查询基站时间
//ip地址和端口指针
unsigned char *coap_ip;
u16 coap_port;
unsigned char *udp_ip1;
u16 udp_port1;
unsigned char *udp_ip2;
u16 udp_port2;
u8 nbiot_temp_connect_type=NBIOT_CONNECT_COAP;
//PSM状态
TYP_PSM_STATE psm_model_state = PSM_STATE_OUT;
TYP_PSM_WAKEUP_STATE s_psm_wakeup_state = PSM_WKUPSTA_IDLE;
TYP_PSM_SLEEP_STATE s_psm_sleep_state = PSM_SLPSTA_IDLE;
//PSM异常检测
static u8 s_psm_adc_done = 0; // AD装换结果完成标志
static u32 s_psm_adc_result = 0; // AD转换后结果存放
/*****************************内部功能状态机***********************************/
void NbiotInitMachine(void);
void CoapConnectMachine(void);
void UdpConnectMachine(void);
void CoapSendDataMachine(void);
void UdpSendDataMachine(void);
void NbiotPowerOffMachine(void);
void UdpReadDataMachine(void);
//static void NbiotMsgDeal(void);
void NbiotReadECLSNRMachine(void);
void StartUdpSendData(void);
void sys_get_three_code (void);
void OnenetConnectMachine(void);
void OneNetSendDataMachine(void);
void StartOnenetAckRev(void);
void NbiotRevAckMachine(void);
/*****************************内部定时器接口**********************************/
void set_timer_1s(u16 time);
u16 check_timer_1s(void);
void set_timer_1ms(u16 time);
u16 check_timer_1ms(void);
void CoapStartConnect(void);
void StartCoapSendData(void);

void StartNbiotInit(void);
void UdpStartConnect(u8 udp_num);

void OneNetStartConnect(void);
void StartOnenetSendData(void);

void Psm_Wakup_Machine(void);
void Psm_Sleep_Machine(void);
/*****************************外部接口****************************************/
void NB_Power_Disable(void) 
{
	Gpio_WriteOutputIO(BAT_NB_PORT, BAT_NB_PIN, FALSE);
	nb_power_flag = FALSE;
}

void NB_Power_Enable(void)  
{
	Gpio_WriteOutputIO(BAT_NB_PORT, BAT_NB_PIN, TRUE);
	nb_power_flag = TRUE;
}

u8 If_NB_Poweron(void)
{    
	return nb_power_flag;    
}
/***************************************************************************
* @fun_name     void NbModuleIOInit(void)
* @brief        模块供电IO、模块复位、电源、PSM唤醒引脚初始化
***************************************************************************/
void NbModuleIOInit(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(BAT_NB_PORT, BAT_NB_PIN, &stcGpioCfg);  //模块供电IO
    Gpio_Init(RSTN_NB_PORT, RSTN_NB_PIN, &stcGpioCfg);
    Gpio_Init(NB_PSM_WAKE_PORT, NB_PSM_WAKE_PIN, &stcGpioCfg);
    Gpio_Init(PWR_NB_PORT, PWR_NB_PIN, &stcGpioCfg);   //电源控制脚
    Gpio_WriteOutputIO(BAT_NB_PORT, BAT_NB_PIN, FALSE);
    Gpio_WriteOutputIO(PWR_NB_PORT, PWR_NB_PIN, FALSE);
	Gpio_WriteOutputIO(RSTN_NB_PORT, RSTN_NB_PIN, FALSE); 
	Gpio_WriteOutputIO(NB_PSM_WAKE_PORT , NB_PSM_WAKE_PIN, FALSE);
}
/***************************************************************************
 * @fun_name     void NbiotMainMachine()
 * @brief        NBIOT主任务机，放在主程序空间的主循环中，进行NBIOT任务处理
 ***************************************************************************/
void NbiotMainMachine(void)
{
    switch (g_s_nbiot_main_state)
    {
        case NBIOT_S_IDLE:
		{
			//沈阳规约修改，udp下发指令和应答帧间隔太短，需要主动查询数据
			/*if(TRUE == UdpIfNeedReadDataBc25(NBIOT_CONNECT_UDP1))
			{
				ClearUdpReadDataFlag(NBIOT_CONNECT_UDP1);
				SetRcvDataType(NB_RCV_UDP1_DATA);
				g_s_nbiot_main_state = NBIOT_READ_UDP_DATA;
			}
			else if(TRUE == UdpIfNeedReadDataBc25(NBIOT_CONNECT_UDP2))
			{
				ClearUdpReadDataFlag(NBIOT_CONNECT_UDP2);
				SetRcvDataType(NB_RCV_UDP2_DATA);
				g_s_nbiot_main_state = NBIOT_READ_UDP_DATA;
			}
			else if(TRUE  == Check_Udp_Data_Received())
			{
				Clear_Udp_Rec_Data_Flag();
				g_s_nbiot_main_state = NBIOT_READ_UDP_DATA;
			}
			else*/
			if(TRUE == NbiotGetRevAck())//收到ONNET下发的数据,先进入应答流程应答一下
			{
				ClearNbiotGetRevAck();
				StartOnenetAckRev();
				g_s_nbiot_main_state = NBIOT_REV_ACK;
			}
			else if(FrameCheckMsgApp(Msg_PsmPowerCheck))
			{
				FrameClearMsgApp(Msg_PsmPowerCheck);
				if(psm_model_state == PSM_STATE_SLEEP)
				{
					NbiotPsmCheckTask();
				}
			}
		}
        break;

        case NBIOT_POWER_INIT:
        {
            if (TASK_INIT == g_s_nbiot_task_flag) //如果是初始状态
            {
                NbiotInitMachine(); //模块初始化状态机
            }
            else if (TASK_SUCCESS == g_s_nbiot_task_flag) //任务成功
            {
				u8 temp_iccid_buf[20];
                NbiotGetICCID((char*)temp_iccid_buf); //中国移动的为:898600;898602;898604;898607;898608 中国电信898603;898611
				Nbiot_Para.Telecom = SIM_CARD_TELECOM;//电信卡
				if(temp_iccid_buf[4]=='0')
				{
				    if((temp_iccid_buf[5]=='0')||(temp_iccid_buf[5]=='2')||(temp_iccid_buf[5]=='4')||(temp_iccid_buf[5]=='7')||(temp_iccid_buf[5]=='8'))
					{
					    Nbiot_Para.Telecom = SIM_CARD_MOBILE;
					}
				}
                Nbiot_Para.net_state = NB_ON_LINE;
				g_s_nbiot_task_flag = TASK_INIT;
				g_s_nbiot_main_state = NBIOT_S_IDLE;
            }
            else //任务失败
            {
				*Nbiot_Send_Data.state = NBIOT_ERROR;
                g_s_nbiot_task_flag = TASK_INIT; 
                g_s_nbiot_main_state = NBIOT_S_IDLE; 
            }
        }
        break;

		case NBIOT_NET_OPEN:
		{
			if (TASK_INIT == g_s_nbiot_task_flag)
            {
				if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP1)
				{
					UdpConnectMachine();
				}
				else if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP2)
				{
					UdpConnectMachine();
				}
				else
				{
					if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
					{
						OnenetConnectMachine();//与ONNET平台建立连接状态机
					}
					else//电信卡
					{
						CoapConnectMachine(); //与主站建立连接状态机	
					}
				}
            }
            else if (TASK_SUCCESS == g_s_nbiot_task_flag)
            {
				if((Sys_data_object.P1.func_cfg_bytes[12]&0x80)&&(Sys_data_object.P1.func_cfg_bytes[12]&0x03)) //PSM模式上报判断
				{
					psm_model_state = PSM_STATE_WAKE; 
				}
				else
				{
					psm_model_state = PSM_STATE_OUT; 
				}
				if(nbiot_temp_connect_type == NBIOT_CONNECT_COAP)
				{
					 Nbiot_Para.coap_state = CONNECT_ON_LINE;	
				}
				else if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP1)
				{
					 Nbiot_Para.udp1_state = CONNECT_ON_LINE;
				}
				else if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP2)
				{
					 Nbiot_Para.udp2_state = CONNECT_ON_LINE;
				}
				g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE;
            }
            else
            {
                g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE; 
            }
		}
		break;

		case NBIOT_DATA_SEND:
        {
			if (g_s_nbiot_task_flag == TASK_INIT)
			{
				if(g_s_nbiot_send_type == SEND_TYPE_COAP)
				{
					if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
					{
						OneNetSendDataMachine();
					}
					else//电信卡
					{
						CoapSendDataMachine(); //数据发送状态机
					}
				}
				else if(g_s_nbiot_send_type == SEND_TYPE_UDP1)
				{
					UdpSendDataMachine(); //数据发送状态机
				}
				else if(g_s_nbiot_send_type == SEND_TYPE_UDP2)
				{
					UdpSendDataMachine(); //数据发送状态机
				}
				else
				{
					g_s_nbiot_task_flag = TASK_INIT;
					g_s_nbiot_main_state = NBIOT_S_IDLE; 
				}
			}
			else//发送完毕回到空闲状态
			{
				g_s_nbiot_task_flag = TASK_INIT;
				g_s_nbiot_main_state = NBIOT_S_IDLE; 
			}
        }
        break;

        case NBIOT_POWER_OFF:
        {
            if (TASK_INIT == g_s_nbiot_task_flag)
            {
                NbiotPowerOffMachine(); //断电关机
            }
            else
            {
				g_s_nbiot_mode_flag = NO_NBIOT_TASK;
                g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE;
                Nbiot_Para.net_state = NB_OFF_LINE;
				Nbiot_Para.coap_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp1_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
            }
        }
        break;

        case NBIOT_READ_ECL_SNR:
        {
            if (NB_ON_LINE == Nbiot_Para.net_state)
            {
                if (g_s_nbiot_task_flag == TASK_INIT)
                {
                    NbiotReadECLSNRMachine(); //读CSQ状态机，上行规约需要自检，其中一项就是读信号值，因此做成单独的状态机
                }
                else if (g_s_nbiot_task_flag == TASK_SUCCESS)
                {
                    *Nbiot_Send_Data.state = RSRP_SUCCESS;
                    g_s_nbiot_mode_flag = NO_NBIOT_TASK;
                    g_s_nbiot_task_flag = TASK_INIT;
                    g_s_nbiot_main_state = NBIOT_S_IDLE;
                }
                else
                {
                    g_s_nbiot_mode_flag = NO_NBIOT_TASK;
                    g_s_nbiot_task_flag = TASK_INIT;
                    g_s_nbiot_main_state = NBIOT_S_IDLE;
                }
            }
            else //如果不在线
            {
                if (TRUE == g_s_nbiot_read_ECL_flag)
                {
                    if (g_s_nbiot_task_flag == TASK_INIT)
                    {
                        NbiotReadECLSNRMachine(); //读CSQ状态机，上行规约需要自检，其中一项就是读信号值，因此做成单独的状态机
                    }
                    else if (g_s_nbiot_task_flag == TASK_SUCCESS)
                    {
                        g_s_nbiot_mode_flag = NO_NBIOT_TASK;
                        g_s_nbiot_task_flag = TASK_INIT;
                        g_s_nbiot_main_state = NBIOT_S_IDLE;
                    }
                    else
                    {
                        g_s_nbiot_mode_flag = NO_NBIOT_TASK;
                        g_s_nbiot_task_flag = TASK_INIT;
                        g_s_nbiot_main_state = NBIOT_S_IDLE; //应用层调用关机流程_
                    }
                }
                else
                {
                    g_s_nbiot_task_flag = TASK_INIT;
                    g_s_nbiot_main_state = NBIOT_POWER_INIT; //模块初始化
					StartNbiotInit();
                }
            }
        }
        break;
		/*
		case NBIOT_READ_UDP_DATA:
		{
            if (TASK_INIT == g_s_nbiot_task_flag)
            {
                UdpReadDataMachine();
            }
            else
            {
                g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE;
            }			
        }
        break;*/
		case NBIOT_REV_ACK:
		{
            if (TASK_INIT == g_s_nbiot_task_flag)
            {
                NbiotRevAckMachine(); 
            }
            else
            {
                g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE;
            }			
        }
        break;
		
		case NBIOT_PSM_WAKEUP:
		{
		    if (TASK_INIT == g_s_nbiot_task_flag)
            {
                Psm_Wakup_Machine(); 
            }
            else
            {
                g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE;
            }	
		}
		break;
		
		case NBIOT_PSM_SLEEP:
		{
			if (TASK_INIT == g_s_nbiot_task_flag)
            {
                Psm_Sleep_Machine(); 
            }
            else
            {
                g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_S_IDLE;
            }			
		}
        break;
		
        default:
        {
            g_s_nbiot_main_state = NBIOT_S_IDLE;
        }
        break;
    }
}
/***************************************************************************
 * @fun_name     u8 NbiotIfIdle()
 * @brief        查询模块的空闲状态
 ***************************************************************************/
u8 NbiotIfIdle(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
        return TASK_IDLE;
    }
    else
    {	
        return TASK_BUSY;
    }
}

/***************************************************************************
 * @fun_name     u8 NbiotIfOnline()
 * @brief        查询NBIOT是否在线
 ***************************************************************************/
u8 NbiotIfOnline(void)
{
    if (NB_ON_LINE == Nbiot_Para.net_state)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

/***************************************************************************
 * @fun_name     u8 ConncetIfOnline()
 * @brief        查询连接是否在线
 ***************************************************************************/
u8 ConncetIfOnline(u8 connect_type)
{  
	if(connect_type == NBIOT_CONNECT_COAP)
	{
		if (CONNECT_ON_LINE == Nbiot_Para.coap_state)
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	else if(connect_type == NBIOT_CONNECT_UDP1)
	{
		if (CONNECT_ON_LINE == Nbiot_Para.udp1_state)
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	else if(connect_type == NBIOT_CONNECT_UDP2)
	{
		if (CONNECT_ON_LINE == Nbiot_Para.udp2_state)
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	return FALSE;
}

/***************************************************************************
 * @fun_name     void NbiotOnlineTask(u8 *state)
 * @brief        NBIOT上线任务
 * @param[in]    state:状态信息
 ***************************************************************************/
void NbiotOnlineTask(u8 *state)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
        if (!NbiotIfOnline())
        {
            if (NBIOT_S_IDLE == g_s_nbiot_main_state)
            {
                Nbiot_Send_Data.state = state; //地址拷贝
                *state = NBIOT_ING;
                g_s_nbiot_mode_flag = ONLINE_MODE;
				g_s_nbiot_task_flag = TASK_INIT;
                g_s_nbiot_main_state = NBIOT_POWER_INIT;
				StartNbiotInit();
            }
        }
        else
        {
            *state = NBIOT_ONLINE;
        }
    }
    else
    {
        *state = NBIOT_ERROR;
    }
}
/***************************************************************************
 * @fun_name     void NB_NetConnectStart
 * @brief        根据连接类型建立连接
 * @param[in]    state:状态信息
 ***************************************************************************/
void NB_NetConnectStart(unsigned char* temp_ip, u16 temp_port, u8 connect_type)
{
	if(connect_type == NBIOT_CONNECT_COAP)
	{
		coap_ip = temp_ip;
		coap_port = temp_port;
		if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
		{
			OneNetStartConnect(); 
		}
		else//电信卡
		{
			CoapStartConnect();	
		}
		nbiot_temp_connect_type = NBIOT_CONNECT_COAP;
	}
	else if(connect_type == NBIOT_CONNECT_UDP1)
	{
		udp_ip1 = temp_ip;
		udp_port1 = temp_port;
		UdpStartConnect(NBIOT_CONNECT_UDP1);
	}
	else if(connect_type == NBIOT_CONNECT_UDP2)
	{
		udp_ip2 = temp_ip;
		udp_port2 = temp_port;
		UdpStartConnect(NBIOT_CONNECT_UDP2);
	}
	g_s_nbiot_task_flag = TASK_INIT;
	g_s_nbiot_main_state = NBIOT_NET_OPEN;
}
void NbiotPsmWakeupTask(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
		g_s_nbiot_task_flag = TASK_INIT;
		g_s_nbiot_main_state = NBIOT_PSM_WAKEUP;
		s_psm_wakeup_state = PSM_WKUPSTA_START;
    }
}
void NbiotPsmSleepTask(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
		g_s_nbiot_task_flag = TASK_INIT;
		g_s_nbiot_main_state = NBIOT_PSM_SLEEP;
		s_psm_sleep_state = PSM_SLPSTA_START;
    }
}
void NbiotPsmCheckTask(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
		g_s_nbiot_task_flag = TASK_INIT;
		g_s_nbiot_main_state = NBIOT_PSM_SLEEP;
		s_psm_sleep_state = PSM_CHECK_START;
    }
}
/***************************************************************************
 * @fun_name     void NbiotSendTask(u8 *addr, u16 len, u8 send_type,u8 *state)
 * @brief        NBIOT数据发送任务
 * @param[in]    addr：内容的首地址 len：长度
 * @param[out]   state:状态信息
 * @retval       None
 * @other        state(NBIOT_ING：查询中, NBIOT_SUCCES：成功 其他：异常)
 ***************************************************************************/
void NbiotSendTask(u8 *addr, u16 len, u8 send_type,u8 *state)
{
    if ((NBIOT_S_IDLE == g_s_nbiot_main_state) && (len > 0) && (len <= UP_BUF_SIZE))
    {
        Nbiot_Send_Data.buf = addr; //地址拷贝
        Nbiot_Send_Data.len = len; //值拷贝
        Nbiot_Send_Data.state = state; //地址拷贝
        *state = NBIOT_ING;
        g_s_nbiot_mode_flag = SEND_MODE;
		g_s_nbiot_send_type = send_type;
		g_s_nbiot_task_flag = TASK_INIT;
		g_s_nbiot_main_state = NBIOT_DATA_SEND;
		StartNbiotSendData();
    }
    else
    {
        *state = NBIOT_ERROR;
    }
}
//获取发送类型
u8 GetNbiotSendType(void)
{
	return g_s_nbiot_send_type;	
}
/***************************************************************************
 * @fun_name     void NbiotReadCsqTask(u8 *out_csq,u8 *state)
 * @brief        NBIOT查询信号值任务
 * @param[in]    out_csq：存放数据地址
 * @param[out]   state:状态信息
 * @retval       None
 * @other        state(CSQ_ING：查询中, CSQ_SUCCES：成功 其他：异常)
 ***************************************************************************/
/*void NbiotUdpOpenTask(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
		if(!UdpIfOnline())
		{
			g_s_nbiot_mode_flag = ONLINE_MODE;
			g_s_nbiot_task_flag = TASK_INIT;
			g_s_nbiot_main_state = NBIOT_UDP_OPEN;
			UdpStartConnect();
		}        
    }   	
}*/

void NbiotReadECLSNRTask(u8 *state)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
        Nbiot_Send_Data.state = state;
        *state = ECL_SNR_ING;
        g_s_nbiot_mode_flag = READ_ECL_SNR;
        g_s_nbiot_read_ECL_flag = FALSE;
		g_s_nbiot_task_flag = TASK_INIT;
        g_s_nbiot_main_state = NBIOT_READ_ECL_SNR;
    }
    else
    {
        *state = ECL_SNR_ERROR;
    }
}


/***************************************************************************
 * @fun_name     u8 NbiotIfSleep()
 * @brief        是否允许休眠
 * @param[in]    None
 * @param[out]   None
 * @retval       TRUE: 允许  FALSE:不允许
 * @other        None
 ***************************************************************************/
u8 NbiotIfSleep(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

/***************************************************************************
 * @fun_name     void NbiotPreSleep()
 * @brief        休眠前操作
 * @param[in]    None
 * @param[out]   None
 * @retval       None
 * @other        None
 ***************************************************************************/
static void NbiotPreSleepNormal(void)
{
    NB_Power_Disable(); //切断电源
    UartPreSleep(NB_UART_COM);
    g_s_nbiot_main_state = NBIOT_S_IDLE;
	Nbiot_Para.coap_state = CONNECT_OFF_LINE;
	Nbiot_Para.udp1_state = CONNECT_OFF_LINE;
	Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
    Nbiot_Para.net_state = NB_OFF_LINE;
	
	//配置NB相关引脚
	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(BAT_NB_PORT, BAT_NB_PIN, &stcGpioCfg);  //模块供电IO
    Gpio_Init(RSTN_NB_PORT, RSTN_NB_PIN, &stcGpioCfg);
    Gpio_Init(NB_PSM_WAKE_PORT, NB_PSM_WAKE_PIN, &stcGpioCfg);
    Gpio_Init(PWR_NB_PORT, PWR_NB_PIN, &stcGpioCfg);   //电源控制脚
	
	Gpio_WriteOutputIO(BAT_NB_PORT, BAT_NB_PIN, FALSE);
    Gpio_WriteOutputIO(PWR_NB_PORT, PWR_NB_PIN, FALSE);
	Gpio_WriteOutputIO(RSTN_NB_PORT, RSTN_NB_PIN, FALSE); 
	Gpio_WriteOutputIO(NB_PSM_WAKE_PORT , NB_PSM_WAKE_PIN, FALSE);	
	
	Gpio_Init(LPUART1_TX_PORT, LPUART1_TX_PIN, &stcGpioCfg);
	Gpio_WriteOutputIO(LPUART1_TX_PORT, LPUART1_TX_PIN, FALSE);	//TX也配置为输出低
	
	stcGpioCfg.enDir = GpioDirIn;   //RX输入
	Gpio_Init(LPUART1_RX_PORT, LPUART1_RX_PIN, &stcGpioCfg);
}
static void NbiotPreSleepPsm(void)
{
    UartPreSleep(NB_UART_COM);
    g_s_nbiot_main_state = NBIOT_S_IDLE;
}
void NbiotPreSleep(void)
{
	if(Sys_data_object.P3.NBSleepMode == 1)//PSM模式休眠
	{
		NbiotPreSleepPsm();
	}
	else
	{
		NbiotPreSleepNormal();
	}
}
/***************************************************************************
 * @fun_name    void NbiotWakeSleep()
 * @brief        休眠后唤醒
 * @param[in]    None
 * @param[out]   None
 * @retval       None
 * @other        None
 ***************************************************************************/
void NbiotWakeSleep(void)
{
  
}

/******************************内部状态机***********************************/
void StartNbiotInit(void)
{
	s_init_state = S_INIT_POWER_ON;
}
/***************************************************************************
 * @fun_name     void NbiotInitMachine()
 * @brief        NBIOT初始化状态机
 * @param[in] 	 None
 * @param[out] 	 None
 * @retval     	 None
 * @other        None
 ***************************************************************************/
#define MODULE_POWER_DELAY_TIME 1000  		//mS
#define MODULE_RESET_DELAY_TIME 1000  		//mS
//AT+QBAND  AT+QBAND=1,5 //设置频段为 BAND 5
//中国移动的为:898600;898602;898604;898607 中国电信898603;898611
void NbiotInitMachine_BC25(void)
{
    static u8 s_at_error_count = 0; //记录AT错误或者指令超时次数  超过指定次数后认为任务失败
    
    static const char* c_AT = "AT\r";
    static const char* c_AT_IMEI = "AT+CGSN=1\r";
    static const char* c_AT_CIMI = "AT+CIMI\r";
    static const char* c_AT_ICCID = "AT+QCCID\r";//做了更改20200605
    static const char* c_AT_CMEE = "AT+CMEE=1\r"; //打开ERROR错误码显示
    static const char* c_AT_CPSMS = "AT+CPSMS=0\r"; //关闭PSM模式
    static const char* c_AT_NPTWEDRXS = "AT+CEDRXS=0\r"; //关闭eDRX模式
    static const char* c_AT_CSQ = "AT+CSQ\r"; //查询信号值
    static const char* c_AT_CEREG = "AT+CEREG?\r";
	static const char* c_AT_NCFG = "AT+NCFG=0,172800\r";//设置lifetime 平台端的生存周期 超过指定时间设备显示离线，48小时
    static const char* c_AT_CGATT = "AT+CGATT?\r";
    static u8 c_AT_CGDCONT_APN[APN_SIZE+50] = "AT+QCGDEFCONT=\"IP\",\""; //指定APN,定义数组大小为固定20字节+APN数组大小，再加预留空间

    switch (s_init_state)
    {
        case S_INIT_POWER_ON://NB模块送电
        {  
			NbModuleIOInit();  //初始化默认模块断电
            UartInit(NB_UART_COM, BAUD9600, DATA_BIT_8, STOPBIT_1, UART_NONE_PARITY,UART_LPUART_Disable);	
            RSTN_NB_HIG();
            PWR_NB_LOW();//PWR_NB_HIG();
            NB_Power_Enable(); 						
            set_timer_1ms(5*MODULE_POWER_DELAY_TIME);//开机等待5秒钟,等SIM卡初始化完成
            s_init_state = S_INIT_POWER_ON_WAIT;
        }
        break;

//        case S_INIT_PWRKEY_LOW://NB模块送电
//        {
//            if (!check_timer_1ms())
//            {
//                PWR_NB_LOW();
//                s_init_state = S_INIT_PWRKEY_HIGH;
//                set_timer_1ms(MODULE_RESET_DELAY_TIME*4);
//            }
//        }
//        break;

//        case S_INIT_PWRKEY_HIGH://NB模块送电
//        {
//            if (!check_timer_1ms())
//            {
//                PWR_NB_HIG();     //高电平
//				set_timer_1s(5);
//				s_init_state = S_INIT_POWER_ON_WAIT;
//            }
//        }
//        break;


        case S_INIT_POWER_ON_WAIT://等待模块搜网注册延时
        {
            if (!check_timer_1ms())
            {
                s_at_error_count = 0; //AT指令错误次数清零
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
				if(getUploadControlPara(UP_AT_SIMPLE)!=AT_SIMPLE_NULL)
				{ 
					s_init_state = S_INIT_ASK_CEREG;
				}
				else
				{
					s_init_state = S_INIT_ATS;
				}
            }
        }
        break;

        case S_INIT_ATS://发送"AT" 确认模块正常运行
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT, strlen(c_AT), cst_AT_No_AT);
                s_init_state = S_INIT_ATS_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_INIT_ATS_R://等待"AT"应答
        {
            if (NbiotCheckAtAck() == UART_OK)//返回正确的应答
            {
                s_at_error_count = 0;
                s_init_state = S_INIT_ASK_IMEI; //下一步开始查询IMEI
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR)) //应答超时或者错误
            {
                if (++s_at_error_count >= NUM_AT_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_INIT_ASK_IMEI; //下一步开始查询IMEI
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ATS;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_INIT_ASK_IMEI: //开始查询IMEI号
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_IMEI, strlen(c_AT_IMEI), cst_AT_No_AT_IMEI);
                s_init_state = S_INIT_ASK_IMEI_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); 
            }
        }
        break;

        case S_INIT_ASK_IMEI_R://等待IMEI应答
        {
            if (NbiotCheckAtAck() == UART_OK)//返回正确的应答
            {
                s_at_error_count = 0;
                s_init_state = S_INIT_ASK_CIMI;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_CIMI_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_INIT_ASK_CIMI;
					set_timer_1ms(2 * AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ASK_IMEI;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_INIT_ASK_CIMI://开始查询CIMI
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CIMI, strlen(c_AT_CIMI), cst_AT_No_AT_CIMI);
                s_init_state = S_INIT_ASK_CIMI_R;
                set_timer_1ms(6*AT_COMMAND_RECEIVE_WAIT_TIME);//去掉开机延时后,等待SIM卡初始化较长
            }
        }
        break;

        case S_INIT_ASK_CIMI_R://等待CIMI应答
        {
            if (NbiotCheckAtAck() == UART_OK)//返回正确的应答
            {
                s_at_error_count = 0;
                s_init_state = S_INIT_ASK_ICCID; //开始查询ICCID
                set_timer_1ms(2*AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_CIMI_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_INIT_ASK_ICCID; //开始查询ICCID
					set_timer_1ms(2*AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ASK_CIMI;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_INIT_ASK_ICCID://开始查询ICCID
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_ICCID, strlen(c_AT_ICCID), cst_AT_No_AT_ICCID);
                s_init_state = S_INIT_ASK_ICCID_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_INIT_ASK_ICCID_R://等待ICCID应答
        {
            if (NbiotCheckAtAck() == UART_OK)//返回正确的应答
            {
                s_at_error_count = 0;
                //将IMEI IMSI ICCID 转换并拷贝到全局RAM
                 sys_get_three_code();
                 s_init_state = S_INIT_CMEE; //下一步打开ERROR错误代码显示
                 set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_ICCID_ERROR)
                {
                    s_at_error_count = 0;
                    s_init_state = S_INIT_CMEE; //下一步打开ERROR错误代码显示
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ASK_ICCID;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_INIT_CMEE: //
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CMEE, strlen(c_AT_CMEE), cst_AT_No_AT_CMEE);
                s_init_state = S_INIT_CMEE_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_INIT_CMEE_R://等待CMEE应答
        {
            if (NbiotCheckAtAck() == UART_OK)//返回正确的应答
            {
                s_at_error_count = 0;
                s_init_state = S_TCP_CPSMS;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_CMEE_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_TCP_CPSMS;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_CMEE;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_TCP_CPSMS://设置关闭或打开PSM模式
        {
            if (!check_timer_1ms())
            {
				NbiotUartSend((u8*) c_AT_CPSMS, strlen(c_AT_CPSMS), cst_AT_No_AT_CPSMS);//关闭PSM
                s_init_state = S_TCP_CPSMS_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_TCP_CPSMS_R:
        {
            if (NbiotCheckAtAck() == UART_OK)//应答正确-下一步
            {
                s_at_error_count = 0;
                s_init_state = S_TCP_NPTWEDRXS;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_CPSMS_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_TCP_NPTWEDRXS;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_TCP_CPSMS;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_TCP_NPTWEDRXS://关闭eDRX模式
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_NPTWEDRXS, strlen(c_AT_NPTWEDRXS), cst_AT_No_AT_NPTWEDRXS);
                s_init_state = S_TCP_NPTWEDRXS_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_TCP_NPTWEDRXS_R://关闭eDRX模式 --等待应答
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
                s_init_state = S_INIT_AT_CGDCONT;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_NPTWEDRXS_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_INIT_AT_CGDCONT;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_TCP_NPTWEDRXS;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_INIT_AT_CGDCONT:
        {
            if(!check_timer_1ms())
            {
                u8 ip_apn = 20;
            
                int i;
				for(i = 0; i < Sys_data_object.P1.apn[1]; i++)
				{
					c_AT_CGDCONT_APN[ip_apn++] = Sys_data_object.P1.apn[2 + i];
				}
				c_AT_CGDCONT_APN[ip_apn++] = '"';
				c_AT_CGDCONT_APN[ip_apn++] = '\r';
				NbiotUartSend((u8*) c_AT_CGDCONT_APN, ip_apn, cst_AT_No_AT_CGDCONT);
				set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
				s_init_state = S_INIT_AT_CGDCONT_R;
            
            }
        }
        break;

        case S_INIT_AT_CGDCONT_R:
        {
            if (NbiotCheckAtAck() == UART_OK) 
            {
                s_at_error_count = 0;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
                s_init_state = S_INIT_ASK_CSQ;
            }
            else if ((NbiotCheckAtAck() == UART_ERROR) || (!check_timer_1ms()))
            {
                s_at_error_count++;
                if (s_at_error_count >= AT_ERROR)
                {
                    s_at_error_count = 0;
                    set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
					s_init_state = S_INIT_ASK_CSQ;
                }
                else
                {
                    s_init_state = S_INIT_AT_CGDCONT;
                }
            }
        }
        break;

        case S_INIT_ASK_CSQ://查询CSQ
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CSQ, strlen(c_AT_CSQ), cst_AT_No_AT_CSQ);
                s_init_state = S_INIT_ASK_CSQ_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_INIT_ASK_CSQ_R://等待CSQ应答
        {
            if (NbiotCheckAtAck() == UART_OK)//返回正确的应答
            {
                
                s_at_error_count = 0;
                
                s_init_state = S_INIT_ASK_CEREG; //开始查询CEREG
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_CSQ_ERROR)
                {
                    
					s_at_error_count = 0;
					
					s_init_state = S_INIT_ASK_CEREG; //开始查询CEREG
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ASK_CSQ;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_INIT_ASK_CEREG://开始查询CEREG
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CEREG, strlen((const char*) c_AT_CEREG), cst_AT_No_AT_CEREG);
                s_init_state = S_INIT_ASK_CEREG_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME * 2); 
            }
        }
        break;

        case S_INIT_ASK_CEREG_R://等待CEREG应答
        {
            if (NbiotCheckAtAck() == UART_OK)//正确应答
            {
                s_at_error_count = 0;
                s_init_state = S_INIT_SET_NCFG;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
            {
				/*u8 NB_login_ask_times = FrameCheckParaApp(FramePara_NbParaLoginAckTimes);
                if (NB_login_ask_times < 30)
                {
                    NB_login_ask_times = 30;
                }
                if (NB_login_ask_times > 150)
                {
                    NB_login_ask_times = 150;
                }
                if (++s_at_error_count >= NB_login_ask_times)*/
				if (++s_at_error_count >= NUM_AT_CEREG_ERROR)
                {
                    s_at_error_count = 0;
					s_init_state = S_INIT_SET_NCFG;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ASK_CEREG;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
		case S_INIT_SET_NCFG:
		{
		    if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_NCFG, strlen((const char*) c_AT_NCFG), cst_AT_No_AT);
                s_init_state = S_INIT_SET_NCFG_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME*2); 
            }	
		} 
		break;
		case S_INIT_SET_NCFG_R:
		{
		    if (NbiotCheckAtAck() == UART_OK)//正确应答
            {
				s_at_error_count = 0;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                s_init_state = S_INIT_ASK_CGATT;
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
			{
			    s_at_error_count = 0;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                s_init_state = S_INIT_ASK_CGATT;		
			}
		}
		break;
        case S_INIT_ASK_CGATT://开始查询CGATT
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CGATT, strlen(c_AT_CGATT), cst_AT_No_AT_CGATT_how);
                s_init_state = S_INIT_ASK_CGATT_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME*2); 
            }
        }
        break;

        case S_INIT_ASK_CGATT_R://等待CGATT应答
        {
            if (NbiotCheckAtAck() == UART_OK)//正确应答
            {
				s_at_error_count = 0;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                s_init_state = S_INIT_ASK_NUESTATS;
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
            {
                u8 NB_login_ask_times = FrameCheckParaApp(FramePara_NbParaLoginAckTimes);
                if (NB_login_ask_times < 30)
                {
                    NB_login_ask_times = 30;
                }
                if (NB_login_ask_times > 150)
                {
                    NB_login_ask_times = 150;
                }
                if (++s_at_error_count >= NB_login_ask_times)
                {
                    s_at_error_count = 0;
					g_s_nbiot_task_flag = TASK_FAIL; //初始化失败
                    s_init_state = S_INIT_POWER_ON;
                }
                else
                {
                    s_init_state = S_INIT_ASK_CGATT;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
		case S_INIT_ASK_NUESTATS:
        {
			if(!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_NUESTATS, strlen(c_AT_NUESTATS), cst_AT_No_AT_NUESTATS);
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
                s_init_state = S_INIT_ASK_NUESTATS_R;
            }
        }
        break;

        case S_INIT_ASK_NUESTATS_R:
        {
			if (NbiotCheckAtAck() == UART_OK)
			{
				//返回正确的应答
				s_at_error_count = 0;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
				s_init_state = S_INIT_ASK_CCLK;
			}
			else if(!check_timer_1ms())
			{
				//返回错误的应答或者定时时间到
				s_at_error_count++;
				if (s_at_error_count >= NUM_AT_ECL_ERROR)
				{
					s_at_error_count = 0;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
					s_init_state = S_INIT_ASK_CCLK;
				}
				else
				{
					s_init_state = S_INIT_ASK_NUESTATS;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
				}
			}
        }
        break;
		
		case S_INIT_ASK_CCLK://开始查询网络时间
        {
            if(!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CCLK, strlen(c_AT_CCLK), cst_AT_No_AT_CCLK);
                s_init_state = S_INIT_ASK_CCLK_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_INIT_ASK_CCLK_R://等待应答
        {
            if (NbiotCheckAtAck() == UART_OK)//正确应答
            {
                s_at_error_count = 0;
                g_s_nbiot_task_flag = TASK_SUCCESS; //初始化成功
                s_init_state = S_INIT_POWER_ON; // 任务指针返回
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
            {
                if (++s_at_error_count >= NUM_AT_CCLK_ERROR)
                {
					s_at_error_count = 0;
					g_s_nbiot_task_flag = TASK_SUCCESS; //初始化成功
					s_init_state = S_INIT_POWER_ON; // 任务指针返回
                }
                else
                {
                    s_init_state = S_INIT_ASK_CCLK;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
        default:
        {
            s_at_error_count = 0;
			s_init_state = S_INIT_POWER_ON;
        }
        break;
    }
}
void NbiotInitMachine(void)
{
    NbiotInitMachine_BC25();
}
//
void CoapStartConnect(void)
{
	s_coap_connect_state = S_COAP_CONNECT_START;
}
/***************************************************************************
 * @fun_name     static void CoapConnectMachine()
 * @brief        连接Coap状态机
 ***************************************************************************/
void CoapConnectMachine_BC25(void)
{
    static u8 s_at_error_count = 0;
    unsigned char *nbiot_ip;
    u16 nbiot_port;
    static char c_AT_NCDP[50] = "AT+NCDPOPEN=\"117.060.157.137\",05683\r"; //
    static const char* c_AT_NCDP_CK = "AT+NMSTATUS?\r"; //
	
    switch (s_coap_connect_state)
    {
        case S_COAP_CONNECT_START: //任务开始
        {
            s_at_error_count=0;
            s_coap_connect_state = S_COAP_NCDP;
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        }
        break;

        case S_COAP_NCDP:
        {
            if (!check_timer_1ms())
            {
				u16 len = 13; //整条AT指令的长度，根据发送长度的位数来定
				nbiot_port = coap_port;//Sys_data_object.P1.server_port.datas;
				nbiot_ip = coap_ip;//Sys_data_object.P1.server_ip;

				//IP 的存储仍然使用水表原来格式，不保存“.”号，使用时加入
				int i;
				for (i = 0; i < 4; i++)
				{
					if (nbiot_ip[i] < 10)
					{
						c_AT_NCDP[len++] = nbiot_ip[i] + 0x30;
					}
					else if (nbiot_ip[i] < 100)
					{
						c_AT_NCDP[len++] = (nbiot_ip[i] / 10) + 0x30;
						c_AT_NCDP[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					else
					{
						c_AT_NCDP[len++] = (nbiot_ip[i] / 100) + 0x30;
						c_AT_NCDP[len++] = (nbiot_ip[i] / 10) % 10 + 0x30;
						c_AT_NCDP[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					c_AT_NCDP[len++] = '.';
				}
				len--; //消除多余的点号
				c_AT_NCDP[len++] = '\"';
				c_AT_NCDP[len++] = ',';
				c_AT_NCDP[len++] = ((nbiot_port) / 10000) + 0x30;
				c_AT_NCDP[len++] = (((nbiot_port) % 10000) / 1000) + 0x30;
				c_AT_NCDP[len++] = (((nbiot_port) % 1000) / 100) + 0x30;
				c_AT_NCDP[len++] = (((nbiot_port) % 100) / 10) + 0x30;
				c_AT_NCDP[len++] = ((nbiot_port) % 10) + 0x30;
				c_AT_NCDP[len++] = '\r';
				NbiotUartSend((u8*)c_AT_NCDP, len, cst_AT_No_AT_NCDP);
				set_timer_1s(35);
				s_coap_connect_state = S_COAP_NCDP_R;
            }
        }
        break;

        case S_COAP_NCDP_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count=0;
				s_coap_connect_state = S_COAP_NCDP_CK;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if (!check_timer_1s() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_NCDP_ERROR)//
                {
					s_at_error_count = 0;
					*Nbiot_Send_Data.state = NBIOT_ERROR;//返回失败
					s_coap_connect_state = S_COAP_CONNECT_START; 
					g_s_nbiot_task_flag = TASK_FAIL;
                }
                else
                {
                    s_coap_connect_state = S_COAP_NCDP;
                }
            }
        }
        break;

        case S_COAP_NCDP_CK:
        {
            if(!check_timer_1ms())
            {
				NbiotUartSend((u8*) c_AT_NCDP_CK, strlen(c_AT_NCDP_CK), cst_AT_No_AT_NCDP_CK);
				set_timer_1s(2);
				s_coap_connect_state = S_COAP_NCDP_CK_R;
            }
        }
        break;

        case S_COAP_NCDP_CK_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
               	*Nbiot_Send_Data.state = NBIOT_ONLINE;
				s_coap_connect_state = S_COAP_CONNECT_START; 
				g_s_nbiot_task_flag = TASK_SUCCESS;
            }
            else if((!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_NCDP_CK_ERROR)
                {
					s_at_error_count = 0;
					*Nbiot_Send_Data.state = NBIOT_ERROR;
					s_coap_connect_state = S_COAP_CONNECT_START; 
					g_s_nbiot_task_flag = TASK_FAIL; 
                }
                else
                {
                    s_coap_connect_state = S_COAP_NCDP_CK;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
        default:
        {
            s_coap_connect_state = S_COAP_CONNECT_START; //状态机回归初始状态
        }
        break;
    }
}
void CoapConnectMachine()
{
    CoapConnectMachine_BC25();
}
void StartNbiotSendData(void)
{
	if(g_s_nbiot_send_type == SEND_TYPE_COAP)
	{
		if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
		{
			StartOnenetSendData();
		}
		else//电信卡
		{
			StartCoapSendData(); //数据发送状态机
		}
	}
	else if(g_s_nbiot_send_type == SEND_TYPE_UDP1)
	{
		StartUdpSendData(); //数据发送状态机
		UdpStartCheckData();//查询UDP数据
	}
	else if(g_s_nbiot_send_type == SEND_TYPE_UDP2)
	{
		StartUdpSendData(); //数据发送状态机
		UdpStartCheckData();//查询UDP数据
	}
}

#if SEND_ACKID_ENABLE
u16 Send_AckID = 0;
#endif


//
void StartCoapSendData(void)
{
	s_coap_send_state = S_SEND_START;
}

void CoapSendDataMachine_BC25(void)
{
    static u8 s_at_error_count = 0; //AT指令累计发送失败次数
    static const u8 temp_AT_Buffer[]= {"AT+NMGS="};
    switch (s_coap_send_state)
    {
        case S_SEND_START:
        {
            s_coap_send_state = S_SEND_DATA; //收到数据立即进行数据发送，模块会报ERROR，因此延时1S，消除此ERROR
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        }
        break;

        case S_SEND_DATA:
        {
            if (!check_timer_1ms())
            {
                u16 len = 8; //整条AT指令的长度，根据发送长度的位数来定
                int i;
                for(i=0; i<8; i++)
                {
                    c_AT_NMGS[i]=temp_AT_Buffer[i];
                }
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len / 10000) + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 10000) / 1000 + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 1000) / 100 + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 100) / 10 + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 10) + 0x30;
                c_AT_NMGS[len++] = ',';
                //内容
                for (i = 0; i < Nbiot_Send_Data.len; i++)//获取发送数据内容
                {
                    if ((*(Nbiot_Send_Data.buf + i) >> 4) >= 0x0A)
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) >> 4) + 0x37;
                    }
                    else
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) >> 4) + 0x30;
                    }

                    if ((*(Nbiot_Send_Data.buf + i) & 0x0F) >= 0x0A)
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) & 0x0F) + 0x37;
                    }
                    else
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) & 0x0F) + 0x30;
                    }
                }
				if((Sys_data_object.P1.func_cfg_bytes[12]&0x80)&&(Sys_data_object.P1.func_cfg_bytes[12]&0x03)) //PSM模式上报判断
				{
						c_AT_NMGS[len++] = ',';
						c_AT_NMGS[len++] = '1';
						c_AT_NMGS[len++] = '0';
						c_AT_NMGS[len++] = '0';//c_AT_NMGS[len++] = '2';
						c_AT_NMGS[len++] = '\r';
						NbiotUartSend((u8*) c_AT_NMGS, len, cst_AT_No_AT_NMGS_ACKID);
				}
				else
				{
					if((Sys_data_object.P1.func_cfg_bytes[10] == 0x55)||(Sys_data_object.P3.ProductUploadFlag == 0x55))//ACK判上报成功
					{
						c_AT_NMGS[len++] = ',';
						c_AT_NMGS[len++] = '1';
						c_AT_NMGS[len++] = '0';
						c_AT_NMGS[len++] = '0';
						c_AT_NMGS[len++] = '\r';
						NbiotUartSend((u8*) c_AT_NMGS, len, cst_AT_No_AT_NMGS_ACKID);
					}
					else
					{
						c_AT_NMGS[len++] = '\r';
						NbiotUartSend((u8*) c_AT_NMGS, len, cst_AT_No_AT_NMGS);
					}
				}
                set_timer_1s(4);
                s_coap_send_state = S_SEND_DATA_R;
            }
        }
        break;

        case S_SEND_DATA_R:
        {
            if (NbiotCheckAtAck() == UART_OK) //返回正确的应答
            {
                s_at_error_count = 0;
                g_s_nbiot_task_flag = TASK_SUCCESS;
                *Nbiot_Send_Data.state = NBIOT_SUCCESS;
                s_coap_send_state = S_SEND_START;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= 1)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = NBIOT_ERROR;
                    g_s_nbiot_task_flag = TASK_FAIL;
                    s_coap_send_state = S_SEND_START;
                }
                else
                {
                    s_coap_send_state = S_SEND_DATA_R;
                }
            }
        }
        break;

        default:
        {
            s_coap_send_state = S_SEND_START;
        }
        break;
    }
}
void CoapSendDataMachine(void)
{
    CoapSendDataMachine_BC25();
}

//启动连接UDP
void UdpStartConnect(u8 udp_num)
{
	nbiot_temp_connect_type = udp_num;
	s_udp_connect_state = S_UDP_CONNECT_START;
}
/***************************************************************************
 * @fun_name     void UdpConnectMachine(void)
 * @brief        连接UDP状态机
 ***************************************************************************/
void UdpConnectMachine_BC25(void)
{
    static u8 s_at_error_count = 0;
    
	unsigned char *nbiot_ip;
    u16 nbiot_port;	
    static char c_AT_QIOPEN[100];// = "AT+QIOPEN=1,0,\"UDP SERVICE\",\"60.208.16.57\",0,8080,0\r"; //   
	static const char* c_AT_QICFG = "AT+QICFG=\"showlength\",1\r"; //显示接收数据长度
    switch (s_udp_connect_state)
    {
        case S_UDP_CONNECT_START: //任务开始
        {
            s_at_error_count=0;
            s_udp_connect_state = S_UDP_QICFG;
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        }
        break;
        case S_UDP_QICFG://设置显示接收数据长度
        {
            if (!check_timer_1ms())
            {
				NbiotUartSend((u8*) c_AT_QICFG, strlen(c_AT_QICFG), cst_AT_No_AT_QICFG);//设置是否显示可选长度参数
                s_udp_connect_state = S_UDP_QICFG_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_UDP_QICFG_R:
        {
            if (NbiotCheckAtAck() == UART_OK)//应答正确-下一步
            {
                s_at_error_count = 0;
                s_udp_connect_state = S_UDP_QIOPEN;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= NUM_AT_QICFG_ERROR)
                {
                    s_at_error_count = 0;
					s_udp_connect_state = S_UDP_QIOPEN;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_udp_connect_state = S_UDP_QIOPEN;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_UDP_QIOPEN:
        {
            if (!check_timer_1ms())
            {
				u16 len = 21; //整条AT指令的长度，根据发送长度的位数来定
				char strings_temp[50];
				memset(c_AT_QIOPEN,0,sizeof(c_AT_QIOPEN));
				memset(strings_temp,0,sizeof(strings_temp));
				strcpy(c_AT_QIOPEN,"AT+QIOPEN=1,0,\"UDP\",\"");
				if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP1)
				{
					nbiot_port = udp_port1;
					nbiot_ip = udp_ip1;
					c_AT_QIOPEN[12] = '0';//更新socket
				}
				else if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP2)
				{
					nbiot_port = udp_port2;
					nbiot_ip = udp_ip2;
					c_AT_QIOPEN[12] = '1';//更新socket
				}
				//IP 的存储仍然使用水表原来格式，不保存“.”号，使用时加入
				for (int i = 0; i < 4; i++)
				{
					if (nbiot_ip[i] < 10)
					{
						c_AT_QIOPEN[len++] = nbiot_ip[i] + 0x30;
					}
					else if (nbiot_ip[i] < 100)
					{
						c_AT_QIOPEN[len++] = (nbiot_ip[i] / 10) + 0x30;
						c_AT_QIOPEN[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					else
					{
						c_AT_QIOPEN[len++] = (nbiot_ip[i] / 100) + 0x30;
						c_AT_QIOPEN[len++] = (nbiot_ip[i] / 10) % 10 + 0x30;
						c_AT_QIOPEN[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					c_AT_QIOPEN[len++] = '.';
				}
				len--; //消除多余的点号
				c_AT_QIOPEN[len++] = '\"';
				c_AT_QIOPEN[len++] = ',';
				c_AT_QIOPEN[len++] = ((nbiot_port) / 10000) + 0x30;
				c_AT_QIOPEN[len++] = (((nbiot_port) % 10000) / 1000) + 0x30;
				c_AT_QIOPEN[len++] = (((nbiot_port) % 1000) / 100) + 0x30;
				c_AT_QIOPEN[len++] = (((nbiot_port) % 100) / 10) + 0x30;
				c_AT_QIOPEN[len++] = ((nbiot_port) % 10) + 0x30;
				c_AT_QIOPEN[len++] = ',';
				c_AT_QIOPEN[len++] = '0';
				c_AT_QIOPEN[len++] = ',';
				c_AT_QIOPEN[len++] = '1'; //0: Buffer 模式; 1:Direct Push 模式
				c_AT_QIOPEN[len++] = '\r';

				len = strlen(c_AT_QIOPEN);              
				NbiotUartSend((u8*)c_AT_QIOPEN, len, cst_AT_No_AT_QIOPEN);
				set_timer_1ms(2*AT_COMMAND_RECEIVE_WAIT_TIME);
				s_udp_connect_state = S_UDP_QIOPEN_R;
            }
        }
        break;

        case S_UDP_QIOPEN_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count = 0;                
				//s_udp_connect_state = S_UDP_NUESTATS;
				s_udp_connect_state = S_UDP_Wait;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if (!check_timer_1ms() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= AT_ERROR)
                {
					//一般不会发生,肯定能查到返回结果
					s_at_error_count = 0;
					s_udp_connect_state = S_UDP_NUESTATS;
					//s_udp_connect_state = S_UDP_Wait;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_udp_connect_state = S_UDP_QIOPEN;
                }
            }
        }
        break;

		case S_UDP_NUESTATS:
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_NUESTATS, strlen(c_AT_NUESTATS), cst_AT_No_AT_NUESTATS);
                set_timer_1ms(2*AT_COMMAND_RECEIVE_WAIT_TIME);
                s_udp_connect_state = S_UDP_NUESTATS_R;
            }
        }
        break;

        case S_UDP_NUESTATS_R:
        {
			if (NbiotCheckAtAck() == UART_OK)
			{
				//返回正确的应答
				s_at_error_count = 0;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
				s_udp_connect_state = S_UDP_CCLK;
			}
			else if (!check_timer_1ms() || NbiotCheckAtAck() == UART_ERROR)
			{
				//返回错误的应答或者定时时间到
				s_at_error_count++;
				if (s_at_error_count >= NUM_AT_ECL_ERROR)
				{
					s_at_error_count = 0;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
					s_udp_connect_state = S_UDP_CCLK;
				}
				else
				{
					s_udp_connect_state = S_UDP_NUESTATS;	
				}
			}
        }
        break;
		
		case S_UDP_CCLK://开始查询网络时间
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CCLK, strlen(c_AT_CCLK), cst_AT_No_AT_CCLK);
                s_udp_connect_state = S_UDP_CCLK_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); 
            }
        }
        break;

        case S_UDP_CCLK_R://等待应答
        {
            if (NbiotCheckAtAck() == UART_OK)//正确应答
            {
                s_at_error_count = 0;
                s_udp_connect_state = S_UDP_Wait;
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
            {
                if (++s_at_error_count >= NUM_AT_CCLK_ERROR)
                {
                    s_at_error_count = 0;
                    s_udp_connect_state = S_UDP_Wait;
                }
                else
                {
                    s_udp_connect_state = S_UDP_CCLK;
                }
            }
        }
        break;
		
        case S_UDP_Wait:
        {
            if((!check_timer_1ms()))
            {
                s_at_error_count = 0;
                *Nbiot_Send_Data.state = NBIOT_ONLINE;
                s_udp_connect_state = S_UDP_CONNECT_START; //状态机回归初始状态
                g_s_nbiot_task_flag = TASK_SUCCESS; //到此为止任务成功
            }
        }
        break;

        default:
        {
            s_udp_connect_state = S_UDP_CONNECT_START; //状态机回归初始状态
        }
        break;
    }
}
void UdpConnectMachine(void)
{
   UdpConnectMachine_BC25();
}
//
void StartUdpSendData(void)
{
	s_udp_send_state = S_SEND_START;
}
//
void UdpSendDataMachine_BC25(void)
{
    static u8 s_at_error_count = 0; //AT指令累计发送失败次数
	static const u8 temp_AT_Buffer[]= {"AT+QISENDEX=0,"};
    switch (s_udp_send_state)
    {
        case S_SEND_START:
        {
            s_udp_send_state = S_SEND_DATA; //收到数据立即进行数据发送，模块会报ERROR，因此延时1S，消除此ERROR
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        }
        break;

        case S_SEND_DATA:
        {
            if (!check_timer_1ms())
            {
                u16 len = 14; //整条AT指令的长度，根据发送长度的位数来定
                int i;
			    for(i=0; i<14; i++)
                {
                    c_AT_NMGS[i]=temp_AT_Buffer[i];
                }
				if(g_s_nbiot_send_type == SEND_TYPE_UDP1)
				{
					c_AT_NMGS[12] = '0';//更新socket
				}
				else if(g_s_nbiot_send_type == SEND_TYPE_UDP2)
				{
					c_AT_NMGS[12] = '1';//更新socket
				}
				
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len / 10000) + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 10000) / 1000 + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 1000) / 100 + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 100) / 10 + 0x30;
                c_AT_NMGS[len++] = (Nbiot_Send_Data.len % 10) + 0x30;
                c_AT_NMGS[len++] = ',';
				c_AT_NMGS[len++] = '\"';
                //内容
								
                for (i = 0; i < Nbiot_Send_Data.len; i++)//获取发送数据内容
                {
                    if ((*(Nbiot_Send_Data.buf + i) >> 4) >= 0x0A)
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) >> 4) + 0x37;
                    }
                    else
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) >> 4) + 0x30;
                    }

                    if ((*(Nbiot_Send_Data.buf + i) & 0x0F) >= 0x0A)
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) & 0x0F) + 0x37;
                    }
                    else
                    {
                        c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) & 0x0F) + 0x30;
                    }
                }
				c_AT_NMGS[len++] = '\"';
                c_AT_NMGS[len++] = '\r';
                NbiotUartSend((u8*) c_AT_NMGS, len, cst_AT_No_AT_NMGS);
                set_timer_1s(4);
                s_udp_send_state = S_SEND_DATA_R;
            }
        }
        break;

        case S_SEND_DATA_R:
        {
            if (NbiotCheckAtAck() == UART_OK) //返回正确的应答
            {
                s_at_error_count = 0;
                g_s_nbiot_task_flag = TASK_SUCCESS;
                *Nbiot_Send_Data.state = NBIOT_SUCCESS;
                s_udp_send_state = S_SEND_START;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= 1)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = NBIOT_ERROR;
                    g_s_nbiot_task_flag = TASK_SUCCESS;
                    s_udp_send_state = S_SEND_START;
                }
                else
                {
					set_timer_1s(4);
                    s_udp_send_state = S_SEND_DATA;
                }
            }
        }
        break;

        default:
        {
            s_udp_send_state = S_SEND_START;
        }
        break;
    }
}
void UdpSendDataMachine(void)
{
	UdpSendDataMachine_BC25();
}
/*
void UdpReadDataMachine_BC25(void)
{
    static u8 s_error_count; //AT指令累计发送失败次数
    static u8 s_read_upd_data_state = S_START;
    static const char* c_AT_QIRD1 = "AT+QIRD=0,512\r";
	static const char* c_AT_QIRD2 = "AT+QIRD=1,512\r";
    switch (s_read_upd_data_state)
    {
        case S_START:
        {
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME*2);
            s_error_count = 0;
            s_read_upd_data_state = S_AT_QIRD;
        }
        break;

        case S_AT_QIRD:
        {
            if (!check_timer_1ms())
            {
				if(GetRcvDataType() == NB_RCV_UDP1_DATA)
				{
					 NbiotUartSend((u8*) c_AT_QIRD1, strlen((const char*) c_AT_QIRD1), cst_AT_No_AT_UPD_READ);
				}
				else if(GetRcvDataType() == NB_RCV_UDP2_DATA)
				{
					 NbiotUartSend((u8*) c_AT_QIRD2, strlen((const char*) c_AT_QIRD2), cst_AT_No_AT_UPD_READ);
				}
                set_timer_1ms(5*AT_COMMAND_RECEIVE_WAIT_TIME);
                s_read_upd_data_state = S_AT_QIRD_R;
            }
        }
        break;

        case S_AT_QIRD_R:
        {
			if (NbiotCheckAtAck() == UART_OK)
			{
				//返回正确的应答
				*Nbiot_Send_Data.state = QIRD_SUCCESS;
				g_s_nbiot_task_flag = TASK_SUCCESS;
				s_read_upd_data_state = S_START;								
			}
			else if (!check_timer_1ms())
			{
				//返回错误的应答或者定时时间到
				s_error_count++;
				if (s_error_count >= 3)
				{
					s_error_count = 0;
					*Nbiot_Send_Data.state = QIRD_ERROR;
					g_s_nbiot_task_flag = TASK_FAIL;
					s_read_upd_data_state = S_START;
				}
				else
				{
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME*5);
					s_read_upd_data_state = S_AT_QIRD;
				}
			}            
        }
        break;
		
        default:
        {
            s_read_upd_data_state = S_START;
        }
        break;
    }	
}
void UdpReadDataMachine(void)
{
   UdpReadDataMachine_BC25();
}*/
//
//OnenetConnectMachine
u8 s_onenet_connect_state=0;
void OneNetStartConnect(void)
{
	s_onenet_connect_state = S_ONENET_CONNECT_START;
}
/***************************************************************************
 * @fun_name     static void CoapConnectMachine()
 * @brief        连接Coap状态机
 ***************************************************************************/
void OnenetConnectMachine(void)
{
    static u8 s_at_error_count = 0;
    unsigned char *nbiot_ip;
    u16 nbiot_port;
	static char c_AT_MIPLCONFIG[40]="AT+MIPLCONFIG=0,183.230.040.040,05683\r";
	static const char* c_AT_MIPLCONFIG_CK="AT+MIPLCONFIG?\r";//+MIPLCONFIG: 0,183.230.40.40,5683 +MIPLCONFIG: 2,2 +MIPLCONFIG: 3,1 +MIPLCONFIG: 4,0,1
	static const char* c_AT_MIPLCREATE="AT+MIPLCREATE\r";
	static const char* c_AT_MIPLADDOBJ = "AT+MIPLADDOBJ=0,3200,1,\"1\",4,2\r";
	static const char* c_AT_MIPLOPEN ="AT+MIPLOPEN=0,600,60\r";
	static const char* c_AT_MIPLOPENPSM ="AT+MIPLOPEN=0,172800,60\r";
	static char c_AT_MIPLDISCOVERRSP[30];// AT+MIPLDISCOVERRSP=0,48839,1,4,"5750"
	
    switch (s_onenet_connect_state)
    {
		case S_ONENET_CONNECT_IDLE:
		{
		    break;
		}
        case S_ONENET_CONNECT_START: //任务开始
        {
            s_at_error_count=0;
            s_onenet_connect_state = S_ONENET_MIPLCONFIG;
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        }
        break;

        case S_ONENET_MIPLCONFIG:
        {
            if (!check_timer_1ms())
            {
				u16 len = 16; //整条AT指令的长度，根据发送长度的位数来定
				nbiot_port = Sys_data_object.P1.server_port.datas;
				nbiot_ip = Sys_data_object.P1.server_ip;

				//IP 的存储仍然使用水表原来格式，不保存“.”号，使用时加入
				int i;
				for (i = 0; i < 4; i++)
				{
					if (nbiot_ip[i] < 10)
					{
						c_AT_MIPLCONFIG[len++] = nbiot_ip[i] + 0x30;
					}
					else if (nbiot_ip[i] < 100)
					{
						c_AT_MIPLCONFIG[len++] = (nbiot_ip[i] / 10) + 0x30;
						c_AT_MIPLCONFIG[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					else
					{
						c_AT_MIPLCONFIG[len++] = (nbiot_ip[i] / 100) + 0x30;
						c_AT_MIPLCONFIG[len++] = (nbiot_ip[i] / 10) % 10 + 0x30;
						c_AT_MIPLCONFIG[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					c_AT_MIPLCONFIG[len++] = '.';
				}
				len--; //消除多余的点号
				c_AT_MIPLCONFIG[len++] = ',';
				//c_AT_MIPLCONFIG[len++] = ((nbiot_port) / 10000) + 0x30;
				c_AT_MIPLCONFIG[len++] = (((nbiot_port) % 10000) / 1000) + 0x30;
				c_AT_MIPLCONFIG[len++] = (((nbiot_port) % 1000) / 100) + 0x30;
				c_AT_MIPLCONFIG[len++] = (((nbiot_port) % 100) / 10) + 0x30;
				c_AT_MIPLCONFIG[len++] = ((nbiot_port) % 10) + 0x30;
				c_AT_MIPLCONFIG[len++] = '\r';
				NbiotUartSend((u8*)c_AT_MIPLCONFIG, len, cst_AT_No_AT_MIPLCONFIG);
				set_timer_1s(5);
				s_onenet_connect_state = S_ONENET_MIPLCONFIG_R;
            }
        }
        break;
		
		case S_ONENET_MIPLCONFIG_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
				s_onenet_connect_state = S_ONENET_MIPLCONFIG_CK;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if (!check_timer_1s() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_MIPLCONF_ERROR)//
                {
					s_at_error_count = 0;
					s_onenet_connect_state = S_ONENET_MIPLCONFIG_CK;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLCONFIG;
                }
            }
        }
        break;
		
        case S_ONENET_MIPLCONFIG_CK:
        {
			 if (!check_timer_1ms())
			 {
				NbiotUartSend((u8*)c_AT_MIPLCONFIG_CK, strlen(c_AT_MIPLCONFIG_CK), cst_AT_No_AT_MIPLCONFIG_CK);
				s_onenet_connect_state = S_ONENET_MIPLCONFIG_CK_R;
				set_timer_1s(2);
			 }
        }
        break;
		
		case S_ONENET_MIPLCONFIG_CK_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
                s_onenet_connect_state = S_ONENET_MIPLCREATE;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if (!check_timer_1s())
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_MIPLCONF_ERROR)//
                {
					//一般不会发生,肯定能查到返回结果
					s_at_error_count = 0;
					s_onenet_connect_state = S_ONENET_MIPLCREATE;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLCONFIG_CK;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;

        case S_ONENET_MIPLCREATE:
        {
            if(!check_timer_1ms())
            {
				NbiotUartSend((u8*) c_AT_MIPLCREATE, strlen(c_AT_MIPLCREATE), cst_AT_No_AT_MIPLCREATE);
				set_timer_1s(2);
				s_onenet_connect_state = S_ONENET_MIPLCREATE_R;		
            }
        }
        break;

        case S_ONENET_MIPLCREATE_R:
        {
            if(NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
                s_onenet_connect_state = S_ONENET_MIPLADDOBJ;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if(!check_timer_1s())
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_MIPLCREATE_ERROR)
                {
					s_at_error_count = 0;
					s_onenet_connect_state = S_ONENET_MIPLADDOBJ;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLCREATE;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
		
		case S_ONENET_MIPLADDOBJ:
        {
            if(!check_timer_1ms())
            {
				NbiotUartSend((u8*) c_AT_MIPLADDOBJ, strlen(c_AT_MIPLADDOBJ), cst_AT_No_AT_MIPLADDOBJ);
				set_timer_1s(2);
				s_onenet_connect_state = S_ONENET_MIPLADDOBJ_R;
            }
        }
        break;

        case S_ONENET_MIPLADDOBJ_R:
        {
            if(NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
                s_onenet_connect_state = S_ONENET_MIPLOPEN;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else if((!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_MIPLADDOBJ_ERROR)
                {
					s_at_error_count = 0;
					s_onenet_connect_state = S_ONENET_MIPLOPEN;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLADDOBJ;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
		
		case S_ONENET_MIPLOPEN:
        {
            if(!check_timer_1ms())
            {
				if((Sys_data_object.P1.func_cfg_bytes[12]&0x80)&&(Sys_data_object.P1.func_cfg_bytes[12]&0x03)) //PSM模式上报判断
				{
					NbiotUartSend((u8*) c_AT_MIPLOPEN, strlen(c_AT_MIPLOPENPSM), cst_AT_No_AT_MIPLOPEN);
				}
				else
				{
					NbiotUartSend((u8*) c_AT_MIPLOPEN, strlen(c_AT_MIPLOPEN), cst_AT_No_AT_MIPLOPEN);
				}
				set_timer_1s(10);
				s_onenet_connect_state = S_ONENET_MIPLOPEN_R;
            }
        }
        break;

        case S_ONENET_MIPLOPEN_R:
        {
            if(NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
				NbiotClearAtAck();
				NbiotSetRevMipldiscover(); 
				set_timer_1s(20);
                s_onenet_connect_state = S_ONENET_MIPLDISCOVER;
            }
            else if((!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_MIPLOPEN_ERROR)
                {
					s_at_error_count = 0;
					set_timer_1s(10);
					s_onenet_connect_state = S_ONENET_MIPLDISCOVER;			
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLOPEN;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
		case S_ONENET_MIPLDISCOVER: //static char c_AT_MIPLDISCOVERRSP[30];// AT+MIPLDISCOVERRSP=0,48839,1,4,"5750"
		{			
			if (NbiotCheckAtAck() == UART_OK)	
            {
				u8 len;
				char discover_num[10];
				memset(discover_num,0,sizeof(discover_num));
				memset(c_AT_MIPLDISCOVERRSP,0,sizeof(c_AT_MIPLDISCOVERRSP));
				strcpy(c_AT_MIPLDISCOVERRSP,"AT+MIPLDISCOVERRSP=0,");
				
				NbiotGetDiscover_num(discover_num);
				strcat(c_AT_MIPLDISCOVERRSP,discover_num);
				strcat(c_AT_MIPLDISCOVERRSP,",1,4,\"5750\"\r");
				
				len = strlen(c_AT_MIPLDISCOVERRSP);
				NbiotUartSend((u8*)c_AT_MIPLDISCOVERRSP, len, cst_AT_No_AT);
				set_timer_1s(2);
				
				s_onenet_connect_state = S_ONENET_MIPLDISCOVER_R; 	
            }
			else if(!check_timer_1s())
			{
				s_at_error_count = 0;
				*Nbiot_Send_Data.state = NBIOT_ERROR;
				g_s_nbiot_task_flag = TASK_FAIL; //到此为止任务成功 
				s_onenet_connect_state = S_ONENET_CONNECT_IDLE;
			}
		} 
		break; 
          
		case S_ONENET_MIPLDISCOVER_R://应答接收到数据--等待响应
		{
			if(NbiotCheckAtAck() == UART_OK)
			{
				s_at_error_count = 0;
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
				s_onenet_connect_state = S_ONENET_Wait;
			}
			else if((!check_timer_1s()))
			{
				s_at_error_count++;
				if (s_at_error_count >= NUM_AT_MIPLDISCOVERRSP_ERROR)
				{
					s_at_error_count = 0;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
					s_onenet_connect_state = S_ONENET_Wait;
				}
				else
				{
					NbiotClearAtAck();
					NbiotSetRevMipldiscover();
					s_onenet_connect_state = S_ONENET_MIPLDISCOVER;
					set_timer_1s(5);
				}
			}
		}  
		break;  
		
		case S_ONENET_Wait:
        {
            if((!check_timer_1ms()))
            {
				s_at_error_count = 0;
				 *Nbiot_Send_Data.state = NBIOT_ONLINE;
				g_s_nbiot_task_flag = TASK_SUCCESS; //到此为止任务成功 
				s_onenet_connect_state = S_ONENET_CONNECT_IDLE;
            }
        }
        break;
		
        default:
        {
            s_onenet_connect_state = S_ONENET_CONNECT_IDLE; //状态机回归初始状态
        }
        break;
    }
}

#if SEND_ACKID_ENABLE
     u16 Send_AckID=0;
#endif

//Onnet发送数据状态机
#define S_ONENET_SEND_START     0
#define S_ONENET_SEND_DATA      1
#define S_ONENET_SEND_DATA_R    2

u8 s_onenet_send_state = S_ONENET_SEND_START;
void StartOnenetSendData(void)
{
	s_onenet_send_state = S_ONENET_SEND_START;
}
u8 Send_AckID=0;
void OneNetSendDataMachine(void)
{
//    static u8 s_at_error_count=0; //AT指令累计发送失败次数
    static const char temp_AT_MIPLDISCOVERRSP[] = "AT+MIPLNOTIFY=0,0,3200,0,5750,1,";
    //static char c_AT_MIPLNOTIFY[50+SEND_DATA_LENGTH];//内存不足，使用公用发送缓存 c_AT_NMGS
	
    switch (s_onenet_send_state)
    {
        case S_ONENET_SEND_START:
        {
            s_onenet_send_state = S_ONENET_SEND_DATA; //收到数据立即进行数据发送，模块会报ERROR，因此延时1S，消除此ERROR
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        } break;
        
        case S_ONENET_SEND_DATA://发送数据 
        {
             if (!check_timer_1ms())
            {
				if(TASK_IDLE == UartIfIdle(NB_UART_COM))
				{
					 //u16 len = 31; //整条AT指令的长度，根据发送长度的位数来定
					u16 len,i,len_Gprs_Send_Data;
					char len_buffer[6]={0};
					
					c_AT_NMGS[0]=0;//强制归零
					strcat(c_AT_NMGS,temp_AT_MIPLDISCOVERRSP);
					len_Gprs_Send_Data=2*Nbiot_Send_Data.len;
					sprintf(len_buffer,"%u",len_Gprs_Send_Data);
					strcat(c_AT_NMGS,len_buffer);
					strcat(c_AT_NMGS,",\"");
					len=strlen(c_AT_NMGS);
					for (i = 0; i < Nbiot_Send_Data.len; i++)//获取发送数据内容
					{
						if ((*(Nbiot_Send_Data.buf + i) >> 4) >= 0x0A)
						{
							c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) >> 4) + 0x37;//字符转换
						}
						else
						{
							c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) >> 4) + 0x30;//数字转换 
						}

						if ((*(Nbiot_Send_Data.buf + i) & 0x0F) >= 0x0A)
						{
							c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) & 0x0F) + 0x37;
						}
						else
						{
							c_AT_NMGS[len++] = (*(Nbiot_Send_Data.buf + i) & 0x0F) + 0x30;
						}
					}
					c_AT_NMGS[len++] = 0;//手动加字符串结束符防止意外溢出                
					strcat(c_AT_NMGS,"\",0,0");           
					if((Sys_data_object.P1.func_cfg_bytes[10] == 0x55)||(Sys_data_object.P3.ProductUploadFlag == 0x55))//ACK判上报成功
					{	
						char strtemp[8];
						if(++Send_AckID==0) 
						{
							Send_AckID=1;  
						}        
						sprintf(strtemp,",%u",Send_AckID);
						strcat(c_AT_NMGS,strtemp);              
						strcat(c_AT_NMGS,"\r");  
						NbiotClearMsg();				
						NbiotUartSend((u8*) c_AT_NMGS,strlen(c_AT_NMGS), cst_AT_No_AT_MIPLNOTIFY_ACKID);
					}
					else
					{
						strcat(c_AT_NMGS,"\r");     
						NbiotClearMsg();				
						NbiotUartSend((u8*) c_AT_NMGS,strlen(c_AT_NMGS), cst_AT_No_AT_MIPLNOTIFY);
					}		     
					
					s_onenet_send_state = S_ONENET_SEND_DATA_R; 
					set_timer_1ms(5*AT_COMMAND_RECEIVE_WAIT_TIME); //发送数据延时较长5倍时间等待 
				}
            }
        } break; 
        
     case S_ONENET_SEND_DATA_R:
    {
        if (NbiotCheckAtAck() == UART_OK) //返回正确的应答
        {
            g_s_nbiot_task_flag = TASK_SUCCESS;
            *Nbiot_Send_Data.state = NBIOT_SUCCESS;
            s_onenet_send_state = S_ONENET_SEND_START;
        }
        else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms()))//返回错误的应答或者定时时间到
        {
            *Nbiot_Send_Data.state = NBIOT_ERROR;
            g_s_nbiot_task_flag = TASK_FAIL;
            s_onenet_send_state = S_ONENET_SEND_START;
        }
    } break; 
    default: break;   
    }
}
/***************************************************************************
 * @fun_name    static void NbiotPowerOffMachine()
 * @brief        关机状态机
 ***************************************************************************/
void NbiotPowerOffMachine(void) //先注销网络然后断电关机
{
    //关机流程
    static u8 s_at_error_count = 0;
	static const char* c_AT_MIPLCLOSE = "AT+MIPLCLOSE=0\r"; //登录注销流程
	static const char* c_AT_MIPLDELOBJ = "AT+MIPLDELOBJ=0,3200\r"; //模组侧订阅资源列表释放
	static const char* c_AT_MIPLDEL = "AT+MIPLDELETE=0\r"; //模组侧通信实例删除
    static const char* c_AT_CFUN0 = "AT+CFUN=0\r"; //设置最小功能模式
    static const char* c_AT_NCSEARFCN = "AT+QCSEARFCN=0\r"; //清除已保存频点
    static const char* c_AT_CFUN1 = "AT+CFUN=1\r"; //设置正常功能模式
    static const char* c_AT_NETCLOSE = "AT+NCDPCLOSE\r";
	static const u8 c_AT_QPOWD[] = "AT+QPOWD=1\r";
	static const char* c_AT_QICFG0 = "AT+QICFG=\"showlength\",0\r"; //不显示接收数据长度
	
    switch (s_power_off_state)
    {
        case S_POWER_OFF_START:
        {
            s_at_error_count = 0;
            if (Nbiot_Para.net_state == NB_ON_LINE)
            {
				Nbiot_Para.net_state = NB_OFF_LINE;
				Nbiot_Para.coap_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp1_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
				if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)
				{
                    s_power_off_state = S_UDP_QICFG0;
				}
				else
				{
					s_power_off_state = S_AT_NETCLOSE;
				}
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
            else
            {
                s_power_off_state = S_AT_CFUN0;
            }
        }
        break;
        case S_AT_MIPLCLOSE://登录注销流程  //注销指令改为5s,重试2次
        {
            if(!check_timer_1ms())
            {
              NbiotUartSend((u8*) c_AT_MIPLCLOSE, strlen(c_AT_MIPLCLOSE), cst_AT_No_AT_MIPLCLOSE);
              s_power_off_state = S_AT_MIPLCLOSE_R;
              set_timer_1ms(5*AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        } break;
                
        case S_AT_MIPLCLOSE_R:
        {
            if (NbiotCheckAtAck() == UART_OK) 
            {
                //返回正确的应答
                s_at_error_count = 0;
                s_power_off_state = S_AT_MIPLDELOBJ;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            } 
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms())) 
            {
                //返回错误的应答或者定时时间到
               if (++s_at_error_count >= NUM_AT_MIPLCLOSE_ERROR)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = cst_AT_No_AT_MIPLCLOSE;
                    s_power_off_state = S_AT_MIPLDELOBJ;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else 
                {
                    s_power_off_state = S_AT_MIPLCLOSE;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        } break;
                
        case S_AT_MIPLDELOBJ://模组侧订阅资源列表释放
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_MIPLDELOBJ, strlen(c_AT_MIPLDELOBJ), cst_AT_No_AT_MIPLDELOBJ);
                s_power_off_state = S_AT_MIPLDELOBJ_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        } break;
                
        case S_AT_MIPLDELOBJ_R:
        {
            if (NbiotCheckAtAck() == UART_OK) 
            {
                //返回正确的应答
                s_at_error_count = 0;
                s_power_off_state = S_AT_MIPLDEL;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            } 
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms())) 
            {
                //返回错误的应答或者定时时间到
               if (++s_at_error_count >= NUM_AT_MIPLDEL_ERROR)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = cst_AT_No_AT_MIPLDELOBJ;
                    s_power_off_state = S_AT_MIPLDEL;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                } 
                else 
                {
                    s_power_off_state = S_AT_MIPLDELOBJ;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        } break;
                
        case S_AT_MIPLDEL://模组侧订阅资源列表释放
        {
            if (!check_timer_1ms()) 
            {
                NbiotUartSend((u8*) c_AT_MIPLDEL, strlen(c_AT_MIPLDEL), cst_AT_No_AT_MIPLDEL);
                s_power_off_state = S_AT_MIPLDEL_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); 
            }
        } break;                
        case S_AT_MIPLDEL_R:
        {
            if (NbiotCheckAtAck() == UART_OK) 
            {
                //返回正确的应答
                s_at_error_count = 0;
                s_power_off_state = S_AT_NETCLOSE;    
            } 
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms())) 
            {
                //返回错误的应答或者定时时间到
                if (++s_at_error_count >= NUM_AT_MIPLDEL_ERROR)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = cst_AT_No_AT_MIPLDEL;
                    s_power_off_state = S_AT_NETCLOSE;
                } 
                else 
                {
                    s_power_off_state = S_AT_MIPLDEL;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        } break;  
        case S_AT_NETCLOSE:
        {
			if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)
			{
				s_power_off_state = S_UDP_QICFG0;
			}
			else
			{
				NbiotUartSend((u8*) c_AT_NETCLOSE, strlen(c_AT_NETCLOSE), cst_AT_No_AT_NETCLOSE);
				set_timer_1s(3);
				s_power_off_state = S_AT_NETCLOSE_R;
			}
        }
        break;

        case S_AT_NETCLOSE_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                //返回正确的应答
                s_at_error_count = 0;
				set_timer_1s(1);
                s_power_off_state = S_UDP_QICFG0;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1s()))
            {
                //返回错误的应答或者定时时间到
                s_at_error_count++;
                if (s_at_error_count >= 2)		//两次不成功直接关机
                {
                    s_at_error_count = 0;
                    s_power_off_state = S_UDP_QICFG0;			//关机命令
                }
                else
                {
                    s_power_off_state = S_AT_NETCLOSE;
                }
            }
        }
        break; 
		
		 case S_UDP_QICFG0://设置是否显示可选长度参数
        {
            if (!check_timer_1ms())
            {
				NbiotUartSend((u8*) c_AT_QICFG0, strlen(c_AT_QICFG0), cst_AT_No_AT_QICFG);//设置是否显示可选长度参数
                s_power_off_state = S_UDP_QICFG0_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_UDP_QICFG0_R:
        {
            if (NbiotCheckAtAck() == UART_OK)//应答正确-下一步
            {
                s_at_error_count = 0;
                s_power_off_state = S_AT_QPOWD;
                set_timer_1s(1);
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= 2)
                {
                    s_at_error_count = 0;
					s_power_off_state = S_AT_QPOWD;
					set_timer_1s(1);
                }
                else
                {
                    s_power_off_state = S_UDP_QICFG0;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        break;
		
		case S_AT_QPOWD:
		{
			if (!check_timer_1s())
			{
				NbiotUartSend((u8*) c_AT_QPOWD, strlen((const char*) c_AT_QPOWD), cst_AT_No_AT_QPOWD);
				set_timer_1s(3);
				s_power_off_state = S_AT_QPOWD_R;
			}
		}
		break;
		
		case S_AT_QPOWD_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                //返回正确的应答
                s_at_error_count = 0;				
				set_timer_1s(3);
                s_power_off_state = S_POWER_OFF;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1s()))
            {
                //返回错误的应答或者定时时间到
                s_at_error_count++;
                if (s_at_error_count >= 2)		//两次不成功直接关机
                {
                    s_at_error_count = 0;
                    s_power_off_state = S_POWER_OFF;			//直接去关机
                }
                else
                {
                    s_power_off_state = S_AT_QPOWD;
                }
            }
        }
        break;

        case S_AT_CFUN0://设置模组最小功能模式
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CFUN0, strlen((const char*) c_AT_CFUN0), cst_AT_No_AT_CFUN);
                s_power_off_state = S_AT_CFUN0_R;
                set_timer_1ms(2 * AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_AT_CFUN0_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                //返回正确的应答
                s_at_error_count = 0;
				set_timer_1ms( AT_COMMAND_SEND_INTERVAL_TIME);
                s_power_off_state = S_AT_NCSEARFCN;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms()))
            {
                //返回错误的应答或者定时时间到
                if (++s_at_error_count >= NUM_AT_CFUN_ERROR)
                {
                    s_at_error_count = 0;
                    s_power_off_state = S_AT_NCSEARFCN;
                }
                else
                {
                    s_power_off_state = S_AT_CFUN0;
                    set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
                }
            }
        }
        break;

        case S_AT_NCSEARFCN://清除频点
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_NCSEARFCN, strlen((const char*) c_AT_NCSEARFCN), cst_AT_No_AT_NCSEARFCN);
                s_power_off_state = S_AT_NCSEARFCN_R;
                set_timer_1ms(2 * AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_AT_NCSEARFCN_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                //返回正确的应答
                s_at_error_count = 0;
				set_timer_1ms( AT_COMMAND_SEND_INTERVAL_TIME*6);//清频后延时3秒
                s_power_off_state = S_AT_CFUN1;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms()))
            {
                //返回错误的应答或者定时时间到
                if (++s_at_error_count >= NUM_AT_NCSEARFCN_ERROR)
                {
                    s_at_error_count = 0;
                    s_power_off_state = S_AT_CFUN1;
                }
                else
                {
                    s_power_off_state = S_AT_NCSEARFCN;
                    set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
                }
            }
        }
        break;

        case S_AT_CFUN1://设置模组正常功能模式
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CFUN1, strlen((const char*) c_AT_CFUN1), cst_AT_No_AT_CFUN);
                s_power_off_state = S_AT_CFUN1_R;
                set_timer_1ms(2 * AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_AT_CFUN1_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                //返回正确的应答
                s_at_error_count = 0;
				set_timer_1s(1);
                s_power_off_state = S_UDP_QICFG0;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms()))
            {
                //返回错误的应答或者定时时间到
                if (++s_at_error_count >= NUM_AT_CFUN_ERROR)
                {
                    s_at_error_count = 0;
                    set_timer_1s(1);
					s_power_off_state = S_UDP_QICFG0;
                }
                else
                {
                    s_power_off_state = S_AT_CFUN1;
                    set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
                }
            }
        }
        break;

        case S_POWER_OFF:
        {
			if (!check_timer_1s())
			{
				NB_Power_Disable(); //切断电源
				set_timer_1s(1);
				s_power_off_state = S_POWER_OFF_WAIT;
				Nbiot_Para.net_state = NB_OFF_LINE;
				Nbiot_Para.coap_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp1_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
			}
        }
        break;

        case S_POWER_OFF_WAIT:
        {
            if (!check_timer_1s())
            {
                NbiotPreSleep();
                g_s_nbiot_task_flag = TASK_SUCCESS;
                s_power_off_state = S_START;
            }
        }
        break;

        default:
        {
            s_power_off_state = S_START;
        }
        break;
    }
}

void NbiotReadECLSNRMachine(void)
{
    static u8 s_error_count; //AT指令累计发送失败次数
    static u8 s_ecl_state = S_START;
    switch (s_ecl_state)
    {
        case S_START:
        {
            set_timer_1ms(1000);
            s_error_count = 0;
            s_ecl_state = S_AT_ECL;
        }
        break;

        case S_AT_ECL:
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_NUESTATS, strlen((const char*) c_AT_NUESTATS), cst_AT_No_AT_NUESTATS);
                set_timer_1ms(500);
                s_ecl_state = S_AT_ECL_R;
            }
        }
        break;

        case S_AT_ECL_R:
        {
            if (!check_timer_1ms())
            {
                if (NbiotCheckAtAck() == UART_OK)
                {
                    //返回正确的应答
                    *Nbiot_Send_Data.state = ECL_SNR_SUCCESS;
                    g_s_nbiot_task_flag = TASK_SUCCESS;
                    s_ecl_state = S_START;
                }
                else
                {
                    //返回错误的应答或者定时时间到
                    s_error_count++;
                    if (s_error_count >= 1)
                    {
                        s_error_count = 0;
                        *Nbiot_Send_Data.state = ECL_SNR_ERROR;
                        g_s_nbiot_task_flag = TASK_FAIL;
                        s_ecl_state = S_START;
                    }
                    else
                    {
                        s_ecl_state = S_AT_ECL;
                    }
                }
            }
        }
        break;

        default:
        {
            s_ecl_state = S_START;
        }
        break;
    }
}

/*****************************ONENET应答下发指令*********************/
static u8 s_onenet_ack_rev_state = S_ONENET_ACKREV_START;

static void StartOnenetAckRev(void)
{
	s_onenet_ack_rev_state = S_ONENET_ACKREV_START;
}
/*******************************************************
NbiotRevAckMachine
对接收到的指令先应答
*******************************************************/
void NbiotRevAckMachine(void)
{
    static u8 s_error_count; //AT指令累计发送失败次数
    static char c_AT_MIPLWRITE_EXECUTE[30];// =   "AT+MIPLWRITERSP=0,12345,2\r";
    //static char c_AT_MIPLEXECUTE[30];// = "AT+MIPLEXECUTERSP=0,12345,2\r";
    switch (s_onenet_ack_rev_state)
    {
	  case S_ONENET_ACKREV_IDLE:
      {
      } break; 
      case S_ONENET_ACKREV_START:
      {
			set_timer_1ms(1000);
            s_onenet_ack_rev_state = S_ONENET_REPLY_REV_ACKID;
            s_error_count = 0;
      } break;  
         
     case S_ONENET_REPLY_REV_ACKID://应答接收到数据
    {
        u8 len;
		char ack_num[10];
		if (!check_timer_1ms())
		{
			memset(ack_num,0,sizeof(ack_num));
			memset(c_AT_MIPLWRITE_EXECUTE,0,sizeof(c_AT_MIPLWRITE_EXECUTE));
			if(ORDER_EXECUTE == NbiotGetOnenetTypeDownOrder())
			{			
				strcpy(c_AT_MIPLWRITE_EXECUTE,"AT+MIPLEXECUTERSP=0,");
			}
			else 
			{
				strcpy(c_AT_MIPLWRITE_EXECUTE,"AT+MIPLWRITERSP=0,");
			}
			NbiotGetWriteAck_num(ack_num);
			strcat(c_AT_MIPLWRITE_EXECUTE,ack_num);
			strcat(c_AT_MIPLWRITE_EXECUTE,",2\r");
			
			len = strlen(c_AT_MIPLWRITE_EXECUTE);
			NbiotUartSend((u8*)c_AT_MIPLWRITE_EXECUTE, len, cst_AT_No_AT_MIPLWRITE);
			set_timer_1ms(5*AT_COMMAND_RECEIVE_WAIT_TIME);
			
			s_onenet_ack_rev_state = S_ONENET_REPLY_REV_ACKID_R; 
		}			
    } break; 
          
    case S_ONENET_REPLY_REV_ACKID_R://应答接收到数据--等待响应
    {
        if (NbiotCheckAtAck() == UART_OK)
        {
            g_s_nbiot_task_flag = TASK_SUCCESS;
            s_onenet_ack_rev_state = S_ONENET_ACKREV_IDLE;
			SetUartCommRevFlag(); //应答写命名完成--进行数据处理
        }
        else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms()))//返回错误的应答或者定时时间到
        {
            if (++s_error_count >= NUM_AT_MIPLWRITE_ERROR)
            {
                *Nbiot_Send_Data.state = cst_AT_No_AT_MIPLWRITE;
                g_s_nbiot_task_flag = TASK_FAIL;
                s_onenet_ack_rev_state = S_ONENET_ACKREV_IDLE;
            }
            else
            {
                s_onenet_ack_rev_state = S_ONENET_REPLY_REV_ACKID;
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            }
        }
    }  break;  
    default: break;    
    }
}
/***************************************************************************
 * @fun_name     void PsmWakupMachine(void)
 * @brief        唤醒PSM
 ***************************************************************************/
static void Psm_Wakup_Machine(void)
{	
	static const char *c_AT_QSCLK = "AT+QSCLK=0\r"; //临时关闭深度休眠功能，进行NB通信
	static const char *c_AT_QPING = "AT+QPING=1,\"8.8.8.8\",1,1\r";//+CSCON: 1  触发模组与基站交互后查询信号值
	static const char* c_AT_NCDP_CK = "AT+NMSTATUS?\r"; //查询信号值
	
	static u8 s_at_error_count = 0;
	switch(s_psm_wakeup_state)
	{
		//硬件唤醒:当模块处于PSM模式时,拉低PSM_EINT(下降沿>100ms)可将模块从 PSM 唤醒
		case PSM_WKUPSTA_IDLE:
		{
		}
		break;
		case PSM_WKUPSTA_START:
		{  
			 UartInit(NB_UART_COM, BAUD9600, DATA_BIT_8, STOPBIT_1, UART_NONE_PARITY,UART_LPUART_Disable);
			 NB_PSM_WAKE_HIG();
			 set_timer_1ms(500);
			 s_psm_wakeup_state= PSM_WKUPSTA_EINT_LOW;
		}
		break;
		case PSM_WKUPSTA_EINT_LOW:
		{
			if (!check_timer_1ms())
			{
				NB_PSM_WAKE_LOW();
				set_timer_1ms(500);
			   s_psm_wakeup_state= PSM_WKUPSTA_EINT_HIGH;			 
			}
		}
		break;
		case PSM_WKUPSTA_EINT_HIGH:
		{
			if (!check_timer_1ms())
			{ 
				NB_PSM_WAKE_HIG();			
				NbiotUartSend(0, 0, cst_AT_No_AT_NCDP);//查询+QLWEVTIND状态
				set_timer_1ms(5000);//5s,超时等待5s,信号差的时候+QLWEVTIND: 6响应也很快,但PING和上报都失败
				s_psm_wakeup_state= PSM_WKUPSTA_QLWEVTIND6;
			}			
		}
		break;
        case PSM_WKUPSTA_QLWEVTIND6://检查深度睡眠唤醒连接恢复成功 +QLWEVTIND: 6,
		{
			if (NbiotCheckAtAck() == UART_OK)
			{
				set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
			    s_psm_wakeup_state = PSM_WKUPSTA_QSCLK0;
			}
			else if (!check_timer_1ms())
			{
				s_psm_wakeup_state = PSM_WKUPSTA_WAKE_FAIL;
			}  		
		}
		break;	
		//模块进入工作模式
		case PSM_WKUPSTA_QSCLK0:
		{
			if (!check_timer_1ms())
			{
				NbiotUartSend((u8*) c_AT_QSCLK, strlen(c_AT_QSCLK), cst_AT_QSCLK_CLOSE);
				s_at_error_count = 0;
				set_timer_1ms(2000); 
				s_psm_wakeup_state = PSM_WKUPSTA_QSCLK0_R;
			}
		}		
		break;		
		case PSM_WKUPSTA_QSCLK0_R:
		{
		    if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count = 0;
				s_psm_wakeup_state = PSM_WKUPSTA_NPING;//PSM_WKUPSTA_NCDP_CK;
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                if (++s_at_error_count >= 3)
                {
                    s_at_error_count = 0;
					s_psm_wakeup_state = PSM_WKUPSTA_WAKE_FAIL;
                }
                else
                {
                    s_psm_wakeup_state = PSM_WKUPSTA_QSCLK0;
                    set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
            } 
		}
		break;
		//检查连接服务器是否成功
		case PSM_WKUPSTA_NCDP_CK:
		{
			if (!check_timer_1ms())
			{
				NbiotUartSend((u8*) c_AT_NCDP_CK, strlen((const char*) c_AT_NCDP_CK), cst_AT_No_AT_NCDP_CK);
				set_timer_1s(3);
				s_psm_wakeup_state = PSM_WKUPSTA_NCDP_CK_R;
			}	
		} 
		break;	
		case PSM_WKUPSTA_NCDP_CK_R://应答的应该是模组保存的状态,跟本次唤醒是否真正成功连到服务无关.+NMSTATUS: REGISTERED_AND_OBSERVED
		{
		    if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count = 0;
				s_psm_wakeup_state = PSM_WKUPSTA_NPING;
            }
            else if((!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >=3)
                {
                    s_at_error_count = 0;
					s_psm_wakeup_state = PSM_WKUPSTA_WAKE_FAIL;
                }
                else
                {
                    s_psm_wakeup_state = PSM_WKUPSTA_NCDP_CK;
                }
            }
		} 
		break;
		//PING
		/*当返回+CSCON:1---标准模组与基站建立链接
		后执行AT+QENG=0查询---此时在模组与基站建立链接的状态下查询信号*/
		case PSM_WKUPSTA_NPING:
		{
			if (!check_timer_1ms())
			{
				NbiotUartSend((u8*) c_AT_QPING, strlen((const char*) c_AT_QPING), cst_AT_No_CSCON1);
				set_timer_1s(5);
				s_psm_wakeup_state = PSM_WKUPSTA_NPING_R;
			}	
		}
		break;
		case PSM_WKUPSTA_NPING_R:
		{
			if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count = 0;
				s_psm_wakeup_state = PSM_WKUPSTA_NUESTATS;
            }
			else if((!check_timer_1s()))
            {
				s_psm_wakeup_state = PSM_WKUPSTA_NUESTATS;
            }
		}
		break;
		//更新信号值
		case PSM_WKUPSTA_NUESTATS:
        {
            if (!check_timer_1s())
            {
                NbiotUartSend((u8*) c_AT_NUESTATS, strlen(c_AT_NUESTATS), cst_AT_No_AT_NUESTATS);
                set_timer_1s(2);
                s_psm_wakeup_state = PSM_WKUPSTA_NUESTATS_R;
            }
        }
        break; 
        case PSM_WKUPSTA_NUESTATS_R:
        {
			if (NbiotCheckAtAck() == UART_OK)
			{
				s_psm_wakeup_state = PSM_WKUPSTA_WAKE_SUCCESS;
			}
			else if((!check_timer_1s()))
			{
				s_psm_wakeup_state = PSM_WKUPSTA_WAKE_SUCCESS;
			}
        }
        break;
		case PSM_WKUPSTA_WAKE_SUCCESS:
		{
			psm_model_state = PSM_STATE_WAKE;
			g_s_nbiot_task_flag = TASK_SUCCESS; //初始化成功
			s_psm_wakeup_state = PSM_WKUPSTA_IDLE;
		}
		break;
		case PSM_WKUPSTA_WAKE_FAIL:
		{
			NbForcePowerOff();
			psm_model_state = PSM_STATE_OUT;
			g_s_nbiot_task_flag = TASK_FAIL; 
			s_psm_wakeup_state = PSM_WKUPSTA_IDLE;
		}
		break;
		default:
		{
			s_psm_wakeup_state = PSM_WKUPSTA_IDLE;
		}
		break;
    }
}

/***************************************************************************
 * @fun_name     void Psm_Sleep_Machine(void)
 * @brief        进入低功耗模式
 ***************************************************************************/
static void Psm_Sleep_Machine(void)
{	
	static const char* c_AT_CPSMS1 = "AT+CPSMS=1\r"; //开启PSM模式
	static const char c_AT_QSCLK1[] = "AT+QSCLK=1\r"; //开启深度休眠功能，进行NB通信
	switch(s_psm_sleep_state)
	{
		case PSM_SLPSTA_IDLE:
		{
		}
		break;
		
        case PSM_SLPSTA_START://设置关闭或打开PSM模式
        {
			NbiotUartSend((u8*) c_AT_CPSMS1, strlen(c_AT_CPSMS1), cst_AT_No_AT_CPSMS);//使用PSM
			s_init_state = S_TCP_CPSMS_R;
			set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
			s_psm_sleep_state = PSM_SLPSTA_CPSMS1_R;
        }
        break;

		case PSM_SLPSTA_CPSMS1_R:
		{
			if (NbiotCheckAtAck() == UART_OK)//应答正确-下一步
			{
				NbiotUartSend((u8*) c_AT_QSCLK1, strlen(c_AT_QSCLK1), cst_AT_QSCLK_OPEN);
				s_psm_sleep_state = PSM_SLPSTA_WAIT;
				set_timer_1s(30); //进入休眠模式30s超时等待
			}
			else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))
            {
                NbForcePowerOff();
				psm_model_state = PSM_STATE_OUT;
				g_s_nbiot_task_flag = TASK_FAIL;
				s_psm_sleep_state = PSM_SLPSTA_IDLE;
            }
		}	
		break;
		case PSM_SLPSTA_WAIT://等待应答 +QATSLEEP
		{
		    if (NbiotCheckAtAck() == UART_OK)//应答正确-下一步
            {
				psm_model_state = PSM_STATE_SLEEP;
				g_s_nbiot_task_flag = TASK_SUCCESS;
                s_psm_sleep_state = PSM_SLPSTA_IDLE;
            }
            else if ((!check_timer_1s()) || (NbiotCheckAtAck() == UART_ERROR))
            {
				NbForcePowerOff();
				psm_model_state = PSM_STATE_OUT;
				g_s_nbiot_task_flag = TASK_FAIL;
                s_psm_sleep_state = PSM_SLPSTA_IDLE;
            } 
		}
		break;
		case PSM_CHECK_START:
		{
			if(TASK_IDLE == AdcIfIdle())
			{
				AdcStartConvert(PSM_CHECK_CHANNEL, PSM_CHECK_NUM, PSM_CHECK_INTERVAL, &s_psm_adc_result, &s_psm_adc_done);
				s_psm_sleep_state =PSM_CHECK_WAIT;
			}
		}
		break;
		case PSM_CHECK_WAIT:
		{
			 if (TRUE == s_psm_adc_done)
			{
				if (ADC_OK == AdcGetStatus())
				{
					if(s_psm_adc_result>1500)//大于1V左右
					{
						NbForcePowerOff();
						psm_model_state = PSM_STATE_OUT;
					}
					g_s_nbiot_task_flag = TASK_SUCCESS;
					s_psm_sleep_state = PSM_SLPSTA_IDLE;
				}
			}
		}
		break;
		default:
		{
			NbForcePowerOff();
			psm_model_state = PSM_STATE_OUT;
			g_s_nbiot_task_flag = TASK_SUCCESS;
			s_psm_sleep_state = PSM_SLPSTA_IDLE;
		}
		break;
    }
}
/***************************************************************************
 * @fun_name    定时器资源
 * @brief       该内部接口主要为了方便记忆及使用
 ***************************************************************************/
void set_timer_1s(u16 time)
{
    Set100msTimer(TIMER_100MS_NBIOT, time * 10);
}

u16 check_timer_1s(void)
{
    return Check100msTimer(TIMER_100MS_NBIOT);
}

void set_timer_1ms(u16 time)
{
    Set5msTimer(TIMER_5MS_NBIOT, time / 5);
}

u16 check_timer_1ms(void)
{
    return Check5msTimer(TIMER_5MS_NBIOT);
}

/***************************************************************************
 * @fun_name     void StartPowerOffTask()
 * @brief        关机接口
 ***************************************************************************/
void StartPowerOffTask(void)
{	
    g_s_nbiot_task_flag = TASK_INIT;
    g_s_nbiot_main_state = NBIOT_POWER_OFF;
	s_power_off_state = S_POWER_OFF_START;	
}
//NB强制关机
void NbForcePowerOff(void)
{
    NB_Power_Disable();
	Nbiot_Para.net_state = NB_OFF_LINE;
	Nbiot_Para.coap_state = CONNECT_OFF_LINE;
	Nbiot_Para.udp1_state = CONNECT_OFF_LINE;
	Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
    g_s_nbiot_task_flag = TASK_INIT;
    g_s_nbiot_main_state = NBIOT_S_IDLE;
}


void set_clear_ncsearfcn (void)
{
    flag_clear_ncsearfcn =1;
}


void sys_get_three_code (void)
{
//    NbiotGetIMEI(Sys_data_object.P1.NB_module_IMEI_0016);
//    NbiotGetIMSI(Sys_data_object.P1.NB_module_IMSI);
//    NbiotGetICCID(Sys_data_object.P1.SIMCard_ICCID_200A);
}

UNION_4U8TOU32 net_state_data;
u32 sys_get_net_state(void)
{
	s16 s_temp_data=0;
	if(g_s_nbiot_main_state == NBIOT_POWER_INIT)
	{
		net_state_data.data_buf[0] = 1;
		net_state_data.data_buf[1] = s_init_state;
		//net_state_buf[2]CEREG
		//net_state_buf[3]cgatt
	}
	else if(g_s_nbiot_main_state == NBIOT_NET_OPEN)
	{
		net_state_data.data_buf[0] = 2;
		if(Nbiot_Para.Telecom == SIM_CARD_TELECOM)
		{
			net_state_data.data_buf[1] = s_coap_connect_state;
		}
		else
		{
			net_state_data.data_buf[1] = s_onenet_connect_state;
		}
	}
	else if(If_NB_Poweron()==FALSE)
	{
		net_state_data.data_buf[0] = 3;
		//rsrp
		NbiotGetRSRP(&s_temp_data);
		net_state_data.data_buf[1] = -(s_temp_data/10);
		//SNR
		NbiotGetSNR(&s_temp_data);
		if(s_temp_data<0)
		{
			net_state_data.data_buf[2] = (-s_temp_data/10)|0x80;
		}
		else
		{
			net_state_data.data_buf[2] = s_temp_data/10;
		}
		//CSQ
		 NbiotGetCSQ(&net_state_data.data_buf[3]); 
	}
	return net_state_data.datas;
}

void sys_set_net_state(u8 state, u8 data)
{
	net_state_data.data_buf[state] = data;
}
TYP_PSM_STATE getPsmState(void)
{
    return psm_model_state;
}
u16 get_Send_AckID(void)
{
    return Send_AckID;
}		
				
#ifdef	__cplusplus
}
#endif

#endif
