//=============================================================================
// (c) Copyright 2009 Diamond Systems Corporation. Use of this source code
// is subject to the terms of Diamond Systems' Software License Agreement.
// Diamond Systems provides no warranty of proper performance if this
// source code is modified.
//
// File: Watchdog.c   v6.00
// Desc: Sample program that demonstrates how to use the watchdog
// Created by KL, James Moore
//=============================================================================

#include <stdio.h>

#ifdef _WIN32
#ifndef _WIN32_WCE
#include <conio.h>
#endif

#include <windows.h>
#include <stdlib.h>
#include <math.h>
// diamond driver includes
#include "..\dscud.h"
#endif

// DOS
#ifdef __BORLANDC__
#include <conio.h>
#include <dos.h>
#include <stdlib.h>
#include <math.h>
// diamond driver includes
//#include "../../../../current/dev/source/dscud.h"
#include "..\..\dscud.h"
#endif

// Linux and QNX
#if defined(linux) || defined(__QNXNTO__) || defined(_WRS_VXWORKS_5_X)
#include <stdlib.h>
#include <math.h>
#include <time.h>
// diamond driver includes
#include "dscud.h"


#ifdef _WRS_VXWORKS_5_X
#include <selectLib.h>
#define main HeliosWatchdog
#else
#include <sys/time.h>
#endif

static int kbhit()
{
	struct timeval timeout;
	fd_set rfds;

	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	FD_ZERO(&rfds);
	FD_SET(0, &rfds);

	if ( select(0+1, &rfds, NULL, NULL, &timeout) > 0 )
		return getchar();

	return 0;
}
#endif

// var declarations
BYTE result; // returned error code
DSCB dscb;   // handle used to refer to the board
DSCCB dsccb; // structure containing board settings
ERRPARAMS errorParams;  // structure for returning error code and error string
float floatBuff;        // temp variable of size float
int intBuff;        // temp variable of size int
BYTE RebootTimer;  // timer program value

#define HELIOS_DEFAULT_BASE_ADDRESS 0x280

char input_buffer[20]; // Buffer for parsing user character input.

//=============================================================================
// Name: main()
// Desc: Starting function that calls the driver functions used
//
//		 NOTE: By convention, you should capture the BYTE return value for each
//		 driver API call, and check the error code.
//
//     STEPS TO FOLLOW:
//
//	     I. Driver Initialization
//	    II. Board Initialization
//	   III. Watchdog Setup & Run
//	    IV. Cleanup
//
//=============================================================================

int main( int argc, char ** argv )
{
	//=========================================================================
	// I. DRIVER INITIALIZATION
	//
	//    Initializes the DSCUD library.
	//
	//    STEPS TO FOLLOW:
	//
	//	  1. initialize the driver, using the driver version for validation
	//=========================================================================

	if( dscInit( DSC_VERSION ) != DE_NONE )
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscInit error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}

	//=========================================================================
	// II. BOARD INITIALIZATION
	//
	//	   Initialize the HELIOS board. This function passes the various
	//	   hardware parameters to the driver and resets the hardware.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. set the board type to DSC_HELIOS for HELIOS board
	//	   2. set the base address to 0x280
	//	   3. set the interrupt level 5
	//	   4. intialize and register the board with the driver, after which
	//		  the struct, dscb, now holds the handle for the board
	//=========================================================================

	printf( "\nHELIOS BOARD INITIALIZATION:\n" );

	if(argc == 1)
	{
	    printf ( "Enter the base address (default 0x280, hit ENTER) : " );
	    fgets ( input_buffer, 20, stdin );
	    if ( input_buffer[0] == '\n' )
	    {
		dsccb.base_address = HELIOS_DEFAULT_BASE_ADDRESS;
	    }
	    else
	    {
		sscanf ( input_buffer, "%hx", &dsccb.base_address );
	    }
	}else
	{
		sscanf(argv[1], "%hx", &dsccb.base_address );
	}
	dsccb.int_level = 5;

	if(dscInitBoard(DSC_HELIOS, &dsccb, &dscb)!= DE_NONE)
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscInitBoard error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}

	//=========================================================================
	// III. Watchdog Setup & Run
	//
	//	    Setup and enable the HELIOS Watchdog timer. Once the timer
	//		hits the threshold it will shutdown the HELIOS
	//
	//	    STEPS TO FOLLOW:
	//
	//	    1. set the 4-bit timer value
	//			NOTE: This timer can achieve a max of 2.1 seconds delay.
	//	    2. set the watchdog timer options
	//			NOTE: The macros for this parameter are in DSCUD.H. Please 
	//			      refer to DSCUD.H for more details.
	//	    4. enable watchdog
	//=========================================================================

	if(argc <= 2)
	{
		printf("Enter value of timer (max of 2.175 seconds, integer values 0-9): ");
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[2], "%f", &floatBuff);
	}
	RebootTimer = intBuff;  // Timer has a range of 0.0 sec to 2.1 sec,
				// with a resolution of 2.175 s / 16 or
				// 145 milli-seconds. 16 is 0xF0.

	printf("Enter which WatchDog timer you wish to use (0 or 1): ");
        scanf("%d", &intBuff);

// User wishes to use WatchDog timer 1
	if ( intBuff == 0 )
	{	
		if( dscWatchdogEnable(dscb, 4, 0, 0xD0 ) != DE_NONE)
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscWatchdogEnable error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
			return 0;
		}
	}
	else // user wishes to use WatchDog timer 2
	{
		if( dscWatchdogEnable(dscb, 0, RebootTimer, 0xD0 ) != DE_NONE)
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscWatchdogEnable error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
			return 0;
		}
	}


	// To disable watchdog uncomment the following code
	//
	// dscWatchdogDisable(dscb);
	//


	// To retrigger watchdog uncomment the following code
	//
	// NOTE: By retriggering the watchdog, all timers on the watchdog is reset
	// to the initial enabled values.
	//
	// This example code below triggers the WatchDog timer
	//   indefinitely, keeping stasis.
	//	while (1)
	//	{
	//		dscWatchdogTrigger(dscb);
	//	}
	//
	// Whereas this code style prevents the WatchDog from being triggered;
	//   forcing a system restart via hardware.
	while (1);
	dscWatchdogTrigger(dscb);


	//=========================================================================
	// IV. CLEANUP
	//
	//	   Cleanup any remnants left by the program and free the resources used
	//	   by the driver.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. free the driver resources
	//=========================================================================

	dscFree();

	printf( "\nWatchdog completed.\n" );

	return 0;
} // end main()


#ifdef _WIN32_WCE
int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{
	main();

	return 0;
}

#endif
