/*********************************************************************
*Project:MG82F6B08_001_104-DEMO
*			MG82F6B08_001_104 SOP16_V11 EV Board (TH221A)
*			CpuCLK=8MHz, SysCLK=8MHz
*Description:
*			Read the 16-byte UID and use it to encrypt the program
*           Use U1/U2 offline burning SN, the program to determine whether the SN is in the correct range
*Note:
*
*Creat time:
*Modify:
*    
*********************************************************************/
#define _MAIN_C

#include <Intrins.h>
#include <Absacc.h>

#include <Stdio.h>  // for printf

#include ".\include\REG_MG82F6B08_001_104.H"
#include ".\include\Type.h"
#include ".\include\API_Macro_MG82F6B08_001_104.H"
#include ".\include\API_Uart_BRGRL_MG82F6B08_001_104.H"


/*************************************************
*Set SysClk (MAX.24MHz)
*Selection: 
*	8000000,16000000
*	11059200,22118400
*************************************************/
#define MCU_SYSCLK		8000000
/*************************************************/
/*************************************************
*Set CpuClk (MAX.16MHz)
*	1) CpuCLK=SysCLK
*	2) CpuClk=SysClk/2
*************************************************/
#define MCU_CPUCLK		(MCU_SYSCLK)
//#define MCU_CPUCLK		(MCU_SYSCLK/2)

#define TIMER_1T_1ms_TH	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(1000000)))) /256) 			
#define TIMER_1T_1ms_TL	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(1000000)))) %256)

#define TIMER_12T_1ms_TH	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(12000000)))) /256) 			
#define TIMER_12T_1ms_TL	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(12000000)))) %256)

#define LED_R		P32
#define LED_G_0		P33
#define LED_G_1		P46

#define ISP_ADDRESS    0x1A00	 //ISP start address 
#define IAP_ADDRESS    0x1600	 //IAP start address  

#define UID_ENCRYPT_BUF_ADDRESS	0x1000
#define DEVICE_SN_BUF_ADDRESS	0x0200

#define ERR_CNT_MAX		4		// Error, Try again times

code u8 UIDEncryptBuf[16] _at_ UID_ENCRYPT_BUF_ADDRESS;

// Burning S/N by U1/U2. The starting address is set to the address defined by the variable below. (ex. 0x0200)
// If the S/N is not in the correct range, the burning file may be stolen.
code u8 DeviceSn[16] _at_ DEVICE_SN_BUF_ADDRESS;

// The S/N is 12 bytes character + 4 bytes number 
// 
code u8 DeviceSnString[]="Megawin--MCU";

/*************************************************
*Function: char putchar (char c)   
*Description: send for printf
*Input:     char c
*Output:     
*************************************************/
char putchar (char c)   
{      
	bit bES;
	bES=ES0;
    ES0=0;        
    S0BUF = c;        
    while(TI0==0);        
    TI0=0;        
    ES0=bES;        
    return 0;
}

/*************************************************
*Function:     void DelayXus(u8 xUs)
*Description:  delay,unit:us
*Input:     u8 Us -> *1us  (1~255)
*Output:     
*************************************************/
void DelayXus(u8 xUs)
{
	while(xUs!=0)
	{
#if (MCU_CPUCLK>=11059200)
		_nop_();
#endif
#if (MCU_CPUCLK>=14745600)
		_nop_();
		_nop_();
		_nop_();
		_nop_();
#endif
#if (MCU_CPUCLK>=16000000)
		_nop_();
#endif

#if (MCU_CPUCLK>=22118400)
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
#endif
#if (MCU_CPUCLK>=24000000)
		_nop_();
		_nop_();
#endif		
#if (MCU_CPUCLK>=29491200)
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
#endif
#if (MCU_CPUCLK>=32000000)
		_nop_();
		_nop_();
#endif

		xUs--;
	}
}

/*************************************************
*Function:     void DelayXms(u16 xMs)
*Description:delay,unit:ms
*Input:     u16 xMs -> *1ms  (1~65535)
*Output:     
*************************************************/
void DelayXms(u16 xMs)
{
	while(xMs!=0)
	{
		CLRWDT();
		DelayXus(200);
		DelayXus(200);
		DelayXus(200);
		DelayXus(200);
		DelayXus(200);
		xMs--;
		
	}
}

