#include "sys_config.h"
#if PRODUCT_BLE_SS
#include "UWater_frame_app.h"
#include "UWater_rtcc_app.h"
#include "UWater_lcd_app.h"	
#include "UWater_pt_app.h" 
#include "UWater_frame_func_ReplyBLE.h"
#include "UWater_encryption_driver.h"
#include "UWater_DataTools_App.h"
#include "UWater_uart_driver.h"
#include "UWater_eeprom_driver.h"
#include "UWater_power_app.h"
#include "sys_processor.h"
#include "UWater_valve_driver.h"
#include "UWater_Valve_app.h"
#include "UWater_power_app.h"
#include "UWater_gp22_app.h"
#include "UWater_QZ_Store_App.h" 
#include "UWater_frame_func_ReplyNB.h"
#include "SOE.h"

/**********************************************深水规约******************************************/
static u8 s_eep_complete_BLE=0;
static u8 task_complete_ShenShui = PTL_PACK_BUSY;
static u8 g_frame_temp_buf_ShenShui[UP_BUF_SIZE];	//数据部分缓冲区
static u16 g_frame_temp_len_ShenShui=0; 
static DateTime shenshui_rtcc_time;
static STRUCT_FRAME_IES frame_struct_ShenShui; //规约信息 
static u8 *new_message_data_rev_ShenShui; 
static u8 up_deal_stat_ShenShui = UP_DEAL_S0;//规约处理状态机
/*******主动上传数据相关变量*****************************************/
//积成规约上报缓存
static STRU_UPLOAD_FRAME store_frame;//长帧存储数据
//补报数据,间隔流量存储
static TYP_STATE_SS step_save_supplt=SS_STATE_S0; 
static RTCC_To_Float old_jiange_total_flow;
static RTCC_To_Float new_jiange_total_flow;
static RTCC_UNION_2U8TOU16 jiange_data;
/////////////////////////////////////////////////////////////////////////////////////////////////////
static u8 task_complete_ble = PTL_PACK_BUSY;
//static STRUCT_FRAME_MBUS frame_struct_MBUS; //规约信息
static u8 *new_message_data_rev_ble;
static u16 g_frame_temp_len_ble;
static u8 g_frame_temp_send_buf_ble[UP_BUF_SIZE];	//数据部分缓冲区
//static u8 s_eep_complete_mbus;
static u8 up_deal_stat_ble=UP_DEAL_S0;
//static UNION_QZ_STORE_MONTH  mbus_month_data;//月冻结数据
static u8 frame_flag=0;//规约类型标志
//static u8 broad_addr[7] = {0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA};
static u8 ble_read_access_flag=0;//是否允许通信标志

//3.2抄读表数
static void frame_func_reply_BLE_ReadData(void)
{		
	UNION_FLOAT_STORAGE tmp_float_datas1,tmp_float_datas2;
	u16 temp_u16data=0;
	
	task_complete_ble = PTL_PACK_FAIL;
	g_frame_temp_len_ble =0;
	//当前净累计流量F1 单位L
	tmp_float_datas1.float_storage_format.datas = Gp30CheckDataApp(GP30_APP_TOTAL_FLOW);
	tmp_float_datas2.float_storage_format.datas = tmp_float_datas1.float_datas*10;//转成L
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[0];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[1];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[2];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[3];
	//正向累计
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[0];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[1];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[2];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[3];
	//反向累计
	tmp_float_datas1.float_storage_format.datas = Gp30CheckDataApp(GP30_APP_TOTAL_FLOW_REVERSE);
	tmp_float_datas2.float_storage_format.datas = tmp_float_datas1.float_datas*10;//转成L
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[0];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[1];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[2];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_float_datas2.float_storage_format.data_buf[3];
	//信号强度
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0;//蓝牙驱动暂无此接口
    //电池电压
	temp_u16data = PowerCheckValueSys();
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (temp_u16data&0xFF);
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_u16data>>8;
	//表计状态
	UNION_4U8TOU32 temp_MetState;
	temp_MetState = getBleWetState();
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_MetState.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_MetState.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_MetState.datas_map.data2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_MetState.datas_map.data3;
	//软件版本
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (PROGRAME_VERSION>>24)&0xFF;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (PROGRAME_VERSION>>16)&0xFF;
	//蓝牙固件版本
	BleGetFirmVerson(&g_frame_temp_send_buf_ble[g_frame_temp_len_ble]);
	g_frame_temp_len_ble++;
	g_frame_temp_len_ble++;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0;
	//温度
	tmp_float_datas1.float_datas = TempCheckValueApp();  
	if(tmp_float_datas1.float_datas < 0) //CMR还不能显示负温度  
	{
		tmp_float_datas1.float_datas = -tmp_float_datas1.float_datas;
		temp_u16data = (u32)(tmp_float_datas1.float_datas*100);//HexToBcd32((u32)(tempTempratureFlag*100));
		temp_u16data|= 0x8000;
	}
	else
	{
		temp_u16data = (u32)(tmp_float_datas1.float_datas*100);//HexToBcd32((u32)(tempTempratureFlag*100));
		temp_u16data &= 0x7FFF;
	} 
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (temp_u16data&0xFF);
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_u16data>>8;
	//运行天数
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (Sys_data_object.ee_data.data.work_hour/24)&0xFF;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (Sys_data_object.ee_data.data.work_hour/24)>>8;
	//复位次数
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (Meter_GetResetCount()>>8)&0xFF;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0;
	//校时
	DateTime tmp_data_time_buf;
	tmp_data_time_buf.s.year =  *(new_message_data_rev_ble + 4);
	tmp_data_time_buf.s.month = *(new_message_data_rev_ble + 3);
	tmp_data_time_buf.s.day =   *(new_message_data_rev_ble + 2);
	tmp_data_time_buf.s.hour =  *(new_message_data_rev_ble + 1);
	tmp_data_time_buf.s.minute =*(new_message_data_rev_ble + 0);
	tmp_data_time_buf.s.second =0x00;
	if(Rtcc_Check_DateTime(&tmp_data_time_buf)==SUCCESS)
	{
		if(tmp_data_time_buf.s.year>=0x23)
		{
			RtccSetDateTime(&tmp_data_time_buf);
			RtccClearError();
			PowerUnSleepClearSumSys(); //休眠管理，如果长时间不休眠的处理
		}
	}
	task_complete_ble = PTL_PACK_SUCCESS;
}
//3.3 控阀0x55开阀，99应急关阀，AA半开阀,BB普通关阀，CC权限关阀，DD应急开阀
/*
01	普通开阀
02	应急开阀
03	普通关
04	应急关
05	权限关
*/
static void frame_func_reply_BLE_ValveCtrl(void)
{		
	g_frame_temp_len_ble =0;
#if defined(VALVE)
    if(0x55 == *new_message_data_rev_ble)//普通开阀
    {
        ValveDealAppStart(VALVE_STATE_OPEN);
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x01;
    }
	else if(0xDD == *new_message_data_rev_ble)//应急开阀
    {
		//权限关阀期间,允许规约(手机)应急开阀.
		//通过将权限关阀状态改为应急关阀状态再执行应急开阀来实现
		if(VALVE_STATE_CLOSE_LOCK == Sys_data_object.P1.ies_valve_paras.valve_state)
		{
			Sys_data_object.P1.ies_valve_paras.valve_state = VALVE_STATE_CLOSE_EMERGENCY;
		}
        ValveDealAppStart(VALVE_STATE_OPEN_EMERGENCY);
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x02;
    }
	else if(0xBB == *new_message_data_rev_ble)	//普通关阀
    {
        ValveDealAppStart(VALVE_STATE_CLOSE);
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x03;
    }
    else if(0x99 == *new_message_data_rev_ble)	//应急关阀
    {
        ValveDealAppStart(VALVE_STATE_CLOSE_EMERGENCY);
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x04;
    }
    else if(0xCC== *new_message_data_rev_ble)		//权限关阀
    {
        ValveDealAppStart(VALVE_STATE_CLOSE_LOCK);
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x05;
    }
	else
	{
	    task_complete_ble = PTL_PACK_FAIL;
	}
# else
	task_complete_ble = PTL_PACK_FAIL;
#endif
	task_complete_ble = PTL_PACK_SUCCESS;
}
//3.4读表地址
static void frame_func_reply_BLE_ReadAddr(void)
{
	g_frame_temp_len_ble = 0;
	BleGetCurMacAddr(g_frame_temp_send_buf_ble);
	g_frame_temp_len_ble+=6;
	task_complete_ble = PTL_PACK_SUCCESS;
}
//3.5写表地址,修改mac地址
static void frame_func_s3_BLE_SetAddr(void)
{
	if(TASK_IDLE == EepIfIdle())//存储数据到EEPROM
	{
		g_frame_temp_len_ble = 0; 
		if(0x01 == Sys_data_object.P1.start_using_flg)
		{
			task_complete_ble = PTL_PACK_FAIL; 
			return;
		}
		for (int tmp_i = 0; tmp_i < 7; tmp_i++)
		{
			Sys_data_object.P1.met_addr[tmp_i] = *(new_message_data_rev_ble + tmp_i);
		}		
		EepWrite(&Sys_data_object.P1.met_addr[0], EEP_FRAME_MET_ADDR, 7, &s_eep_complete_BLE);
		Frame_Para_Init();
		FrameSetMsgApp(MsgAddr_Change);//更新MAC地址
		task_complete_ble = PTL_PACK_SUCCESS;
	}
}
//3.6设置表底数
static void frame_func_reply_BLE_WriteInitValue(void)
{
	g_frame_temp_len_ble=0;
    if (0x01 == Sys_data_object.P1.start_using_flg)  //出厂启用
    {
		task_complete_ble = PTL_PACK_FAIL;
        return;
    }	
	FrameSetMsgApp(InitialDataMsg); //累计流量防护			
	UNION_4U8TOU32 tmp_datas_buf1,tmp_datas_buf2;
	fram_tools_writeU32ByBuf(tmp_datas_buf1.data_buf, new_message_data_rev_ble, 0);					
	fram_tools_writeU32ByBuf(tmp_datas_buf2.data_buf, (new_message_data_rev_ble + 4), 0);								

	Gp30InitDataApp(tmp_datas_buf1.datas/10,tmp_datas_buf2.datas/10);		
	FrameSetMsgApp(MsgBLE_AdvChange);//下初值,更新广播数据    
	task_complete_ble = PTL_PACK_SUCCESS;		
}
//新升级规约
static void frame_func_s3_BLE_diff_BootLoad(void)
{
	static u8 s_bootloader_version_flg = 0; //远程升级版本比较结果

	switch(up_deal_stat_ble)
	{
		case UP_DEAL_S0:
		{
			if(TASK_IDLE == EepIfIdle())
			{
				g_frame_temp_len_ble = 0;
				Sys_data_object.P2.mcu = *(new_message_data_rev_ble + 0);//平台类型
				Sys_data_object.P2.mcu_model = *(new_message_data_rev_ble + 1);//MCU型号
				Sys_data_object.P2.product_model = *(new_message_data_rev_ble + 2);//产品型号
				Sys_data_object.P2.hardware_version = *(new_message_data_rev_ble + 3);//硬件版本号
				u16 software_version = (AsciiToHex(*(new_message_data_rev_ble + 10))<<12)+
				                       (AsciiToHex(*(new_message_data_rev_ble + 11))<<8)+
				                       (AsciiToHex(*(new_message_data_rev_ble + 12))<<4)+
				                       (AsciiToHex(*(new_message_data_rev_ble + 13))<<0);
				if ((Sys_data_object.P2.hardware_version == HARDWARE_VERSION_USED)&&//硬件版本2.4
					(0x22== Sys_data_object.P2.mcu) && //高:0-MIC, 1-ST, 2-HC32; 低:0-水表,1-气表,2-超水,3-超气
					(0x00 == Sys_data_object.P2.mcu_model)&&//0x00--HC32L196
					(software_version != (PROGRAME_VERSION>>16))&&//同版本不升级
				#if defined(VALVE)
					((BCD2HEX(GP30_APP_DNX)+1) == Sys_data_object.P2.product_model))//产品类型;有阀口径+1
				#else
					(BCD2HEX(GP30_APP_DNX) == Sys_data_object.P2.product_model))//产品类型;表计口径
				#endif	
				{
					//软件版本
					fram_tools_writeU32ByBuf(Sys_data_object.P2.soft_version, (new_message_data_rev_ble + 10), 0);
					//升级总字节数
					fram_tools_writeU32ByBuf(Sys_data_object.P2.update_num.data_buf, (new_message_data_rev_ble + 4), 0);
					//升级校验码
					Sys_data_object.P2.update_check.datas_map.data0 = *(new_message_data_rev_ble + 8);
					Sys_data_object.P2.update_check.datas_map.data1 = *(new_message_data_rev_ble + 9);	
					//升级通道:1-串口;2-coap;3-udp;4-蓝牙
					Sys_data_object.P2.bootloader_datas_sourse = *(new_message_data_rev_ble + 14);
					//升级标志/方式:1-完整升级;2-差分升级
					if(*(new_message_data_rev_ble + 15) == 2)
					{
						Sys_data_object.P2.bootloader_update_flg = 0x77;//差分升级
					}
					else
					{
						Sys_data_object.P2.bootloader_update_flg = 0x55;//全包升级
					}
					//包号清0
					Sys_data_object.P2.bootloader_paknum.datas =0;
					//程序破坏标志清0
					Sys_data_object.P2.bootloader_RSSI = 0;
					s_bootloader_version_flg = 0x00;
					FrameSetMsgApp(MsgUpdateSoftVersionCheckOk);
					EepWrite(&Sys_data_object.P2.soft_version[0], EEP_SOFT_VERSION, 17, &s_eep_complete_BLE);
				}
				else
				{
					s_bootloader_version_flg = 0x10;
					if(software_version == (PROGRAME_VERSION>>16))//版本相同
					{
						s_bootloader_version_flg |= 0x20;
					}
					if (0x22 != Sys_data_object.P2.mcu)
					{
						s_bootloader_version_flg = s_bootloader_version_flg|0x01;
					}
					if(0x00 != Sys_data_object.P2.mcu_model)
					{
						s_bootloader_version_flg = s_bootloader_version_flg|0x02;
					}
					if(Sys_data_object.P2.hardware_version != HARDWARE_VERSION_USED)
					{
						s_bootloader_version_flg = s_bootloader_version_flg|0x04;
					}
					#if defined(VALVE)
						if((BCD2HEX(GP30_APP_DNX)+1) != Sys_data_object.P2.product_model)//产品类型;有阀口径+1
					#else
						if(BCD2HEX(GP30_APP_DNX) != Sys_data_object.P2.product_model)//产品类型;表计口径
					#endif	
					{
						s_bootloader_version_flg = s_bootloader_version_flg|0x08;
					}
				}
				up_deal_stat_ble  = UP_DEAL_S1;
			}
		}
		break;
		case UP_DEAL_S1:
		{
			if(TASK_IDLE == EepIfIdle())//存储数据完成
			{
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P2.mcu;
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P2.mcu_model;
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P2.product_model;
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P2.hardware_version;
				fram_tools_writeU32ByBuf(&g_frame_temp_send_buf_ble[4], Sys_data_object.P2.soft_version, 0);
				g_frame_temp_len_ble +=4;
				//升级版本后加升级通道与升级方式
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]=Sys_data_object.P2.bootloader_datas_sourse;//升级通道
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = *(new_message_data_rev_ble + 15);
				g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = s_bootloader_version_flg;

				task_complete_ble = PTL_PACK_SUCCESS;
				FrameSetMsgApp(BootloaderMsg);		
				if(01 == LcdCheckStateApp())      //检定状态
				{
					FrameSetMsgApp(OutVerificationMsg);//出检定msg
				}
				up_deal_stat_ble  = UP_DEAL_S0;
			}
		}
		break;
		default:
		{
			up_deal_stat_ble  = UP_DEAL_S0;
			task_complete_ble = PTL_PACK_FAIL;
		}
		break;
	}
}			

