




已阅读5页,还剩31页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
最近因为工作的关系,要学习串口编程,在网上无意中发现了PJ Naughter写的一个串口类(不知是何许人,孤陋寡闻,甚觉汗颜),感觉还可以,就抽了点时间把他网站上的有关此类的信息翻译了下,有时间研究下,说不定能用到项目中。时间较为仓促,加上我也不想在咬文嚼字上较真,肯定有许多不足,望大家指正,同时也希望对串口有研究的同志们不吝赐教。一、类源文件1.SERIALPORT.H/*Module : SERIALPORT.HPurpose: Declaration for an MFC wrapper class for serial portsCreated: PJN / 31-05-1999History: NoneCopyright (c) 1999 by PJ Naughter.All rights reserved.*/ Macros / Structs etc /#ifndef _SERIALPORT_H_#define _SERIALPORT_H_/ Classes / Serial port exception class /void AfxThrowSerialException(DWORD dwError = 0);class CSerialException : public CExceptionpublic:/Constructors / DestructorsCSerialException(DWORD dwError);CSerialException();/Methods#ifdef _DEBUGvirtual void Dump(CDumpContext& dc) const;#endifvirtual BOOL GetErrorMessage(LPTSTR lpstrError, UINT nMaxError,PUINT pnHelpContext = NULL);CString GetErrorMessage();/Data membersDWORD m_dwError;protected:DECLARE_DYNAMIC(CSerialException);/ The actual serial port class /class CSerialPort : public CObjectpublic:/Enums enum FlowControl NoFlowControl, CtsRtsFlowControl, CtsDtrFlowControl, DsrRtsFlowControl, DsrDtrFlowControl, XonXoffFlowControl ; enum Parity EvenParity, MarkParity, NoParity, OddParity, SpaceParity ; enum StopBits OneStopBit, OnePointFiveStopBits, TwoStopBits ;/Constructors / Destructors CSerialPort(); CSerialPort();/General Methods void Open(int nPort, DWORD dwBaud = 9600, Parity parity = NoParity, BYTE DataBits = 8, StopBits stopbits = OneStopBit, FlowControl fc = NoFlowControl, BOOL bOverlapped = FALSE); void Close(); void Attach(HANDLE hComm); HANDLE Detach(); operator HANDLE() const return m_hComm; ; BOOL IsOpen() const return m_hComm != INVALID_HANDLE_VALUE; ;#ifdef _DEBUG void CSerialPort:Dump(CDumpContext& dc) const;#endif/Reading / Writing Methods DWORD Read(void* lpBuf, DWORD dwCount); BOOL Read(void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped); void ReadEx(void* lpBuf, DWORD dwCount); DWORD Write(const void* lpBuf, DWORD dwCount); BOOL Write(const void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped); void WriteEx(const void* lpBuf, DWORD dwCount); void TransmitChar(char cChar); void GetOverlappedResult(OVERLAPPED& overlapped, DWORD& dwBytesTransferred, BOOL bWait); void CancelIo();/Configuration Methods void GetConfig(COMMCONFIG& config); static void GetDefaultConfig(int nPort, COMMCONFIG& config); void SetConfig(COMMCONFIG& Config); static void SetDefaultConfig(int nPort, COMMCONFIG& config);/Misc RS232 Methods void ClearBreak(); void SetBreak(); void ClearError(DWORD& dwErrors); void GetStatus(COMSTAT& stat); void GetState(DCB& dcb); void SetState(DCB& dcb); void Escape(DWORD dwFunc); void ClearDTR(); void ClearRTS(); void SetDTR(); void SetRTS(); void SetXOFF(); void SetXON(); void GetProperties(COMMPROP& properties); void GetModemStatus(DWORD& dwModemStatus);/Timeouts void SetTimeouts(COMMTIMEOUTS& timeouts); void GetTimeouts(COMMTIMEOUTS& timeouts); void Set0Timeout(); void Set0WriteTimeout(); void Set0ReadTimeout();/Event Methods void SetMask(DWORD dwMask); void GetMask(DWORD& dwMask); void WaitEvent(DWORD& dwMask); void WaitEvent(DWORD& dwMask, OVERLAPPED& overlapped);/Queue Methods void Flush(); void Purge(DWORD dwFlags); void TerminateOutstandingWrites(); void TerminateOutstandingReads(); void ClearWriteBuffer(); void ClearReadBuffer(); void Setup(DWORD dwInQueue, DWORD dwOutQueue);/Overridables virtual void OnCompletion(DWORD dwErrorCode, DWORD dwCount, LPOVERLAPPED lpOverlapped);protected: HANDLE m_hComm; /Handle to the comms port BOOL m_bOverlapped; /Is the port open in overlapped IO static void WINAPI _OnCompletion(DWORD dwErrorCode, DWORD dwCount, LPOVERLAPPED lpOverlapped);DECLARE_DYNAMIC(CSerialPort);#endif /_SERIALPORT_H_2./*Module : SERIALPORT.CPPPurpose: Implementation for an MFC wrapper class for serial portsCreated: PJN / 31-05-1999History: PJN / 03-06-1999 1. Fixed problem with code using CancelIo which does not exist on 95. 2. Fixed leaks which can occur in sample app when an exception is thrown PJN / 16-06-1999 1. Fixed a bug whereby CString:ReleaseBuffer was not being called in CSerialException:GetErrorMessage PJN / 29-09-1999 1. Fixed a simple copy and paste bug in CSerialPort:SetDTRCopyright (c) 1999 by PJ Naughter.All rights reserved.*/ Includes /#include stdafx.h#include serialport.h#include winerror.h/ defines /#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE = _FILE_;#endif/ Implementation /Class which handles CancelIo function which must be constructed at run time/since it is not imeplemented on NT 3.51 or Windows 95. To avoid the loader/bringing up a message such as Failed to load due to missing export., the/function is constructed using GetProcAddress. The CSerialPort:CancelIo/function then checks to see if the function pointer is NULL and if it is it/throws an exception using the error code ERROR_CALL_NOT_IMPLEMENTED which/is what 95 would have done if it had implemented a stub for it in the first/place !class _SERIAL_PORT_DATApublic:/Constructors /Destructors _SERIAL_PORT_DATA(); _SERIAL_PORT_DATA(); HINSTANCE m_hKernel32; typedef BOOL (CANCELIO)(HANDLE); typedef CANCELIO* LPCANCELIO; LPCANCELIO m_lpfnCancelIo;_SERIAL_PORT_DATA:_SERIAL_PORT_DATA() m_hKernel32 = LoadLibrary(_T(KERNEL32.DLL); VERIFY(m_hKernel32 != NULL); m_lpfnCancelIo = (LPCANCELIO) GetProcAddress(m_hKernel32, CancelIo);_SERIAL_PORT_DATA:_SERIAL_PORT_DATA() FreeLibrary(m_hKernel32); m_hKernel32 = NULL;/The local variable which handle the function pointers_SERIAL_PORT_DATA _SerialPortData;/ Exception handling codevoid AfxThrowSerialException(DWORD dwError /* = 0 */)if (dwError = 0)dwError = :GetLastError();CSerialException* pException = new CSerialException(dwError);TRACE(_T(Warning: throwing CSerialException for error %dn), dwError);THROW(pException);BOOL CSerialException:GetErrorMessage(LPTSTR pstrError, UINT nMaxError, PUINT pnHelpContext)ASSERT(pstrError != NULL & AfxIsValidString(pstrError, nMaxError);if (pnHelpContext != NULL)*pnHelpContext = 0;LPTSTR lpBuffer;BOOL bRet = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, m_dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), (LPTSTR) &lpBuffer, 0, NULL);if (bRet = FALSE)*pstrError = 0;elselstrcpyn(pstrError, lpBuffer, nMaxError);bRet = TRUE;LocalFree(lpBuffer);return bRet;CString CSerialException:GetErrorMessage() CString rVal; LPTSTR pstrError = rVal.GetBuffer(4096); GetErrorMessage(pstrError, 4096, NULL); rVal.ReleaseBuffer(); return rVal;CSerialException:CSerialException(DWORD dwError)m_dwError = dwError;CSerialException:CSerialException()IMPLEMENT_DYNAMIC(CSerialException, CException)#ifdef _DEBUGvoid CSerialException:Dump(CDumpContext& dc) constCObject:Dump(dc);dc m_dwError = m_dwError;#endif/ The actual serial port codeCSerialPort:CSerialPort() m_hComm = INVALID_HANDLE_VALUE; m_bOverlapped = FALSE;CSerialPort:CSerialPort() Close();IMPLEMENT_DYNAMIC(CSerialPort, CObject)#ifdef _DEBUGvoid CSerialPort:Dump(CDumpContext& dc) constCObject:Dump(dc);dc _T(m_hComm = ) m_hComm _T(n); dc _T(m_bOverlapped = ) 0 & nPorthEvent; ASSERT(pSerialPort-IsKindOf(RUNTIME_CLASS(CSerialPort); /Call the C+ function pSerialPort-OnCompletion(dwErrorCode, dwCount, lpOverlapped);void CSerialPort:OnCompletion(DWORD /*dwErrorCode*/, DWORD /*dwCount*/, LPOVERLAPPED lpOverlapped) /Just free up the memory which was previously allocated for the OVERLAPPED structure delete lpOverlapped; /Your derived classes can do something useful in OnCompletion, but dont forget to /call CSerialPort:OnCompletion to ensure the memory is freed upvoid CSerialPort:CancelIo() ASSERT(IsOpen(); if (_SerialPortData.m_lpfnCancelIo = NULL) TRACE(_T(CancelIo function is not supported on this OS. You need to be running at least NT 4 or Win 98 to use this functionn); AfxThrowSerialException(ERROR_CALL_NOT_IMPLEMENTED); if (!:_SerialPortData.m_lpfnCancelIo(m_hComm) TRACE(_T(Failed in call to CancelIOn); AfxThrowSerialException(); void CSerialPort:WriteEx(const void* lpBuf, DWORD dwCount) ASSERT(IsOpen(); OVERLAPPED* pOverlapped = new OVERLAPPED; ZeroMemory(pOverlapped, sizeof(OVERLAPPED); pOverlapped-hEvent = (HANDLE) this; if (!WriteFileEx(m_hComm, lpBuf, dwCount, pOverlapped, _OnCompletion) delete pOverlapped; TRACE(_T(Failed in call to WriteFileExn); AfxThrowSerialException(); void CSerialPort:ReadEx(void* lpBuf, DWORD dwCount) ASSERT(IsOpen(); OVERLAPPED* pOverlapped = new OVERLAPPED; ZeroMemory(pOverlapped, sizeof(OVERLAPPED); pOverlapped-hEvent = (HANDLE) this; if (!ReadFileEx(m_hComm, lpBuf, dwCount, pOverlapped, _OnCompletion) delete pOverlapped; TRACE(_T(Failed in call to ReadFileExn); AfxThrowSerialException(); void CSerialPort:TransmitChar(char cChar) ASSERT(IsOpen(); if (!TransmitCommChar(m_hComm, cChar) TRACE(_T(Failed in call to TransmitCommCharn); AfxThrowSerialException(); void CSerialPort:GetConfig(COMMCONFIG& config) ASSERT(IsOpen(); DWORD dwSize = sizeof(COMMCONFIG); if (!GetCommConfig(m_hComm, &config, &dwSize) TRACE(_T(Failed in call to GetCommConfign); AfxThrowSerialException(); void CSerialPort:SetConfig(COMMCONFIG& config) ASSERT(IsOpen(); DWORD dwSize = sizeof(COMMCONFIG); if (!SetCommConfig(m_hComm, &config, dwSize) TRACE(_T(Failed in call to SetCommConfign); AfxThrowSerialException(); void CSerialPort:SetBreak() ASSERT(IsOpen(); if (!SetCommBreak(m_hComm) TRACE(_T(Failed in call to SetCommBreakn); AfxThrowSerialException(); void CSerialPort:ClearBreak() ASSERT(IsOpen(); if (!ClearCommBreak(m_hComm) TRACE(_T(Failed in call to SetCommBreakn); AfxThrowSerialException(); void CSerialPort:ClearError(DWORD& dwErrors) ASSERT(IsOpen(); if (!ClearCommError(m_hComm, &dwErrors, NULL) TRACE(_T(Failed in call to ClearCommErrorn); AfxThrowSerialException(); void CSerialPort:GetDefaultConfig(int nPort, COMMCONFIG& config) /Validate our parameters ASSERT(nPort0 & nPort0 & nPort=255); /Create the device name as a string CString sPort; sPort.Format(_T(COM%d), nPort); DWORD dwSize = sizeof(COMMCONFIG); if (!SetDefaultCommConfig(sPort, &config, dwSize) TRACE(_T(Failed in call to GetDefaultCommConfign); AfxThrowSerialException(); void CSerialPort:GetStatus(COMSTAT& stat) ASSERT(IsOpen(); DWORD dwErrors; if (!ClearCommError(m_hComm, &dwErrors, &stat) TRACE(_T(Failed in call to ClearCommErrorn); AfxThrowSerialException(); void CSerialPort:Ge
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 二零二五年度手机配件OEM定制生产及销售合同范本
- 二零二五版航空设备加工制造承包合同样本
- 二零二五年度WPS文档租赁合同:政府机构定制服务
- 2025版彩钢钢结构安装与设计合同
- 二零二五年度办公家具智能化改造升级合同创新
- 2025版智能设备生产车间承包与智能化升级合同
- 二零二五年度厂房物业管理与业务拓展服务合同
- 2025版高性能塑料销售合同规范范本
- 二零二五年度茶山茶叶种植与茶叶加工一体化承包合同
- 二零二五年壁纸原材料供应链管理合同
- 全新退换货协议模板
- 危重患者的早期识别与处理
- (正式版)JBT 14449-2024 起重机械焊接工艺评定
- 商务礼仪之座次及用餐
- SEO谷歌推广方案
- 注塑标准成型条件表电子表格模板
- 企业数字化管理
- 道闸系统施工方案
- DB41-T 2563-2023 新生儿脐静脉导管维护技术操作规范
- 配置管理与漏洞修复
- 新版中国复发难治性急性髓系白血病诊疗指南
评论
0/150
提交评论