[Tinyos-contrib-commits] CVS: tinyos-1.x/contrib/imote2/tools/src/SerialTerminal/SerialTerminal ConfigurationPage.cpp, NONE, 1.1 ConfigurationPage.h, NONE, 1.1 MainFrm.cpp, NONE, 1.1 MainFrm.h, NONE, 1.1 ReadMe.txt, NONE, 1.1 resource.h, NONE, 1.1 SerialPort.cpp, NONE, 1.1 SerialPort.h, NONE, 1.1 SerialTerminal.aps, NONE, 1.1 SerialTerminal.cpp, NONE, 1.1 SerialTerminal.h, NONE, 1.1 SerialTerminal.rc, NONE, 1.1 SerialTerminal.reg, NONE, 1.1 SerialTerminal.vcproj, NONE, 1.1 SerialTerminalDoc.cpp, NONE, 1.1 SerialTerminalDoc.h, NONE, 1.1 SerialTerminalView.cpp, NONE, 1.1 SerialTerminalView.h, NONE, 1.1 stdafx.cpp, NONE, 1.1 stdafx.h, NONE, 1.1

Robbie Adler radler at users.sourceforge.net
Fri May 4 13:26:32 PDT 2007


Update of /cvsroot/tinyos/tinyos-1.x/contrib/imote2/tools/src/SerialTerminal/SerialTerminal
In directory sc8-pr-cvs10.sourceforge.net:/tmp/cvs-serv31005

Added Files:
	ConfigurationPage.cpp ConfigurationPage.h MainFrm.cpp 
	MainFrm.h ReadMe.txt resource.h SerialPort.cpp SerialPort.h 
	SerialTerminal.aps SerialTerminal.cpp SerialTerminal.h 
	SerialTerminal.rc SerialTerminal.reg SerialTerminal.vcproj 
	SerialTerminalDoc.cpp SerialTerminalDoc.h 
	SerialTerminalView.cpp SerialTerminalView.h stdafx.cpp 
	stdafx.h 
Log Message:
initial export of Serial Terminal application.  This app is a C++/MFC based hyperterminal-like Windows app that adds some nice additional features such as timestamping and logging and color coding of imote2 specific shell message

--- NEW FILE: ConfigurationPage.cpp ---
// ConfigurationPage.cpp : implementation file
//

#include "stdafx.h"
#include "SerialTerminal.h"
#include "ConfigurationPage.h"

// CConfigurationPage dialog

IMPLEMENT_DYNAMIC(CConfigurationPage, CPropertyPage)
CConfigurationPage::CConfigurationPage(COMMCONFIG *CommConfig, CString COMPortName, CString logfileName)
	: CPropertyPage(CConfigurationPage::IDD), m_pCommConfig(CommConfig)
	, m_comportComboValue(_T("")), m_strPortName(COMPortName)
	, m_filename(logfileName)
	, m_bAutoStart(FALSE)
{
}

CConfigurationPage::~CConfigurationPage()
{
}

void CConfigurationPage::DoDataExchange(CDataExchange* pDX)
{
	CPropertyPage::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO_COMPORT, m_comportComboControl);
	DDX_CBString(pDX, IDC_COMBO_COMPORT, m_comportComboValue);
	DDX_Text(pDX, IDC_EDIT_FILENAME, m_filename);
	DDX_Check(pDX, IDC_CHECK_AUTOSTART, m_bAutoStart);
	DDX_Radio(pDX, IDC_RADIO_OVERWRITE, m_bAppendLog);
}


BEGIN_MESSAGE_MAP(CConfigurationPage, CPropertyPage)
	ON_BN_CLICKED(IDC_BUTTON_SETTINGS, OnBnClickedButtonSettings)
//	ON_EN_CHANGE(IDC_EDIT_FILENAME, &CConfigurationPage::OnEnChangeEditFilename)
//ON_BN_CLICKED(IDC_BUTTON1, &CConfigurationPage::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON_BROWSE, &CConfigurationPage::OnBnClickedButtonBrowse)
END_MESSAGE_MAP()


// CConfigurationPage message handlers
void CConfigurationPage::PopulateSystemSerialPorts()
{
	//serial ports reside at HKLM/HARDWARE/DEVICEMAP/SERIALCOMM
	HKEY hkey;
	DWORD dwIndex = 0;
	TCHAR *lpValueName; 
	BYTE *lpData;
	DWORD values, maxValueNameLen, nameLen, maxValueDataLen, dataLen;
	
	if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
					TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
					0,
					KEY_QUERY_VALUE,
					&hkey) != ERROR_SUCCESS) 
	{
		TRACE(_T("Unable to open HKLM\\HARDWARE\\DEVICEMAP\\SERIALCOMM\n"));	
		return;
	}
	
	RegQueryInfoKey(hkey, NULL, NULL, NULL, NULL, NULL, NULL, &values,&maxValueNameLen, &maxValueDataLen, NULL, NULL);
	maxValueNameLen++;//need to include the terminating NULL char
	maxValueDataLen++;//need to include the terminating NULL char
	lpValueName = new TCHAR[maxValueNameLen+1];
	lpData = new BYTE[maxValueDataLen+1];

	nameLen = maxValueNameLen;
	dataLen = maxValueDataLen;
	while(RegEnumValue(hkey, dwIndex, lpValueName, &nameLen, NULL, NULL, lpData, &dataLen) != ERROR_NO_MORE_ITEMS)
	{
		TRACE(_T("%s = %s\n"),lpValueName, lpData);
		dwIndex++;
		nameLen = maxValueNameLen;
		dataLen = maxValueDataLen;
		m_comportComboControl.AddString((LPCTSTR)lpData);
	}

	//	RegQueryValueEx(hkey, lpValueName, lpreserved, lptype, lpdata, lpcbdata);
	delete[] lpValueName;
	delete[] lpData;

	RegCloseKey(hkey);
}

BOOL CConfigurationPage::OnInitDialog()
{
	CPropertyPage::OnInitDialog();
	
	PopulateSystemSerialPorts();
	int i, NumEntries = m_comportComboControl.GetCount();
	for (i=0; i<NumEntries; i++)
	{	
		CString string;
		m_comportComboControl.GetLBText(i,string);
		if(m_strPortName == (_T("\\\\.\\")+ string))
		{
			m_comportComboControl.SetCurSel(i);
			break;		
		}
	}
	if(i==NumEntries)
	{
		m_comportComboControl.SetCurSel(0);
	}
	
	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CConfigurationPage::OnBnClickedButtonSettings()
{
	UpdateData();
	if(!CommConfigDialog(m_comportComboValue,m_hWnd,m_pCommConfig))
	{
		LPVOID lpMsgBuf;

		FormatMessage( 
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM | 
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				GetLastError(),
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
				(LPTSTR) &lpMsgBuf,
				0,
				NULL 
			);

		TRACE((char*)lpMsgBuf);
		LocalFree( lpMsgBuf );
	}
}

BOOL CConfigurationPage::OnApply()
{
	ASSERT_VALID(this);
	
	//don't let the ok button be pressed unless the dcb structure as been filled in
	if(m_pCommConfig->dcb.BaudRate == 0){
		OnBnClickedButtonSettings();
	}
	if(m_pCommConfig->dcb.BaudRate == 0){
		
		//user must have cancelled out...don't do anything
		return FALSE;	
	}
	else{
		
		return TRUE;
	}
}

void CConfigurationPage::OnBnClickedButtonBrowse()
{
	UpdateData();

	CFileDialog dlg(TRUE,_T(".log"),m_filename);
	
	if(dlg.DoModal() == IDOK){
		m_filename = dlg.GetPathName();	
		UpdateData(FALSE);
	}	
}

--- NEW FILE: ConfigurationPage.h ---
#pragma once
#include "afxwin.h"

// CConfigurationPage dialog

class CConfigurationPage : public CPropertyPage
{
	DECLARE_DYNAMIC(CConfigurationPage)

public:
	CConfigurationPage(COMMCONFIG *CommConfig, CString COMPortName, CString logfileName);
	virtual ~CConfigurationPage();

// Dialog Data
	enum { IDD = IDD_PP_CONFIGURATION };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	void PopulateSystemSerialPorts();

	DECLARE_MESSAGE_MAP()
public:
	virtual BOOL OnInitDialog();
	CComboBox m_comportComboControl;
	COMMCONFIG *m_pCommConfig;
	CString m_strPortName;
	afx_msg void OnBnClickedButtonSettings();
	CString m_comportComboValue;
	CString m_filename;
	BOOL m_bAutoStart;
	BOOL m_bAppendLog;
public:
	virtual BOOL OnApply();
public:
	afx_msg void OnBnClickedButtonBrowse();
	
};

--- NEW FILE: MainFrm.cpp ---
// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "SerialTerminal.h"

#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};


// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	// TODO: add member initialization code here
}

CMainFrame::~CMainFrame()
{
}


int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE(_T("Failed to create toolbar\n"));
		return -1;      // fail to create
	}

	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE(_T("Failed to create status bar\n"));
		return -1;      // fail to create
	}
	
	if (!m_mainDialogBar.Create(this, 
			IDD_MainDialogBar, 
			CBRS_GRIPPER|CBRS_TOP|CBRS_FLYBY, 
			IDD_MainDialogBar))
	{
		TRACE(_T("Failed to create status bar\n"));
		return -1;      // fail to create
	}


	// TODO: Delete these three lines if you don't want the toolbar to be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	m_mainDialogBar.EnableDocking(CBRS_ALIGN_ANY);

	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);
	DockControlBar(&m_mainDialogBar);
	

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return TRUE;
}


// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG


// CMainFrame message handlers




--- NEW FILE: MainFrm.h ---
// MainFrm.h : interface of the CMainFrame class
//


#pragma once

class CMainFrame : public CFrameWnd
{
	
protected: // create from serialization only
	CMainFrame();
	DECLARE_DYNCREATE(CMainFrame)

// Attributes
public:

// Operations
public:

// Overrides
public:
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

// Implementation
public:
	virtual ~CMainFrame();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

protected:  // control bar embedded members
	CStatusBar  m_wndStatusBar;
	CToolBar    m_wndToolBar;
public:
	CDialogBar  m_mainDialogBar;

// Generated message map functions
protected:
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
	DECLARE_MESSAGE_MAP()
};



--- NEW FILE: ReadMe.txt ---
================================================================================
    MICROSOFT FOUNDATION CLASS LIBRARY : SerialTerminal Project Overview
===============================================================================

The application wizard has created this SerialTerminal application for 
you.  This application not only demonstrates the basics of using the Microsoft 
Foundation Classes but is also a starting point for writing your application.

This file contains a summary of what you will find in each of the files that
make up your SerialTerminal application.

SerialTerminal.vcproj
    This is the main project file for VC++ projects generated using an application wizard. 
    It contains information about the version of Visual C++ that generated the file, and 
    information about the platforms, configurations, and project features selected with the
    application wizard.

SerialTerminal.h
    This is the main header file for the application.  It includes other
    project specific headers (including Resource.h) and declares the
    CSerialTerminalApp application class.

SerialTerminal.cpp
    This is the main application source file that contains the application
    class CSerialTerminalApp.

SerialTerminal.rc
    This is a listing of all of the Microsoft Windows resources that the
    program uses.  It includes the icons, bitmaps, and cursors that are stored
    in the RES subdirectory.  This file can be directly edited in Microsoft
    Visual C++. Your project resources are in 1033.

res\SerialTerminal.ico
    This is an icon file, which is used as the application's icon.  This
    icon is included by the main resource file SerialTerminal.rc.

res\SerialTerminal.rc2
    This file contains resources that are not edited by Microsoft 
    Visual C++. You should place all resources not editable by
    the resource editor in this file.

SerialTerminal.reg
    This is an example .reg file that shows you the kind of registration
    settings the framework will set for you.  You can use this as a .reg
    file to go along with your application or just delete it and rely
    on the default RegisterShellFileTypes registration.


