// SerialCommHelper.h: interface for the CSerialCommHelper class.
//
//////////////////////////////////////////////////////////////////////

#pragma once

#include "robbase.h"
#include "SerialBuffer.h"
#include <map>

typedef enum tagSERIAL_STATE
{
	SS_Unknown,
	SS_UnInit,
	SS_Init,
	SS_Started ,
	SS_Stopped ,
} SERIAL_STATE;

class ROBBASE_API CSerialCommHelper  
{
private:
	
	HANDLE	m_hCommPort;
	HANDLE	m_hThreadTerm ;
	HANDLE	m_hThread;
	HANDLE	m_hThreadStarted;
	HANDLE	m_hDataRx;
	bool	m_abIsConnected;
	void	InvalidateHandle(HANDLE& hHandle );
	void	CloseAndCleanHandle(HANDLE& hHandle) ;
	
	CSerialBuffer m_theSerialBuffer;
	CRITICAL_SECTION m_csLock;
	

protected:
	SERIAL_STATE	m_eState;
	

public:
	CSerialCommHelper();
	virtual ~CSerialCommHelper();

	SERIAL_STATE GetCurrentState() {return m_eState;}

	//void		GetEventToWaitOn(HANDLE* hEvent) {*hEvent = m_hDataRx;}
	HANDLE	GetWaitForEvent() {return m_hDataRx;} 

	inline void		LockThis()			{EnterCriticalSection ( &m_csLock );}	
	inline void		UnLockThis()		{LeaveCriticalSection (&m_csLock); }
	inline void		InitLock()			{InitializeCriticalSection (&m_csLock );}
	inline void		DelLock()				{DeleteCriticalSection (&m_csLock );}
 	
	inline bool		IsInputAvailable()
	{
		LockThis (); 
		bool abData = ( !m_theSerialBuffer.IsEmpty() ) ;
		UnLockThis (); 
		return abData;
	} 

	inline bool		IsConnection() {return m_abIsConnected ;}
 	
	inline void		SetDataReadEvent()	{		SetEvent ( m_hDataRx );	}
	

	HRESULT  		ReadN		(char* pszData,long  alCount,long alTimeOut);
	HRESULT			ReadUpto	(char* pszData,char chTerminator ,long *pAlCount,long alTimeOut);
	//HRESULT			ReadAvailable(std::string& data);

	int  Read(char* pszData, long alCount,long alTimeOut);

	HRESULT			Write (const char* data,DWORD dwSize);

	//byStopBits为1，2，或其它值（ONE5STOPBITS）。 WINDOW: StopBits; /* 0,1,2 = 1, 1.5, 2               */
	//Parity;          /* 0-4=None,Odd,Even,Mark,Space    */
	//ByteSize;        /* Number of bits/byte, 4-8        */
	HRESULT			Init(const char*  szPortName=  "COM1" , DWORD dwBaudRate = 9600,BYTE byParity = 0,BYTE byStopBits = 1,BYTE byByteSize  = 8, int recvBuffSize = 1024);
	virtual BOOL			Start();
	virtual void		Stop();
	HRESULT			UnInit();

	static unsigned __stdcall ThreadFn(void*pvParam);
	//-- helper fn.
 	HRESULT  CanProcess();
	void OnSetDebugOption(long  iOpt,BOOL bOnOff);
	
};