//3.8 读取软件版本号,程序版本2，硬件版本2，蓝牙固件3字节
static void frame_func_reply_BLE_ReadSwVersion(void)
{
	g_frame_temp_len_ble=0;

	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (PROGRAME_VERSION>>24)&0xFF;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (PROGRAME_VERSION>>16)&0xFF;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (PROGRAME_VERSION>>8)&0xFF;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = (PROGRAME_VERSION>>0)&0xFF;
	BleGetFirmVerson(&g_frame_temp_send_buf_ble[g_frame_temp_len_ble]);
	g_frame_temp_len_ble+=3;
	
	task_complete_ble = PTL_PACK_SUCCESS;
}
//3.9读取表计时间
static void frame_func_reply_BLE_TimeFrequency(void)
{		
	DateTime date_time;
	g_frame_temp_len_ble =0;
	
	RtccGetDateTime(&date_time);
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = date_time.s.second;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = date_time.s.minute;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = date_time.s.hour;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = date_time.s.day;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = date_time.s.month;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = date_time.s.year;        

	task_complete_ble = PTL_PACK_SUCCESS;
}
 //3.10校时
static void frame_func_reply_BLE_CalibrateTime(void)
{
	DateTime tmp_data_time_buf;
	g_frame_temp_len_ble = 0;
	
	tmp_data_time_buf.s.year =  *(new_message_data_rev_ble + 5);
	tmp_data_time_buf.s.month = *(new_message_data_rev_ble + 4);
	tmp_data_time_buf.s.day =   *(new_message_data_rev_ble + 3);
	tmp_data_time_buf.s.hour =  *(new_message_data_rev_ble + 2);
	tmp_data_time_buf.s.minute =*(new_message_data_rev_ble + 1);
	tmp_data_time_buf.s.second =*(new_message_data_rev_ble + 0);

	RtccSetDateTime(&tmp_data_time_buf);
	RtccClearError();
	PowerUnSleepClearSumSys(); //休眠管理，如果长时间不休眠的处理  2015-7-15 增加的接口。。。
	task_complete_ble = PTL_PACK_SUCCESS;
}
 //3.11启动自检
static void frame_func_reply_BLE_TestStart(void)
{
	//阀门  rtcc   读数  EE  GP30  
	g_frame_temp_len_ble = 0;
	task_complete_ble = PTL_PACK_SUCCESS;
}
 //3.12 查询自检结果
static void frame_func_reply_BLE_TestRead(void)
{
	g_frame_temp_len_ble = 0;
	task_complete_ble = PTL_PACK_SUCCESS;
}