/////////////////////////////////////////////////////////////////////////////

For the main frame window:
    The project includes a standard MFC interface.

MainFrm.h, MainFrm.cpp
    These files contain the frame class CMainFrame, which is derived from
    CFrameWnd and controls all SDI frame features.

res\Toolbar.bmp
    This bitmap file is used to create tiled images for the toolbar.
    The initial toolbar and status bar are constructed in the CMainFrame
    class. Edit this toolbar bitmap using the resource editor, and
    update the IDR_MAINFRAME TOOLBAR array in SerialTerminal.rc to add
    toolbar buttons.
/////////////////////////////////////////////////////////////////////////////

The application wizard creates one document type and one view:

SerialTerminalDoc.h, SerialTerminalDoc.cpp - the document
    These files contain your CSerialTerminalDoc class.  Edit these files to
    add your special document data and to implement file saving and loading
    (via CSerialTerminalDoc::Serialize).
    The Document will have the following strings:
        File extension:      log
        File type ID:        SerialTerminal.Document
        Main frame caption:  SerialTerminal
        Doc type name:       SerialTerminal
        Filter name:         SerialTerminal Files (*.log)
        File new short name: SerialTerminal
        File type long name: SerialTerminal.Document

SerialTerminalView.h, SerialTerminalView.cpp - the view of the document
    These files contain your CSerialTerminalView class.
    CSerialTerminalView objects are used to view CSerialTerminalDoc objects.





/////////////////////////////////////////////////////////////////////////////

Other Features:

ActiveX Controls
    The application includes support to use ActiveX controls.

Printing and Print Preview support
    The application wizard has generated code to handle the print, print setup, and print preview
    commands by calling member functions in the CView class from the MFC library.

/////////////////////////////////////////////////////////////////////////////

Other standard files:

StdAfx.h, StdAfx.cpp
    These files are used to build a precompiled header (PCH) file
    named SerialTerminal.pch and a precompiled types file named StdAfx.obj.

Resource.h
    This is the standard header file, which defines new resource IDs.
    Microsoft Visual C++ reads and updates this file.

SerialTerminal.manifest
	Application manifest files are used by Windows XP to describe an applications 
	dependency on specific versions of Side-by-Side assemblies. The loader uses this 
	information to load the appropriate assembly from the assembly cache or private 
	from the application. The Application manifest  maybe included for redistribution 
	as an external .manifest file that is installed in the same folder as the application 
	executable or it may be included in the executable in the form of a resource. 
/////////////////////////////////////////////////////////////////////////////

Other notes:

The application wizard uses "TODO:" to indicate parts of the source code you
should add to or customize.

If your application uses MFC in a shared DLL, you will need 
to redistribute the MFC DLLs. If your application is in a language 
other than the operating system's locale, you will also have to 
redistribute the corresponding localized resources MFC80XXX.DLL. 
For more information on both of these topics, please see the section on 
redistributing Visual C++ applications in MSDN documentation. 

/////////////////////////////////////////////////////////////////////////////

--- NEW FILE: resource.h ---
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by SerialTerminal.rc
//
#define IDR_CNTR_INPLACE                6
#define IDD_ABOUTBOX                    100
#define IDP_OLE_INIT_FAILED             100
#define IDP_FAILED_TO_CREATE            102
#define IDR_MAINFRAME                   128
#define IDR_SerialTerminalTYPE          129
#define IDR_MENU1                       130
#define IDD_PP_CONFIGURATION            132
#define IDD_MainDialogBar               134
#define IDC_BUTTON_SETTINGS             1000
#define IDC_STATIC_ASSIGNMENTBOX        1001
#define IDC_COMBO_COMPORT               1002
#define IDC_EDIT1                       1003
#define IDC_EDIT_FILENAME               1003
#define IDC_BUTTON_CONNECT              1004
#define IDS_Connect                     1004
#define IDC_CHECK_TIMESTAMPING          1005
#define IDS_STRING1005                  1005
#define IDC_BUTTON_LOG                  1006
#define IDS_STRING1006                  1006
#define IDC_BUTTON_BROWSE               1007
#define IDC_BUTTON_LOG2                 1007
#define IDC_BUTTON_CLEAR                1007
#define IDC_CHECK_AUTOSTART             1008
#define IDC_RADIO_OVERWRITE             1009
#define IDC_RADIO_APPEND                1010
#define ID_CANCEL_EDIT_CNTR             32768
#define ID_EDIT_OPTIONS                 32771

// Next default values for new objects
// 
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE        135
#define _APS_NEXT_COMMAND_VALUE         32775
#define _APS_NEXT_CONTROL_VALUE         1010
#define _APS_NEXT_SYMED_VALUE           101
#endif
#endif

--- NEW FILE: SerialPort.cpp ---
// SerialPort.cpp: implementation of the CSerialPort class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "SerialPort.h"
#include <cassert>
#include ".\serialport.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSerialPort::CSerialPort() : m_rxThread(NULL)
{
	m_hComm = INVALID_HANDLE_VALUE;
	m_hTxUpdateEvent = INVALID_HANDLE_VALUE;

	m_txOv.hEvent = m_rxOv.hEvent = INVALID_HANDLE_VALUE;
	m_txOv.Offset = m_rxOv.Offset = 0;
	m_txOv.OffsetHigh = m_rxOv.OffsetHigh = 0;

	m_bConnected = false;

	m_rxOv.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	m_txOv.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	m_hTxUpdateEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	assert(m_rxOv.hEvent);
	assert(m_txOv.hEvent);
	assert(m_hTxUpdateEvent);
}

CSerialPort::~CSerialPort()
{
	ClearQueue();
}

bool CSerialPort::OpenPort(const wchar_t *lpcstrPort, DCB *pDCB)
{
	if(m_hComm != INVALID_HANDLE_VALUE)
	{
		//port is apparently already openned, abort this operation
		TRACE(_T("OpenPort called with non INVALID_HANDLE_VALUE value for COM port handle\n"));
		return false;
	}

	ResetEvent(m_rxOv.hEvent);
	ResetEvent(m_txOv.hEvent);
	ResetEvent(m_hTxUpdateEvent);

	m_hComm = CreateFile(lpcstrPort,  
					GENERIC_READ | GENERIC_WRITE, 
					0, 
					0, 
					OPEN_EXISTING,
					FILE_FLAG_OVERLAPPED,
					0);
	
	if (m_hComm == INVALID_HANDLE_VALUE)
   	{
		// error opening port; abort
		
		OutputError("Error Opening COM port, ",GetLastError());
		return false;
	}
	else
	{
		TRACE(_T("Successfully opened port %s\n"),lpcstrPort);
	}

	// Set new state.
	if (!SetCommState(m_hComm, pDCB))
	{   
		 // Error in SetCommState. Possibly a problem with the communications 
		 // port handle or a problem with the DCB structure itself.	
		OutputError("Error Setting Commstate, ",GetLastError());
		PrivateClosePort();
		return false;
	}
	TRACE(_T("Successfully set Comstate\n"));

	//setup the comm mask for the notification event
	DWORD temp;
	GetCommMask(m_hComm,&temp);
	
	if(!SetCommMask(m_hComm,EV_RXCHAR))
	{
		OutputError("Error Setting CommMask, ",GetLastError());
	}

	TRACE(_T("Successfully set CommMask\n"));
	
	m_commtimeouts.ReadIntervalTimeout          = 200;
	m_commtimeouts.ReadTotalTimeoutMultiplier   = 300;
	m_commtimeouts.ReadTotalTimeoutConstant     = 16;
	m_commtimeouts.WriteTotalTimeoutMultiplier  = 0;
	m_commtimeouts.WriteTotalTimeoutConstant    = 0;

	if (!SetCommTimeouts(m_hComm, &m_commtimeouts))
	{
		TRACE(_T("Error Setting CommTimeouts.  GetLastError returned %d"),GetLastError());
		PrivateClosePort();
		return false;
	}
	TRACE(_T("Successfully set CommTimeouts\n"));
	TRACE(_T("Succesfully initialized port %s\n"),lpcstrPort);

	m_bConnected = true;
	if(!(m_rxThread = AfxBeginThread(CommThreadRxFunc, this)))
	{
		TRACE(_T("Unable to start helper rx thread\n"));
		ClosePort();
		//PrivateClosePort();
		return FALSE;
	}
	m_rxThread->m_bAutoDelete=false;
	TRACE(_T("Rx Thread started\n"));
#if 0
	if(!(m_txThread = AfxBeginThread(CommThreadTxFunc, this)))
	{
		TRACE(_T("Unable to start helper tx thread\n"));
		ClosePort();
		return FALSE;
	}
	m_txThread->m_bAutoDelete=false;
#endif
	TRACE(_T("Tx Thread started\n"));
	
	DWORD modemstatus;
	GetCommModemStatus(m_hComm, &modemstatus);
	TRACE(_T("ModemStatus value = %d\n"),modemstatus);
	TRACE(_T("CTS_ON = %d, DSR_ON = %d, RING_ON = %d, RLSD_ON = %d\n"),MS_CTS_ON, MS_DSR_ON, MS_RING_ON, MS_RLSD_ON);
	
		
	return true;
}

bool CSerialPort::WriteData(BYTE *data, DWORD datalen){
	DWORD dwError;
	COMSTAT comstat;

	if(!m_bConnected)
		return false;
#if 0
	BYTE *tempdata = (BYTE *)malloc(datalen);
	PCommdata temp = (PCommdata)malloc(sizeof(Commdata));
	memcpy(tempdata, data, datalen);
	temp->data = tempdata;
	temp->datalen = datalen;
	QueueData(temp);
	return true;
#endif
#if 0
	//set to 1 to force datasize to 32 bytes
	DWORD actualBytesWrote,requestedBytesWrote = 32;
	char tempData[32];
	int length=( datalen > 32) ? 32: datalen;
	memset(tempData,0,32);
	for(int i=0; i<length; i++)
		tempData[i]= data[i];
#else
	//original code
	DWORD actualBytesWrote,requestedBytesWrote = datalen;
	BYTE *tempData = new BYTE[datalen];
	memcpy(tempData,data,datalen);
#endif

	OVERLAPPED ovWrite;
	ovWrite.Offset = 0;
	ovWrite.OffsetHigh = 0;
	ovWrite.hEvent = CreateEvent(NULL,TRUE,FALSE, NULL);
	
	ClearCommError(m_hComm,&dwError,&comstat);
	
	TRACE(_T("Attempting to send command \"%s\"\n"),tempData);
	if(WriteFile(m_hComm,tempData, requestedBytesWrote,&actualBytesWrote,&ovWrite))
	{
		/***************************************************************************
		if for some reason the WriteFile call returns immediately, everyone's happy.  
		However, since we are using overlapped IO, this will most likely not happen
		***************************************************************************/
		
		if(actualBytesWrote == requestedBytesWrote)
		{
			TRACE(_T("String sent immediately by WriteFile\n"));
		}
		else if(actualBytesWrote > requestedBytesWrote)
		{
			TRACE(_T("Error: WriteFile returned but wrote more bytes than requested\n"));
		}
		else if(actualBytesWrote < requestedBytesWrote)
		{
			TRACE(_T("Error:WriteFile returned but wrote fewer bytes than requested\n"));
		}
	}
	else
	{
		switch(dwError = GetLastError())
		{
		case ERROR_IO_PENDING:
			TRACE(_T("Write queued\n"));
			break;
		default:
			OutputError("Error writing COM port, ",dwError);	
			TRACE(_T("Aborting write\n"));
			delete tempData;
			return false;
		}

		//wait for the write to complete
		WaitForSingleObject(ovWrite.hEvent, INFINITE);

		if(GetOverlappedResult(m_hComm,&ovWrite,&actualBytesWrote,TRUE))
		{
			if(actualBytesWrote == requestedBytesWrote)
			{
				TRACE(_T("Write completed\n"));
			}
			else if(actualBytesWrote > requestedBytesWrote)
			{
				TRACE(_T("Error: WriteFile returned but wrote more bytes than requested\n"));
			}
			else if(actualBytesWrote < requestedBytesWrote)
			{
				TRACE(_T("Error:WriteFile returned but wrote fewer bytes than requested\n"));
			}		
		}
		else
		{
			OutputError("GetOverlappedResult failed, ",GetLastError());
		}
	}
	delete tempData;
	return true;
}


