// ModemCmdDlg.cpp
//

#include "stdafx.h"
#include "ModemCmd.h"
#include "ModemCmdDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CModemCmdDlg Dialog

CModemCmdDlg::CModemCmdDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CModemCmdDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CModemCmdDlg)
	//}}AFX_DATA_INIT
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CModemCmdDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CModemCmdDlg)
	DDX_Control(pDX, IDC_COMBO_FLOW_CTRL, m_FlowCtrl);
	DDX_Control(pDX, IDC_EDIT_RET, m_Ret);
	DDX_Control(pDX, IDC_EDIT_PARAM, m_Param);
	DDX_Control(pDX, IDC_COMBO_STOP_BIT, m_StopBit);
	DDX_Control(pDX, IDC_COMBO_PORT, m_Port);
	DDX_Control(pDX, IDC_COMBO_PARITY, m_Parity);
	DDX_Control(pDX, IDC_COMBO_DATA_BIT, m_DataBit);
	DDX_Control(pDX, IDC_COMBO_COMMAND, m_Command);
	DDX_Control(pDX, IDC_COMBO_BAUDRATE, m_Baudrate);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CModemCmdDlg, CDialog)
	//{{AFX_MSG_MAP(CModemCmdDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_OPEN, OnButtonOpen)
	ON_BN_CLICKED(IDC_BUTTON_SETTING, OnButtonSetting)
	ON_BN_CLICKED(IDC_BUTTON_CLOSE, OnButtonClose)
	ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)
	ON_BN_CLICKED(IDC_BUTTON_END, OnButtonEnd)
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CModemCmdDlg Message Handler
void CModemCmdDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this);

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

HCURSOR CModemCmdDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

//===========================================================
// Globals
//===========================================================
HANDLE	hComm;		// COM Port Handle

//===========================================================
// Initialize Dialog
//===========================================================
typedef struct {
	char	Str[50];
	DWORD	Num;
} STR_NUM;

// Baudrate
STR_NUM	snBaudrate[] = {
	{	"300",		300		},
	{	"600",		600		},
	{	"1200",		1200	},
	{	"2400",		2400	},
	{	"4800",		4800	},
	{	"9600",		9600	},
	{	"14400",	14400	},
	{	"19200",	19200	},
	{	"38400",	38400	},
	{	"57600",	57600	},
	{	"115200",	115200	},
	{	"230400",	230400	},
	{	"460800",	460800	},
	{	"921600",	921600	},
	{	"End",		0		}
};

// Data Bit
STR_NUM	snDataBit[] = {
	{	"7",		7		},
	{	"8",		8		},
	{	"End",		0		}
};

// Parity
STR_NUM	snParity[] = {
	{	"NONE",		NOPARITY	},
	{	"EVEN",		EVENPARITY	},
	{	"ODD",		ODDPARITY	},
	{	"End",		0			}
};

// Stop Bit
STR_NUM	snStopBit[] = {
	{	"1",		ONESTOPBIT	},
	{	"2",		TWOSTOPBITS	},
	{	"End",		0			}
};

// Flow Control
#define	FLOW_NONE	0
#define	FLOW_HW		1
#define	FLOW_XON	2

STR_NUM	snFlowCtrl[] = {
	{	"NONE",		FLOW_NONE	},
	{	"Hardware",	FLOW_HW		},
	{	"XON/XOFF",	FLOW_XON	},
	{	"End",		0			}
};

// Command
STR_NUM	snCommand[] = {
	{	"@RAR",		0	},
	{	"@CAB",		0	},
	{	"@RBS",		0	},
	{	"@INI",		0	},
	{	"@RSD",		0	},
	{	"@RSE",		0	},
	{	"@CRB",		0	},
	{	"@RRG",		0	},
	{	"@RST",		0	},
	{	"@CTB",		0	},
	{	"@VER",		0	},
	{	"@PIG",		0	},
	{	"@ECO",		0	},
	{	"@SAV",		0	},
	{	"@RES",		0	},
	{	"@RRT",		0	},
	{	"End",		0	}
};

