/*
 * watchdog.c
 *
 *  Created on: 2018Äê7ÔÂ13ÈÕ
 *      Author: Think
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#include <sys/ioctl.h>
#include <linux/watchdog.h>
#include "watchdog.h"

#define WATCHDOG_DEV	"/dev/watchdog"

static int watch_fd = -1;

static void catch_int(int signum)
{
	printf("In signal handler\r\n");
	watchdog_close();
	exit(0);
}

int watchdog_init(void)
{
	int data = 0;
    int ret_val = 0;

	watch_fd = open(WATCHDOG_DEV, O_WRONLY);
	if (watch_fd == -1) {
		//LOG_printf(LOG_ERROR, "Watchdog init error!\r\n");
		return -1;
	}

    ret_val = ioctl (watch_fd, WDIOC_GETTIMEOUT, &data);
    if (ret_val) {
    	//LOG_printf(LOG_ERROR, "Watchdog Timer : WDIOC_GETTIMEOUT failed\r\n");
    }
    else {
    	//LOG_printf(LOG_DBG_COLLECTOR_RAW, "Current timeout value is : %d seconds\r\n", data);
    }

    signal(SIGINT, catch_int);

	return 0;
}

int watchdog_close(void)
{
	int ret_val = 0;
	int flags = WDIOS_DISABLECARD;

	if (watch_fd > 0)
	{
		ret_val = ioctl(watch_fd, WDIOC_SETOPTIONS, &flags);
		if (ret_val)
		{
	    	//LOG_printf(LOG_ERROR, "Watchdog WDIOS_DISABLECARD failed\r\n");
	    	return -1;
		}
		else if (0 != close (watch_fd))
		{
			//LOG_printf(LOG_ERROR, "Watchdog close failed\r\n");
			return -1;
		}

		watch_fd = -1;
	}

	return 0;
}

int watchdog_refresh(int timeout)
{
    int ret_val = 0;

    if (watch_fd <= 0)
    {
    	return -1;
    }

    ret_val = ioctl (watch_fd, WDIOC_KEEPALIVE, NULL);
    if (ret_val) {
    	//LOG_printf(LOG_ERROR, "Watchdog Timer : WDIOC_KEEPALIVE failed\r\n");
    	return -1;
    }
    else {
    	//LOG_printf(LOG_DBG_COLLECTOR_RAW, "watchdog keep alive\r\n");
    }

    return 0;
}

