#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>

#define MAX_PORT 24

char *cTest = " <==> ttyUSB%02u\n";

void set_tty(int fd) {
    struct termios stty;
    tcgetattr(fd, &stty);
    stty.c_iflag = IGNBRK | IGNPAR | IGNCR;
    stty.c_cflag = CS8 | CREAD | B115200;
    stty.c_oflag = 0;
    stty.c_lflag = 0;
    stty.c_cc[VMIN] = 0;
    stty.c_cc[VTIME] = 0;

    stty.c_iflag |= (IXON | IXOFF );
    stty.c_cflag &= ~(CRTSCTS);
    stty.c_cflag |= (CLOCAL);
    if (tcsetattr(fd, TCSANOW, &stty) < 0) {
	perror("IOCTL");
	exit(1);
    }
}

int main(int argc,char *argv[])
{
    int nHandle[MAX_PORT];
    int i,j;
    char cSend[1024];
    int nWrite;
    printf("Test USBPORT\n");
    for ( i = 0 ; i < MAX_PORT ; i++ ) {
	char cName[128];
	sprintf(cName,"/dev/ttyUSB%u",i);
	nHandle[i] = open(cName, O_RDWR );
	if ( nHandle[i] != -1 ) {
	    set_tty(nHandle[i]);
	} else {
	    //printf("Error open port %s\n",cName);
        }
    }
    for ( i = 0 ; i < MAX_PORT ; i++ ) {
	char cName[128];
	sprintf(cName,"/dev/ttyUSB%u",i);
	if ( nHandle[i] != -1 ) {
	    sprintf(cSend,cTest,i);
	    if ( (nWrite = write(nHandle[i],cSend,strlen(cSend))) == strlen(cSend) ) {
		//printf("Write to port %s - %d bytes OK\n",cName,strlen(cSend));
	    } else {
		printf("Error write to port\n");
		exit(1);
	    }
	} else {
	    //printf("Error open port %s\n",cName);
        }
	usleep(200000);
	for ( j = 0 ; j < MAX_PORT ; j++ ) {
	    char cTmp[1024];
	    int nRead;
	    if ( nHandle[j] != -1 ) {
		if ( (nRead = read(nHandle[j],cTmp,1024)) > 0 ) {
		    cTmp[nRead] = 0x0;
		    printf("Port ttyUSB%u %s",j,cTmp);
		    fflush(stdout);
		    if ( nRead < nWrite ) {
			printf("Error read from port %s\n",cName);
			exit(1);
		    }
		    break;
		}
	    }
	}	
    }
    for ( j = 0 ; j < MAX_PORT ; j++ ) {
	close(nHandle[j]);
    }
    return 0;
}
