/*-------------------------------------------------------------------------
--
--                              -*- Mode: C -*- 
-- Filename        : os_connection.c
-- Description     : lowest level routines connecting Ada to Linux
--
--------------------------------------------------------------------------*/

/*--------------------------------------------------------------------------
--
-- Includes
--
--------------------------------------------------------------------------*/

#include 
#include 
#include 
#include 
#include 


/*--------------------------------------------------------------------------
--
-- Set of routines for Ada
--
--------------------------------------------------------------------------*/


int open_serial_port (char *Device)
{
int fd;

  fd = open(Device, O_RDWR | O_NOCTTY ); 
  if (fd <0) {perror(Device); exit(-1); }
  return (fd);
}


close_serial_port (int fd)

{
  close (fd);
}


setup_serial_port (int fd, unsigned int PortSpeed)

{
  struct termios newtio;

  bzero(&newtio, sizeof(newtio));
  newtio.c_cflag = PortSpeed | CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR | IGNBRK;
  newtio.c_oflag = 0;

  newtio.c_lflag = 0;   /* set input mode (non-canonical, no echo,...) */

  newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
  newtio.c_cc[VMIN]     = 0;   /* blocking read until 5 chars received */

  tcflush(fd, TCIFLUSH);
  tcsetattr(fd,TCSANOW,&newtio);
}


int read_serial_port (int fd, char *Buffer)
{
  int BytesRead;

  BytesRead = read (fd, Buffer, 255);

  return (BytesRead);
}


write_serial_port (int fd, char *Buffer, int BytesToWrite)

{
  int AmountWritten = 0;
  int StillToWrite;
  
  StillToWrite = BytesToWrite;
  while (StillToWrite > 0) {
/*      printf("%d to write", StillToWrite);  */
    AmountWritten = write(fd, Buffer, StillToWrite);
/*      printf("%d written", AmountWritten);  */
    if (AmountWritten >= 0) {
      StillToWrite -= AmountWritten;
      Buffer += AmountWritten;
    } 
    if (StillToWrite > 0) {
      usleep(1);
    }
  }
}

enable_serial_port_interrupt (int fd)

{
  fcntl(fd, F_SETOWN, getpid());
  fcntl(fd, F_SETFL, FASYNC);
}