void CSerialPort::QueueData(PCommdata data){
	//m_sendQueue.enqueue(data);
	SetEvent(m_hTxUpdateEvent);
}

void CSerialPort::ClearQueue(){
#if 0
	while(m_sendQueue.getLength() > 0){
		PCommdata temp = (PCommdata)m_sendQueue.dequeue();
		free(temp->data);
		free(temp);
	}
#endif
}

UINT CSerialPort::CommThreadTxFunc(LPVOID pParam){
	CSerialPort *pPort = (CSerialPort *)pParam;
	BYTE *buffer = NULL;
	DWORD actualBytesWrote, requestedBytesWrote;
	DWORD dwError, dwEvent;
	COMSTAT comstat;

	while(pPort->IsConnected()){
		//if(pPort->m_sendQueue.getLength() < 1)
		//	WaitForSingleObject(pPort->m_hTxUpdateEvent, INFINITE);
		ResetEvent(pPort->m_hTxUpdateEvent);
		if(!pPort->IsConnected())
			break;
		PCommdata temp; //(PCommdata)pPort->m_sendQueue.dequeue();
		buffer = temp->data;
		requestedBytesWrote = temp->datalen;
		free(temp);
		temp = NULL;
			
		ClearCommError(pPort->m_hComm,&dwError,&comstat);
		if(WriteFile(pPort->m_hComm, buffer, requestedBytesWrote, &actualBytesWrote,&(pPort->m_txOv))){
			/***************************************************************************
			if for some reason the WriteFile call returns immediately, everyone's happy.
			However, since we are using overlapped IO, this will most likely not happen
			***************************************************************************/
			if(actualBytesWrote == requestedBytesWrote){
				TRACE(_T("String sent immediately by WriteFile\n"));
				free(buffer);
				buffer = NULL;
			}
			else if(actualBytesWrote > requestedBytesWrote){
				TRACE(_T("Error: WriteFile returned but wrote more bytes than requested\n"));
				temp = (PCommdata)malloc(sizeof(Commdata));
				temp->data = buffer;
				temp->datalen = requestedBytesWrote;
				//pPort->m_sendQueue.push((void *)temp);
				buffer = NULL;
				temp = NULL;
			}
			else if(actualBytesWrote < requestedBytesWrote){
				TRACE(_T("Error:WriteFile returned but wrote fewer bytes than requested\n"));
				temp = (PCommdata)malloc(sizeof(Commdata));
				temp->data = buffer;
				temp->datalen = requestedBytesWrote;
				//pPort->m_sendQueue.push((void *)temp);
				buffer = NULL;
				temp = NULL;
			}
		}
		else{
			bool error = false;
			switch(dwError = GetLastError())
			{
			case ERROR_IO_PENDING:
				//TRACE("Write queued\n");
				break;
			default:
				OutputError("Error writing COM port, ",dwError);	
				TRACE(_T("Aborting write and disconnecting\n"));
				free(buffer);
				buffer = NULL;
				error = true;
				if(pPort->IsConnected())
					pPort->m_parent->PostMessage(WM_CLOSE_PORT);
			}
			if(error)break;


			//wait for the write to complete
			while((dwEvent = WaitForSingleObject(pPort->m_txOv.hEvent,200)) == WAIT_TIMEOUT)
				if(!pPort->IsConnected()){
					free(buffer);
					break;
				}
			
			switch(dwEvent){
			case WAIT_OBJECT_0:
				//our overlapped structure was signaled
				if(GetOverlappedResult(pPort->m_hComm,&(pPort->m_txOv),&actualBytesWrote,TRUE)){
					if(actualBytesWrote == requestedBytesWrote){
						//TRACE("Write completed\n");
						free(buffer);
						buffer = NULL;
					}
					else if(actualBytesWrote > requestedBytesWrote){
						TRACE(_T("Error: WriteFile returned but wrote more bytes than requested\n"));
						temp = (PCommdata)malloc(sizeof(Commdata));
						temp->data = buffer;
						temp->datalen = requestedBytesWrote;
						//pPort->m_sendQueue.push((void *)temp);
						buffer = NULL;
						temp = NULL;
					}
					else if(actualBytesWrote < requestedBytesWrote){
						TRACE(_T("Error:WriteFile returned but wrote fewer bytes than requested\n"));
						temp = (PCommdata)malloc(sizeof(Commdata));
						temp->data = buffer;
						temp->datalen = requestedBytesWrote;
						//pPort->m_sendQueue.push((void *)temp);
						buffer = NULL;
						temp = NULL;
					}
				}
				else{
					OutputError("GetOverlappedResult failed, ",GetLastError());
					temp = (PCommdata)malloc(sizeof(Commdata));
					temp->data = buffer;
					temp->datalen = requestedBytesWrote;
					//pPort->m_sendQueue.push((void *)temp);
					buffer = NULL;
					temp = NULL;
					buffer = NULL;
				}
				break;
			}
		}
	}
	TRACE(_T("Tx Thread Exiting...\n"));
	return true;
}

UINT CSerialPort::CommThreadRxFunc(LPVOID pParam)
{
	DWORD dwEvent,dwError, dwEventMask;
	CSerialPort *pPort = (CSerialPort *)pParam;

	OVERLAPPED overlapped;
	COMSTAT comstat;
	DWORD actualBytesRead,requestedBytesRead;
	unsigned char *buffer;

	overlapped.hEvent = CreateEvent(NULL,FALSE,FALSE,_T("WaitEvent"));
	/*************************************************************************
	Basic idea is to simply continously read from the serial port.  If there's
	nothing to read, the thread will simply go to sleep until any actual data
	exists
	*************************************************************************/

	while(pPort->IsConnected())
	{
		if(WaitCommEvent(pPort->m_hComm,&dwEventMask,&overlapped))
		{
			//we succeeded, don't do anything
		}
		else
		{
			if(WaitForSingleObject(overlapped.hEvent,200)!=WAIT_OBJECT_0)
			{
				continue;	
			}
			GetOverlappedResult(pPort->m_hComm,&overlapped,&requestedBytesRead,TRUE);

		}
		switch(dwEventMask)
		{	
		case EV_RXCHAR:
			break;
		default:
			continue;
			break;
		}
		ClearCommError(pPort->m_hComm,&dwError,&comstat);
		requestedBytesRead = comstat.cbInQue;//(comstat.cbInQue < 2) ? 2 : (comstat.cbInQue & 0xFFFFFFFE);
		buffer = new unsigned char[requestedBytesRead+1];
			
		if(ReadFile(pPort->m_hComm,buffer,requestedBytesRead,&actualBytesRead,&(pPort->m_rxOv)))
		{
			if(actualBytesRead == requestedBytesRead)
			{
				//TRACE("Received %d bytes immediately\n", actualBytesRead);
				//SendMessage(*pPort->m_parent,WM_RECEIVE_DATA, (WPARAM)actualBytesRead, (LPARAM)buffer);
				//pParent->OnReceiveData((WPARAM)actualBytesRead, (LPARAM)buffer);
				//TRACE("Tx...Buffer = %#X\tNumBytesReceived = %d\n",buffer,actualBytesRead);
				buffer[actualBytesRead] = '\0';
				pPort->m_parent->PostMessage(WM_RECEIVE_SERIAL_DATA, (WPARAM)actualBytesRead, (LPARAM)buffer);
			}
			else if(actualBytesRead > requestedBytesRead)
			{
				TRACE(_T("Error: ReadFile returned but read more bytes than requested\n"));
			}
			else if(actualBytesRead < requestedBytesRead)
			{
				TRACE(_T("Error: ReadFile returned but read fewer bytes than requested\n"));
			}
		}			
		else
		{
			switch(dwError = GetLastError())
			{
			case ERROR_IO_PENDING:
				break;
			default:
				OutputError("Error reading COM port, ",dwError);	
				TRACE(_T("Aborting read\n"));
				delete buffer;
				continue;
			}

			while((dwEvent = WaitForSingleObject(pPort->m_rxOv.hEvent,200)) == WAIT_TIMEOUT)
				if(!pPort->IsConnected())
					break;

			switch(dwEvent)
			{
			case WAIT_OBJECT_0:
				
				//our overlapped structure was signaled
				if(GetOverlappedResult(pPort->m_hComm,&pPort->m_rxOv,&actualBytesRead,TRUE))
				{
					if(actualBytesRead == requestedBytesRead)
					{
						//TRACE("Received %d bytes asynchronously\n", actualBytesRead);
						//SendMessage(*pPort->m_parent,WM_RECEIVE_DATA, (WPARAM)actualBytesRead, (LPARAM)buffer);		
						//pParent->OnReceiveData((WPARAM)actualBytesRead, (LPARAM)buffer);
						//TRACE("Tx...Buffer = %#X\tNumBytesReceived = %d\n",buffer,actualBytesRead);
						buffer[actualBytesRead] = '\0';
						pPort->m_parent->PostMessage(WM_RECEIVE_SERIAL_DATA, (WPARAM)actualBytesRead, (LPARAM)buffer);
					}
					else if(actualBytesRead > requestedBytesRead)
					{
						TRACE(_T("Error: Overlapped ReadFile returned but read more bytes than requested\n"));
					}
					else if(actualBytesRead < requestedBytesRead && actualBytesRead != 0)
					{
						TRACE(_T("Error: Overlapped ReadFile returned but read fewer bytes than requested\n"));
					}
				}
				else
				{
					OutputError("GetOverlappedResult failed, ",GetLastError());
				}	
				break;
			}
		}
		//delete[] buffer;
	}
	TRACE(_T("Thread Exiting...\n"));
	CloseHandle(pPort->m_hComm);
	pPort->m_hComm = INVALID_HANDLE_VALUE;
	return 1;
}

bool CSerialPort::IsConnected()
{
	return m_bConnected;
}

bool CSerialPort::ClosePort()
{
	if(IsConnected()){
		TRACE(_T("Requesting COM port closure\n"));
		m_bConnected = false;
		if(m_rxThread != NULL){
			WaitForSingleObject(m_rxThread->m_hThread,INFINITE);
			if(m_rxThread){
				delete m_rxThread;
				m_rxThread=NULL;
			}
		}
#if 0
		if(m_txThread != NULL){
			SetEvent(m_hTxUpdateEvent);
			WaitForSingleObject(m_txThread->m_hThread,INFINITE);
			if(m_txThread){
				delete m_txThread;
				m_txThread=NULL;
			}
		}
#endif
		CloseHandle(m_hComm);
		m_hComm = INVALID_HANDLE_VALUE;
	}
	ClearQueue();
	//((CIMoteTerminal *)m_parent)->DisplayChange();
	return true;
}



bool CSerialPort::IsRxThreadAlive()
{
	DWORD retVal;
	GetExitCodeThread(m_rxThread->m_hThread, &retVal);
	if(retVal!=STILL_ACTIVE)
	{
		if(m_rxThread)
		{
			delete m_rxThread;
			m_rxThread=NULL;
		}
		return false;
	}
	else return true;
}

bool CSerialPort::PrivateClosePort()
{
	bool retVal=true;
	TRACE(_T("Closing COM port\n"));
	CloseHandle(m_hComm);
	m_hComm = INVALID_HANDLE_VALUE;
	return retVal;
}

void CSerialPort::OutputError(char *string, DWORD error)
{
	LPVOID lpMsgBuf;

	FormatMessage( 
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM | 
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				error,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
				(LPTSTR) &lpMsgBuf,
				0,
				NULL 
			);

	TRACE(string);
	TRACE((char*)lpMsgBuf);
	LocalFree( lpMsgBuf );
	
}

