#include <soc.h>
#include <drv/wdt.h>
#include "app_wdt.h"
/**
 * The exact time-out can be calculated according to the formula
 * freq = 67500000 Hz
 * user changeable para is 10 (range is 0 ~ 15)
 * 994ms = ((0x10000 << 10)/ (67500000 / 1000))
 */
#define WDT_TIMEOUT_MS                  (994U)               ///< timeout: 0.94s

static csi_wdt_t g_wdt_handle;

static void wdt_event_cb_fun(csi_wdt_t *wdt, void *arg)
{
    (void)arg;
    csi_wdt_feed(wdt);
    // printf("enter cb fun\n");
}

static int32_t app_wdt_enable(void)
{
    int32_t ret = 0;
    int32_t state;

    ///<!!! if wdt attach callback, system only enter irq, can not system reset
    state = csi_wdt_attach_callback(&g_wdt_handle, wdt_event_cb_fun, NULL);
    if (state < 0) {
        printf("csi_wdt_attach_callback error\n");
        ret = -1;
    }

    state = csi_wdt_set_timeout(&g_wdt_handle, WDT_TIMEOUT_MS);

    if (state < 0) {
        printf("csi_wdt_set_timeout error\n");
        ret = -1;
    }

    state = csi_wdt_start(&g_wdt_handle);

    if (state < 0) {
        printf("csi_wdt_start error\n");
        ret = -1;
    }

    return ret;
}

void app_wdt_reset(void)
{
    ///<!!! if wdt detach callback, system only system reset
//    csi_wdt_detach_callback(&g_wdt_handle);
//	csi_wdt_uninit(&g_wdt_handle);
    csi_system_reset();
}

int app_wdt_init(void)
{
    int ret = 0;
    int32_t state;
    state = csi_wdt_init(&g_wdt_handle, 0U);
    if (state < 0) {
        printf("csi_wdt_init error\n");
        ret = -1;
    }

    state = app_wdt_enable();
    if (state < 0) {
        printf("test_wdt_feed error\n");
        ret = -1;
    }
	
    return ret;
}
void app_feed_wdt(void)
{
	csi_wdt_feed(&g_wdt_handle);
}