/*
 * sample_sequence.c
 *
 *  Created on: Jun 16, 2010
 *      Author: rj185
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/sysmacros.h> /* major() minor() */
#include <signal.h>
#include <stdint.h>

#include <apci3120.h>
#include "findboards.h"

#define NB_READ 100

int run_test ( int fd )
{
	unsigned int arg[5] = {0};
	int i = 0;
	int j = 0;
	int error = 0;
	uint64_t average;


	arg[0] = 0; 			// Channel number (1 to 16)
	arg[1] = APCI3120_1_GAIN;	// Gain to use (APCI3120_1_GAIN, APCI3120_2_GAIN, APCI3120_5_GAIN and APCI3120_10_GAIN)
	arg[2] = APCI3120_BIPOLAR;	// Polarity can be APCI3120_UNIPOLAR or APCI3120_BIPOLAR
	arg[3] = 50;				// Selection of the conversion time from 10us to 32767us
	arg[4] = APCI3120_DISABLE;	// Interrupt flag (NOT IMPLEMENTED)

	printf("Read 100 times each channel \n");
	for ( i = 0; i < APCI3120_MAX_CHANNEL_NBR; i++)
	{
		average = 0;
		for ( j = 0; j < NB_READ; j++ )
		{
			arg[0] = i; 			// Channel number (1 to 16)
			arg[1] = APCI3120_1_GAIN;	// Gain to use (APCI3120_1_GAIN, APCI3120_2_GAIN, APCI3120_5_GAIN and APCI3120_10_GAIN)
			arg[2] = APCI3120_BIPOLAR;	// Polarity can be APCI3120_UNIPOLAR or APCI3120_BIPOLAR
			arg[3] = 50;				// Selection of the conversion time from 10us to 32767us
			arg[4] = APCI3120_DISABLE;	// Interrupt flag (NOT IMPLEMENTED)

			error = ioctl (fd, CMD_APCI3120_Read1AnalogInput, arg);
			if ( error != 0 )
			{
				printf("Error with the ioctl : %d \n", error );
				return 1;
			}
			average += arg[0];
		}
		average = average / NB_READ;
		printf("Channel %d, average : %lld \n", i, average);
	}


	return 0;
}

//--------------------------------------------------------------------------------
int main(int argc, char** argv)
{
	int i=0;
	int * apci3120_card_fd;
	unsigned int apci3120_card_number = 0;
	{
		apci3120_card_number = apci_find_boards("apci3120",&apci3120_card_fd);
		printf("total: %d cards\n",apci3120_card_number);
	}

	// No card
	if ( apci3120_card_number <= 0)
	{
		printf("No card found, exit ... \n");
		return 0;
	}

	for ( i = 0 ; i< apci3120_card_number; i++)
	{
		printf("****************Board %d***********************\n", i);
		run_test(apci3120_card_fd[i]);

		close(apci3120_card_fd[i]);
	}

	return 0;
}