void CSerialPort::SetParent(CWnd *parent)
{
	m_parent=parent;
}

void CSerialPort::CheckBuffer()
{
	COMSTAT comstat;
	DWORD dwError;
	ClearCommError(m_hComm,&dwError,&comstat);	

	DWORD temp;
	GetCommMask(m_hComm, &temp);
}

bool CSerialPort::SetBreak(bool On)
{
	bool bret;
	if(On)
	{
		bret = (bool)SetCommBreak(m_hComm);
	}
	else
	{
		bret = (bool)ClearCommBreak(m_hComm);	
	}
	if(bret)
	{
		TRACE(_T("Succeded: Set or clear break\r\n"));
	}
	else
	{
		TRACE(_T("Failed: Set or clear break\r\n"));
	}
	return bret;
}

--- NEW FILE: SerialPort.h ---
// SerialPort.h: interface for the CSerialPort class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_SERIALPORT_H__69D89F91_3784_41DB_8142_AE1A84BDC69B__INCLUDED_)
#define AFX_SERIALPORT_H__69D89F91_3784_41DB_8142_AE1A84BDC69B__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

typedef struct __Commdata{
	BYTE *data;
	DWORD datalen;
} Commdata;
typedef Commdata *PCommdata;

#define WM_RECEIVE_SERIAL_DATA (WM_USER + 1)
#define WM_RECEIVE_USB_DATA (WM_USER + 2)
#define WM_CLOSE_PORT (WM_USER + 3)
class CSerialPort  
{
public:
	void CheckBuffer(void);
	bool IsRxThreadAlive();
	bool ClosePort(void);
	bool IsConnected();
	bool WriteData(BYTE *sendString, DWORD datalen);
	bool OpenPort(const wchar_t *lpcstrPort, DCB *pDCB);
	CSerialPort();
	virtual ~CSerialPort();
	void SetParent(CWnd *parent);

protected:
	static	UINT CommThreadRxFunc(LPVOID pParam);
	static	UINT CommThreadTxFunc(LPVOID pParam);
	COMMTIMEOUTS m_commtimeouts;
	HANDLE m_hComm;
	
	OVERLAPPED m_rxOv, m_txOv;
	HANDLE m_hTxUpdateEvent;

private:
	bool PrivateClosePort(void);
	static void OutputError(char *string, DWORD error);
	bool m_bConnected;
	CWinThread *m_rxThread;
	//CWinThread *m_txThread;
	CWnd *m_parent;
	void QueueData(PCommdata data);
	void ClearQueue();
	//CDynQueue m_sendQueue;
public:
	bool SetBreak(bool On);
};

#endif // !defined(AFX_SERIALPORT_H__69D89F91_3784_41DB_8142_AE1A84BDC69B__INCLUDED_)

--- NEW FILE: SerialTerminal.aps ---


AFX_ID_PREVIEW_NUMPAGE
AFX_IDS_DELETED
AFX_IDP_E_OUTOFSTACKSPACE
EXT_SYMED_VALUE

















DS_ITALIC

#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE 9, 1
#pragma code_page(1252)
#include "res\SerialTerminal.rc2"  // non-Microsoft Visual C++ edited resources
#include "afxres.rc"         // Standard components
#include "afxprint.rc"       // printing/print preview resources
#include "afxolecl.rc"       // OLE container resources
#endif

÷÷÷÷÷÷÷÷÷÷÷÷÷÷ïšš  À®êÊËÌÜÝÞÎÏпËÌÌÇÒ¿§­÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷ïïïïïÀ®êàÊËõôÍÎÏÐõ
üüüüüüüûž´ÇÓÔÖרÚÊËÅ¿«¬üüüüüüüüüûû¡æÆçÓõøòçãø÷Å«­üüüüüüüüüüüüüæÆãçõ
!D?H31IT.-,%B;G1JKS.(
)*E9A011R.&#++E/4678:."&' NQWhX^XXXe	Šrpqƒt}~]mvށŒ†\ˆl{‹




















































--- NEW FILE: SerialTerminal.cpp ---
// SerialTerminal.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "SerialTerminal.h"
#include "MainFrm.h"

#include "SerialTerminalDoc.h"
#include "SerialTerminalView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CSerialTerminalApp

BEGIN_MESSAGE_MAP(CSerialTerminalApp, CWinApp)
	ON_COMMAND(ID_APP_ABOUT, &CSerialTerminalApp::OnAppAbout)
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
	// Standard print setup command
	ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()


// CSerialTerminalApp construction

CSerialTerminalApp::CSerialTerminalApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}


// The one and only CSerialTerminalApp object

CSerialTerminalApp theApp;


// CSerialTerminalApp initialization

BOOL CSerialTerminalApp::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	// Initialize OLE libraries
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}
	AfxEnableControlContainer();
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));
	LoadStdProfileSettings(4);  // Load standard INI file options (including MRU)
	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CSerialTerminalDoc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CSerialTerminalView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);


	// Enable DDE Execute open
	EnableShellOpen();
	RegisterShellFileTypes(TRUE);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);


	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// The one and only window has been initialized, so show and update it
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();
	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand
	// Enable drag/drop open
	m_pMainWnd->DragAcceptFiles();
	return TRUE;
}



// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

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

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()

// App command to run the dialog
void CSerialTerminalApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}


// CSerialTerminalApp message handlers


--- NEW FILE: SerialTerminal.h ---
// SerialTerminal.h : main header file for the SerialTerminal application
//
#pragma once

#ifndef __AFXWIN_H__
	#error "include 'stdafx.h' before including this file for PCH"
#endif

#include "resource.h"       // main symbols


// CSerialTerminalApp:
// See SerialTerminal.cpp for the implementation of this class
//

class CSerialTerminalApp : public CWinApp
{
public:
	CSerialTerminalApp();


// Overrides
public:
	virtual BOOL InitInstance();

// Implementation
	afx_msg void OnAppAbout();
	DECLARE_MESSAGE_MAP()
};

extern CSerialTerminalApp theApp;
--- NEW FILE: SerialTerminal.rc ---
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"

#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"

/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS

/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32

#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//

1 TEXTINCLUDE 
BEGIN
    "resource.h\0"
END

2 TEXTINCLUDE 
BEGIN
    "#include ""afxres.h""\r\n"
    "\0"
END

3 TEXTINCLUDE 
BEGIN
    "#define _AFX_NO_SPLITTER_RESOURCES\r\n"
    "#define _AFX_NO_OLE_RESOURCES\r\n"
    "#define _AFX_NO_TRACKER_RESOURCES\r\n"
    "#define _AFX_NO_PROPERTY_RESOURCES\r\n"
    "\r\n"
    "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n"
    "LANGUAGE 9, 1\r\n"
    "#pragma code_page(1252)\r\n"
    "#include ""res\\SerialTerminal.rc2""  // non-Microsoft Visual C++ edited resources\r\n"
    "#include ""afxres.rc""         // Standard components\r\n"
    "#include ""afxprint.rc""       // printing/print preview resources\r\n"
    "#include ""afxolecl.rc""       // OLE container resources\r\n"
    "#endif\r\n"
    "\0"
END

#endif    // APSTUDIO_INVOKED


/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDR_MAINFRAME           ICON                    "res\\SerialTerminal.ico"
IDR_SerialTerminalTYPE  ICON                    "res\\SerialTerminalDoc.ico"

/////////////////////////////////////////////////////////////////////////////
//
// Bitmap
//

IDR_MAINFRAME           BITMAP                  "res\\Toolbar.bmp"

/////////////////////////////////////////////////////////////////////////////
//
// Toolbar
//

IDR_MAINFRAME TOOLBAR  16, 15
BEGIN
    BUTTON      ID_FILE_NEW
    BUTTON      ID_FILE_OPEN
    BUTTON      ID_FILE_SAVE
    SEPARATOR
    BUTTON      ID_EDIT_CUT
    BUTTON      ID_EDIT_COPY
    BUTTON      ID_EDIT_PASTE
    SEPARATOR
    BUTTON      ID_FILE_PRINT
    BUTTON      ID_APP_ABOUT
END


/////////////////////////////////////////////////////////////////////////////
//
// Menu
//

IDR_MAINFRAME MENU 
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "&New\tCtrl+N",                ID_FILE_NEW
        MENUITEM "&Open...\tCtrl+O",            ID_FILE_OPEN
        MENUITEM "&Save\tCtrl+S",               ID_FILE_SAVE
        MENUITEM "Save &As...",                 ID_FILE_SAVE_AS
        MENUITEM SEPARATOR
        MENUITEM "&Print...\tCtrl+P",           ID_FILE_PRINT
        MENUITEM "Print Pre&view",              ID_FILE_PRINT_PREVIEW
        MENUITEM "P&rint Setup...",             ID_FILE_PRINT_SETUP
        MENUITEM SEPARATOR
        MENUITEM "Recent File",                 ID_FILE_MRU_FILE1, GRAYED
        MENUITEM SEPARATOR
        MENUITEM "E&xit",                       ID_APP_EXIT
    END
    POPUP "&Edit"
    BEGIN
        MENUITEM "&Undo\tCtrl+Z",               ID_EDIT_UNDO
        MENUITEM SEPARATOR
        MENUITEM "Cu&t\tCtrl+X",                ID_EDIT_CUT
        MENUITEM "&Copy\tCtrl+C",               ID_EDIT_COPY
        MENUITEM "&Paste\tCtrl+V",              ID_EDIT_PASTE
        MENUITEM "Paste &Special...",           ID_EDIT_PASTE_SPECIAL
        MENUITEM "Select A&ll\tCtrl+A",         ID_EDIT_SELECT_ALL
        MENUITEM SEPARATOR
        MENUITEM "&Find...\tCtrl+F",            ID_EDIT_FIND
        MENUITEM "F&ind Next\tF3",              ID_EDIT_REPEAT
        MENUITEM "R&eplace\tCtrl+H",            ID_EDIT_REPLACE
        MENUITEM SEPARATOR
        MENUITEM "Options",                     ID_EDIT_OPTIONS
    END
    POPUP "&View"
    BEGIN
        MENUITEM "&Toolbar",                    ID_VIEW_TOOLBAR
        MENUITEM "&Status Bar",                 ID_VIEW_STATUS_BAR
    END
    POPUP "&Help"
    BEGIN
        MENUITEM "&About SerialTerminal...",    ID_APP_ABOUT
    END
END

IDR_CNTR_INPLACE MENU 
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "&New\tCtrl+N",                ID_FILE_NEW
        MENUITEM "&Open...\tCtrl+O",            ID_FILE_OPEN
        MENUITEM "&Save\tCtrl+S",               ID_FILE_SAVE
        MENUITEM "Save &As...",                 ID_FILE_SAVE_AS
        MENUITEM SEPARATOR
        MENUITEM "&Print...\tCtrl+P",           ID_FILE_PRINT
        MENUITEM "Print Pre&view",              ID_FILE_PRINT_PREVIEW
        MENUITEM "P&rint Setup...",             ID_FILE_PRINT_SETUP
        MENUITEM SEPARATOR
        MENUITEM "Recent File",                 ID_FILE_MRU_FILE1, GRAYED
        MENUITEM SEPARATOR
        MENUITEM "E&xit",                       ID_APP_EXIT
    END
    MENUITEM SEPARATOR
    MENUITEM SEPARATOR
END


/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//

