#include "bsp/bsp.h"
#include "bsp/gd32_bkp.h"
#include "libs/logger.h"
#include "os/os_types.h"
#include "bsp/uart.h"
#include "bsp/timer_count32.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);
	//dbg_periph_enable(DBG_TIMER2_HOLD);
	//dbg_periph_enable(DBG_TIMER3_HOLD);
	systick_open();
	task_ticks_enable();
	timer_count32_init();
	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);
}


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;
}


