/************************************************************************************
 * @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_E7025

#ifdef	__cplusplus
extern "C"
{
#endif

#include "nb_uart_driver_e7025.h"
#include "nb_driver_e7025.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"

/********************************变量定义************************************/
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];//发送数据长度较小

//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;
/*****************************内部功能状态机***********************************/
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 sys_get_net_state (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 TcpStartConnect(void);
void TcpConnectMachine(void);
void TcpSendDataMachine(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:
		{
			if(TRUE == UdpIfNeedReadData())
			{
				ClearUdpReadDataFlag();
				g_s_nbiot_main_state = NBIOT_READ_UDP_DATA;
			}
			if(TRUE == NbiotGetRevAck())//收到ONNET下发的数据,先进入应答流程应答一下
			{
				ClearNbiotGetRevAck();
				StartOnenetAckRev();
				g_s_nbiot_main_state = NBIOT_REV_ACK;
			}
		}
        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 中国电信898603;898611

                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'))
                    {
                        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 //任务失败
            {
                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_COAP)
				{
					/*if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
					{
						OnenetConnectMachine();//与ONNET平台建立连接状态机
					}
					else//电信卡
					{
						CoapConnectMachine(); //与主站建立连接状态机	
					}	*/	
					TcpConnectMachine(); //与主站建立连接状态机
				}
				else if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP1)
				{
					UdpConnectMachine();
				}
				else if(nbiot_temp_connect_type == NBIOT_CONNECT_UDP2)
				{
					UdpConnectMachine();
				}
				/*else if(nbiot_temp_connect_type == NBIOT_CONNECT_COAP)
				{
					TcpConnectMachine(); //与主站建立连接状态机
				}*/
				else
				{
					g_s_nbiot_task_flag = TASK_INIT;
					g_s_nbiot_main_state = NBIOT_S_IDLE; 
				}
            }
            else if (TASK_SUCCESS == g_s_nbiot_task_flag)
            {
				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;
				}
				/*else if (nbiot_temp_connect_type == NBIOT_CONNECT_TCP1)
				{
					 Nbiot_Para.tcp1_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(); //数据发送状态机
					}*/
					TcpSendDataMachine(); //数据发送状态机
				}
				else if(g_s_nbiot_send_type == SEND_TYPE_UDP1)
				{
					UdpSendDataMachine(); //数据发送状态机
				}
				else if(g_s_nbiot_send_type == SEND_TYPE_UDP2)
				{
					UdpSendDataMachine(); //数据发送状态机
				}
				/*else if(g_s_nbiot_send_type == SEND_TYPE_TCP1)
				{
					TcpSendDataMachine(); //数据发送状态机
				}*/
				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_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;
		

        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;
		}
	}
	/*else if(connect_type == NBIOT_CONNECT_TCP1)
	{
		if (CONNECT_ON_LINE == Nbiot_Para.tcp1_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)
	{
		//Nbiot_Para.Telecom = SIM_CARD_TELECOM;//debug 强制改为电信平台通信
		
		coap_ip = temp_ip;
		coap_port = temp_port;
		/*if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
		{
			OneNetStartConnect(); 
		}
		else//电信卡
		{
			CoapStartConnect();	
		}*/
		TcpStartConnect();
		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);
	}
	/*else if(connect_type == NBIOT_CONNECT_TCP1)
	{
		coap_ip = temp_ip;
		coap_port = temp_port;
		TcpStartConnect();
	}*/
	g_s_nbiot_task_flag = TASK_INIT;
	g_s_nbiot_main_state = NBIOT_NET_OPEN;
}
u8 getNB_NetConnectType(void)
{
	return nbiot_temp_connect_type;
}
/***************************************************************************
 * @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 NbiotTcpOpenTask(void)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
		if(!TcpIfOnline())
		{
			g_s_nbiot_mode_flag = ONLINE_MODE;
			g_s_nbiot_task_flag = TASK_INIT;
			g_s_nbiot_main_state = NBIOT_TCP_OPEN;
			TcpStartConnect();
		}        
    }   	
}*/
void NbiotReadECLSNRTask(u8 *state)
{
    if (NBIOT_S_IDLE == g_s_nbiot_main_state)
    {
        //        g_s_ecl_val = out_ecl;
        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
 ***************************************************************************/
void NbiotPreSleep(void)
{
    NB_Power_Disable(); //切断电源
    UartPreSleep(NB_UART_COM);
    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;
	//Nbiot_Para.tcp1_state = CONNECT_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);
}

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

/***************************************************************************
 * @fun_name    u8 NbiotOfflineReason()
 * @brief        查询NBIOT掉线原因
 * @param[in]    None
 * @param[out]   None
 * @retval       NBIOT参数改变；心跳异常；掉电掉线；主站主动下线；复位下线
 * @other        None
 ***************************************************************************/
//u8 NbiotOfflineReason(void)
//{
//    return Nbiot_Para.offline_reason;
//}

/******************************内部状态机***********************************/
//
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_E7025(void)
{
    static u8 s_at_error_count = 0; //记录AT错误或者指令超时次数  超过指定次数后认为任务失败
    
    static const char* c_ATE1 = "ATE1\r"; //E7025打开回显
    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+ECICCID\r";//E7025
    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_CGATT = "AT+CGATT?\r";
	static const char* c_AT_ECCESQS = "AT+ECCESQS=0\r";//关闭信号更新报告
	static const char* c_AT_ECSTATUS = "AT+ECSTATUS\r";//查询信号等关键参数
	static u8 c_AT_CGDCONT_APN[APN_SIZE+50] = "AT+CGDCONT=1,\"IP\",\""; //指定APN,定义数组大小为固定20字节+APN数组大小，再加预留空间
    static const char* c_AT_CFUN0 = "AT+CFUN=0\r"; //设置最小功能模式
    static const char* c_AT_CFUN1 = "AT+CFUN=1\r"; //设置正常功能模式
	
    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_LOW();//模组复位使能
            PWR_NB_HIG();//开机键不使能
            NB_Power_Enable(); 						//打开电源，延时1S,等待上电稳定
            set_timer_1ms(MODULE_POWER_DELAY_TIME);
            s_init_state = S_INIT_RESET_HIGH;//S_INIT_PWRKEY_LOW;
        }
        break;
        case S_INIT_RESET_HIGH://完成复位NB模块
        {
            if (!check_timer_1ms())
            {
                RSTN_NB_HIG();     //高电平
                s_init_state = S_INIT_POWER_ON_WAIT; //到时候查询CSQ和CEREG来确认搜网注册完成 已节约初始化时间 降低功耗
                set_timer_1s(5); //等待NB模块搜网注册5S --5秒时间不够 此时可以继续进行其他任务
            }
        }
        break;

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

        case S_INIT_ATS://打开回显, 确认模块正常运行
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_ATE1, strlen(c_ATE1), cst_AT_No_AT);
                s_init_state = S_INIT_ATS_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); 
            }
        }
        break;

        case S_INIT_ATS_R://等待"ATE1"应答
        {
            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); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        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(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_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(3*AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        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();
                if(0)//if(0 == Sys_data_object.product_test_state)
                {
					//Sys_data_object.product_test_state = 1; //单片机已经获取到三码，等待读取
                    s_init_state = S_INIT_POWER_ON;
                    g_s_nbiot_task_flag = TASK_INIT;
					StartPowerOffTask();				    //调用关机流程
                }
                else
                {
                    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); 
            }
        }
        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);
                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_CFUN0://设置模组最小功能模式
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CFUN0, strlen((const char*) c_AT_CFUN0), cst_AT_No_AT_CFUN);
                s_init_state = S_INIT_CFUN0_R;
                set_timer_1ms(2 * AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

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

        case S_INIT_AT_CGDCONT://配置网络参数
        {
			 if(!check_timer_1ms())
            {
                u8 ip_apn = 19;
				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_CFUN1://设置模组正常功能模式
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CFUN1, strlen((const char*) c_AT_CFUN1), cst_AT_No_AT_CFUN);
                s_init_state = S_INIT_CFUN1_R;
                set_timer_1ms(2 * AT_COMMAND_RECEIVE_WAIT_TIME);
            }
        }
        break;

        case S_INIT_CFUN1_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                //返回正确的应答
                s_at_error_count = 0;
				set_timer_1ms( AT_COMMAND_SEND_INTERVAL_TIME);
                s_init_state = S_INIT_ASK_CSQ;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1ms()))
            {
                //返回错误的应答或者定时时间到
                if (++s_at_error_count >= NUM_AT_CFUN_ERROR)
                {
                    s_at_error_count = 0;
                    set_timer_1ms( AT_COMMAND_SEND_INTERVAL_TIME);
					s_init_state = S_INIT_ASK_CSQ;
                }
                else
                {
                    s_init_state = S_INIT_CFUN1;
                    set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME);
                }
            }
        }
        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_AT_ECCESQS; 
                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_AT_ECCESQS; //开始查询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_AT_ECCESQS://关闭信号更新报告
        {
            if (!check_timer_1s())
            {
                NbiotUartSend((u8*) c_AT_ECCESQS, strlen(c_AT_ECCESQS), cst_AT_No_AT_ECCESQS);
                set_timer_1s(2);
                s_init_state = S_INIT_AT_ECCESQS_R;
            }
        }
        break;

        case S_INIT_AT_ECCESQS_R:
        {
            if (!check_timer_1s())
            {
                if (NbiotCheckAtAck() == UART_OK)
                {
                    //返回正确的应答
					s_at_error_count = 0;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                    s_init_state = S_INIT_AT_ECSTATUS;
                }
                else
                {
                    //返回错误的应答或者定时时间到
                    s_at_error_count++;
                    if (s_at_error_count >= 2)
                    {
                        s_at_error_count = 0;
						set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                        s_init_state = S_INIT_AT_ECSTATUS;
                    }
                    else
                    {
                        s_init_state = S_INIT_AT_ECCESQS;
						set_timer_1s(1);
                    }
                }
            }
        }
        break;

		case S_INIT_AT_ECSTATUS://查询信号等关键参数
        {
            if (!check_timer_1ms())
            {
                NbiotUartSend((u8*)c_AT_ECSTATUS, strlen((const char*) c_AT_ECSTATUS), cst_AT_No_AT_ECSTATUS);
                set_timer_1ms(4*AT_COMMAND_SEND_INTERVAL_TIME);//2s
                s_init_state = S_INIT_AT_ECSTATUS_R;
            }
        }
        break;

        case S_INIT_AT_ECSTATUS_R:
        {
            if (!check_timer_1ms())
            {
                if (NbiotCheckAtAck() == UART_OK)
                {
					 s_at_error_count = 0;
					s_init_state = S_INIT_ASK_CEREG; 
                }
                else
                {
                    //返回错误的应答或者定时时间到
                    s_at_error_count++;
                    if (s_at_error_count >= 2)
                    {
						s_at_error_count = 0;
						s_init_state = S_INIT_ASK_CEREG; 
                    }
                    else
                    {
                        s_init_state = S_INIT_AT_ECSTATUS;
                    }
                }
            }
        }
        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_ASK_CGATT;
                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)
                {
                    s_at_error_count = 0;
					s_init_state = S_INIT_ASK_CGATT;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_init_state = S_INIT_ASK_CEREG;
                    set_timer_1ms(2 * AT_COMMAND_SEND_INTERVAL_TIME);
                }
            }
        }
        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); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_INIT_ASK_CGATT_R://等待CGATT应答
        {
            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_CGATT_ERROR)
                {
                    s_at_error_count = 0;
					*Nbiot_Send_Data.state = NBIOT_ERROR;
					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;
        default:
        {
            s_at_error_count = 0;
			s_init_state = S_INIT_POWER_ON;
        }
        break;
    }
}
void NbiotInitMachine(void)
{
	NbiotInitMachine_E7025();
}
//
void CoapStartConnect(void)
{
	s_coap_connect_state = S_COAP_CONNECT_START;
}
/***************************************************************************
 * @fun_name     static void CoapConnectMachine()
 * @brief        连接Coap状态机
 ***************************************************************************/
