/***********************************************************************
 *  avrp - Atmel AVR programming software to use with Atmel's
 *         serial-port programmers.
 *  Copyright (C) 1997-1998 Jon Anders Haugum
 *
 *  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; see the file COPYING.  If not, write to
 *  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 *  Boston, MA 02111-1307, USA.
 *
 *
 *  Author of avrp can be reached at:
 *     email: jonah@colargol.tihlde.hist.no
 *     www: http://www.colargol.tihlde.hist.no/~jonah/el/avrp.html
 *     Postal address: Jon Anders Haugum
 *                     Øvre Møllenbergsgt 52
 *                     7014 Trondheim
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "avrp.h"

#define BAUDRATE B19200

struct Ser
	{
	char *Name;
	int fd;
	struct termios oldtio, newtio;
	};


void *OpenSer(char *SerPort)
	{
	struct Ser *Ser = NULL;

	Ser = (struct Ser *)malloc(sizeof(struct Ser));
	if(Ser)
		{
		Ser->Name = SerPort;
		if((Ser->fd = open(SerPort, O_RDWR | O_NOCTTY )) != -1)
			{
			tcgetattr(Ser->fd, &Ser->oldtio); /* save current port settings */

			bzero(&Ser->newtio, sizeof(Ser->newtio));
			Ser->newtio.c_cflag = CS8 | CLOCAL | CREAD;
			cfsetispeed(&Ser->newtio, BAUDRATE);
			cfsetospeed(&Ser->newtio, BAUDRATE);
			Ser->newtio.c_iflag = IGNPAR;
			Ser->newtio.c_oflag = 0;

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

			Ser->newtio.c_cc[VTIME] = 3;  /* Timeout in value * 0.1s  */
			Ser->newtio.c_cc[VMIN] = 0;
			tcflush(Ser->fd, TCIFLUSH);
			tcsetattr(Ser->fd, TCSANOW, &Ser->newtio);
			}
		else
			{
			perror(SerPort);
			free(Ser);
			Ser = NULL;
			}
		}
	else
		printf("Error: Unable to allocate memory\n");
	return(Ser);
	}


void CloseSer(void *Ser)
	{
	tcsetattr(((struct Ser *)Ser)->fd, TCSANOW, &((struct Ser *)Ser)->oldtio);
	close(((struct Ser *)Ser)->fd);
	free(Ser);
	}


void SerWriteByte(void *Ser, unsigned char Byte)
	{
	write(((struct Ser *)Ser)->fd, &Byte, 1);
	}


int SerReadData(void *Ser, unsigned char *Buff, int Count)
	{
	int ret;

	ret = read(((struct Ser *)Ser)->fd, Buff, Count);
	if(ret == -1)
		{
		perror(((struct Ser *)Ser)->Name);
		return(0);
		}
	return(ret);
	}