//3.15 读取时间段SOE
static void frame_func_reply_BLE_ReadSoe(void)
{
	static u8 num_get,num_to_get,num_to_read,totalnum;
    static mtype16_ temp_soe_type;
    static ONE_SOE soe_event_read;
    static DateTime_noweek start_time;
    static DateTime_noweek end_time;

    switch(up_deal_stat_ble)
    {
        case UP_DEAL_S0:
        {
            totalnum = 0;
            num_get = 0;
            num_to_read = Sys_data_object.P4.Point_SOE_write;
            temp_soe_type.to_uint8[0] = *(new_message_data_rev_ble); //获取事件代码类型
            temp_soe_type.to_uint8[1] = *(new_message_data_rev_ble+1);
			start_time.s.year   = *(new_message_data_rev_ble + 2);				//起始时间
            start_time.s.month  = *(new_message_data_rev_ble + 3);
            start_time.s.day    = *(new_message_data_rev_ble + 4);
            start_time.s.hour   = *(new_message_data_rev_ble + 5);
            start_time.s.minute = *(new_message_data_rev_ble + 6);
            start_time.s.second = *(new_message_data_rev_ble + 7);

            end_time.s.year   = *(new_message_data_rev_ble + 8);					//结束时间
            end_time.s.month  = *(new_message_data_rev_ble + 9);
            end_time.s.day    = *(new_message_data_rev_ble + 10);
            end_time.s.hour   = *(new_message_data_rev_ble + 11);
            end_time.s.minute = *(new_message_data_rev_ble + 12);
            end_time.s.second = *(new_message_data_rev_ble + 13);

            num_to_get = *(new_message_data_rev_ble + 14);							//读取数量
			if((0 == num_to_get) || (MAX_NUM_READ_SOE <= num_to_get))
			{
				up_deal_stat_ble = UP_DEAL_S3;
			}
			else
			{
				up_deal_stat_ble = UP_DEAL_S1;
			}
       }
       break;
	   
       case UP_DEAL_S1://读取一条SOE
       {
           if(totalnum >= TOTAL_NUM_SOE)//总共读TOTAL_NUM_SOE次  强制退出不能再读了
           {
                up_deal_stat_ble = UP_DEAL_S3;
                break;
           }
           if(TASK_IDLE == EepIfIdle())//存储数据到EEPROM
           {
                totalnum++;
                if(num_to_read > TOTAL_NUM_SOE) //防止指针跑飞了
                {
                    num_to_read = TOTAL_NUM_SOE;
                }
                if(num_to_read == 0)
                {
                    num_to_read = TOTAL_NUM_SOE;
                }
                num_to_read--;
                EepRead(EEP_ADDR_SOE_BASE + (u16)num_to_read*LENGTH_ONE_SOE,(u8*)&soe_event_read,LENGTH_ONE_SOE, &s_eep_complete_BLE);
            	up_deal_stat_ble = UP_DEAL_S2;
		   }
          
        }
        break;
		
        case UP_DEAL_S2:
        {
             if(TASK_IDLE == EepIfIdle())//读完了
             {
                 if(TRUE == Check_One_Soe(temp_soe_type.to_uint16,&start_time,&end_time,&soe_event_read))//检测到一条有效的SOE
                 {
                     memcpy(g_frame_temp_send_buf_ble + 1 + (u16)num_get * LENGTH_ONE_SOE,&soe_event_read,LENGTH_ONE_SOE);
                     num_get++;
                     if(num_get >= num_to_get)//读完了
                     {
                         up_deal_stat_ble = UP_DEAL_S3;
                         break;
                     }
                 }
                 up_deal_stat_ble = UP_DEAL_S1;
            }
        }
        break;
		
        case UP_DEAL_S3:
        {
			up_deal_stat_ble = UP_DEAL_S0;
            g_frame_temp_send_buf_ble[0] = num_get;
			g_frame_temp_len_ble = (1 + (u16) num_get * LENGTH_ONE_SOE);
			task_complete_ble = PTL_PACK_SUCCESS;  
        }
        break;
		
        default:
        {
            up_deal_stat_ble  = UP_DEAL_S0;
			task_complete_ble = PTL_PACK_FAIL;  
        }
        break;
    }
}

//3.16 读取欠压阈值
static void frame_func_reply_BLE_ReadVoltageLow(void)
{
	g_frame_temp_len_ble =0;
	
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P1.voltage_low[0];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P1.voltage_low[1];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P1.voltage_low[2];
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = Sys_data_object.P1.voltage_low[3];
	
	up_deal_stat_ble  = UP_DEAL_S0;
	task_complete_ble = PTL_PACK_SUCCESS;
}
//3.17 设置欠压阈值
static void frame_func_reply_BLE_SetVoltageLow(void)
{
	if(TASK_IDLE == EepIfIdle())
	{
		g_frame_temp_len_ble = 0;
		
		Sys_data_object.P1.voltage_low[0]  = *(new_message_data_rev_ble + 0);	
		Sys_data_object.P1.voltage_low[1]  = *(new_message_data_rev_ble + 1);
		Sys_data_object.P1.voltage_low[2]  = *(new_message_data_rev_ble + 2);
		Sys_data_object.P1.voltage_low[3]  = *(new_message_data_rev_ble + 3);
		EepWrite(Sys_data_object.P1.voltage_low, EEP_BLE_PARA_VOLTAGE, 4, &s_eep_complete_BLE);

		up_deal_stat_ble  = UP_DEAL_S0;
		task_complete_ble = PTL_PACK_SUCCESS;
	}
}
//3.25 读取日结数据
static UNION_QZ_STORE_DAY temp_daily_data;
static void frame_func_reply_BLE_ReadDaily(void)
{
    static u8 temp_read_index = 0;
    static u8 temp_read_code = 0;   
	static u8 temp=0;

    switch(up_deal_stat_ble)
    {
		case UP_DEAL_S0:
		{
			temp_read_code = 1;   
			g_frame_temp_len_ble =0;
			temp_read_index = get_QZ_StorePara(QZ_StoreCurIndex_Daily);
			up_deal_stat_ble = UP_DEAL_S1;
		}
		break;
        case UP_DEAL_S1:
        {
			if(TASK_IDLE == EepIfIdle())//读取历史数据
			{
				if (temp_read_index >= temp_read_code)
				{
					temp = temp_read_index - temp_read_code;
				}
				else
				{
					temp = 100 - (temp_read_code - temp_read_index);
				}
				EepRead((EEP_ADDR_QZ_STORE_DAY +(temp*128)), temp_daily_data.data_buf, 128, &s_eep_complete_BLE);		
				up_deal_stat_ble  = UP_DEAL_S2;
			}  					           
        }
        break;
        case UP_DEAL_S2:
        {
            if(TASK_IDLE == EepIfIdle())//读取历史数据完成
            {
				if(temp_read_code<32)
				{
					if((temp_daily_data.Data.Head==0x5A)&&(temp_daily_data.Data.End==0xA5))
					{
						temp_daily_data.Data.DailyFlowData.gp22_u32 = temp_daily_data.Data.DailyFlowData.gp22_u32*10;
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.DailyFlowData.buf[0];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.DailyFlowData.buf[1];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.DailyFlowData.buf[2];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.DailyFlowData.buf[3];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.MetState[0];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.MetState[1];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.MetState[2];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.MetState[3];
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.Year;
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.Month;
						g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_daily_data.Data.Day;
					}
					temp_read_code++;
					up_deal_stat_ble  = UP_DEAL_S1;
				}
				else
				{
					task_complete_ble = PTL_PACK_SUCCESS;                
					up_deal_stat_ble  = UP_DEAL_S0;
				}
            }
        }
        break;
        default:
        {
			task_complete_ble = PTL_PACK_FAIL;
            up_deal_stat_ble  = UP_DEAL_S0;
        }
        break;
    }   	
}
//3.26 读取月结数据
static UNION_QZ_STORE_MONTH  temp_month_data;
static void frame_func_reply_BLE_ReadMonth(void)
{
    static u8 temp_read_index = 0;
    static u8 temp_read_code = 0;   
	static u8 temp=0;

    switch(up_deal_stat_ble)
    {
		case UP_DEAL_S0:
		{
			temp_read_code = 0;   
			g_frame_temp_len_ble =0;
			temp_read_index = get_QZ_StorePara(QZ_StoreCurIndex_Month);
			up_deal_stat_ble = UP_DEAL_S1;
		}
		break;
        case UP_DEAL_S1:
        {
			if(TASK_IDLE == EepIfIdle())//读取历史数据
			{
				if (temp_read_index >= temp_read_code)
				{
					temp = temp_read_index - temp_read_code;
				}
				else
				{
					temp = 24 - (temp_read_code - temp_read_index);
				}
				EepRead((EEP_ADDR_QZ_STORE_MONTH +(temp*6)), temp_month_data.data_buf, 6, &s_eep_complete_BLE);			
				up_deal_stat_ble  = UP_DEAL_S2;
			}  					           
        }
        break;
        case UP_DEAL_S2:
        {
            if(TASK_IDLE == EepIfIdle())//读取历史数据完成
            {
				if(temp_read_code<24)
				{
					temp_month_data.Data.FlowData.gp22_u32 = temp_month_data.Data.FlowData.gp22_u32*10;
					g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_month_data.Data.FlowData.buf[0];
					g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_month_data.Data.FlowData.buf[1];
					g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_month_data.Data.FlowData.buf[2];
					g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_month_data.Data.FlowData.buf[3];
					g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_month_data.Data.Year;
					g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_month_data.Data.Month;
					temp_read_code++;
					up_deal_stat_ble  = UP_DEAL_S1;
				}
				else
				{
					task_complete_ble = PTL_PACK_SUCCESS;                
					up_deal_stat_ble  = UP_DEAL_S0;
				}
            }
        }
        break;
        default:
        {
			task_complete_ble = PTL_PACK_FAIL;
            up_deal_stat_ble  = UP_DEAL_S0;
        }
        break;
    }   	
}