IDR_MAINFRAME ACCELERATORS 
BEGIN
    "N",            ID_FILE_NEW,            VIRTKEY, CONTROL
    "O",            ID_FILE_OPEN,           VIRTKEY, CONTROL
    "S",            ID_FILE_SAVE,           VIRTKEY, CONTROL
    "P",            ID_FILE_PRINT,          VIRTKEY, CONTROL
    "Z",            ID_EDIT_UNDO,           VIRTKEY, CONTROL
    "X",            ID_EDIT_CUT,            VIRTKEY, CONTROL
    "C",            ID_EDIT_COPY,           VIRTKEY, CONTROL
    "V",            ID_EDIT_PASTE,          VIRTKEY, CONTROL
    "A",            ID_EDIT_SELECT_ALL,     VIRTKEY, CONTROL
    "F",            ID_EDIT_FIND,           VIRTKEY, CONTROL
    VK_F3,          ID_EDIT_REPEAT,         VIRTKEY 
    "H",            ID_EDIT_REPLACE,        VIRTKEY, CONTROL
    VK_RETURN,      ID_OLE_EDIT_PROPERTIES, VIRTKEY, ALT, NOINVERT
    VK_BACK,        ID_EDIT_UNDO,           VIRTKEY, ALT
    VK_DELETE,      ID_EDIT_CUT,            VIRTKEY, SHIFT
    VK_INSERT,      ID_EDIT_COPY,           VIRTKEY, CONTROL
    VK_INSERT,      ID_EDIT_PASTE,          VIRTKEY, SHIFT
    VK_F6,          ID_NEXT_PANE,           VIRTKEY 
    VK_F6,          ID_PREV_PANE,           VIRTKEY, SHIFT
    VK_ESCAPE,      ID_CANCEL_EDIT_CNTR,    VIRTKEY, NOINVERT
END

IDR_CNTR_INPLACE ACCELERATORS 
BEGIN
    "N",            ID_FILE_NEW,            VIRTKEY, CONTROL
    "O",            ID_FILE_OPEN,           VIRTKEY, CONTROL
    "S",            ID_FILE_SAVE,           VIRTKEY, CONTROL
    "P",            ID_FILE_PRINT,          VIRTKEY, CONTROL
    VK_F6,          ID_NEXT_PANE,           VIRTKEY 
    VK_F6,          ID_PREV_PANE,           VIRTKEY, SHIFT
    VK_ESCAPE,      ID_CANCEL_EDIT_CNTR,    VIRTKEY, NOINVERT
END


/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//

IDD_ABOUTBOX DIALOGEX 0, 0, 235, 55
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About SerialTerminal"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
    ICON            IDR_MAINFRAME,IDC_STATIC,11,17,20,20
    LTEXT           "SerialTerminal Version 0.1",IDC_STATIC,40,10,119,8,SS_NOPREFIX
    LTEXT           "Copyright (C) 2007",IDC_STATIC,40,25,119,8
    DEFPUSHBUTTON   "OK",IDOK,178,7,50,16,WS_GROUP
END

IDD_PP_CONFIGURATION DIALOGEX 0, 0, 254, 209
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Configuration"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
    GROUPBOX        "COM Port Configuration",IDC_STATIC,14,17,120,40
    PUSHBUTTON      "Settings",IDC_BUTTON_SETTINGS,75,33,50,14
    COMBOBOX        IDC_COMBO_COMPORT,19,33,48,65,CBS_DROPDOWN | CBS_SORT | WS_VSCROLL | WS_TABSTOP
    EDITTEXT        IDC_EDIT_FILENAME,19,85,141,14,ES_AUTOHSCROLL
    GROUPBOX        "Logfile Configuration",IDC_STATIC,13,63,223,131
    PUSHBUTTON      "Browse",IDC_BUTTON_BROWSE,168,85,50,14
    LTEXT           "The following substitutions can be made:",IDC_STATIC,19,103,131,8
    LTEXT           "%D - Current Date",IDC_STATIC,19,113,62,8
    CONTROL         "Start Log Upon Connect",IDC_CHECK_AUTOSTART,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,19,179,93,10
    CONTROL         "Overwrite File",IDC_RADIO_OVERWRITE,"Button",BS_AUTORADIOBUTTON | WS_GROUP,19,164,61,10
    CONTROL         "Append To File",IDC_RADIO_APPEND,"Button",BS_AUTORADIOBUTTON,86,164,63,10
    GROUPBOX        "Filename",IDC_STATIC,15,75,209,72
    GROUPBOX        "Options",IDC_STATIC,16,152,208,40
END

IDD_MainDialogBar DIALOGEX 0, 0, 268, 16
STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
    PUSHBUTTON      "Connect",IDC_BUTTON_CONNECT,6,1,50,14
    CONTROL         "Display Timestamps",IDC_CHECK_TIMESTAMPING,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,186,3,75,10
    PUSHBUTTON      "StartLog",IDC_BUTTON_LOG,66,1,50,14
    PUSHBUTTON      "ClearView",IDC_BUTTON_CLEAR,126,1,50,14
END


/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,0,1
 PRODUCTVERSION 1,0,0,1
 FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
 FILEOS 0x4L
 FILETYPE 0x1L
 FILESUBTYPE 0x0L
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904e4"
        BEGIN
            VALUE "CompanyName", "TODO: <Company name>"
            VALUE "FileDescription", "TODO: <File description>"
            VALUE "FileVersion", "1.0.0.1"
            VALUE "InternalName", "SerialTerminal.exe"
            VALUE "LegalCopyright", "TODO: (c) <Company name>.  All rights reserved."
            VALUE "OriginalFilename", "SerialTerminal.exe"
            VALUE "ProductName", "TODO: <Product name>"
            VALUE "ProductVersion", "1.0.0.1"
        END
    END
    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END


/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//

#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO 
BEGIN
    IDD_ABOUTBOX, DIALOG
    BEGIN
        LEFTMARGIN, 7
        RIGHTMARGIN, 228
        TOPMARGIN, 7
        BOTTOMMARGIN, 48
    END

    IDD_PP_CONFIGURATION, DIALOG
    BEGIN
        LEFTMARGIN, 7
        RIGHTMARGIN, 247
        TOPMARGIN, 7
        BOTTOMMARGIN, 202
    END

    IDD_MainDialogBar, DIALOG
    BEGIN
        LEFTMARGIN, 7
        RIGHTMARGIN, 261
        TOPMARGIN, 7
        BOTTOMMARGIN, 15
    END
END
#endif    // APSTUDIO_INVOKED


/////////////////////////////////////////////////////////////////////////////
//
// String Table
//

STRINGTABLE 
BEGIN
    IDP_OLE_INIT_FAILED     "OLE initialization failed.  Make sure that the OLE libraries are the correct version."
    IDP_FAILED_TO_CREATE    "Failed to create object.  Make sure the object is entered in the system registry."
END

STRINGTABLE 
BEGIN
    IDR_MAINFRAME           "SerialTerminal\n\nSerialTerminal\nSerialTerminal Configuration Files (*.term)\n.term\nSerialTerminal.Document\nSerialTerminal.Document"
END

STRINGTABLE 
BEGIN
    AFX_IDS_APP_TITLE       "SerialTerminal"
    AFX_IDS_IDLEMESSAGE     "Ready"
END

STRINGTABLE 
BEGIN
    ID_INDICATOR_EXT        "EXT"
    ID_INDICATOR_CAPS       "CAP"
    ID_INDICATOR_NUM        "NUM"
    ID_INDICATOR_SCRL       "SCRL"
    ID_INDICATOR_OVR        "OVR"
    ID_INDICATOR_REC        "REC"
END

STRINGTABLE 
BEGIN
    ID_FILE_NEW             "Create a new document\nNew"
    ID_FILE_OPEN            "Open an existing document\nOpen"
    ID_FILE_CLOSE           "Close the active document\nClose"
    ID_FILE_SAVE            "Save the active document\nSave"
    ID_FILE_SAVE_AS         "Save the active document with a new name\nSave As"
    ID_FILE_PAGE_SETUP      "Change the printing options\nPage Setup"
    ID_FILE_PRINT_SETUP     "Change the printer and printing options\nPrint Setup"
    ID_FILE_PRINT           "Print the active document\nPrint"
    ID_FILE_PRINT_PREVIEW   "Display full pages\nPrint Preview"
END

STRINGTABLE 
BEGIN
    ID_APP_ABOUT            "Display program information, version number and copyright\nAbout"
    ID_APP_EXIT             "Quit the application; prompts to save documents\nExit"
END

STRINGTABLE 
BEGIN
    ID_FILE_MRU_FILE1       "Open this document"
    ID_FILE_MRU_FILE2       "Open this document"
    ID_FILE_MRU_FILE3       "Open this document"
    ID_FILE_MRU_FILE4       "Open this document"
    ID_FILE_MRU_FILE5       "Open this document"
    ID_FILE_MRU_FILE6       "Open this document"
    ID_FILE_MRU_FILE7       "Open this document"
    ID_FILE_MRU_FILE8       "Open this document"
    ID_FILE_MRU_FILE9       "Open this document"
    ID_FILE_MRU_FILE10      "Open this document"
    ID_FILE_MRU_FILE11      "Open this document"
    ID_FILE_MRU_FILE12      "Open this document"
    ID_FILE_MRU_FILE13      "Open this document"
    ID_FILE_MRU_FILE14      "Open this document"
    ID_FILE_MRU_FILE15      "Open this document"
    ID_FILE_MRU_FILE16      "Open this document"
END

STRINGTABLE 
BEGIN
    ID_NEXT_PANE            "Switch to the next window pane\nNext Pane"
    ID_PREV_PANE            "Switch back to the previous window pane\nPrevious Pane"
END

STRINGTABLE 
BEGIN
    ID_WINDOW_SPLIT         "Split the active window into panes\nSplit"
END

STRINGTABLE 
BEGIN
    ID_EDIT_CLEAR           "Erase the selection\nErase"
    ID_EDIT_CLEAR_ALL       "Erase everything\nErase All"
    ID_EDIT_COPY            "Copy the selection and put it on the Clipboard\nCopy"
    ID_EDIT_CUT             "Cut the selection and put it on the Clipboard\nCut"
    ID_EDIT_FIND            "Find the specified text\nFind"
    ID_EDIT_PASTE           "Insert Clipboard contents\nPaste"
    ID_EDIT_PASTE_LINK      "Insert Clipboard contents and a link to its source\nPaste Link"
    ID_EDIT_PASTE_SPECIAL   "Insert Clipboard contents with options\nPaste Special"
    ID_EDIT_REPEAT          "Repeat the last action\nRepeat"
    ID_EDIT_REPLACE         "Replace specific text with different text\nReplace"
    ID_EDIT_SELECT_ALL      "Select the entire document\nSelect All"
    ID_EDIT_UNDO            "Undo the last action\nUndo"
    ID_EDIT_REDO            "Redo the previously undone action\nRedo"
END

STRINGTABLE 
BEGIN
    ID_VIEW_TOOLBAR         "Show or hide the toolbar\nToggle ToolBar"
    ID_VIEW_STATUS_BAR      "Show or hide the status bar\nToggle StatusBar"
END

STRINGTABLE 
BEGIN
    ID_OLE_INSERT_NEW       "Insert new embedded object\nNew Object"
    ID_OLE_EDIT_LINKS       "Edit linked objects\nEdit Links"
    ID_OLE_EDIT_CONVERT     "Convert object to different type\nConvert Object"
END

STRINGTABLE 
BEGIN
    ID_OLE_VERB_FIRST       "Activate embedded or linked object"
    57873                   "Activate embedded or linked object"
    57874                   "Activate embedded or linked object"
    57875                   "Activate embedded or linked object"
END

STRINGTABLE 
BEGIN
    AFX_IDS_SCSIZE          "Change the window size"
    AFX_IDS_SCMOVE          "Change the window position"
    AFX_IDS_SCMINIMIZE      "Reduce the window to an icon"
    AFX_IDS_SCMAXIMIZE      "Enlarge the window to full size"
    AFX_IDS_SCNEXTWINDOW    "Switch to the next document window"
    AFX_IDS_SCPREVWINDOW    "Switch to the previous document window"
    AFX_IDS_SCCLOSE         "Close the active window and prompts to save the documents"
