#include "sys_config.h"

#if PRODUCT_JS
#include "sys_processor.h"

#include "UWater_eeprom_driver.h"
#include "UWater_timer1uS_driver.h"
#include "UWater_DataTools_App.h"
#include "UWater_JX_Store_App.h"
#include "UWater_frame_func_ReplyNB.h"
#include "UWater_frame_func_ReplyJiangShui.h"

static u8 s_eep_complete_JiangShui=0;
static u8 task_complete_JiangShui = PTL_PACK_BUSY;
static u8 g_frame_temp_buf_JiangShui[UP_BUF_SIZE];	//数据部分缓冲区
static u16 g_frame_temp_len_JiangShui=0;

static STRUCT_FRAME_IES frame_struct_JiangShui; //规约信息 
static u8 *new_message_data_rev_JiangShui; 
static u8 up_deal_stat_JiangShui = UP_DEAL_S0;//规约处理状态机
/*******主动上传数据相关变量*****************************************/
static u16 upload_serial_num_JiangShui=0;
static STRUCT_FRAME_IES upload_struct_JiangShui; //规约信息 
static u8 upload_frame_stat_JiangShui=0; //主动上报组帧状态
static u8 upload_task_complete_JiangShui = PTL_PACK_FAIL;  	
static u8 temp_format_error;//上报格式异常标志
static u8 jx_upload_fail_times=0;

//江西规约上报缓存
static u8 upload_temp_buf_JiangShui[PACK_NUM_GPRS_TOTAL];
static u16 upload_temp_len_JiangShui=0;//主动上报数据长度	
static u16 jx_upload_record_cnts = 0;//需要上报的记录条数
static u8  jx_upload_total_packs=0;//本次需要上报的总包数
static u8  jx_upload_cur_pack=0;//本次需要上报的当前包号
static u16 s_upload_connect_time=0;//联网时间
//上传应答处理
static void frame_func_reply_NB_AckUpload(void)
{
	 g_frame_temp_len_JiangShui =0;
	u8 sernum0 = upload_serial_num_JiangShui&0xFF;
	u8 sernum1 = (upload_serial_num_JiangShui>>8)&0xFF;
	if(*(new_message_data_rev_JiangShui + 6) == 1)//上报数据格式异常
	{
		if(frame_struct_JiangShui.serial_num0 == sernum0)
		{
			if(frame_struct_JiangShui.serial_num1 == sernum1)
			{
				FrameSetMsgApp(MsgNbUplaod_AckOk);//江西水务产线生产测试返回格式异常,应判断过
				NB_SS_Control_SetPara(NB_SS_FormatError, 1);//置起上报格式异常标志
			}
		}
	}
	else
	{
		if(frame_struct_JiangShui.serial_num0 == sernum0)
		{
			if(frame_struct_JiangShui.serial_num1 == sernum1)
			{
				FrameSetMsgApp(MsgNbUplaod_AckOk);
			}
		}
		NB_SS_Control_SetPara(NB_SS_FormatError, 0);//清除上报格式异常标志
	}
	task_complete_JiangShui = PTL_PACK_FAIL;//这是上报应答帧,返回错误,表计不应答
}

//登录帧------------------------判断的应答控制字，返回PTL_PACK_FAIL
static void frame_func_reply_NB_AckLogin(void)
{			
	FrameSetMsgApp(MsgNbUplaod_AckLoginOk);
}
//清除失败次数
static void frame_func_s3_NB_ClearFailTimes(void)
{   
	static u8 temp_clear_buf[4];
	if(TASK_IDLE == EepIfIdle())
	{
		g_frame_temp_len_JiangShui = 0;
		NB_SS_Control_SetPara(NB_SS_FormatError, 0);
		NB_SS_Control_SetPara(NB_UploadFailTimes, 0);
		temp_clear_buf[0]=0;
		temp_clear_buf[1]=0;
		temp_clear_buf[2]=0;
		temp_clear_buf[3]=0;
		EepWrite(temp_clear_buf, FRAME_NBIot_BUBAO_FLAG, 4, &s_eep_complete_JiangShui);
		task_complete_JiangShui = PTL_PACK_SUCCESS;
	}
}