//终端重启
static void frame_func_reply_BLE_TernalRestart(void)
{
	g_frame_temp_len_ble = 0;
	FrameSetMsgApp(BootloaderMsg);			
	if(01 == LcdCheckStateApp())      //检定状态
	{
		FrameSetMsgApp(OutVerificationMsg);  //出检定msg
	}
	task_complete_ble = PTL_PACK_SUCCESS;
}
//配置功能
static void frame_func_s3_BLE_CfgFunctioncfg(void)
{
	if(TASK_IDLE == EepIfIdle())//存储数据到EEPROM
	{
		g_frame_temp_len_ble = 0;
		UNION_4U8TOU32 temp_flag_bytes;
		fram_tools_writeU32ByBuf(temp_flag_bytes.data_buf, (new_message_data_rev_ble + 0), 0);
		if (temp_flag_bytes.datas > 0)
		{
			for(int temp_i = 0; temp_i < 32; temp_i++)
			{
				if (0x00000001 == ((temp_flag_bytes.datas >> temp_i) & 0x00000001))
				{
					Sys_data_object.P1.func_cfg_bytes[temp_i] = *(new_message_data_rev_ble + 4 + temp_i);
				}
			}
			EepWrite(&Sys_data_object.P1.func_cfg_bytes[0], EEP_FRAME_FUNCCFGBYTES_ADDR, 32, &s_eep_complete_BLE);
			Frame_Para_Init();
			FrameSetMsgApp(MsgBLE_ConfigChange);
		}			
		for(int i = 0; i<32 ;i++)
		{
			g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]	= Sys_data_object.P1.func_cfg_bytes[i];
		}
		task_complete_ble = PTL_PACK_SUCCESS;
	}
}
//读瞬时流量和温度
static void frame_func_reply_BLE_ReadInstantFlowAndTemperature(void)
{
	MET_STATE temp_state; //状态字
	static DateTime tmp_time_buf;
	UNION_4U8TOU32 tmp_datas_buf;
	UNION_FLOAT_STORAGE tmp_float_datas_buf;
	g_frame_temp_len_ble=0;
	tmp_float_datas_buf.float_storage_format.datas = Gp30CheckDataApp(GP30_APP_TOTAL_FLOW); //当前累积流量
	tmp_datas_buf.datas = (u32) tmp_float_datas_buf.float_datas;
	tmp_datas_buf.datas = HexToBcd32(tmp_datas_buf.datas);
	fram_tools_writeU32ByBuf(&g_frame_temp_send_buf_ble[g_frame_temp_len_ble], tmp_datas_buf.data_buf, 0);
	g_frame_temp_len_ble+=4;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x2C;//m3
	tmp_datas_buf.datas = Gp30CheckDataApp(GP30_APP_INS_FLOW); //瞬时流量(四位小数，放大100000倍)//BCD
	tmp_datas_buf.datas = Gp30DataToBcd(tmp_datas_buf.datas, 100);
	fram_tools_writeU32ByBuf(&g_frame_temp_send_buf_ble[5], tmp_datas_buf.data_buf, 0);
	g_frame_temp_len_ble+=4;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x35;//m3/h
	float tmep = TempCheckValueApp();      //							
	if(tmep <0)
	{				
		tmp_datas_buf.datas = (u32)(tmep*(-100));	
		tmp_datas_buf.datas &= 0x0FFFF;
		tmp_datas_buf.datas |= 0x80000;
	}
	else
	{
		tmp_datas_buf.datas = (u32)(tmep*(100));	
		tmp_datas_buf.datas &= 0x7FFFF;
	}
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data2;
	RtccGetDateTime(&tmp_time_buf);
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.day; //日
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.hour; //时
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.minute; //分
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.second; //秒
	temp_state = FrameGetByte();
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat3;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat4;
	
	task_complete_ble = PTL_PACK_SUCCESS;
}
//设置为检定状态
static void frame_func_reply_BLE_SetVerification(void)
{
	g_frame_temp_len_ble=0;
	if(*new_message_data_rev_ble == 1)//进入检定
	{
		if (0 == Sys_data_object.P1.enable_verification_function)
		{
			task_complete_ble = PTL_PACK_FAIL;
			return;
		}
		FrameSetMsgApp(SetVerificationMsg);
		FrameClearMsgApp(MsgCaliberate);//清零 单程时间校准校准标志
	}
	else if(*new_message_data_rev_ble == 10)//退出检定
	{
		if(01 == LcdCheckStateApp())      //检定状态
		{
			FrameSetMsgApp(OutVerificationMsg); //出检定msg
		}	
	}
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = *new_message_data_rev_ble;
	task_complete_ble = PTL_PACK_SUCCESS;
}
//读检定数据
static void frame_func_reply_BLE_ReadVerificationData(void)
{
	int i;
	static MET_STATE temp_state; //状态字
	static DateTime tmp_time_buf;
	UNION_4U8TOU32 tmp_datas_buf;
	UNION_FLOAT_STORAGE tmp_float_datas_buf;
	float tempTempratureFlag;
	 g_frame_temp_len_ble=0;
	if(01 != LcdCheckStateApp())      //非检定状态
	{
		task_complete_ble = PTL_PACK_FAIL;
		return;
	}	
	//温度

	if(TRUE==Check_Start_STOP_Filter_Flag())//获取start-stop完成温度滤波标志
	{
		Clear_Start_STOP_Filter_Flag();//清零start-stop完成温度滤波标志
		tempTempratureFlag = Check_Temperature_Parameter();//传递滤波的反算温度数据
	}
	else
	{
		tempTempratureFlag = TempCheckValueApp();//获取实时温度
	}
	
	if(tempTempratureFlag < 0)  
	{
		tempTempratureFlag = -tempTempratureFlag;
		tmp_datas_buf.datas = HexToBcd32((u32)(tempTempratureFlag*100));
		tmp_datas_buf.datas|= 0x800000;
	}
	else
	{
	tmp_datas_buf.datas = HexToBcd32((u32)(tempTempratureFlag*100));
	tmp_datas_buf.datas &= 0x7FFFFF;
	}  
  for(i=0;i<3;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }		
	//累计流量
	tmp_float_datas_buf.float_storage_format.datas = Gp30CheckTestDataApp(GP30_APP_TOTAL_FLOW); //累计流量//BCD
	tmp_datas_buf.datas = (u32) (tmp_float_datas_buf.float_datas);
	tmp_datas_buf.datas = HexToBcd32(tmp_datas_buf.datas);
  for(i=0;i<4;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }	
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x2C; //m?
	//瞬时流量
	tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_INS_FLOW); //瞬时流量(四位小数，放大100000倍)//BCD
	tmp_datas_buf.datas = Gp30DataToBcd(tmp_datas_buf.datas, 100);
  for(i=0;i<4;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }	
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x35; //m?/h
	//up单程时间
  tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_TOF);//up单程时间获取 
  for(i=0;i<4;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }	
	//Magnify 100000 times（m3/h）：Real-time instantaneous flow
	tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_INS_FLOW_LCD); 
	tmp_datas_buf.datas = Gp30DataToBcd(tmp_datas_buf.datas, 100);
  for(i=0;i<4;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }	
	//tof
	tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_DIFF); //时间差
  for(i=0;i<4;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }	
	////累计工作时间//BCD
	tmp_datas_buf.datas = RtccGetWorkHourApp(); 
	tmp_datas_buf.datas = HexToBcd32(tmp_datas_buf.datas);
  for(i=0;i<3;i++)
  {
    g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
  }	
	//实时时间
	RtccGetDateTime(&tmp_time_buf); 
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0x20;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.year;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.month;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.day;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.hour;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.minute;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_time_buf.s.second;
	//状态字
	temp_state = FrameGetByte();
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat3;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = temp_state.stat4;
   //************************新增数据:15字节***********************/
  //反算温度T0-T2（T2）:3字节
    //温度T0-T2（T2）:3字节
   #if WENDU_FANSUAN_OPEN
	tempTempratureFlag = TempCheckValueApp();//传递实时的反算数据
					
	if(tempTempratureFlag < 0)  
	{
		tempTempratureFlag = -tempTempratureFlag;
		tmp_datas_buf.datas = HexToBcd32((u32)(tempTempratureFlag*100));
		tmp_datas_buf.datas|= 0x800000;
	}
	else
	{
        tmp_datas_buf.datas = HexToBcd32((u32)(tempTempratureFlag*100));
        tmp_datas_buf.datas &= 0x7FFFFF;
	}
	for(i=0;i<3;i++)
    {
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.data_buf[i];
    }
	tmp_datas_buf.datas = Gp30CheckDataApp(11);	//TOF_UP补偿系数
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data3;
	 
	tmp_datas_buf.datas = Gp30CheckDataApp(12);//TOF_DOWN补偿系数
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data3;
	#else//常规程序反算温度默认写0
	for(i=0;i<3;i++)
    {
        g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = 0;
    }	
    //up amplitude(V1):4字节
	tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_PEAK_UP);
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data3;
	 //down amplitude(V2):4字节
	tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_PEAK_DOWN);
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++]  = tmp_datas_buf.datas_map.data3;
	#endif
	//预留:4字节
    tmp_datas_buf.datas = Gp30CheckTestDataApp(GP30_APP_DOWN);//down 的单程时间       
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data0;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data1;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data2;
	g_frame_temp_send_buf_ble[g_frame_temp_len_ble++] = tmp_datas_buf.datas_map.data3;

	task_complete_ble = PTL_PACK_SUCCESS;
}
//蓝牙规约:读某天历史数据
static void frame_func_reply_BLE_ReadHistoryData(void)
{
    u8 temp = 0;
    u8 temp_read_index = 0;
    u8 temp_read_code = *new_message_data_rev_ble;   

    switch(up_deal_stat_ble)
    {
        case UP_DEAL_S0:
        {
			if(TASK_IDLE == EepIfIdle())//读取历史数据
			{
				g_frame_temp_len_ble =0;
				temp_read_index = NB_SS_Control_GetPara(NB_HistroyReadIndex);
				if (temp_read_index >= temp_read_code)
				{
					temp = temp_read_index - temp_read_code;
				}
				else
				{
					temp = 32 - (temp_read_code - temp_read_index);
				}
				EepRead((FRAME_NBIot_HISTORY_READ_ADD +(temp*PACK_NUM_GPRS)), g_frame_temp_send_buf_ble, PACK_NUM_GPRS, &s_eep_complete_BLE);		
				up_deal_stat_ble  = UP_DEAL_S1;
			}         
        }
        break;

        case UP_DEAL_S1:
        {
            if(TASK_IDLE == EepIfIdle())//读取历史数据完成
            {
				g_frame_temp_len_ble = PACK_NUM_GPRS;  
				task_complete_ble = PTL_PACK_SUCCESS; 				
                up_deal_stat_ble  = UP_DEAL_S0;
            }
        }
        break;
      
        default:
        {
            up_deal_stat_ble  = UP_DEAL_S0;
			task_complete_ble = PTL_PACK_FAIL; 
        }
        break;
    }    	 
}
//深水规约:读某天历史数据
static void frame_func_reply_NB_ReadHistoryData(void)
{
    u8 temp = 0;
    u8 temp_read_index = 0;
    u8 temp_read_code = *new_message_data_rev_ShenShui;   

    switch(up_deal_stat_ShenShui)
    {
        case UP_DEAL_S0:
        {
			if(TASK_IDLE == EepIfIdle())//读取历史数据
			{
				g_frame_temp_len_ShenShui =0;
				temp_read_index = NB_SS_Control_GetPara(NB_HistroyReadIndex);
				if (temp_read_index >= temp_read_code)
				{
					temp = temp_read_index - temp_read_code;
				}
				else
				{
					temp = 32 - (temp_read_code - temp_read_index);
				}
				EepRead((FRAME_NBIot_HISTORY_READ_ADD +(temp*PACK_NUM_GPRS)), g_frame_temp_buf_ShenShui, PACK_NUM_GPRS, &s_eep_complete_BLE);		
				up_deal_stat_ShenShui  = UP_DEAL_S1;
			}         
        }
        break;

        case UP_DEAL_S1:
        {
            if(TASK_IDLE == EepIfIdle())//读取历史数据完成
            {
				g_frame_temp_len_ShenShui = PACK_NUM_GPRS;  
                task_complete_ShenShui = PTL_PACK_SUCCESS; 			
                up_deal_stat_ShenShui  = UP_DEAL_S0;
            }
        }
        break;
      
        default:
        {
            up_deal_stat_ShenShui  = UP_DEAL_S0;
            task_complete_ShenShui = PTL_PACK_FAIL;
        }
        break;
    }    	 
}
//设置OTA
static void frame_func_reply_BLE_SetOta(void)
{
	g_frame_temp_len_ble=0;
	if(*new_message_data_rev_ble == 0xAA)//进入OTA升级状态
	{
		FrameSetMsgApp(MsgBLE_OtaEnter);
	}
	else
	{
		FrameSetMsgApp(MsgBLE_OtaExit);
	}
	task_complete_ble = PTL_PACK_SUCCESS;
}

