/* serialtft */
/*
 * Sets DTR or RTS high for switching purpose.
 *
 * Written by Joachim Welker
 *
 * 17.02.2007
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>

/* Define the signals used to switch tft on and off */
#define TFT_ON TIOCM_DTR
#define TFT_OFF TIOCM_RTS


static int fd = 0;

int main(int argc, char **argv)
{
	int state = 0;
	char *port;

	if (argc < 2)
        {
	    fprintf(stderr, "\nYou have to use on of the following options:\n"
			    "  on   :  sets RTS high for 1sec\n"  
                            "  off  :  sets DTR high for 1sec\n");
	    fprintf(stderr, "\nOptionally you can specify device as 2nd option (default /dev/ttyS0), eg:\n"
		            "serialtft on /dev/ttyS1\n" );
            exit(2);
        }

	if (argc < 3)
        {
	    fprintf(stderr, "No device specified, using ttyS0 by default!\n"
			    "You can specify device as 2nd option, eg:\n"
		            "  serialtft on /dev/ttyS1\n");

	    strcpy(port,"/dev/ttyS0");
        }
        else
            strcpy(port,argv[2]);

	/* open device */
	fd = open(port, O_RDWR | O_NDELAY);
	if (fd < 0) {
		fprintf(stderr, "ERROR: can not open \"%s\"\n", port);
		exit(2);
	}

	/* first set a defined state, all off */
        if (ioctl(fd, TIOCMSET, &state)<0)
        {
            fprintf(stderr, "ERROR: %s: ioctl TIOCMSET failed\n", port);
            exit(2);
        }

        if (strcmp (argv[1], "on") == 0) 
	    state |= TFT_ON;
	if (strcmp (argv[1], "off") == 0) 
            state |= TFT_OFF;

        ioctl(fd, TIOCMSET, &state);

	sleep(1);

        state = 0;
        if (ioctl(fd, TIOCMSET, &state)<0)
        {
            fprintf(stderr, "ERROR: %s: ioctl TIOCMSET failed\n", port);
            exit(2);
        }

        close(fd);
	return (2);
}
