#include "led.h"
#include "app.h"
#include "device.h"
#include "ch455g.h"
#include "net_proc.h"
#include "bsp.h"
#include "at_module.h"
#include "net_ctrl.h"
#include "me3616.h"
#include "./gateway_collect/gateway_collect.h"
#include "../APP/tax/tax.h"
#include "../APP/network/downlink.h"
#include "../APP/command/uart_conf.h"
#include "../BSP/Uart.h"
#include "../APP/network/nettimer.h"
#include "../APP/network_mgr/net_proc.h"
#include "../APP/network/timeout.h"
#include "../BSP/adc.h"
#include "../BSP/BSP.h"
#include "./storage/AT24C128Opt.h"
#include "./network_mgr/sx1268/lora.h"
#include "./ota/ota.h"
extern ME3616  air;

/*
*********************************************************************************************************
*                                            LOCAL VARIABLES
*********************************************************************************************************
*/
extern float Temp_test(void);

OS_TCB   LED_TASK_HandleTCB;
CPU_STK  LED_TASK_HandleStk[APP_TASK_START_STK_SIZE];
void 		 LED_TASK_Handle(void * p_arg);

OS_TCB   UART_TASK_HandleTCB;
CPU_STK  UART_TASK_HandleStk[UART_TASK_START_STK_SIZE];
void 		 UART_TASK_Handle(void * p_arg);

OS_TCB   PROG_TASK_HandleTCB;
CPU_STK  PROG_TASK_HandleStk[PROG_TASK_START_STK_SIZE];
void 		 PROG_TASK_Handle(void * p_arg);

OS_TCB   SVC_TASK_HandleTCB;
CPU_STK  SVC_TASK_HandleStk[SVC_TASK_START_STK_SIZE];
void 		 SVC_TASK_Handle(void * p_arg);

OS_TCB   LORA_TASK_HandleTCB;
CPU_STK  LORA_TASK_HandleStk[LORA_TASK_START_STK_SIZE];
void 		 LORA_TASK_Handle(void * p_arg);

OS_TCB   INFO_TASK_HandleTCB;
CPU_STK  INFO_TASK_HandleStk[INFO_TASK_START_STK_SIZE];
void 		 INFO_TASK_Handle(void * p_arg);

OS_TCB   NETTIM_TASK_HandleTCB;
CPU_STK  NETTIM_TASK_HandleStk[NETTIM_TASK_START_STK_SIZE];
void 		 NETTIM_TASK_Handle(void * p_arg);

/*
*********************************************************************************************************
*                                          STARTUP TASK
*
* Description : This is an example of a startup task.  As mentioned in the book's text, you MUST
*               initialize the ticker only once multitasking has started.
*
* Arguments   : p_arg   is the argument passed to 'AppTaskStart()' by 'OSTaskCreate()'.
*
* Returns     : none
*
* Notes       : 1) The first line of code is used to prevent a compiler warning because 'p_arg' is not
*                  used.  The compiler should not generate any code for this statement.
*********************************************************************************************************
*/
//extern u8 USART3_RX_BUF[128];     //接收缓冲,最大USART_REC_LEN个字节.
//接收状态
//bit15，	接收完成标志
//bit14，	接收到0x0d
//bit13~0，	接收到的有效字节数目
extern u16 USART3_RX_STA; 
extern int rcv_flag;
int len;

void init_powerup_ledstatus(void)
{
    uint16_t ledstatus = 0;
    volatile uint32_t i = 0;

    ledstatus = (~ledstatus&0xFFFF);
    set_led_no_init_sn(ledstatus);
    for(i=0;i<500000;i++);
    //ledstatus = (~ledstatus&0x0FFF);
   //   set_led_no_init_sn(ledstatus);
}

