/*
******************************************************************************************************
 @Module        	
 @Filename     	Energy_Monitor.c
 @Project        	SEM-3000
-----------------------------------------------------------------------------------------------------
 @Controller     	Si1001

 @Compiler      	Keil 8.12

 @ Frequency   	Using Internal clock 24.5MHz

 @Codegenerator 	0.1

 @Description   

------------------------------------------------------------------------------------------------------
 @Date          		2013-07-05 11:00:00

******************************************************************************************************
*/


#define _Energy_Monitor_C_

/*
********************************************************************************************************
									 @Project Includes
********************************************************************************************************
*/

#include "PROJECT_INCLUDES.H"

#if 1	//500A 이하 Clamp

//*******************************************************************************************************

//--------------------CT Sensor Spec. -------------------------------------------------------

#define CT_TURN_NUNBER		3000  	// Current Transformer  샌서의 권선수 ( 사용 하고자 하는 CT 샌서의  DataSheet 참조 )
#define RL			       	120		///120   	// 클램프와 병렬 부하 저항  ( 합성 저항 값임 )	(저항 30옴 적용)		//120  -> 44 -> 28



//****************************  전력 공식을 위한 정의 . ******************************************************

#define CT1_V_RATIO_0A			0.000000000 	//0W       			
#define CT2_V_RATIO_0A			0.000000000 	//0W       			
#define CT3_V_RATIO_0A			0.000000000 	//0W       			

#define CT1_V_RATIO_0_01A		0.000000000 	//000150000
#define CT2_V_RATIO_0_01A		0.000000000 	//000150000
#define CT3_V_RATIO_0_01A		0.000000000 	//000150000

#define CT1_V_RATIO_0_02A		0.000100000 	//000100000
#define CT2_V_RATIO_0_02A		0.000100000 	//000100000
#define CT3_V_RATIO_0_02A		0.000100000 	//000100000

#define CT1_V_RATIO_0_05A		0.000230000 	//000230000
#define CT2_V_RATIO_0_05A		0.000320000 	//
#define CT3_V_RATIO_0_05A		0.000240000 	//

#define CT1_V_RATIO_0_1A		0.000360000 	//
#define CT2_V_RATIO_0_1A		0.000360000 	//
#define CT3_V_RATIO_0_1A		0.000360000 	//

#define CT1_V_RATIO_0_5A		0.000544000 	//
#define CT2_V_RATIO_0_5A		0.000540000 	//
#define CT3_V_RATIO_0_5A		0.000540000 	//

#define CT1_V_RATIO_1A			0.000600000 	// 1A(1 ~ 1.5A까지 Cal값 적용)
#define CT2_V_RATIO_1A			0.000594000 	// 1A(1 ~ 1.5A까지 Cal값 적용)
#define CT3_V_RATIO_1A			0.000596000 	// 1A(1 ~ 1.5A까지 Cal값 적용)

#define CT1_V_RATIO_5A			0.000653000 	// 5A
#define CT2_V_RATIO_5A			0.000644500 	// 5A
#define CT3_V_RATIO_5A			0.000647000 	// 5A

#define CT1_V_RATIO_10A			0.000658500 	// 10A
#define CT2_V_RATIO_10A			0.000650000 	// 10A
#define CT3_V_RATIO_10A			0.000651000 	// 10A

#define CT1_V_RATIO_20A			0.000662600 	// 
#define CT2_V_RATIO_20A			0.000654200		// 
#define CT3_V_RATIO_20A			0.000654500 	//

#define CT1_V_RATIO_30A			0.000668000 	// 30A(25A ~ 35A까지 Cal값 적용)	
#define CT2_V_RATIO_30A			0.000661000 	// 30A(25A ~ 35A까지 Cal값 적용)	
#define CT3_V_RATIO_30A			0.000662000 	// 30A(25A ~ 35A까지 Cal값 적용)	

#define CT1_V_RATIO_40A			0.000673000 	// 
#define CT2_V_RATIO_40A			0.000666000 	// 
#define CT3_V_RATIO_40A			0.000665000 	// 

#define CT1_V_RATIO_50A			0.000675000 	// 
#define CT2_V_RATIO_50A			0.000665000 	// 
#define CT3_V_RATIO_50A			0.000665000 	// 

#define CT1_V_RATIO_60A			0.000675000 	// 
#define CT2_V_RATIO_60A			0.000663000 	// 
#define CT3_V_RATIO_60A			0.000666000 	// 

////////////////////////////////////////////////////////////  코일 사용

#define CT1_V_RATIO_70A			0.000669000 	// 
#define CT2_V_RATIO_70A			0.000673000 	// 
#define CT3_V_RATIO_70A			0.000678000 	// 

#define CT1_V_RATIO_80A			0.000678000 	// 
#define CT2_V_RATIO_80A			0.000675000 	// 
#define CT3_V_RATIO_80A			0.000675000 	// 




#define CT1_V_RATIO 			0.000675000 	// 
#define CT2_V_RATIO 			0.000675000 	// 
#define CT3_V_RATIO 			0.000675000 	// 

//*******************************************************************************************************

/*
*********************************************************************************************************
*                                        				Eng_Vrms_Calculation
*
* Description:    ADC로 부터  읽어들인  전압의 합을  Sampling Phase 와  계산하여 반환 한다. ( 이 함수 이전에 sumV 을 구한다. )
*
* Arguments  :   sumV :   ADC로 부터  읽어들인  전압의 합
*                       numberOfSamples :	Sampling Phase 
*
* Returns    :      Vrms : 피상 전압 
*********************************************************************************************************
1A 	= 220	*	3 = 660
5A 	= 1100	*	3 = 3300
10A 	= 2200	*	3 = 6600
15A = 3300	*	3 = 9900
20A	= 4400	*	3 = 13200
25A	= 5500	*	3 = 16500
30A	= 6600	*	3 = 19800
35A	= 7700	*	3 = 23100
40A	= 8800	*	3 = 26400
45A	= 9900	*	3 = 29700
50A	= 11000	*	3 = 33000 
55A	= 12100	*	3 = 36300
60A	= 13200	*	3 = 39600
*/

double CT1_Eng_Vrms_Calculation(double sumV,  U8 numberOfSamples)										
{										
//	printf("\n CT1_Eng_Vrms = , %f  ", sumV);
	
     	 if( (0<=sumV)&&(sumV<3400)) 						return (CT1_V_RATIO_0A * sqrt(sumV /numberOfSamples) );
 	else if( (3401<=sumV)&&(sumV<=3600)) 					return (CT1_V_RATIO_0_01A* sqrt(sumV /numberOfSamples) ); 
 	else if( (3601<=sumV)&&(sumV<=4200)) 					return (CT1_V_RATIO_0_02A* sqrt(sumV /numberOfSamples) ); 
 	else if( (4201<=sumV)&&(sumV<=6200)) 					return (CT1_V_RATIO_0_05A* sqrt(sumV /numberOfSamples) ); 
 	else if( (6201<=sumV)&&(sumV<=8900)) 					return (CT1_V_RATIO_0_1A* sqrt(sumV /numberOfSamples) ); 
	else if( (8901<=sumV)&&(sumV<=77700)) 					return (CT1_V_RATIO_0_5A* sqrt(sumV /numberOfSamples) );
	else if( (77701<=sumV)&&(sumV<=245700)) 				return (CT1_V_RATIO_1A* sqrt(sumV /numberOfSamples) );  
	else if( (245701<=sumV)&&(sumV<=5077700))				return (CT1_V_RATIO_5A* sqrt(sumV /numberOfSamples) );
	else if( (5077701<=sumV)&&(sumV<=20309000)) 			return (CT1_V_RATIO_10A* sqrt(sumV /numberOfSamples) );
	else if( (20309001<=sumV)&&(sumV<=81219000)) 			return (CT1_V_RATIO_20A* sqrt(sumV /numberOfSamples) );
	else if( (81219001<=sumV)&&(sumV<=178940000))		 	return (CT1_V_RATIO_30A* sqrt(sumV /numberOfSamples) );
	else if( (178940001<=sumV)&&(sumV<=310766000))		 	return (CT1_V_RATIO_40A* sqrt(sumV /numberOfSamples) );
	else if( (310766001<=sumV)&&(sumV<=488687000)) 			return (CT1_V_RATIO_50A* sqrt(sumV /numberOfSamples) );
	else if( (488687001<=sumV)&&(sumV<=697890000)) 			return (CT1_V_RATIO_60A* sqrt(sumV /numberOfSamples) );
	else if( (697890001<=sumV)&&(sumV<=947867000)) 			return (CT1_V_RATIO_70A* sqrt(sumV /numberOfSamples) );
	else if( (947867001<=sumV)&&(sumV<=1224843000)) 		return (CT1_V_RATIO_80A* sqrt(sumV /numberOfSamples) );
	else if( 1224843001< sumV)         				 	 	return (CT1_V_RATIO* sqrt(sumV /numberOfSamples) ); 					

}


