/* Send and Receive ASCII command from a i7k/i8k/i87k modules via serial port.

   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 April 2005 by Moki Matsushima
     create, blah blah... */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>
#include "msw.h"
#include "xvboard.h"

#define iTalkVersion	15
void	usage(void);

int main(int argc, char **argv)
{
	int RetValue,slot,comport=COM1,timeout=100, addr, count, function, netid;
	char szBuf[80];
	DWORD baudrate=115200, dwValue;
	WORD wT;
	if (argc == 3) {
		addr = atoi(argv[1]);
		count = atoi(argv[2]);
	}
	else {
		usage();
		return FAILURE;
	}
	/* open device file */
	RetValue = Open_Com(comport, baudrate, Data8Bit, NonParity, OneStopBit);
	if (RetValue >0) {
		printf("open COM%d failed!\n",comport);
		return FAILURE;
	}
	memset(szBuf, 0, sizeof(szBuf));
	RetValue = getXVBit(comport, addr, count, szBuf, sizeof(szBuf));
	Close_Com(comport);
	if (RetValue == 0) {
		if(count <= 8) {
			printf("%d", szBuf[0]);
		} else if (count <= 16){ 
			dwValue = (szBuf[1]<<8)|szBuf[0];
			printf("%u", dwValue);
		} else {
			dwValue = (szBuf[3]<<24)|(szBuf[2]<<16)|(szBuf[1]<<8)|szBuf[0];
			printf("%u", dwValue);
		}
	} else if (RetValue == CmdError) {
		printf("XV-Board return error code %d !!!\n", szBuf[0]);
		return FAILURE;
	} else {
		printf("XV-Board error %d !!!\n", RetValue);
		return FAILURE;
	}
	return NoError;
}

void usage(void)
{
	printf("ICPDAS iTalk utility v%d\n",iTalkVersion);
	printf("function : getxvdi\n");
	printf("Get digital input value from a xv module\n");
	printf("Usage: getxvdi addr count\n");
	printf("Example 1:getxvdi 1 2 \n");
	printf("Get the dec digital input value from the xv module at addr 1~3\n");
	printf("Example 2:getxvdi 2 3 \n");
	printf("Get the dec digital input value from the xv module at addr 2~5\n");
}
