#include "H/Function_Init.H"
#include "IAP_Lib/IAP_Option_EW.h"

#if (Test == 9)

unsigned char code* POINT;	     //该指针指向0x0000

#define IAP_UniqueID 0x01
#define IAP_EEPROM 0x02

unsigned char IAP_Read(unsigned long IAP_IapAddr, unsigned char area);

unsigned char  CheckSaveData(uint32_t test_data)
{
	//实现数据有效性检查逻辑
	//假设数据合法返回SET，否则返回0
	// 示例中假设数据总是合法
	
	unsigned char bitstatus = 0;
	if(test_data == 0xAA)
	{
		bitstatus = 1;
	}
	else
	{
		bitstatus = 0;
	}
	return bitstatus; 
}

void IAP_Test(void)
{
  unsigned char IapReadData;				//定义储存读出数据的变量
	unsigned char Key_Press=0,Iap_Enflag=0;
	unsigned char i = 0;
	P1CON &= ~0x20;
	P1PH  |= 0x20;
	
	if(P10 == 0)      //IAP操作触发条件有效
	{
		for(i=0;i<100;i++)
		{
			WDTCON |=0x10;
		}
		
		if((P10 == 0) && (Key_Press == 0))
		{
			Key_Press = 1;
			Iap_Enflag = 1;   //按下按键，允许IAP写入，作为解锁的第一个必要条件
		}
	}
	else
	{
		Key_Press = 0;
	}
	
		if(Iap_Enflag == 1)
		{
			IapWriteFlag = IAP_SOFTKEY1;  //允许写入IAP，置第一重安全锁解锁(注意:解锁IAP和操作IAP不能在同一流程分支)
		}
		if(CheckSaveData(0xAA) == 1)
		{
			IapWriteFlag |= IAP_SOFTKEY2;  //待写入数据合法性，作为解锁的第二个必要条件，置第二重安全锁解锁
		}			

	if(Iap_Enflag == 1)  //IAP操作触发条件有效，操作IAP
	{		
		EEPROM_WriteTime_Config(EEPROM_WriteTime_2ms);   //EEPROM写入时间设为2ms
		
		IAP_EEPROMProgramByteOption(0xFF, 0x00);			//往EEPROM 0xFF地址写入0x00
		IAP_EEPROMProgramByteOption(0xFF, 0xAA);			//往EEPROM 0xFF地址写入0xAA

		IapReadData = IAP_Read(0xFF, IAP_EEPROM);		//读取EEPROM 0xFF地址数据
	}	
	IapWriteFlag = IAP_DISABLE;  //加锁IAP
	
  while(1)
  {
    if(IapReadData == 0xAA)
    {
			WDTCON |=0x10;
      P22 = ~P22;
    }
		else
		{
			P23 = ~P23;
		}
  }
}

/**************************************************
*函数名称：unsigned char IAP_Read(unsigned long Add,unsigned char ADER)
*函数功能：单Byte读取
*入口参数：Add ：需要读取的地址(0X00~0X7FFF（FLASH物理地址）
*         Iapad：读取的数据
*出口参数：void
**************************************************/
unsigned char IAP_Read(unsigned long Add, unsigned char Iapade)
{
  unsigned char IAP_IapData;
  //保存IAPADE、EA
  unsigned char tempADER = IAPADE;
  unsigned char tempEA = EA;

  unsigned char code* point = 0;

  EA = 0;//关闭中断

  IAPADE = Iapade;

  IAP_IapData = *(point + Add);

  //操作结束恢复IAPADE、EA，避免MOVC位置出错
  IAPADE = tempADER;
  EA = tempEA;

  return IAP_IapData;

}

#endif


