#include "sdk_common.h"
#include "SEGGER_RTT.h"
#include "nrf_drv_pwm.h"
#include "usr_config.h"
#include "nrf_drv_wdt.h"
#include "nrf_delay.h"
#include "exception.h"
#include "system.h"
#include "bsp_time.h"
#include "bsp_wdt.h"

static uint32_t feed_dog_time = 0;

nrf_drv_wdt_channel_id m_channel_id;

uint32_t Get_FeedWatchDogTime(void)
{
	return feed_dog_time;
}

void feed_watchdog(void)
{
	feed_dog_time = NRF_RTC0->COUNTER;
  nrf_drv_wdt_channel_feed(m_channel_id); 
}

/**
 * @brief WDT events handler.
 */
void wdt_event_handler(void)
{
	DEBUG_LOG("wdt_event_handler:%d\n",TIME_GetTicks());
	Except_Unkown_Reset_WDT_Set();
}

static void WatchDog_Process(void)
{
	 feed_watchdog();
//	 DEBUG_LOG("WatchDog_Process:%d\n",TIME_GetTicks());
}

static void bsp_wdt_init_process(void)
{
	if(Except_TxError(EXCEPT_WDT_INIT,"bsp_wdt_init_error\r\n") == 0)
	{
		Process_Stop(bsp_wdt_init_process);
	}
}

void watchdog_init(void){
	
	int 				ret = 0;
	ret_code_t 	errCode;
	
	nrf_drv_wdt_config_t config = NRF_DRV_WDT_DEAFULT_CONFIG;
	config.interrupt_priority = WDT_IRQ_PRIORITY;
	config.reload_value = WDT_RELOAD_VALUE;
	errCode = nrf_drv_wdt_init(&config, wdt_event_handler);
	if(errCode != NRF_SUCCESS)ret = -1;
	
	errCode = nrf_drv_wdt_channel_alloc(&m_channel_id);
	if(errCode != NRF_SUCCESS)ret = -1;
	
	nrf_drv_wdt_enable();

	Process_Start(1000,"WatchDog",WatchDog_Process);
	
	if(ret == -1)
	{
		Process_Start(0,"bsp_wdt_init",bsp_wdt_init_process);
	}
}

