#include "common.h"
#include "delay.h"
#include "drv_usart.h"
#include "drv_usart_2.h"
#include "drv_io.h"
#include "drv_can.h"
#include "measure_temprature.h"
#include "app_rs485_1.h"
#include "app_rs485_2.h"
#include "app.h"
#include "app_can.h"
#include "app_bms_1.h"
#include "app_bms_2.h"
#include "app_end_ctr.h"
#include "app_adas.h"
#include "low_power.h"
#include "hardware_test.h"
#include "shark_xl.h"
#include "shark_charge.h"

shark_u64 shark_mseconds;
shark_u32 shark_seconds;
shark_u16 shark_msecond;

shark_u64 shark_get_time_safe(void)
{
	u64 time = shark_mseconds;
	shark_uart_poll_safe();
	return time;
}

void systick_close(void)
{
	//close tick
	
	SysTick->CTRL  &= ~SysTick_CTRL_TICKINT_Msk;
	SysTick->CTRL  &= ~SysTick_CTRL_ENABLE_Msk;

}

void delay_1us(uint16_t cnt)
{
	uint32_t  count = 3*cnt;
	while(count--); 
}

/*!
    \brief      configure systick
    \param[in]  none
    \param[out] none
    \retval     none
*/

void systick_config(void)
{
	if (SysTick_Config(SystemCoreClock / 1000))
	{ 
		/* Capture error */ 
		while (1);
	}
    NVIC_SetPriority(SysTick_IRQn, 0x00U);
}

/*!
    \brief      delay a time in milliseconds
    \param[in]  count: count in milliseconds
    \param[out] none
    \retval     none
*/
void delay_1ms(uint32_t count)
{
	uint64_t time = shark_mseconds + count;

	while (time > shark_mseconds) {
		fwdgt_counter_reload();
	}
}

#if 0
/*!
    \brief      delay decrement
    \param[in]  none
    \param[out] none
    \retval     none
*/
void delay_decrement(void)
{
    if (0 != delay){ 
        delay--;
    }
}
#endif

void shark_second_tick(void)
{
	Measure_Temprature_Delay();
	Save_Param_Time_Out();
}

void SysTick_Handler(void)
{
	shark_mseconds++;

	if (shark_msecond < 1000) {
		shark_msecond++;
	} else {
		shark_msecond = 0;
		shark_seconds++;
		shark_second_tick();
	}

	shark_uart_tick();
	shark_xl_tick();
	shark_charge_tick();

	ACC2_PWM();
	
	if(side_stay_dec_delay.set)
		side_stay_dec_delay.count++;
	if(soak_dec_delay.set)
		soak_dec_delay.count++;
	if(sti_dec_delay.set)
		sti_dec_delay.count++;
	if(repair_dec_delay.set)
		repair_dec_delay.count++;
	if(qd_dec_delay.set)
		qd_dec_delay.count++;
	if(acc2_dec_delay.set)
		acc2_dec_delay.count++;
	
	
	
	if(left_light_delay.set)
	{
		++left_light_delay.count;
		if(left_light_delay.count >= ZONG_TIME)
		{
			Left_Light_Enable(1);
			left_light_delay.count = 0;
		}
		else if(left_light_delay.count >= LIANG_TIME)
		{
			Left_Light_Enable(0);
		}
	}
	if(right_light_delay.set)
	{
		++right_light_delay.count;
		if(right_light_delay.count >= ZONG_TIME)
		{
			Right_Light_Enable(1);
			right_light_delay.count = 0;
		}
		else if(right_light_delay.count >= LIANG_TIME)
		{
			Right_Light_Enable(0);
		}
	}



	Bms_1_Self_Send_Timeout();

	Bms_2_Self_Send_Timeout();

	End_Ctr_Self_Send_Timeout();

	ADAS_Timeout();

	Series_Delay_Timeout();

	Enter_Sleep_Delay_Timeout();

	HT_Reboot_Timeout();
	
}




