/*
Anthony DiSante's dsrmon - monitors serial port pin 6
and exits when it goes from high to low.  Part of the
musicbox:
http://nodivisions.com/tech/systems/musicbox/
v20040329
*/

#include <stdio.h>
#include <termio.h>
#include <sys/fcntl.h>

main(int argc, char *argv[]) 
{
	int fd;
	char port[15] = "\0";

	if(argc < 2)
	{
		fprintf(stderr, "Usage:\ndsrmon <serial port>\nwhere serial port is probably /dev/ttyS0 or /dev/ttyS1, etc.\n");
		exit(1);
	}
	else
	{
		strcat(port, argv[1]);
		if((fd = open(port, O_RDONLY)) < 0)
		{
			fprintf(stderr, "Couldn't open serial port: %s\n", port);
			exit(1);
		}
	}
	
	int i = TIOCM_DTR;
	ioctl(fd, TIOCMSET, &i);

	printf("Monitoring the DSR line (pin 6) on serial port %s.\nI'll exit when it goes low.\n",port);
	int dsr_state=0, dsr_prev_state=0;

	while(1)
	{
		if(ioctl(fd, TIOCMGET, &i) < 0)
		{
			perror("Couldn't get port status: ");
			exit(1);
		}

		dsr_state = i & TIOCM_DSR;

		/* printf("dsr_state=%i,dsr_prev_state=%i\n",dsr_state,dsr_prev_state); */
		if((dsr_state==0) && (dsr_prev_state==256))
		{
			printf("The DSR pin went low.\n");
			exit(1);
		}

		dsr_prev_state = dsr_state;
		sleep(1);
	}
}