void setBleReadAccessFlag(u8 data)
{
	ble_read_access_flag = data;
}
static u8 getBleReadAccessFlag(void)
{
	return ble_read_access_flag;
}
//积成规约表地址判断
u8 check_met_addr_BLE(u8 *p_buf,u8 *des_buf)
{
    u8 tmp_i;
    for (tmp_i = 0; tmp_i < 7; tmp_i++)
    {
        if (*(p_buf + 2 +tmp_i) != *(des_buf + tmp_i))
        {
            break;
        }
    }
	if( (BLE_READ_MET_DI0 == *(p_buf+13))
		||(BLE_SET_MET_DI0 == *(p_buf+13)))//读写表地址
	{
		for(tmp_i=0;tmp_i < 7;tmp_i++)
		{
			if(0xAA != *(p_buf + 2 + tmp_i))//广播读地址
			break;
		}	
	}
	if(tmp_i >= 7)	
	{
		return SUCCESS_IES;
	}
	return ERROR_IES;
}
//蓝牙规约解析
static u8 crack_frame_BLE_Static(u16 frame_lenth,u8 *frame_buffer)
{
	u16 tmp_i = 0;
    u16 tmp_j = 0;
    u8 tmp_check = 0;

    for (tmp_i = 0; tmp_i < frame_lenth; tmp_i++)
    {
        if (FM_HEAD_MARK == *(frame_buffer + tmp_i))
        {
            if (MET_TYPE == *(frame_buffer + tmp_i + 1))
            {
                    frame_struct_ShenShui.head_site = tmp_i; //记录帧头
                    frame_struct_ShenShui.sta  = *(frame_buffer + tmp_i + 10);//状态字
                    frame_struct_ShenShui.len = *(frame_buffer + tmp_i + 11)+ *(frame_buffer + tmp_i + 12)*256;//数据长度
                    frame_struct_ShenShui.end_site = frame_struct_ShenShui.head_site + frame_struct_ShenShui.len + 14;  //长度占俩字节 再改14
                    frame_struct_ShenShui.check_len = frame_struct_ShenShui.end_site - frame_struct_ShenShui.head_site - 1;
                
                    //检测数据帧是否有效
                    if ((frame_struct_ShenShui.end_site < frame_lenth) && (FM_END_MARK == *(frame_buffer + frame_struct_ShenShui.end_site)))
                    {
                        frame_struct_ShenShui.ctrl = *(frame_buffer + frame_struct_ShenShui.head_site + 9);
                        //计算校验和
                        for (tmp_j = frame_struct_ShenShui.head_site; tmp_j < (frame_struct_ShenShui.end_site - 1); tmp_j++)
                        {
                            tmp_check += *(frame_buffer + tmp_j);
                        }
                        if (tmp_check == *(frame_buffer + frame_struct_ShenShui.end_site - 1))
                        {			
							if((frame_struct_ShenShui.sta  & 0x01) == 0x01)//判断是否为加密规约
							{
								//还原成明文规约:解密,修改加密标志
								//AES_decrypt(frame_buffer+frame_struct_ShenShui.head_site +12, frame_struct_ShenShui.len,Sys_data_object.P1.key);
								  AES_decrypt(frame_buffer+frame_struct_ShenShui.head_site +13, frame_struct_ShenShui.len,Sys_data_object.P1.key);								
								//非加密校验和
								tmp_check = 0;
								for (tmp_j = frame_struct_ShenShui.head_site; tmp_j < (frame_struct_ShenShui.end_site - 1); tmp_j++)
								{
									tmp_check += *(frame_buffer + tmp_j);
								}
								*(frame_buffer + frame_struct_ShenShui.end_site - 1) = tmp_check;
							}
							if (SUCCESS_IES == check_met_addr_BLE(frame_buffer + frame_struct_ShenShui.head_site, Sys_data_object.P1.met_addr)) 
							{
								frame_struct_ShenShui.sta &= 0xFD; //表示非主动上传（bit1为1时表示主动上传，0表示应答）
								frame_struct_ShenShui.DI0 = *(frame_buffer + frame_struct_ShenShui.head_site + 13);
								frame_struct_ShenShui.DI1 = *(frame_buffer + frame_struct_ShenShui.head_site + 14);
								frame_struct_ShenShui.serial_num0 = *(frame_buffer + frame_struct_ShenShui.head_site + 15);	
								frame_struct_ShenShui.serial_num1 = *(frame_buffer + frame_struct_ShenShui.head_site + 16); 
								new_message_data_rev_ble = frame_buffer + frame_struct_ShenShui.head_site + 17;										
								return  SUCCESS_IES;
							}
                        }
                    }
            }
        }
    }
    return ERROR_IES;
}