double CT2_Eng_Vrms_Calculation(double sumV,  U8 numberOfSamples)										
{										
//	printf("\n ,,CT2_Eng_Vrms = , %f  ", sumV);

     	 if( (0<=sumV)&&(sumV<3400)) 						return (CT2_V_RATIO_0A * sqrt(sumV /numberOfSamples) );
	else if( (3401<=sumV)&&(sumV<=3600)) 					return (CT2_V_RATIO_0_01A* sqrt(sumV /numberOfSamples) ); 
	else if( (3601<=sumV)&&(sumV<=4100)) 					return (CT2_V_RATIO_0_02A* sqrt(sumV /numberOfSamples) ); 

	else if( (4101<=sumV)&&(sumV<=5400)) 					return (CT2_V_RATIO_0_05A* sqrt(sumV /numberOfSamples) ); 
	else if( (3301<=sumV)&&(sumV<=8700)) 					return (CT2_V_RATIO_0_1A* sqrt(sumV /numberOfSamples) ); 
    else if( (8701<=sumV)&&(sumV<=78400)) 					return (CT2_V_RATIO_0_5A* sqrt(sumV /numberOfSamples) );
	else if( (78401<=sumV)&&(sumV<=256100)) 				return (CT2_V_RATIO_1A* sqrt(sumV /numberOfSamples) );  
	else if( (256101<=sumV)&&(sumV<=5136700))				return (CT2_V_RATIO_5A* sqrt(sumV /numberOfSamples) );
	else if( (5136701<=sumV)&&(sumV<=20062000))				return (CT2_V_RATIO_10A* sqrt(sumV /numberOfSamples) );
	else if( (20062001<=sumV)&&(sumV<=79917000)) 			return (CT2_V_RATIO_20A* sqrt(sumV /numberOfSamples) );
	else if( (79917001<=sumV)&&(sumV<=176562000))		 	return (CT2_V_RATIO_30A* sqrt(sumV /numberOfSamples) );
	else if( (176562001<=sumV)&&(sumV<=314729000))		 	return (CT2_V_RATIO_40A* sqrt(sumV /numberOfSamples) );
	else if( (314729001<=sumV)&&(sumV<=487755000)) 			return (CT2_V_RATIO_50A* sqrt(sumV /numberOfSamples) );
	else if( (487755001<=sumV)&&(sumV<=704100000)) 			return (CT2_V_RATIO_60A* sqrt(sumV /numberOfSamples) );
	else if( (704100001<=sumV)&&(sumV<=966870000)) 			return (CT2_V_RATIO_70A* sqrt(sumV /numberOfSamples) );
	else if( (966870001<=sumV)&&(sumV<=1253861000)) 		return (CT2_V_RATIO_80A* sqrt(sumV /numberOfSamples) );
	else if( 1253861001< sumV)         			 	  		return (CT2_V_RATIO* sqrt(sumV /numberOfSamples) ); 					
									  

//***************************************************************************************************************//	


}

double CT3_Eng_Vrms_Calculation(double sumV,  U8 numberOfSamples)										
{										
//	printf("\n ,,,,CT3_Eng_Vrms = , %f  ", sumV);

		 if( (0<=sumV)&&(sumV<3400)) 						return (CT3_V_RATIO_0A * sqrt(sumV /numberOfSamples) );
	else if( (3401<=sumV)&&(sumV<=3380)) 					return (CT3_V_RATIO_0_01A* sqrt(sumV /numberOfSamples) );
	else if( (3381<=sumV)&&(sumV<=4550)) 					return (CT3_V_RATIO_0_02A* sqrt(sumV /numberOfSamples) );
	else if( (4551<=sumV)&&(sumV<=6200)) 					return (CT3_V_RATIO_0_05A* sqrt(sumV /numberOfSamples) );
	else if( (6201<=sumV)&&(sumV<=9000)) 					return (CT3_V_RATIO_0_1A* sqrt(sumV /numberOfSamples) );
    else if( (9001<=sumV)&&(sumV<=75200)) 					return (CT3_V_RATIO_0_5A* sqrt(sumV /numberOfSamples) );
	else if( (75201<=sumV)&&(sumV<=254100)) 				return (CT3_V_RATIO_1A* sqrt(sumV /numberOfSamples) );  
	else if( (254101<=sumV)&&(sumV<=5054700))				return (CT3_V_RATIO_5A* sqrt(sumV /numberOfSamples) );
	else if( (5054701<=sumV)&&(sumV<=20278000))				return (CT3_V_RATIO_10A* sqrt(sumV /numberOfSamples) );
	else if( (20278001<=sumV)&&(sumV<=80658000)) 			return (CT3_V_RATIO_20A* sqrt(sumV /numberOfSamples) );
	else if( (80658001<=sumV)&&(sumV<=177949000))		 	return (CT3_V_RATIO_30A* sqrt(sumV /numberOfSamples) );
	else if( (177949001<=sumV)&&(sumV<=308841000))		 	return (CT3_V_RATIO_40A* sqrt(sumV /numberOfSamples) );
	else if( (308841001<=sumV)&&(sumV<=477817000)) 			return (CT3_V_RATIO_50A* sqrt(sumV /numberOfSamples) );
	else if( (477817001<=sumV)&&(sumV<=696407000)) 			return (CT3_V_RATIO_60A* sqrt(sumV /numberOfSamples) );
	else if( (696407001<=sumV)&&(sumV<=951950000)) 			return (CT3_V_RATIO_70A* sqrt(sumV /numberOfSamples) );
	else if( (951950001<=sumV)&&(sumV<=1205077000)) 		return (CT3_V_RATIO_80A* sqrt(sumV /numberOfSamples) );
	else if( 1205077001< sumV)         			 	 		return (CT3_V_RATIO* sqrt(sumV /numberOfSamples) ); 					



}

#else	//500A Clamp


//--------------------전력 공식을 위한 정의 . -------------------------------------------------------
/*
#define V_RATIO_0A			0.000000000 	//0W       			
#define V_RATIO_0_5A		0.000280000 	//
#define V_RATIO_1A			0.000340000 	// 1A(1 ~ 1.5A까지 Cal값 적용)
#define V_RATIO_3A			0.000360000 	// 3A(1.5 ~ 4A까지 Cal값 적용)
#define V_RATIO_5A			0.000380000 	// 5A(4 ~ 7A까지 Cal값 적용)
#define V_RATIO_10A			0.000396000 	// 10A(7 ~ 15A까지 Cal값 적용)
#define V_RATIO_20A			0.000398000 	// 20A(15 ~ 25A까지 Cal값 적용)
#define V_RATIO_30A			0.000400000 	// 30A(25A ~ 35A까지 Cal값 적용)
#define V_RATIO_40A			0.000401000 	// 40A(35A ~ 45A까지 Cal값 적용)
#define V_RATIO_50A			0.000403000 	// 50A(45A ~ 55A까지 Cal값 적용)
#define V_RATIO_60A   		0.000405000 	// 60A(55A ~~~~ Cal값 적용)
#define V_RATIO 				0.000420000 	// 60A 이상 
*/

