⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 comdlg.cpp

📁 运用通信API编写串口通信。 功能:1)通过串口进行数据的收发并在接收端显示收到的数据 2)打开串口
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// comDlg.cpp : implementation file
//

#include "stdafx.h"
#include "com.h"
#include "comDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

HANDLE		m_hCom;								
HANDLE		hThreadEvent;						
DWORD WINAPI		CommProc(LPVOID pParam);     
BOOL		fEventRun;							
HWND		hWnd;							
DWORD		dwThreadID;						
OVERLAPPED  Eol={0};							
OVERLAPPED  Wol={0};							
OVERLAPPED  Rol={0};						
BOOL		fStopMsg;												
std::deque<BYTE>     m_data;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About


class CAboutDlg : public CDialog
{
public:
	CAboutDlg();
	
	// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA
	
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL
	
	// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP

END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CComDlg dialog

CComDlg::CComDlg(CWnd* pParent /*=NULL*/)
: CDialog(CComDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CComDlg)
	m_strSend = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	
	
}

void CComDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CComDlg)
	DDX_Control(pDX, IDC_BUTTON_CONFIG, m_btnConfig);
	DDX_Control(pDX, IDC_REALSEND, m_RealSend);
	DDX_Control(pDX, IDC_EDIT_SEND, m_editSend);
	DDX_Control(pDX, IDCANCEL, m_btnCancel);
	DDX_Control(pDX, IDC_EDIT_RECEIVE, m_editReceive);
	DDX_Control(pDX, IDC_BUTTON_SEND, m_btnSend);
	DDX_Control(pDX, IDC_BUTTON_CLOSEPORT, m_btnClosePort);
	DDX_Control(pDX, IDC_BUTTON_OPENPORT, m_btnOpenPort);
	DDX_Text(pDX, IDC_EDIT_SEND, m_strSend);
	DDX_Text(pDX, IDC_EDIT_RECEIVE, m_strReceive);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CComDlg, CDialog)
//{{AFX_MSG_MAP(CComDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_OPENPORT, OnButtonOpenport)
ON_BN_CLICKED(IDC_BUTTON_CLOSEPORT, OnButtonCloseport)
ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)
ON_BN_CLICKED(IDC_BUTTON_CONFIG, OnButtonConfig)
ON_BN_CLICKED(IDC_BUTTON_C, OnButtonC)
	ON_WM_CTLCOLOR()
	//}}AFX_MSG_MAP
ON_MESSAGE(WM_COMMNOTIFY, OnCommNotify)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CComDlg message handlers

BOOL CComDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	
	// Add "About..." menu item to system menu.
	
	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
	
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
	
	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_btnClosePort.EnableWindow(FALSE);      //make [close port] button invalid 
	m_btnSend.EnableWindow(FALSE);           //make [send] button invalid
	//	m_editReceive.SetReadOnly(TRUE);         //set received edit read_only
	m_btnOpenPort.EnableWindow(FALSE);	     //make [open port] button invalid
	m_strSend.GetLength();
	
    
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CComDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CComDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting
		
		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
		
		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;
		
		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CComDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

BOOL CComDlg::OnButtonOpenport() 
{
	// TODO: Add your control notification handler code here
	
	
	m_hCom=CreateFile(myCom, 
		GENERIC_READ | GENERIC_WRITE,     // read and write
		0,                                
		NULL,                              
		OPEN_EXISTING,                    
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,   //We planned uses the asynchronous communication 
		NULL); 
	if(m_hCom!=INVALID_HANDLE_VALUE)       //check  open the com_port whether success
	{   
							 
		DCB dcb;
		GetCommState( m_hCom, &dcb );					 
		dcb.BaudRate=myBaudRate;		
		dcb.fParity=myfParity;
		dcb.ByteSize=myByteSize;
		dcb.Parity=myParity;
		dcb.StopBits=myStopBits;							 		
        dcb.fBinary=TRUE;
		btnOpened=TRUE;
		if(!SetCommState(m_hCom,&dcb))
			return FALSE;
		if(!SetupComm(m_hCom,1024,1024))
			return FALSE;           // set the size of I/O buffer
//		if(!PurgeComm (m_hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR| PURGE_RXCLEAR))
//			return FALSE;  //clear I/O buffer  
		
		COMMTIMEOUTS TimeOuts;         //define timeout丆and fill in the structure 
		
		//set time_interval the maxest,set total_time_interval 0 will lead ReadFile returns to and completes the operation immediately
		TimeOuts.ReadIntervalTimeout=MAXDWORD; 	
		TimeOuts.ReadTotalTimeoutMultiplier=0; 	
		TimeOuts.ReadTotalTimeoutConstant=0; 
		
		//set write_time timeout to formulation the WriteComm of GetOverlappedResult's wait time
		TimeOuts.WriteTotalTimeoutMultiplier=50;
		TimeOuts.WriteTotalTimeoutConstant=2000;
		
		SetCommTimeouts(m_hCom, &TimeOuts);    //set read_write operation permits the timeout
		
		m_btnSend.EnableWindow(TRUE);													 
		m_btnClosePort.EnableWindow(TRUE);				
		m_btnOpenPort.EnableWindow(FALSE);			
		
	}
	else
	{
		AfxMessageBox("can't open the com! Please open  the com dosn't redundant!");
		return FALSE;
		
	}
	hWnd=GetSafeHwnd();	
	
	/*****When opens the com create the thread automatically,and carries out immediately*****/
	
	DWORD dwParam;
	if(!SetCommMask(m_hCom,EV_RXCHAR))		    //set permission event type		
	{												
		AfxMessageBox("create event mask fail!");
		
	}
	hThreadEvent=CreateThread(NULL,				 //create event thread	
		0,										
		(LPTHREAD_START_ROUTINE)CommProc,	     //the name of thread
		&dwParam,									
		0,									   //carries out immediately
		&dwThreadID);								
	if(hThreadEvent==INVALID_HANDLE_VALUE)
	{
		AfxMessageBox("event thread create fail!");
	}
	
	fEventRun=TRUE;	
	return TRUE;
}



