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 的相关文章

  • 9月10日美团网2014校招研发笔试哈尔滨站

    1 链表翻转 给出一个链表和一个数k xff0c 比如链表1 2 3 4 5 6 xff0c k 61 2 xff0c 则翻转后2 1 4 3 6 5 xff0c 若k 61 3 翻转后3 2 1 6 5 4 xff0c 若k 61 4 x
  • 腾讯2014校园招聘软件后台开发类笔试题

    转http www itmian4 com forum php mod 61 viewthread amp tid 61 3572
  • 百度2014校招笔试题(一)

    算法和程序设计题 xff1a 1 题意 xff1a 一幢大楼的底层有1001根电线 xff0c 这些电线一直延伸到大楼楼顶 xff0c 你需要确定底层的1001个线头和楼顶的1001次线头的对应关系 你有一个电池 xff0c 一个灯泡 xf
  • 2014找工作总结-机会往往留给有准备的人

    好基友的文章必须转 xff0c 大神一枚 xff1a 出处 xff1a http blog csdn net xiajun07061225 article details 12844801 其实我的求职过程在十一之前就已经结束了 xff0c
  • 2014.软院.Problem B. 最长连续等差子数列

    题目描述 给定一个长度为N的整数数列 xff0c 你需要在其中找到最长的连续子数列的长度 xff0c 并满足这个子序列是等差的 注意公差小于或等于0的情况也是允许的 输入格式 第一行为数据组数T xff08 1 lt 61 T lt 61
  • Luogu 2114 [NOI 2014] 起床困难综合症

    传送门思路参考代码 传送门 思路 按位贪心 但是我太弱了 xff0c 明明可以 O n O n 预处理 xff0c 我却只会 O 32 n O
  • Luogu 2305 [NOI 2014] 购票

    传送门思路别人家的题解弱化的传送门 xff08 Luogu 3994 高速公路 xff09 参考代码 对于没有距离限制的 50 分 参考代码 对于 100 分的数据参考代码Remarks 传送门 思路 唉 xff0c 我太弱了 xff0c
  • 回望2014

    时光荏苒 xff0c 流光飞逝 xff0c 一转眼的时间又是一年 回望一下2014年 xff0c 这一年应该是成长的一年 xff0c 是温暖的一年 xff0c 也是丰收的一年 在这过去的一年里 xff0c 大概可以从工作和生活两方面说说吧
  • 总结2014——迷茫以及迷茫过后的坚持

    首先 xff0c 借用一句话和大家共勉 xff1a 少一些功利主义的追求 xff0c 多一些不为什么的坚持 xff01 xff01 不知不觉15年也快过了1个月了 xff0c 还是想着要为14年做一下总结 xff1a 记录一下自己的历程 今
  • 【无人机】【2014.08】无人机循环路由

    本文为以色列理工学院 xff08 作者 xff1a Nir Drucker xff09 的硕士论文 xff0c 共65页 许多无人驾驶飞行器 xff08 UAV xff09 针对的国防和民用相关任务涉及在各种时间限制下监测预先确定的一组地面
  • 回首2013,展望2014

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

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

    2014 xff0c 不 xff0c 应该是先说说现在的2015吧 xff0c 2015年1月18号 xff0c 我刚刚注册了CSDN的博客账号 xff0c 相对来说 xff0c 我是个新手 xff0c 其实以前都没有写博客的习惯 xff0
  • 美团2014校招笔试题第二题答案分析

    今天在论坛里看到一网友贴出的美团2014校招笔试题 xff0c 其中第二题个人觉得答案应该为7次 xff0c 这里做了一个分析 xff0c 欢迎大家指出其中的纰漏 题目 xff1a 有25匹马 xff0c 每次比赛只能有5匹马参加 xff0
  • 我的2014

    时间匆匆如流水 xff0c 生活总是不停的翻写新的篇章 我的2014同样缺少不了 毕业两年了 xff0c 工作也比较轻松 xff0c 无趣 同事们的话 xff1a 坐等OVER 在清闲的工作中 xff0c 失去了往日的 冲动 感觉自己也一点
  • 2014年24段魔尺变三叶花视频教程

    2014年24段魔尺变三叶花视频教程 xff08 升级版 xff09 偶是真心喜欢24段魔尺制作的三叶花 xff0c 那是相当漂亮 xff0c 体现了几何美 xff0c 对称美 xff0c 空间美 xff0c 色彩美 xff0c 见下图 三
  • 腾讯2014校园招聘软件后台开发类笔试题

    转http www itmian4 com forum php mod 61 viewthread amp tid 61 3572
  • 回首2013,展望2014

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

    文章目录 0 结果1 题目2 思路附录 0 结果 1 题目 2 思路 二叉树的带权路径长度 xff08 WPL xff09 的计算方法有两种 xff1a 1 xff0c 定义 xff1a W P L 61
  • 爱线段树的好孩子[POI2014]KAR-Cards

    There are nn cards arranged on a table in a certain order Two integers are written on each card one per side the obverse

随机推荐

  • 欧拉角奇异性产生的原因

    1 欧拉角奇异性的原因 1 1 奇异性的定义 奇异性 xff0c 英文Singularity wiki中的解释为 In mathematics a singularity is in general a point at which a g
  • 数据结构----依据出栈顺序判断所需的最少栈空间

    1 问题描述 问题 若元素 a b c d e f g 顺序进栈 xff0c 且出栈顺序是 b d c f e a g 则栈的容量至少是 答案 xff1a 3 2 解法描述与分析 2 1 解法描述 记 1 2 3 4 5 6 分别对应 a
  • error: ‘usleep’ was not declared in this scope

    报错 error usleep was not declared in this scope 解决办法 在出错程序的头文件中加入即可 span class token macro property span class token dire
  • Ubuntu 安装 cuda 时卡在登录界面(login loop)的解决方案之一

    当安装 cuda 时 xff0c 需要我们需要安装NVIDIA driver driver 用来支撑cuda 库的调用 xff0c 在满足官方文档 xff08 见 Table1 xff09 对于cuda 版本对于driver版本的要求情况下
  • QT开发--串口助手的编写

    一 创建工程 正常创建一个widget项目工程 xff0c 控件的方式进行代码研究 创建好编译测试一下工程 可以编译进行下一步操作 二 串口UI界面设计 1 选择ui控件 串口接收下位机数据显示界面控件 选择容器 波特率 串口号 数据位等多
  • 又是一年,我的2013年终总结

    昨天是冬至 xff08 2013年的12月22日 xff09 xff0c 日历摆了乌龙 xff0c 不少人提前把节给过了 xff0c 感觉稀里糊涂的 xff0c 也正如自己这一年的心情一样 xff0c 再过一个星期2013年也就算落下帷幕了
  • 按位与、按位异或、按位取反

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

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

    一 简要说明 按位与 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
  • PIXHAWK飞控的外部控制

    PIXHAWK飞控可以运行PX4原生固件和APM固件 xff0c 我这里用的是PX4原生固件 xff0c 因为这款固件是专门为PIXHAWK量身打造的 xff0c 两者合起来性能更强 不过据说APM固件因为其比较完善 xff0c 更加稳定
  • 只知道用一样东西,不明白他的道理,实在不高明

    无论在哪个领域 xff0c 要抓住问题的本质 xff0c 切勿停留在表面 xff0c 要不断地深入下去 就这个小的领域来说 xff0c 你花个3 5年的时间挤进前20 是非常可能的 精通某一方面的技能 xff0c 才能使自己不容易被别人所替
  • 对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