#define CT1_V_RATIO_0A			0.000000000 	//0W       			
#define CT2_V_RATIO_0A			0.000000000 	//0W       			
#define CT3_V_RATIO_0A			0.000000000 	//0W       			


#define CT1_V_RATIO_0_25A		0.000200000 	//
#define CT2_V_RATIO_0_25A		0.000200000 	//
#define CT3_V_RATIO_0_25A		0.000200000 	//


#define CT1_V_RATIO_0_5A		0.000290000 	//
#define CT2_V_RATIO_0_5A		0.000290000 	//
#define CT3_V_RATIO_0_5A		0.000290000 	//

#define CT1_V_RATIO_1A			0.000377000 	// 1A(1 ~ 1.5A까지 Cal값 적용)
#define CT2_V_RATIO_1A			0.000377000 	// 1A(1 ~ 1.5A까지 Cal값 적용)
#define CT3_V_RATIO_1A			0.000377000 	// 1A(1 ~ 1.5A까지 Cal값 적용)

#define CT1_V_RATIO_2A			0.000428000 	// 2A(1.5 ~ 2.5A까지 Cal값 적용)
#define CT2_V_RATIO_2A			0.000428000 	// 2A(1.5 ~ 2.5A까지 Cal값 적용)
#define CT3_V_RATIO_2A			0.000428000 	// 2A(1.5 ~ 2.5A까지 Cal값 적용)

#define CT1_V_RATIO_3A			0.000452000 	// 3A(2.5 ~ 3.5A까지 Cal값 적용)
#define CT2_V_RATIO_3A			0.000452000 	// 3A(2.5 ~ 3.5A까지 Cal값 적용)
#define CT3_V_RATIO_3A			0.000452000 	// 3A(2.5 ~ 3.5A까지 Cal값 적용)

#define CT1_V_RATIO_5A			0.000478000 	// 5A(3.5 ~ 7A까지 Cal값 적용)
#define CT2_V_RATIO_5A			0.000478000 	// 5A(3.5 ~ 7A까지 Cal값 적용)
#define CT3_V_RATIO_5A			0.000478000 	// 5A(3.5 ~ 7A까지 Cal값 적용)

#define CT1_V_RATIO_10A			0.000494000 	// 10A(7 ~ 15A까지 Cal값 적용)
#define CT2_V_RATIO_10A			0.000494000 	// 10A(7 ~ 15A까지 Cal값 적용)
#define CT3_V_RATIO_10A			0.000494000 	// 10A(7 ~ 15A까지 Cal값 적용)

#define CT1_V_RATIO_20A			0.000502000 	// 20A(15 ~ 25A까지 Cal값 적용)
#define CT2_V_RATIO_20A			0.000502000 	// 20A(15 ~ 25A까지 Cal값 적용)
#define CT3_V_RATIO_20A			0.000502000 	// 20A(15 ~ 25A까지 Cal값 적용)

#define CT1_V_RATIO_30A			0.000506000 	// 30A(25A ~ 35A까지 Cal값 적용)	
#define CT2_V_RATIO_30A			0.000506000 	// 30A(25A ~ 35A까지 Cal값 적용)	
#define CT3_V_RATIO_30A			0.000506000 	// 30A(25A ~ 35A까지 Cal값 적용)	

#define CT1_V_RATIO_40A			0.000507000 	// 40A(35A ~ 45A까지 Cal값 적용)
#define CT2_V_RATIO_40A			0.000507000 	// 40A(35A ~ 45A까지 Cal값 적용)
#define CT3_V_RATIO_40A			0.000507000 	// 40A(35A ~ 45A까지 Cal값 적용)

#define CT1_V_RATIO_50A			0.000508000 	// 50A(45A ~ 55A까지 Cal값 적용)	
#define CT2_V_RATIO_50A			0.000508000 	// 50A(45A ~ 55A까지 Cal값 적용)	
#define CT3_V_RATIO_50A			0.000508000 	// 50A(45A ~ 55A까지 Cal값 적용)	

#define CT1_V_RATIO_60A   		0.000509000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_60A   		0.000509000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_60A   		0.000509000 	// 60A(55A ~~~~ Cal값 적용)

//**************************************************************************************//

#define CT1_V_RATIO_70A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_70A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_70A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_80A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_80A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_80A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_90A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_90A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_90A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_100A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_100A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_100A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_150A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_150A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_150A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_200A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_200A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_200A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_250A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_250A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_250A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_300A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_300A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_300A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_350A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_350A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_350A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_400A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_400A  		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_400A  		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_450A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_450A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_450A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

#define CT1_V_RATIO_500A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT2_V_RATIO_500A   		0.000502000 	// 60A(55A ~~~~ Cal값 적용)
#define CT3_V_RATIO_500A  		0.000502000 	// 60A(55A ~~~~ Cal값 적용)

//**************************************************************************************//

#define CT1_V_RATIO 				0.000530000 	// 60A 이상 
#define CT2_V_RATIO 				0.000530000 	// 60A 이상 
#define CT3_V_RATIO 				0.000530000 	// 60A 이상 


//--------------------CT Sensor Spec. -------------------------------------------------------

#define CT_TURN_NUNBER   1500  	// Current Transformer  샌서의 권선수 ( 사용 하고자 하는 CT 샌서의  DataSheet 참조 )

#define RL			          11   	// 클램프와 병렬 부하 저항  ( 합성 저항 값임 )		25 -> 16 -> 13 -> 11

/*
*********************************************************************************************************
*                                        				Eng_Vrms_Calculation
*
* Description:    ADC로 부터  읽어들인  전압의 합을  Sampling Phase 와  계산하여 반환 한다. ( 이 함수 이전에 sumV 을 구한다. )
*
* Arguments  :   sumV :   ADC로 부터  읽어들인  전압의 합
*                       numberOfSamples :	Sampling Phase 
*
* Returns    :      Vrms : 피상 전압 
*********************************************************************************************************
1A 	= 220	*	3 = 660
5A 	= 1100	*	3 = 3300
10A 	= 2200	*	3 = 6600
15A = 3300	*	3 = 9900
20A	= 4400	*	3 = 13200
25A	= 5500	*	3 = 16500
30A	= 6600	*	3 = 19800
35A	= 7700	*	3 = 23100
40A	= 8800	*	3 = 26400
45A	= 9900	*	3 = 29700
50A	= 11000	*	3 = 33000 
55A	= 12100	*	3 = 36300
60A	= 13200	*	3 = 39600
*/

double CT1_Eng_Vrms_Calculation(double sumV,  U8 numberOfSamples)
{
//          printf("\n CT1_sumV=%f  ", sumV);

		if((0<=sumV)&&(sumV<7000))	 					return (CT1_V_RATIO_0A * sqrt(sumV /numberOfSamples) );  	
	else if( (7001<=sumV)&&(sumV<=30000)) 				return (CT1_V_RATIO_0_5A* sqrt(sumV /numberOfSamples) );
	else if( (30001<=sumV)&&(sumV<=80000)) 				return (CT1_V_RATIO_1A* sqrt(sumV /numberOfSamples) );
	else if( (80001<=sumV)&&(sumV<=180000))	 			return (CT1_V_RATIO_2A* sqrt(sumV /numberOfSamples) );
	else if( (180001<=sumV)&&(sumV<=320000))	 		return (CT1_V_RATIO_3A* sqrt(sumV /numberOfSamples) );	
	else if( (320001<=sumV)&&(sumV<=1300000)) 			return (CT1_V_RATIO_5A* sqrt(sumV /numberOfSamples) );
	else if( (1300001<=sumV)&&(sumV<=5000000))	 		return (CT1_V_RATIO_10A* sqrt(sumV /numberOfSamples) );
	else if( (5000001<=sumV)&&(sumV<=14000000)) 		return (CT1_V_RATIO_20A* sqrt(sumV /numberOfSamples) );
	else if( (14000001<=sumV)&&(sumV<=26000000)) 		return (CT1_V_RATIO_30A* sqrt(sumV /numberOfSamples) );
	else if( (26000001<=sumV)&&(sumV<=44000000)) 		return (CT1_V_RATIO_40A* sqrt(sumV /numberOfSamples) );
	else if( (44000001<=sumV)&&(sumV<=65000000)) 		return (CT1_V_RATIO_50A* sqrt(sumV /numberOfSamples) );
	else if( (65000001<=sumV)&&(sumV<=85000000)) 		return (CT1_V_RATIO_60A* sqrt(sumV /numberOfSamples) );

//***************************************************************************************************************//	

	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_70A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_80A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_90A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_100A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_150A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_200A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_250A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_300A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_350A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_400A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_450A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT1_V_RATIO_500A* sqrt(sumV /numberOfSamples) );

