CSerialPort串口类最新修正版(解决关闭死锁问题)2014-01-11

2023-05-16

 这是一份优秀的类文件,好多的地方值得我们学习,具体在多线程,事件,自定义消息,类的封装方面等等。
Remon提供的串口类网址为: http://codeguru.earthweb.com/network/serialport.shtml,
由于已经运行十几年了,原文的问答部分列出来这么多年来的问题,经过网友们的总结,补充和修改原来代码后,整理出一份相对比较完美的代码。


此外还附带一份小项目的源代码,它超越了串口助手,给人一种耳目一新的感觉。亮点如下:

1. 它解决了串口关闭时出现死锁不响应问题,可以直接用到开发的项目上。
2. 并且是扩展了的串口助手,具有通信协议编辑和使用功能,
3. 软件升级检测,值得做软件升级例子使用。
4. 最重要的是源代码很不错,很值得大家去研究。

   分享给需要的朋友们,有问题,可以在留言,以便做进一步修正。

VC串口修正类应用的小项目下载地址:http://download.csdn.net/detail/liquanhai/3763088

2014-01-11补充说明:

最新的CSerialPort类的下载地址在:https://github.com/liquanhai/CSerialPort



头文件CSerialPort.h如下:

/*
**	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
**
**
************************************************************************************
**  author: mrlong date:2007-12-25
**
**  改进
**    1) 增加ClosePort
**    2) 增加 writetoProt() 两个方法
**    3) 增加 SendData 与 RecvData 方法
**************************************************************************************
***************************************************************************************
**  author:liquanhai date:2011-11-04
**  改进
**    1)增加 ClosePort中交出控制权,防止死锁问题
**    2) 增加 ReceiveChar中防止线程死锁
 */

#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(CWnd* 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,
			
				DWORD ReadIntervalTimeout = 1000,
				DWORD ReadTotalTimeoutMultiplier = 1000,
				DWORD ReadTotalTimeoutConstant = 1000,
				DWORD WriteTotalTimeoutMultiplier = 1000,
				DWORD WriteTotalTimeoutConstant = 1000);

	// start/stop comm watching
	BOOL		StartMonitoring();
	BOOL		RestartMonitoring();
	BOOL		StopMonitoring();

	DWORD		GetWriteBufferSize();
	DWORD		GetCommEvents();
	DCB			GetDCB();

	void		WriteToPort(char* string);
	void        WriteToPort(char* string,int n); // add by mrlong 2007-12-25
	void		WriteToPort(LPCTSTR string);     // add by mrlong 2007-12-25
	void        WriteToPort(BYTE* Buffer, int n);// add by mrlong
	void        ClosePort();                     // add by mrlong 2007-12-2  

	void SendData(LPCTSTR lpszData, const int nLength);   //串口发送函数 by mrlong 2008-2-15
	BOOL RecvData(LPTSTR lpszData, const int nSize);      //串口接收函数 by mrlong 2008-2-15

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;
	BOOL				m_bThreadAlive;

	// handles
	HANDLE				m_hShutdownEvent;  //stop发生的事件
	HANDLE				m_hComm;           // read  
	HANDLE				m_hWriteEvent;     // write

	// Event array. 
	// One element is used for each event. There are two event handles for each port.
	// A Write event and a receive character event which is located in the overlapped structure (m_ov.hEvent).
	// There is a general shutdown when the port is closed. 
	HANDLE				m_hEventArray[3];

	// structures
	OVERLAPPED			m_ov;
	COMMTIMEOUTS		m_CommTimeouts;
	DCB					m_dcb;

	// owner window
	CWnd*				m_pOwner;

	// misc
	UINT				m_nPortNr;        //?????
	char*				m_szWriteBuffer;
	DWORD				m_dwCommEvents;
	DWORD				m_nWriteBufferSize;

	int                 m_nWriteSize; //add by mrlong 2007-12-25
};

#endif __SERIALPORT_H__


源文件cpp文件如下:

