#include "bsp.h"

/*************************************************************
 * 定时器功能
 *************************************************************/
 
 
/* 计时器的计数值 */
volatile u32    g_clock_ms = 0;
bit s1_flag=0;
bit ms100_flag = 0;
bit rs485_recv_timeout_flag = 0;
bit rs485_recv_timeout_check_flag = 0;
u8 rs485_timeout_cnt = 0;
bit timeout_flag=0;
bit timeout_enable=0;
static u16 timeout_countdown=0;
void reset_timeout_countdown(u16 count)
{
	timeout_enable = 1;
	timeout_flag=0;
	timeout_countdown=count;
}
void stop_timeout_countdown(void)
{
	timeout_enable = 0;
}
void reset_rs485_recv_timeout(void)
{
	rs485_recv_timeout_check_flag=1;
	rs485_recv_timeout_flag = 0;
	rs485_timeout_cnt = 0;
}

bit rs485_has_recv_timeout(void)
{
	if(rs485_recv_timeout_check_flag && rs485_recv_timeout_flag)
	{
		rs485_recv_timeout_check_flag = 0;
		rs485_timeout_cnt = 0;
		return 1;
	}
	else
	{
		return 0;
	}
}
bit rs485_recv_timeout_flag2 = 0;
bit rs485_recv_timeout_check_flag2 = 0;
u8 rs485_timeout_cnt2 = 0;
void reset_rs485_recv_timeout2(void)
{
	rs485_recv_timeout_check_flag2=1;
	rs485_recv_timeout_flag2 = 0;
	rs485_timeout_cnt2 = 0;
}

bit rs485_has_recv_timeout2(void)
{
	if(rs485_recv_timeout_check_flag2 && rs485_recv_timeout_flag2)
	{
		rs485_recv_timeout_check_flag2 = 0;
		rs485_timeout_cnt2 = 0;
		return 1;
	}
	else
	{
		return 0;
	}
}
void hal_timer_init(void)
{
  TCON1 = 0x00;						//Tx0定时器时钟为Fosc
	TMOD = 0x00;						//16位重装载定时器/计数器

	//Tim0计算时间 	= (65536 - 0xCBEB) * (1 / (Fosc /Timer分频系数))
	//				= 13333 / (16000000 / 12)
	//				= 10 ms

	//定时1ms
	//反推初值 	= 65536 - ((1/1000) / (1/(Fosc / Timer分频系数)))
	//		   	= 65536 - ((1/1000) / (1/(16000000 / 12)))
	//			= 65536 - 1333
	//			= 0xFACB
	TH0 = 0xFA;
	TL0 = 0xCB;							//T0定时时间1ms
	IE |= 0x02;							//打开T0中断
	TCON |= 0x10;						//使能T0

//	/* T1 40 ms */
//	TH1 = 0x2F;
//	TL1 = 0xAB;
//	IE |= 0x08;							//
//	TCON |= 0x40;						//
	
	EA = 1;
	
	
}

void TIMER0_Rpt(void) interrupt TIMER0_VECTOR
{
	g_clock_ms ++;
	if(rs485_recv_timeout_check_flag)
	{
		rs485_timeout_cnt ++;
		if(rs485_timeout_cnt>5)
		{
			rs485_recv_timeout_flag = 1;
		}
	}
	if(timeout_enable == 1){
		if(timeout_countdown >0) timeout_countdown --;
		else timeout_flag = 1;
	}else{
		timeout_flag = 0;
	}
	if(rs485_recv_timeout_check_flag2)
	{
		rs485_timeout_cnt2 ++;
		if(rs485_timeout_cnt2>2)
		{
			rs485_recv_timeout_flag2 = 1;
		}
	}
	if((g_clock_ms % 80) == 0){
		ms100_flag = 1;
	}

	if((g_clock_ms % 1000) == 0){
		s1_flag = 1;
	}
	TCON &=~0x20;
}

//volatile u32 tmp = 0;
//void TIMER1_Rpt(void) interrupt TIMER1_VECTOR
//{
//	tmp ++;
//	if(tmp == 100) {
//		if(g_adc_cb != NULL) {
//			g_adc_cb();/* 每隔40ms调用一次此函数，采样电池电压 */
//		}
//		tmp = 0;
//	}
//	TCON &=~0x80;
//}