//***************************************************************************************************************//	

	else if( 45000000< sumV)         			 	  		return (CT1_V_RATIO* sqrt(sumV /numberOfSamples) ); 	
   
}

double CT2_Eng_Vrms_Calculation(double sumV,  U8 numberOfSamples)
{
 //         printf("\n CT2_sumV=%f  ", sumV);

		if((0<=sumV)&&(sumV<7000))	 					return (CT2_V_RATIO_0A * sqrt(sumV /numberOfSamples) );  	
	else if( (7001<=sumV)&&(sumV<=30000)) 				return (CT2_V_RATIO_0_5A* sqrt(sumV /numberOfSamples) );
	else if( (30001<=sumV)&&(sumV<=80000)) 				return (CT2_V_RATIO_1A* sqrt(sumV /numberOfSamples) );
	else if( (80001<=sumV)&&(sumV<=180000))	 			return (CT2_V_RATIO_2A* sqrt(sumV /numberOfSamples) );
	else if( (180001<=sumV)&&(sumV<=320000))	 			return (CT2_V_RATIO_3A* sqrt(sumV /numberOfSamples) );	
	else if( (320001<=sumV)&&(sumV<=1300000)) 			return (CT2_V_RATIO_5A* sqrt(sumV /numberOfSamples) );
	else if( (1300001<=sumV)&&(sumV<=5000000))	 		return (CT2_V_RATIO_10A* sqrt(sumV /numberOfSamples) );
	else if( (5000001<=sumV)&&(sumV<=14000000)) 			return (CT2_V_RATIO_20A* sqrt(sumV /numberOfSamples) );
	else if( (14000001<=sumV)&&(sumV<=26000000))	 		return (CT2_V_RATIO_30A* sqrt(sumV /numberOfSamples) );
	else if( (26000001<=sumV)&&(sumV<=44000000)) 		return (CT2_V_RATIO_40A* sqrt(sumV /numberOfSamples) );
	else if( (44000001<=sumV)&&(sumV<=65000000)) 		return (CT2_V_RATIO_50A* sqrt(sumV /numberOfSamples) );
	else if( (65000001<=sumV)&&(sumV<=85000000)) 		return (CT2_V_RATIO_60A* sqrt(sumV /numberOfSamples) );

//***************************************************************************************************************//	

	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_70A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_80A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_90A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_100A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_150A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_200A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_250A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_300A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_350A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_400A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_450A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT2_V_RATIO_500A* sqrt(sumV /numberOfSamples) );

//***************************************************************************************************************//	
	
	else if( 45000000< sumV)         			 	  		return (CT2_V_RATIO* sqrt(sumV /numberOfSamples) ); 	
   
}

double CT3_Eng_Vrms_Calculation(double sumV,  U8 numberOfSamples)
{
 //        printf("\n CT3_sumV=%f  ", sumV);

		if((0<=sumV)&&(sumV<7000))	 					return (CT3_V_RATIO_0A * sqrt(sumV /numberOfSamples) );  	
	else if( (7001<=sumV)&&(sumV<=30000)) 				return (CT3_V_RATIO_0_5A* sqrt(sumV /numberOfSamples) );
	else if( (30001<=sumV)&&(sumV<=80000)) 				return (CT3_V_RATIO_1A* sqrt(sumV /numberOfSamples) );
	else if( (80001<=sumV)&&(sumV<=180000))	 			return (CT3_V_RATIO_2A* sqrt(sumV /numberOfSamples) );
	else if( (180001<=sumV)&&(sumV<=320000))	 			return (CT3_V_RATIO_3A* sqrt(sumV /numberOfSamples) );	
	else if( (320001<=sumV)&&(sumV<=1300000)) 			return (CT3_V_RATIO_5A* sqrt(sumV /numberOfSamples) );
	else if( (1300001<=sumV)&&(sumV<=5000000))	 		return (CT3_V_RATIO_10A* sqrt(sumV /numberOfSamples) );
	else if( (5000001<=sumV)&&(sumV<=14000000)) 			return (CT3_V_RATIO_20A* sqrt(sumV /numberOfSamples) );
	else if( (14000001<=sumV)&&(sumV<=26000000))	 		return (CT3_V_RATIO_30A* sqrt(sumV /numberOfSamples) );
	else if( (26000001<=sumV)&&(sumV<=44000000)) 		return (CT3_V_RATIO_40A* sqrt(sumV /numberOfSamples) );
	else if( (44000001<=sumV)&&(sumV<=65000000)) 		return (CT3_V_RATIO_50A* sqrt(sumV /numberOfSamples) );
	else if( (65000001<=sumV)&&(sumV<=85000000)) 		return (CT3_V_RATIO_60A* sqrt(sumV /numberOfSamples) );

//***************************************************************************************************************//	

	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_70A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_80A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_90A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_100A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_150A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_200A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_250A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_300A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_350A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_400A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_450A* sqrt(sumV /numberOfSamples) );
	else if( (27000001<=sumV)&&(sumV<=45000000)) 		return (CT3_V_RATIO_500A* sqrt(sumV /numberOfSamples) );

//***************************************************************************************************************//		

	else if( 45000000< sumV)         			 	  		return (CT3_V_RATIO* sqrt(sumV /numberOfSamples) ); 	
   
}
#endif


#define POWER_MAX_BUFFER   7

typedef enum {

	Eng_IDLE = 0,
			
	Eng_CHK_COMPLETE,
	
	Eng__FINISHED
	
}Eng_STATE_ID;


typedef enum {

	Eng_COMPLETE = 0,
		
	Eng_SENDING
	
}Eng_STATUS;



typedef struct{

	U8 			Eng_State_ID;			
	Eng_STATUS	EngStateus;			
	
}Eng_CLESS;


volatile  U8 idata Get_Ct_Sensor ;	
//idata U8 Get_Ct_Sensor_old ;	

volatile  U8 idata Ct_Sensor_Count ;	
volatile  U8 idata  Energy_Scan_Count;
volatile  U8 idata  Energy_Min_Count;

volatile  U32 idata Apparent_Power[BUFFER_NO];

/// xdata volatile  Queue_32bit	ADAPTER_ADC_Q;
 
 xdata volatile  Queue_32bit	CT1_ADC_Q;							//  Q 버퍼 생성  
 xdata volatile  Queue_32bit	CT2_ADC_Q;							//  Q 버퍼 생성  
 xdata volatile  Queue_32bit	CT3_ADC_Q;							//  Q 버퍼 생성  

static Eng_CLESS	volatile  Eng_Power_Chk;

static Eng_CLESS	volatile  *pEng = &Eng_Power_Chk ;


volatile  U8 idata  fEnergy_Power_Measuring_State;
volatile  U8 idata ADC_Timeout_Chk_Timer;

extern  void Put_CT_Sensor(U8 CT_Sensor_Adc);

static void CT1_Sensor__ADC0_Interrupt_Handler(void);
static void CT2_Sensor__ADC0_Interrupt_Handler(void);
static void CT3_Sensor__ADC0_Interrupt_Handler(void);

static void SendRF_Energy_Power_CT_Sensor(void);
/*
*********************************************************************************************************
*
*									 @DEFINE  HMI COMMAND
*									 
*********************************************************************************************************
*/