//江西水务:设置密集存储间隔
static void frame_func_s3_NB_SetStorageFrequency(void)
{   
	switch(up_deal_stat_JiangShui)
	{
		case UP_DEAL_S0:
		{
			if(TASK_IDLE == EepIfIdle())//存储数据到EEPROM
			{
				g_frame_temp_len_JiangShui = 0;
				if(*new_message_data_rev_JiangShui> 0x5A) //最大采样间隔90min
				{
					task_complete_JiangShui = PTL_PACK_FAIL;
					return;
				}
				Sys_data_object.P1.storage_frequency = *(new_message_data_rev_JiangShui);
				EepWrite(&Sys_data_object.P1.storage_frequency, EEP_FRAME_STORAGE_FREQUENCY, 1, &s_eep_complete_JiangShui);
				Frame_Para_Init();	
				task_complete_JiangShui = PTL_PACK_SUCCESS;       
			}
		}
		break;
		default:
		{
		    up_deal_stat_JiangShui  = UP_DEAL_S0;
            task_complete_JiangShui = PTL_PACK_FAIL;
		}
		break;
	}
}


//江西水务:设置采样频率  
static void frame_func_s3_NB_SetSamplingFrequecy(void)
{   
	if(TASK_IDLE == EepIfIdle())//存储数据到EEPROM
	{
		g_frame_temp_len_JiangShui = 0;
		Sys_data_object.P1.jx_sampling_frequency[0] = *(new_message_data_rev_JiangShui + 0);
		Sys_data_object.P1.jx_sampling_frequency[1] = *(new_message_data_rev_JiangShui + 1);
		EepWrite(&Sys_data_object.P1.jx_sampling_frequency[0], EEP_FRAME_JX_SAMPLING_FREQUENCY_ADDR, 2, &s_eep_complete_JiangShui);
		Frame_Para_Init();	
		task_complete_JiangShui = PTL_PACK_SUCCESS;       
	}
}

//江西水务:设置NB模组为PSM或断电模式
static void frame_func_s3_NB_SetPsmOrPwDown(void)
{   
	if(TASK_IDLE == EepIfIdle())
	{
		g_frame_temp_len_JiangShui = 0;
		Sys_data_object.P1.jx_psm_pwdown = *new_message_data_rev_JiangShui;
		EepWrite(&Sys_data_object.P1.jx_psm_pwdown, EEP_FRAME_JX_PSM_PWDOWN_ADDR, 1, &s_eep_complete_JiangShui);
		Frame_Para_Init();	
		task_complete_JiangShui = PTL_PACK_SUCCESS;                
	}
}

/************************************************************************************************************/
//解规约
u8 crack_frame_JiangShui(u16 frame_lenth,u8 *frame_buffer)
{
	u8 temp_res = crack_frame_IES_Base(frame_lenth, frame_buffer, &frame_struct_JiangShui);
	if(temp_res == SUCCESS_IES)
	{
		frame_struct_JiangShui.sta &= 0xFD; //表示非主动上传（bit1为1时表示主动上传，0表示应答）
		frame_struct_JiangShui.DI0 = *(frame_buffer + frame_struct_JiangShui.head_site + 12);
		frame_struct_JiangShui.DI1 = *(frame_buffer + frame_struct_JiangShui.head_site + 13);
		frame_struct_JiangShui.serial_num0 = *(frame_buffer + frame_struct_JiangShui.head_site + 14);	
		frame_struct_JiangShui.serial_num1 = *(frame_buffer + frame_struct_JiangShui.head_site + 15); 		
		new_message_data_rev_JiangShui = frame_buffer + frame_struct_JiangShui.head_site + 16;								
		frame_lenth = 0;
		return  SUCCESS_IES;
	}
	return ERROR_IES;
}

