/*
Module : SERIALPORT.CPP
Purpose: Implementation for an MFC wrapper class for serial ports
Created: PJN / 31-05-1999
History: 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::SetDTR
PJN / 08-05-2000 1. Fixed an unreferrenced variable in CSerialPort::GetOverlappedResult in VC 6
PJN / 10-12-2000 1. Made class destructor virtual
PJN / 15-01-2001 1. Attach method now also allows you to specify whether the serial port
is being attached to in overlapped mode
2. Removed some ASSERT's which were unnecessary in some of the functions
3. Updated the Read method which uses OVERLAPPED IO to also return the bytes
read. This allows calls to WriteFile with a 0'ized overlapped structure (This
is required when dealing with TAPI and serial communications)
4. Now includes copyright message in the source code and documentation.
PJN / 24-03-2001 1. Added a BytesWaiting method
PJN / 04-04-2001 1. Provided an overriden version of BytesWaiting which specifies a timeout
PJN / 23-04-2001 1. Fixed a memory leak in DataWaiting method
PJN / 01-05-2002 1. Fixed a problem in Open method which was failing to initialize the DCB
structure incorrectly, when calling GetState. Thanks to Ben Newson for this fix.
PJN / 29-05-2002 1. Fixed an problem where the GetProcAddress for CancelIO was using the
wrong calling convention
PJN / 07-08-2002 1. Changed the declaration of CSerialPort::WaitEvent to be consistent with the
rest of the methods in CSerialPort which can operate in "OVERLAPPED" mode. A note
about the usage of this: If the method succeeds then the overlapped operation
has completed synchronously and there is no need to do a WaitForSingle/Multiple]Object.
If any other unexpected error occurs then a CSerialException will be thrown. See
the implementation of the CSerialPort::DataWaiting which has been rewritten to use
this new design pattern. Thanks to Serhiy Pavlov for spotting this inconsistency.
PJN / 20-09-2002 1. Addition of an additional ASSERT in the internal _OnCompletion function.
2. Addition of an optional out parameter to the Write method which operates in
overlapped mode. Thanks to Kevin Pinkerton for this addition.
Copyright (c) 1996 - 2002 by PJ Naughter. (Web: www.naughter.com, Email: pjna@naughter.com)
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
///////////////////////////////// Includes //////////////////////////////////
#include "stdafx.h"
#include "serialport.h"
#ifndef _WINERROR_
#include "winerror.h"
#endif
///////////////////////////////// defines /////////////////////////////////////
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static 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_DATA
{
public:
//Constructors /Destructors
_SERIAL_PORT_DATA();
~_SERIAL_PORT_DATA();
HINSTANCE m_hKernel32;
typedef BOOL (WINAPI 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 code
void AfxThrowSerialException(DWORD dwError /* = 0 */)
{
if (dwError == 0)
dwError = ::GetLastError();
CSerialException* pException = new CSerialException(dwError);
TRACE(_T("Warning: throwing CSerialException for error %d\n"), 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';
else
{
lstrcpyn(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 _DEBUG
void CSerialException::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
dc << "m_dwError = " << m_dwError;
}
#endif
////////// The actual serial port code
CSerialPort::CSerialPort()
{
m_hComm = INVALID_HANDLE_VALUE;
m_bOverlapped = FALSE;
m_hEvent = NULL;
}
CSerialPort::~CSerialPort()
{
Close();
}
IMPLEMENT_DYNAMIC(CSerialPort, CObject)
#ifdef _DEBUG
void CSerialPort::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
dc << _T("m_hComm = ") << m_hComm << _T("\n");
dc << _T("m_bOverlapped = ") << m_bOverlapped;
}
#endif
void CSerialPort::Open(int nPort, DWORD dwBaud, Parity parity, BYTE DataBits, StopBits stopbits, FlowControl fc, BOOL bOverlapped)
{
//Validate our parameters
ASSERT(nPort>0 && nPort<=255);
Close(); //In case we are already open
//Call CreateFile to open up the comms port
CString sPort;
sPort.Format(_T("\\\\.\\COM%d"), nPort);
m_hComm = CreateFile(sPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, bOverlapped ? FILE_FLAG_OVERLAPPED : 0, NULL);
if (m_hComm == INVALID_HANDLE_VALUE)
{
TRACE(_T("Failed to open up the comms port\n"));
AfxThrowSerialException();
}
//Create the event we ne