#define DAY_POWER_DSP   			0
#define WEEK_POWER_DSP   			1
#define THIS_MONTH_POWER_DSP   	2
#define MONTH_POWER_DSP   			3


/*
*********************************************************************************************************
 									@Macros
*********************************************************************************************************
*/





/*
***************************************************************************************************************************
									@Global Variables
***************************************************************************************************************************
*/

volatile U8  Lcd_All_Data_Dispaly_Timer;
volatile U8  Dsp_State, Dsp_State_Graph;
volatile U8  Rf_Receive_State_Count[Max_CHANNEL_ID];
U8 Rf_Disconnected[Max_CHANNEL_ID];


volatile  U32   Power_Old;
volatile  U32   Power_Data;

U32 RealTime_PowerData[Max_CHANNEL_ID];


U8   Test_Hour;
U8   Test_day;

/*
*********************************************************************************************************
*                                        				Eng_Irms_Calculation
*
* Description:    Irms  를 계산하여 반환 한다. 
*
* Arguments  :   Irms :  계산된  피상 전류 
*                       
*
* Returns    :      Irms : 피상 전압 
*********************************************************************************************************
*/

double Eng_Irms_Calculation(double Vrms)
{
	return ( Vrms*CT_TURN_NUNBER/RL);
}

/*
***************************************************************************************************************************
*                                                            Energy_Monitor_Init
*
* Description:    
*
* Arguments  :  NONE
*
* Returns      :   NONE
***************************************************************************************************************************
*/ 
void Energy_Monitor_Init (void)
{     U8 k;
  #if 0
	Lcd_All_Data_Dispaly_Timer = timerSecHandleAssign();

	Display_Channel=1;

	Test_Hour=0;

	Test_day=event1.output_days;
	
	Power_Old=0;
	Dsp_State=0;
	Dsp_State_Graph=WEEK_POWER_DSP;
		
	memset(& Rf_Receive_State_Count[0], 0, sizeof(Rf_Receive_State_Count));	
	memset(& RealTime_PowerData[0], 0, sizeof(RealTime_PowerData));	
	memset(& Rf_Disconnected[0], 0, sizeof(Rf_Disconnected));	
#else
     
	 Queue_Buf_Init_32bit(&CT1_ADC_Q);    //  Q 버퍼 초기화  
	Queue_Buf_Init_32bit(&CT2_ADC_Q);
	Queue_Buf_Init_32bit(&CT3_ADC_Q);
    
	ADC_Timeout_Chk_Timer = 0;
  	ADC_Timeout_Chk_Timer= timer_mSecHandleAssign();

	fEnergy_Power_Measuring_State=0;
	Energy_Scan_Count=0;
	Energy_Min_Count = 0;
    Minute_Total_Power = 0;
	
	memset(&Apparent_Power[0], NULL, sizeof(Apparent_Power));  //  버퍼 초기화  
	memset(&Minute_Power[0], NULL, sizeof(Minute_Power));  //  버퍼 초기화  
	
	CT1_Monitor_Intertupt_Service_Init( CT1_Sensor__ADC0_Interrupt_Handler );   // Set ADC0 interrupt service function
	CT2_Monitor_Intertupt_Service_Init( CT2_Sensor__ADC0_Interrupt_Handler );   // Set ADC0 interrupt service function
	CT3_Monitor_Intertupt_Service_Init( CT3_Sensor__ADC0_Interrupt_Handler );   // Set ADC0 interrupt service function
	 #if 0
	 #endif
#endif


}




/*
***************************************************************************************************************************
*                                                            Get_RealTime_PowerData_send
*
* Description:   실시간으로 수신된 RF 파워 데이터를  가져 온다  
*
* Arguments  :  ID: 체널 
*
* Returns      :   PowerData
***************************************************************************************************************************
*/
U32 Get_RealTime_PowerData_send ( U8 ID)
{   		
	U32 Get_Data;
      // U16 Cnt;
	//U32  Sum_Power_Data;
	
	#if 0
	Get_Data=RealTime_PowerData[ID];
	#else
	Get_Data=Get_RealTime_One_Min_PowerData(ID); 
	#endif
	return Get_Data;

}


/*
***************************************************************************************************************************
*                                                            Clr_Now_Energy_Display
*
* Description:   Lcd 의  Now Energy 영역을 클리어  한다 
*
* Arguments  :  NONE
*
* Returns      :   NONE
***************************************************************************************************************************
*/

#define RX_TIME_OUT 6          // RF data 가  30초(5*6) 이상 없을시  (5초  단위로  6번 체크 ) //140328 변경 3 -> 40 - > 5    orig 5    6
//#define DISCONNECT_TIME_OUT 24    // 24*5     약 20분 이상 연결이 없을 경우 배터리가 없는 것으로 간주하고 0으로  만든다.    시간 변경 가능 

/*
*********************************************************************************************************
*                                                           Eng__Real_Power_Proc
*
* Description:      합산된 전압을 전류로 환산 하여  전력을  계산한다 
*
* Arguments  :    sumV  : CT  Sensor 전압을  합산한 전압 (mV)
*                        Sample_Count:  Sampling Count

* Returns      :    NONE
*
*********************************************************************************************************
*/

U32 CT1_Eng__Real_Power_Proc(double sumV, U8 Sample_Count  )
{	
	volatile  double idata Vrms, Irms;
	volatile  U32 idata Apparent_Power;   

	Vrms=CT1_Eng_Vrms_Calculation(sumV, Sample_Count);
							
	Irms=Eng_Irms_Calculation(Vrms); 
	
	//printf("\n Irms=%f  ", Irms);

	#if 1  // thhan 2014.12.11 Will Calculate to the IHD.
	Apparent_Power=(U32)(Irms * 100);
	#else
	Apparent_Power=(U32)Eng__Apparent_Power_Calculation(Irms);
	#endif
	
	return Apparent_Power;
	
}


U32 CT2_Eng__Real_Power_Proc(double sumV, U8 Sample_Count  )
{	
	volatile  double idata Vrms, Irms;
	volatile  U32 idata Apparent_Power;   

	Vrms=CT2_Eng_Vrms_Calculation(sumV, Sample_Count);
							
	Irms=Eng_Irms_Calculation(Vrms); 
	
	//printf("\n Irms=%f  ", Irms);

	#if 1  // thhan 2014.12.11 Will Calculate to the IHD.
	Apparent_Power=(U32)(Irms * 100);
	#else
	Apparent_Power=(U32)Eng__Apparent_Power_Calculation(Irms);
	#endif
	
	return Apparent_Power;
	
}

U32 CT3_Eng__Real_Power_Proc(double sumV, U8 Sample_Count  )
{	
	volatile  double idata Vrms, Irms;
	volatile  U32 idata Apparent_Power;   

	Vrms=CT3_Eng_Vrms_Calculation(sumV, Sample_Count);
							
	Irms=Eng_Irms_Calculation(Vrms); 
	
	//printf("\n Irms=%f  ", Irms);

	#if 1  // thhan 2014.12.11 Will Calculate to the IHD.
	Apparent_Power=(U32)(Irms * 100);
	#else
	Apparent_Power=(U32)Eng__Apparent_Power_Calculation(Irms);
	#endif
	
	return Apparent_Power;
	
}


 /*
*********************************************************************************************************
*                                                           Eng__Average_Power_Proc
*
* Description:      Q 버퍼에 저장 되여 있는  전력을  평균  계산한다 
*
* Arguments  :    pRing :  Q 버퍼
*                       
* Returns      :    Average Power
*
*********************************************************************************************************
*/