void  AppTaskStart (void *p_arg)
{
    OS_ERR err;
    uint16_t flash_size, ram_size;
    uint8_t chip_id[12];
    uint16_t data = 0,bdr2 =0;//data1 = 0,
    uint16_t bfirstPowerup = 0;
//	g_ptTest.bTestStart = 1;
//    uint8_t uuid[12] = {0x45,0x50,0x47,0x46,0x34,0x39,0x33,0x0f,0x39,0x30,0x36,0x31};
//    uint8_t i = 0,flag = 0;

    BSP_Init();        // Initialize BSP functions
    CPU_Init();        // Initialize the uC/CPU services
    CH455_Init();


  //  cmd_init(UART_DEBUG);
    init_powerup_ledstatus();
    cpuidGetId(); //读取芯片ID
    getcpuTypeIdcode();
	//g_ptTest.bTestStart = 1;

     printf("\r\n App Start \r\n");

    bfirstPowerup = fram_read_eeprom_powerUpFlag();
    fram_read_gateway_hardware_msg();
    if((bfirstPowerup != 0x55AA) ) {
        if(downlink_config.gateway_id==0xFFFFFFFF) {
            printf("设备没有初始化\r\n");
            system_first_powerup();
        }
        else if(downlink_config.gateway_id == 0x00000000){
            printf("设备进行过操作\r\n");
        }
        else {
            printf("设备异常%010u\r\n",downlink_config.gateway_id);
        }
    }

// BKP_DR2: 放的为升级标志，回退标志
// BKP_DR5: 存储的为升级来源，是网络还是离线升级,还用于网络升级第一次没有上报状态，重启了，需要再次上报状态
// BKP_DR3: 升级的状态码
// BKP_DR4: 升级的任务号
    data = BKP_ReadBackupRegister(BKP_DR2); // 升级标志
    bdr2 = data;
    if(data != 0){
        if(updata_state_cmp(data)){
            if((data&0x00ff) == 0x82){ // 升级成功
                data = set_updata_state(UPDATE_SUCCESS);
                BKP_WriteBackupRegister(BKP_DR3, data);
                printf("\r\n send to net update sucess\r\n");

            }
            else if((data&0x00ff) == 0x83) { // 回退成功
                data = set_updata_state(UPDATE_RETURN_SUCESS);
                BKP_WriteBackupRegister(BKP_DR3, data);
                 printf("\r\n send to net return sucess\r\n");
            }
            printf("\r\n update status1 = %x\r\n",data);
            BKP_WriteBackupRegister(BKP_DR2, 0);
            data = BKP_ReadBackupRegister(BKP_DR3);
            g_runData.bsendUpdateStatus = data&0xFF;
            data = BKP_ReadBackupRegister(BKP_DR5);
            if(data == UP_PROG_FROM_NET){
                BKP_WriteBackupRegister(BKP_DR5, bdr2);
                g_runData.bResetUpdate = 1;
						}
            else {
                g_runData.bResetUpdate = 2;
                BKP_WriteBackupRegister(BKP_DR5, 0);
            }
        }
    }
    else{
        data = BKP_ReadBackupRegister(BKP_DR5);
        if(data != 0) {
            g_runData.bResetUpdate = 1;
            data = BKP_ReadBackupRegister(BKP_DR3);
            g_runData.bsendUpdateStatus = data&0xFF;
            printf("last no send update status\r\n");
        }
        else {
            g_runData.bResetUpdate = 0;
            printf("\r\n no update program, data = %x\r\n",data);
        }
    }

    //printf("coll_msg size = %d\r\n",sizeof(collect_conf_t));

    check_usim_status(0);


	
#if OS_CFG_STAT_TASK_EN > 0u                                    //如果使能（默认使能）了统计任务
    OSStatTaskCPUUsageInit(&err);                               //计算没有应用任务（只有空闲任务）运行时 CPU 的（最大）
#endif                                                          //容量（决定 OS_Stat_IdleCtrMax 的值，为后面计算 CPU 
    //使用率使用）。

	board_info_get(&flash_size, &ram_size, chip_id);
      /*  if(downlink_config.gateway_id == 0x00000000) {
            printf("设备SN为0,需要操作\r\n");
            for(i=0;i<12;i++){
                if(g_firmwareMsg.gatewayMsg.Uuid[i] != uuid[i]){
                    flag = 1;
                    break;
                }
            }
            if(flag == 0){
                printf("已写入\r\n");
                downlink_config.gateway_id = 161;
                g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn = 161;
                fram_write_gateway_hardware_msg();
            }
        }*/
#if 0//for test
	adc_test();
	SPI_FLASH_Test();
	SPI_E2PROM_Test();
	I2C_Test();
	can_test();
#endif	

    OSTaskCreate((OS_TCB     *)&LED_TASK_HandleTCB, 
                 (CPU_CHAR   *)"LED TASK Handle",
                 (OS_TASK_PTR )LED_TASK_Handle,
                 (void       *)0,
                 (OS_PRIO     )LED_TASK_PRIO,
                 (CPU_STK    *)&LED_TASK_HandleStk[0],
                 (CPU_STK_SIZE)APP_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)APP_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

    OSTaskCreate((OS_TCB     *)&UART_TASK_HandleTCB,
                 (CPU_CHAR   *)"UART TASK Handle",
                 (OS_TASK_PTR )UART_TASK_Handle,  //串口数据查询
                 (void       *)0,
                 (OS_PRIO     )UART_TASK_PRIO,
                 (CPU_STK    *)&UART_TASK_HandleStk[0],
                 (CPU_STK_SIZE)UART_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)UART_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

    OSTaskCreate((OS_TCB     *)&LORA_TASK_HandleTCB,
                 (CPU_CHAR   *)"LORA TASK Handle",
                 (OS_TASK_PTR )LORA_TASK_Handle, // lora数据处理
                 (void       *)0,
                 (OS_PRIO     )LORA_TASK_PRIO,
                 (CPU_STK    *)&LORA_TASK_HandleStk[0],
                 (CPU_STK_SIZE)LORA_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)LORA_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

    OSTaskCreate((OS_TCB     *)&PROG_TASK_HandleTCB,
                 (CPU_CHAR   *)"PROG TASK Handle",
                 (OS_TASK_PTR )PROG_TASK_Handle, // 4G模块收发处理
                 (void       *)0,
                 (OS_PRIO     )PROG_TASK_PRIO,
                 (CPU_STK    *)&PROG_TASK_HandleStk[0],
                 (CPU_STK_SIZE)PROG_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)PROG_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

   /* OSTaskCreate((OS_TCB     *)&SVC_TASK_HandleTCB,
                 (CPU_CHAR   *)"SVC TASK Handle",
                 (OS_TASK_PTR )SVC_TASK_Handle,  // 设备初始化
                 (void       *)0,
                 (OS_PRIO     )SVC_TASK_PRIO,
                 (CPU_STK    *)&SVC_TASK_HandleStk[0],
                 (CPU_STK_SIZE)SVC_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)SVC_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);*/
								 
    OSTaskCreate((OS_TCB     *)&INFO_TASK_HandleTCB,
                 (CPU_CHAR   *)"INFO TASK Handle",
                 (OS_TASK_PTR )INFO_TASK_Handle, //网关查询采集器的信息 0x86 0x83 0x89这组协议是明文
                 (void       *)0,
                 (OS_PRIO     )INFO_TASK_PRIO,
                 (CPU_STK    *)&INFO_TASK_HandleStk[0],
                 (CPU_STK_SIZE)INFO_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)INFO_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);
    OSTaskCreate((OS_TCB     *)&NETTIM_TASK_HandleTCB,
                 (CPU_CHAR   *)"NETTIM TASK Handle",
                 (OS_TASK_PTR )NETTIM_TASK_Handle, //网关查询采集器的信息 0x86 0x83 0x89这组协议是明文
                 (void       *)0,
                 (OS_PRIO     )NETTIM_TASK_PRIO,
                 (CPU_STK    *)&NETTIM_TASK_HandleStk[0],
                 (CPU_STK_SIZE)NETTIM_TASK_START_STK_SIZE / 10,
                 (CPU_STK_SIZE)NETTIM_TASK_START_STK_SIZE,
                 (OS_MSG_QTY  )0,
                 (OS_TICK     )0,
                 (void       *)0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

    OSTaskDel(&AppTaskStartTCB, &err);
		
}

