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

static void wdog_enable(void);
#define DGB_TIM1_STOP (1<<10)
#define DGB_TIM8_STOP (1<<17)

static void dbg_stop_tim1_8(void) {
    __IO uint32_t *p = (uint32_t*)0xE0042004;
    *p |= DGB_TIM1_STOP;
    *p |= DGB_TIM8_STOP;
}
void bsp_init(void){
	wdog_enable();
	SystemCoreClockUpdate();
	dbg_stop_tim1_8();
	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_Config(SystemCoreClock / 1000);
}

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

static u32 _mcu_rst_status = 0xFFFFFFFF;
u32 get_mcu_reset_source(void)
{
	if (_mcu_rst_status == 0xFFFFFFFF) {
		_mcu_rst_status = RCC->CTRLSTS;
		RCC_ClrFlag();
	}
	return _mcu_rst_status;
}

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

static void wdog_enable(void)
{
#if CONFIG_DEBUG == 0  
    /* IWDG timeout equal to 250 ms (the timeout may varies due to LSI frequency
       dispersion) */
    /* Enable write access to IWDG_PR and IWDG_RLR registers */
    IWDG_WriteConfig(IWDG_WRITE_ENABLE);
    /* IWDG counter clock: LSI/32 */
    IWDG_SetPrescalerDiv(IWDG_PRESCALER_DIV128);
    /* Set counter reload value to obtain 250ms IWDG TimeOut.
       Counter Reload Value = 250ms/IWDG counter clock period
                            = 250ms / (LSI/32)
                            = 0.25s / (LsiFreq/32)
                            = LsiFreq/(32 * 4)
                            = LsiFreq/128
     */
    IWDG_CntReload(1600);
    /* Reload IWDG counter */
    IWDG_ReloadKey();
    /* Enable IWDG (the LSI oscillator will be enabled by hardware) */
    IWDG_Enable();
#endif    
}

int wdog_set_timeout(int wdog_time)
{  
	return 0;
}