U32 Eng__Average_Power_Proc( Queue_32bit * pRing )
{
      	volatile U8 idata	i, Cnt, temp;
	volatile U32 idata  Power;
	volatile double idata sumP;   

	
	if( Queue_Chk_Contains_32bit( pRing) == EMPTY_CONTAINS)
	{
		return 0;
	}

	Cnt=pRing->Ring_Buf_Counter;
	sumP=0; 
	
	for(i=0; i<Cnt; i++){

		Power = 0;
		
		Queue_Get_Data_32bit(pRing, &Power);	
		temp = Power >> 24;
		if(0x80 & temp) Power = 0; // if power is minus then put 0 the power
		
	       sumP+=Power;
           
	#if (CT_Sensor_DEBUG)
		printf("\n Cnt=%d, Power = %ld, sumP=%ld", (U16)Cnt,Power,sumP );  //CT Sensor Power Data  원림
	#endif     
	}
	
	return sumP/Cnt;
	
}

#if 0
U32 Adapter__Average_Power_Proc( Queue_32bit * pRing )
{
	volatile U8 idata	i, Cnt;
	volatile U32 idata  Power;
	volatile double idata sumP;   

	
	if( Queue_Chk_Contains_32bit( pRing) == EMPTY_CONTAINS)
	{
		return 0;
	}

	Cnt=pRing->Ring_Buf_Counter;

	sumP=0; 
	
	for(i=0; i<Cnt; i++){

		Power = 0;
		
		Queue_Get_Data_32bit(pRing, &Power);	

		if(0 > Power) Power = 0;
		
	       sumP+=Power;
	}
	
	return sumP/Cnt;
	
}
#endif

 /*
*********************************************************************************************************
*                                                           Energy_Monitor_For_Start_ADC  
*
* Description:      ADC ON 하고  CT Sensor 의 유무  체크 하고  그에 맞는 전력을 측정한다 
*
* Arguments  :    NONE
*                       
* Returns      :     NONE
*
*********************************************************************************************************
*/

#define  ENERGY_POWER_SAMPING_END_CT1	0x01 
#define  ENERGY_POWER_SAMPING_END_CT2	0x02
#define  ENERGY_POWER_SAMPING_END_CT3	0x04 

#define  CT_DECT_Monitor						0x08

#define  ENERGY_POWER_SAMPING_END_ALL_CT	( ENERGY_POWER_SAMPING_END_CT1 | \
												  ENERGY_POWER_SAMPING_END_CT2 | \
												  ENERGY_POWER_SAMPING_END_CT3 )

#define POWER_PHASE_SAMPLING   50    // 50 교류 PHASE 샘플링   횟수 		50 -> 40 -> 70->100 ->10변경 30		140318 변경  50-> 30

void Energy_Monitor_For_Start_ADC(void)
{
        U8 idata k, Ct_Number;
	   
	AD0INT = 0;                               // clear ADC0 conv. complete flag	
   
	Adc_Mux_Channel_Initialize();
	INTERRUPT_ENABLE_ADC_0(); 
	Timer3_Run();
       EA=1;
       
	timer_mSecTimerSet(ADC_Timeout_Chk_Timer, 50); 	// Set Time out priode	10 -> 50으로 변경   140318 : 50 -> 10으로 변경

	for(k=0; k<10; k++){}  // ADC 를 위한 Delay
	while(1) 
	{
		if(time_mSecTimeExpired(ADC_Timeout_Chk_Timer) == TIMER_EXPIRED )		
		{
			break;
		}
	}
	
	//printf("  b ed"); 
	
	for(k=0; k<60; k++){}  // ADC 를 위한 Delay
	
	INTERRUPT_DISABLE_ADC_0(); 	
	Timer3_Stop();


	Ct_Number=Ct_Detect_ADC_Chk();
    	//printf("\n  Ct_Number=%d", (U16)Ct_Number);

	Put_CT_Sensor( Ct_Number );

	fEnergy_Power_Measuring_State=0;

	Queue_Buf_Init_32bit(&CT1_ADC_Q);    //  Q 버퍼 초기화  
	Queue_Buf_Init_32bit(&CT2_ADC_Q);
	Queue_Buf_Init_32bit(&CT3_ADC_Q);
	
///	Queue_Buf_Init_32bit(&ADAPTER_ADC_Q);
	
	
	AD0INT = 0;                               // clear ADC0 conv. complete flag	
	
	Set_Adc_Mux_Channel_Count (ADC_CT1);

	ADC_Set_Channel(ADC_CT1);
	
	INTERRUPT_ENABLE_ADC_0(); 
	
	Timer3_Run();
    
	timer_mSecTimerSet(ADC_Timeout_Chk_Timer, 300); 	// Set Time out priode	20140318 원림 변경 700 -> 300

	//printf("\nc st", ADC_Timeout_Chk_Timer); 

	for(k=0; k<60; k++){}  // ADC 를 위한 Delay
		
	while(1)
	{
		if( fEnergy_Power_Measuring_State ==ENERGY_POWER_SAMPING_END_ALL_CT )
		{
			break;
		}
		
		if(time_mSecTimeExpired(ADC_Timeout_Chk_Timer) == TIMER_EXPIRED )
		{
			//printf(" tout"); 
			break;
		}
		
	}

	INTERRUPT_DISABLE_ADC_0();
	Timer3_Stop();
	AD0INT = 0;                               // clear ADC0 conv. complete flag	
	for(k=0; k<10; k++){}  // ADC 를 위한 Delay
	
}
/*
*********************************************************************************************************
*                                                          Save_Buffer_Energy_Power
*
* Description:      
*
* Arguments  :    NONE
*                       
* Returns      :     NONE
*
*********************************************************************************************************
*/

 void Save_Buffer_Energy_Power(void)
{
	volatile u32 idata Power;
	
	Get_Ct_Sensor=Ct_Detect_Chk() ;

	
	if( (Get_Ct_Sensor&CT1_EXIST))
	{		 	 		
		Power= Eng__Average_Power_Proc(&CT1_ADC_Q);

		Apparent_Power[BUFFER_CT1] +=Power; 

		#if (CT_Sensor_DEBUG)
			printf("\n 1Ch = %ld ", Power );  //CT Sensor Power Data  원림
		#endif
		
	}
       else Apparent_Power[BUFFER_CT1]=0;
	   	
	 	
	if( (Get_Ct_Sensor&CT2_EXIST) )
	{		 	 		
		Power= Eng__Average_Power_Proc(&CT2_ADC_Q);
		
		Apparent_Power[BUFFER_CT2] +=Power;

		#if (CT_Sensor_DEBUG)
			printf("\n 2Ch = %ld", Power);  //CT Sensor Power Data  원림
		#endif
		
	}
       else Apparent_Power[BUFFER_CT2]=0;


	if( (Get_Ct_Sensor&CT3_EXIST) )
	{		 	 		
		Power= Eng__Average_Power_Proc(&CT3_ADC_Q);
		
		Apparent_Power[BUFFER_CT3] +=Power;

		#if (CT_Sensor_DEBUG)
			printf("\n 3Ch = %ld",Power);  //CT Sensor Power Data  원림
		#endif
		
	}
       else Apparent_Power[BUFFER_CT3]=0;


	#if (CT_Sensor_DEBUG)

	 printf("\n Sum = %ld  ", Apparent_Power[BUFFER_CT1] + Apparent_Power[BUFFER_CT2] + Apparent_Power[BUFFER_CT3] );

	#endif
  
}
/*
*********************************************************************************************************
*                                                           SendRF_Energy_Power_CT_Sensor  ( RTC  alarm interrupt , 1초 주기 ) 
*
* Description:      CT Sensor 로 부터 측정된 전력을  RF 무선으로 송신 한다.
*
* Arguments  :    NONE
*                       
* Returns      :     NONE
*
*********************************************************************************************************
*/

//extern U8 Receive_ACK;
// static
#define DIV_FOR_MINUTE 2
#define POWER_INTERVAL 22 /// 6 sec