/*
**	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;
	m_nWriteSize = 1;
}

//
// Delete dynamic memory
//
CSerialPort::~CSerialPort()
{
	do
	{
		SetEvent(m_hShutdownEvent);
	} while (m_bThreadAlive);

	if (m_hComm != NULL)
	{
		CloseHandle(m_hComm);
		m_hComm = NULL;
	}
	// Close Handles  
	if(m_hShutdownEvent!=NULL)
		CloseHandle( m_hShutdownEvent); 
	if(m_ov.hEvent!=NULL)
		CloseHandle( m_ov.hEvent ); 
	if(m_hWriteEvent!=NULL)
		CloseHandle( m_hWriteEvent ); 

	TRACE("Thread ended\n");

	delete [] m_szWriteBuffer;
}

//
// Initialize the port. This can be port 1 to 4.
//
//
//parity:
//  n=none
//  e=even
//  o=odd
//  m=mark
//  s=space
//data:
//  5,6,7,8
//stop:
//  1,1.5,2 
//
BOOL CSerialPort::InitPort(CWnd* pPortOwner,	// the owner (CWnd) of the port (receives message)
						   UINT  portnr,		// portnumber (1..4)
						   UINT  baud,			// baudrate
						   char  parity,		// parity 
						   UINT  databits,		// databits 
						   UINT  stopbits,		// stopbits 
						   DWORD dwCommEvents,	// EV_RXCHAR, EV_CTS etc
						   UINT  writebuffersize,// size to the writebuffer
						   
						   DWORD   ReadIntervalTimeout,
						   DWORD   ReadTotalTimeoutMultiplier,
						   DWORD   ReadTotalTimeoutConstant,
						   DWORD   WriteTotalTimeoutMultiplier,
						   DWORD   WriteTotalTimeoutConstant )	

{
	assert(portnr > 0 && portnr < 5);
	assert(pPortOwner != NULL);

	// if the thread is alive: Kill
	if (m_bThreadAlive)
	{
		do
		{
			SetEvent(m_hShutdownEvent);
		} while (m_bThreadAlive);
		TRACE("Thread ended\n");
	}

	// create events
	if (m_ov.hEvent != NULL)
		ResetEvent(m_ov.hEvent);
	else
		m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	if (m_hWriteEvent != NULL)
		ResetEvent(m_hWriteEvent);
	else
		m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	
	if (m_hShutdownEvent != NULL)
		ResetEvent(m_hShutdownEvent);
	else
		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;

	// initialize critical section
	InitializeCriticalSection(&m_csCommunicationSync);
	
	// set buffersize for writing and save the owner
	m_pOwner = pPortOwner;

	if (m_szWriteBuffer != NULL)
		delete [] m_szWriteBuffer;
	m_szWriteBuffer = new char[writebuffersize];

	m_nPortNr = portnr;

	m_nWriteBufferSize = writebuffersize;
	m_dwCommEvents = dwCommEvents;

	BOOL bResult = FALSE;
	char *szPort = new char[50];
	char *szBaud = new char[50];

	// now it critical!
	EnterCriticalSection(&m_csCommunicationSync);

	// if the port is already opened: close it
	if (m_hComm != NULL)
	{
		CloseHandle(m_hComm);
		m_hComm = NULL;
	}

	// prepare port strings
	sprintf(szPort, "COM%d", portnr);
	// stop is index 0 = 1 1=1.5 2=2
	int mystop;
	int myparity;
	switch(stopbits)
	{
		case 0:
			mystop = ONESTOPBIT;
			break;
		case 1:
			mystop = ONE5STOPBITS;
			break;
		case 2:
			mystop = TWOSTOPBITS;
			break;
	}
	myparity = 0;
	switch(parity)
	{
		case 'N':
			myparity = 0;
			break;
		case 'E':
			myparity = 1;
			break;
		case 'O':
			myparity = 2;
			break;
		case 'M':
			myparity = 3;
			break;
		case 'S':
			myparity = 4;
			break;
	}
	sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, mystop);

	// get a handle to the port
	m_hComm = CreateFile(szPort,						// communication port string (COMX)
					     GENERIC_READ | GENERIC_WRITE,	// read/write types
					     0,								// comm devices must be opened with exclusive access
					     NULL,							// no security attributes
					     OPEN_EXISTING,					// comm devices must use OPEN_EXISTING
					     FILE_FLAG_OVERLAPPED,			// Async I/O
					     0);							// template must be 0 for comm devices

	if (m_hComm == INVALID_HANDLE_VALUE)
	{
		// port not found
		delete [] szPort;
		delete [] szBaud;

		return FALSE;
	}

	// set the timeout values
	m_CommTimeouts.ReadIntervalTimeout         = ReadIntervalTimeout * 1000;
	m_CommTimeouts.ReadTotalTimeoutMultiplier  = ReadTotalTimeoutMultiplier * 1000;
	m_CommTimeouts.ReadTotalTimeoutConstant    = ReadTotalTimeoutConstant * 1000;
	m_CommTimeouts.WriteTotalTimeoutMultiplier = WriteTotalTimeoutMultiplier * 1000;
	m_CommTimeouts.WriteTotalTimeoutConstant   = WriteTotalTimeoutConstant * 1000;

	// configure
	if (SetCommTimeouts(m_hComm, &m_CommTimeouts))
	{						   
		if (SetCommMask(m_hComm, dwCommEvents))
		{
			if (GetCommState(m_hComm, &m_dcb))
			{
				m_dcb.EvtChar = 'q';
				m_dcb.fRtsControl = RTS_CONTROL_ENABLE;		// set RTS bit high!
				m_dcb.BaudRate = baud;  // add by mrlong
				m_dcb.Parity   = myparity;
				m_dcb.ByteSize = databits;
				m_dcb.StopBits = mystop;
						
				//if (BuildCommDCB(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;

	// flush the port
	PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);

	// release critical section
	LeaveCriticalSection(&m_csCommunicationSync);

	TRACE("Initialisation for communicationport %d completed.\nUse Startmonitor to communicate.\n", portnr);

	return TRUE;
}

//
//  The CommThread Function.
//
UINT CSerialPort::CommThread(LPVOID pParam)
{
	// Cast the void pointer passed to the thread back to
	// a pointer of CSerialPort class
	CSerialPort *port = (CSerialPort*)pParam;
	
	// Set the status variable in the dialog class to
	// TRUE to indicate the thread is running.
	port->m_bThreadAlive = TRUE;	
		
	// Misc. variables
	DWORD BytesTransfered = 0; 
	DWORD Event = 0;
	DWORD CommEvent = 0;
	DWORD dwError = 0;
	COMSTAT comstat;
	BOOL  bResult = TRUE;
		
	// Clear comm buffers at startup
	if (port->m_hComm)		// check if the port is opened
		PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);

	// begin forever loop.  This loop will run as long as the thread is alive.
	for (;;) 
	{ 

		// Make a call to WaitCommEvent().  This call will return immediatly
		// because our port was created as an async port (FILE_FLAG_OVERLAPPED
		// and an m_OverlappedStructerlapped structure specified).  This call will cause the 
		// m_OverlappedStructerlapped element m_OverlappedStruct.hEvent, which is part of the m_hEventArray to 
		// be placed in a non-signeled state if there are no bytes available to be read,
		// or to a signeled state if there are bytes available.  If this event handle 
		// is set to the non-signeled state, it will be set to signeled when a 
		// character arrives at the port.

		// we do this for each port!

		bResult = WaitCommEvent(port->m_hComm, &Event, &port->m_ov);

		if (!bResult)  
		{ 
			// If WaitCommEvent() returns FALSE, process the last error to determin
			// the reason..
			switch (dwError = GetLastError()) 
			{ 
			case ERROR_IO_PENDING: 	
				{ 
					// This is a normal return value if there are no bytes
					// to read at the port.
					// Do nothing and continue
					break;
				}
			case 87:
				{
					// Under Windows NT, this value is returned for some reason.
					// I have not investigated why, but it is also a valid reply
					// Also do nothing and continue.
					break;
				}
			default:
				{
					// All other error codes indicate a serious error has
					// occured.  Process this error.
					port->ProcessErrorMessage("WaitCommEvent()");
					break;
				}
			}
		}
		else
		{
			// If WaitCommEvent() returns TRUE, check to be sure there are
			// actually bytes in the buffer to read.  
			//
			// If you are reading more than one byte at a time from the buffer 
			// (which this program does not do) you will have the situation occur 
			// where the first byte to arrive will cause the WaitForMultipleObjects() 
			// function to stop waiting.  The WaitForMultipleObjects() function 
			// resets the event handle in m_OverlappedStruct.hEvent to the non-signelead state
			// as it returns.  
			//
			// If in the time between the reset of this event and the call to 
			// ReadFile() more bytes arrive, the m_OverlappedStruct.hEvent handle will be set again
			// to the signeled state. When the call to ReadFile() occurs, it will 
			// read all of the bytes from the buffer, and the program will
			// loop back around to WaitCommEvent().
			// 
			// At this point you will be in the situation where m_OverlappedStruct.hEvent is set,
			// but there are no bytes available to read.  If you proceed and call
			// ReadFile(), it will return immediatly due to the async port setup, but
			// GetOverlappedResults() will not return until the next character arrives.
			//
			// It is not desirable for the GetOverlappedResults() function to be in 
			// this state.  The thread shutdown event (event 0) and the WriteFile()
			// event (Event2) will not work if the thread is blocked by GetOverlappedResults().
			//
			// The solution to this is to check the buffer with a call to ClearCommError().
			// This call will reset the event handle, and if there are no bytes to read
			// we can loop back through WaitCommEvent() again, then proceed.
			// If there are really bytes to read, do nothing and proceed.
		
			bResult = ClearCommError(port->m_hComm, &dwError, &comstat);

			if (comstat.cbInQue == 0)
				continue;
		}	// end if bResult

		// Main wait function.  This function will normally block the thread
		// until one of nine events occur that require action.
		Event = WaitForMultipleObjects(3, port->m_hEventArray, FALSE, INFINITE);

		switch (Event)
		{
		case 0:
			{
				// Shutdown event.  This is event zero so it will be
				// the higest priority and be serviced first.

			 	port->m_bThreadAlive = FALSE;
				
				// Kill this thread.  break is not needed, but makes me feel better.
				AfxEndThread(100);
				break;
			}
		case 1:	// read event
			{
				GetCommMask(port->m_hComm, &CommEvent);
				if (CommEvent & EV_RXCHAR) //接收到字符,并置于输入缓冲区中 
					ReceiveChar(port, comstat);
				
				if (CommEvent & EV_CTS) //CTS信号状态发生变化
					::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_CTS_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
				if (CommEvent & EV_RXFLAG) //接收到事件字符,并置于输入缓冲区中 
					::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RXFLAG_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
				if (CommEvent & EV_BREAK)  //输入中发生中断
					::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_BREAK_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
				if (CommEvent & EV_ERR) //发生线路状态错误,线路状态错误包括CE_FRAME,CE_OVERRUN和CE_RXPARITY 
					::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_ERR_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
				if (CommEvent & EV_RING) //检测到振铃指示
					::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RING_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
					
				break;
			}  
		case 2: // write event
			{
				// Write character event from port
				WriteChar(port);
				break;
			}

		} // end switch

	} // close forever loop

	return 0;
}

//
// start comm watching
//
BOOL CSerialPort::StartMonitoring()
{
	if (!(m_Thread = AfxBeginThread(CommThread, this)))
		return FALSE;
	TRACE("Thread started\n");
	return TRUE;	
}

//
// Restart the comm thread
//
BOOL CSerialPort::RestartMonitoring()
{
	TRACE("Thread resumed\n");
	m_Thread->ResumeThread();
	return TRUE;	
}


//
// Suspend the comm thread
//
BOOL CSerialPort::StopMonitoring()
{
	TRACE("Thread suspended\n");
	m_Thread->SuspendThread(); 
	return TRUE;	
}


//
// If there is a error, give the right message
//
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); 
	MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);

	LocalFree(lpMsgBuf);
	delete[] Temp;
}

//
// Write a character.
//
void CSerialPort::WriteChar(CSerialPort* port)
{
	BOOL bWrite = TRUE;
	BOOL bResult = TRUE;

	DWORD BytesSent = 0;
	DWORD SendLen   = port->m_nWriteSize;
	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,							// Handle to COMM Port
							port->m_szWriteBuffer,					// Pointer to message buffer in calling finction
							SendLen,    // add by mrlong
							//strlen((char*)port->m_szWriteBuffer),	// Length of message to send
							&BytesSent,								// Where to store the number of bytes sent
							&port->m_ov);							// Overlapped structure

		// 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,		// Stores number of bytes sent
									  TRUE); 			// Wait flag

		LeaveCriticalSection(&port->m_csCommunicationSync);

		// deal with the error code 
		if (!bResult)  
		{
			port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()");
		}	
	} // end if (!bWrite)

	// Verify that the data size send equals what we tried to send
	if (BytesSent != SendLen /*strlen((char*)port->m_szWriteBuffer)*/)  // add by 
	{
		TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)port->m_szWriteBuffer));
	}
}