//江水规约处理:扩展积成规约
u8 up_deal_code_JiangShui(void)
{
    task_complete_JiangShui = PTL_PACK_BUSY;
    switch(frame_struct_JiangShui.ctrl)
    {
		case SS_ACK_UPLOAD_CTRL:
		{
			frame_func_reply_NB_AckUpload();
		}
		break;

		case SS_ACK_SIGN_IN_CTRL:
		{
			frame_func_reply_NB_AckLogin();
		}
		break;
		
		case SS_CLEAR_FAIL_TIMES_CTRL:
		{
			frame_func_s3_NB_ClearFailTimes();;
			frame_struct_JiangShui.ack_ctrl = SS_ACK_CLEAR_FAIL_TIMES_CTRL;
		}
		break;
	
		case FM_SET_MJJI_SPACE_TIME_CTRL:
		{
			frame_func_s3_NB_SetStorageFrequency();;
			frame_struct_JiangShui.ack_ctrl = FM_SET_MJJI_SPACE_TIME_REPLY_CTRL;
		}
		break;
		case FM_SET_SAMPLING_FREQUENCY_CTRL:
		{
			frame_func_s3_NB_SetSamplingFrequecy();;
			frame_struct_JiangShui.ack_ctrl = FM_SET_SAMPLING_FREQUENCY_REPLY_CTRL;
		}
		break;
		case FM_SET_PSM_PWDOWN_CTRL:
		{
			frame_func_s3_NB_SetPsmOrPwDown();;
			frame_struct_JiangShui.ack_ctrl = FM_SET_PSM_PWDOWN_REPLY_CTRL;
		}
		break;
        default:
        {     
			up_deal_stat_JiangShui  = UP_DEAL_S0;
			task_complete_JiangShui = PTL_PACK_FAIL;           
        }
        break;
    }
    return task_complete_JiangShui;
}

void Frame_ResetDealState_JiangShui(void)
{
	up_deal_stat_JiangShui = UP_DEAL_S0;//基线扩展规约处理状态复位
}
//应答数据组帧
void Frame_ack_JiangShui(u8* p_send_buf, u16* p_send_len)
{
	STRUCT_FRAME_IES temp_struct;
	
	temp_struct.ack_ctrl = frame_struct_JiangShui.ack_ctrl;
	temp_struct.DI0 = frame_struct_JiangShui.DI0;
	temp_struct.DI1 = frame_struct_JiangShui.DI1;
	temp_struct.sta = frame_struct_JiangShui.sta;
	temp_struct.serial_num0 = frame_struct_JiangShui.serial_num0;
	temp_struct.serial_num1 = frame_struct_JiangShui.serial_num1;

	Frame_ack_IesBase(temp_struct,g_frame_temp_buf_JiangShui, g_frame_temp_len_JiangShui, p_send_buf, p_send_len);
}
/****************************************************************以下主动上报数据的处理*********************************************/
static u8 upload_frame_retry_times=0;
//static u8 temp_upload_step=0;

void GetUploadDataResetState_JX(void)
{
	upload_frame_stat_JiangShui =UP_DEAL_S0;
	upload_task_complete_JiangShui = PTL_PACK_BUSY;
}
u8 GetUploadDataCheckIdle_JX(void)
{
	if(UP_DEAL_S0 == upload_frame_stat_JiangShui)
    {
        return TASK_IDLE;
    }
    else
    {
        return TASK_BUSY;
    }
}
u8 GetUploadDataCheckTask_JX(void)
{
	return upload_task_complete_JiangShui;
}

/***********************************************
获取联网时间
***********************************************/
u16 GetUploadConnectTime_JX(u8 type)
{
	if(type == 0)
	{
		return s_upload_connect_time;
	}
	else
	{
		return (Get100msTimer(TIMER_100MS_WAIT_SLEEP_GPRS)/1000000);
	}
}

