在这里插入代码片
```
#ifndef _CN_COMM_H_
#define _CN_COMM_H_
#pragma warning(disable: 4530)
#pragma warning(disable: 4786)
#pragma warning(disable: 4800)
#include <assert.h>
#include <stdio.h>
#include <windows.h>
#define ON_COM_RECEIVE WM_USER + 618
#define ON_COM_CTS WM_USER + 619
#define ON_COM_DSR WM_USER + 621
#define ON_COM_RING WM_USER + 623
#define ON_COM_RLSD WM_USER + 624
#define ON_COM_BREAK WM_USER + 625
#define ON_COM_TXEMPTY WM_USER + 626
#define ON_COM_ERROR WM_USER + 627
#define DEFAULT_COM_MASK_EVENT EV_RXCHAR | EV_ERR | EV_CTS | EV_DSR | EV_BREAK | EV_TXEMPTY | EV_RING | EV_RLSD
class cnComm
{
public:
cnComm(bool fAutoBeginThread = true, DWORD dwIOMode = FILE_FLAG_OVERLAPPED)
: _dwIOMode(dwIOMode), _fAutoBeginThread(fAutoBeginThread)
{
Init();
}
virtual ~cnComm()
{
Close();
UnInit();
}
inline bool IsOpen()
{
return _hCommHandle != INVALID_HANDLE_VALUE;
}
operator bool ()
{
return _hCommHandle != INVALID_HANDLE_VALUE;
}
inline HANDLE GetHandle()
{
return _hCommHandle;
}
operator HANDLE()
{
return _hCommHandle;
}
DCB *GetState()
{
return IsOpen() && ::GetCommState(_hCommHandle, &_DCB) ? &_DCB : NULL;
}
bool SetState(DCB *pdcb = NULL)
{
return IsOpen() ? ::SetCommState(_hCommHandle, pdcb == NULL ? &_DCB : pdcb) == TRUE : false;
}
bool SetState(char *szSetStr)
{
if(IsOpen())
{
if(!::GetCommState(_hCommHandle, &_DCB))
return false;
if(!::BuildCommDCBA(szSetStr, &_DCB))
return false;
return ::SetCommState(_hCommHandle, &_DCB) == TRUE;
}
return false;
}
bool SetState(DWORD dwBaudRate, DWORD dwByteSize = 8, DWORD dwParity = NOPARITY, DWORD dwStopBits = ONESTOPBIT)
{
if(IsOpen())
{
if(!::GetCommState(_hCommHandle, &_DCB))
return false;
_DCB.BaudRate = dwBaudRate;
_DCB.ByteSize = (unsigned char)dwByteSize;
_DCB.Parity = (unsigned char)dwParity;
_DCB.StopBits = (unsigned char)dwStopBits;
return ::SetCommState(_hCommHandle, &_DCB) == TRUE;
}
return false;
}
LPCOMMTIMEOUTS GetTimeouts(void)
{
return IsOpen() && ::GetCommTimeouts(_hCommHandle, &_CO) ? &_CO : NULL;
}
bool SetTimeouts(LPCOMMTIMEOUTS lpCO)
{
return IsOpen() ? ::SetCommTimeouts(_hCommHandle, lpCO) == TRUE : false;
}
bool SetBufferSize(DWORD dwInputSize, DWORD dwOutputSize)
{
return IsOpen() ? ::SetupComm(_hCommHandle, dwInputSize, dwOutputSize) == TRUE : false;
}
inline void SetWnd(HWND hWnd)
{
assert(::IsWindow(hWnd));
_hNotifyWnd = hWnd;
}
inline void SetNotifyNum(DWORD dwNum)
{
_dwNotifyNum = dwNum;
}
inline bool IsThreadRunning()
{
return _hThreadHandle != NULL;
}
inline HANDLE GetThread()
{
return _hThreadHandle;
}
void SetMaskEvent(DWORD dwEvent = DEFAULT_COM_MASK_EVENT)
{
_dwMaskEvent = dwEvent;
}
int GetInputSize()
{
COMSTAT Stat;
DWORD dwError;
return ::ClearCommError(_hCommHandle, &dwError, &Stat) ? Stat.cbInQue : (DWORD)-1L;
}
bool Open(DWORD dwPort)
{
return Open(dwPort, 9600);
}
bool Open(DWORD dwPort, DWORD dwBaudRate)
{
if(dwPort < 1 || dwPort > 1024)
return false;
BindCommPort(dwPort);
if(!OpenCommPort())
return false;
if(!SetupPort())
return false;
return SetState(dwBaudRate);
}
bool Open(DWORD dwPort, char *szSetStr)
{
if(dwPort < 1 || dwPort > 1024)
return false;
BindCommPort(dwPort);
if(!OpenCommPort())
return false;
if(!SetupPort())
return false;
return SetState(szSetStr);
}
BOOL flushinput()
{
return(PurgeComm(_hCommHandle,PURGE_RXCLEAR));
}
DWORD Read(LPVOID Buffer, DWORD dwBufferLength, DWORD dwWaitTime = 20000)
{
if(!IsOpen())
return 0;
COMSTAT Stat;
DWORD dwError;
if(::ClearCommError(_hCommHandle, &dwError, &Stat) && dwError > 0)
{
::PurgeComm(_hCommHandle, PURGE_RXABORT | PURGE_RXCLEAR);
return 0;
}
if(!Stat.cbInQue)
return 0;
unsigned long uReadLength = 0;
dwBufferLength = dwBufferLength > Stat.cbInQue ? Stat.cbInQue : dwBufferLength;
if(!::ReadFile(_hCommHandle, Buffer, dwBufferLength, &uReadLength, &_ReadOverlapped))
{
if(::GetLastError() == ERROR_IO_PENDING)
{
WaitForSingleObject(_ReadOverlapped.hEvent, dwWaitTime);
if(!::GetOverlappedResult(_hCommHandle, &_ReadOverlapped, &uReadLength, false))
{
if(::GetLastError() != ERROR_IO_INCOMPLETE)
uReadLength = 0;
}
}
else
uReadLength = 0;
}
return uReadLength;
}
char * ReadString(char *szBuffer, DWORD dwBufferLength, DWORD dwWaitTime = 20)
{
unsigned long uReadLength = Read(szBuffer, dwBufferLength - 1, dwWaitTime);
szBuffer[uReadLength] = '\0';
return szBuffer;
}
DWORD Write(LPVOID Buffer, DWORD dwBufferLength)
{
if(!IsOpen())
return 0;
DWORD dwError;
if(::ClearCommError(_hCommHandle, &dwError, NULL) && dwError > 0)
::PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_TXCLEAR);
unsigned long uWriteLength = 0;
if(!::WriteFile(_hCommHandle, Buffer, dwBufferLength, &uWriteLength, &_WriteOverlapped))
if(::GetLastError() != ERROR_IO_PENDING)
uWriteLength = 0;
return uWriteLength;
}
DWORD Write(const char *szBuffer)
{
assert(szBuffer);
return Write((void *)szBuffer, strlen(szBuffer));
}
DWORD WriteSync(LPVOID Buffer, DWORD dwBufferLength)
{
if(!IsOpen())
return 0;
DWORD dwError;
if(::ClearCommError(_hCommHandle, &dwError, NULL) && dwError > 0)
::PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_TXCLEAR);
unsigned long uWriteLength = 0;
::WriteFile(_hCommHandle, Buffer, dwBufferLength, &uWriteLength, NULL);
return uWriteLength;
}
DWORD Write(char *szBuffer, DWORD dwBufferLength, char * szFormat, ...)
{
if(!IsOpen())
return 0;
va_list va;
va_start(va, szFormat);
_vsnprintf(szBuffer, dwBufferLength, szFormat, va);
va_end(va);
return Write(szBuffer);
}
DWORD Write(char *szBuffer, char * szFormat, ...)
{
if(!IsOpen())
return 0;
va_list va;
va_start(va, szFormat);
vsprintf(szBuffer, szFormat, va);
va_end(va);
return Write(szBuffer);
}
virtual void Close()
{
if(IsOpen())
{
PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_TXCLEAR);
EndThread();
::CloseHandle(_hCommHandle);
_hCommHandle = INVALID_HANDLE_VALUE;
}
}
bool SetDTR(bool OnOrOff)
{
return IsOpen() ? EscapeCommFunction(_hCommHandle, OnOrOff ? SETDTR : CLRDTR) : false;
}
bool SetRTS(bool OnOrOff)
{
return IsOpen() ? EscapeCommFunction(_hCommHandle, OnOrOff ? SETRTS : CLRRTS) : false;
}
bool SetBreak(bool OnOrOff)
{
return IsOpen() ? EscapeCommFunction(_hCommHandle, OnOrOff ? SETBREAK : CLRBREAK) : false;
}
bool BeginThread()
{
if(!IsThreadRunning())
{
_fRunFlag = true;
_hThreadHandle = NULL;
DWORD id;
_hThreadHandle = ::CreateThread(NULL, 0, CommThreadProc, this, 0, &id);
return (_hThreadHandle != NULL);
}
return false;
}
inline bool SuspendThread()
{
return IsThreadRunning() ? ::SuspendThread(_hThreadHandle) != 0xFFFFFFFF : false;
}
inline bool ResumeThread()
{
return IsThreadRunning() ? ::ResumeThread(_hThreadHandle) != 0xFFFFFFFF : false;
}
bool EndThread(DWORD dwWaitTime = 100)
{
if(IsThreadRunning())
{
_fRunFlag = false;
::SetCommMask(_hCommHandle, 0);
::SetEvent(_WaitOverlapped.hEvent);
if(::WaitForSingleObject(_hThreadHandle, dwWaitTime) != WAIT_OBJECT_0)
if(!::TerminateThread(_hThreadHandle, 0))
return false;
::CloseHandle(_hThreadHandle);
::ResetEvent(_WaitOverlapped.hEvent);
_hThreadHandle = NULL;
return true;
}
return false;
}
protected:
volatile DWORD _dwPort;
volatile HANDLE _hCommHandle;
char _szCommStr[20];
DCB _DCB;
COMMTIMEOUTS _CO;
DWORD _dwIOMode;
OVERLAPPED _ReadOverlapped, _WriteOverlapped;
volatile HANDLE _hThreadHandle;
volatile HWND _hNotifyWnd;
volatile DWORD _dwNotifyNum;
volatile DWORD _dwMaskEvent;
volatile bool _fRunFlag;
bool _fAutoBeginThread;
OVERLAPPED _WaitOverlapped;
void Init()
{
memset(_szCommStr, 0, 20);
memset(&_DCB, 0, sizeof(_DCB));
_DCB.DCBlength = sizeof(_DCB);
_hCommHandle = INVALID_HANDLE_VALUE;
memset(&_ReadOverlapped, 0, sizeof(_ReadOverlapped));
memset(&_WriteOverlapped, 0, sizeof(_WriteOverlapped));
_ReadOverlapped.hEvent = ::CreateEvent(NULL, true, false, NULL);
assert(_ReadOverlapped.hEvent != INVALID_HANDLE_VALUE);
_WriteOverlapped.hEvent = ::CreateEvent(NULL, true, false, NULL);
assert(_WriteOverlapped.hEvent != INVALID_HANDLE_VALUE);
_hNotifyWnd = NULL;
_dwNotifyNum = 0;
_dwMaskEvent = DEFAULT_COM_MASK_EVENT;
_hThreadHandle = NULL;
memset(&_WaitOverlapped, 0, sizeof(_WaitOverlapped));
_WaitOverlapped.hEvent = ::CreateEvent(NULL, true, false, NULL);
assert(_WaitOverlapped.hEvent != INVALID_HANDLE_VALUE);
}
void UnInit()
{
if(_ReadOverlapped.hEvent != INVALID_HANDLE_VALUE)
CloseHandle(_ReadOverlapped.hEvent);
if(_WriteOverlapped.hEvent != INVALID_HANDLE_VALUE)
CloseHandle(_WriteOverlapped.hEvent);
if(_WaitOverlapped.hEvent != INVALID_HANDLE_VALUE)
CloseHandle(_WaitOverlapped.hEvent);
}
void BindCommPort(DWORD dwPort)
{
assert(dwPort >= 1 && dwPort <= 1024);
char p[5];
_dwPort = dwPort;
strcpy(_szCommStr, "\\\\.\\COM");
ltoa(_dwPort, p, 10);
strcat(_szCommStr, p);
}
virtual bool OpenCommPort()
{
if(IsOpen())
Close();
_hCommHandle = ::CreateFileA(
_szCommStr,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | _dwIOMode,
NULL
);
if(_fAutoBeginThread)
{
if(IsOpen() && BeginThread())
return true;
else
{
Close();
return false;
}
}
return IsOpen();
}
virtual bool SetupPort()
{
if(!IsOpen())
return false;
if(!::SetupComm(_hCommHandle, 20000, 20000))
return false;
if(!::GetCommTimeouts(_hCommHandle, &_CO))
return false;
_CO.ReadIntervalTimeout = 0xFFFFFFFF;
_CO.ReadTotalTimeoutMultiplier = 0;
_CO.ReadTotalTimeoutConstant = 0;
_CO.WriteTotalTimeoutMultiplier = 0;
_CO.WriteTotalTimeoutConstant = 2000;
if(!::SetCommTimeouts(_hCommHandle, &_CO))
return false;
if(!::PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ))
return false;
return true;
}
virtual void OnReceive()
{
if(::IsWindow(_hNotifyWnd))
::PostMessage(_hNotifyWnd, ON_COM_RECEIVE, WPARAM(_dwPort), LPARAM(0));
}
virtual void OnDSR()
{
if(::IsWindow(_hNotifyWnd))
{
DWORD Status;
if(GetCommModemStatus(_hCommHandle, &Status))
::PostMessage(_hNotifyWnd, ON_COM_DSR, WPARAM(_dwPort), LPARAM( (Status & MS_DSR_ON) ? 1 : 0));
}
}
virtual void OnCTS()
{
if(::IsWindow(_hNotifyWnd))
{
DWORD Status;
if(GetCommModemStatus(_hCommHandle, &Status))
::PostMessage(_hNotifyWnd, ON_COM_CTS, WPARAM(_dwPort), LPARAM( (Status & MS_CTS_ON) ? 1 : 0));
}
}
virtual void OnBreak()
{
if(::IsWindow(_hNotifyWnd))
{
::PostMessage(_hNotifyWnd, ON_COM_BREAK , WPARAM(_dwPort), LPARAM(0));
}
}
virtual void OnTXEmpty()
{
if(::IsWindow(_hNotifyWnd))
::PostMessage(_hNotifyWnd, ON_COM_TXEMPTY, WPARAM(_dwPort), LPARAM(0));
}
virtual void OnError()
{
DWORD dwError;
::ClearCommError(_hCommHandle, &dwError, NULL);
if(::IsWindow(_hNotifyWnd))
::PostMessage(_hNotifyWnd, ON_COM_ERROR, WPARAM(_dwPort), LPARAM(dwError));
}
virtual void OnRing()
{
if(::IsWindow(_hNotifyWnd))
::PostMessage(_hNotifyWnd, ON_COM_RING, WPARAM(_dwPort), LPARAM(0));
}
virtual void OnRLSD()
{
if(::IsWindow(_hNotifyWnd))
::PostMessage(_hNotifyWnd, ON_COM_RLSD, WPARAM(_dwPort), LPARAM(0));
}
virtual DWORD ThreadFunc()
{
if(!::SetCommMask(_hCommHandle, _dwMaskEvent))
{
char szBuffer[256];
_snprintf(szBuffer, 255, "%s(%d) : COM%d Call WINAPI SetCommMask(%x, %x) Fail, thread work invalid! GetLastError() = %d;",
__FILE__, __LINE__, _dwPort, _hCommHandle, _dwMaskEvent, GetLastError());
MessageBoxA(NULL, szBuffer, "Class cnComm", MB_OK);
return 1;
}
COMSTAT Stat;
DWORD dwError;
for(DWORD dwLength, dwMask = 0; _fRunFlag && IsOpen(); dwMask = 0)
{
if(!::WaitCommEvent(_hCommHandle, &dwMask, &_WaitOverlapped))
{
if(::GetLastError() == ERROR_IO_PENDING)
::GetOverlappedResult(_hCommHandle, &_WaitOverlapped, &dwLength, TRUE);
else
continue;
}
if(dwMask == 0)
continue;
switch(dwMask)
{
case EV_RXCHAR :
::ClearCommError(_hCommHandle, &dwError, &Stat);
if(Stat.cbInQue >= _dwNotifyNum)
OnReceive();
break;
case EV_TXEMPTY :
OnTXEmpty();
break;
case EV_CTS :
OnCTS();
break;
case EV_DSR :
OnDSR();
break;
case EV_RING :
OnRing();
break;
case EV_RLSD :
OnRLSD();
break;
case EV_BREAK:
OnBreak();
break;
case EV_ERR :
OnError();
break;
}
}
return 0;
}
private:
cnComm(const cnComm&);
const cnComm &operator = (const cnComm&);
static DWORD WINAPI CommThreadProc(LPVOID lpPara)
{
return ( (cnComm *)lpPara )->ThreadFunc();
}
};
#endif