/***********************************************************************************
*Function:   void InitUart0_S0BRG(void)
*Description:   Initialize Uart0, The source of baud rate was S0BRG
*Input:   
*Output:     
*************************************************************************************/
void InitUart0_S0BRG(void)
{
	UART0_SetAccess_S0CR1();			// Set SFR 0xB9 address to access S0CR1
	UART0_SetMode8bitUARTVar();			// 8-bit, Variable B.R.
	UART0_EnReception();				// Enable reception
	UART0_SetBRGFromS0BRG();			// B.R. source: S0BRG
	UART0_SetS0BRGBaudRateX2();			// S0BRG x2
	UART0_SetS0BRGSelSYSCLK();			// S0BRG clock source:SYSCLK
	UART0_SetRxTxP30P31();
	// Sets B.R. value
	UART0_SetS0BRGValue(S0BRG_BRGRL_9600_2X_8000000_1T);

	UART0_EnS0BRG();					// Enable S0BRG
}

/***********************************************************************************
*Function:   void InitPort(void)
*Description:   Initialize IO Port
*Input:   
*Output:     
*************************************************************************************/
void InitPort(void)
{
	PORT_SetP3QuasiBi(BIT0|BIT1|BIT2|BIT3);		// Set P30,P31,P32,P33 as Quasi-Bidirectional,for RXD/TXD,LED
	PORT_SetP4OpenDrainPu(BIT6);				// Set P46 as Open-Drain with pull-up resistor,for LED
}

/***********************************************************************************
*Function:   void InitClock(void)
*Description:   Initialize clock	
*Input:   
*Output:     
*************************************************************************************/
void InitClock(void)
{
#if (MCU_SYSCLK==8000000)
	// Default: IHRCO=16MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK/2
#endif

#if (MCU_SYSCLK==11059200)
	// IHRCO=22.12MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK/2
	CLK_SelIHRCO_22118400Hz();
#endif
	
#if (MCU_SYSCLK==16000000)
	// IHRCO=16MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK
	CLK_SetCKCON3(WDTCS_ILRCO|FWKP_NORMAL_120uS|MCKDO_MCK_DIV_1);
#endif

#if (MCU_SYSCLK==22118400)
	// IHRCO=22.12MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK
	CLK_SelIHRCO_22118400Hz();
	CLK_SetCKCON3(WDTCS_ILRCO|FWKP_NORMAL_120uS|MCKDO_MCK_DIV_1);
#endif
	

#if (MCU_CPUCLK==MCU_SYSCLK)
	CLK_SetCpuclk_Sysclk();
#else
	CLK_SetCpuclk_SysclkDiv2();
#endif

	// P45 ouput MCK/4
	//CLK_P45OC_MCKDiv4();
}

/***********************************************************************************
*Function:   u8 IAP_ReadPPage(u8 PsfrAddr)
*Description:Read P page sfr
*Input:u8 PsfrAddr: sfr address   
*Output:u8: sfr data     
*************************************************************************************/
u8 IAP_ReadPPage(u8 PsfrAddr)
{
	bit bEA=EA;
	EA = 0; 					//Disable interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= PsfrAddr;			//set sfr address;
	IFMT = ISP_READ_P;
	ISPCR = 0x80;				//Enable ISP/IAP
//	CheckTrapFlag();
	SCMD = 0x46;
//	CheckTrapFlag();
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//Clear ISPCR
	EA = bEA;					//restore interrupt
	return IFD;
}

/***********************************************************************************
*Function:void IAP_WritePPage(u8 PsfrAddr,u8 PsfrData)
*Description:write P page sfr
*Input:u8 PsfrAddr: sfr address,u8 PsfrData:  sfr data   
*Output:     
*************************************************************************************/
void IAP_WritePPage(u8 PsfrAddr,u8 PsfrData)
{
	bit bEA=EA;
	EA = 0; 					//Disable interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= PsfrAddr;			//set sfr address;
	IFD= PsfrData;				//Set sfr data
	IFMT = ISP_WRITE_P;
	ISPCR = 0x80;				//Enable ISP/IAP
//	CheckTrapFlag();
	SCMD = 0x46;
//	CheckTrapFlag();
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//Clear ISPCR
	EA = bEA;					//restore interrupt
}