static u8 up_deal_code_ble_static(void)
{
	task_complete_ble = PTL_PACK_BUSY;
    switch(frame_struct_ShenShui.ctrl)
    {
		case 0xb0:
		{
			FrameSetMsgApp(MsgBLE_RevData);//收到指令信息 
			if(frame_struct_ShenShui.DI0 != BLE_READ_DATA_DI0)//如果不是读表数据命令,则判断是否鉴权成功
			{
				if(getBleReadAccessFlag()==0)
				{
					up_deal_stat_ShenShui  = UP_DEAL_S0;
					task_complete_ble = PTL_PACK_FAIL;  
					return task_complete_ble;
				}
			}
			switch(frame_struct_ShenShui.DI0)
			{
				case BLE_READ_DATA_DI0://抄读表数
				{
					frame_func_reply_BLE_ReadData(); 
					FrameSetMsgApp(MsgBLE_ReadData);//读表数据消息
					setBleReadAccessFlag(1);//鉴权成功
				}
				break;
				case BLE_VALVE_CTRL_DI0://阀控
				{
					frame_func_reply_BLE_ValveCtrl();
				}
				break;
				case BLE_READ_MET_DI0://读取表地址 
				{
					frame_func_reply_BLE_ReadAddr();
				}
				break;
				case BLE_SET_MET_DI0://设置表地址
				{
					frame_func_s3_BLE_SetAddr();
				}
				break;
				case BLE_SET_DATA_DI0://设置表底数
				{
					frame_func_reply_BLE_WriteInitValue();
				}
				break;
				case BLE_SET_BOOT_DI0://升级
				{
					frame_func_s3_BLE_diff_BootLoad();
				}
				break;
				case BLE_READ_VERSION_DI0://读软件版本
				{
					frame_func_reply_BLE_ReadSwVersion();
				}
				break;
				case BLE_READ_TIME_DI0://读表时间
				{
					frame_func_reply_BLE_TimeFrequency();
				}
				break;
				case BLE_SET_TIME_DI0://设置表时间
				{
					frame_func_reply_BLE_CalibrateTime();
				}
				break;
				case BLE_TEST_START_DI0://启动自检
				{
					frame_func_reply_BLE_TestStart();
				}
				break;
				case BLE_TEST_READ_DI0://查询自检
				{
					frame_func_reply_BLE_TestRead();
				}
				break;
				case BLE_READ_SOE_DI0://读SOE
				{
					frame_func_reply_BLE_ReadSoe();
				}
				break;
				case BLE_READ_PWLOW_DI0://读欠压阈值
				{
					frame_func_reply_BLE_ReadVoltageLow();
				}
				break;
				case BLE_SET_PWLOW_DI0://设置欠压阈值
				{
					frame_func_reply_BLE_SetVoltageLow();
				}
				break;
				case BLE_READ_DAILY_DI0://读日结数据
				{
					frame_func_reply_BLE_ReadDaily();
				}
				break;
				case BLE_READ_MONTH_DI0://读月结数据
				{
					frame_func_reply_BLE_ReadMonth();
				}
				break;
				case BLE_RESET_MCU_DI0://MCU重启
				{
					frame_func_reply_BLE_TernalRestart();
				}
				break;
				case BLE_SET_CONFIG_DI0://设置功能配置字
				{
					frame_func_s3_BLE_CfgFunctioncfg();
				}
				break;
				
				case BLE_READ_FLOWTEMP_DI0://读瞬时流量和温度
				{
					frame_func_reply_BLE_ReadInstantFlowAndTemperature();
				}
				break;
				case BLE_ENTER_TEST_DI0://检定状态
				{
					frame_func_reply_BLE_SetVerification();
				}
				break;
				case BLE_READ_TEST_DI0://读检定数据
				{
					frame_func_reply_BLE_ReadVerificationData();
				}
				break;
				case BLE_READ_HIS_DI0://读某天历史数据
				{
					frame_func_reply_BLE_ReadHistoryData();
				}
				break;
				case BLE_OTA_NOTIC_DI0://OTA
				{
					frame_func_reply_BLE_SetOta();
				}
				break;
				
				default:
				{
					up_deal_stat_ShenShui  = UP_DEAL_S0;
					task_complete_ble = PTL_PACK_FAIL; 
				}
			}
			frame_struct_ShenShui.ack_ctrl = 0xA0;
		}
		break;
        default:
        {     
			up_deal_stat_ShenShui  = UP_DEAL_S0;
			task_complete_ble = PTL_PACK_FAIL;           
        }
        break;
    }
    return task_complete_ble;
}

static void Frame_ResetDealState_BLE_Static(void)
{
	up_deal_stat_ble = UP_DEAL_S0;
}
/*******************************************************************************
 * @fun_name:	Frame_CreatCrcCs_Ack
 * @brief   :   组cs或CRC校验帧
 * @param[in] :	*p;len
 * @param[out]: None
 * @retval    : None
 * @other     :
 ******************************************************************************/
void Frame_ack_BleBase(STRUCT_FRAME_IES temp_struct, u8* p_temp_buf, u16 p_temp_len, u8* p_send_buf, u16* p_send_len)
{
    int i = 0;
	UNION_2U8TOU16 temp_pack_len;
	
    p_send_buf[0] = 0xFE;
    p_send_buf[1] = 0xFE;
    p_send_buf[2] = FM_HEAD_MARK;
    p_send_buf[3] = MET_TYPE;
	for (i = 0; i < 7; i++)
	{
		p_send_buf[4 + i] = Sys_data_object.P1.met_addr[i];
	}
    p_send_buf[11] = temp_struct.ack_ctrl;
    p_send_buf[12] = temp_struct.sta;//sta 0x40标识主动上传帧  0x80 位加密帧 0xc0为加密的主动上传帧  
    {
        temp_pack_len.datas  = p_temp_len+4;
        p_send_buf[13] = temp_pack_len.datas_map.data0;
        p_send_buf[14] = temp_pack_len.datas_map.data1;
        p_send_buf[15] = temp_struct.DI0; //DI0
        p_send_buf[16] = temp_struct.DI1; //DI1
        p_send_buf[17] = temp_struct.serial_num0; //SER
        p_send_buf[18] = temp_struct.serial_num1; //SER
        memcpy(&p_send_buf[19], p_temp_buf, p_temp_len);
        if((temp_struct.sta & 0x01) == 0x01)
        {
            AES_encrypt(1,&p_send_buf[15], temp_pack_len.datas, Sys_data_object.P1.key);//加密
            temp_pack_len.datas = (temp_pack_len.datas/16+1)*16;
            p_send_buf[13]=temp_pack_len.datas_map.data0;//蓝牙低位在前
            p_send_buf[14]=temp_pack_len.datas_map.data1;
        }
        p_send_buf[15+temp_pack_len.datas]=0;
        for (i = 2; i < 15+temp_pack_len.datas; i++)
        {
            p_send_buf[15+temp_pack_len.datas] += p_send_buf[i];//校验和
        }           
        p_send_buf[16+temp_pack_len.datas] = FM_END_MARK; //帧结束符
        *p_send_len = 17+temp_pack_len.datas;
    }    
}
static void Frame_CreatAck_BLE(u8* p_send_buf, u16* p_send_len)
{
	STRUCT_FRAME_IES temp_struct;
	
	temp_struct.ack_ctrl = frame_struct_ShenShui.ack_ctrl;
	temp_struct.DI0 = frame_struct_ShenShui.DI0;
	temp_struct.DI1 = frame_struct_ShenShui.DI1;
	temp_struct.sta = frame_struct_ShenShui.sta;
	temp_struct.serial_num0 = frame_struct_ShenShui.serial_num0;
	temp_struct.serial_num1 = frame_struct_ShenShui.serial_num1;

	Frame_ack_BleBase(temp_struct,g_frame_temp_send_buf_ble, g_frame_temp_len_ble, p_send_buf, p_send_len);
}

//------------------------------------------------------深水规约处理--------------------------------------------------/

/******************************************深水规约*************************************************************/
//解深水规约
static u8 crack_frame_ShenShui(u16 frame_lenth,u8 *frame_buffer)
{
	u8 temp_res = crack_frame_IES_Base(frame_lenth, frame_buffer, &frame_struct_ShenShui);
	if(temp_res == SUCCESS_IES)
	{

		frame_struct_ShenShui.sta &= 0xFD; //表示非主动上传（bit1为1时表示主动上传，0表示应答）
		frame_struct_ShenShui.DI0 = *(frame_buffer + frame_struct_ShenShui.head_site + 12);
		frame_struct_ShenShui.DI1 = *(frame_buffer + frame_struct_ShenShui.head_site + 13);
		frame_struct_ShenShui.serial_num0 = *(frame_buffer + frame_struct_ShenShui.head_site + 14);	
		frame_struct_ShenShui.serial_num1 = *(frame_buffer + frame_struct_ShenShui.head_site + 15); 		
		new_message_data_rev_ShenShui = frame_buffer + frame_struct_ShenShui.head_site + 16;								
		frame_lenth = 0;
		return  SUCCESS_IES;
	}
	return ERROR_IES;
}
//深水规约处理
static u8 up_deal_code_ShenShui(void)
{
    task_complete_ShenShui = PTL_PACK_BUSY;
    switch(frame_struct_ShenShui.ctrl)
    {
		case SS_READ_HIS_CTRL:
		{
			switch(frame_struct_ShenShui.DI1)
			{
				case SS_READ_HIS_CTRL_ID1://深水规约读历史数据
				{
					frame_func_reply_NB_ReadHistoryData();
				}
				break;
				default:
				{
					up_deal_stat_ShenShui  = UP_DEAL_S0;
					task_complete_ShenShui = PTL_PACK_FAIL; 
				}
			}
			frame_struct_ShenShui.ack_ctrl = SS_ACK_READ_HIS_CTRL;
		}
		break;
        default:
        {     
			up_deal_stat_ShenShui  = UP_DEAL_S0;
			task_complete_ShenShui = PTL_PACK_FAIL;           
        }
        break;
    }
    return task_complete_ShenShui;
}

