#include "sys_config.h"
#if UPLOAD_MODE_1
#include "UWater_frame_app.h"
#include "UWater_eeprom_driver.h"
#include "UWater_Timer1us_driver.h"
#include "UWater_lptimer_driver.h"
#include "UWater_rtcc_driver.h"
#include "UWater_valve_driver.h"
#include "eeprom_app.h"
#include "UWater_rtcc_app.h"
#include "UWater_power_app.h"
#include "UWater_gp22_app.h"
#include "sys_processor.h"
#include "UWater_DataTools_App.h"
#include "UWater_key_app.h"
#include "UWater_pt_app.h"
#include "UWater_DebugPrint.h"
#include "UWater_Valve_app.h"
#include <string.h>
#include "UWater_sys.h"
#include "soe.h"
#include "nb_upload_monitor.h"

//数据发送缓存
static u8 upload_send_buf[UPLOAD_BUF_SIZE];
static u16 upload_send_len;
static u8 upload_send_state;

static DateTime upload_skew;
static TYP_MAIN_STATE_UPLOAD main_upload_state = UPLOAD_S0;
static TYP_STATE_UPLOAD time_upload_state=TIME_UPLOAD_S0;
static EVENT_UPLOAD_ event_upload;	//事件记录
static u32 g_delay_upload_time;
static u8 g_jingge_time_para;
static u8  upload_delay_flag = 0;
static u16 g_activity_times=0;
static u8 upload_frame_data_step = 0;	//上行数据组帧步骤
static u8 s_upload_ack_fail_times=0;//记录连续多天无应答次数
static u16 valve_close_upload_time_cnt;

static u8 s_upload_eep_complete=0;
static u8 save_freeze_sate = SAVE_FREEZE_S0; //数据冻结类状态机
static u8 data_save_judge_flag = FALSE;	//保存冻结类数据
static u8 sys_deal_judge_flag = FALSE;	//系统处理
static DateTime sys_rtcc_time;				//用于获取系统当前时间
static u16 sys_temp_min_hex;//分钟转16进制格式
//RTC故障超时时间
static u32 rtcc_err_check_time=0;
static u8 rtcc_err_check_count=0;
static u8 sys_rtcc_clk_source=0;
static u8 sys_rtcc_check_flag=FALSE;
//系统初始化标志
static u8 sys_inite_flag=FALSE;
//离散和补传机制变量
#define __no_init __attribute__((zero_init))
__no_init volatile u8 upload_again_cnt_copy __attribute__((section(".ARM.__at_0x20007F34")));
static u8 up_delay_count_flag=0; //防护,顺延20分钟每天只执行一次
static u8 up_time_check_2hour=120;//防护,防止NB校时连续上报,2小时内不允许
/****************************************时间扫描、消息分发**********************/
void MinuteEventScan(void)
{
	if (0x02 == (RtccCheckMsg() & 0x02))//分钟消息
    {
		RtccClearMsg(1);
        RtccSetMsgApp(RtccMsg_UploadInTime);	//RTCC定时上报
		RtccSetMsgApp(RtccMsg_OtherProtl); 		//抛给其他规约的分钟消息
		FrameSetMsgApp(Msg_FrozenStore);      //冻结数据
        data_save_judge_flag = TRUE;			//保存冻结类数据
        sys_deal_judge_flag = TRUE;				//系统处理
		RtccSetMsgApp(RtccMsg_ValveActive);
    }
}  
//系统处理
void SysDealAppMachine(void)
{
	if(sys_deal_judge_flag)
	{
		sys_deal_judge_flag = FALSE;
		rtcc_err_check_count=0;
		RtccGetDateTime(&sys_rtcc_time);
		if(0 == sys_rtcc_time.s.minute)	//整点时间
		{
			FrameSetMsgApp(MsgTouchKeyReset);//复位触摸按键消息
			if(PSM_STATE_SLEEP == getPsmState())
			{ 
				FrameSetMsgApp(Msg_PsmPowerCheck);//PSM模式电压检测
			}
			if (sys_rtcc_time.s.hour == 0x00)//0点清除触摸次数
			{	
				FrameSetMsgApp(MsgTchKey_ClearKeyLimit);//清除触摸按键限制次数
				sys_rtcc_check_flag = TRUE;//检测一下时钟
				up_delay_count_flag=0; 
			}
			if(sys_rtcc_time.s.hour == 0x02)  //每天2点置换能器检测标志
			{
				RtccSetMsgApp(RtccMsg_Transducer_Check);
				if(TRUE == CheckDiftofCalibrationFlag())
				{
					RtccSetMsgApp(RtccMsg_DiftofCalibration);//每天2点置校准零流量标志
				}
			}
		}
		//非检定超时不休眠防护
		if (10 == LcdCheckStateApp()) //非检定状态
		{
			PowerUnSleepSumAddSys();
		}
	}
	/**
	外部32768晶振失效防护:
	1、main函数休眠期间收不到RTC秒中断唤醒,看门狗复位表计使表计重新选择RTC时钟。
	2、检定或唤醒期间通过1us定时器计算时间超过2分钟而收不到分钟消息，则复位表计重新选择RTC时钟。
	3、如果时钟已经切换到内部低速时钟，则每天重新检查一次是否外部时钟又恢复正常。
	*/
	if(Timer1usGetTick() - rtcc_err_check_time > 1000000)//1秒,防止检定和唤醒
	{
		rtcc_err_check_time = Timer1usGetTick();
		rtcc_err_check_count++;
		if(rtcc_err_check_count > 120)
		{
			rtcc_err_check_count = 0;
			Meter_ResetCountAdd(0x08);
			NVIC_SystemReset(); 
		}
	}
	if((sys_rtcc_check_flag==TRUE)&&(LcdCheckStateApp() == 10))//非检定状态
	{
		sys_rtcc_check_flag = FALSE;
		if(RTC_ClkSource() == 1)//如果是内部RC
		{
			sys_rtcc_clk_source = RtccInit();
			if(sys_rtcc_clk_source == 0)//如果切换成了外部RC
			{
				LPTimer1Init(sys_rtcc_clk_source);
			}
		}
	}
}
void SysDealAppPreSleep(void)
{
	rtcc_err_check_count = 0;
	if(sys_inite_flag==FALSE)
	{
		sys_inite_flag = TRUE;
		if(Sys_data_object.P1.func_cfg_bytes[0] > 0)//如果在厂区时段,复位第一次休眠唤醒后执行一次厂区上报
		{
			FrameSetMsgApp(Msg_FactoryUpload);//厂区上报消息
		}
	}
}
/*******************************************************************************
 * @fun_name:	UploadSkewTimeCount
 * @brief   :错峰时间计算 包括补报机制   
               定时上传错峰方案：定时上传时间 + 表号后3位 ×错峰时间间隔 + 60秒。
 * @param[in] :	None
 * @param[out]: None 
* @retval    : 
 * @other     :
 ******************************************************************************/
