/* siob.c - simple serial output code */
/* based on code at: http://www.easysw.com/~mike/serial/ */
/* type shit- hit return and it gets sent out cua0*/
/* also checks for input after each character typed */
/* send a Z to exit */

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */

int open_port (void);

main ()
    {
    int sfd; /*serial port file descriptor*/
    struct termios o_opts, n_opts; 
    int n =0;
    int ni=0;
    int c;
    int i;
    char buf[80], ibuf[80];

    sfd = open_port(); /*open serial port*/

    /*make read return 0 bytes if none available*/
    fcntl(sfd, F_SETFL, FNDELAY);

    /* set some port parameters */
    tcgetattr(sfd, &o_opts);
    n_opts=o_opts;
    /*turn off echo*/
    n_opts.c_lflag &= ~(ECHO);
    /*apparently handles \n correctly*/
    n_opts.c_iflag |= (IGNCR);
    /*now baud rates*/
    cfsetispeed(&n_opts,B9600);
    cfsetospeed(&n_opts,B9600);
    /* now set to 8N1 */
    n_opts.c_cflag &= ~CSIZE;
    n_opts.c_cflag |= CS8;
    n_opts.c_cflag &= ~PARENB;
    n_opts.c_cflag &= ~CSTOPB;

    /*now make these settings active now*/
    tcsetattr(sfd, TCSANOW, &n_opts);

    while ((c=getchar())!='Z')
        {
        buf[n++]=c;
        if (c=='\n')
            {
            buf[n]='\0';
            if (write(sfd,buf,n)<0)
                fprintf(stderr,"write() of %d bytes failed.\n",n);
            n=0;
            }
        /*check for input*/
        if ((ni=read(sfd,ibuf,80))>0)
            {
            ibuf[ni]='\0';
            printf("I read %d bytes: %s\n",ni,ibuf);
            /*for (i=0;i<=ni;i++)*/
             /*   printf("char %d is %c or %d.\n",i,ibuf[i],ibuf[i]);*/
            }

        }
  
   /* tell sio to stop with a Z*/
   strcpy(buf,"Z\n\0");
   if (write(sfd, buf, 2)<0)
        puts("ending write failed");

    tcsetattr(sfd, TCSANOW, &o_opts);
    close (sfd);
    }

int open_port(void)

    {
    int fd; /*file descriptor*/
    
   fd = open("/dev/cua0", O_RDWR | O_NOCTTY | O_NDELAY);
   if (fd == -1)
     fprintf(stderr, "open_port: Unable to open /dev/cua0 - %s\n",
             strerror(errno));

   return (fd);
 }