END

STRINGTABLE 
BEGIN
    AFX_IDS_SCRESTORE       "Restore the window to normal size"
    AFX_IDS_SCTASKLIST      "Activate Task List"
END

STRINGTABLE 
BEGIN
    AFX_IDS_PREVIEW_CLOSE   "Close print preview mode\nCancel Preview"
END

STRINGTABLE 
BEGIN
    IDS_Connect             "Connect To Selected Port"
    IDS_STRING1005          "Enable Timestamping of newlines"
    IDS_STRING1006          "Save incoming data to logfile"
END

#endif    // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////



#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE 9, 1
#pragma code_page(1252)
#include "res\SerialTerminal.rc2"  // non-Microsoft Visual C++ edited resources
#include "afxres.rc"         // Standard components
#include "afxprint.rc"       // printing/print preview resources
#include "afxolecl.rc"       // OLE container resources
#endif

/////////////////////////////////////////////////////////////////////////////
#endif    // not APSTUDIO_INVOKED


--- NEW FILE: SerialTerminal.reg ---
REGEDIT
; This .REG file may be used by your SETUP program.
;   If a SETUP program is not available, the entries below will be
;   registered in your InitInstance automatically with a call to
;   CWinApp::RegisterShellFileTypes and COleObjectFactory::UpdateRegistryAll.

HKEY_CLASSES_ROOT\.log = SerialTerminal.Document
HKEY_CLASSES_ROOT\SerialTerminal.Document\shell\open\command = SerialTerminal.EXE %1
HKEY_CLASSES_ROOT\SerialTerminal.Document\shell\open\ddeexec = [open("%1")]
HKEY_CLASSES_ROOT\SerialTerminal.Document\shell\open\ddeexec\application = SerialTerminal
    ; note: the application is optional
    ;  (it defaults to the app name in "command")

HKEY_CLASSES_ROOT\SerialTerminal.Document = SerialTerminal.Document


--- NEW FILE: SerialTerminal.vcproj ---
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
	ProjectType="Visual C++"
	Version="8.00"
	Name="SerialTerminal"
	ProjectGUID="{41C8FD84-92BF-4D9A-A21F-7DBA3615A653}"
	RootNamespace="SerialTerminal"
	Keyword="MFCProj"
	>
	<Platforms>
		<Platform
			Name="Win32"
		/>
	</Platforms>
	<ToolFiles>
	</ToolFiles>
	<Configurations>
		<Configuration
			Name="Debug|Win32"
			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
			IntermediateDirectory="$(ConfigurationName)"
			ConfigurationType="1"
			UseOfMFC="1"
			CharacterSet="1"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
				PreprocessorDefinitions="_DEBUG"
				MkTypLibCompatible="false"
				ValidateParameters="false"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				PreprocessorDefinitions="WIN32;_WINDOWS;_DEBUG"
				MinimalRebuild="true"
				BasicRuntimeChecks="3"
				RuntimeLibrary="1"
				UsePrecompiledHeader="2"
				WarningLevel="3"
				Detect64BitPortabilityProblems="true"
				DebugInformationFormat="4"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
				PreprocessorDefinitions="_DEBUG"
				Culture="1033"
				AdditionalIncludeDirectories="$(IntDir)"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				LinkIncremental="2"
				GenerateDebugInformation="true"
				SubSystem="2"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCWebDeploymentTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
			/>
		</Configuration>
		<Configuration
			Name="Release|Win32"
			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
			IntermediateDirectory="$(ConfigurationName)"
			ConfigurationType="1"
			UseOfMFC="2"
			CharacterSet="1"
			WholeProgramOptimization="1"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
				PreprocessorDefinitions="NDEBUG"
				MkTypLibCompatible="false"
				ValidateParameters="false"
			/>
			<Tool
				Name="VCCLCompilerTool"
				PreprocessorDefinitions="WIN32;_WINDOWS;NDEBUG"
				MinimalRebuild="false"
				RuntimeLibrary="2"
				UsePrecompiledHeader="2"
				WarningLevel="3"
				Detect64BitPortabilityProblems="true"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
				PreprocessorDefinitions="NDEBUG"
				Culture="1033"
				AdditionalIncludeDirectories="$(IntDir)"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				LinkIncremental="1"
				GenerateDebugInformation="true"
				SubSystem="2"
				OptimizeReferences="2"
				EnableCOMDATFolding="2"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCWebDeploymentTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
			/>
		</Configuration>
	</Configurations>
	<References>
	</References>
	<Files>
		<Filter
			Name="Source Files"
			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
			>
			<File
				RelativePath=".\ConfigurationPage.cpp"
				>
			</File>
			<File
				RelativePath=".\MainFrm.cpp"
				>
			</File>
			<File
				RelativePath=".\SerialPort.cpp"
				>
			</File>
			<File
				RelativePath=".\SerialTerminal.cpp"
				>
			</File>
			<File
				RelativePath=".\SerialTerminalDoc.cpp"
				>
			</File>
			<File
				RelativePath=".\SerialTerminalView.cpp"
				>
			</File>
			<File
				RelativePath=".\stdafx.cpp"
				>
				<FileConfiguration
					Name="Debug|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						UsePrecompiledHeader="1"
					/>
				</FileConfiguration>
				<FileConfiguration
					Name="Release|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						UsePrecompiledHeader="1"
					/>
				</FileConfiguration>
			</File>
		</Filter>
		<Filter
			Name="Header Files"
			Filter="h;hpp;hxx;hm;inl;inc;xsd"
			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
			>
			<File
				RelativePath=".\ConfigurationPage.h"
				>
			</File>
			<File
				RelativePath=".\MainFrm.h"
				>
			</File>
			<File
				RelativePath=".\Resource.h"
				>
			</File>
			<File
				RelativePath=".\SerialPort.h"
				>
			</File>
			<File
				RelativePath=".\SerialTerminal.h"
				>
			</File>
			<File
				RelativePath=".\SerialTerminalDoc.h"
				>
			</File>
			<File
				RelativePath=".\SerialTerminalView.h"
				>
			</File>
			<File
				RelativePath=".\stdafx.h"
				>
			</File>
		</Filter>
		<Filter
			Name="Resource Files"
			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
			>
			<File
				RelativePath=".\res\SerialTerminal.ico"
				>
			</File>
			<File
				RelativePath=".\SerialTerminal.rc"
				>
			</File>
			<File
				RelativePath=".\res\SerialTerminal.rc2"
				>
			</File>
			<File
				RelativePath=".\res\SerialTerminalDoc.ico"
				>
			</File>
			<File
				RelativePath=".\res\Toolbar.bmp"
				>
			</File>
		</Filter>
		<File
			RelativePath=".\ReadMe.txt"
			>
		</File>
		<File
			RelativePath=".\SerialTerminal.reg"
			>
		</File>
	</Files>
	<Globals>
		<Global
			Name="RESOURCE_FILE"
			Value="SerialTerminal.rc"
		/>
	</Globals>
</VisualStudioProject>

--- NEW FILE: SerialTerminalDoc.cpp ---
// SerialTerminalDoc.cpp : implementation of the CSerialTerminalDoc class
//

#include "stdafx.h"
#include "SerialTerminal.h"
#include "MainFrm.h"

#include "SerialTerminalDoc.h"
#include "SerialTerminalView.h"
#include "ConfigurationPage.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CSerialTerminalDoc

IMPLEMENT_DYNCREATE(CSerialTerminalDoc, CDocument)

BEGIN_MESSAGE_MAP(CSerialTerminalDoc, CDocument)
	ON_COMMAND(ID_EDIT_OPTIONS, &CSerialTerminalDoc::OnEditOptions)
	ON_BN_CLICKED(IDC_BUTTON_CONNECT, &CSerialTerminalDoc::OnBnClickedButtonConnect)
	ON_BN_CLICKED(IDC_BUTTON_LOG, &CSerialTerminalDoc::OnBnClickedButtonLog)
END_MESSAGE_MAP()


// CSerialTerminalDoc construction/destruction

CSerialTerminalDoc::CSerialTerminalDoc()
: m_strPortName(_T("")), m_strLogfileName(_T("logfile.log")), 
m_bAutoStart(true), m_bAppendLog(false), m_logging(false)
{
	// TODO: add one-time construction code here
	memset(&m_CommConfig,0,sizeof(COMMCONFIG));
	m_CommConfig.dwSize = sizeof(COMMCONFIG);
	m_CommConfig.dcb.DCBlength = sizeof(DCB);
	InsertNewLastLine();
}

CSerialTerminalDoc::~CSerialTerminalDoc()
{
}

BOOL CSerialTerminalDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)

	return TRUE;
}




// CSerialTerminalDoc serialization

void CSerialTerminalDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		ar.Write(&m_CommConfig,sizeof(COMMCONFIG));
		ar.Write(&m_bAppendLog,sizeof(m_bAppendLog));
		ar.Write(&m_bAutoStart,sizeof(m_bAutoStart));
		ar.WriteString(m_strLogfileName);
		ar.WriteString(_T("\n"));
		ar.WriteString(m_strPortName);
		ar.WriteString(_T("\n"));
	}
	else
	{
		ar.Read(&m_CommConfig, sizeof(COMMCONFIG));
		ar.Read(&m_bAppendLog,sizeof(m_bAppendLog));
		ar.Read(&m_bAutoStart,sizeof(m_bAutoStart));
		ar.ReadString(m_strLogfileName);
		ar.ReadString(m_strPortName);
	}
}


// CSerialTerminalDoc diagnostics

#ifdef _DEBUG
void CSerialTerminalDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CSerialTerminalDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG


// CSerialTerminalDoc commands

void CSerialTerminalDoc::OnEditOptions()
{
	CPropertySheet sheet(_T("Options"),AfxGetApp()->m_pMainWnd,0);
	
 	CConfigurationPage configPage(&m_CommConfig,m_strPortName, m_strLogfileName);
	configPage.m_bAutoStart = m_bAutoStart;
	configPage.m_bAppendLog = m_bAppendLog;
	
	sheet.AddPage(&configPage);
	
	if(sheet.DoModal() == IDOK)
	{
		//update the port info
		SetTitle(configPage.m_comportComboValue);
		m_strPortName = _T("\\\\.\\") + configPage.m_comportComboValue;
		m_bAutoStart = configPage.m_bAutoStart;
		m_strLogfileName = configPage.m_filename;
		m_bAppendLog = configPage.m_bAppendLog;
	}
}


void CSerialTerminalDoc::SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU)
{
	CDocument::SetPathName(lpszPathName, bAddToMRU);
	SetTitle(m_strPortName.Right(m_strPortName.GetLength() - 4));
}

void CSerialTerminalDoc::OnBnClickedButtonConnect()
{
	CMainFrame *pMainFrame= (CMainFrame *)AfxGetApp()->m_pMainWnd;
	CDialogBar *pDialogBar = &(pMainFrame->m_mainDialogBar);
	CButton *connectButton = (CButton *)pDialogBar->GetDlgItem(IDC_BUTTON_CONNECT);
	
	if(!m_port.IsConnected()){
		//port is not connected
		if(m_strPortName.IsEmpty()){
			//we haven't been configured yet
			OnEditOptions();
			if(m_strPortName.IsEmpty()){
				//user cancelled out of the config dialog box
				return;
			}
		}
		if(m_port.OpenPort(m_strPortName,&m_CommConfig.dcb)){
			POSITION pos = GetFirstViewPosition();
			CView* pView = GetNextView(pos);
			m_port.SetParent(pView);
			if(m_bAutoStart){
				OnBnClickedButtonLog();
			}
			if(m_bAppendLog==FALSE){
				ClearDocument();
			}
			UpdateAllViews(NULL);
			ScrollAllViews();
			connectButton->SetWindowTextW(_T("Disconnect"));
		}
		else{
			pMainFrame->MessageBox(_T("Unable to open Port.  Please check your settings"));
		}	
	}
	else{
		m_port.ClosePort();
		if(m_logging){
			OnBnClickedButtonLog();
		}
		connectButton->SetWindowTextW(_T("Connect"));		
	}
}