void CoapConnectMachine_E7025(void)
{
    static u8 s_at_error_count = 0;
    unsigned char *nbiot_ip;
    u16 nbiot_port;
	static char c_AT_CTM2MSETPM[50] = "AT+CTM2MSETPM=\"117.060.157.137\",05683,86400\r"; //配置电信IOT平台连接参数
	static const char* c_AT_CTM2MREG = "AT+CTM2MREG\r"; //注册电信IOT平台
	static const char* c_AT_CCLK = "AT+CCLK?\r"; //查询基站时间
	
    switch (s_coap_connect_state)
    {
        case S_COAP_CONNECT_START:
        {
            s_at_error_count=0;
            s_coap_connect_state = S_AT_CTM2MSET; 
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        } 
        break;

        case S_AT_CTM2MSET://配置电信IOT平台连接参数
        {
            if (!check_timer_1ms())
            {
				u16 len = 15; //整条AT指令的长度，根据发送长度的位数来定
				nbiot_port = coap_port;
				nbiot_ip = coap_ip;
				
                //IP 的存储仍然使用水表原来格式，不保存“.”号，使用时加入
				int i;
				for (i = 0; i < 4; i++)
				{
					if (nbiot_ip[i] < 10)
					{
						c_AT_CTM2MSETPM[len++] = nbiot_ip[i] + 0x30;
					}
					else if (nbiot_ip[i] < 100)
					{
						c_AT_CTM2MSETPM[len++] = (nbiot_ip[i] / 10) + 0x30;
						c_AT_CTM2MSETPM[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					else
					{
						c_AT_CTM2MSETPM[len++] = (nbiot_ip[i] / 100) + 0x30;
						c_AT_CTM2MSETPM[len++] = (nbiot_ip[i] / 10) % 10 + 0x30;
						c_AT_CTM2MSETPM[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					c_AT_CTM2MSETPM[len++] = '.';
				}
				len--; //消除多余的点号
				
                c_AT_CTM2MSETPM[len++] = '\"';
                c_AT_CTM2MSETPM[len++] = ',';
                c_AT_CTM2MSETPM[len++] = ((nbiot_port) / 10000) + 0x30;
                c_AT_CTM2MSETPM[len++] = (((nbiot_port) % 10000) / 1000) + 0x30;
                c_AT_CTM2MSETPM[len++] = (((nbiot_port) % 1000) / 100) + 0x30;
                c_AT_CTM2MSETPM[len++] = (((nbiot_port) % 100) / 10) + 0x30;
                c_AT_CTM2MSETPM[len++] = ((nbiot_port) % 10) + 0x30;
				c_AT_CTM2MSETPM[len++] = ',';
				c_AT_CTM2MSETPM[len++] = '8';
				c_AT_CTM2MSETPM[len++] = '6';
				c_AT_CTM2MSETPM[len++] = '4';
				c_AT_CTM2MSETPM[len++] = '0';
				c_AT_CTM2MSETPM[len++] = '0';
                c_AT_CTM2MSETPM[len++] = '\r';
                NbiotUartSend((u8*)c_AT_CTM2MSETPM, len, cst_AT_No_AT_CTM2MSET);
                set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                s_coap_connect_state = S_AT_CTM2MSET_R;
            }
        }
        break;
		
		case S_AT_CTM2MSET_R:
		{
			if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
                s_coap_connect_state = S_AT_CTM2MREG;
                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 >= NUM_AT_CTM2MSET_ERROR)//
                {
					s_at_error_count = 0;
                    s_coap_connect_state = S_AT_CTM2MREG;
					set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
                }
                else
                {
                    s_coap_connect_state = S_AT_CTM2MSET;
                }
            }
		}
		break;
		
		case S_AT_CTM2MREG://注册电信IOT平台
		{
			if(!check_timer_1ms())
            {
                NbiotUartSend((u8*) c_AT_CTM2MREG, strlen(c_AT_CTM2MREG), cst_AT_No_AT_CTM2MREG);
                set_timer_1s(8);
                s_coap_connect_state = S_AT_CTM2MREG_R;
            }
		}
		break;
		
		case S_AT_CTM2MREG_R:
		{
			if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count = 0;
                s_coap_connect_state = S_AT_COAP_CCLK;
                set_timer_1s(1);
            }
            else if (!check_timer_1s() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_CTM2MREG_ERROR)//
                {
					*Nbiot_Send_Data.state = NBIOT_ERROR;
					g_s_nbiot_task_flag = TASK_FAIL; //到此为止任务成功
					s_at_error_count = 0;
					set_timer_1s(1);
					s_coap_connect_state = S_COAP_CONNECT_START; //状态机回归初始状态
                }
                else
                {
					set_timer_1ms(8*AT_COMMAND_SEND_INTERVAL_TIME);
                    s_coap_connect_state = S_AT_CTM2MREG;
                }
            }
		}
		break;
		
	
		case S_AT_COAP_CCLK://开始查询网络时间
        {
            if (!check_timer_1s())
            {
                NbiotUartSend((u8*) c_AT_CCLK, strlen(c_AT_CCLK), cst_AT_No_AT_CCLK);
                s_coap_connect_state = S_AT_COAP_CCLK_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_AT_COAP_CCLK_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_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
            {
                if (++s_at_error_count >= NUM_AT_CCLK_ERROR)
                {
					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
                {
                    s_coap_connect_state = S_COAP_CCLK;
                    set_timer_1s(1);
                }
            }
        }
        break;

        default:
        {
            s_coap_connect_state = S_COAP_CONNECT_START; //状态机回归初始状态
        }
        break;
    }
}
void CoapConnectMachine(void)
{
	CoapConnectMachine_E7025();
}
void StartNbiotSendData(void)
{
	if(g_s_nbiot_send_type == SEND_TYPE_COAP)
	{
		/*if(Nbiot_Para.Telecom == SIM_CARD_MOBILE)//移动卡
		{
			StartOnenetSendData();
		}
		else//电信卡
		{
			StartCoapSendData(); //数据发送状态机
		}*/
		StartTcpSendData();
	}
	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_E7025(void)
{
    static u8 s_at_error_count = 0; //AT指令累计发送失败次数
    static const u8 temp_AT_Buffer[]= {"AT+CTM2MSEND="};
    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 = 13;//8; //整条AT指令的长度，根据发送长度的位数来定
                int i;
                for(i=0; i<13; i++)
                {
                    c_AT_NMGS[i]=temp_AT_Buffer[i];
                }
                //发送内容
                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++] = '\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 >= 2)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = cst_AT_No_AT_NMGS;
                    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_E7025();
}
//启动连接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_E7025(void)
{
    static u8 s_at_error_count = 0;

    static char c_AT_QIOPEN[100];  
	
    switch (s_udp_connect_state)
    {
        case S_UDP_CONNECT_START: //任务开始
        {
            s_at_error_count=0;
            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+ECSOCR=DGRAM,17,1234,1,AF_INET\r"); //UDP
				len = strlen(c_AT_QIOPEN);              
				NbiotUartSend((u8*)c_AT_QIOPEN, len, cst_AT_No_AT_QIOPEN);
				set_timer_1s(2);
				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_Wait;
				set_timer_1s(1);
            }
            else if (!check_timer_1s() || 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_Wait;
					set_timer_1s(1);
                }
                else
                {
                    s_udp_connect_state = S_UDP_QIOPEN;
                }
            }
        }
        break;

        case S_UDP_Wait:
        {
            if((!check_timer_1s()))
            {
                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_E7025();
}

//TdpConnectMachine

//模组AT指令编号
typedef enum{
	S_TCP_CONNECT_START=0, 
	S_TCP_QIOPEN,
	S_TCP_QIOPEN_R,
	S_TCP_NCDP_CK,
	S_TCP_NCDP_CK_R,
	S_TCP_SUCCESS,
	S_TCP_FAIL
}TYP_AT_CMDCODE;

const char tcp_socket_buf[6]={'0','1','2','3','4','5'};
u8 tcp_socket_index=0;
TYP_AT_CMDCODE s_tcp_connect_state=S_TCP_CONNECT_START;
static char stringbuffer_temp[256];

void TcpStartConnect(void)
{
	s_tcp_connect_state = S_TCP_CONNECT_START;
}
void TcpConnectMachine(void)
{
	unsigned char *nbiot_ip;
    u16 nbiot_port;
    static u8 s_at_error_count = 0;
	//static const u8 temp_AT_Buffer[34]= {"AT+ECSOCR=DGRAM,17,1234,1,AF_INET\r"};
	static const u8 temp_AT_Buffer[34]= {"AT+ECSOCR=STREAM,6,1234,1,AF_INET\r"};//TCP
    static char c_AT_QIOPEN[50];  
	
    switch (s_tcp_connect_state)
    {
        case S_TCP_CONNECT_START: //任务开始
        {
            s_at_error_count=0;
            s_tcp_connect_state = S_TCP_QIOPEN;
			tcp_socket_index = 0;
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
        }
        break;

        case S_TCP_QIOPEN://创建套接字
        {
			if(TASK_IDLE == UartIfIdle(NB_UART_COM))
			{
				if (!check_timer_1ms())
				{
					u16 len = 0; //整条AT指令的长度，根据发送长度的位数来定
					int i;
					for(i=0; i<34; i++)
					{
						c_AT_QIOPEN[i]=temp_AT_Buffer[i];
					}
					if(tcp_socket_index>4)
					{
						tcp_socket_index = 0;
					}
					c_AT_QIOPEN[22] = tcp_socket_buf[tcp_socket_index];//更新socket
					
					len = 34;          
					NbiotUartSend((u8*)c_AT_QIOPEN, len, cst_AT_No_AT_QIOPEN);
					set_timer_1s(5);
					s_tcp_connect_state = S_TCP_QIOPEN_R;
				}
			}
        }
        break;

        case S_TCP_QIOPEN_R:
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count = 0;                
				s_tcp_connect_state = S_TCP_NCDP_CK;
				set_timer_1s(1);
            }
            else if (!check_timer_1s() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= 3)
                {
					s_at_error_count = 0;
					s_tcp_connect_state = S_TCP_FAIL;
					set_timer_1s(1);
                }
                else
                {
                    s_tcp_connect_state = S_TCP_QIOPEN;
                }
            }
        }
        break;
		case S_TCP_NCDP_CK://连接服务器
		{	
			if(TASK_IDLE == UartIfIdle(NB_UART_COM))
			{
				if (!check_timer_1s())
				{
					int ip_len = 0; 
					nbiot_port = coap_port;
					nbiot_ip = coap_ip;
					memset(stringbuffer_temp,0,sizeof(stringbuffer_temp));
					//"AT+ECSOCO=1,"183.230.174.137",6065"
					//IP 的存储仍然使用水表原来格式，不保存“.”号，使用时加入
					stringbuffer_temp[ip_len++]='A';
					stringbuffer_temp[ip_len++]='T';
					stringbuffer_temp[ip_len++]='+';
					stringbuffer_temp[ip_len++]='E';
					stringbuffer_temp[ip_len++]='C';
					stringbuffer_temp[ip_len++]='S';
					stringbuffer_temp[ip_len++]='O';
					stringbuffer_temp[ip_len++]='C';
					stringbuffer_temp[ip_len++]='O';
					stringbuffer_temp[ip_len++]='=';
					stringbuffer_temp[ip_len++]=NbiotGetE7025TcpSocket();
					stringbuffer_temp[ip_len++]=',';
					stringbuffer_temp[ip_len++]='"';
					
					for (int i = 0; i < 4; i++)
					{
						if (nbiot_ip[i] < 10)
						{
							stringbuffer_temp[ip_len++] = nbiot_ip[i] + 0x30;
						}
						else if (nbiot_ip[i] < 100)
						{
							stringbuffer_temp[ip_len++] = (nbiot_ip[i] / 10) + 0x30;
							stringbuffer_temp[ip_len++] = (nbiot_ip[i] % 10) + 0x30;
						}
						else
						{
							stringbuffer_temp[ip_len++] = (nbiot_ip[i] / 100) + 0x30;
							stringbuffer_temp[ip_len++] = (nbiot_ip[i] / 10) % 10 + 0x30;
							stringbuffer_temp[ip_len++] = (nbiot_ip[i] % 10) + 0x30;
						}
						stringbuffer_temp[ip_len++] = '.';
					}
					ip_len--; //消除多余的点号
					stringbuffer_temp[ip_len++] = '\"';
					stringbuffer_temp[ip_len++] = ',';
					stringbuffer_temp[ip_len++] = ((nbiot_port) / 10000) + 0x30;
					stringbuffer_temp[ip_len++] = (((nbiot_port) % 10000) / 1000) + 0x30;
					stringbuffer_temp[ip_len++] = (((nbiot_port) % 1000) / 100) + 0x30;
					stringbuffer_temp[ip_len++] = (((nbiot_port) % 100) / 10) + 0x30;
					stringbuffer_temp[ip_len++] = ((nbiot_port) % 10) + 0x30;
					stringbuffer_temp[ip_len++] = '\r';
					
					NbiotUartSend((u8*)stringbuffer_temp, ip_len, cst_AT_No_AT);
					set_timer_1s(10);
					s_tcp_connect_state = S_TCP_NCDP_CK_R;
				}
			}
		}
		break;
		
		case S_TCP_NCDP_CK_R:
		{
			if (NbiotCheckAtAck() == UART_OK)
            {
				s_at_error_count = 0;                
				s_tcp_connect_state = S_TCP_SUCCESS;
				set_timer_1s(1);
            }
            else if (!check_timer_1s() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= 5)//
                {
					s_at_error_count = 0;
					s_tcp_connect_state = S_TCP_FAIL;
					set_timer_1s(1);
                }
                else
                {
                    s_tcp_connect_state = S_TCP_NCDP_CK;
                }
            }
		}
		break;
		
        case S_TCP_SUCCESS:
        {
            if((!check_timer_1s()))
            {
                s_at_error_count = 0;
                s_tcp_connect_state = S_TCP_CONNECT_START; //状态机回归初始状态
                g_s_nbiot_task_flag = TASK_SUCCESS; //到此为止任务成功
            }
        }
        break;
		
		case S_TCP_FAIL:
        {
            if((!check_timer_1s()))
            {
                s_at_error_count = 0;
                s_tcp_connect_state = S_TCP_CONNECT_START; //状态机回归初始状态
                g_s_nbiot_task_flag = TASK_FAIL; //到此为止任务成功
            }
        }
        break;

        default:
        {
            s_tcp_connect_state = S_TCP_CONNECT_START; //状态机回归初始状态
        }
        break;
    }
}
//
void StartUdpSendData(void)
{
	s_udp_send_state = S_SEND_START;
}
//AT+ECSOST=1,"183.230.174.137",6065,2,"3334"
void UdpSendDataMachine_E7025(void)
{
	unsigned char *nbiot_ip;
    u16 nbiot_port;	
    static u8 s_at_error_count = 0; //AT指令累计发送失败次数
	static const u8 temp_AT_Buffer[10]= {"AT+ECSOST="};
    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 = 0; //整条AT指令的长度，根据发送长度的位数来定
				nbiot_port = udp_port1;
				nbiot_ip = udp_ip1;
				int i;	
				for(i=0;i<10;i++)
				{
					c_AT_NMGS[len++] = temp_AT_Buffer[i];
				}
				//socekt
				c_AT_NMGS[len++] = NbiotGetE7025UdpSocket();//socket范围为0~6
				c_AT_NMGS[len++] = ',';
				c_AT_NMGS[len++] = '\"';
				//IP: NSOST Udp发送使用
				for (i = 0; i < 4; i++)
				{
					if (nbiot_ip[i] < 10)
					{
						c_AT_NMGS[len++] = nbiot_ip[i] + 0x30;
					}
					else if (nbiot_ip[i] < 100)
					{
						c_AT_NMGS[len++] = (nbiot_ip[i] / 10) + 0x30;
						c_AT_NMGS[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					else
					{
						c_AT_NMGS[len++] = (nbiot_ip[i] / 100) + 0x30;
						c_AT_NMGS[len++] = (nbiot_ip[i] / 10) % 10 + 0x30;
						c_AT_NMGS[len++] = (nbiot_ip[i] % 10) + 0x30;
					}
					c_AT_NMGS[len++] = '.';
				}
				//端口号
				len--; //消除多余的点号 
				c_AT_NMGS[len++] = '\"';
				c_AT_NMGS[len++] = ',';
				c_AT_NMGS[len++] = (nbiot_port / 10000) + 0x30;
				c_AT_NMGS[len++] = (nbiot_port % 10000) / 1000 + 0x30;
				c_AT_NMGS[len++] = (nbiot_port % 1000) / 100 + 0x30;
				c_AT_NMGS[len++] = (nbiot_port % 100) / 10 + 0x30;
				c_AT_NMGS[len++] = (nbiot_port % 10) + 0x30;
				c_AT_NMGS[len++] = ',';
				//长度
				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;
					}
				}
				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 >= 2)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = cst_AT_No_AT_NMGS;
                    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_E7025();
}

