/*
 ******************************************************************************
 *
 * @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"

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

#if BAT_VALUE

#define C_offset_bat_level_MAX  		50
#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   10

/*充电电池电压会浮高,具体电压需要测试。*/
const uint16_t Boost_batlevel_Threshold[C_batLevel_SetMax] = 
{
    3200,   //1
    3300,	//2
    3400,   //3
    3660,	//4
    3730,	//5
    3800,   //6
    3900,	//7
    3980,	//8
    4050,   //9
    4200   //10   
};

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;
   	   	offset_bat_level = ( C_offset_bat_level_MAX + C_offset_bat_level_MIN ) / 2;
   	}    
 #if 0  
    if( bat_level <= C_bat_level_protect )
    {
        F_batlevel_protect = 1;
    }
    else if( bat_level > ( C_bat_level_protect + 1 ) )
    {
        F_batlevel_protect = 0;
    }
 #endif   
    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