static void Frame_ResetDealState_ShenShui(void)
{
	up_deal_stat_ShenShui = UP_DEAL_S0;
}
//深水应答数据组帧
static void Frame_ack_ShenShui(u8* p_send_buf, u16* p_send_len)
{
	STRUCT_FRAME_IES temp_struct;
	
	temp_struct.ack_ctrl = frame_struct_ShenShui.ack_ctrl;
	temp_struct.DI0 = frame_struct_ShenShui.DI0;
	temp_struct.DI1 = frame_struct_ShenShui.DI1;
	temp_struct.sta = frame_struct_ShenShui.sta;
	temp_struct.serial_num0 = frame_struct_ShenShui.serial_num0;
	temp_struct.serial_num1 = frame_struct_ShenShui.serial_num1;

	Frame_ack_IesBase(temp_struct,g_frame_temp_buf_ShenShui, g_frame_temp_len_ShenShui, p_send_buf, p_send_len);
}
/////////////////////////////////////对外接口,解规约////////////////////
u8 crack_frame_BLE(u16 frame_lenth,u8 *frame_buffer)
{
	frame_flag = 0;
	if(SUCCESS_IES == crack_frame_BLE_Static(frame_lenth, frame_buffer))
	{
		frame_flag = 1;
		return  SUCCESS_IES;
	}
	if(SUCCESS_IES == crack_frame_ShenShui(frame_lenth, frame_buffer))
	{
		return  SUCCESS_IES;
	}
	return ERROR_IES;
}

//深水规约处理
u8 up_deal_code_ble(void)
{
	if(frame_flag)
	{
		return up_deal_code_ble_static();
	}
	else
	{
		return up_deal_code_ShenShui();
	}
}

void Frame_ResetDealState_BLE(void)
{
	if(frame_flag)
	{
		Frame_ResetDealState_BLE_Static();
	}
	else
	{
		Frame_ResetDealState_ShenShui();
	}
}
//应答数据组帧
void Frame_ack_BLE(u8* p_send_buf, u16* p_send_len)
{
	if(frame_flag)
	{
		Frame_CreatAck_BLE(p_send_buf, p_send_len);
	}
	else
	{
		Frame_ack_ShenShui(p_send_buf, p_send_len);
	}
}
/************************************************************历史数据存储********************************/
//更新数据包中的当前流量和信息状态
static void Upload_RenewCurrentData(STRU_UPLOAD_FRAME* temp_frame)
{
	MET_STATE temp_state; //状态字
	u8 temp1 = 0;
	Fram_To_Float tmp_float;
	u8* hight_flow; 
	DateTime tempRtcc_time;

	tmp_float.gp22_u32  = Gp30CheckDataApp(2);
	temp_frame->data.CurrentFlow.datas = (u32)(tmp_float.gp22_float*10);//当前累计流量
	temp_frame->data.CurrentFlowForward.datas = temp_frame->data.CurrentFlow.datas;//当前累计正向流量
	tmp_float.gp22_u32 = Gp30CheckDataApp(3);//当前累积逆向流量
	temp_frame->data.CurrentFlowReverse.datas = (u32)(tmp_float.gp22_float*10);
	//获取:日最高流量(4字节),日最高流量持续时间(2字节),日最高流量开始时间(8字节,预留)	
	RtccCheck_Hight_Flow(&hight_flow);			
	for(temp1 = 0; temp1 <14 ;temp1++)
	{
		temp_frame->data.DailyHighestFlowAndTime[temp1] = *(hight_flow+temp1);
	}
	//获取电压值
	temp_frame->data.UploadInfo.metinfo.bat_val.u16_data =HexToBcd16(PowerCheckValueSys());															
	temp_frame->data.UploadInfo.metinfo.bat_threshold_val = Sys_data_object.P1.voltage_low[0]+(Sys_data_object.P1.voltage_low[1]<<8);//欠压阈值3v
	//获取间隔流量:2B(间隔流量)X2(次/h)X24h=96B
	/*
	上报时通过UPLOAD_DATA_READ_HIS获取，0点存储时通过UPLOAD_DATA_STEP_FLOW获取
	*/
	//上报时间
	RtccGetDateTime(&tempRtcc_time);//上报时间
	temp_frame->data.UploadTime[0] = tempRtcc_time.s.second;
	temp_frame->data.UploadTime[1] = tempRtcc_time.s.minute;
	temp_frame->data.UploadTime[2] = tempRtcc_time.s.hour;
	temp_frame->data.UploadTime[3] = tempRtcc_time.s.day;
	temp_frame->data.UploadTime[4] = tempRtcc_time.s.month;
	temp_frame->data.UploadTime[5] = tempRtcc_time.s.year; 
	temp_frame->data.UploadTime[6] = 0x20;
	//状态字
	temp_state = FrameGetByte();
	temp_frame->data.StateBytes[0] = temp_state.stat0;
	temp_frame->data.StateBytes[1] = temp_state.stat1;
	temp_frame->data.StateBytes[2] = temp_state.stat2;
	temp_frame->data.StateBytes[3] = temp_state.stat3;
	temp_frame->data.StateBytes[4] = temp_state.stat4;
	//累计活跃时间
	temp_frame->data.DailyActiveTime.datas = GetEventUploadType();//上报类型
}
static void SS_Store_CircleDataMachine(void)
{
	switch (step_save_supplt)//数据存储
	{
		case SS_STATE_S0://存储消息类型判断
		{
			if (RtccCheckMsgApp(RtccMsg_OtherProtl))
			{
				RtccClearMsgApp(RtccMsg_OtherProtl);
				RtccGetDateTime(&shenshui_rtcc_time);
				if((shenshui_rtcc_time.s.minute==0x00)||(shenshui_rtcc_time.s.minute==0x30))
				{
					FrameSetMsgApp(MsgSS_JianGeStore);//半小时间隔流量存储消息
				}
				if ((shenshui_rtcc_time.s.hour == 0)&&(shenshui_rtcc_time.s.minute==0x00))//冻结时间到，零点
				{
					RtccSetMsgApp(RtccMsg_DataSave);//0点更新冻结数据
					FrameSetMsgApp(MsgSS_HisIndexStore);//0点更新冻结数据指针
				}
			}	
			/**间隔流量和冻结数据存储：先0点存储冻结数据; 然后最后存储指针增加; 最后开始新的一轮间隔流量存储,期间判断写指针的有效性;*/
			if(RtccCheckMsgApp(RtccMsg_DataSave))//0点保存冻结数据
			{
				RtccClearMsgApp(RtccMsg_DataSave);
				FrameSetMsgApp(MsgBLE_AdvChange);//冻结数据时间,更新广播数据
				
				step_save_supplt = SS_STATE_S10;
			}
			else if(FrameCheckMsgApp(MsgSS_HisIndexStore))//0点更新冻结数据指针
			{
				FrameClearMsgApp(MsgSS_HisIndexStore);
				step_save_supplt = SS_STATE_S2;
			}
			else if(FrameCheckMsgApp(MsgSS_JianGeStore)) //半小时间隔流量存储
			{
				FrameClearMsgApp(MsgSS_JianGeStore);
				step_save_supplt = SS_STATE_S20;
			}
			else if(FrameCheckMsgApp(Msg_ClearHisOther))//清表数据
			{
				FrameClearMsgApp(Msg_ClearHisOther);
				step_save_supplt = SS_STATE_S40;
			} 
			break;
		}
		/*0点更新冻结数据*/
		case SS_STATE_S10:
		{
			if(TASK_IDLE == EepIfIdle())
			{
				//(只)更新表计数据和表计状态
				Upload_RenewCurrentData(&store_frame);
			    EepWrite(store_frame.buf, (FRAME_NBIot_HISTORY_READ_ADD+(Sys_data_object.P1.histroy_w*PACK_NUM_GPRS)), CURRENT_DATA_INFO_LEN, &s_eep_complete_BLE);
				step_save_supplt = SS_STATE_S11;
			}
		    break;
		}
		case SS_STATE_S11://保存上报时间 
		{
			if(TASK_IDLE == EepIfIdle())
			{
			    EepWrite(&store_frame.data.UploadTime[0], (FRAME_NBIot_HISTORY_READ_ADD+(Sys_data_object.P1.histroy_w*PACK_NUM_GPRS)+UPLOAD_TIME_ADDR), 7, &s_eep_complete_BLE);
				step_save_supplt = SS_STATE_WAIT;
			}
		    break;
		}
		/*0点更新冻结数据指针*/
		case SS_STATE_S2:
		{
			if(TASK_IDLE == EepIfIdle())
			{			
				Sys_data_object.P1.histroy_w++;
				if(Sys_data_object.P1.histroy_w>=PERIOD_DATA_NUM) 
				{
					Sys_data_object.P1.histroy_w=0; 
				}				
				Sys_data_object.P1.Supplemental_send_flag.datas &=(~(0x0001<<(Sys_data_object.P1.histroy_w)));//清该位置补报标志
				EepWrite(&Sys_data_object.P1.Supplemental_send_flag.datas_map.data0, FRAME_NBIot_BUBAO_FLAG, 6, &s_eep_complete_BLE);
				step_save_supplt = SS_STATE_WAIT;
			}	
			break;					
		}
		/*间隔流量存储*/
		case SS_STATE_S20://半小时间隔流量时间判断:防止首次上电,日期变更
		{
			if(EepIfIdle())
			{		
				if(	(shenshui_rtcc_time.s.year  == store_frame.data.StepFlowStartTime[5])&&
					(shenshui_rtcc_time.s.month == store_frame.data.StepFlowStartTime[4])&&
					(shenshui_rtcc_time.s.day   == store_frame.data.StepFlowStartTime[3]))
				{
					step_save_supplt = SS_STATE_S22;
				}
				else
				{	
					EepRead(FRAME_NBIot_HISTORY_READ_ADD+(Sys_data_object.P1.histroy_w*PACK_NUM_GPRS)+STEP_FLOW_TIME_ADDR, &store_frame.data.StepFlowStartTime[0], 7, &s_eep_complete_BLE);
					step_save_supplt = SS_STATE_S21;
				}
			}
		}
		break;
		case SS_STATE_S21:
		{
			if(EepIfIdle())
			{		
				if(	(shenshui_rtcc_time.s.year  == store_frame.data.StepFlowStartTime[5])&&
					(shenshui_rtcc_time.s.month == store_frame.data.StepFlowStartTime[4])&&
					(shenshui_rtcc_time.s.day   == store_frame.data.StepFlowStartTime[3]))
				{
					step_save_supplt = SS_STATE_S22;
				}
				else//间隔流量无效,进行当前区域初始化
				{
					//获取表计数据和表计状态
					Upload_RenewCurrentData(&store_frame);
					//上报信号参数清除
					store_frame.data.UploadInfo.metinfo.ecl_val =0;
					store_frame.data.UploadInfo.metinfo.RSRP_val =0;
					store_frame.data.UploadInfo.metinfo.single_val =0;
					store_frame.data.UploadInfo.metinfo.snr_val =0;
					//保存间隔流量起始时间
					store_frame.data.StepFlowStartTime[0]= 0x00;
					store_frame.data.StepFlowStartTime[1]= 0x00;
					store_frame.data.StepFlowStartTime[2]= 0x00;
					store_frame.data.StepFlowStartTime[3]= shenshui_rtcc_time.s.day;
					store_frame.data.StepFlowStartTime[4]= shenshui_rtcc_time.s.month;
					store_frame.data.StepFlowStartTime[5]= shenshui_rtcc_time.s.year;        
					store_frame.data.StepFlowStartTime[6]= 0x20; 
					//间隔流量清除:2B(间隔流量)X2(次/h)X24h=96B
					for(int i = 0; i <96 ;i++)//间隔流量清除
					{
						store_frame.data.StepFlow[i] = 0;
					}
					if(Sys_data_object.P1.histroy_w>=PERIOD_DATA_NUM) 
					{
						Sys_data_object.P1.histroy_w=0; 
					}
					EepWrite(store_frame.buf, (FRAME_NBIot_HISTORY_READ_ADD+(Sys_data_object.P1.histroy_w*PACK_NUM_GPRS)), PACK_NUM_GPRS, &s_eep_complete_BLE);
				}
			}
		}
		break;
		case SS_STATE_S22://存储某半点间隔流量
		{
			if(EepIfIdle())
			{		
				u16 temp_step_flow_addr=0;
				//计算间隔流量
				new_jiange_total_flow.gp22_u32 = Gp30CheckDataApp(2);
				jiange_data.datas = (u16)((new_jiange_total_flow.gp22_float - old_jiange_total_flow.gp22_float)*10);
				old_jiange_total_flow.gp22_u32 = new_jiange_total_flow.gp22_u32;
			    //计算本时刻间隔流量存储位置
				temp_step_flow_addr = FRAME_NBIot_HISTORY_READ_ADD+(Sys_data_object.P1.histroy_w*PACK_NUM_GPRS)+STEP_FLOW_START_ADDR + 
				                      BCD2HEX(shenshui_rtcc_time.s.hour)*4 + (BCD2HEX(shenshui_rtcc_time.s.minute)/30)*2;
				EepWrite(&jiange_data.datas_map.data0, temp_step_flow_addr, 2, &s_eep_complete_BLE);
				step_save_supplt = SS_STATE_WAIT;
				//RtccAdjustDateTime(1,1800-10);//往后校时半小时//debug-----------------
			}
		}
		break;
		/*上报前更新并保存要读取的上报数据*/
		/*清表数据初始化读写指针*/
		case SS_STATE_S40:
		{
			if(TASK_IDLE == EepIfIdle())
			{			
				for(int i=0;i<7;i++)
				{
					store_frame.data.StepFlowStartTime[i]= 0x00;
				}
				Sys_data_object.P1.histroy_w = 0;
				Sys_data_object.P1.histroy_r = 0;
				Sys_data_object.P1.Supplemental_send_flag.datas = 0;//补报也清0		
				EepWrite(&Sys_data_object.P1.Supplemental_send_flag.datas_map.data0, FRAME_NBIot_BUBAO_FLAG, 6, &s_eep_complete_BLE);
				step_save_supplt = SS_STATE_WAIT;
			}	
			break;					
		}
		case SS_STATE_WAIT:
		{
            if(TASK_IDLE == EepIfIdle())
            {
                 step_save_supplt = SS_STATE_S0;
            }
            break;
		}
        default:
        {
            break;		
        }			
    }
}