extern uint64_t g_checkDa[16][2][8];
uint8_t rcv_buf[128], rcv_size = 0;
//uint8_t lora_buf[13] = "this is gw";
void LED_TASK_Handle(void * p_arg)//信息传输装置
{
    uint8_t i = 0,j=0,k=0;
    uint8_t key = 0;//,time = 0;
    //char val = 0;
    OS_ERR  err;
    float vol=0.0,sumVol = 0.0,temperature = 0.0;//, sumTemperature = 0.0;
    float sref = 0.0;//, stemp = 0.0;
    uint16_t temp=0;
    static uint32_t sumtemp = 0;
    static uint16_t times = 0,ledstatus = 0,tempertureTimes = 0;
    static uint8_t flag = 0;
    float Vdd = 0.0;
    uint16_t ref;
    (void)p_arg;
    SysTick_init();
    g_ledStatus.ledM = LED_M_LOW;
    while (1)
    {

        if(flag>=g_ledStatus.ledM){
            LED_RUN = !LED_RUN;
            flag = 0;
            if(downlink_config.gateway_id==0x00000000 || downlink_config.gateway_id==0xFFFFFFFF) {
              ledstatus = (~ledstatus&0x0FFF);
              ledstatus = ((g_firmwareExpl.dd<<4)&0xF000) | ledstatus;
                set_led_no_init_sn(ledstatus);
            }
        }
        flag++;

        key=KEY_Scan(0);	//
        if(key == KEY0_PRES){ // 拓盛密文立即读取
            g_runData.bReadMingWenData=5;
            for(i=0;i<downlink_config.collect_num;i++){
                for(j=0;j<2;j++){
                    for(k=0;k<8;k++){
                        g_checkDa[i][j][k] = 0;
                    }
                }
            }
        }
        else if(key == KEY1_PRES){ // 显示lora信道索引
            if(key_info.state == 0){
                key_info.state = 1;
                key_info.num = 0;
                timeout_setValue(&key_info.tt_key_state,5*1000);//设置按键计时参数
                timeout_start(&key_info.tt_key_state);
            }
            key_info.num++;
            key_info.keyvalue = key;
            printf("key num:%d\n",key_info.num);
        }
        else if(key == KEY2_PRES){
            printf("按键k2 \n");
            //updata_state = UPDATA_DATA_SUCCESS;
            //updata_state_save = set_updata_state(updata_state);
           // BKP_WriteBackupRegister(BKP_DR3, updata_state_save);
            //置升级标志
            //updata_state_info.updata_flag = set_updata_state(UPDATA_FLAG);
           // BKP_WriteBackupRegister(BKP_DR2, updata_state_info.updata_flag);
        }


        if(key_info.keyvalue == KEY1_PRES) {
            if(timeout_isOut(&key_info.tt_key_state))//按键计时
            {
                  //timeout_stop(&key_info.tt_key_state);
                  key_info.state = 0;
                  if(key_info.num == 1)//5s内按一次按键.信道灯显示
                  {
                    g_ledStatus.status = LED_DISP_LORA;
                    set_led_lora_index(g_runData.curloraIndex+1);
                    timeout_setValue(&key_info.tt_key_state,3*1000);//设置loraindex灯计时参数
                    timeout_start(&key_info.tt_key_state);
                    key_info.optcmd = 1;
                  }
                  else if(key_info.num == 3) { // 5S内按三次，进行升级任务
                    printf("key = 3\r\n");
                    gateway_update_gateway_proc();
                  }
                key_info.num = 0;
            }

            //lora组号灯计时
            if(timeout_isOut(&key_info.tt_key_state))//灯亮超时
            {
                if(key_info.optcmd==1){ //信道
                    g_ledStatus.status = LED_DISP_NULL;
                    key_info.optcmd = 0;
                }
                else if(key_info.optcmd == 3){
                    key_info.optcmd = 0;
                }
              key_info.keyvalue = 0;
            }
            
        }

        if(times<5) {
            ref = get_adc(ADC_Channel_Vrefint, 1, ADC_SampleTime_239Cycles5);
            Vdd=1.2/(float)ref*4095;
            //printf("\r\n++++++Vdd=%.3f V\r\n",Vdd);
            sref += Vdd;
            if(g_runData.bRef12 == 0) {
                temp = get_adc(ADC_Channel_0, 1, ADC_SampleTime_239Cycles5);
                vol = (float)temp*Vdd*1000/4096;
                sumVol += vol;//
            }
            if(times>=4){
                vol = sumVol/5.0;
                sumVol = 0.0;
                if(g_runData.bRef12 == 0)
                    g_firmwareMsg.gatewayMsg.fVol.fvoltage = vol/1000.0*2;
                else
                    g_firmwareMsg.gatewayMsg.fVol.fvoltage = sref/5.0;
               // printf("`````````````````vol = %f\r\n",g_firmwareMsg.gatewayMsg.fVol.fvoltage);
                times= 0;
                sref = 0;
            }
            else
                times++;
        }
        if(tempertureTimes<20){

            temp = get_adc(ADC_Channel_16, 1, ADC_SampleTime_239Cycles5);
           // printf("-------temp = %d\r\n",temp);

            sumtemp += temp;
            if(tempertureTimes>=19){
                temp = (float)sumtemp/20.0;
                temperature = (1.376 - temp*3.3/4096)*1000/4.6 + 25;
                g_firmwareMsg.gatewayMsg.fTemper.ftemperature = temperature;
              //  printf("`````````````````temper = %f\r\n",g_firmwareMsg.gatewayMsg.fTemper.ftemperature);
             //   printf("----------adc = %f,temp = %f \r\n",temperature,temperature1);
//                sumTemperature = 0.0;
                tempertureTimes= 0;
                sumtemp = 0;
            }
            else
                tempertureTimes++;
        }

        OSTimeDlyHMSM(0, 0, 0, 100, OS_OPT_TIME_DLY, &err);



    /******************************/
    /*
            //屏蔽// uart_rs232_init(Console_UID, cmd_rcv);
    */
    rcv_size = uart_blocking_read((char *)rcv_buf, UART_DEBUG, 10);
    if(rcv_size)
    {
            uart_cmd_task(rcv_buf,rcv_size);
    }
    else {
        if(g_ptTest.bTestStart==1){
            if(timeout_isOut(&g_ptTest.ptTime)==1){ // 超时了
                g_ptTest.bTestStart = 0;
                timeout_stop(&g_ptTest.ptTime);
            }
        }
    }
    /******************************/
			
		
    }

}

