/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 2003 by Matthew R. Stein
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* This function inserted by MS for Linux implementation.  In Linux, we connect
the teach pendant directly to the serial port of the linux machine, i.e.
/dev/ttys0.  This function will be called by the control-level process
periodically to determine if a key has been pressed.  This routine will write
a prompting word to the teach pendandt then await a reply before returning.  
The teach pendandt, when functioning, always responds immediately to a prompt, 
wether or not anything has been pressed.
*/

#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 */
#include <fstream.h>
#include <iostream>

#include "../h/pendant.h"

int mainfd=0;    

int puma_pendant_startup ()
  
{
  struct termios options;
  mainfd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
  
  if (mainfd == -1){                                              
    fprintf(stderr, "open_port: Unable to open /dev/ttyS0 - %s\n",
	    strerror(errno));
    return(-1);
  }
  
  tcgetattr(mainfd, &options);
  cfsetispeed(&options, B9600);                    /*Set the baud rates to 9600 */
  cfsetospeed(&options, B9600);
  
  /* Enable the receiver and set local mode 
  options.c_cflag |= (CLOCAL | CREAD);
  options.c_cflag &= ~PARENB;                      /* Mask the character size to 8 bits, no parity*/
  options.c_cflag &= ~CSTOPB;
  options.c_cflag &= ~CSIZE;
  options.c_cflag |=  CS8;                         /* Select 8 data bits */
  options.c_cflag &= ~CRTSCTS;                     /* Disable hardware flow control*/
  
  
  options.c_lflag &= ~(ICANON | ECHO | ISIG);      /*Enable data to be processed as raw input*/
  
  
  tcsetattr(mainfd, TCSANOW, &options);            /* Set the new options for the port*/
  
  return (1);
}

void puma_pendant_read(int prompt, long *pendant)
{
  short buf[9];
  short outbuf = M_NULL | (short) prompt | M_PROG_RUNNING; 
  
  /* Prompt the pendant, Write data to the port */
  write(mainfd, &outbuf, sizeof(outbuf));        
  
  
  /* Read the response as 8 characters */
  for(int i=0;i<=8;i++)
    read(mainfd, &buf[i], sizeof(buf));           
  
  pendant[0]= buf[0] | (buf[1] >>8);
  pendant[1]=	 buf[2] | (buf[3] >>8);
  
  
}

void puma_pendant_release()
{
  /* Close the serial port */
  if(mainfd != 0) close(mainfd);    
  
}