void UploadSkewTimeCount(void)
{
	if((0 == sys_rtcc_time.s.hour) && (0 == sys_rtcc_time.s.minute))//0点重试次数清0
	{
		upload_again_cnt_copy = 0;
	}
    if(UPLOAD_MODE_HOUR == Sys_data_object.P1.Time_upload_2006.s.type)	//小时模式
    {
        g_delay_upload_time = 0;
		 if(upload_again_cnt_copy > Sys_data_object.P1.report_retry_times)
        {
            upload_again_cnt_copy = 0;
        }
		g_delay_upload_time = (Sys_data_object.P1.met_addr[0] >> 4) * 10 + (Sys_data_object.P1.met_addr[0] & 0x0F);
		g_delay_upload_time *= Sys_data_object.P1.report_step_len.datas;//表计后两位x估长值
        g_delay_upload_time += (u32)MINUTE_TO_SECOND * BCD2HEX(Sys_data_object.P1.Time_upload_2006.s.period);	//上传设定的分
        g_delay_upload_time += (u32)MINUTE_TO_SECOND * 20 * upload_again_cnt_copy;//重传计算

        g_delay_upload_time %= HOUR_TO_SECOND;	//离散到1h内
        upload_skew.s.minute = g_delay_upload_time / MINUTE_TO_SECOND;
        upload_skew.s.minute = HEX2BCD(upload_skew.s.minute);
		//频繁上报测试,设置小时模式大于50分钟时,上报间隔为(5x-50)
		if(Sys_data_object.P1.Time_upload_2006.s.period>0x52)
		{
			upload_skew.s.minute = (BCD2HEX(sys_rtcc_time.s.minute)/(Sys_data_object.P1.Time_upload_2006.s.period - 0x50))*(Sys_data_object.P1.Time_upload_2006.s.period - 0x50);
			upload_skew.s.minute = HEX2BCD(upload_skew.s.minute);
		}
    }
    else	//其他上报模式，天、周、月
    {
//	#if defined(VALVE)
//		if(ValveGetUploadStateApp()==VALVE_CLOSE_UPLOAD_TIME)//阀门关闭的处理
//		{
//			return;
//		}
//	#endif
		if((BCD2HEX(sys_rtcc_time.s.day) % getUploadControlPara(UP_DAY_COUNT))!=0)
		{
			return;
		}
       	g_delay_upload_time = (Sys_data_object.P1.met_addr[0]&0x0F)*100 + (Sys_data_object.P1.met_addr[0] >> 4)*10+(Sys_data_object.P1.met_addr[1]&0x0F);
		
        if(Sys_data_object.P1.report_step_len.datas < 15)	//离散系数有效性判断
        {
            Sys_data_object.P1.report_step_len.datas = 15;
        }
        else if(Sys_data_object.P1.report_step_len.datas > 43)
        {
            Sys_data_object.P1.report_step_len.datas = 43;
        }

        if(Sys_data_object.P1.report_retry_times > 3)   		//重传次数有效性判断
        {
            Sys_data_object.P1.report_retry_times = 2;			//默认2次
        }
        if(upload_again_cnt_copy > Sys_data_object.P1.report_retry_times)
        {
            upload_again_cnt_copy = 0;
        }

		//补传间隔时间处理
		/*if((Sys_data_object.P1.Upload_again_interval_time.datas < 600)||(Sys_data_object.P1.Upload_again_interval_time.datas > 43200))//小于3小时=3*3600=10800,大于12小时=12*3600=43200 
		{
			Sys_data_object.P1.Upload_again_interval_time.datas = 18000;     //默认5小时=5*3600=18000
		}转成小时判断*/
		g_jingge_time_para = Sys_data_object.P1.Upload_again_interval_time.datas/3600;
	    if(g_jingge_time_para < 1)  	// 重传间隔时间有效性判断
        {
            g_jingge_time_para = 5;     //默认5小时,有效值为1-9，当该参数为1时，表示间隔20min重传，其余为相应数字的小时
        }
        else if(g_jingge_time_para >= 10)
        {
            g_jingge_time_para = 5;
        }
		
        g_delay_upload_time *= Sys_data_object.P1.report_step_len.datas;	//乘离散系数
		if(upload_again_cnt_copy==0)
		{
			if(0 == up_delay_count_flag)//每天第一次上报时置起，每天只执行一次
			{
				g_delay_upload_time += MINUTE_TO_SECOND + getUploadControlPara(UP_DELAY_COUNT)*1200;	//增加1min和偏移时间
			}
		}
        else//偏移参数不改变重试时间
		{
			g_delay_upload_time += MINUTE_TO_SECOND;
		}
        g_delay_upload_time += (u32) HOUR_TO_SECOND * BCD2HEX(Sys_data_object.P1.Time_upload_2006.s.hour);		//上传设定的时
        g_delay_upload_time += (u32) MINUTE_TO_SECOND * BCD2HEX(Sys_data_object.P1.Time_upload_2006.s.minute);	//上传设定的分
        if(JIANGE_20_MIN == g_jingge_time_para)				//按20min后重传
        {
            g_delay_upload_time += (u32)MINUTE_TO_SECOND * 20 * upload_again_cnt_copy;//重传计算
        }
        else	//按小时重传
        {
            g_delay_upload_time += (u32)HOUR_TO_SECOND * (g_jingge_time_para) * upload_again_cnt_copy;//重传计算
        }

        g_delay_upload_time %= DAY_TO_SECOND;	//离散到1天内
        upload_skew.s.hour   = g_delay_upload_time / HOUR_TO_SECOND;
        upload_skew.s.minute = (g_delay_upload_time % HOUR_TO_SECOND) / MINUTE_TO_SECOND;
        upload_skew.s.hour   = HEX2BCD(upload_skew.s.hour);
        upload_skew.s.minute = HEX2BCD(upload_skew.s.minute);
    }
}
//查询真实上报时间点
void SystemGetUploadTime(DateTime *pDT)
{
	pDT->s.second = (Sys_data_object.P1.ies_valve_up_times.valve_up_times_pre * 30) - valve_close_upload_time_cnt;//关阀上报
	pDT->s.minute = upload_skew.s.minute;
	pDT->s.hour = upload_skew.s.hour;
	pDT->s.day = HEX2BCD(valve_close_upload_time_cnt%100);
	pDT->s.month = HEX2BCD((valve_close_upload_time_cnt/100)%100);
	pDT->s.year = HEX2BCD(Sys_data_object.P1.ies_valve_up_times.valve_up_times_realtime);
	pDT->s.weekday = 0x00;
}
//设置事件上报
static void SetEventUploadFlag(u8 type)
{
	if(type == UPLOAD_TYPE_FRAME_ORDER||type == UPLOAD_TYPE_FACTORY)//规约或厂区上报
	{
		event_upload.event_cnt = 0;
		event_upload.upload_cnt =0;
		main_upload_state = UPLOAD_S1;//生产上报流程
	}
	else
	{
		main_upload_state = UPLOAD_S2;//其他上报流程
	}
    event_upload.event_cnt++;
    event_upload.event_cnt %= UPLOAD_EVENT_NUM;
    event_upload.upload_type[event_upload.event_cnt] = type;
}
//查询事件上报
static u8 GetEventUploadFlag(void)
{
    if(event_upload.event_cnt != event_upload.upload_cnt)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
//清除事件上报,(下线时清除,防止超时复位表计)
static void ClearEventUploadFlag(void)
{
    event_upload.event_cnt = 0;
	event_upload.upload_cnt =0;
}
//查询事件上报类型
u8 GetEventUploadType(void)
{
    return event_upload.upload_type[event_upload.upload_cnt];
}
//判空闲
u8 FixedTimeNbIoTUploadIfIdle(void)
{
    if(TIME_UPLOAD_S0 == time_upload_state)
    {
        return TASK_IDLE;
    }
    else
    {
        return TASK_BUSY;
    }
}

//上传消息的判断
static void UploadConditionJuge(void)
{
	//定时上报:
	if(RtccCheckMsgApp(RtccMsg_UploadInTime))
	{
		if(up_time_check_2hour<200)
		{
			up_time_check_2hour++;
		}
		DateTime sys_rtcc_time;
		RtccClearMsgApp(RtccMsg_UploadInTime);
		RtccGetDateTime(&sys_rtcc_time);
		UploadSkewTimeCount();//定时上报错峰时间\补报时间计算
		#if defined(VALVE)
			//获取阀门状态--关闭,关阀状态下频繁上报以及时开阀
			if((VALVE_STATE_CLOSE_EMERGENCY == Sys_data_object.P1.ies_valve_paras.valve_state) || 
				(VALVE_STATE_CLOSE_LOCK == Sys_data_object.P1.ies_valve_paras.valve_state) || 
				(VALVE_STATE_CLOSE == Sys_data_object.P1.ies_valve_paras.valve_state))
			{
				if(0 == Sys_data_object.P1.ies_valve_up_times.valve_up_times_total)	//为0时，默认关闭该功能
				{
					Sys_data_object.P1.func_cfg_bytes[12] &=~ 0x01;//清除PSM上报	
				}
				else
				{
					valve_close_upload_time_cnt++;//分钟计时
					if(0 == Sys_data_object.P1.ies_valve_up_times.valve_up_times_pre)
					{
						Sys_data_object.P1.ies_valve_up_times.valve_up_times_pre = 2;	//默认按1h
					}
					if(valve_close_upload_time_cnt >= (Sys_data_object.P1.ies_valve_up_times.valve_up_times_pre * 30))//大于上报间隔时间，最小30分钟
					{
						valve_close_upload_time_cnt = 0;
						if(Sys_data_object.P1.ies_valve_up_times.valve_up_times_total > VALVE_CLOSE_UPLOAD_MAX)
						{
							Sys_data_object.P1.ies_valve_up_times.valve_up_times_total = VALVE_CLOSE_UPLOAD_MAX;
						}
						if(Sys_data_object.P1.ies_valve_up_times.valve_up_times_realtime < Sys_data_object.P1.ies_valve_up_times.valve_up_times_total)
						{
							Sys_data_object.P1.ies_valve_up_times.valve_up_times_realtime++;
							FrameSetMsgApp(MsgChangcha_ValveUploadCnts);//上报次数存EE
							SetEventUploadFlag(UPLOAD_TYPE_VALVE_CLOSE);//置起关阀上报消息
							SaveNewSoe(SOE_MANUAL_UPLOAD,0x20);		//存SOE
							Sys_data_object.P1.func_cfg_bytes[12] |= 0x01;//使用PSM上报
						}
						else
						{
							Sys_data_object.P1.func_cfg_bytes[12] &=~ 0x01;//清除PSM上报
						}
					}
				}
			}
			else
			{
				valve_close_upload_time_cnt = 0;
				Sys_data_object.P1.ies_valve_up_times.valve_up_times_realtime = 0;
				Sys_data_object.P1.func_cfg_bytes[12] &=~ 0x01;//清除PSM上报
			}
		#endif
		if(UPLOAD_MODE_HOUR == Sys_data_object.P1.Time_upload_2006.s.type)	//小时模式
        {
            if(sys_rtcc_time.s.minute == upload_skew.s.minute)  //离散时间
            {
				upload_delay_flag = 1;
            }
        }
        else
        {
            if((sys_rtcc_time.s.hour == upload_skew.s.hour) && (sys_rtcc_time.s.minute == upload_skew.s.minute))  //离散时间
            {
				if(up_time_check_2hour < 120)//离上次定时上报不到2小时
				{
					return;
				}
				if(UPLOAD_MODE_WEEK == Sys_data_object.P1.Time_upload_2006.s.type)//周模式
				{
					if(Sys_data_object.P1.Time_upload_2006.s.period == sys_rtcc_time.s.weekday)
					{
						upload_delay_flag = 1;
						up_time_check_2hour=0;//重新计时
					}
				}
				else if(UPLOAD_MODE_MONTH == Sys_data_object.P1.Time_upload_2006.s.type)//月模式
				{
					if(Sys_data_object.P1.Time_upload_2006.s.period == sys_rtcc_time.s.day)
					{
						upload_delay_flag = 1;
						up_time_check_2hour=0;//重新计时
					}
				}
				else//天模式
				{
					if((BCD2HEX(sys_rtcc_time.s.day) % getUploadControlPara(UP_DAY_COUNT))!=0)
					{
						return;
					}
					up_delay_count_flag =1;
					upload_delay_flag = 1;
					up_time_check_2hour=0;//重新计时
				}
            }
        }
	}
	if(upload_delay_flag==1)//等待离散时间到达
	{
		if(01 != LcdCheckStateApp())//非检定状态
		{
			upload_delay_flag = 0;
			if(0 == upload_again_cnt_copy)
			{
				SetEventUploadFlag(UPLOAD_TYPE_FIX_TIME);	//RTCC定时上报
				SaveNewSoe(SOE_MANUAL_UPLOAD,0x10);		//存SOE
			}
			else
			{
				SetEventUploadFlag(UPLOAD_TYPE_RETRY_AGAIN);	//重传上报
				SaveNewSoe(SOE_MANUAL_UPLOAD,0x11);		//存SOE
			}
		}
	}
	//主动上报:
	if(FrameCheckMsgApp(MsgNbUartSend))//判断串口发起上传消息
	{
		FrameClearMsgApp(MsgNbUartSend);
		SetEventUploadFlag(UPLOAD_TYPE_FRAME_ORDER);
		SaveNewSoe(SOE_MANUAL_UPLOAD,0x01);		//存SOE
	}
	else if(KeyCheckLcdMsgApp(MENU_ACTIVE_RF))//按键发起上传消息
	{
		KeyClearLcdMsgApp(MENU_ACTIVE_RF);//清按键消息
		SetEventUploadFlag(UPLOAD_TYPE_HAND_KEY);
		SaveNewSoe(SOE_MANUAL_UPLOAD,0x02);		//存SOE
	}
	else if(FrameCheckMsgApp(MsgNbUploadByValveStateChange))//阀门状态改变发起上报
	{
		FrameClearMsgApp(MsgNbUploadByValveStateChange);
		SetEventUploadFlag(UPLOAD_TYPE_VALVE_ACTIVE);
		SaveNewSoe(SOE_MANUAL_UPLOAD,0x03);		//存SOE
	}
	//设置IP:工装用于获取IMEI
	if(FrameCheckMsgApp(MsgNbIpPortChange))//ip及端口号发生改变
	{
		FrameClearMsgApp(MsgNbIpPortChange);
		SetEventUploadFlag(UPLOAD_TYPE_SET_IP);
		SaveNewSoe(SOE_MANUAL_UPLOAD,0x04);		//存SOE
	}
	//即时报警上传
	if(FrameCheckMsgApp(MsgShenYang_NbUploadWarning))
	{
		FrameClearMsgApp(MsgShenYang_NbUploadWarning);
		SetEventUploadFlag(UPLOAD_TYPE_WARNING);
		SaveNewSoe(SOE_MANUAL_UPLOAD,0x05);		//存SOE
	}
	//厂区上传,只进行到附网成功
	if(FrameCheckMsgApp(Msg_FactoryUpload))
	{
		FrameClearMsgApp(Msg_FactoryUpload);
		SetEventUploadFlag(UPLOAD_TYPE_FACTORY);
		SaveNewSoe(SOE_MANUAL_UPLOAD,0x06);		//存SOE
	}
}
/*******************************************************************************
 * @fun_name:	FixedTimeNbIoTUpload
 * @brief   : 
 ******************************************************************************/
static void FixedTimeNbIoTUpload_Ies(void)
{
    switch(time_upload_state)
    {
        case(TIME_UPLOAD_S0):
        {
            if(TRUE == GetEventUploadFlag())									//是否有上报任务
            {
                event_upload.upload_cnt++;
                event_upload.upload_cnt %= UPLOAD_EVENT_NUM;
				
                Set100msTimer(TIMER_100MS_WAIT_SLEEP_GPRS, NB_TOTAL_WORK_TIME);	//总时长6min
                g_activity_times++;												//有上报任务，活跃次数即累加
				if(((FrameCheckParaApp(FramePara_FuncCfg0_3)>>16)&0xFF) == 0xAA)
				{
				    OpenPrintNbDataSwitch();//打开红外调试功能
				}
				Sys_data_object.P3.ProductUploadFlag = 0x55;
				FrameClearMsgApp(MsgNbUplaod_AckOk);//清收到应答消息
				FrameClearMsgApp(MsgNb_FlagRcvNbFrame);
				NbUploadParaSet();
                time_upload_state = TIME_UPLOAD_S1;
            }
        }
        break;
		
		case(TIME_UPLOAD_S1):
        {
            if (NbiotIfOnline())//已在线
            {
                time_upload_state = TIME_UPLOAD_S2;
            }
            else //不在线  启动模块上线任务
            {
                if (NbiotIfIdle())
                {
                    NbiotOnlineTask(&upload_send_state);
                    Set100msTimer(TIMER_100MS_ERROR_UPLOAD,NB_LAUNCH_TIME); 	//最长时间登录任务处理 5min
                    time_upload_state = TIME_UPLOAD_S2;
                }
            }
        }
        break;
		case(TIME_UPLOAD_S2):
        {
            if (NbiotIfOnline()) //上线成功  上线流程中读出IMEI,ICCID，ECL，SNR，RSRP等参数
            {				
				if(UPLOAD_TYPE_FACTORY == GetEventUploadType())		//是厂区上传测试
				{					
					 upload_frame_data_step = UPLOAD_FRAME_UPLOAD_OK;//厂区测试期间,符网成功则认为成功
					 time_upload_state = TIME_UPLOAD_S3;//上报成功,清失败次数
				}
				else
				{
					NB_NetConnectStart(Sys_data_object.P1.server_ip, Sys_data_object.P1.server_port.datas, MAIN_CONNECT_TYPE);
					time_upload_state = TIME_UPLOAD_S20;
				}
            }
            else if((upload_send_state == NBIOT_ERROR)||(0 == Check100msTimer(TIMER_100MS_ERROR_UPLOAD)))//登录超时，本次上传失败
            {
				upload_frame_data_step = UPLOAD_FRAME_ONLINE_FAIL;
				time_upload_state = TIME_UPLOAD_S3;
            }
        }
        break;
		case(TIME_UPLOAD_S20)://主连接
        {
            if (ConncetIfOnline(MAIN_CONNECT_TYPE)) //上线成功  上线流程中读出IMEI,ICCID，ECL，SNR，RSRP等参数
            {
				upload_frame_data_step = UPLOAD_FRAME_REQUEST_NEW;
                time_upload_state = TIME_UPLOAD_S3;
            }
            else if((upload_send_state == NBIOT_ERROR)||(0 == Check100msTimer(TIMER_100MS_ERROR_UPLOAD)))//登录超时，本次上传失败
            {
				upload_frame_data_step = UPLOAD_FRAME_ONLINE_FAIL;
				time_upload_state = TIME_UPLOAD_S3;
            }
        }
        break;
		
		case(TIME_UPLOAD_S3):	//上报数据组帧状态复位
        {
			GetUploadDataResetState();
			time_upload_state = TIME_UPLOAD_S4;
        }
        break;

		case(TIME_UPLOAD_S4):	//等上报数据组帧完成
        {
			GetUploadDataMachineProduction(upload_frame_data_step, upload_send_buf, &upload_send_len);
			if(GetUploadDataCheckIdleProduction() == TASK_IDLE)
			{
				if(GetUploadDataCheckTaskProduction() == PTL_PACK_SUCCESS)
				{
					time_upload_state = TIME_UPLOAD_S5;
				}
				else
				{
					Set100msTimer(TIMER_100MS_NBIOT_20, NB_WAIT_5S);//5秒等待
					time_upload_state = TIME_UPLOAD_S7;
				}
			}
        }
        break;
		
		case(TIME_UPLOAD_S5):	//等待数据发送
        {
			if (TASK_IDLE == NbiotIfIdle())
			{
				NbiotSendTask(upload_send_buf, upload_send_len, MAIN_SEND_TYPE, &upload_send_state);
				Set100msTimer(TIMER_100MS_NBIOT_20, COAP_UPLOAD_WAIT_ACK_TIME);//等待应答
				time_upload_state = TIME_UPLOAD_S6;
			}
        }
        break;                
		
		case(TIME_UPLOAD_S6):	//等待上报应答
        {
			if((FrameCheckMsgApp(MsgNbUplaod_AckOk) == 1)||(Check100msTimer(TIMER_100MS_NBIOT_20) == 0))//收到上传应答帧或等待应答时间到,判为上报成功
			{
				FrameClearMsgApp(MsgNbUplaod_AckOk);//清消息
				upload_frame_data_step = UPLOAD_FRAME_UPLOAD_OK;
				Sys_data_object.P3.ProductUpoadFailFlag = 0;
				NB_SS_Control_SetPara(NB_UploadFailTimes, 0);//生产上报成功,清除失败次数
				time_upload_state = TIME_UPLOAD_S4;
			}
			else if(upload_send_state == NBIOT_ERROR)//数据发送失败,请求重新发送
			{
				Sys_data_object.P3.ProductUpoadFailFlag = 50;
				upload_frame_data_step = UPLOAD_FRAME_UPLOAD_RETRY;
				time_upload_state = TIME_UPLOAD_S4;
			}
        }
        break;          		
		
		case(TIME_UPLOAD_S7)://处理下行指令和上报队列
        {
			if(FrameCheckMsgApp(MsgNb_FlagRcvNbFrame))//是否收到nb数据
			{
				FrameClearMsgApp(MsgNb_FlagRcvNbFrame);
				Set100msTimer(TIMER_100MS_NBIOT_20, NB_WAIT_5S);
			} 
			if (Check100msTimer(TIMER_100MS_NBIOT_20) == 0)//5s超时时间到
			{
				if(TRUE == GetNbiotRevHandleOverFlag())	//无NB数据在处理
				{
					time_upload_state = TIME_UPLOAD_PowerDown;
				}
			}
        }
        break;
		//模组断电流程
		case TIME_UPLOAD_PowerDown:
		{
			if(NbiotIfIdle())
			{
				StartPowerOffTask();
				time_upload_state = TIME_UPLOAD_PowerDownWait;
			}   
		}
		break;
		
		case TIME_UPLOAD_PowerDownWait:
		{
			if(NbiotIfIdle())
			{
				time_upload_state = TIME_UPLOAD_PowerDownEnd;
			}
		} 
		break;
		
		case TIME_UPLOAD_PowerDownEnd:
		{
			if(TASK_IDLE == EepIfIdle())
			{
				if(((FrameCheckParaApp(FramePara_FuncCfg0_3)>>16)&0xFF) == 0xAA)//如果红外调试开启,则关闭红外调试
				{
					Sys_data_object.P1.func_cfg_bytes[2] = 0;
					s_upload_eep_complete = 0;
					EepWrite(&Sys_data_object.P1.func_cfg_bytes[2], (EEP_FRAME_FUNCCFGBYTES_ADDR+2), 1, &s_upload_eep_complete);
					Frame_Para_Init();
				}
				NbForcePowerOff();//NB强制关机
				UdpEndCheckData();
				ClosePrintNbDataSwitch();
				ClearEventUploadFlag();
				Sys_data_object.P3.ProductUploadFlag = 0;
				time_upload_state = TIME_UPLOAD_S0;	
				main_upload_state = UPLOAD_S0;
			}
		}
		break;
		
		default:
		{
			time_upload_state = TIME_UPLOAD_S0;
		}
		break;
	} 
	//NB活跃时间超时处理,超时不空闲,则强制关机
	if(TASK_BUSY == FixedTimeNbIoTUploadIfIdle())
    {
        if(0 == Check100msTimer(TIMER_100MS_WAIT_SLEEP_GPRS))
		{
			time_upload_state = TIME_UPLOAD_PowerDownEnd;
		} 
    }
}

static void FixedTimeNbIoTUpload_Other(void)
{
    switch(time_upload_state)
    {
        case(TIME_UPLOAD_S0):
        {
            if(TRUE == GetEventUploadFlag())									//是否有上报任务
            {
                event_upload.upload_cnt++;
                event_upload.upload_cnt %= UPLOAD_EVENT_NUM;
				
                Set100msTimer(TIMER_100MS_WAIT_SLEEP_GPRS, NB_TOTAL_WORK_TIME);	//总时长6min
                g_activity_times++;												//有上报任务，活跃次数即累加
				if(((FrameCheckParaApp(FramePara_FuncCfg0_3)>>16)&0xFF) == 0xAA)
				{
				    OpenPrintNbDataSwitch();//打开红外调试功能
				}
				FrameClearMsgApp(MsgNbUplaod_AckOk);//清收到应答消息
				FrameClearMsgApp(MsgNb_FlagRcvNbFrame);
				NbUploadParaSet();//根据功耗配置上报参数
                time_upload_state = TIME_UPLOAD_S1;
            }
        }
        break;
		
		case(TIME_UPLOAD_S1):
        {
            if(NbiotIfOnline())//已在线
            {
				if(PSM_STATE_OUT != getPsmState())//如果在PSM状态,正常在PSM_STATE_SLEEP状态开始,阀门动作会在PSM_STATE_WAKE状态继续上报
				{
					NbiotPsmWakeupTask();   //psm模式唤醒			
					time_upload_state = TIME_UPLOAD_S10;
				}
				else 
				{
					time_upload_state = TIME_UPLOAD_S2;
				}
            }
            else //不在线  启动模块上线任务
            {
                if (NbiotIfIdle())
                {
                    NbiotOnlineTask(&upload_send_state);
                    Set100msTimer(TIMER_100MS_ERROR_UPLOAD,NB_LAUNCH_TIME); 	//最长时间登录任务处理 5min
                    time_upload_state = TIME_UPLOAD_S2;
                }
            }
        }
        break;
		
		case TIME_UPLOAD_S10://等待模组PSM唤醒任务完成
		{
			if(NbiotIfIdle()==TASK_IDLE)
			{
				if(PSM_STATE_WAKE == getPsmState())//唤醒成功
				{
					time_upload_state = TIME_UPLOAD_S20;
				}
				else//唤醒失败,模组重新联网
				{
					NbiotOnlineTask(&upload_send_state);
                    Set100msTimer(TIMER_100MS_ERROR_UPLOAD,NB_LAUNCH_TIME); 	//最长时间登录任务处理 2min
                    time_upload_state = TIME_UPLOAD_S2;
				}
			}
		}
		break;		
		
		case(TIME_UPLOAD_S2):
        {
            if (NbiotIfOnline()) //上线成功  上线流程中读出IMEI,ICCID，ECL，SNR，RSRP等参数
            {
				setUploadControlPara(UP_CGATT_FAIL, FALSE);//附网成功 
				NB_NetConnectStart(Sys_data_object.P1.server_ip, Sys_data_object.P1.server_port.datas, MAIN_CONNECT_TYPE);
                time_upload_state = TIME_UPLOAD_S20;
            }
            else if((upload_send_state == NBIOT_ERROR)||(0 == Check100msTimer(TIMER_100MS_ERROR_UPLOAD)))//登录超时，本次上传失败
            {
				setUploadControlPara(UP_CGATT_FAIL, TRUE);//附网失败
				upload_frame_data_step = UPLOAD_FRAME_ONLINE_FAIL;
				time_upload_state = TIME_UPLOAD_S3;
            }
        }
        break;
		case(TIME_UPLOAD_S20)://主连接
        {
            if (ConncetIfOnline(MAIN_CONNECT_TYPE)) //上线成功  上线流程中读出IMEI,ICCID，ECL，SNR，RSRP等参数
            {
				if(PSM_STATE_WAKE == getPsmState())//唤醒成功
				{
					upload_frame_data_step = UPLOAD_FRAME_REQUEST_NEW;
					time_upload_state = TIME_UPLOAD_S3;
				}
				else if(getUploadControlPara(UP_ONLY_REV)==TRUE)
				{
					setUploadControlPara(UP_ONLY_REV, FALSE);
					Set100msTimer(TIMER_100MS_NBIOT_20, getUploadControlPara(UP_DELAY_TIME1));
					time_upload_state = TIME_UPLOAD_S7;
				}
				else
				{
					upload_frame_data_step = UPLOAD_FRAME_REQUEST_NEW;
					time_upload_state = TIME_UPLOAD_S3;
				}
            }
            else if((upload_send_state == NBIOT_ERROR)||(0 == Check100msTimer(TIMER_100MS_ERROR_UPLOAD)))//登录超时，本次上传失败
            {
				upload_frame_data_step = UPLOAD_FRAME_ONLINE_FAIL;
				time_upload_state = TIME_UPLOAD_S3;
            }
        }
        break;
		
		case(TIME_UPLOAD_S3):	//上报数据组帧状态复位
        {
			GetUploadDataResetState();
			time_upload_state = TIME_UPLOAD_S4;
        }
        break;

		case(TIME_UPLOAD_S4):	//等上报数据组帧完成
        {
            GetUploadDataMachine(upload_frame_data_step, upload_send_buf, &upload_send_len);
			if(GetUploadDataCheckIdle() == TASK_IDLE)
			{
				if(GetUploadDataCheckTask() == PTL_PACK_SUCCESS)
				{
					time_upload_state = TIME_UPLOAD_S5;
				}
				else
				{
					Set100msTimer(TIMER_100MS_NBIOT_20, getUploadControlPara(UP_DELAY_TIME1));
					time_upload_state = TIME_UPLOAD_S7;
				}
			}
        }
        break;
		
		case(TIME_UPLOAD_S5):	//等待数据发送
        {
			if (TASK_IDLE == NbiotIfIdle())
			{
				NbiotSendTask(upload_send_buf, upload_send_len, MAIN_SEND_TYPE, &upload_send_state);
				Set100msTimer(TIMER_100MS_NBIOT_20, COAP_UPLOAD_WAIT_ACK_TIME);//等待应答
				time_upload_state = TIME_UPLOAD_S6;
			}
        }
        break;
		
		case(TIME_UPLOAD_S6):	//等待上报应答
        {
			if((FrameCheckMsgApp(MsgNbUplaod_AckOk) == 1)||(Check100msTimer(TIMER_100MS_NBIOT_20) == 0))//收到上传应答帧或等待应答时间到,判为上报成功
			{
				FrameClearMsgApp(MsgNbUplaod_AckOk);//清消息
				s_upload_ack_fail_times = 0;//多天无应答记录清0
				upload_frame_data_step = UPLOAD_FRAME_UPLOAD_OK;
				Sys_data_object.P3.ProductUpoadFailFlag = 0;
				time_upload_state = TIME_UPLOAD_S4;
			}
			else if(upload_send_state == NBIOT_ERROR)//数据发送失败,请求重新发送
			{
				upload_frame_data_step = UPLOAD_FRAME_UPLOAD_RETRY;
				time_upload_state = TIME_UPLOAD_S4;
			}
        }
        break;          		
		
		case(TIME_UPLOAD_S7)://处理下行指令和上报队列
        {
			if(FrameCheckMsgApp(MsgNb_FlagRcvNbFrame))//是否收到nb数据
			{
				FrameClearMsgApp(MsgNb_FlagRcvNbFrame);
				Set100msTimer(TIMER_100MS_NBIOT_20, getUploadControlPara(UP_DELAY_TIME1));
			}
			else if (Check100msTimer(TIMER_100MS_NBIOT_20) == 0)//10s超时时间到
			{
				if(TRUE == GetNbiotRevHandleOverFlag())	//无NB数据在处理
				{
					if(TRUE == GetEventUploadFlag())    	//是否还有上报任务
					{
						event_upload.upload_cnt++;
						event_upload.upload_cnt %= UPLOAD_EVENT_NUM;
						time_upload_state = TIME_UPLOAD_S20;
					}
					else
					{
						if(PSM_STATE_WAKE == getPsmState())//如果在PSM唤醒状态
						{
							if((Sys_data_object.P1.func_cfg_bytes[12]&0x80)&&(Sys_data_object.P1.func_cfg_bytes[12]&0x03)) //PSM模式上报判断
							{
								time_upload_state = TIME_UPLOAD_PsmSleep;
							}
							else
							{
								time_upload_state = TIME_UPLOAD_UDP_S1;
							}
						}
						else
						{
							if((getUploadControlPara(UP_WITH_UDP)==TRUE)&&(getUploadControlPara(UP_CGATT_FAIL)==FALSE))//附网成功才UDP上报
							{
								time_upload_state = TIME_UPLOAD_UDP_S1;
							}
							else
							{
								time_upload_state = TIME_UPLOAD_PowerDown;
							}
						} 
					}
				}
			}
        }
        break;
		//UDP上报流程
		case TIME_UPLOAD_UDP_S1:
		{
			if(TRUE == GetNbiotRevHandleOverFlag())	//无NB数据在处理
			{
				if(NbiotIfIdle())
				{
					upload_frame_data_step=0;
					NB_NetConnectStart(Sys_data_object.P2.server_ip, Sys_data_object.P2.server_port.datas, SLAVE_CONNECT_TYPE);	
					Set100msTimer(TIMER_100MS_NBIOT_20, getUploadControlPara(UP_DELAY_TIME1));			
					time_upload_state = TIME_UPLOAD_UDP_S2;
				}
			}
		}
		break;
		
		case TIME_UPLOAD_UDP_S2://上报数据组帧状态复位
		{
			if(ConncetIfOnline(SLAVE_CONNECT_TYPE)) 
			{
				upload_frame_data_step = UPLOAD_FRAME_REQUEST_NEW;
				time_upload_state = TIME_UPLOAD_UDP_S3;
			}
			else if (Check100msTimer(TIMER_100MS_NBIOT_20) == 0)//5s超时时间到
			{
				upload_frame_data_step = UPLOAD_FRAME_ONLINE_FAIL;
				time_upload_state = TIME_UPLOAD_UDP_S3; 
			}
		}
		break;
		case(TIME_UPLOAD_UDP_S3):	//等上报数据组帧完成
        {
			GetUploadDataResetState_UDP();
			time_upload_state = TIME_UPLOAD_UDP_S4;
        }
        break;
		
		case(TIME_UPLOAD_UDP_S4):	//等上报数据组帧完成
        {
            GetUploadDataMachine_UDP(upload_frame_data_step, upload_send_buf, &upload_send_len);
			if(GetUploadDataCheckIdle_UDP() == TASK_IDLE)
			{
				if(GetUploadDataCheckTask_UDP() == PTL_PACK_SUCCESS)
				{
					time_upload_state = TIME_UPLOAD_UDP_S5;
				}
				else
				{
					Set100msTimer(TIMER_100MS_NBIOT_20, getUploadControlPara(UP_DELAY_TIME1));
					time_upload_state = TIME_UPLOAD_UDP_S7;
				}
			}
        }
        break;
		
		case TIME_UPLOAD_UDP_S5://等待UDP数据发送
		{
			if (TASK_IDLE == NbiotIfIdle())
			{
				NbiotSendTask(upload_send_buf, upload_send_len, SLAVE_SEND_TYPE, &upload_send_state);	
				Set100msTimer(TIMER_100MS_NBIOT_20, UDP_UPLOAD_WAIT_ACK_TIME);//等待应答时间
				time_upload_state = TIME_UPLOAD_UDP_S6; 
			}
		}
		break;
		
		case(TIME_UPLOAD_UDP_S6):	//等待UDP应答
        {
			if(FrameCheckMsgApp(MsgNbUplaod_AckOk) == 1)//收到上传应答帧
			{
				FrameClearMsgApp(MsgNbUplaod_AckOk);//清消息
				upload_frame_data_step = UPLOAD_FRAME_UPLOAD_OK;
				time_upload_state = TIME_UPLOAD_UDP_S4;
			}
			else if (Check100msTimer(TIMER_100MS_NBIOT_20) == 0)//超时无应答
			{
				upload_frame_data_step = UPLOAD_FRAME_UPLOAD_RETRY;
				time_upload_state = TIME_UPLOAD_UDP_S4;
			}
        }
        break; 
			
		case TIME_UPLOAD_UDP_S7:
		{
			if(FrameCheckMsgApp(MsgNb_FlagRcvNbFrame)||(TRUE == UdpIfNeedReadData()))//收到下行指令再延长5s在线时间
			{
				FrameClearMsgApp(MsgNb_FlagRcvNbFrame);
				Set100msTimer(TIMER_100MS_NBIOT_20, getUploadControlPara(UP_DELAY_TIME1));
			}
			if(Check100msTimer(TIMER_100MS_NBIOT_20) == 0)
			{
				if(TRUE == GetNbiotRevHandleOverFlag())	//无NB数据在处理
				{
					time_upload_state = TIME_UPLOAD_PowerDown;
				}
			}
		}
		break;
		case TIME_UPLOAD_PsmSleep:
		{
			if(NbiotIfIdle()==TASK_IDLE)
			{
				NbiotPsmSleepTask();
				time_upload_state = TIME_UPLOAD_PsmSleepWait;
			}     
		}
		break;
		case TIME_UPLOAD_PsmSleepWait:
		{
			if(NbiotIfIdle()==TASK_IDLE)
			{
				if(PSM_STATE_SLEEP == getPsmState())//如果进入PSM休眠成功
				{
					Sys_data_object.P3.NBSleepMode = 1;
					UdpEndCheckData();
					ClosePrintNbDataSwitch();
					ClearEventUploadFlag();
					time_upload_state = TIME_UPLOAD_S0;	
					main_upload_state = UPLOAD_S0;
				}
				else
				{
					time_upload_state= TIME_UPLOAD_PowerDown;
				}
			}     
		}
		break;	
		//模组断电流程
		case TIME_UPLOAD_PowerDown:
		{
			if(NbiotIfIdle())
			{
				StartPowerOffTask();
				time_upload_state = TIME_UPLOAD_PowerDownWait;
			}   
		}
		break;
		
		case TIME_UPLOAD_PowerDownWait:
		{
			if(NbiotIfIdle())
			{
				time_upload_state = TIME_UPLOAD_PowerDownEnd;
			}
		} 
		break;
		
		case TIME_UPLOAD_PowerDownEnd:
		{
			if(TASK_IDLE == EepIfIdle())
			{
				if(((FrameCheckParaApp(FramePara_FuncCfg0_3)>>16)&0xFF) == 0xAA)//如果红外调试开启,则关闭红外调试
				{
					Sys_data_object.P1.func_cfg_bytes[2] = 0;
					s_upload_eep_complete = 0;
					EepWrite(&Sys_data_object.P1.func_cfg_bytes[2], (EEP_FRAME_FUNCCFGBYTES_ADDR+2), 1, &s_upload_eep_complete);
					Frame_Para_Init();
				}
				NbForcePowerOff();//NB强制关机
				UdpEndCheckData();
				ClosePrintNbDataSwitch();
				ClearEventUploadFlag();
				Sys_data_object.P3.NBSleepMode = 0; //NB模组休眠选择标志
				time_upload_state = TIME_UPLOAD_S0;	
				main_upload_state = UPLOAD_S0;
			}
		}
		break;
		
		default:
		{
			time_upload_state = TIME_UPLOAD_S0;
		}
		break;
	} 
	//NB活跃时间超时处理,超时不空闲,则强制关机
	if(TASK_BUSY == FixedTimeNbIoTUploadIfIdle())
    {
        if(0 == Check100msTimer(TIMER_100MS_WAIT_SLEEP_GPRS))
		{
			time_upload_state = TIME_UPLOAD_PowerDownEnd;
		} 
    }
}

void FixedTimeNbIoTUpload(void)
{
	UploadConditionJuge();
	switch(main_upload_state)
	{
		case UPLOAD_S0:
		{
		}
		break;
		case UPLOAD_S1://生产上报流程
		{
			FixedTimeNbIoTUpload_Ies();
		}
		break;
		case UPLOAD_S2://其他规约上报流程
		{
			FixedTimeNbIoTUpload_Other();
		}
		break;
		default:
		{
			main_upload_state = UPLOAD_S0;
		}
		break;
	}
}
void SystemClearUploadAgain(void)
{
	upload_again_cnt_copy = 0;
}
void SystemAddUploadAgain(void)
{
	if(UPLOAD_TYPE_FIX_TIME == GetEventUploadType())//定时上传
	{
		s_upload_ack_fail_times++;//多天无应答记录增加
	}
	if(s_upload_ack_fail_times<10)
	{
		upload_again_cnt_copy++;
	}
}

/*******************************数据存储******************************/

IES_PULSE_DAY_MAX_FLOW ies_pulse_day_max_flow;	
static void SysCheckFlowMinMax(DateTime alarm_time)  
{
	static u16 pulse_day_max_flow_time_temp;
	static u32 old_total_speed = 0;
	static u32 new_total_speed = 0;
	static u8 date_flag = 0;
	RTCC_To_Float temp_to_gloat;//数据转换专用
	if((0 == alarm_time.s.hour) && (0 == alarm_time.s.minute)) //每天0点刷新上传数据
	{
		old_total_speed = 0;
		pulse_day_max_flow_time_temp =0;
		date_flag = 0;
		RtccGetDateTime(&alarm_time);
		ies_pulse_day_max_flow.pulse_flow_time[0] = alarm_time.s.second;
		ies_pulse_day_max_flow.pulse_flow_time[1] = alarm_time.s.minute;
		ies_pulse_day_max_flow.pulse_flow_time[2] = alarm_time.s.hour;
		ies_pulse_day_max_flow.pulse_flow_time[3] = alarm_time.s.weekday;
		ies_pulse_day_max_flow.pulse_flow_time[4] = alarm_time.s.day;
		ies_pulse_day_max_flow.pulse_flow_time[5] = alarm_time.s.month;
		ies_pulse_day_max_flow.pulse_flow_time[6] = alarm_time.s.year;
		ies_pulse_day_max_flow.pulse_flow_time[7] = 0x20;
	}
	//流量更新
	new_total_speed = Gp30CheckDataApp(GP30_APP_INS_FLOW);
	if((0.9*old_total_speed) < new_total_speed < (1.1*old_total_speed))
	{
		pulse_day_max_flow_time_temp++;//持续时间增加
		ies_pulse_day_max_flow.pulse_continue_time.to_uint16 = pulse_day_max_flow_time_temp*60;
		
		temp_to_gloat.gp22_float = new_total_speed; //瞬时流量 瞬时流量单位为0.01L/H，4字节无符号整数。
		ies_pulse_day_max_flow.pulse_max_flow.to_uint32 = (u32)(temp_to_gloat.gp22_float / (float)65536.00)/60; //平台转换成每小时用水量	
		//判断开始时间是否更新
		if(date_flag==1)
		{
			date_flag = 0;
			RtccGetDateTime(&alarm_time);
			ies_pulse_day_max_flow.pulse_flow_time[0] = alarm_time.s.second;
			ies_pulse_day_max_flow.pulse_flow_time[1] = alarm_time.s.minute;
			ies_pulse_day_max_flow.pulse_flow_time[2] = alarm_time.s.hour;
			ies_pulse_day_max_flow.pulse_flow_time[3] = alarm_time.s.weekday;
			ies_pulse_day_max_flow.pulse_flow_time[4] = alarm_time.s.day;
			ies_pulse_day_max_flow.pulse_flow_time[5] = alarm_time.s.month;
			ies_pulse_day_max_flow.pulse_flow_time[6] = alarm_time.s.year;
			ies_pulse_day_max_flow.pulse_flow_time[7] = 0x20;
		}
	}
	else if(new_total_speed <= (0.9*old_total_speed))//流量变小
	{
		pulse_day_max_flow_time_temp = 0;
		date_flag = 1;
	}
	else if(new_total_speed >= (1.1*old_total_speed))//流量变大
	{
		old_total_speed = new_total_speed;
		pulse_day_max_flow_time_temp =0;
		date_flag = 0;
		ies_pulse_day_max_flow.pulse_flow_time[0] = alarm_time.s.second;
		ies_pulse_day_max_flow.pulse_flow_time[1] = alarm_time.s.minute;
		ies_pulse_day_max_flow.pulse_flow_time[2] = alarm_time.s.hour;
		ies_pulse_day_max_flow.pulse_flow_time[3] = alarm_time.s.weekday;
		ies_pulse_day_max_flow.pulse_flow_time[4] = alarm_time.s.day;
		ies_pulse_day_max_flow.pulse_flow_time[5] = alarm_time.s.month;
		ies_pulse_day_max_flow.pulse_flow_time[6] = alarm_time.s.year;
		ies_pulse_day_max_flow.pulse_flow_time[7] = 0x20;
	}
}
//获取日最高流量数据
void RtccCheck_Hight_Flow(u8 **addr)
{
    *addr = ies_pulse_day_max_flow.byte;
}

void SaveFreezeData(void)
{
	switch(save_freeze_sate)
    {
        case SAVE_FREEZE_S0:
		{
			if(data_save_judge_flag)
			{
				data_save_judge_flag = FALSE;
				RtccGetDateTime(&sys_rtcc_time);
				sys_temp_min_hex = (sys_rtcc_time.s.minute >> 4)*10 + (sys_rtcc_time.s.minute & 0x0F);
				if(0 ==(sys_temp_min_hex % 5))//5分钟间隔
                { 
                    RtccAppCheckMiJi(sys_rtcc_time);
                }	
				if(0 == sys_rtcc_time.s.minute)	//整点时间
				{
					save_freeze_sate = SAVE_FREEZE_S1;
				}
				SysCheckFlowMinMax(sys_rtcc_time);
			}
		}
		break;
		case SAVE_FREEZE_S1:
		{
			if (EepIfIdle())
			{
				Sys_data_object.ee_data.data.work_hour++;//累计工作时间增加
				EepWrite(Sys_data_object.ee_data.byte, EE_FIRST_USE_ADDR, sizeof (RTCC_EE_DATA), &s_upload_eep_complete);
				save_freeze_sate  = SAVE_FREEZE_S2;
			}
		}
		break;
		case SAVE_FREEZE_S2://厂区时间判断
		{
			if(0 == sys_rtcc_time.s.hour) //每天0点
			{
				if (EepIfIdle())
				{
					if(Sys_data_object.P1.func_cfg_bytes[0] > 0)//厂区15天时间还没有到
					{
						Sys_data_object.P1.func_cfg_bytes[0]--;//厂区时间减一天
						EepWrite(&Sys_data_object.P1.func_cfg_bytes[0],ee_addr_compute((u8*)(&Sys_data_object.P1.func_cfg_bytes[0])),1,&s_upload_eep_complete);
					}
					save_freeze_sate  = SAVE_FREEZE_S3;
				}
			}
			else
			{
				save_freeze_sate  = SAVE_FREEZE_S0;
			}
		}
		break;
		case SAVE_FREEZE_S3://小时模式0点恢复天模式
		{
			if (EepIfIdle())
			{
				if(UPLOAD_MODE_HOUR == Sys_data_object.P1.Time_upload_2006.s.type)	//小时模式
				{
					Sys_data_object.P1.Time_upload_2006.s.type = UPLOAD_MODE_DAY;
					Sys_data_object.P1.Time_upload_2006.s.period = 0x00; //0x00,//report_freq_val[1]---天模式无效
					Sys_data_object.P1.Time_upload_2006.s.hour   = 0x06; //0x06,//report_freq_val[2]---6点
					Sys_data_object.P1.Time_upload_2006.s.minute = 0x00; //0x00,//report_freq_val[3]---0分
					Sys_data_object.P1.Time_upload_2006.s.second = 0x00; //0x00,//report_freq_val[4]---0秒
					EepWrite(&Sys_data_object.P1.Time_upload_2006.buf[0], FRAME_NBIot_FREQVAL, 5, &s_upload_eep_complete);
				}
				save_freeze_sate  = SAVE_FREEZE_S7;
			}
		}
		break;
		case SAVE_FREEZE_S7:
		{
			if (EepIfIdle())
			{
				save_freeze_sate = SAVE_FREEZE_S0;
			}
		}
		break;
		default:
		{
			save_freeze_sate = SAVE_FREEZE_S0;
		}
		break;
	}
}

u8 GetMcuResetSouce(void)
{
	u8 reset_souce;
	reset_souce = Reset_GetFlag(ResetFlagMskRstb);//RESET脚复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskSysreq);//软件复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskLockup);//系统异常复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskPca);//PCA复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskWdt);//看门狗复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskLvd);//低电压检测复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskPor1_5V);//1.5V启动复位
	reset_souce <<= 1;
	reset_souce |= Reset_GetFlag(ResetFlagMskPor5V);//5V启动复位
	reset_souce <<= 1;
	
	return reset_souce;
}
/*******************************************************************************
 * @fun_name:	FrameGsmMsgManage
 * @brief   :  上传和上传数据存储
 * @param[in] :	None
 * @param[out]: None
 * @retval    : None
 * @other     :
 ******************************************************************************/
void SystemProcessor(void)
{
	MinuteEventScan();
	SysDealAppMachine();
    SaveFreezeData();
    FixedTimeNbIoTUpload();	
	DataStoreMachine();
}

void SystemProcessorInit(void)
{
	upload_delay_flag = 0;
	upload_send_state=0;
	if(upload_again_cnt_copy >3)
	{
		upload_again_cnt_copy = 0;
	}
	SaveNewSoe(SOE_SY_SYS_RESET, GetMcuResetSouce());//系统重启记录
	if(Reset_GetFlag(ResetFlagMskWdt))//看门狗复位
	{
		FrameSetMsgApp(Msg_WdtReset); //用于复位补偿
	}
	if(Reset_GetFlag(ResetFlagMskPor5V))//欠压或硬复位
	{
		FrameSetMsgApp(Msg_Por5VReset); //GP30复位
	}
	
	Reset_ClearFlagAll();//清复位标识寄存器
	DataStoreInit();
	NbUploadParaSet();
	//KeySetLcdMsgApp(MENU_ACTIVE_RF);//天线测试，按键上传
}

u8 SystemProcessorIfSleep(void)
{
	if((FixedTimeNbIoTUploadIfIdle() == TASK_IDLE) && (DataStoreIfIdle() == TRUE))
	{
		return TRUE;
	}
	return FALSE;
}
#endif