u8 s_tcp_send_state=S_SEND_START;
void StartTcpSendData(void)
{
	s_tcp_send_state = S_SEND_START;
}
//AT+ECSOST=1,"183.230.174.137",6065,2,"3334"
//AT+ECSOSD=1,2,"3132"
void TcpSendDataMachine(void)
{
    static u8 s_at_error_count = 0; //AT指令累计发送失败次数
	static const u8 temp_AT_Buffer[10]= {"AT+ECSOSD="};
    switch (s_tcp_send_state)
    {
        case S_SEND_START:
        {
            s_tcp_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 = 0; //整条AT指令的长度，根据发送长度的位数来定
				for(int i=0;i<10;i++)
				{
					c_AT_NMGS[len++] = temp_AT_Buffer[i];
				}
				//socekt
				c_AT_NMGS[len++] = NbiotGetE7025TcpSocket();//socket范围为0~6
				c_AT_NMGS[len++] = ',';
				//长度
				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 (int 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_tcp_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_tcp_send_state = S_SEND_START;
            }
            else if (NbiotCheckAtAck() == UART_ERROR || (!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= 2)
                {
                    s_at_error_count = 0;
                    *Nbiot_Send_Data.state = cst_AT_No_AT_NMGS;
                    g_s_nbiot_task_flag = TASK_SUCCESS;
                    s_tcp_send_state = S_SEND_START;
                }
                else
                {
					set_timer_1s(4);
                    s_tcp_send_state = S_SEND_DATA;
                }
            }
        }
        break;

        default:
        {
            s_tcp_send_state = S_SEND_START;
        }
        break;
    }
}

