/* Get Analog Input for i8k/i9k modules.

   Author: Moki Matsushima

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */

/* File level history (record changes for this file here.)

   v 0.0.0  1 Sep 2017 by Moki Matsushima
     create, blah blah... */

/*Read gain and ofsset of each input range 
  gain 0:   +/- 10V
  gain 1:   +/- 5V
  gain 2:   +/- 2.5V
  gain 3:   +/- 1.25V 
            +/- 20mA */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "msw.h"
#include "i8017W.h"
#define iTalkVersion	15

int main(int argc, char **argv)
{
	int ret, RetValue, slot, channel, gain, mode;
	short jumper;
	float fVal=0;  
	if (argc != 5) {
		printf("ICPDAS iTalk utility v%d\n",iTalkVersion);
		printf("function: getai\n");
		printf("Get analog input value to a module\n");
		printf("Usage: getai slot channel gain mode\n");
		printf("Example: ./getai.exe 1 2 3 0\n");
		printf("Get the analog value from channel 2 of slot 1 with gain 3 and mode 0\n");
		return FAILURE;
	}
	
	slot=atoi(argv[1]);
	channel=atoi(argv[2]);
	gain=atoi(argv[3]);
	mode=atoi(argv[4]);
	
	/* open device file */
	RetValue = Open_Slot(slot);
	if (RetValue >0) {
		printf("open Slot %d failed!\n",slot);
		return FAILURE;
	}

	ret=I8017_Init(slot);

	if (ret == -1)   
		printf("There's an eroor in '8017_Init' function at Slot%d, ret value= %d \n",slot,ret);
	else 
	{
		//I8017_Select_SingleEnd(slot, 0); //0:differential ; 1:single-ended mode., this function is for I-9017-15 only
		I8017_GetSingleEndJumper(slot, &jumper);  
		//printf("Jumper mode= %d\n", jumper);	//0: differential ; 1: single-ended mode
		if(jumper)
			printf("Input Mode= Single-End\n");
		else
			printf("Input Mode= Differential\n");
  
		I8017_ReadAI(slot,channel,gain,&fVal);
		printf("I8017_ReadAI= %f\n", fVal);
	} 

	Close_Slot(slot);
	return SUCCESS;
}