/***********************************************************************************
*Function:u8 IAP_ReadByte(u16 ByteAddr)
*Description:read one byte from IAP
*Input:u16 ByteAddr: IAP Address   
*Output:     
*************************************************************************************/
u8 IAP_ReadByte(u16 ByteAddr)
{
		bit bEA=EA;
		IFADRH = ByteAddr>>8;		//Set address high byte
		IFADRL= (u8)(ByteAddr);			//Set address low byte;
		EA = 0;						//Disable interrupt
		IFMT = ISP_READ;
		ISPCR = 0x80; 				//Enable ISP/IAP
//		CheckTrapFlag();
		SCMD = 0x46;
//		CheckTrapFlag();
		SCMD = 0xB9;
		IFMT=0;
		ISPCR = 0;					//Clear ISPCR
		EA = bEA; 					//restore interrupt
		return IFD;
}
// Can use MOVC to read IAP
#define	IAP_ReadByteByMOVC(x)	CBYTE[x]

/***********************************************************************************
*Function:void IAP_ErasePage(u16 ByteAddr)
*Description:Erase one page
*Input:u8 ByteAddr: IAP Address   
*************************************************************************************/
void IAP_ErasePage(u16 ByteAddr)
{
		bit bEA=EA;
		IFADRH = (u8)(ByteAddr>>8);				//Set address high byte
		IFADRL= (u8)(ByteAddr)&B11000000;		//Set address low byte;
		EA = 0;									//Disable interrupt
		IFMT = ISP_ERASE;
		ISPCR = 0x80; 							//Enable ISP/IAP
//		CheckTrapFlag();
		SCMD = 0x46;
//		CheckTrapFlag();
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;								//Clear ISPCR
		EA = bEA; 								//restore interrupt
}

/***********************************************************************************
*Function:		u8 IAP_WriteBuf_With_Verify_Protect(u16 ByteAddr,u8 *pBuf,u8 Cnt)
*Description:	Write data to IAP
*		 	    use 64 bytes XDATA to save orgin IAP data.
*Input:  u16 ByteAddr: IAP Address, u8 *pBuf: The data buf to be write,u8 Cnt: Length to be write(<64) 
*Output:u8  0->succeed, other->failure     
*************************************************************************************/
u8 IAP_WriteBuf_With_Verify_Protect(u16 ByteAddr,u8 *pBuf,u8 Cnt)
{
		xdata u8 TempBuf[64];
		u16 i;
		u8 ErrCnt;
		WordTypeDef SectorAddr;
		bit bEA=EA;

		// read orgin data to XDATA
		ErrCnt=0;
		
		SectorAddr.W=ByteAddr&0xFFC0;
		for(i=0;i<64;i++)
		{
			TempBuf[i]=IAP_ReadByte(SectorAddr.W);
			SectorAddr.W++;
		}
		// modify data which to be write
		i=ByteAddr&0x003F;
		while(Cnt!=0)
		{
			TempBuf[i]=*pBuf;
			pBuf++;
			i++;
			Cnt--;
		}
	P_Err_Loop:
		// Erase page
		SectorAddr.W=ByteAddr&0xFE00;
		IAP_ErasePage(SectorAddr.W);
		
		// write data to IAP		
		EA = 0;								//Disable interrupt
		
		ISPCR = 0x80;               		//Enable ISP/IAP
		IFMT = ISP_BYTE_WRITE;				//Byte write mode
		
		for(i=0;i<64;i++)
		{
			IFADRH= SectorAddr.B.BHigh;		//Set address high byte
			IFADRL= SectorAddr.B.BLow; 		//Set address low byte;
			IFD = TempBuf[i]; 				//Set data to be wite 
			//		CheckTrapFlag();
			SCMD = 0x46;
			//		CheckTrapFlag();
			SCMD = 0xB9;
			nop();
			SectorAddr.W++;
		}
		IFMT = ISP_PAGE_WRITE;				//Page write mode
		//CheckTrapFlag();
		SCMD = 0x46;
		//CheckTrapFlag();
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;							//Clear ISPCR

		EA = bEA; 							//restore interrupt

		// Verify
		SectorAddr.W=ByteAddr&0xFFC0;
		for(i=0;i<64;i++)
		{
			if(TempBuf[i]!=IAP_ReadByte(SectorAddr.W))
			{
				ErrCnt++;
				if(ErrCnt<ERR_CNT_MAX)
				{
					goto P_Err_Loop;
				}
				else
				{
					goto P_Err_Return;
				}
			}
			SectorAddr.W++;
		}
		ErrCnt=0;
	P_Err_Return:
		return ErrCnt;		
}