void UdpReadDataMachine_E7025(void)
{
    static u8 s_error_count; //AT指令累计发送失败次数
    static u8 s_read_upd_data_state = S_START;
	static const u8 temp_AT_Buffer[16]= {"AT+ECSORF=2,512\r"};
    switch (s_read_upd_data_state)
    {
        case S_START:
        {
            set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
            s_error_count = 0;
            s_read_upd_data_state = S_AT_QIRD;
        }
        break;

        case S_AT_QIRD:
        {
            if (!check_timer_1ms())
            {
				u16 len=0;
				int i;	
				for(i=0;i<16;i++)
				{
					c_AT_NMGS[len++] = temp_AT_Buffer[i];
				}
				c_AT_NMGS[10] = NbiotGetE7025UdpSocket();//socket范围为0~6
                 NbiotUartSend((u8*) c_AT_NMGS, len, cst_AT_No_AT_UPD_READ);
                set_timer_1ms(3*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);
					s_read_upd_data_state = S_AT_QIRD;
				}
			}            
        }
        break;

        default:
        {
            s_read_upd_data_state = S_START;
        }
        break;
    }	
}
void UdpReadDataMachine(void)
{
   UdpReadDataMachine_E7025();
}
//
//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_3 = "AT+MIPLCONFIG=3,0\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_CCLK = "AT+CCLK?\r"; //查询基站时间
	static char c_AT_MIPLRSP_BUF[40];// 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 = coap_port;
				nbiot_ip = coap_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(2);
				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;//S_ONENET_MIPLCONFIG3;
                set_timer_1s(2);
            }
            else if (!check_timer_1s() || NbiotCheckAtAck() == UART_ERROR)
            {
                s_at_error_count++;
                if (s_at_error_count >= AT_ERROR)//
                {
					//一般不会发生,肯定能查到返回结果
					s_at_error_count = 0;
					s_onenet_connect_state = S_ONENET_MIPLCONFIG_CK;//S_ONENET_MIPLCONFIG3;
					set_timer_1s(2);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLCONFIG;
                }
            }
        }
        break;

        case S_ONENET_MIPLCONFIG_CK:
        {
			 if (!check_timer_1s())
			 {
				 if(TASK_IDLE == UartIfIdle(NB_UART_COM))
				 {
				 	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_1s(2);
            }
            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_1s(2);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLCONFIG_CK;
                }
            }
        }
        break;

        case S_ONENET_MIPLCREATE:
        {
            if(!check_timer_1s())
            {
				if(TASK_IDLE == UartIfIdle(NB_UART_COM))
				{
					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_1s(2);
            }
            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_1s(2);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLCREATE;
                    set_timer_1s(2);
                }
            }
        }
        break;
		
		case S_ONENET_MIPLADDOBJ:
        {
            if(!check_timer_1s())
            {
				if(TASK_IDLE == UartIfIdle(NB_UART_COM))
				{
					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_1s(2);
            }
            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_1s(2);
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLADDOBJ;
                    set_timer_1s(1);
                }
            }
        }
        break;
	
        case S_ONENET_MIPLOPEN:
        {
            if (!check_timer_1s())
            {
                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();
				NbiotSetRevMiplobserve();
				set_timer_1s(10);
                s_onenet_connect_state = S_ONENET_MIPLOBSERVE;
            }
 
            else if ((!check_timer_1s()))
            {
                s_at_error_count++;

                if (s_at_error_count >= NUM_AT_MIPLOPEN_ERROR)
                {
					*Nbiot_Send_Data.state = NBIOT_ERROR;
					g_s_nbiot_task_flag = TASK_FAIL; //到此为止任务成功
                    s_at_error_count	= 0;
                    s_onenet_connect_state = S_ONENET_MIPLOBSERVE;
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_MIPLOPEN;
                    set_timer_1s(1);
                }
            }
        }
        break;

        case S_ONENET_MIPLOBSERVE: //static char c_AT_MIPLDISCOVERRSP[30];// AT+MIPLDISCOVERRSP=0,48839,1,4,"5750"
        {
			if ((NbiotCheckAtAck() == UART_OK)||(!check_timer_1s()))
			{
				u8	len;
				char  observe_num[10];
				memset(observe_num, 0, sizeof(observe_num));
				memset(c_AT_MIPLRSP_BUF, 0, sizeof(c_AT_MIPLRSP_BUF));
				strcpy(c_AT_MIPLRSP_BUF, "AT+MIPLOBSERVERSP=0,");

				NbiotGetObserve_num(observe_num);
				strcat(c_AT_MIPLRSP_BUF, observe_num);
				strcat(c_AT_MIPLRSP_BUF, ",1\r");

				len = strlen(c_AT_MIPLRSP_BUF);
				NbiotUartSend((u8 *) c_AT_MIPLRSP_BUF, len, cst_AT_No_AT);
				set_timer_1s(2);

				s_onenet_connect_state = S_ONENET_MIPLOBSERVE_R;
			}
        }
        break;

        case S_ONENET_MIPLOBSERVE_R: //应答接收到数据--等待响应
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                s_at_error_count	= 0;
				NbiotClearAtAck();
				NbiotSetRevMipldiscover(); 
				set_timer_1s(5);
                s_onenet_connect_state = S_ONENET_MIPLDISCOVER;
            }
            else if ((!check_timer_1s()))
            {
                s_at_error_count++;
                if (s_at_error_count >= NUM_AT_MIPLOBSERVERSP_ERROR)
                {
                    *Nbiot_Send_Data.state = NBIOT_ERROR;
					g_s_nbiot_task_flag = TASK_FAIL; //到此为止任务成功
                    set_timer_1s(1);
                    s_at_error_count	= 0;
                    s_onenet_connect_state = S_ONENET_CONNECT_IDLE;
                }
                else
                {    
					set_timer_1s(5);					
                    s_onenet_connect_state = S_ONENET_MIPLOBSERVE;
                }
            }
        }
        break;

        case S_ONENET_MIPLDISCOVER: 
        {
			if ((NbiotCheckAtAck() == UART_OK)||(!check_timer_1s()))	
            {
				u8	len;
				char discover_num[10];
				memset(discover_num, 0, sizeof(discover_num));
                memset(c_AT_MIPLRSP_BUF, 0, sizeof(c_AT_MIPLRSP_BUF));
                strcpy(c_AT_MIPLRSP_BUF, "AT+MIPLDISCOVERRSP=0,");

                NbiotGetDiscover_num(discover_num);
                strcat(c_AT_MIPLRSP_BUF, discover_num);
                strcat(c_AT_MIPLRSP_BUF, ",1,4,\"5750\"\r");

                len = strlen(c_AT_MIPLRSP_BUF);
                NbiotUartSend((u8 *) c_AT_MIPLRSP_BUF, len, cst_AT_No_AT);
				set_timer_1s(5);
                s_onenet_connect_state = S_ONENET_MIPLDISCOVER_R;
            }
        }
        break;

        case S_ONENET_MIPLDISCOVER_R: //应答接收到数据--等待响应
        {
            if (NbiotCheckAtAck() == UART_OK)
            {
                set_timer_1s(1);
                s_at_error_count	= 0;
                s_onenet_connect_state = S_ONENET_CCLK;
            }
            else if ((!check_timer_1s()))
            {
                s_at_error_count++;

                if (s_at_error_count >= NUM_AT_MIPLDISCOVERRSP_ERROR)
                {
					*Nbiot_Send_Data.state = NBIOT_ERROR;
					g_s_nbiot_task_flag = TASK_FAIL; //到此为止任务成功
                    set_timer_1s(1);
                    s_at_error_count	= 0;
                    s_onenet_connect_state = S_ONENET_CONNECT_IDLE;
                }
                else
                {
                    NbiotSetRevMipldiscover(); 
                    s_onenet_connect_state = S_ONENET_MIPLDISCOVER;
                    set_timer_1s(5);
                }
            }
        }
        break;		
		
		case S_ONENET_CCLK://开始查询网络时间
        {
            if (!check_timer_1s())
            {
                NbiotUartSend((u8*) c_AT_CCLK, strlen(c_AT_CCLK), cst_AT_No_AT_CCLK);
                s_onenet_connect_state = S_ONENET_CCLK_R;
                set_timer_1ms(AT_COMMAND_RECEIVE_WAIT_TIME); //测试报告中AT指令返回的最长时间300ms(不包含发送和接收占用的时间)
            }
        }
        break;

        case S_ONENET_CCLK_R://等待应答
        {
            if (NbiotCheckAtAck() == UART_OK)//正确应答
            {
                s_at_error_count = 0;
                s_onenet_connect_state = S_ONENET_Wait; //状态机回归初始状态
                
            }
            else if ((!check_timer_1ms()) || (NbiotCheckAtAck() == UART_ERROR))//应答超时
            {
                if (++s_at_error_count >= NUM_AT_CCLK_ERROR)
                {
                    s_at_error_count = 0;
                  
                    s_onenet_connect_state = S_ONENET_Wait; //状态机回归初始状态
                   
                }
                else
                {
                    s_onenet_connect_state = S_ONENET_CCLK;
                    set_timer_1s(1);
                }
            }
        }
        break;		
		
        case S_ONENET_Wait:
        {
            if ((!check_timer_1s()))
            {
                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;
}

void OneNetSendDataMachine(void)
{
    char observe_num[10];
    static const char temp_AT_MIPLDISCOVERRSP1[] = "AT+MIPLNOTIFY=0,";
    static const char temp_AT_MIPLDISCOVERRSP2[] = ",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_MIPLDISCOVERRSP1);
                    memset(observe_num, 0, sizeof(observe_num));
                    NbiotGetObserve_num(observe_num);
                    //NbiotGetDiscover_num(observe_num);

                    strcat(c_AT_NMGS, observe_num);
                    strcat(c_AT_NMGS, temp_AT_MIPLDISCOVERRSP2);

                    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 SEND_ACKID_ENABLE
                    char strtemp[8];

                    if(++Send_AckID == 0) Send_AckID = 1; //Send_AckID==0的时候模块会报错ERROR

                    sprintf(strtemp, ",%u", Send_AckID);
                    strcat(c_AT_MIPLNOTIFY, strtemp);
                    strcat(c_AT_MIPLNOTIFY, "\r");
                    NbiotClearMsg();
                    NbiotUartSend((u8*) c_AT_MIPLNOTIFY, strlen(c_AT_MIPLNOTIFY), 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);
                    #endif
                    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 = cst_AT_No_AT_MIPLNOTIFY;
            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_NETCLOSE = "AT+CTM2MDEREG\r";
	//static const char* c_AT_TCPCLOSE = "AT+ECSOCL=1\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_QPOWD = "AT+QPOWD=1\r";
    switch (s_power_off_state)
    {
        case S_POWER_OFF_START:
        {
            s_at_error_count = 0;
			
			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;
//			Nbiot_Para.tcp1_state = CONNECT_OFF_LINE;

			set_timer_1ms(AT_COMMAND_SEND_INTERVAL_TIME);
			s_power_off_state = S_AT_NETCLOSE;
        }
        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_MIPLNOTIFY_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_POWER_OFF;
			}
			else
			{
				int len=0; // "AT+ECSOCL=1\r";
				memset(stringbuffer_temp,0,sizeof(stringbuffer_temp));
				//"AT+ECSOCO=1,"183.230.174.137",6065"
				//IP 的存储仍然使用水表原来格式，不保存“.”号，使用时加入
				stringbuffer_temp[len++]='A';
				stringbuffer_temp[len++]='T';
				stringbuffer_temp[len++]='+';
				stringbuffer_temp[len++]='E';
				stringbuffer_temp[len++]='C';
				stringbuffer_temp[len++]='S';
				stringbuffer_temp[len++]='O';
				stringbuffer_temp[len++]='C';
				stringbuffer_temp[len++]='L';
				stringbuffer_temp[len++]='=';
				stringbuffer_temp[len++]=NbiotGetE7025TcpSocket();
				stringbuffer_temp[len++]='\r';
				
				NbiotUartSend((u8*) stringbuffer_temp,len, cst_AT_No_AT);
				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_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_NETCLOSE;
                }
            }
        }
        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_POWER_OFF;
            }
            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_POWER_OFF;
                }
                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.udp1_state = CONNECT_OFF_LINE;
				Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
//				Nbiot_Para.tcp1_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;
    static const u8 c_AT_NUESTATS[] = "AT+QENG=0\r";
    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    定时器资源
 * @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.udp1_state = CONNECT_OFF_LINE;
	Nbiot_Para.udp2_state = CONNECT_OFF_LINE;
//	Nbiot_Para.tcp1_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.NB_module_IMEI_0016);
//    NbiotGetIMSI(Sys_data_object.NB_module_IMSI);
//    NbiotGetICCID(Sys_data_object.SIMCard_ICCID_200A);
}
u32 sys_get_net_state (void)
{
	return 0;
}
#ifdef	__cplusplus
}
#endif

#endif