extern u8 sys_reverse_flow_state;
UNION_4U8TOU32 getBleWetState(void)
{
	UNION_4U8TOU32 bel_state;
	u16 tmp_stat = Gp30CheckErrDataApp();
	bel_state.datas=0;
    if(tmp_stat & 0x0001)//当前流量>Q4或者<Q1
    {
		bel_state.datas_map.data0 |= 0x10;
    }
    if(tmp_stat & 0x0002)//水温超出温度等级范围
    {
		bel_state.datas_map.data2 |= 0x02;
    }
    //if(tmp_stat & 0x0004) //倒转
	if(sys_reverse_flow_state)
    {
        bel_state.datas_map.data0 |= 0x08;
    }
    if(tmp_stat & 0x0008)//管道无水
    {
        bel_state.datas_map.data2 |= 0x04;
    }
	if(tmp_stat&0x0010)//GPXX异常
    {
		bel_state.datas_map.data0 |= 0x02;
    }
    if(tmp_stat&0x0020)//超低流量报警
    {
        bel_state.datas_map.data0 |= 0x20;
    }
    if(tmp_stat&0x0040)//换能器老化,低振幅
    {
        bel_state.datas_map.data0 |= 0x01;
    }
    if(tmp_stat&0x0080)//GP22通信故障
    {
		bel_state.datas_map.data0 |= 0x04;
    }
	if (1 == RtccIsError())//RTCC设置时间异常
    {
        bel_state.datas_map.data0 |= 0x40;
    }
	if (10 == PowerCheckStatusSys())//电池欠压
    {
        bel_state.datas_map.data0 |= 0x80;
    }
    if(TRUE == CheckTransducerErrorMsg())//持续用水报警(换能器冻坏)
    {
        bel_state.datas_map.data2 |= 0x01;  
    }
	if(TRUE == CheckDiftofCalibrationFlag())//零流量校准开关标志
	{
		bel_state.datas_map.data2 |= 0x08;
	}
	#if defined(VALVE)
	//普通开1;应急开2;普通关3;应急关4;权限关5;阀门异常7
	tmp_stat = ValveGetState();
	if(VALVE_STATE_OPEN == tmp_stat)
	{
		bel_state.datas_map.data1 |= 0x01;
	}
	else if(VALVE_STATE_OPEN_EMERGENCY == tmp_stat)
	{
		bel_state.datas_map.data1 |= 0x02;
	}
	else if(VALVE_STATE_CLOSE == tmp_stat)
	{
		bel_state.datas_map.data1 |= 0x03;
	}
	else if(VALVE_STATE_CLOSE_EMERGENCY == tmp_stat)
	{
		bel_state.datas_map.data1 |= 0x04;
	}
	else if(VALVE_STATE_CLOSE_LOCK == tmp_stat)//权限关阀状态报给集中器为应急关阀
	{
		//bel_state.datas_map.data1 |= 0x05;
		bel_state.datas_map.data1 |= 0x04;
	}
	/*else */if(Sys_data_object.P1.ies_valve_paras.valve_err)
    {
        bel_state.datas_map.data1 |= 0x07;
    }
	#endif
	//电池电压
	bel_state.datas_map.data3 |= (PowerCheckValueSys()/100)<<4;
	bel_state.datas_map.data3 |= ((PowerCheckValueSys()/10)%10);
	//表计类型
	bel_state.datas_map.data3 |= 0x80;
	return bel_state;
}
/*******************************************************************************
 * @fun_name:NB_SS_Control_GetPara
 * @brief   :    
 * @param[in] :读取上报控制相关参数
 * @param[out]: None
 * @retval    : None
 * @other     :
 ******************************************************************************/
u8 NB_SS_Control_GetPara(NB_SS_ControlParaTypeDef paraType)
{
	 switch(paraType)
	{
	    case NB_HistroyReadIndex://历史数据的读指针
		{
			return Sys_data_object.P1.histroy_w;
		}
		case NB_UploadFailTimes://显示蓝牙是否故障
		{
			if(BleGetPowerState()==BlePowerWrong)
			{
				return 1;//蓝牙故障
			}
			else
			{
				return 0;
			}
		}
		default:
			break;
	}
	return 0;
}
/*******************************************************************************
 * @fun_name:NB_SS_Control_SetPara
 * @param[in] :设置上报控制相关参数
 ******************************************************************************/
void NB_SS_Control_SetPara(NB_SS_ControlParaTypeDef paraType, u8 data)
{
   
}


//规约数据存储部分初始化
void DataStoreInit(void)
{
	Quanzhou_Store_InitApp();
	old_jiange_total_flow.gp22_u32  = Gp30CheckDataApp(GP30_APP_TOTAL_FLOW);//间隔流量计算初始化
}
//规约数据存储状态机
void DataStoreMachine(void)
{
	SS_Store_CircleDataMachine();//周期数据存储
	Quanzhou_Store_Machine();//冻结数据存储
}
//规约数据存储休眠判断
u8 DataStoreIfIdle(void)
{
    if((step_save_supplt == SS_STATE_S0)&&(QuanzhouStore_IfSleep()==TRUE))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

#endif