extern u8 uart_redirect_cfg[UART_MAX];

//static int uart_rcv(u8 uartid, void *arg, u8 *pbuf, u16 buflen,u8 version)
//{
//	int i;
//#if 0
//	if(uart_redirect_cfg[uartid]) {
//		uart_msg_send(uart_redirect_cfg[uartid] - 1, pbuf, buflen);
//	} else {
//		uart_msg_send(uartid, pbuf, buflen);
//	}
//#endif
//	printf("uart%d receive %d %s:\r\n", uartid+1, buflen, pbuf);

//	for(i = 0;i < buflen;i++) {
//		printf("%c", *(pbuf + i));
//	}
//	printf("\r\n");

//	return 0;
//}

//u8 gps_buff[100];
//u8 gps_index = 0;
//static int gps_data_rcv(u8 uartid, void *arg, u8 *pbuf, u16 buflen,u8 version)
//{
//	int i;

//	for(i = 0;i < buflen;i++) {
//		gps_buff[gps_index] = *(pbuf+i);
//		if(gps_buff[gps_index] == '$') {
//			gps_index = 0;
//			gps_buff[gps_index] = *(pbuf+i);
//		} else if((gps_buff[gps_index] == 0x0a)&&
//					(gps_buff[gps_index-1] == 0x0d)) {
//			if(strstr(gps_buff, "RMC")) {
//				//printf("%s",  gps_buff);
//			}
//			memset(gps_buff, 0 , gps_index);
//			gps_index = 0;
//			continue;
//		}
//		gps_index++;
//	}
	
