/**
 * \file    drv_wdt.c
 * \brief   watchdog timer definition
 *
 * \par     Copyright (c) 2018 UWE Technologies Corp., Ltd. All Rights Reserved.
 * \author  James
 * \date    2018-03-17
 * \version 
 * 
 * \history 
 *  Date        Note
 *  2018-03-17  Original Creation
 * 
 */

#include "arch.h"
#include "drv_wdt.h"
#include "utils.h"
#include "drv_reg_intf.h"
#include "reg_def_wdt.h"
#include "reg_def_flash.h"
#include "sync.h"

volatile u8_t g_wdt_rst_record = 0;
volatile u8_t g_wdt_rst_record_read_flg = 0;

void drv_wdt_feed(void)
{
    if (DRV_REG_GET(WDT_CTRL_REG) & WDT_CTRL_REG_WDT_ENA_FLDSET)
    {
        sync_enter_critical();
        // Disable flash program
        u32_t restore = DRV_REG_GET(FLASH_CTRL_REG);
        DRV_REG_SET(FLASH_CTRL_REG, restore & FLASH_CTRL_REG_FLASH_PRG_ENA_FLDMSK);
        DRV_REG_SET(WDT_CTRL_REG, 0);
        DRV_REG_SET(WDT_CTRL_REG, WDT_CTRL_REG_WDT_ENA_FLDSET | WDT_CTRL_REG_WDT_MODE_FLDSET);
        // Restore flash operation
        DRV_REG_SET(FLASH_CTRL_REG, restore);
        sync_exit_critical();
    }
}

void drv_wdt_init(u32_t timeout, bool_t enable)
{
    u32_t reload = (double)1000000 / drv_chip_clock_tick_get() * timeout;

    DRV_REG_SET(WDT_LDCNT_REG, reload);

    if (!g_wdt_rst_record_read_flg)
    {
        g_wdt_rst_record = (DRV_REG_GET(WDT_CTRL_REG) & WDT_CTRL_REG_WDT_RST_RECORD_FLDSET) ? TRUE : FALSE;
        g_wdt_rst_record_read_flg = TRUE;
    }

    if (enable)
    {
        /* start the wdt */
        DRV_REG_SET(WDT_CTRL_REG, WDT_CTRL_REG_WDT_ENA_FLDSET | WDT_CTRL_REG_WDT_MODE_FLDSET);
    }
    else {
        DRV_REG_SET(WDT_CTRL_REG, 0);
    }
}

u32_t drv_wdt_timeout_get(void)
{
    return (double)DRV_REG_GET(WDT_LDCNT_REG) / 1000000 * drv_chip_clock_tick_get();
}


