//*****************************************************************************
//
//              Copyright (c) 2005 Advantech eAutomation Division
//
//                      Advantech Co., Ltd.
//
//        Oxford PCI-954/16C950 with Advantech RS232/422/485 capacities
//
//      This is An Unpublished Work Containing Confidential  And Proprietary
//         Information Which Is The Property Of Advantech eAutomation Division.
//
//    Any Disclosure, Use, Or Reproduction, Without Written Authorization From
//               Advantech eAutomation Division, Is Strictly Prohibit.
//
//
//*****************************************************************************

//***********************************************************************
// File:        getconfig.c
// Author:      Po-Cheng Chen
// Purpose:	Get serial port configuration, such as RS232 or RS422/485
//***********************************************************************
//***********************************************************************
#include <sys/types.h>
#include <sys/stat.h>
#include <asm/ioctls.h>
#include <linux/serial.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int i, ttynum, fd;
    char ttyname[80];
    struct serial_struct serinfo;

    if(argc < 3)
    {
	printf("Usage:\n");
	printf("%s TTYNAME TTYNUM", argv[0]);
	return 1;
    }

    ttynum = atoi(argv[2]);
    for(i=0;i<ttynum;i++)
    {
	sprintf(ttyname, "/dev/%s%d", argv[1], i);
	if((fd = open(ttyname, O_RDWR | O_NDELAY)) == -1)
	    break;

	// test serial port exist or not
	if(write(fd, ttyname, strlen(ttyname)) == -1)
	    break;

	// get serial port information
	serinfo.reserved_char[0] = 0;
	if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0)
	{
	    printf("Cannot get serial info\n");
	    close(fd);
	    return 2;
	}

	// get serial port type configuration
	if (serinfo.reserved_char[0] == 0)
	{
	    // RS232
	    printf("%s is RS232\n", ttyname);
	}
	else
	{
	    // RS422/485
	    printf("%s is RS422/485\n", ttyname);
	}

	close(fd);
    }
    return 0;
}