//	return 0;
//}

void UART_TASK_Handle(void * p_arg)//信息传输装置
{
    u8 i;
    OS_ERR  err;
    (void)p_arg;
    //char hello[32] = "hello world!!\n"

    SysTick_init();
    for(i = 0;i < UART_MAX;i++) {
        if(i == UART_DEBUG) {
            uart_rs232_init(i, NULL);
            continue;
        }
        else if(i == UART2_ID) {
           // uart_rs232_init(i, gps_data_rcv);
            continue;
        } else {
            uart_rs232_init(i, NULL);
            continue;
        }
    }

    while (1)
    {
//        for(i = 0;i < UART_MAX;i++) { //5个串口数据接收
//            uart_rcv_process(i);
//        }
        uart_rcv_process(0);
        OSTimeDlyHMSM(0, 0, 0, 5, OS_OPT_TIME_DLY, &err);
        uart_rcv_process(1);
        OSTimeDlyHMSM(0, 0, 0, 5, OS_OPT_TIME_DLY, &err);
    }

}

void PROG_TASK_Handle(void * p_arg)//信息传输装置
{
    (void)p_arg; 
	//char hello[32] = "hello world!!\n"
	
	SysTick_init();	
	net_proc();		
}

void SVC_TASK_Handle(void * p_arg)//信息传输装置
{
	sys_eeprom_info_t info;
    (void)p_arg;
	
	SysTick_init();	

#if 0	
	dev_type = DEV_TYPE_OILTANK_STATION;
	dev_id = 0x55555555;
	AT24CXX_Write(STORAGE_POS_DEVICE_TYPE, (uint8_t *)&dev_type, 4);
	AT24CXX_Write(STORAGE_POS_DEVICE_ID, (uint8_t *)&dev_id, 4);
	printf("write dev_type : 0x%08x, dev_id : 0x%08x\r\n", dev_type, dev_id);

	AT24CXX_Read(STORAGE_POS_DEVICE_TYPE, (uint8_t *)&dev_type, 4);
	AT24CXX_Read(STORAGE_POS_DEVICE_ID, (uint8_t *)&dev_id, 4);
	printf("read dev_type : 0x%08x, dev_id : 0x%08x\r\n", dev_type, dev_id);
#endif	
	
	
	system_info_get(&info);	
	gateway_power_info_get();
	info.DevId = g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn;
	svc_proc(info.DevType, info.DevId);		
}