extern void memory_test(void);
void SendRF_Energy_Power_CT_Sensor(void)
{
	//volatile  U32 idata Apparent_Power_Old, AD_Value;
	POWR_DATA 	sWeek;
	CPOWERS_AUG  Power;
    
	volatile  U32 idata Temp_Power;
       int i ; // cmlee
       U8 one_minute;

        one_minute = 0;
        
       if(fRTC_Run==RTC_RUN){
		RTC_ReadTime();	
        }

    	if(Get_One_Minute_Chk() ==FLAG_CLEAR) ;  //RTC Time 1 minute
    	else 
    	{
    	//printf(" \n 1 MINUTE");

        one_minute = 1;
        Put_One_Minute_Chk(FLAG_CLEAR);  //   1 minute flag Clear   
    	}
    	
	Energy_Monitor_For_Start_ADC();   // ADC 를  한다 
	Save_Buffer_Energy_Power();         //  소비 전력을 계산 한다 

      ///if(Energy_Scan_Count%50 == 0)  Led1_Blink_ms(1, 50); 

	if(++Energy_Scan_Count >= POWER_INTERVAL ){        // 5 회 측정 전력을 RF 로 전송 한다    	Battery 소모 전류로 5 -> 0로 변경 원림_140318

            Led1_Blink_ms(1, 50); 
            Energy_Min_Count++;

		Get_Ct_Sensor=Ct_Detect_Chk();
		Ct_Sensor_Count=0;  //printf(" ct=%d", (U16)Get_Ct_Sensor);

		Temp_Power=0L;

		switch(Get_Ct_Sensor)
		{
		   case CT1_EXIST:    
		   				Temp_Power= Apparent_Power[BUFFER_CT1] / (U32)Energy_Scan_Count ; 
						    //printf("\n DDDDDDDDDD %ld", Temp_Power);
		   				Apparent_Power[BUFFER_CT1] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT1] +=Apparent_Power[BUFFER_CT1];
						Apparent_Power[BUFFER_CT2]=NO_EXIST_POWER_VALUE;
						Apparent_Power[BUFFER_CT3]=NO_EXIST_POWER_VALUE;
						Ct_Sensor_Count=1;
						break;
		   case CT2_EXIST:    
		   				Temp_Power= Apparent_Power[BUFFER_CT2] /(U32)Energy_Scan_Count ; 
						    //printf("\n EEEEEEEEE %ld", Temp_Power);
		   				Apparent_Power[BUFFER_CT2] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT2] +=Apparent_Power[BUFFER_CT2];                            
						Apparent_Power[BUFFER_CT1]=NO_EXIST_POWER_VALUE;
						Apparent_Power[BUFFER_CT3]=NO_EXIST_POWER_VALUE;
						Ct_Sensor_Count=1;
						break;
		   case CT3_EXIST:    
		   				Temp_Power= Apparent_Power[BUFFER_CT3] /(U32)Energy_Scan_Count ; 
						    //printf("\n FFFFFFFFFFFFF %ld", Temp_Power);
		   				Apparent_Power[BUFFER_CT3] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT3] +=Apparent_Power[BUFFER_CT3];
						Apparent_Power[BUFFER_CT1]=NO_EXIST_POWER_VALUE;
						Apparent_Power[BUFFER_CT2]=NO_EXIST_POWER_VALUE;
						Ct_Sensor_Count=1;
						break;


		   case CT_1_2_EXIST:    
		   				Temp_Power= Apparent_Power[BUFFER_CT1] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT1] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT1] +=Apparent_Power[BUFFER_CT1];
                                    //printf("\n GGGGGGGGGG %ld", Temp_Power);

						Temp_Power=0L;
						
		   				Temp_Power= Apparent_Power[BUFFER_CT2] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT2] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT2] +=Apparent_Power[BUFFER_CT2];
						
						Apparent_Power[BUFFER_CT3]=NO_EXIST_POWER_VALUE;
						Ct_Sensor_Count=2;
						break;
		   case CT_2_3_EXIST:    
		   				Temp_Power= Apparent_Power[BUFFER_CT2] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT2] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT2] +=Apparent_Power[BUFFER_CT2];
                                    //printf("\n HHHHHHHH %ld", Temp_Power);

						Temp_Power=0L;

		   				Temp_Power= Apparent_Power[BUFFER_CT3] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT3] =Temp_Power ; 
						
						Apparent_Power[BUFFER_CT1]=NO_EXIST_POWER_VALUE;
		   				Minute_Power[BUFFER_CT3] +=Apparent_Power[BUFFER_CT3];
						Ct_Sensor_Count=2;
						break;
		   case CT_1_3_EXIST:    
		   				Temp_Power= Apparent_Power[BUFFER_CT1] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT1] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT1] +=Apparent_Power[BUFFER_CT1];
                                    //printf("\n ZZZZZZZZZZZZ %ld", Temp_Power);

						Temp_Power=0L;
						
		   				Temp_Power= Apparent_Power[BUFFER_CT3] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT3] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT3] +=Apparent_Power[BUFFER_CT3];
						
						Apparent_Power[BUFFER_CT2]=NO_EXIST_POWER_VALUE;
						Ct_Sensor_Count=2;
						break;
		   case THREE_PHASE_EXIST:
		   				Temp_Power= Apparent_Power[BUFFER_CT1] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT1] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT1] +=Apparent_Power[BUFFER_CT1];
                        //printf("\n XXXXXXXXXX BUFFER_CT1=%ld ", Temp_Power);

						Temp_Power=0L;

		   				Temp_Power= Apparent_Power[BUFFER_CT2] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT2] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT2] +=Apparent_Power[BUFFER_CT2];
                         //printf("\n XXXXXXXXXX BUFFER_CT2=%ld ", Temp_Power);

						Temp_Power=0L;
	
		   				Temp_Power= Apparent_Power[BUFFER_CT3] /(U32)Energy_Scan_Count ; 						
		   				Apparent_Power[BUFFER_CT3] =Temp_Power ; 
		   				Minute_Power[BUFFER_CT3] +=Apparent_Power[BUFFER_CT3];
                         //printf("\n XXXXXXXXXX BUFFER_CT3=%ld ", Temp_Power);
						
						Ct_Sensor_Count=3;
						break;
		   default:    
						Apparent_Power[BUFFER_CT1] = NO_EXIST_POWER_VALUE;
		   				Apparent_Power[BUFFER_CT2] = NO_EXIST_POWER_VALUE; 
						Apparent_Power[BUFFER_CT3] = NO_EXIST_POWER_VALUE;
						Ct_Sensor_Count=0;
						break;

		}
		///AD_Value=Adapter__Average_Power_Proc(&ADAPTER_ADC_Q);

		// RF_Send_AC_Power_Data( &Apparent_Power[0], (Ct_Sensor_Count&0x03), AD_Value );
	//printf("\n , SUM = , %ld   , CT1 = , %ld   , CT2 = , %ld   , CT3 = , %ld         ",( (Apparent_Power[0] + Apparent_Power[1] + Apparent_Power[2])),( Apparent_Power[0]), (Apparent_Power[1]),(Apparent_Power[2]));
      //printf("\n , MIN SUM = , %ld   ,MIN  CT1 = , %ld   ,MIN  CT2 = , %ld   ,MIN  CT3 = , %ld         ",( (Minute_Power[0] + Minute_Power[1] + Minute_Power[2])),( Minute_Power[0]), (Minute_Power[1]),(Minute_Power[2]));
			
	///	printf(" After Send AC \n"); 
		memset(&Apparent_Power[0], 0, sizeof(Apparent_Power));  //  버퍼 초기화  

		Energy_Scan_Count=0;

		//Led_Blink_ms(1, 30);
		
	}

	#ifdef DIV_FOR_MINUTE
	if(one_minute)
	{
	    one_minute =0;
	    if(Minute_Power[BUFFER_CT1] == 0 && Minute_Power[BUFFER_CT2] == 0 && Minute_Power[BUFFER_CT3] == 0) return;
        
            switch(Get_Ct_Sensor)
		  {
    		   case CT1_EXIST:
                    Minute_Power[BUFFER_CT1]/=(U32)Energy_Min_Count;
                  break;
                  case CT2_EXIST:
                    Minute_Power[BUFFER_CT2]/=(U32)Energy_Min_Count;
                  break;
                  case CT3_EXIST:
                    Minute_Power[BUFFER_CT3]/=(U32)Energy_Min_Count;
                  break;
                  case CT_1_2_EXIST:
                    Minute_Power[BUFFER_CT1]/=(U32)Energy_Min_Count;
                    Minute_Power[BUFFER_CT2]/=(U32)Energy_Min_Count;
                  break;
                  case CT_2_3_EXIST:
                    Minute_Power[BUFFER_CT2]/=(U32)Energy_Min_Count;
                    Minute_Power[BUFFER_CT3]/=(U32)Energy_Min_Count;
                  break;
                  case CT_1_3_EXIST:
                    Minute_Power[BUFFER_CT1]/=(U32)Energy_Min_Count;
                    Minute_Power[BUFFER_CT3]/=(U32)Energy_Min_Count;
                  break;
                  case THREE_PHASE_EXIST:
                    Minute_Power[BUFFER_CT1]/=(U32)Energy_Min_Count;
                    Minute_Power[BUFFER_CT2]/=(U32)Energy_Min_Count;
                    Minute_Power[BUFFER_CT3]/=(U32)Energy_Min_Count;
                  break;
                }
            //printf("\n 2 SUM= %ld, CT1 = , %ld   , CT2 = , %ld   , CT3 = , %ld         ",((( Minute_Power[0] + Minute_Power[1] + Minute_Power[2])/2)/100)*220, ( Minute_Power[0]/100)*220, (Minute_Power[1]/100)*220,(Minute_Power[2]/100)*220);
                Minute_Total_Power = ( Minute_Power[0] + Minute_Power[1] + Minute_Power[2]) * VOLTAGE;
                ///MS06_mode_req_set();
                //printf("\n SUM=%ld,  Minute_Power0 = , %ld   , Minute_Power1 = , %ld   , Minute_Power2 = , %ld         ",Minute_Total_Power, ( Minute_Power[0]), (Minute_Power[1]),(Minute_Power[2]));
                ///for(i=0; i < 2; i++) {};
                memset(&Minute_Power[0], 0, sizeof(Minute_Power));  //  버퍼 초기화  
		}
            #endif

		//Led_Blink_ms(1, 30);

}


 /*
*********************************************************************************************************
*                                                           adc 인터럽트 서비스 루틴 모음 
*
* Description:      adc 인터럽트에서 호출 하며  변환된 ADC mV 전압을  Q 버퍼에 저장한다 
*
* Arguments  :    void  
*
* Returns      :    NONE
*
*********************************************************************************************************
*/

