/* -*-mode:C;tab-width:8-*-
 *
 * setserialbits.c   set/get bit values from the serial port
 *
 * Copyright (C) 1995        Alessandro Rubini
 *
 * This program is a minimal tool to test the serial port.
 * It can be useful to understand how your UPS is connected.
 *
 *   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 of the License, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <errno.h>

int main(int argc, char **argv)
{
int fd, timeout=0;
char *me=argv[0];
uint bits, mask=~0, outb=0;


  if (argc<2 || !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h"))
    {
    printf("%s: Usage: \"%s <device> [options]\"\n",me,me);
    printf("    <device>        is a serial device, like /dev/cua0\n"
	   "    \"-rts\" \"+rts\"   clear/set Requst To Send\n"
	   "    \"-dtr\" \"+dtr\"   clear/set Data Terminal Ready\n"
	   "    a number        report data every that many seconds\n\n");
    exit(1);
    }

  if ((fd=open(argv[1], O_RDWR | O_NDELAY)) < 0)
    {fprintf(stderr, "%s: %s: %s\n",me,argv[1],strerror(errno));exit(1);}

  while(++argv,--argc)
    {
    if (!strcmp(*argv,"-rts") || !strcmp(*argv,"+rts"))
      {mask &= ~TIOCM_RTS; outb |= (**argv=='+' ? TIOCM_RTS : 0);}
    if (!strcmp(*argv,"-dtr") || !strcmp(*argv,"+dtr"))
      {mask &= ~TIOCM_DTR; outb |= (**argv=='+' ? TIOCM_DTR : 0);}
    if (isdigit(**argv))
      timeout=atoi(*argv);
    }

  ioctl(fd,TIOCMGET,&bits); bits&=mask; bits|=outb; ioctl(fd,TIOCMSET,&bits);

  printf("CTS DSR DCD\n"); do
    {
    ioctl(fd,TIOCMGET,&bits);
    printf(" %i   %i   %i\n", (bits & TIOCM_CTS) != 0,
	                 (bits & TIOCM_DSR) != 0, (bits & TIOCM_CD) !=0);
    sleep(timeout);
    }
  while(timeout);

  exit(0);
}
    








