这里采用字符串池实现串口数据接收,串口类改自一个老外写的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 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
//
// 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;
}
}