這裏採用字符串池實現串口數據接收,串口類改自一個老外寫的CSerialPort類。
/*
** FILENAME CSerialPort.h
**
** PURPOSE This class can read, write and watch one serial port.
** It sends messages to its owner when something happends on the port
** The class creates a thread for reading and writing so the main
** program is not blocked.
**
** CREATION DATE 15-09-1997
** LAST MODIFICATION 12-11-1997
**
** AUTHOR Remon Spekreijse
**
**
*/
#include "stringpool.h"
#ifndef __SERIALPORT_H__
#define __SERIALPORT_H__
#define WM_COMM_BREAK_DETECTED WM_USER+1 // A break was detected on input.
#define WM_COMM_CTS_DETECTED WM_USER+2 // The CTS (clear-to-send) signal changed state.
#define WM_COMM_DSR_DETECTED WM_USER+3 // The DSR (data-set-ready) signal changed state.
#define WM_COMM_ERR_DETECTED WM_USER+4 // A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
#define WM_COMM_RING_DETECTED WM_USER+5 // A ring indicator was detected.
#define WM_COMM_RLSD_DETECTED WM_USER+6 // The RLSD (receive-line-signal-detect) signal changed state.
#define WM_COMM_RXCHAR WM_USER+7 // A character was received and placed in the input buffer.
#define WM_COMM_RXFLAG_DETECTED WM_USER+8 // The event character was received and placed in the input buffer.
#define WM_COMM_TXEMPTY_DETECTED WM_USER+9 // The last character in the output buffer was sent.
class CSerialPort
{
public:
// contruction and destruction
CSerialPort();
virtual ~CSerialPort();
// port initialisation
BOOL InitPort(CWinThread* pPortOwner, UINT portnr = 1, UINT baud = 19200, char parity = 'N', UINT databits = 8, UINT stopsbits = 1, DWORD dwCommEvents = EV_RXCHAR | EV_CTS, UINT nBufferSize = 512);
// start/stop comm watching
BOOL StartMonitoring();
BOOL RestartMonitoring();
BOOL StopMonitoring();
DWORD GetWriteBufferSize();
DWORD GetCommEvents();
DCB GetDCB();
std::string *GetFrontString();
void WriteToPort(char* string);
protected:
// protected memberfunctions
void ProcessErrorMessage(char* ErrorText);
static UINT CommThread(LPVOID pParam);
static void ReceiveChar(CSerialPort* port, COMSTAT comstat);
static void WriteChar(CSerialPort* port);
// thread
CWinThread* m_Thread;
// synchronisation objects
CRITICAL_SECTION m_csCommunicationSync;
CRITICAL_SECTION m_csQueLock; //隊列鎖
BOOL m_bThreadAlive;
//事件對象
HANDLE m_hShutdownEvent;
HANDLE m_hComm;
HANDLE m_hWriteEvent;
HANDLE m_hEventArray[3];
// structures
OVERLAPPED m_ov;
COMMTIMEOUTS m_CommTimeouts;
DCB m_dcb;
public:
CWinThread* m_pOwner;
StringPool *m_pStringPool;
// misc
UINT m_nPortNr;
char* m_szWriteBuffer;
DWORD m_dwCommEvents;
DWORD m_nWriteBufferSize;
UINT m_nDataLen;
queue<string *> m_strQue; //字符串接收隊列
};
#endif __SERIALPORT_H__
/*
** FILENAME CSerialPort.cpp
**
** PURPOSE This class can read, write and watch one serial port.
** It sends messages to its owner when something happends on the port
** The class creates a thread for reading and writing so the main
** program is not blocked.
**
** CREATION DATE 15-09-1997
** LAST MODIFICATION 12-11-1997
**
** AUTHOR Remon Spekreijse
**
**
*/
#include "stdafx.h"
#include "SerialPort.h"
#include <assert.h>
//
// Constructor
//
CSerialPort::CSerialPort()
{
m_hComm = NULL;
// initialize overlapped structure members to zero
m_ov.Offset = 0;
m_ov.OffsetHigh = 0;
// create events
m_ov.hEvent = NULL;
m_hWriteEvent = NULL;
m_hShutdownEvent = NULL;
m_szWriteBuffer = NULL;
m_bThreadAlive = FALSE;
}
//
// Delete dynamic memory
//
CSerialPort::~CSerialPort()
{
do
{
SetEvent(m_hShutdownEvent);
} while (m_bThreadAlive);
TRACE("Thread ended\n");
delete [] m_szWriteBuffer;
}
//
// Initialize the port. This can be port 1 to 4.
//
BOOL CSerialPort::InitPort(CWinThread* pPortOwner, // the owner (CWinTread) of the port (receives message)
UINT portnr, //端口號
UINT baud, //波特率
char parity, //奇偶校驗位
UINT databits, //數據位
UINT stopbits, // 停止位
DWORD dwCommEvents, // 準備監視的串口事件掩碼
UINT writebuffersize) // 寫緩衝區大小
{
assert(portnr > 0 && portnr < 5);
assert(pPortOwner != NULL);
//判斷線程是否啓動,否則結束線程
if (m_bThreadAlive)
{
do
{
SetEvent(m_hShutdownEvent);
} while (m_bThreadAlive);
TRACE("Thread ended\n");
}
//重疊事件對象
if (m_ov.hEvent != NULL)
ResetEvent(m_ov.hEvent);
m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
//寫事件對象
if (m_hWriteEvent != NULL)
ResetEvent(m_hWriteEvent);
m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
//線程退出事件對象,有信號則線程退出
if (m_hShutdownEvent != NULL)
ResetEvent(m_hShutdownEvent);
m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// initialize the event objects
m_hEventArray[0] = m_hShutdownEvent; // highest priority
m_hEventArray[1] = m_ov.hEvent;
m_hEventArray[2] = m_hWriteEvent;
InitializeCriticalSection(&m_csCommunicationSync);
InitializeCriticalSection(&m_csQueLock);
// set buffersize for writing and save the owner
m_pOwner = pPortOwner;
m_pStringPool = new StringPool;
if (m_szWriteBuffer != NULL)
delete [] m_szWriteBuffer;
m_szWriteBuffer = new char[writebuffersize];
m_nPortNr = portnr;
m_nWriteBufferSize = writebuffersize;
m_dwCommEvents = dwCommEvents;
m_nDataLen = 15;
BOOL bResult = FALSE;
char *szPort = new char[50];
char *szBaud = new char[50];
//鎖住串口,防止對同一串口進行操作
EnterCriticalSection(&m_csCommunicationSync);
if (m_hComm != NULL)
{
CloseHandle(m_hComm);
m_hComm = NULL;
}
//串口連接字符串
sprintf(szPort, "COM%d", portnr);
sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, stopbits);
//打開串口
m_hComm = CreateFileA(szPort, //串口號
GENERIC_READ | GENERIC_WRITE, // 允許讀寫
0, // 以獨佔模式打開
NULL, // 無安全屬性
OPEN_EXISTING, // 通訊設備已存在
FILE_FLAG_OVERLAPPED, // 異步IO
0); //通訊設備不能用模板打開
if (m_hComm == INVALID_HANDLE_VALUE)
{
// 串口未找到
delete [] szPort;
delete [] szBaud;
return FALSE;
}
// 設置超時值
m_CommTimeouts.ReadIntervalTimeout = 1000;
m_CommTimeouts.ReadTotalTimeoutMultiplier = 1000;
m_CommTimeouts.ReadTotalTimeoutConstant = 1000;
m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000;
m_CommTimeouts.WriteTotalTimeoutConstant = 1000;
if (SetCommTimeouts(m_hComm, &m_CommTimeouts))
{
//設置串口要監視的事件
if (SetCommMask(m_hComm, dwCommEvents))
{
//讀取串口配置
if (GetCommState(m_hComm, &m_dcb))
{
m_dcb.fRtsControl = RTS_CONTROL_ENABLE; // set RTS bit high!
//連接串口
if (BuildCommDCBA(szBaud, &m_dcb))
{
//修改串口配置
if (SetCommState(m_hComm, &m_dcb))
; // normal operation... continue
else
ProcessErrorMessage("SetCommState()");
}
else
ProcessErrorMessage("BuildCommDCB()");
}
else
ProcessErrorMessage("GetCommState()");
}
else
ProcessErrorMessage("SetCommMask()");
}
else
ProcessErrorMessage("SetCommTimeouts()");
delete [] szPort;
delete [] szBaud;
// 清空緩衝區
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
LeaveCriticalSection(&m_csCommunicationSync);
TRACE("Initialisation for communicationport %d completed.\nUse Startmonitor to communicate.\n", portnr);
return TRUE;
}
UINT CSerialPort::CommThread(LPVOID pParam)
{
CSerialPort *port = (CSerialPort*)pParam;
//串口線程運行標誌
port->m_bThreadAlive = TRUE;
DWORD BytesTransfered = 0;
DWORD Event = 0;
DWORD CommEvent = 0;
DWORD dwError = 0;
COMSTAT comstat;
BOOL bResult = TRUE;
//檢查串口是否打開
if (port->m_hComm)
PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
//初始化COMSTAT
ClearCommError(port->m_hComm, &dwError, &comstat);
for (;;)
{
//等待串口事件發生,異步操作直接返回
bResult = WaitCommEvent(port->m_hComm, &Event, &port->m_ov);
if (!bResult)
{
//錯誤處理
switch (dwError = GetLastError())
{
case ERROR_IO_PENDING:
{
break;
}
case 87:
{
//特殊處理
break;
}
default:
{
port->ProcessErrorMessage("WaitCommEvent()");
break;
}
}
}
//正常處理
else
{
//清除串口的通信錯誤,返回當前的錯誤狀態
bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
//串口未發送數據
if (comstat.cbInQue == 0)
continue;
}
//等待串口事件發生
Event = WaitForMultipleObjects(3, port->m_hEventArray, FALSE, INFINITE);
switch (Event)
{
case 0:
{
//0號事件對象擁有高優先權,會優先到達
port->m_bThreadAlive = FALSE;
//線程直接退出
AfxEndThread(100);
break;
}
case 1: // 讀事件
{
//讀取串口事件掩碼
GetCommMask(port->m_hComm, &CommEvent);
if (CommEvent & EV_CTS)//CTS信號狀態發生變化
::PostThreadMessage(port->m_pOwner->m_nThreadID, WM_COMM_CTS_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_RXFLAG)//接收到事件字符,並置於輸入緩衝區中
::PostThreadMessage(port->m_pOwner->m_nThreadID, WM_COMM_RXFLAG_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_BREAK) //輸入中發生中斷
::PostThreadMessage(port->m_pOwner->m_nThreadID, WM_COMM_BREAK_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_ERR)//發生線路狀態錯誤,線路狀態錯誤包括CE_FRAME,CE_OVERRUN和CE_RXPARITY
::PostThreadMessage(port->m_pOwner->m_nThreadID, WM_COMM_ERR_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_RING)//檢測到振鈴指示
::PostThreadMessage(port->m_pOwner->m_nThreadID, WM_COMM_RING_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
if (CommEvent & EV_RXCHAR)
//接收到字符,並置於輸入緩衝區中
ReceiveChar(port, comstat);
break;
}
case 2: // 寫事件
{
WriteChar(port);
break;
}
}
}
return 0;
}
BOOL CSerialPort::StartMonitoring()
{
if (!(m_Thread = AfxBeginThread(CommThread, this)))
return FALSE;
TRACE("Thread started\n");
return TRUE;
}
//喚醒線程
BOOL CSerialPort::RestartMonitoring()
{
TRACE("Thread resumed\n");
m_Thread->ResumeThread();
return TRUE;
}
//線程掛起
BOOL CSerialPort::StopMonitoring()
{
TRACE("Thread suspended\n");
m_Thread->SuspendThread();
return TRUE;
}
//查找詳細錯誤信息
void CSerialPort::ProcessErrorMessage(char* ErrorText)
{
char *Temp = new char[200];
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
sprintf(Temp, "WARNING: %s Failed with the following error: \n%s\nPort: %d\n", (char*)ErrorText, lpMsgBuf, m_nPortNr);
MessageBoxA(NULL, Temp, "Application Error", MB_ICONSTOP);
LocalFree(lpMsgBuf);
delete[] Temp;
}
void CSerialPort::WriteChar(CSerialPort* port)
{
BOOL bWrite = TRUE;
BOOL bResult = TRUE;
DWORD BytesSent = 0;
ResetEvent(port->m_hWriteEvent);
// Gain ownership of the critical section
EnterCriticalSection(&port->m_csCommunicationSync);
if (bWrite)
{
// Initailize variables
port->m_ov.Offset = 0;
port->m_ov.OffsetHigh = 0;
// Clear buffer
PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
bResult = WriteFile(port->m_hComm,
port->m_szWriteBuffer, // 發送緩衝區首地址
strlen((char*)port->m_szWriteBuffer), // 消息發送長度
&BytesSent, // 實際寫入字節數的存儲區域指針
&port->m_ov);
// deal with any error codes
if (!bResult)
{
DWORD dwError = GetLastError();
switch (dwError)
{
case ERROR_IO_PENDING:
{
// continue to GetOverlappedResults()
BytesSent = 0;
bWrite = FALSE;
break;
}
default:
{
// all other error codes
port->ProcessErrorMessage("WriteFile()");
}
}
}
else
{
LeaveCriticalSection(&port->m_csCommunicationSync);
}
} // end if(bWrite)
if (!bWrite)
{
bWrite = TRUE;
bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port
&port->m_ov, // Overlapped structure
&BytesSent, // 發送字節數
TRUE); // 等待標誌
LeaveCriticalSection(&port->m_csCommunicationSync);
// deal with the error code
if (!bResult)
{
port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()");
}
}
//驗證是否是期望發送長度
if (BytesSent != strlen((char*)port->m_szWriteBuffer))
{
TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)port->m_szWriteBuffer));
}
}
void CSerialPort::ReceiveChar(CSerialPort* port, COMSTAT comstat)
{
BOOL bRead = TRUE;
BOOL bResult = TRUE;
DWORD dwError = 0;
DWORD BytesRead = 0;
unsigned char RXBuff[1024];
int nRecvChar = 1;
memset(RXBuff, 0, 1024);
for (;;)
{
//獲得串口權限
EnterCriticalSection(&port->m_csCommunicationSync);
////清除串口的通信錯誤返回當前串口狀態
bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
LeaveCriticalSection(&port->m_csCommunicationSync);
// start forever loop. I use this type of loop because I
// do not know at runtime how many loops this will have to
// run. My solution is to start a forever loop and to
// break out of it when I have processed all of the
// data available. Be careful with this approach and
// be sure your loop will exit.
// My reasons for this are not as clear in this sample
// as it is in my production code, but I have found this
// solutiion to be the most efficient way to do this.
if (comstat.cbInQue == 0)
{
//接收緩衝區爲空直接退出
break;
}
EnterCriticalSection(&port->m_csCommunicationSync);
//讀緩衝區
if (bRead)
{
bResult = ReadFile(port->m_hComm, // 串口句柄
&RXBuff, // 讀緩衝區地址
nRecvChar, // 要讀取的長度
&BytesRead, // 讀取長度
&port->m_ov);
//正常返回值爲FALSE,調用GetOverlappedResult獲取重疊結果
if (!bResult)
{
switch (dwError = GetLastError())
{
case ERROR_IO_PENDING:
{
bRead = FALSE;
break;
}
default:
{
port->ProcessErrorMessage("ReadFile()");
break;
}
}
}
else
{
//讀取操作完成,不需要調用GetOverlappedResult
bRead = TRUE;
}
}
//獲取異步結果
if (!bRead)
{
//重置bRead
bRead = TRUE;
bResult = GetOverlappedResult(port->m_hComm,
&port->m_ov,
&BytesRead, //返回讀取的長度
TRUE); // 等待標誌
if (!bResult)
{
port->ProcessErrorMessage("GetOverlappedResults() in ReadFile()");
}
}
if (bRead)
{
if (RXBuff[0] == '#')
{
nRecvChar = port->m_nDataLen;
continue;
}
if (strlen((char*)&RXBuff[0]) < port->m_nDataLen)
{
nRecvChar = 1;
continue;
}
std::string *pStrMsg = (port->m_pStringPool)->GetAString();
pStrMsg->assign((char *)&RXBuff[0], BytesRead);
if (pStrMsg->find('#') != std::string::npos)
{
nRecvChar = 1;
(port->m_pStringPool)->ReleaseAString(pStrMsg);
continue;
}
nRecvChar = 1;
//將字符串放入接收隊列
EnterCriticalSection(&port->m_csQueLock);
port->m_strQue.push(pStrMsg);
LeaveCriticalSection(&port->m_csQueLock);
}
LeaveCriticalSection(&port->m_csCommunicationSync);
::PostThreadMessage((port->m_pOwner)->m_nThreadID, WM_COMM_RXCHAR, (WPARAM) port, (LPARAM) port->m_nPortNr);
}
}
void CSerialPort::WriteToPort(char* string)
{
assert(m_hComm != 0);
memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
strcpy(m_szWriteBuffer, string);
SetEvent(m_hWriteEvent);
}
//
// Return the device control block
//
DCB CSerialPort::GetDCB()
{
return m_dcb;
}
//
// Return the communication event masks
//
DWORD CSerialPort::GetCommEvents()
{
return m_dwCommEvents;
}
//
// Return the output buffer size
//
DWORD CSerialPort::GetWriteBufferSize()
{
return m_nWriteBufferSize;
}
std::string *CSerialPort::GetFrontString()
{
EnterCriticalSection(&m_csQueLock);
if (!m_strQue.empty())
{
string *pString = m_strQue.front();
m_strQue.pop();
LeaveCriticalSection(&m_csQueLock);
return pString;
}
else
{
LeaveCriticalSection(&m_csQueLock);
return NULL;
}
}