/*********************************************************************
 * This file is part of the cpplibs suite.
 *
 * Copyright (C) 2001 Topi Mäenpää
 * All rights reserved.
 *
 * This program is free software. You can redistribute and/or modify
 * it under the terms of the free software licence found in the
 * accompanying file "COPYING". The licence terms must always be
 * redistributed with this source file. The above copyright notice
 * must be reproduced in all modified and unmodified copies of this
 * source file.
 *
 * $Revision: 1.6 $
 *********************************************************************/

#include "RS232.h"
#include <sys/ioctl.h>

namespace util { namespace io {
	RS232::RS232(const char* d, int t)
	{
		device = strdup(d);
		type = t;
	}

	RS232::~RS232()
	{
		free(device);
	}

	void RS232::open(void) throw (IOException&)
	{
		struct termios termios;

		if ((fd = ::open(device,type)) < 0)
			throw IOException("Open: cannot open device");

		if (ioctl(fd,TCGETS,&termios) == -1)
			{
				close();
				throw IOException("Open: cannot get device parameters");
			} 

		termios.c_cflag = (CS8 | B9600 | CLOCAL | CREAD);
		termios.c_cflag &= (~PARENB); 

		termios.c_iflag = (IXON | IXOFF);
		termios.c_iflag &= (~ISTRIP); 

		termios.c_oflag = 0; 
		
		termios.c_lflag = (ICANON);
		termios.c_lflag &= (~ECHO);

		if (ioctl(fd,TCSETS,&termios) == -1)
			{
				close();
				throw IOException("Open: cannot get device parameters");
			}
	}
}}
