//=============================================================================
// (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: DSCADScanInt.c   version 6.01
// Description: Sample program that demonstrates how to perform an interrupt-based A/D scan
// Contributors: KL, James Moore
//=============================================================================

#include <stdio.h>

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

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

#ifdef _WIN32_WCE

#include <string.h>
#include <Winsock2.h>


static int kbhit()
{
	int i;
	int result=0;


	result |= GetAsyncKeyState(VK_RETURN);
	result |= GetAsyncKeyState(VK_SPACE);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	//number keys, 0-9
	for (i=48; i<=57; i++)
		result |= GetAsyncKeyState(i);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	//capital character keys, A-Z
	for (i=65; i<=90; i++)
		result |= GetAsyncKeyState(i);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	//lower case keys, a-z
	for (i=97; i<=122; i++)
		result |= GetAsyncKeyState(i);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	return result;
}

#endif


// DOS
#ifdef __BORLANDC__
#include <conio.h>
#include <dos.h>
#include <stdlib.h>
#include <math.h>
#include <mem.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>
#include <string.h>
// diamond driver includes
#include "dscud.h"

#ifdef _WRS_VXWORKS_5_X
#include <selectLib.h>
#define main HeliosDSCADScanInt
#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(1, &rfds, NULL, NULL, &timeout) > 0 )
		return getchar();

	return 0;
}
#endif

// macros defined
#define SLEEP_TIME 1000

// var declarations
BYTE result; // returned error code
DSCB dscb;   // handle used to refer to the board
DSCCB dsccb; // structure containing board settings
DSCUSERINT	dscuserint; // structure for setting up user int
ERRPARAMS errorParams;  // structure for returning error code and error string
int intBuff;            // temp variable of size int
float floatBuff;        // temp variable of size float
int i;
int counter; // the global variable to be modified by the user defined function
BYTE temp;
DSCS dscs;       // structure containing interrupt-based sampling status

void count(void * param);

#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.
//
//	     I. Driver Initialization
//	    II. Board Initialization
//	   III. UserInt Settings
//	    IV. UserInt Testing
//		 V. 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. USER INT INITIALIZATION and Run
	//
	//		Sets up the rate, counter, interrupt source, and clock source for using 
	//      userinterrupt, USER_INT_INSTEAD mode. 
	//		Both intsource and counter are 0 because prom doesn't support
	//		other interrupt modes of userinterrupt and only counter1 is used
	//		for userinterrupt with no external triggers.
	//=========================================================================

	
	// if using dscCounterDirectSet to specify the user rate then set
	// dscuserint.rate = 0 and uncomment the following code;
	//
	// dscCounterDirectSet(dscb, 0x34, 0, 0);		
	//

	counter =0;
	
	// Prom has the following options
	//
	//	intsource	clksource	description
	//
	//		0			0		 counter1, 100KHz clock
	//		0			1		 counter1, 10MHz clock
	//		0			2		 counter1, external clock.  
	//		1			0		 external interrupt, DIO interrupt. 							 
	//
	//							 NOTE: if running external clock or external interrupt,
	//									can't run DIO functions.
	
	if(argc <= 2)
	{
		printf("Enter the interrupt source (1 for external interrupt, 0 for internal clock) : ");
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[2], "%d", &intBuff);
	}
	dscuserint.intsource = (BYTE) intBuff;

	dscuserint.counter = 0;
	if(argc <= 3)
	{	
		printf("Enter the clock source (0 for 100KHz, 1 for 10MHz, 2 external clock) : "); // select the counter timer
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[3], "%d", &intBuff);
	}
	dscuserint.clksource = (BYTE) intBuff;

	if(argc <= 4)
	{
		printf("Enter the interrupt rate in hertz : ");
		scanf("%f", &floatBuff);
	}else
	{
		sscanf(argv[4], "%f", &floatBuff);
	}
	dscuserint.rate = (FLOAT) floatBuff;

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

	for (i=0; i<15; i++)
	{
		dscInp(dsccb.base_address + i, &temp);
		printf("i %d, temp %x\n", i, (int)temp);
	}

	//===========================================================================
	//	IV. CASES FOR USERINT 
	//
	//      Tests userinterrupt. Prints the number of interrupts
	//===========================================================================

	printf("Hit any key to exit\n");

	

	do
	{
		dscSleep(SLEEP_TIME);
		printf("UserInt counter %d \r", counter);
		fflush(stdout);
	}
	while ( !kbhit() );

	// cancel interrupts manually if interrupts are still running
	if( (result = dscCancelOp(dscb)) != DE_NONE)
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscCancelOp error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}

	//=========================================================================
	// V. CLEANUP
	//
	//	   Cleanup any remnants left by the program and free the resources used
	//	   by the driver.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. free the memory allocated for sample values
	//	   2. free the driver resources
	//=========================================================================

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

	dscFree();

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

	return 0;
} // end main()


///////////////////////////
// User Interrupt Function
///////////////////////////

void count(void * param)
{
	counter ++;
}


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

	return 0;
}

#endif


