#ifndef __SERIAL_PORT_FILE_H__
#define __SERIAL_PORT_FILE_H__
//#pragma warning(disable:4996)

#ifdef SERIAL_PORT_EXPORTS
#define CSerialPort_DLL_API __declspec(dllexport)
#else
#define CSerialPort_DLL_API //__declspec(dllimport)
#endif

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "assert.h" 
#include <iostream>
#include <cstdarg>
#include <sstream>
#include <string>

using std::string;

#define SERIAL_PORT_BASE_ERROR (-90000)

typedef enum
{
	COM_OK = 0,
	COM_FAIL = -1,
	SERIAL_PORT_BASE_FAIL = SERIAL_PORT_BASE_ERROR,
	COM_NO_OPEN,
	SET_TIME_OUT_FAIL,
	GET_COM_PRAM_FAIL,
	SET_COM_PRAM_FAIL,
	SET_COM_BUF_FAIL,
	CLEAR_COM_BUF_FAIL,
	COM_OPEN_FAIL,
	COM_READ_FAIL,
	COM_WRITE_FAIL,
	INPUT_NULL_FAIL,
	NOT_INIT_FAIL
} COMERR;

class CSerialPort_DLL_API CRS232
{
private:
	DCB m_stDcb;
	COMMTIMEOUTS m_CommTimerOuts;
	HANDLE m_hCom = INVALID_HANDLE_VALUE;

	OVERLAPPED m_overlappedRead;
	OVERLAPPED m_overlappedWrite;


private:
	inline bool IsOpen();
	long SetTimerOut(unsigned long dwTimerOut = 5000);
	long SetDCBParm(unsigned long xBabd, unsigned char xDataSize,
		unsigned char xParity, unsigned char xStopBit);
	long SetPortBuffSize(unsigned long InputBuffSize, unsigned long OutputBuffSize);
	long GetInBuffCount();
	long GetOutBuffCount();

public:
	long OpenPort(unsigned long xPort, unsigned long xBabd, unsigned char xDataSize,
		unsigned char xParity, unsigned char xStopBit, unsigned long InputBuffSize,
		unsigned long OutputBuffSize, unsigned long dwTimerOut);
	long OpenPort(char *strPort, unsigned long xBabd, unsigned char xDataSize,
		unsigned char xParity, unsigned char xStopBit, unsigned long InputBuffSize,
		unsigned long OutputBuffSize, unsigned long dwTimerOut);
	void ClosePort();
	
	void ClearBuffer();

	long SerialPortRead(unsigned long dwBufferLength, char *buff, unsigned long dwWaitTime);
	long SerialPortWrite(unsigned long dwBufferLength, char *buff);

	static string GetErrText(long errid);

};

#endif