static void CT1_Sensor__ADC0_Interrupt_Handler(void)
{
	idata volatile U32 mV;                         // measured voltage in mV

	static U32 mV_Old=0, mV_Delta=0;     

	static idata U8 Sample_Count=0;
	static idata double sumV=0;
	
	idata volatile  double sqV;
	idata volatile  U32 Apparent_Power;   	

	if( (Ct_Detect_Chk() & CT1_EXIST )==NO_EXIST|| (fEnergy_Power_Measuring_State & ENERGY_POWER_SAMPING_END_CT1 ))
	{ 		
			fEnergy_Power_Measuring_State |=ENERGY_POWER_SAMPING_END_CT1;
			return;   // CT Sensor 가 존재 하지 않으면  Return 한다 	
	}

	mV = ADC_Get_mV();
//	printf("Before mV1=%ld\n", mV);
		
//	if(mV <2)mV=0;
	

	if(mV > mV_Old)mV_Delta= mV       - mV_Old;
	else 		   mV_Delta= mV_Old - mV;

	if(mV_Delta > mV_Old*2){
						mV_Old =mV;
						mV=0;
	}
	else mV_Old =mV; 
	//printf("After mV1=%ld\n", mV);
	if(mV) 
	{				
		///printf("\n 111111 %ld", mV);			//CT SENSOR 소스 수정 부분 -> 순시 전력 측정- 원림
		
		sqV=(double)(mV*mV);
								
		sumV+=sqV;
					
		if( ++Sample_Count>=POWER_PHASE_SAMPLING ){			

			Apparent_Power=CT1_Eng__Real_Power_Proc( sumV, Sample_Count);
				
			Queue_Buffer_Put_32bit(&CT1_ADC_Q, Apparent_Power); 	
			
			Sample_Count=0;  
			sumV=0;
			fEnergy_Power_Measuring_State |=ENERGY_POWER_SAMPING_END_CT1;
		}
	}	

}



static void CT2_Sensor__ADC0_Interrupt_Handler(void)
{
	idata volatile U32 mV;                         // measured voltage in mV

	static U32 mV_Old=0, mV_Delta=0;

	static idata U8 Sample_Count=0;
	static idata double sumV=0;
	
	idata volatile  double sqV;
	idata  volatile U32 Apparent_Power;   

	if( (Ct_Detect_Chk() & CT2_EXIST )==NO_EXIST|| (fEnergy_Power_Measuring_State & ENERGY_POWER_SAMPING_END_CT2 ) )
	{ 		
			fEnergy_Power_Measuring_State |=ENERGY_POWER_SAMPING_END_CT2;
			return;   // CT Sensor 가 존재 하지 않으면  Return 한다 	
	}
	
	mV = ADC_Get_mV();  
//	printf("Before mV2=%ld\n", mV);
//	if(mV < 2) mV=0;


	if(mV > mV_Old)mV_Delta= mV       - mV_Old;
	else 		   mV_Delta= mV_Old - mV;

	if(mV_Delta > mV_Old*2){
						mV_Old =mV;
						mV=0;
	}
	else mV_Old =mV;
	///printf("After mV2=%ld\n", mV);

	if(mV) 
	{		
		sqV=(double)(mV*mV);
								
		sumV+=sqV;
			
		if(++Sample_Count>=POWER_PHASE_SAMPLING){

			Apparent_Power=CT2_Eng__Real_Power_Proc( sumV, Sample_Count);
	
			Queue_Buffer_Put_32bit(&CT2_ADC_Q, Apparent_Power); 	

			Sample_Count=0;  
			sumV=0;
			fEnergy_Power_Measuring_State |=ENERGY_POWER_SAMPING_END_CT2;
		}
	}	
}



static void CT3_Sensor__ADC0_Interrupt_Handler(void)
{
	idata volatile U32 mV;                         // measured voltage in mV

	static U32 mV_Old=0, mV_Delta=0;

	static idata U8 Sample_Count=0;
	static idata double sumV=0;
	
	idata  volatile double sqV;
	idata  volatile U32 Apparent_Power;   


	if( (Ct_Detect_Chk() & CT3_EXIST )==NO_EXIST|| (fEnergy_Power_Measuring_State & ENERGY_POWER_SAMPING_END_CT3 ))
	{ 		
			fEnergy_Power_Measuring_State |=ENERGY_POWER_SAMPING_END_CT3;
			return;   // CT Sensor 가 존재 하지 않으면  Return 한다 	
	}
	
	mV = ADC_Get_mV();  
	//printf("Before mV3=%ld\n", mV);

//	if(mV < 2) mV=0;
	
	if(mV > mV_Old)mV_Delta= mV       - mV_Old;
	else 		   mV_Delta= mV_Old - mV;

	if(mV_Delta > mV_Old*2){
						mV_Old =mV;
						mV=0;
	}
	else mV_Old =mV;
	//printf("After mV3=%ld\n", mV);

	if(mV) 
	{		
		sqV=(double)(mV*mV);
								
		sumV+=sqV;
			
		if(++Sample_Count>=POWER_PHASE_SAMPLING){
			
			Apparent_Power=CT3_Eng__Real_Power_Proc( sumV, Sample_Count);
	
			Queue_Buffer_Put_32bit(&CT3_ADC_Q, Apparent_Power); 	

			Sample_Count=0;  
			sumV=0;
			fEnergy_Power_Measuring_State |=ENERGY_POWER_SAMPING_END_CT3;
		}
	}	
}