void GetUploadDataMachine_JX(u8 data_step, u8* p_send_buf, u16* p_send_len)
{
	switch(upload_frame_stat_JiangShui)
	{
		case UP_DEAL_S0:
		{
			if(data_step == UPLOAD_FRAME_REQUEST_NEW)//请求新数据包
			{
				s_upload_connect_time = Get100msTimer(TIMER_100MS_WAIT_SLEEP_GPRS)/1000000;
				upload_frame_retry_times = 0;
				upload_frame_stat_JiangShui = UP_DEAL_S1;
			}
			else if(data_step == UPLOAD_FRAME_UPLOAD_OK)//发送成功
			{
				jx_upload_fail_times = 0;
				upload_frame_retry_times = 0;
				SystemClearUploadAgain();//重传清0
				upload_frame_stat_JiangShui = UP_DEAL_S10;//获取下一包数据
			}
			else if(data_step == UPLOAD_FRAME_UPLOAD_RETRY)//请求重新发送
			{
				upload_frame_stat_JiangShui = UP_DEAL_S21;
			}
			else if(data_step == UPLOAD_FRAME_ONLINE_FAIL) //联网失败
			{
				  if(UPLOAD_TYPE_FIX_TIME == GetEventUploadType()||
					(UPLOAD_TYPE_RETRY_AGAIN == GetEventUploadType()))//定时上传
				{
					SystemAddUploadAgain();//重传增加
				}
				if((Sys_data_object.P1.func_cfg_bytes[0]>0)&&NbiotIfOnline())//厂区上报时间,如果有信号值,则不报故障
				{
					NB_SS_Control_SetPara(NB_UploadFailTimes, 0);
				}
				else
				{
					jx_upload_fail_times++;//失败次数增加
				}
				upload_task_complete_JiangShui = PTL_PACK_FAIL;
				upload_frame_stat_JiangShui = UP_DEAL_S0;
			}
			else 
			{
				upload_task_complete_JiangShui = PTL_PACK_FAIL;
				upload_frame_stat_JiangShui = UP_DEAL_S0;
			}
		}
		break;
		case UP_DEAL_S1://计算总上报包数,获取第一包数据
		{
			if(Copy_R_W_Count() == SUCCESS)//获取冻结的存储读、写指针
			{
				jx_upload_record_cnts = get_com_rx_num_copy(); //获取需要上传的记录条数
				if(jx_upload_record_cnts >0)
				{
					jx_upload_total_packs = (jx_upload_record_cnts/JX_ONE_PACKET_COUNTS);//计算需要上传的总包数,45条记录一包
					if(jx_upload_record_cnts % JX_ONE_PACKET_COUNTS)
					{
						jx_upload_total_packs += 1;
					}
					if(jx_upload_total_packs > MAX_PACKS_TOUPLOAD)//最大65包
					{
						jx_upload_total_packs = MAX_PACKS_TOUPLOAD;
					}                       
				}
				else//如果无数据存储，则获取当前流量数据上传
				{
					jx_upload_total_packs = 1;//总包数
				}
				jx_upload_cur_pack = 1;//当前包号从1开始
				upload_frame_stat_JiangShui = UP_DEAL_S2;
			}  
		}
		break;
		case UP_DEAL_S10://更新已上报指针,获取下一包数据
		{
			if(Renew_Rcount() == SUCCESS)//保存读指针
			 {
				jx_upload_cur_pack += 1;//上传数据包加1
				if(jx_upload_cur_pack > jx_upload_total_packs)//上传完毕
				{
					upload_task_complete_JiangShui = PTL_PACK_FAIL;//失败
					upload_frame_stat_JiangShui = UP_DEAL_S0;
				}
				else
				{
					jx_upload_record_cnts = get_com_rx_num_copy();//获取需要上传的记录条数
					upload_frame_stat_JiangShui = UP_DEAL_S2;
				}
			 } 
		}
		break;
		case UP_DEAL_S2://获取上报数据并组帧
		{
			if(get_com_rx_data() == SUCCESS)//获取数据
            {
                NB_JX_Frame_Upload_Data(upload_temp_buf_JiangShui, &upload_temp_len_JiangShui, jx_upload_total_packs, jx_upload_cur_pack);//组数据部分
				
				upload_struct_JiangShui.ack_ctrl = SS_UPLOAD_CTRL;
				upload_struct_JiangShui.DI0 = SS_UPLOAD_CTRL_ID0;
				upload_struct_JiangShui.DI1 = SS_UPLOAD_CTRL_ID1;
				upload_struct_JiangShui.sta = 0x03;//加密主动上传
				upload_serial_num_JiangShui++;
				upload_struct_JiangShui.serial_num0 = upload_serial_num_JiangShui&0xFF;
				upload_struct_JiangShui.serial_num1 = (upload_serial_num_JiangShui>>8)&0xFF;
				
				Frame_ack_IesBase(upload_struct_JiangShui, upload_temp_buf_JiangShui, upload_temp_len_JiangShui, p_send_buf, p_send_len);
	
				upload_task_complete_JiangShui = PTL_PACK_SUCCESS;// 成功
				upload_frame_stat_JiangShui = UP_DEAL_S0;
            }
		}
		break;
		
		case UP_DEAL_S21://重试
		{
			if(upload_frame_retry_times < 1) //改为重发1次
			{
				upload_frame_retry_times++;
				upload_frame_stat_JiangShui = UP_DEAL_S2;
			} 
			else//重新发送失败3次的处理
			{
				if((UPLOAD_TYPE_FIX_TIME == GetEventUploadType())||    //定时上传
				   (UPLOAD_TYPE_RETRY_AGAIN == GetEventUploadType()))  //重传
				{
					SystemAddUploadAgain();//重传增加
				}
				if((Sys_data_object.P1.func_cfg_bytes[0]>0)&&NbiotIfOnline())//厂区上报时间,如果有信号值,则不报故障
				{
					NB_SS_Control_SetPara(NB_UploadFailTimes, 0);
				}
				else
				{
					jx_upload_fail_times++;//失败次数增加
				}
				upload_task_complete_JiangShui = PTL_PACK_FAIL;
				upload_frame_stat_JiangShui = UP_DEAL_S0;
			}
		}
		break;

		default:
		{
			upload_task_complete_JiangShui = PTL_PACK_FAIL;
			upload_frame_stat_JiangShui = UP_DEAL_S0;
		}
		break;
	}
}
/*******************************************************************************
 * @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_UploadFailTimes://需要上报包数
//		{
//			u8 temp_fail_times=JiangXiStore_UploadPacks();
//			return temp_fail_times;
//		}
		case NB_UploadFailTimes://失败次数
		{
			u8 temp_fail_times=0;
			if(Sys_data_object.P3.ProductUpoadFailFlag)//串口上报失败
			{
				temp_fail_times = Sys_data_object.P3.ProductUpoadFailFlag;
			}
			else
			{
				temp_fail_times = jx_upload_fail_times;
			}
			return temp_fail_times;
		}
		case NB_SS_FormatError://上报数据格式错误
		{
			return temp_format_error;
		}
		default:
			break;
	}
	return 0;
}
/*******************************************************************************
 * @fun_name:NB_SS_Control_SetPara
 * @brief   :    
 * @param[in] :设置上报控制相关参数
 * @param[out]: None
 * @retval    : None
 * @other     :
 ******************************************************************************/
void NB_SS_Control_SetPara(NB_SS_ControlParaTypeDef paraType, u8 data)
{
    switch(paraType)
	{
		case NB_SS_FormatError://上报数据格式错误
		{
			temp_format_error = data;
			break;
		}
		case NB_UploadFailTimes://失败次数
		{
			SystemClearUploadAgain();
			Sys_data_object.P3.ProductUpoadFailFlag = 0;
			jx_upload_fail_times = 0;
			break;
		}
		default:
			break;
	}
}

//规约数据存储部分初始化
void DataStoreInit(void)
{
	JiangXiStore_InitApp();
}
//规约数据存储状态机
void DataStoreMachine(void)
{
	JiangXiStore_Machine();
}
//规约数据存储休眠判断
u8 DataStoreIfIdle(void)
{
    return JiangXiStore_IfSleep();
}

#endif

