#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);

void bsp_init(void){
	wdog_enable();
	gd32_bkp_init();
	dbg_periph_enable(DBG_TIMER0_HOLD);
	dbg_periph_enable(DBG_TIMER1_HOLD);
	nvic_priority_group_set(NVIC_PRIGROUP_PRE4_SUB0);
	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 = RCU_RSTSCK;
		rcu_all_reset_flag_clear();
	}
	return _mcu_rst_status;
}

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

static void wdog_enable(void)
{
#if CONFIG_DEBUG == 0  

	/* enable IRC40K */
	rcu_osci_on(RCU_IRC40K);

	/* wait till IRC40K is ready */
	while(SUCCESS != rcu_osci_stab_wait(RCU_IRC40K)){
	}  

	/* confiure FWDGT counter clock: 40KHz(IRC40K) / 256 = 0.15625 KHz */
	fwdgt_config(4*40000UL/256, FWDGT_PSC_DIV256);  
	/* after 4 seconds to generate a reset */
	fwdgt_enable();
#endif    
}

/* write value to FWDGT_RLD_RLD bit field */
#define RLD_RLD(regval)             (BITS(0,11) & ((uint32_t)(regval) << 0))

int wdog_set_timeout(int wdog_time)
{  
#if CONFIG_DEBUG == 0
	uint32_t flag_status = RESET;
	uint32_t timeout = FWDGT_RLD_TIMEOUT;
    /* enable write access to FWDGT_PSC,and FWDGT_RLD */
    FWDGT_CTL = FWDGT_WRITEACCESS_ENABLE;
  
    /* wait until the RUD flag to be reset */
    do{
        flag_status = FWDGT_STAT & FWDGT_STAT_RUD;
    }while((--timeout > 0U) && (RESET != flag_status));
   
    if (RESET != flag_status){
        return -1;
    }
    
    FWDGT_RLD = RLD_RLD(wdog_time*40000UL/256);

    /* reload the counter */
    FWDGT_CTL = FWDGT_KEY_RELOAD;
#endif
	return 0;
}