DWORD WINAPI CommProc(LPVOID pParam)     //  Uses in worker thread which monitors the com
{
	DWORD dwEvtMask,dwRes;					
	Eol.hEvent=CreateEvent(NULL,		  	 //set the non- signal condition
		TRUE,								 
		FALSE,								
		NULL);								 
	while (fEventRun) {
		WaitCommEvent(m_hCom,				 //Surveillance com event
			&dwEvtMask,						 
			&Eol);							 
		dwRes=WaitForSingleObject(Eol.hEvent,      //wait for signal
			100);							
		switch(dwRes) {
		case WAIT_OBJECT_0:			          //get the result of event surveillance		 
			{
				switch(dwEvtMask) {			 
				case EV_RXCHAR:	                //received the data
					if (!fStopMsg) {
						fStopMsg=TRUE;											
						::PostMessage(hWnd,WM_COMMNOTIFY,0,(LPARAM)EV_RXCHAR);
					}
					break;
					
				default:
					;
				}
			}
			break;
		default:
			;
		}
	}
	return TRUE;
	
}



LRESULT CComDlg::OnCommNotify(WPARAM wParam, LPARAM lParam)
{
	
	BYTE   buffer[1000];
	DWORD  dwRes;
	DWORD  dwRead;
	DWORD  dwErrors;
	COMSTAT Stat;
	CString recvStr,r,e;
	CString strDis,strTemp;
	fStopMsg=TRUE;		       //Stops thread message transmit	
	int i,sum=0;	
	strDis="Receive:";
	ClearCommError(m_hCom,&dwErrors,&Stat);			
	if(Stat.cbInQue){
		if (ReadFile(m_hCom,&buffer,Stat.cbInQue,NULL,&Rol)){
			for(int i=0;i<Stat.cbInQue;i++){
				m_data.push_back(buffer[i]);
			}       		
		}else{
			AfxMessageBox("can't received successfully! ");
			Rol.hEvent=CreateEvent(NULL,	
				true,						
				false,			
				NULL);						
			dwRes=WaitForSingleObject(Rol.hEvent,5000);	
			switch(dwRes) {	
			case WAIT_OBJECT_0:				
				if (!GetOverlappedResult(m_hCom,
					&Rol,		
					&dwRead,	
					TRUE))		
				{
					
					AfxMessageBox("can't read!");
				}
				else
				{
					
					AfxMessageBox("WAIT_OBJECT_0 else");
					for( i=0;i<Stat.cbInQue;i++){
						m_data.push_back(buffer[i]);
					}
				
					break;
			case WAIT_TIMEOUT:
				
				AfxMessageBox("WAIT_TIMEOUT error!");
				break;
			default:
				
				AfxMessageBox("default!");
				break;
				}
			}
		}
	}
	if (judge(m_data,strDis)) {
		strDis += "\15\12";
		m_editReceive.ReplaceSel(strDis);
	}
	
	PurgeComm(m_hCom,PURGE_RXCLEAR);
	PurgeComm(m_hCom,PURGE_TXCLEAR);
	CloseHandle(Rol.hEvent);
	fStopMsg=FALSE;					
	return 0;
	
}


BOOL CComDlg::judge(deque<BYTE> & data,CString &recvStr)
{
	BYTE Output[1000];
	int i;
	CString r;
	BOOL is = FALSE,retr = TRUE,display = FALSE,correct=FALSE,next = FALSE; 
	int length;		
	while(retr){			
		i = 0;	
		int sum=0;		
		while(!data.empty()&&(is == FALSE)){			
			if(data.at(0) == 0XFF){
				if(data.size()<=5){
					is = TRUE;
				}else{
					if(data.at(1)==0XFF&&data.at(2)==0XFB)
						is =TRUE;
					else

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -