#include "bsp/bsp.h"
#include "bsp/bsp_driver.h"
#include "libs/logger.h"
#include "os/os_types.h"
#include "version.h"

extern void system_clock_config(void);
static void wdog_enable(void);

void bsp_init(void){
	system_clock_config();
	wdog_enable();
	debug_periph_mode_set(DEBUG_TMR1_PAUSE, TRUE);
	nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
	systick_open();
	task_ticks_enable();
	gpio_pin_init();
	shark_uart_init(SHARK_UART0);
}


void system_reboot(void){
	NVIC_SystemReset();
}

void systick_close(void)
{
	SysTick->CTRL  &= ~SysTick_CTRL_ENABLE_Msk;
}

void systick_open(void)
{
	systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV);
	SysTick_Config(system_core_clock / 1000);
	NVIC_SetPriority(SysTick_IRQn, 0x00U);
}

u8 mcu_chip_id(u8 *buff)
{
	u32 values[] = { REG32(0x1FFFF7E0), REG32(0x1FFFF7E8), REG32(0x1FFFF7EC), REG32(0x1FFFF7F0) };
	memcpy(buff, values, sizeof(values));
	return sizeof(values);
}

u32 get_mcu_reset_source(void)
{
	uint32_t reset_source = CRM->ctrlsts;
	CRM->ctrlsts_bit.rstfc = TRUE;
	return reset_source;
}

void wdog_reload(void){
#if CONFIG_DEBUG == 0
    wdt_counter_reload();
#endif    
}

static void wdog_enable(void)
{
#if CONFIG_DEBUG == 0  
	/* disable register write protection */
	 wdt_register_write_enable(TRUE);
	
	 /* set the wdt divider value */
	 wdt_divider_set(WDT_CLK_DIV_64);
	
	 /* set reload value
	
	  timeout = reload_value * (divider / lick_freq )	 (s)
	
	  lick_freq    = 40000 Hz
	  divider	   = 4
	  reload_value = 30000
	
	  timeout = 3000 * (64 / 40000 ) = 4.8s = 4800ms
	 */
	 wdt_reload_value_set(3000 - 1);
	
	 /* reload wdt counter */
	 wdt_counter_reload();
	 
	 /* enable wdt */
	 wdt_enable();
#endif
}

int wdog_set_timeout(int wdog_time)
{  
	return 0;
}


