/*
 ******************************************************************************
 *
 * @file     bat.c
 * @brief    Voltage-based RC model gauge algorithm 
 *                 
 *
 * @version  1.0
 * @date     2023/02/20   17:35:40
 * @author   Alex Xu
 *
 * Copyright (c) 2013-2099,Tkplusemi Technology Co.,Ltd.
 * All Rights Reserved
 *
 * History:
 * Revision          Date           Author            Desc
 * 1.0.0            2023/02/20      Alex          build this file
 ******************************************************************************
 */
#include "bat.h"
#include "adc.h"
#include "userapp.h"
#include "led.h"
#include "system.h"
#include "vox_module.h"
#include "sleep.h"

idata uint8_t bat_level = 0;
//bit F_batlevel_low = 0;				//电池低压

#if BAT_VALUE

#define C_offset_bat_level_MAX  		60
#define C_offset_bat_level_MIN  		10

#define C_bat_level_protect     		0
#define C_bat_level_lowpower     		1


bit F_batlevel_protect = 0;			//低电保护
idata uint8_t offset_bat_level = ( C_offset_bat_level_MAX + C_offset_bat_level_MIN ) / 2;


#define C_batLevel_SetMax   11

/*充电电池电压会浮高,具体电压需要测试。*/
const uint16_t Boost_batlevel_Threshold[C_batLevel_SetMax] = 
{
#if 1
	/*实际测试电压会有偏差，原因：adc误差在50mV左右。*/
	3200,	//0
	//3300,	//5%
	3450,	//10%
	3510,	//20%
	3575,	//30%
	3630,	//40%
	3700,	//50%
	3785,	//60%
	3875,	//70%	
	4000,	//80%	
	4100,	//90%	
	4200   //100%  

#else
	/*实际测试电压会有偏差，原因：adc误差在50mV左右。*/
	3200,	//0
	//3300,	//5%
	3450,	//10%
	3510,	//20%
	3554,	//30%
	3590,	//40%
	3690,	//50%
	3775,	//60%
	3875,	//70%	
	4000,	//80%	
	4100,	//90%	
	4200   //100%    

#endif
};

void check_bat_level(void)
{
    uint8_t i = 0;
	
    //get bat level
#if ADC_ENABLE

	for(i=0; i < C_batLevel_SetMax; i++)
	{	
		if( Vbat_Adc < Boost_batlevel_Threshold[i] )
		{
			break;
		}
	}
	
#endif

	if( i > bat_level )
   	{
   	   	offset_bat_level++;
   	}
   	else 
   	{
   	   	offset_bat_level--;
   	}
    
    //debounce
   	if( (offset_bat_level > C_offset_bat_level_MAX) || (offset_bat_level < C_offset_bat_level_MIN) )
   	{
   	   	//update
   	   	bat_level = i;
		
		/*系统重启后，显示电量*/
		if( System_Init_Flag )
		{
			System_Init_Flag = 0;

			if( Vbat_Adc < Boost_batlevel_Threshold[1] )
			{
				bat_level = 0;
			}
			else
			{
				bat_level = i;
			}
			
#if LED_188
			g_188_Num = 10 * bat_level;

			Display_Show_Num(g_188_Num);
			
			/*初始化显示电量*/

			CHG_LED_Disp_Flag = 1;   

			Init_LED_Disp_Flag = 1;

		//	Enter_Sleep_Cnt_Restart_Flag = 1;
#endif
		}	
		
   	   	offset_bat_level = ( C_offset_bat_level_MAX + C_offset_bat_level_MIN ) / 2;
   	}    
	 
    if( bat_level <= C_bat_level_protect )
    {
        F_batlevel_protect = 1;
    }
    else if( bat_level > ( C_bat_level_protect + 1 ) )
    {
        F_batlevel_protect = 0;
    }
	
#if 0  

    if( bat_level <= C_bat_level_lowpower )
    {
        F_batlevel_low = 1;
    }
    else if( bat_level > (C_bat_level_lowpower + 1) )
    {
        F_batlevel_low = 0;
    }  
 #endif   	
}

#endif