//
// Character received. Inform the owner
//
void CSerialPort::ReceiveChar(CSerialPort* port, COMSTAT comstat)
{
	BOOL  bRead = TRUE; 
	BOOL  bResult = TRUE;
	DWORD dwError = 0;
	DWORD BytesRead = 0;
	unsigned char RXBuff;

	for (;;) 
	{ 
             //add by liquanhai 2011-11-06  防止死锁
             if(WaitForSingleObject(port->m_hShutdownEvent,0)==WAIT_OBJECT_0)
                 return;

                // Gain ownership of the comm port critical section.
		// This process guarantees no other part of this program 
		// is using the port object. 
		
		EnterCriticalSection(&port->m_csCommunicationSync);

		// ClearCommError() will update the COMSTAT structure and
		// clear any other errors.
		
		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 out when all bytes have been read
			break;
		}
						
		EnterCriticalSection(&port->m_csCommunicationSync);

		if (bRead)
		{
			bResult = ReadFile(port->m_hComm,		// Handle to COMM port 
							   &RXBuff,				// RX Buffer Pointer
							   1,					// Read one byte
							   &BytesRead,			// Stores number of bytes read
							   &port->m_ov);		// pointer to the m_ov structure
			// deal with the error code 
			if (!bResult)  
			{ 
				switch (dwError = GetLastError()) 
				{ 
					case ERROR_IO_PENDING: 	
						{ 
							// asynchronous i/o is still in progress 
							// Proceed on to GetOverlappedResults();
							bRead = FALSE;
							break;
						}
					default:
						{
							// Another error has occured.  Process this error.
							port->ProcessErrorMessage("ReadFile()");
							break;
						} 
				}
			}
			else
			{
				// ReadFile() returned complete. It is not necessary to call GetOverlappedResults()
				bRead = TRUE;
			}
		}  // close if (bRead)

		if (!bRead)
		{
			bRead = TRUE;
			bResult = GetOverlappedResult(port->m_hComm,	// Handle to COMM port 
										  &port->m_ov,		// Overlapped structure
										  &BytesRead,		// Stores number of bytes read
										  TRUE); 			// Wait flag

			// deal with the error code 
			if (!bResult)  
			{
				port->ProcessErrorMessage("GetOverlappedResults() in ReadFile()");
			}	
		}  // close if (!bRead)
				
		LeaveCriticalSection(&port->m_csCommunicationSync);

		// notify parent that a byte was received
		::SendMessage((port->m_pOwner)->m_hWnd, WM_COMM_RXCHAR, (WPARAM) RXBuff, (LPARAM) port->m_nPortNr);
	} // end forever loop

}