BOOL CModemCmdDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	SetIcon(m_hIcon, TRUE);
	SetIcon(m_hIcon, FALSE);
	//-----------------------------------------------
	// Initialize Combo Box
	//-----------------------------------------------
	int		i;
	char	szText[100];
	// Port
	for (i=1; i<100; i++) {
		wsprintf(szText, "COM%d", i);
		m_Port.AddString(szText);
	}
	m_Port.SelectString(-1, "COM1");
	// Baudrate
	for (i=0; lstrcmp(snBaudrate[i].Str, "End") != 0; i++) {
		m_Baudrate.AddString(snBaudrate[i].Str);
	}
	m_Baudrate.SelectString(-1, "9600");
	// Data Bit
	for (i=0; lstrcmp(snDataBit[i].Str, "End") != 0; i++) {
		m_DataBit.AddString(snDataBit[i].Str);
	}
	m_DataBit.SelectString(-1, "8");
	// Parity
	for (i=0; lstrcmp(snParity[i].Str, "End") != 0; i++) {
		m_Parity.AddString(snParity[i].Str);
	}
	m_Parity.SelectString(-1, "NONE");
	// Stop Bit
	for (i=0; lstrcmp(snStopBit[i].Str, "End") != 0; i++) {
		m_StopBit.AddString(snStopBit[i].Str);
	}
	m_StopBit.SelectString(-1, "1");
	// Command
	for (i=0; lstrcmp(snCommand[i].Str, "End") != 0; i++) {
		m_Command.AddString(snCommand[i].Str);
	}
	m_Command.SelectString(-1, "@RAR");
	// Flow Control
	for (i=0; lstrcmp(snFlowCtrl[i].Str, "End") != 0; i++) {
		m_FlowCtrl.AddString(snFlowCtrl[i].Str);
	}
	m_FlowCtrl.SelectString(-1, "NONE");
	return TRUE;
}

