/* 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 "msw.h"
#include "modbus.h"

#define iTalkVersion	15
void	usage(void);

int main(int argc, char **argv)
{
	int RetValue,slot,comport,timeout, addr, count, function, netid;
	char szBuf[80];
	DWORD baudrate;
	WORD wT;
	if (argc == 8) {
		comport = atoi(argv[1]);
		baudrate = atol(argv[2]);
		netid = atoi(argv[3]);
		function = atoi(argv[4]);
		addr = atoi(argv[5]);
		count = atoi(argv[6]);
		timeout=atoi(argv[7]);
	}
	else {
		usage();
		return FAILURE;
	}
	if((function < 1) || (function > 4)) {
		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;
	}
	RetValue = modbusRequest(comport, netid, function, addr, count, szBuf, sizeof(szBuf), timeout, &wT);
	Close_Com(comport);
	if (RetValue == 0) {
		if((function==1)||(function==2))
			printf("%d", szBuf[0]);
		else { 
			RetValue = (szBuf[0]<<8)|szBuf[1];
			printf("%ld", RetValue);
		}
	} else if (RetValue == CmdError) {
		printf("Module at COM%d return error code %d !!!\n",comport,szBuf[0]);
		return FAILURE;
	} else {
		printf("Module at COM%d error %d !!!\n",comport,RetValue);
		return FAILURE;
	}
}

void usage(void)
{
	printf("ICPDAS iTalk utility v%d\n",iTalkVersion);
	printf("function : getmodbus\n");
	printf("Send MODBUS/RTU command and wait resopnse from a serial module\n");
	printf("Usage: getmodbus comport baudrate netid command addr count timeout\n");
	printf("Example 1:getmodbus 1 115200 1 1 1 2 100\n");
	printf("Send command FC01 to the module at COM1 and wait response\n");
	printf("Example 2:getmodbus 1 115200 1 3 1 2 100\n");
	printf("Send command FC03 to the module at COM1 and wait response\n");
}