//
// Write a string to the port
//
void CSerialPort::WriteToPort(char* string)
{		
	assert(m_hComm != 0);

	memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
	strcpy(m_szWriteBuffer, string);
	m_nWriteSize=strlen(string); // add by mrlong
	// set event for write
	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;
}

void CSerialPort::ClosePort()
{
        MSG message;
	do
	{
	      SetEvent(m_hShutdownEvent);
              if(::PeekMessage(&message,m_pOwner->m_hWnd,0,0,PM_REMOVE))
               {
               ::TranslateMessage(&message);
                ::DispatchMessage(&message);
              }
               
         } while (m_bThreadAlive);

	// if the port is still opened: close it 
	if (m_hComm != NULL)
	{
		CloseHandle(m_hComm);
		m_hComm = NULL;
	}
	
	// Close Handles  
	if(m_hShutdownEvent!=NULL)
		ResetEvent(m_hShutdownEvent);
	if(m_ov.hEvent!=NULL)
		ResetEvent(m_ov.hEvent);
	if(m_hWriteEvent!=NULL)
		ResetEvent(m_hWriteEvent);			
		
	//delete [] m_szWriteBuffer;
	
}

void CSerialPort::WriteToPort(char* string,int n)
{
	assert(m_hComm != 0);
	memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
	memcpy(m_szWriteBuffer, string, n);
	m_nWriteSize = n;

	// set event for write
	SetEvent(m_hWriteEvent);
}