//===========================================================
// Open
//===========================================================
void CModemCmdDlg::OnButtonOpen() 
{
	char	szCommPort[100];
	char	szText[100];
	DWORD	dwError;
	//-----------------------------------------------
	// Create COM port name
	//-----------------------------------------------
	m_Port.GetWindowText(szText, sizeof(szText));
	wsprintf(szCommPort, "\\\\.\\%s", szText);
	//-----------------------------------------------
	// Open
	//-----------------------------------------------
	hComm = CreateFile(
				szCommPort,
				GENERIC_READ | GENERIC_WRITE,
				0,
				NULL,
				OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL,
				NULL);
	//-----------------------------------------------
	// Error check
	//-----------------------------------------------
	if (hComm == INVALID_HANDLE_VALUE) {
		dwError = GetLastError();
		wsprintf(szText, "CreateFile:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("CreateFile:Success");
}

//===========================================================
// Close
//===========================================================
void CModemCmdDlg::OnButtonClose() 
{
	BOOL	bRet;
	char	szText[100];
	DWORD	dwError;
	//-----------------------------------------------
	// Close
	//-----------------------------------------------
	KillTimer(1);
	bRet = CloseHandle(hComm);
	//-----------------------------------------------
	// Error check
	//-----------------------------------------------
	if (bRet == FALSE) {
		dwError = GetLastError();
		wsprintf(szText, "CloseHandle:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("CloseHandle:Success");
}

//===========================================================
// Setting
//===========================================================
void CModemCmdDlg::OnButtonSetting() 
{
	DWORD	dwBaudrate;
	BYTE	bDataBit;
	BYTE	bParity;
	BYTE	bStopBit;
	DWORD	dwFlowCtrl;
	COMMTIMEOUTS	CommTimeOuts;
	DCB		dcb;
	char	szText[100];
	BOOL	bRet;
	int		i;
	DWORD	dwError;
	//-----------------------------------------------
	// Get data from display
	//-----------------------------------------------
	// Baudrate
	m_Baudrate.GetWindowText(szText, sizeof(szText));
	dwBaudrate = 9600;
	for (i=0; lstrcmp(snBaudrate[i].Str, "End") != 0; i++) {
		if (lstrcmp(snBaudrate[i].Str, szText) == 0) {
			dwBaudrate = snBaudrate[i].Num;
			break;
		}
	}
	// Data Bit
	m_DataBit.GetWindowText(szText, sizeof(szText));
	bDataBit = 8;
	for (i=0; lstrcmp(snDataBit[i].Str, "End") != 0; i++) {
		if (lstrcmp(snDataBit[i].Str, szText) == 0) {
			bDataBit = (BYTE)snDataBit[i].Num;
			break;
		}
	}
	// Parity
	m_Parity.GetWindowText(szText, sizeof(szText));
	bParity = NOPARITY;
	for (i=0; lstrcmp(snParity[i].Str, "End") != 0; i++) {
		if (lstrcmp(snParity[i].Str, szText) == 0) {
			bParity = (BYTE)snParity[i].Num;
			break;
		}
	}
	// Stop bit
	m_StopBit.GetWindowText(szText, sizeof(szText));
	bStopBit = ONESTOPBIT;
	for (i=0; lstrcmp(snStopBit[i].Str, "End") != 0; i++) {
		if (lstrcmp(snStopBit[i].Str, szText) == 0) {
			bStopBit = (BYTE)snStopBit[i].Num;
			break;
		}
	}
	// Flow Control
	m_FlowCtrl.GetWindowText(szText, sizeof(szText));
	dwFlowCtrl = FLOW_NONE;
	for (i=0; lstrcmp(snFlowCtrl[i].Str, "End") != 0; i++) {
		if (lstrcmp(snFlowCtrl[i].Str, szText) == 0) {
			dwFlowCtrl = snFlowCtrl[i].Num;
			break;
		}
	}
	//-----------------------------------------------
	// Clear Tx Rx data buffer
	//-----------------------------------------------
	PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT |
					 PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
	//-----------------------------------------------
	// Set timeout
	//-----------------------------------------------
	CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 5000;
	CommTimeOuts.WriteTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.WriteTotalTimeoutConstant = 5000;
	SetCommTimeouts(hComm, &CommTimeOuts ) ;
	//-----------------------------------------------
	// Get DCB
	//-----------------------------------------------
	dcb.DCBlength = sizeof( DCB ) ;
	GetCommState(hComm, &dcb ) ;
	//-----------------------------------------
	// Set DCB
	//-----------------------------------------
	dcb.BaudRate = dwBaudrate;
	dcb.ByteSize = bDataBit;
	dcb.Parity = bParity;
	dcb.StopBits = bStopBit;
	switch (dwFlowCtrl) {
	case FLOW_NONE:
		dcb.fOutxCtsFlow = FALSE;
		dcb.fOutX = FALSE;
		dcb.fInX = FALSE;
		dcb.fRtsControl = RTS_CONTROL_ENABLE;
		break;
	case FLOW_HW:
		dcb.fOutxCtsFlow = TRUE;
		dcb.fOutX = FALSE;
		dcb.fInX = FALSE;
		dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
		break;
	case FLOW_XON:
		dcb.fOutxCtsFlow = FALSE;
		dcb.fOutX = TRUE;
		dcb.fInX = TRUE;
		dcb.fRtsControl = RTS_CONTROL_ENABLE;
		break;
	}

	dcb.fOutxDsrFlow = FALSE;
	dcb.fDtrControl = DTR_CONTROL_ENABLE;

	dcb.fBinary = TRUE;
	dcb.fParity = TRUE;

	bRet = SetCommState(hComm, &dcb);
	//-----------------------------------------
	// Error check
	//-----------------------------------------
	if (bRet == FALSE ) {
		dwError = GetLastError();
		wsprintf(szText, "SetCommState:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("SetCommState:Success");
}

//===========================================================
// Send
//===========================================================
void CModemCmdDlg::OnButtonSend() 
{
	char	szWriteData[4000];
	BOOL	bRet;
	DWORD	dwBytesWritten;
	DWORD	nWriteLength;
	DWORD	dwError;
	char	szText[1000];
	//-----------------------------------------------
	// Get data from display
	//-----------------------------------------------
	m_Command.GetWindowText(szWriteData, sizeof(szWriteData));
	m_Param.GetWindowText(szText, sizeof(szText));
	lstrcat(szWriteData, szText);
	lstrcat(szWriteData, "\r");
	nWriteLength = lstrlen(szWriteData);
	//-----------------------------------------------
	// Send
	//-----------------------------------------------
	bRet = WriteFile(hComm, (LPCVOID)szWriteData, nWriteLength, &dwBytesWritten, NULL);
	//-----------------------------------------
	// Error check
	//-----------------------------------------
	if (bRet == FALSE ) {
		dwError = GetLastError();
		wsprintf(szText, "WriteFile:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("WriteFile:Success");
	SetTimer(1, 500, NULL);
}

//===========================================================
// Exit
//===========================================================
void CModemCmdDlg::OnButtonEnd() 
{
	//-----------------------------------------------
	// Exit
	//-----------------------------------------------
	OnCancel();
}

//===========================================================
// Receive on timer
//===========================================================
void CModemCmdDlg::OnTimer(UINT nIDEvent) 
{
	BOOL		bRet;
	DWORD		dwErrorFlags;
	COMSTAT		ComStat;
	DWORD		dwLength = 0;
	char		szReadData[4000];
	DWORD		dwError;
	char		szText[100];
	//-----------------------------------------------
	// Buffer check
	//-----------------------------------------------
	ClearCommError(hComm, &dwErrorFlags, &ComStat) ;
	if (dwErrorFlags > 0){
		wsprintf(szText, "ClearCommError:Error(dwErrorFlags=%X Hex)\n", dwErrorFlags);
		m_Ret.SetWindowText(szText);
		return;
	}
	if (ComStat.cbInQue == 0) {
		return;
	}
	//-----------------------------------------------
	// Receive
	//-----------------------------------------------
	dwLength = sizeof(szReadData);
	bRet = ReadFile(hComm, szReadData, dwLength, &dwLength, NULL);
	//-----------------------------------------------
	// Error check
	//-----------------------------------------------
	if (bRet == FALSE) {
		dwError = GetLastError();
		wsprintf(szText, "ReadFile:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	//-----------------------------------------------
	// Dispaly data
	//-----------------------------------------------
	szReadData[dwLength] = '\0';
	m_Ret.SetWindowText(szReadData);

	CDialog::OnTimer(nIDEvent);
}
