/*
This program is distributed under the terms of the 'MIT license'. The text
of this licence follows...

Copyright (c) 2006,2009 J.D.Medhurst (a.k.a. Tixy)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
@file

@brief Implementation of #SerialPort for Linux.
*/

#include "../../common/common.h"
#include "../ymodem_tx.h"


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

/**
Root of serial port device names.
*/
#define DEVICE_NAME_ROOT "/dev/ttyS"

// comment in next line to get a log of all port trafic...
// #define DEBUG_LOG

/**
@brief Serial port object for Linux.
@ingroup serialport

@version 2009-10-02
	- Made implementation of i/o functions on Linux use <CODE>select()</CODE> rather than
	  hand rolled polling and sleeping.
*/
class LinuxSerialPort : public SerialPort
	{
public:
	LinuxSerialPort();
	int Open(unsigned port);
	int Initialise(unsigned baud);
	int Out(const uint8_t* data, size_t size, unsigned timeout);
	int In(uint8_t* data, size_t maxSize, unsigned timeout);
	void Close();
private:
	~LinuxSerialPort();
	int Error(int defaultError=ErrorUnspecified);
private:
	int SerialHandle; /**< File handle for serial port. */
#ifdef DEBUG_LOG
	void DebugDump(const char* prefix, const uint8_t* data, size_t size);
	FILE* DebugLog;
#endif
	};


/**
Process an error.

@param defaultError The default error value to return.

@return An error value from #Errors
*/
int LinuxSerialPort::Error(int defaultError)
	{
#ifdef DEBUG_LOG
	if(DebugLog)
		fprintf(DebugLog,"ERROR: %d (errno=%d '%s')",defaultError,errno,strerror(errno));
#endif
	return defaultError;
	}


int LinuxSerialPort::Open(unsigned port)
	{
	// make name for port...
	char name[] = DEVICE_NAME_ROOT "???.???";
	char* nameNumber = name+sizeof(name)-8;
	char* nameEnd = nameNumber;
	if(port>999)
		return ErrorInvalidPort;
	if(port>99)
		{
		*nameEnd++ = '0'+port/100;
		port %= 100;
		}
	if(port>9)
		{
		*nameEnd++ = '0'+port/10;
		port %= 10;
		}
	*nameEnd++ = '0'+port;
	*nameEnd = 0;

	// open port...
	SerialHandle = open(name, O_RDWR | O_NOCTTY);
	if(SerialHandle<0)
		{
		switch(errno)
			{
// Linux seems to allow more than one program to access port at the same time
// so there's no way to detect an 'already in use' error...
//			case ?:
//				return Error(ErrorPortInUse);
			default:
				return Error(ErrorInvalidPort);
			}
		}

#ifdef DEBUG_LOG
	strcpy(nameEnd,".log");
	DebugLog = fopen(nameNumber,"w+b");
#endif

	return 0;
	}


int LinuxSerialPort::Initialise(unsigned baud)
	{
	switch(baud)
		{
		case 1200: baud = B1200; break;
		case 2400: baud = B2400; break;
		case 4800: baud = B4800; break;
		case 9600: baud = B9600; break;
		case 19200: baud = B19200; break;
		case 38400: baud = B38400; break;
		case 57600: baud = B57600; break;
		case 115200: baud = B115200; break;
		case 230400: baud = B230400; break;
		default: return ErrorInvalidSettings;
		}

	struct termios tio;
	memset(&tio, 0, sizeof(tio));
	tio.c_cflag		= baud | CRTSCTS | CS8 | CLOCAL | CREAD;
	tio.c_iflag		= IGNPAR;
	tio.c_oflag		= 0;
	tio.c_lflag		= 0;	// set input mode (non-canonical, no echo,...)
	tio.c_cc[VTIME]	= 0;	// inter-character timer unused
	tio.c_cc[VMIN]	= 0;	// don't block if no chars available

	tcflush(SerialHandle, TCIFLUSH);
	if(tcsetattr(SerialHandle,TCSANOW,&tio)<0)
		return ErrorInvalidSettings;

	return 0;
	}


int LinuxSerialPort::Out(const uint8_t* data, size_t size, unsigned timeout)
	{
retry:
	// wait for serial port to be ready to write...
	fd_set writefds;
	FD_ZERO(&writefds);
	FD_SET(SerialHandle,&writefds);
	timeval wait;
	wait.tv_sec = timeout/1000;
	wait.tv_usec = timeout%1000*1000;
	int selectResult = select(SerialHandle+1, 0, &writefds, 0, &wait);

	int bytes;
	if(selectResult==0)
		{
		// timeout...
		bytes = 0;
		}
	else if(selectResult<0)
		{
		// a select error...
		if(errno==EINTR)
			goto retry; // interupted by a signal so just retry
		bytes = -1; // flag error
		}
	else
		{
		// ready for write...
		bytes = write(SerialHandle,data,size);
		}

	if(bytes<0)
		return Error(ErrorTransmitError);

#ifdef DEBUG_LOG
	DebugDump(">",data,bytes);
#endif

	return bytes;
	}


int LinuxSerialPort::In(uint8_t* data, size_t maxSize, unsigned timeout)
	{
retry:
	// wait for serial port to be ready to read...
	fd_set readfds;
	FD_ZERO(&readfds);
	FD_SET(SerialHandle,&readfds);
	timeval wait;
	wait.tv_sec = timeout/1000;
	wait.tv_usec = timeout%1000*1000;
	int selectResult = select(SerialHandle+1, &readfds, 0, 0, &wait);

	int bytes;
	if(selectResult==0)
		{
		// timeout...
		bytes = 0;
		}
	else if(selectResult<0)
		{
		// a select error...
		if(errno==EINTR)
			goto retry; // interupted by a signal so just retry
		bytes = -1; // flag error
		}
	else
		{
		// ready for read...
		bytes = read(SerialHandle,data,maxSize);
		}

	if(bytes<0)
		return Error(ErrorReceiveError);

#ifdef DEBUG_LOG
	DebugDump("<",data,bytes);
#endif

	return bytes;
	}


void LinuxSerialPort::Close()
	{
	if(SerialHandle)
		{
		close(SerialHandle);
		SerialHandle = 0;
		}
#ifdef DEBUG_LOG
	if(DebugLog)
		{
		fclose(DebugLog);
		DebugLog = 0;
		}
#endif
	}


#ifdef DEBUG_LOG

void LinuxSerialPort::DebugDump(const char* prefix, const uint8_t* data, size_t size)
	{
	if(!DebugLog)
		return;

	size_t i=0;
	while(i<size)
		{
		fprintf(DebugLog,prefix);
		unsigned j;
		for(j=0; j<16 && i+j<size; j++)
			{
			fprintf(DebugLog," %02x",data[i+j]);
			}
		fprintf(DebugLog," ");
		for(unsigned k=0; k<j; k++)
			{
			uint8_t c = data[i+k];
			if(c<' '|| c>=0x7f)
				c = '.';
			fprintf(DebugLog,"%c",c);
			}
		fprintf(DebugLog,"\n");
		i += j;
		}
	}

#endif


inline LinuxSerialPort::LinuxSerialPort()
	: SerialHandle(0)
#ifdef DEBUG_LOG
	,DebugLog(0)
#endif
	{
	}


LinuxSerialPort::~LinuxSerialPort()
	{
	Close();
	}


SerialPort* SerialPort::New()
	{
	return new LinuxSerialPort;
	}


SerialPort::~SerialPort()
	{
	}