void CSerialPort::WriteToPort(LPCTSTR string)
{
	assert(m_hComm != 0);
	memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
	strcpy(m_szWriteBuffer, string);
	m_nWriteSize=strlen(string);
	// set event for write
	SetEvent(m_hWriteEvent);
}

void CSerialPort::WriteToPort(BYTE* Buffer, int n)
{
	assert(m_hComm != 0);
	memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
	int i;
	for(i=0; i<n; i++)
	{
		m_szWriteBuffer[i] = Buffer[i];
	}
	m_nWriteSize=n;

	// set event for write
	SetEvent(m_hWriteEvent);
}


void CSerialPort::SendData(LPCTSTR lpszData, const int nLength)
{
	assert(m_hComm != 0);
	memset(m_szWriteBuffer, 0, nLength);
	strcpy(m_szWriteBuffer, lpszData);
	m_nWriteSize=nLength;
	// set event for write
	SetEvent(m_hWriteEvent);
}

BOOL CSerialPort::RecvData(LPTSTR lpszData, const int nSize)
{
	//
	//接收数据
	//
	assert(m_hComm!=0);
	memset(lpszData,0,nSize);
	DWORD mylen  = 0;
	DWORD mylen2 = 0;
	while (mylen<nSize) {
		if(!ReadFile(m_hComm,lpszData,nSize,&mylen2,NULL)) 
			return FALSE;
		mylen += mylen2;

		
	}
	
	return TRUE;
}
