void LORA_TASK_Handle(void * p_arg)//信息传输装置
{
    OS_ERR  err;
    (void)p_arg;
    //char hello[32] = "hello world!!\n"

    SysTick_init();

    g_runData.curloraIndex = fram_read_lora_index();
    printf("Lora 信道索引：%d\r\n", g_runData.curloraIndex);
    lora_init("golden_beans");

    while(1) {
    //  if( g_ptTest.bTestStart ==0 )
        lora_task();
        ota_process_handle();
        OSTimeDlyHMSM(0, 0, 0, 1, OS_OPT_TIME_DLY, &err);
    }
}

float tmper = 0.0;
void INFO_TASK_Handle(void * p_arg)//
{
//    static uint8_t flag = 0;
    sys_eeprom_info_t info;

    OS_ERR  err;
    (void)p_arg;


    SysTick_init();

    system_info_get(&info);
    gateway_power_info_get();
    info.DevId = g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn;
    svc_init(DEV_TYPE_GATEWAY, info.DevId);
    while(1) {

        if( sys_net.net_hdl && ((downlink_config.config_flag&0x01) != CONFIG_WRITE)) {
            gateway_net_send_gatewayMsg();
            gateway_update_collect_status(); // 升级状态读取以及重传
            gateway_reset_send_update_status();// 上报服务器网关自己的升级状态
        }
        if(((g_runData.bUpdate!=0) && (g_updateProg.updateProgFrom==UPDATE_PROG_FROM_GATEWAY)) || (g_runData.bResetUpdate==2)) {
            gateway_update_gateway_status();
            gateway_update_status_send(&sys_net);
            goto END_DELAY;
        }
        if(sys_net.net_hdl && (downlink_config.config_flag == CONFIG_WRITE) && (g_runData.bInitNetProc==1))
        {
            gateway_update_collect_status(); // 升级状态读取以及重传
            gateway_reset_send_update_status();// 上报服务器网关自己的升级状态

            if(g_cmdInfo83.bread83 == 1){
                tax_manual_0x83_process();

            }
            else if(g_runData.bchangelora == 1){
                tax_send_cmd_0x5B();
            }
            else if(g_runData.bfirstSend0x56){
                tax_send_cmd_0x56_first();
            }
            else if(g_runData.bfirstRead0x83 && (g_runData.bUpdate==0)){ // 83税控序列号
                tax_0x83_process();
            }
            else if((g_runData.bRead0x58)&& (g_runData.ballowRead58==0) && (g_runData.bUpdate==0) ){ // 读取固件信息时，且判断数据信息是否读取完成一次
                gateway_net_send_gatewayMsg();
                tax_send_cmd_0x58(); // 固件信息读取
//                flag = 1;
            }
            else if((g_runData.bRead1053)&&(g_runData.read1053Num<2)){
                tax_send_cmd_0x01_0x1053();
            }
            else if(g_runData.bReadData && (g_runData.bUpdate==0) ) {//业务数据
                net_to_read_cmd(); // 处理网络下发的数据
                //if(g_encodeOpt.benable == 1) tax_process_encoder();
                //else
                tax_process();
//                flag = 0;
            }
        }

END_DELAY:
        OSTimeDlyHMSM(0, 0, 0, 100, OS_OPT_TIME_DLY, &err);
    }
}
extern void lora_send(char *tx_data, uint32_t tx_len);