/***********************************************************************************
*Function:   void IAP_ReadUID(u8 *pUID)
*Description:Read UID
*Input:u8 *PUID: Address of the buffer  
*Output:     
*************************************************************************************/
void IAP_ReadUID(u8 *pUID)
{
	u8 i;
	ISPCR = 0x80;
	BOREV = 0x22;
	IFMT = 0x06;
	IFADRH = 0x00;
	IFADRL = 0x70;
	
	for(i = 0; i < 16; i ++)
	{
		SCMD = 0x46;
		SCMD = 0xB9;
		pUID[i] = IFD;
		IFADRL ++;
	}
	BOREV = 0x00;
	IFMT=0;
	ISPCR = 0x00;
}

/***********************************************************************************
*Function:   u8 UID_Encrypt()
*Description:Encrypt by UID
*Input:   
*Output:0:Pass, other:Fail   
*************************************************************************************/
u8 UID_Encrypt(void)
{
	xdata u8 UID[16]; 
	u8 i;

	IAP_ReadUID(&UID[0]);

	for(i=0;i<16;i++)
	{
		if(UIDEncryptBuf[i]!=0xFF) break;
	}
	if(i<16)
	{ // There are encrypted bytes stored. check it
		for(i=0;i<16;i++)
		{
			if(UID[i] != UIDEncryptBuf[i]) break;
		}
		if(i<16)
		{ // Error
			return i+1;
		}
		else
		{
			return 0;
		}
	}
	else
	{ // All FF,no stored
		IAP_WritePPage(IAPLB_P,UID_ENCRYPT_BUF_ADDRESS/256);

		IAP_WriteBuf_With_Verify_Protect(UID_ENCRYPT_BUF_ADDRESS,&UID[0],16);
		
		IAP_WritePPage(IAPLB_P,ISP_ADDRESS/256);
		return 0;
	}

	return 0;
	
	
}


/***********************************************************************************
*Function:   void InitSystem(void)
*Description:   Initialize MCU
*Input:   
*Output:     
*************************************************************************************/
void InitSystem(void)
{
	InitPort();
	InitClock();
	InitUart0_S0BRG();	
}

void main()
{

	u8 i;
	bit bUIDEncryptFlag,bDeviceStringFlag;
	
	InitSystem();
	
	printf("\nHello!!");
	
	LED_G_0=0;LED_G_1=0;LED_R=0;
	DelayXms(1000);
	LED_G_0=1;LED_G_1=1;LED_R=1;

	// Check UID
	if(UID_Encrypt()!=0)
	{ // Fail
		printf("\nUID Test Fail!!");
		bUIDEncryptFlag=FALSE;
	}
	else
	{ // Pass
		printf("\nUID Test Pass!!");
		bUIDEncryptFlag=TRUE;
		LED_G_0=0;
	}

	// Check SN
	bDeviceStringFlag=TRUE;
	for(i=0;i<12;i++)
	{
		if(DeviceSnString[i] != DeviceSn[i])
		{ // Fail 
			bDeviceStringFlag=FALSE;
		}
	}

	if(bDeviceStringFlag)
	{
		printf("\nDeviceSN Test Pass!!");
		LED_G_1=0;
	}
	else
	{
		printf("\nDeviceSN Test Fail!!");
	}
	
    while(1)
	{	
		LED_R=!LED_R;
		DelayXms(100);
	}
	
}


