//============================================================================
// (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.
//
// DSCDIOFunctions.c  v6.01
// Desc: Writes and reads from Digital I/O port, on Helios as well as
//       Vortex86 processor interface through the DSCUD.
// 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 HeliosDSCDIOFunctions
#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

// These work on the Athene II and Helios
//#define DEFAULT_CONFIGURATION_BYTE 0x80 // <== bug: DIOCTRL is inverted!
#define DEFAULT_CONFIGURATION_BYTE 0x00
#define ATHENA_DEFAULT_CONFIGURATION_BYTE 0x80
#define DIO_PORT_A_BIT_MASK 0x10
#define DIO_PORT_B_BIT_MASK 0x02
#define DIO_PORT_CL_BIT_MASK 0x01
#define DIO_PORT_CH_BIT_MASK 0x08
#define ATHENAII_DEFAULT_BASE_ADDRESS 0x280
#define HELIOS_DEFAULT_BASE_ADDRESS 0x280

int DIOConfigurePort();
int DIOConfigurePorts();
int Output();
int Input();

// 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
int intBuff;            // temp variables of size int
BYTE config_bytes_array[5]; // For use with Vortex86 DIO ports
BYTE config_bytes;      // DIO Configuration byte
BYTE output_b;          // output byte
BYTE input_b;           // input byte
BYTE port;               // digital I/O port
int menu;
char input_buffer[20];
int i; // miscellaneous counter

#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. DA Conversion
//	    IV. Cleanup
//
//=============================================================================

int main()
{
	//=========================================================================
	// 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 0x300
	//	   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" );

	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 );
	}
	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. DIO INPUT AND OUTPUT
	//
	//	Performs a set of byte-level inputs and outputs. The user is
	//	presented with a menu; once the ports are configured, the
	//	user may take input or give output to the DIO ports. A simple
	//	test is to feed the output of a DIO port to another port set
	//	for input.

	//	For word and bit-level operations, the steps are nearly
	//	identical with a few minor changes to function names and the size
	//	of the data to be transferred.
	//
	//	STEPS TO FOLLOW:
	//
	//	1. Call dscDIOSetConfig to setup the DIO ports input/output modes.
	//	2. Select a port for output.
	//	3. Enter the output byte value.
	//	4. Select a port for input.
	//=========================================================================

	printf( "\nDIO INPUT AND OUTPUT:\n" );

	/*
	Example:
		config_bytes = 0x82;
	*/

	do
	{


	printf ( "\n0.) Quit\n1.) Configure ports\n2.) Output\n3.) Input\n" );

	printf ( "Enter your choice: " );

        fgets ( input_buffer, 20, stdin );
	sscanf ( input_buffer, "%d", &menu );

	if ( menu == 1 )
	{
	  DIOConfigurePorts();
	}
	if ( menu == 2 )
	{
	  Output();
	}
	if ( menu == 3 )
	{
	  Input();
	}

	} while ( menu != 0 );



	//=========================================================================
	// 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( "\nDSCDIOFunctions completed.\n" );

	return 0;
} // end main()


int DIOConfigurePorts()
{

//	BYTE configuration_byte = DEFAULT_CONFIGURATION_BYTE;
	BYTE configuration_byte = 0x00;

	printf ( "PORT CONFIGURATION SECTION: \n" );

	port = 0;

	printf("Enter the direction for port A (0 output, 1 input): ");
        fgets ( input_buffer, 20, stdin );
	sscanf ( input_buffer, "%d", &intBuff );

	if ( intBuff == 1 )
	{
	  configuration_byte |= DIO_PORT_A_BIT_MASK;
	  intBuff = 0;
        }

	printf("Enter the direction for port B (0 output, 1 input): ");
        fgets ( input_buffer, 20, stdin );
	sscanf ( input_buffer, "%d", &intBuff );

	if ( intBuff == 1 )
	{
	  configuration_byte |= DIO_PORT_B_BIT_MASK;
	  intBuff = 0;
        }

	printf("Enter the direction for port CL (0 output, 1 input): ");
        fgets ( input_buffer, 20, stdin );
	sscanf ( input_buffer, "%d", &intBuff );

	if ( intBuff == 1 )
	{
	  configuration_byte |= DIO_PORT_CL_BIT_MASK;
	  intBuff = 0;
        }

    printf("Enter the direction for ports CH (0 output, 1 input): ");
        fgets ( input_buffer, 20, stdin );
	sscanf ( input_buffer, "%d", &intBuff );

	if ( intBuff == 1 )
	{
	  configuration_byte |= DIO_PORT_CH_BIT_MASK;
	  intBuff = 0;
        }

//	printf("Enter the configuration byte in hex (failsafe: hit ENTER if already done above): ");
//    fgets ( input_buffer, 20, stdin );
//    if ( input_buffer[0] != '\n' )
//    {
//    	sscanf ( input_buffer, "%x", &configuration_byte );
//    }
//    else
//    {
//        printf ( "Configuration byte written: [%hx]", configuration_byte );
//    }

    config_bytes = configuration_byte;

	DIOConfigurePort();

	return 0;

}

// Configure an individual port with data already collected
int DIOConfigurePort()
{

   	    config_bytes_array[0] = 0x00;
	    config_bytes_array[1] = config_bytes;

	if( (result = dscDIOSetConfig(dscb, &config_bytes_array[0])) != DE_NONE) //set DIO configuration
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscDIOSetConfig error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		printf ( "Error using standard DIO ports.\n" );
		return 0;
	}
	return 0;
}


int Output()
{

	printf ( "\nOUTPUT section:\n" );

	printf("Enter port number (0-4): ");
	scanf("%x", &intBuff);
	port = (BYTE) intBuff;

		printf("Enter the value to port in HEX: ");
		scanf("%x", &intBuff);
		getchar();
		output_b = (BYTE) intBuff;

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

		printf( "Byte value sent to port: %x\n", (int)output_b );

	return 0;

}

int Input()
{
		printf ( "\nINPUT section: \n" );

		printf("Enter port number (0-4): ");
		scanf("%d", &intBuff);
		getchar();
		port = (BYTE) intBuff;

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

		printf( "Byte value (previously) sent to port: %x, Byte value received from port: %x\n", (int)output_b, (int)input_b );

	return 0;
}


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

	return 0;
}

#endif