void NETTIM_TASK_Handle(void *p_arg)
{
    OS_ERR  err;
    uint8_t ret = 0;

    SysTick_init();

    nettimer_init();
    timeout_setValue(&g_usmTimeOut,60*1000);
    while(1){

        if(sys_net.net_hdl ){
            net_check_status();
        }
        ret = check_usim_status(1);
        if(((g_runData.cregStatus!=1) || (g_data4G.errorTime>=2) || (air.State.MQTT_State==0) || (ret!=0)) \
                        && (sys_net.net_hdl!=NULL) && (g_runData.bUpdate==0)) { // 网络注册失败
            printf("mqtt can not connect \r\n");
            if( (timeout_isOut(&g_usmTimeOut))){ //||(g_data4G.errorTime>=2)
                sys_net.net_hdl = NULL;
                sys_net.net_hdl = uplink_net_init((char*)g_upLinkTopic);
                sys_net.uplink_send = uplink_net_send; //上传数据的函数指针 4G
                sys_net.downlink_send = lora_send; // 下发数据的函数指针 lora
                device_init(0x0101, downlink_config.gateway_id);
                g_data4G.flag++;
                if(g_data4G.flag==1) timeout_setValue(&g_usmTimeOut,3*60*1000);
                else if(g_data4G.flag==2) timeout_setValue(&g_usmTimeOut,5*60*1000);
                else {
                    g_data4G.flag = 3;
                    timeout_setValue(&g_usmTimeOut,10*60*1000);
                }
                timeout_start(&g_usmTimeOut);
                printf("app start g_usmTime\r\n");
                /*if(g_data4G.errorTime>=2){
                    printf("mqtt can not connect\r\n");
                }
                g_data4G.errorTime = 0;*/
                g_mqttRunDa.connectNum++;
                if(g_mqttRunDa.connectNum>=3) {
                    g_mqttRunDa.bChangeSuc = 2; // 切换连接失败
                }
            }
        }
        else if(g_runData.cregStatus==1 && (air.State.MQTT_State==1) &&(g_data4G.flag!=0)){
            if(g_usmTimeOut.flag ==0) {
                g_data4G.flag = 0;
                timeout_setValue(&g_usmTimeOut,60*1000);
                timeout_stop(&g_usmTimeOut);
                printf("app start cergstatus = 1\r\n");
            }

        }
        if(g_mqttRunDa.bChangeMqtt == 1){ // 切换mqtt
            if(air.State.MQTT_State==1) { // 切换成功// 保存mqtt地址
                memset(&(g_firmwareMsg.mqttidport),0,sizeof(MqttIdPort));
                memcpy(g_firmwareMsg.mqttidport.ip,g_mqttRunDa.mqttMsg.ip,g_mqttRunDa.mqttIdlen);
                memcpy(g_firmwareMsg.mqttidport.port,g_mqttRunDa.mqttMsg.port,g_mqttRunDa.mqttPortlen);
                memcpy(g_firmwareMsg.mqttidport.admin,g_mqttRunDa.mqttMsg.admin,g_mqttRunDa.mqttUserlen);
                memcpy(g_firmwareMsg.mqttidport.password,g_mqttRunDa.mqttMsg.password,g_mqttRunDa.mqttPwdlen);
                g_firmwareMsg.mqttidport.flag = 1;
                fram_write_mqtt_msg();
                printf("mqtt 切换成功,并保存mqtt的地址\r\n");
                g_mqttRunDa.bChangeMqtt = 0;
                g_mqttRunDa.connectNum = 0;
            }
            else if((air.State.MQTT_State==0) && (g_mqttRunDa.bChangeSuc==2)){ // 切换失败
                // 恢复mqtt地址，进行重新连接
                g_mqttRunDa.bChangeMqtt = 0;
                g_mqttRunDa.connectNum = 0;
                timeout_stop(&g_usmTimeOut);
                printf("mqtt 切换失败，切换到原来的地址上\r\n");
            }

        }
        OSTimeDlyHMSM(0, 0, 2, 0, OS_OPT_TIME_DLY, &err);
    }
}