void CSerialTerminalDoc::OnBnClickedButtonLog()
{
	CMainFrame *pMainFrame= (CMainFrame *)AfxGetApp()->m_pMainWnd;
	CDialogBar *pDialogBar = &(pMainFrame->m_mainDialogBar);
	CButton *pButton = (CButton *)pDialogBar->GetDlgItem(IDC_BUTTON_LOG);
	
	CString text;
	pButton->GetWindowText(text);

	if(text == _T("StartLog")){
		CString filename = m_strLogfileName;
		if(filename.Find(_T("%D")) >= 0){
			CTime currentTime = CTime::GetCurrentTime();
			filename.Replace(_T("%D"),currentTime.Format("%m%d%Y"));
		}
		m_logging = logfile.Open(filename, CFile::modeCreate|(m_bAppendLog ? CFile::modeNoTruncate : 0) | CFile::modeWrite | CFile::shareDenyNone );
		if(m_logging){
			logfile.SeekToEnd();
			pButton->SetWindowText(_T("StopLog"));
		}
	}
	else{
		logfile.Close();
		m_logging = false;
		pButton->SetWindowText(_T("StartLog"));
	}
}

void CSerialTerminalDoc::ClearDocument(){
	POSITION pos = m_docData.GetTailPosition();
	while(pos != NULL){
		SDocData *currentItem = m_docData.GetPrev(pos);
		delete currentItem;
		m_docData.RemoveTail();
	}
}
void CSerialTerminalDoc::OnCloseDocument()
{
//make sure that the port is closed when we close the document
	if(!m_port.IsConnected()){
		m_port.ClosePort();
	}

	ClearDocument();	

	CDocument::OnCloseDocument();
}


int CSerialTerminalDoc::LogText(char *buffer, DWORD numBytes)
{
	if(m_logging){
		logfile.Write(buffer,numBytes);
	}
	return 0;
}

int CSerialTerminalDoc::LogText(CString &text)
{
	if(m_logging){
		logfile.WriteString(text);
		logfile.Flush();
	}
	return 0;
}

int CSerialTerminalDoc::AddChar(UINT nChar)
{
	BYTE *pData = new BYTE[1];
	pData[0] = nChar;
	m_port.WriteData(pData, 1);
	delete pData;
	return 1;
}

int CSerialTerminalDoc::ScrollAllViews(){

	POSITION pos = GetFirstViewPosition();
	CSerialTerminalView* pView;
	int count = (int)m_docData.GetCount();
	while (pos != NULL){
		pView = (CSerialTerminalView *)GetNextView( pos );
		pView->ScrollView(count);
	}   
	return count;
}


int CSerialTerminalDoc::AppendText(CString &text)
{
	int start=0, newlineLocation=0;
	CString currentline;

	//remove \r's from the buffer if they exist
 	text.Remove('\r');
	
	while( (newlineLocation = text.Find('\n',start)) != -1)
	{
		currentline = text.Mid(start,newlineLocation+1-start);
		AppendToLastLine(currentline);
		CommitLastLine();
		InsertNewLastLine();
		start = newlineLocation + 1;
	}
	
	if(start != text.GetLength()){
		currentline = text.Mid(start,text.GetLength()-start);
		AppendToLastLine(currentline);
	}
	return 0;
}

int CSerialTerminalDoc::InsertNewLastLine(void)
{
	//make sure that this line actually has a \n in it 
	SDocData *newDocData = new SDocData;
	newDocData->line = _T("");
	m_docData.AddTail(newDocData);
	ScrollAllViews();
	return 0;
}

int CSerialTerminalDoc::AppendToLastLine(CString &line)
{
	//make sure that this line actually has a \n in it 
	POSITION pos = m_docData.GetTailPosition();
	if(pos == NULL){
		//something was wrong and we didn't have a last line
		return 0;
	}
		
	SDocData *newDocData = m_docData.GetPrev(pos);

	if(newDocData->line == _T("")){
		CTime currentTime = CTime::GetCurrentTime();
		newDocData->timestamp = currentTime.Format("%c>> ");
	}
	for(int i=0; i< line.GetLength(); i++){
		switch(line[i]){
			case '\b':
				{
					int length = newDocData->line.GetLength();
					if(length > 0){
						newDocData->line.Delete(length-1,1);
					}
				}
				break;
			case 0x07:
				MessageBeep(-1);
				break;
			default:
				newDocData->line += line[i];
		}
	}
	UpdateAllViews(NULL);
	return 0;
}

int CSerialTerminalDoc::CommitLastLine()
{
	//make sure that this line actually has a \n in it 
	POSITION pos = m_docData.GetTailPosition();
	if(pos == NULL){
		//something was wrong and we didn't have a last line
		return 0;
	}
		
	SDocData *newDocData = m_docData.GetPrev(pos);
	LogText(newDocData->timestamp);
	LogText(newDocData->line);
	return 0;
}

--- NEW FILE: SerialTerminalDoc.h ---
// SerialTerminalDoc.h : interface of the CSerialTerminalDoc class
//
#include "SerialPort.h"
#include <fstream>
#include <afxtempl.h>
#pragma once

using namespace std;

struct SDocData
{
	CString timestamp;
	CString line;
};

class CSerialTerminalDoc : public CDocument
{

protected: // create from serialization only
	CSerialTerminalDoc();
	DECLARE_DYNCREATE(CSerialTerminalDoc)

// Attributes
public:

// Operations
public:

// Overrides
public:
	virtual BOOL OnNewDocument();
	virtual void Serialize(CArchive& ar);

// Implementation
public:
	virtual ~CSerialTerminalDoc();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

protected:

// Generated message map functions
protected:
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnEditOptions();
	CList<SDocData*,SDocData*> m_docData;
private:
	CString m_strPortName;
	CString m_strLogfileName;
	COMMCONFIG m_CommConfig;
	CSerialPort m_port;
	BOOL m_bAutoStart;
	BOOL m_bAppendLog;
	BOOL m_logging;
	CStdioFile logfile;
public:
//	virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
public:
	virtual void SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU = TRUE);
public:
	afx_msg void OnBnClickedButtonConnect();
public:
	afx_msg void OnBnClickedButtonLog();
public:
	void ClearDocument();
	virtual void OnCloseDocument();
public:
	int LogText(char *buffer, DWORD numBytes);
	int LogText(CString &text);
public:
	int AddChar(UINT nChar);
	int AppendText(CString &text);
	int InsertNewLastLine(void);
	int AppendToLastLine(CString &line);
	int CommitLastLine();
	int ScrollAllViews();
};



--- NEW FILE: SerialTerminalView.cpp ---
// SerialTerminalView.cpp : implementation of the CSerialTerminalView class
//

#include "stdafx.h"
#include "SerialTerminal.h"

#include "MainFrm.h"
#include "SerialTerminalDoc.h"
#include "SerialTerminalView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CSerialTerminalView

IMPLEMENT_DYNCREATE(CSerialTerminalView, CView)

BEGIN_MESSAGE_MAP(CSerialTerminalView, CView)
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
	ON_MESSAGE(WM_RECEIVE_SERIAL_DATA, &CSerialTerminalView::OnReceiveSerialData)
	ON_WM_CREATE()
	ON_WM_SIZE()
	ON_WM_TIMER()
//	ON_WM_CHAR()
ON_BN_CLICKED(IDC_BUTTON_CLEAR, &CSerialTerminalView::OnBnClickedButtonClear)
ON_WM_SETFOCUS()
ON_WM_VSCROLL()
ON_WM_CHAR()
ON_BN_CLICKED(IDC_CHECK_TIMESTAMPING, &CSerialTerminalView::OnBnClickedCheckTimestamping)
END_MESSAGE_MAP()

// CSerialTerminalView construction/destruction

CSerialTerminalView::CSerialTerminalView() : m_promptColor(RGB(0,200,0)) ,m_timestampColor(RGB(0,0,200)), m_displayTimestamps(1), m_promptStr(_T("BluSH"))
{
	// TODO: add construction code here
	m_font.CreatePointFont(80,_T("Courier New"));
}

CSerialTerminalView::~CSerialTerminalView()
{
}

BOOL CSerialTerminalView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CView::PreCreateWindow(cs);
}

// CSerialTerminalView drawing
void CSerialTerminalView::DrawLine(CDC* pDC, SDocData *lineInfo, int xpos, int ypos){
	
	int promptpos;
	if(m_displayTimestamps){
		xpos += DrawText(pDC, lineInfo->timestamp, &m_timestampColor, xpos, ypos);
	}
	
	promptpos= lineInfo->line.Find(m_promptStr);
	if(promptpos == -1){
		DrawText(pDC,lineInfo->line, NULL, xpos, ypos);
	}
	else{
		//have a prompt somewhere in the line
		//get what might be to the left
		CString temp;
		temp = lineInfo->line.Left(promptpos);
		xpos += DrawText(pDC,temp, NULL, xpos, ypos);
		temp = lineInfo->line.Mid(promptpos, m_promptStr.GetLength()+1);
		xpos += DrawText(pDC,temp, &m_promptColor, xpos, ypos);
		temp = lineInfo->line.Right(lineInfo->line.GetLength() - promptpos - m_promptStr.GetLength()-1);
		xpos += DrawText(pDC,temp, NULL, xpos, ypos);
	}
}


int CSerialTerminalView::DrawText(CDC* pDC, CString &text, COLORREF *pCR, int xpos, int ypos){
	COLORREF oldcr;
	CSize textExtent;

	if(pCR != NULL){
		oldcr = pDC->SetTextColor(*pCR);
	}
	pDC->TextOut(xpos, ypos, text);
	textExtent = pDC->GetTextExtent(text);
	if(pCR != NULL){
		pDC->SetTextColor(oldcr);
	}
	return textExtent.cx;
}

void CSerialTerminalView::OnDraw(CDC* pDC)
{
	CRect clientRect;
	int maxLines, lineHeight, i=0;
	TEXTMETRIC tm;
	
	CSerialTerminalDoc* pDoc = GetDocument();
	if (!pDoc){
		return;	
	}
	ASSERT_VALID(pDoc);
	
	
	GetClientRect(clientRect);
	pDC->GetTextMetrics(&tm);
	CFont *oldFont = pDC->SelectObject(&m_font);	
	
	lineHeight = tm.tmHeight + tm.tmExternalLeading;
	maxLines = clientRect.Height()/lineHeight;

	if(pDoc->m_docData.GetCount() > maxLines){
		//we have more data than we can paint...
		//start drawing from where the scroll bar says to

		SCROLLINFO si;
		GetScrollInfo(SB_VERT, &si, SIF_ALL);
		POSITION pos = pDoc->m_docData.GetTailPosition();
		for(i=0; i<si.nMax-si.nPos; i++){
			pDoc->m_docData.GetPrev(pos);
		}
		for(i=0; (i<maxLines) && (pos != NULL); i++){
			SDocData *currentItem = pDoc->m_docData.GetNext(pos);
			DrawLine(pDC, currentItem, 0, i*lineHeight);
		}
	}
	else{
		POSITION pos = pDoc->m_docData.GetHeadPosition();
		while(pos != NULL){
			SDocData *currentItem = pDoc->m_docData.GetNext(pos);
			DrawLine(pDC, currentItem, 0, i*lineHeight);
			i++;
		}
	}
	pDC->SelectObject(oldFont);
}


// CSerialTerminalView printing

BOOL CSerialTerminalView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CSerialTerminalView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CSerialTerminalView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}


// CSerialTerminalView diagnostics

#ifdef _DEBUG
void CSerialTerminalView::AssertValid() const
{
	CView::AssertValid();
}

void CSerialTerminalView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}

CSerialTerminalDoc* CSerialTerminalView::GetDocument() const // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSerialTerminalDoc)));
	return (CSerialTerminalDoc*)m_pDocument;
}
#endif //_DEBUG


// CSerialTerminalView message handlers

void CSerialTerminalView::OnInitialUpdate()
{
	CView::OnInitialUpdate();

	//we want to override the default font with something nice
	SetFont(&m_font);

	CMainFrame *pMainFrame= (CMainFrame *)AfxGetApp()->m_pMainWnd;
	CDialogBar *pDialogBar = &(pMainFrame->m_mainDialogBar);
	CButton *checkBox = (CButton *)pDialogBar->GetDlgItem(IDC_CHECK_TIMESTAMPING);

	checkBox->SetCheck(BST_CHECKED);

//	SetTimer(100, 1000, NULL);
	EnableScrollBarCtrl(SB_VERT);

	SCROLLINFO si;
	si.cbSize = sizeof(si);
	si.fMask  = SIF_PAGE | SIF_RANGE | SIF_POS | SIF_DISABLENOSCROLL;
	si.nPage = 0;
	si.nMin = 0;
	si.nMax = 0;
	si.nPos = 0;
	SetScrollInfo(SB_VERT,&si, TRUE);
}

int CSerialTerminalView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CView::OnCreate(lpCreateStruct) == -1)
		return -1;

	CRect rect;
	GetClientRect(rect);
	TRACE("Initial size of the Edit Ctrl is %d %d %d %d\n",rect.top, rect.left, rect.bottom, rect.right);

	return 0;
}

void CSerialTerminalView::OnSize(UINT nType, int cx, int cy)
{
	CView::OnSize(nType, cx, cy);
	CRect rect;
	CClientDC dc(this);
	int maxLines;
	TEXTMETRIC tm;
	SCROLLINFO si;

	CSerialTerminalDoc* pDoc = GetDocument();
	if (!pDoc){
		return;	
	}
	ASSERT_VALID(pDoc);



	//get the total size of our client area
	GetClientRect(rect);
	//get our textmetrics so that we can figure out the total lines
	dc.GetTextMetrics(&tm);
	maxLines = rect.Height()/(tm.tmHeight + tm.tmExternalLeading);

	if(pDoc->m_docData.GetSize() > maxLines){
		EnableScrollBarCtrl(SB_VERT, TRUE);
		si.fMask  = SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
		si.nMin = 0;
		si.nMax = (int)pDoc->m_docData.GetSize()-1;
		si.nPos = (int)pDoc->m_docData.GetSize()-1;
		SetScrollInfo(SB_VERT,&si, TRUE);
	}
	else{
		EnableScrollBarCtrl(SB_VERT, FALSE);
	}

	si.cbSize = sizeof(si);
	si.fMask  = SIF_PAGE | SIF_DISABLENOSCROLL;
	si.nPage = maxLines;
	SetScrollInfo(SB_VERT,&si, TRUE);


	TRACE("Window Resized to %d %d %d %d\n",rect.top, rect.left, rect.bottom, rect.right);
	//m_TerminalEditCtrl.SetWindowPos(&CWnd::wndTop,rect.left,rect.top,rect.Width(),rect.Height(), SWP_SHOWWINDOW);
	//m_TerminalEditCtrl.SetFocus();
}

afx_msg LRESULT CSerialTerminalView::OnReceiveSerialData(WPARAM numBytes, LPARAM pBuffer)
{
	
	//CMainFrame *pMainFrame= (CMainFrame *)AfxGetApp()->m_pMainWnd;
	//CDialogBar *pDialogBar = &(pMainFrame->m_mainDialogBar);
	//CButton *checkBox = (CButton *)pDialogBar->GetDlgItem(IDC_CHECK_TIMESTAMPING);
	DWORD length = (DWORD)numBytes;
	char *buffer = (char *)pBuffer;
	
	CString text(buffer);
 	
	//remove \r's from the buffer if they exist
 	text.Remove('\r');
	
//	GetDocument()->AppendText(text, checkBox->GetCheck() == BST_CHECKED);
	GetDocument()->AppendText(text);
	
	delete buffer;
	return 1;
}

void CSerialTerminalView::ScrollView(int TotalLinesInDoc){
	CClientDC dc(this);
	CRect clientRect;
	int maxLines;
	TEXTMETRIC tm;
	SCROLLINFO si;
	
	//get the total size of our client area
	GetClientRect(clientRect);
	dc.GetTextMetrics(&tm);
	maxLines = clientRect.Height()/(tm.tmHeight + tm.tmExternalLeading);


	if(TotalLinesInDoc > maxLines){
		EnableScrollBarCtrl(SB_VERT, TRUE);
		si.cbSize = sizeof(si);
		si.fMask  = SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
		si.nMin = 0;
		si.nMax = TotalLinesInDoc-1;
		si.nPos = TotalLinesInDoc-1;
		SetScrollInfo(SB_VERT,&si, TRUE);
	}
	else{
		EnableScrollBarCtrl(SB_VERT, FALSE);
	}
}


void CSerialTerminalView::OnTimer(UINT_PTR nIDEvent)
{
#if 1
	static int count = 0;
	
	WORD actualBytesRead = 500;
	char *buffer = new char[actualBytesRead];
    
    sprintf_s(buffer, actualBytesRead,"Total space allocated from system = \t%10u\r\nNumber of non-inuse chunks = \t\t%10u\r\nNumber of MMAPPED regions = \t\t%10u\r\nTotal space in MMAPPED regions = \t%10u\r\n",1234,5678, 91011,1234);
	
	actualBytesRead = strlen(buffer);

	this->PostMessage(WM_RECEIVE_SERIAL_DATA, (WPARAM)actualBytesRead, (LPARAM)buffer);
	CView::OnTimer(nIDEvent);

	count++;
	if(count > 10){
//		KillTimer(nIDEvent);
	}
#else
	//hack
	OnBnClickedButtonClear();
#endif
}


void CSerialTerminalView::OnBnClickedButtonClear()
{
#if 0
	m_TerminalEditCtrl.SetSel(0, -1);
	m_TerminalEditCtrl.Clear();
	m_TerminalEditCtrl.SetSel(0,-1);
	CHARFORMAT cf;
	cf.cbSize = sizeof(CHARFORMAT);
	cf.crTextColor = RGB(0,0,0);
	cf.dwMask = CFM_COLOR;
	cf.dwEffects = 0;
	m_TerminalEditCtrl.SetSelectionCharFormat(cf);
	m_TerminalEditCtrl.SetSel(-1,-1);
#endif
}

void CSerialTerminalView::OnSetFocus(CWnd* pOldWnd)
{
	//CView::OnSetFocus(pOldWnd);

	//m_TerminalEditCtrl.SetFocus();
}

void CSerialTerminalView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
	// TODO: Add your message handler code here and/or call default
	SCROLLINFO si;
	GetScrollInfo(SB_VERT, &si, SIF_ALL);
	switch(nSBCode){
		case SB_BOTTOM:
			SetScrollPos(SB_VERT,si.nMax);
			break;
		case SB_LINEDOWN:
			SetScrollPos(SB_VERT,si.nPos+1);	
			break;
		case SB_LINEUP:
			SetScrollPos(SB_VERT,si.nPos-1);
			break;
		case SB_PAGEDOWN:
			SetScrollPos(SB_VERT,si.nPos+si.nPage);
			break;
		case SB_PAGEUP:
			SetScrollPos(SB_VERT,si.nPos-si.nPage);
			break;
		case SB_THUMBPOSITION:
			SetScrollPos(SB_VERT,nPos);
			break;
		case SB_THUMBTRACK:
			SetScrollPos(SB_VERT,nPos);
			break;
		case SB_TOP:
			SetScrollPos(SB_VERT,0);
			break;
		default:
			//unknown code
			return;
	}
	Invalidate();
	return;
}

void CSerialTerminalView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	CSerialTerminalDoc *pDoc = GetDocument();
	if(pDoc == NULL){
		return;
	}
	ASSERT_VALID(pDoc);

	TRACE("OnChar %d %d %d\n",nChar, nRepCnt, nFlags);
	switch(nChar){
		case VK_RETURN:
			pDoc->AddChar('\r');
		break;
		case VK_BACK:
			pDoc->AddChar('\b');
		break;
		default:
			pDoc->AddChar(nChar);
	}
}

void CSerialTerminalView::OnBnClickedCheckTimestamping()
{
	CMainFrame *pMainFrame= (CMainFrame *)AfxGetApp()->m_pMainWnd;
	CDialogBar *pDialogBar = &(pMainFrame->m_mainDialogBar);
	CButton *checkBox = (CButton *)pDialogBar->GetDlgItem(IDC_CHECK_TIMESTAMPING);
	m_displayTimestamps = checkBox->GetCheck();
	Invalidate();
}

--- NEW FILE: SerialTerminalView.h ---
// SerialTerminalView.h : interface of the CSerialTerminalView class
//


#pragma once
#include "afxwin.h"

class CSerialTerminalView : public CView
{
protected: // create from serialization only
	CSerialTerminalView();
	DECLARE_DYNCREATE(CSerialTerminalView)

// Attributes
public:
	CSerialTerminalDoc* GetDocument() const;

// Operations
public:

// Overrides
public:
	void ScrollView(int TotalLinesInDoc);
	virtual void OnDraw(CDC* pDC);  // overridden to draw this view
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
	virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
	virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
	virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
	afx_msg LRESULT OnReceiveSerialData(WPARAM numBytes, LPARAM pBuffer);
	int DrawText(CDC* pDC, CString &text, COLORREF *pCR, int xpos, int ypos);
	void DrawLine(CDC* pDC, SDocData *lineInfo, int xpos, int ypos);

// Implementation
public:
	virtual ~CSerialTerminalView();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

protected:
	COLORREF m_timestampColor;
	COLORREF m_promptColor;
	CFont m_font;
	BOOL m_displayTimestamps;
	CString m_promptStr;
// Generated message map functions
protected:
	DECLARE_MESSAGE_MAP()
public:
public:
	virtual void OnInitialUpdate();
public:
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
public:
	afx_msg void OnSize(UINT nType, int cx, int cy);
public:
	afx_msg void OnTimer(UINT_PTR nIDEvent);
public:
//	afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
	afx_msg void OnBnClickedButtonClear();
	afx_msg void OnSetFocus(CWnd* pOldWnd);
	afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
public:
	afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
public:
	afx_msg void OnBnClickedCheckTimestamping();
};

#ifndef _DEBUG  // debug version in SerialTerminalView.cpp
inline CSerialTerminalDoc* CSerialTerminalView::GetDocument() const
   { return reinterpret_cast<CSerialTerminalDoc*>(m_pDocument); }
#endif


--- NEW FILE: stdafx.cpp ---
// stdafx.cpp : source file that includes just the standard includes
// SerialTerminal.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"



--- NEW FILE: stdafx.h ---
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently

#pragma once

#ifndef _SECURE_ATL
#define _SECURE_ATL 1
#endif

#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN		// Exclude rarely-used stuff from Windows headers
#endif

// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER				// Allow use of features specific to Windows XP or later.
#define WINVER 0x0501		// Change this to the appropriate value to target other versions of Windows.
#endif

#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.                   
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif						

#ifndef _WIN32_WINDOWS		// Allow use of features specific to Windows 98 or later.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif

#ifndef _WIN32_IE			// Allow use of features specific to IE 6.0 or later.
#define _WIN32_IE 0x0600	// Change this to the appropriate value to target other versions of IE.
#endif

#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS	// some CString constructors will be explicit

// turns off MFC's hiding of some common and often safely ignored warning messages
#define _AFX_ALL_WARNINGS

#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions


#include <afxdisp.h>        // MFC Automation classes



#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h>		// MFC support for Internet Explorer 4 Common Controls
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>			// MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxdlgs.h>









#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif





More information about the Tinyos-contrib-commits mailing list