/*
 * SerialPort.h
 *
 *  Created on: Jun 20, 2012
 *      Author: willie
 */

#include <string>
#include <exception>

#ifndef SERIALPORT_H_
#define SERIALPORT_H_

namespace kserial
{

class SerialPort
{
public:
	enum eDataBits { DB_8, DB_7, DB_6, DB_5 };
	enum eStopBits { SB_1, SB_2 };
	enum eBaudRate { BR_115200, BR_57600, BR_38400, BR_19200, BR_9600 };
	enum ePortMode { PM_RS232, PM_RS485 };

	SerialPort(const char *device);
	~SerialPort();

	void connect();
	int getFD() { return mFD; }
	const char * getDevice() { return mDevice.c_str(); }
	const char * getOwner() { return mOwner.c_str(); }

	void setOwner(const char *str);
	void setDataBits(const char *str);
	void setStopBits(const char *str);
	void setBaudRate(const char *str);
	void setPortMode(const char *str);
	void setNonBlock(const char *str);

   eBaudRate getBaudRate() const
   {
      return mBaudRate;
   }

   eDataBits getDataBits() const
   {
      return mDataBits;
   }

   bool isNonBlock() const
   {
      return mNonBlock;
   }

   ePortMode getPortMode() const
   {
      return mPortMode;
   }

   eStopBits getStopBits() const
   {
      return mStopBits;
   }

private:
	void setSerialOptions();

	int mFD;
	std::string mDevice;
	std::string mOwner;
	eDataBits mDataBits;
	eStopBits mStopBits;
	eBaudRate mBaudRate;
	ePortMode mPortMode;
	bool mNonBlock;
};

class BadValueException : public std::exception
{
public:
	BadValueException(const char *param, const char *val) : mParam(param), mVal(val) { }
	~BadValueException() throw() { }
	virtual const char* what() const throw()
	{
		std::string msg("");
		msg += mParam;
		msg += " = ";
		msg += mVal;
		return msg.c_str();
	}
private:
	std::string mParam;
	std::string mVal;
};

class PortSetupException : public std::exception
{
public:
	PortSetupException(const char *errstr) : mErrStr(errstr) { }
	~PortSetupException() throw() { }
	virtual const char* what() const throw() { return mErrStr.c_str(); }
private:
	std::string mErrStr;

};
} /* namespace kserial */
#endif /* SERIALPORT_H_ */
