// Eg12_1Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "Eg12_1.h"
#include "Eg12_1Dlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
    DCB dcb;		//编程配置串口结构
	HANDLE hCom1;	//句柄
	DWORD dwError,dwEvtMask,dwEvent;
	BOOL fSuccess;//判断是否成功

	OVERLAPPED o;
	COMMPROP CommProp;	//串口信息结构，不可更改
	COMMTIMEOUTS timeouts;	//定义超时设置结构
	COMSTAT cs;

	char input[1000];
	CString receiveData;
	HWND hWndUpdate;
	int t=50;
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()

/////////////////////////////////////////////////////////////////////////////
// CEg12_1Dlg dialog

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

void CEg12_1Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CEg12_1Dlg)
	DDX_Text(pDX, IDC_EDIT1, m_sendData);
	DDX_Text(pDX, IDC_EDIT2, m_receiveData);
	DDX_Text(pDX, IDC_EDIT3, m_receive);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CEg12_1Dlg, CDialog)
	//{{AFX_MSG_MAP(CEg12_1Dlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, OnConfig)
	ON_BN_CLICKED(IDC_BUTTON2, OnSend)
	ON_BN_CLICKED(IDC_BUTTON3, OnClear)
	ON_BN_CLICKED(IDC_BUTTON4, OnQuit)
	//}}AFX_MSG_MAP
	ON_MESSAGE(WM_USERUPDATE,OnUserUpdate)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CEg12_1Dlg message handlers

BOOL CEg12_1Dlg::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
	//打开COM1口
	hCom1=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,//访问类型可读写
		0,//独占串口
		NULL,//无安全属性
		OPEN_EXISTING,//打开已存在的串口
		FILE_FLAG_OVERLAPPED,//异步串口
		NULL);//模块句柄为空

//	if(hCom1==INVALID_HANDLE_VALUE)	//检测打开是否成功。
//	{
//		dwError=GetLastError();
//		MessageBox("Error");
//	}
	SetupComm(hCom1,1024,1024);	//设置接收，发送缓冲区各1024字节
	GetCommProperties(hCom1,&CommProp);	//获取串口信息
	
	
////////////////定义串口//////////////////////////////////
//////获取DCB结构
	GetCommProperties(hCom1,&CommProp);	//获取串口信息
	fSuccess=GetCommState(hCom1,&dcb);
	if(!fSuccess)
		MessageBox("获取DCB结构错误！");
	
	//检测串口是否支持19200的波特率
	if(CommProp.dwSettableBaud&BAUD_19200)
	dcb.BaudRate=9600;		//定义19200的波特率
	dcb.ByteSize=8;			//定义串口的数据位数8
	dcb.Parity=NOPARITY;	//无奇偶校验
	dcb.StopBits=ONESTOPBIT;//一位停止位
	dcb.EvtChar=0x7e;		//定义当接收此字符时，产生一事件
	fSuccess=SetCommState(hCom1,&dcb);//设置串口

	if(!fSuccess) //检测串口DCB结构设置是否正确
		MessageBox("DCB结构设置错误!");
	
//////////////////超时设定///////////////////////////////////
	GetCommTimeouts(hCom1,&timeouts);
	timeouts.ReadIntervalTimeout=MAXDWORD;//读区间超时设定
	timeouts.ReadTotalTimeoutConstant=1000;
	timeouts.WriteTotalTimeoutConstant=1000;
	SetCommTimeouts(hCom1,&timeouts);
//////////////////////////////////////////////////////////////
	

	UpdateData(FALSE);	
	OnReceive();
	return TRUE;  // return TRUE  unless you set the focus to a control
}
UINT ReadProc(LPVOID param )
{ 	
	unsigned long nBytesRead;
	o.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
	while(TRUE)
	{
		SetCommMask(hCom1,EV_RXCHAR);		// 设置通信检测事件。
		if(WaitCommEvent(hCom1,&dwEvent,NULL))	//检测通信事件。
		{
			::Sleep(t);	//等待t毫秒，以便数据能完全接收。
			ClearCommError(hCom1,&dwError,&cs); //获取缓冲区字节数。
			if(cs.cbInQue)
			{
				if(!ReadFile(hCom1,input,cs.cbInQue,
					&nBytesRead,&o)) 		 //读串口
				{
					AfxMessageBox("读串口失败!");
					return 0;
				}
				else		//读串口成功!
				{
					receiveData=CString(input,nBytesRead);
					//把字符串转换为String型。
					::PostMessage(hWndUpdate,WM_USERUPDATE,0,0);
					//告诉主线程，数据接收完毕，可以处理数据了。
				}
				ResetEvent(o.hEvent);	//复位
			}
		}
		PurgeComm(hCom1,PURGE_RXCLEAR); 	//清输入缓冲区。
	}
	return 1;
}
void CEg12_1Dlg::OnReceive() 
{
	// TODO: Add your control notification handler code here

HWND hWndread=GetSafeHwnd();
	//启动读线程.
 AfxBeginThread(ReadProc,hWndread,THREAD_PRIORITY_NORMAL);
}
void CEg12_1Dlg::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 CEg12_1Dlg::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 CEg12_1Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
void CEg12_1Dlg::OnSend() 
{

	// TODO: Add your control notification handler code here
	unsigned long nToWrite;
	UpdateData();
	PurgeComm(hCom1,PURGE_TXCLEAR);//清发送缓冲区。
	PurgeComm(hCom1,PURGE_RXCLEAR);//清接受缓冲区。		
	WriteFile(hCom1,m_sendData,m_sendData.GetLength(),&nToWrite,&o);
	//WriteFile(hCom,out,length,&nToWrite,&o); //写串口
	PurgeComm(hCom1,PURGE_TXCLEAR); //清发送缓冲区。
	
}	
void CEg12_1Dlg::OnConfig() 
{
	// TODO: Add your control notification handler code here
	COMMCONFIG cc;
	cc.dcb=dcb;
	if(!CommConfigDialog("com1",GetSafeHwnd(),&cc))
		return;
	dcb=cc.dcb;
	SetCommState(hCom1,&dcb);	
}

LONG CEg12_1Dlg::OnUserUpdate(WPARAM wParam,LPARAM lParam)
{
	//等待读线程完毕，或超出定时。
	m_receiveData=receiveData;
	m_receive+=m_receiveData;
	UpdateData(FALSE);

	return 0;
}

void CEg12_1Dlg::OnClear() 
{
	// TODO: Add your control notification handler code here
	m_sendData="";
	UpdateData(FALSE);
	
}
void CEg12_1Dlg::OnQuit() 
{
	// TODO: Add your control notification handler code here
	CloseHandle(hCom1);
	CDialog::OnCancel();	
}