VC串口修正类应用的小项目下载地址:http://download.csdn.net/detail/liquanhai/3763088


补充一下几篇有用的参考文献:

如何添加CSerialPort类以及相应的消息函数

使用CSerialPort类编写串口通信程序的问题

VC serialPort类加上关闭功能————我的解决方法

CSerialPort类解析(一)





本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CSerialPort串口类最新修正版(解决关闭死锁问题)2014-01-11 的相关文章

  • 百度2014校园招聘笔试题(武汉站 9.28)

    一 简答题 xff08 本题共30分 xff09 动态链接库与静态链接库分别有什么优缺点 xff1f xff08 10分 xff09 轮训任务调度和抢占式任务调度有什么区别 xff1f xff08 10分 xff09 请列出数据库中常用的锁
  • 腾讯2014软件开发笔试题目

    腾讯2014软件开发笔试题目 9月21日 xff0c 腾讯2014软件开发校招 简答题 广州 简答题 xff1a 1 请设计一个排队系统 xff0c 能够让每个进入队伍的用户都能看到自己在 中所处的位置和变化 队伍可能随时有人加入和退出 x
  • 2014欢聚时代(YY)软件研发笔试题

    本文转载自 xff1a http blog csdn net arcsinsin article details 12714027
  • 回首2013,展望2014

    此刻值此2013年末 xff0c 明天便是元旦 近日浏览CSDN论坛时 xff0c 发现有许多的坛友都在写2013年度总结 xff0c 博客作为个人的名片 xff0c 也决定开始尝试写博客 xff0c 我的第一篇博客就是关于2013年度总结
  • 阿里巴巴2014校招笔试题-2013年9月14日

    不得不吐槽 xff0c 阿里真是太混乱了 xff0c 北京的笔试在考场等了两个半小时 xff0c 考卷都没运到考场 xff0c 64 阿里巴巴集团校园招聘 回应说 xff1a 北京的同学们 xff0c 简单解释下 xff0c 为了试卷的保密
  • Luogu 3647 [APIO 2014] 连珠线

    传送门思路参考代码 传送门 思路 唉 xff0c 我太弱了 xff0c 又看错题了 题目中说一个新的珠子和一个已经添加的珠子连接起来 xff0c 我没有看到 xff0c 然后就凉了 立个 flag xff1a 已经连续看错五题了 xff0c
  • 2014-09-2 ccf画图 c++

    span class token comment 2014 09 2 span span class token comment 画图 span span class token macro property span class toke
  • 回望2014

    时光荏苒 xff0c 流光飞逝 xff0c 一转眼的时间又是一年 回望一下2014年 xff0c 这一年应该是成长的一年 xff0c 是温暖的一年 xff0c 也是丰收的一年 在这过去的一年里 xff0c 大概可以从工作和生活两方面说说吧
  • 再见2014,你好2015

    过去就是过去了 2014年再见 xff0c 2015年你好 xff01 回首 总结也只是慰藉 1999年12月至今 xff0c 经历了整整十五个曾经 xff0c 这其中的波折 xff0c 怎是我这样的小辈能够理解的 借这个平台也只是为了感谢
  • 回首2013,展望2014

    此刻值此2013年末 xff0c 明天便是元旦 近日浏览CSDN论坛时 xff0c 发现有许多的坛友都在写2013年度总结 xff0c 博客作为个人的名片 xff0c 也决定开始尝试写博客 xff0c 我的第一篇博客就是关于2013年度总结
  • 我的2014作的一手好死,2015求轻虐

    真的好想上来开头就写 新的一年 xff0c 全新的自己 xff0c 但是这样自欺欺人的话我还是别说了 xff0c 省得一大批损友又来吐嘈我 2015年希望找到自己的另一半这样的话我也不想再提了 xff0c 因为这样写了两年 依旧单身 xff
  • 2014英伟达校园招聘-上海

    时间 xff1a 2013 10 19 地点 xff1a 上海交通大学中院楼 申请职位 xff1a 嵌入式系统工程师 1 指针数组和数组指针 函数指针 指针函数 2 存储对齐 3 Getmemory问题 4 6进制转换成10进制 5 时钟方
  • 致我们终将逝去的2014

    一眨眼 xff0c 2014年的最后一张日历即将撕去 xff0c 迎来的是面貌全新的2015 回首2014 xff0c 回首这一年所经历的一切 xff0c 感觉那么近又那么远 下面将从几个方便总结自己的2014 xff1a 一 专业方面 x
  • 腾讯2014校园招聘软件后台开发类笔试题

    转http www itmian4 com forum php mod 61 viewthread amp tid 61 3572
  • 学神的“诞生”-2014清华大学本科生特等奖学金答辩观后感

    清华的特奖与交大的竢实扬华 偶然间在学堂在线上留意到有这样的一场现场答辩 xff0c 很想知道最高学府的最高荣誉花落谁家 xff0c 得此殊荣的又是些怎样的 学神 xff0c 几点感受记录之 1 经历 gt gt 证书 清华的学生更注重大学
  • 阿里巴巴2014校招笔试题-2013年9月14日

    不得不吐槽 xff0c 阿里真是太混乱了 xff0c 北京的笔试在考场等了两个半小时 xff0c 考卷都没运到考场 xff0c 64 阿里巴巴集团校园招聘 回应说 xff1a 北京的同学们 xff0c 简单解释下 xff0c 为了试卷的保密
  • 2014校园招聘总结

    本篇博文已迁移至吹水小镇reetsee com xff0c 迁移后地址为 xff1a http blog reetsee com archives 215 注 xff1a 貌似不少童鞋看到这篇东西觉得我是牛人 其实不是stO xff0c 以
  • SQL Server 2014无法连接到服务器之解决方法

    问题如图所示 xff1a 解决方法 1 打开SQL server 配置管理器 gt SQL server 网络配置 gt MSSQLSERVER的协 xff0c 将SQLEXPRESS协议中的Named Pipes改为已启用 xff1a 2
  • CSerialPort教程4.3.x (7) - CSerialPort在vcpkg中的使用

    CSerialPort教程4 3 x 7 CSerialPort在vcpkg中的使用 前言 CSerialPort项目是一个基于C C 的轻量级开源跨平台串口类库 可以轻松实现跨平台多操作系统的串口读写 同时还支持C Java Python
  • CSerialPort教程4.3.x (5) - CSerialPort在cmake中的使用

    CSerialPort教程4 3 x 5 CSerialPort在cmake中的使用 环境 系统 windows 10 64位 QT 5 12 9 5 9及以上版本支持cmake构建 MFC vs2008 前言 CSerialPort项目是

随机推荐

  • 个性化定制你的命令行

    如果您很容易使shell 提示行变得色彩绚烂斓且带有更多信息 xff0c 为什么还要坚持用单调的标准 shell 提示行呢 xff1f 在这篇技巧中 xff0c Daniel Robbins 将说明如何获得符合您的意愿的shell提示行 x
  • Android中viewBinding的简单用法

    初级菜鸟 xff0c 正在向中级菜鸟努力 xff01 刚刚接触Android开发 xff0c 有好多东西都不太懂 xff0c 又喜欢忘东西 xff0c 干脆写博客记录一下吧 目录 在activity中使用viewBinding 在Fragm
  • python爬虫实战 | 批量爬取开放服务器的文件

    今天在查有关spss modeler的参考资料时 xff0c 发现了这个网站 xff1a ftp public dhe ibm com software analytics spss documentation modeler 14 2 z
  • 一个图的连通子图个数

    问题描述 xff1a 给出一个无向图 xff0c 输出图中连通分支的个数 无向图的连通分支是一个子图 xff0c 因此在子图两个节点之间至少存在一个路径 输入 xff1a 给出一个连通图的二维数组 01000 10100 01000 000
  • IT牛人博客聚合 - Linode日本东京机房速度飞快 编程牛人 技术牛人

    为了应对亚太地域快速增加的需求 Linode起头把机房建在亚洲了 第一个 Linode 亚洲机房选择在日本东京 我测了下 速度比本来在美国加州快多了 应当首要得益于收集延时的削减 所以 我当即开了张 Support Ticket 将我的 V
  • kali tightvncserver 自启动

    kali创建service自启动 xff0c 文件如下 xff0c kali2021版真的改了好多 xff0c 在这里记录一下 Unit Description 61 TightVNC remote desktop server After
  • 重载new/delete运算符

    下面介绍用重载new delete运算符的方式来实现一个简单的内存泄露检测工具 xff0c 基本思想是重载全局new delete运算符 xff0c 被检测代码调用new和delete运算符时就会调用重载过的operator new和ope
  • 按位与、按位异或、按位取反

    amp 按位与 按位或 按位异或 1 按位与运算 按位与运算符 34 amp 34 是双目运算符 其功能是参与运算的两数各对应的二进位相与 只有对应的两个二进位均为1时 xff0c 结果位才为1 xff0c 否则为0 参与运算的数以补码方式
  • VS断点设置无效的问题

    新的一年第一篇博客点的名字是已经被写烂了的题目 xff0c 并且也是浪费了网友无数的宝贵时间也很难解决的老大难问题 VS无法设定断点问题 先得吐槽一下CSDN的编辑器 xff0c 火狐下竟然无法显示工具条问题 xff0c 可能是因为xhEd
  • 解决Ubuntu安装依赖问题

    解决Ubuntu安装依赖问题 解决Ubuntu安装依赖问题最主要问题 xff0c 修改的国内镜像源可能不是对应的ubuntu版本 xff0c 大部人直接找了个镜像源就复制到source list里面了 xff0c 其实需要对应版本的 xff
  • &与&&有什么区别?

    一 简要说明 按位与 xff1a a amp b 是把 a 和 b 都转换成二进制数然后再进行与的运算 xff1b 逻辑与 xff1a a amp amp b 就是当且仅当两个操作数均为 true 时 xff0c 其结果才为 true xf
  • VC在编译链接的无故死掉解决方案(防VC6卡死)

    现在网上有很多集成了SP6的VC6 xff0c 但是使用起来会有些某名奇妙的问题 xff0c 也许是我用的龙卷风那个版本不行 xff0c 最常见的就是VC在编译链接的时候经常无故死掉的问题了 xff0c 发生时候关也关不掉 xff0c 停也
  • 给纯SDK程序加上自己的ICO图标

    方法一 xff1a 给纯SDK程序加上自己的ICO图标 1 在项目中建一个resource h文件写入一句 define IDR MAINFRAME 128 2 在项目中建一个resource rc写入一句IDI ICO ICON DISC
  • Teechart 的用法详解:在VC6.0 跟Visual Studio 2005及之后版本的区别

    csdn的文件限制导致 xff0c gif图片不清晰 xff0c 我把文章放到简书上了 xff0c 地址 xff1a http www jianshu com p 2f3f6047d99a 什么时候开始接触teechart呢 xff0c 说
  • 为什么现在多数软件都默认选择安装目录为user下的AppData而非Progamfiles?

    为什么放弃默认选择Program Files 我一直百思不得其解 都是UAC xff08 用户权限控制 xff09 惹得祸 自从VISTA引入了权限机制UAC后 xff0c windows7及以后的系统版本 xff0c 对于Program
  • 对VC++工程编译过程的梳理

    对VC 43 43 工程编译过程的梳理 VC 43 43 的项目和解决方案文件解读 xff0c 无非就是利用这些信息进行一个软件的编译 xff0c 这些文件里面是存放的项目的配置和工程的组织 xff0c 类似于makefile文件 但是只有
  • Teechart在VC++中使用的碎碎念

    今天再看官网推荐的Teechart的使用方式 xff0c 感觉他们还是推荐使用VC 43 43 6 0的导出头文件格式 xff0c 来引入所有的类 xff0c 并操作teechart控件 All the files necessary ca
  • 汇编语言里 eax, ebx, ecx, edx, esi, edi, ebp, esp这些都是什么意思啊?

    eax ebx ecx edx esi edi ebp esp等都是X86 汇编语言中CPU上的通用寄存器的名称 xff0c 是32位的寄存器 如果用C语言来解释 xff0c 可以把这些寄存器当作变量看待 比方说 xff1a add eax
  • 计算机CPU的工作原理动画

    一直在找有关CPU相关的工作原理动画 xff0c 终于找到了 喜欢这个的可以认真看看了 CPU工作原理系列动画下载
  • CSerialPort串口类最新修正版(解决关闭死锁问题)2014-01-11

    这是一份优秀的类文件 xff0c 好多的地方值得我们学习 xff0c 具体在多线程 xff0c 事件 xff0c 自定义消息 xff0c 类的封装方面等等 Remon提供的串口类网址为 xff1a http codeguru earthwe