// ModemTxRxDlg.cpp : Cve[V t@C
//

#include "stdafx.h"
#include "ModemTxRx.h"
#include "ModemTxRxDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CModemTxRxDlg _CAO

CModemTxRxDlg::CModemTxRxDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CModemTxRxDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CModemTxRxDlg)
		// : ̈ʒu ClassWizard ɂăȍǉ܂B
	//}}AFX_DATA_INIT
	// : LoadIcon  Win32  DestroyIcon ̃TuV[PXv܂B
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CModemTxRxDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CModemTxRxDlg)
	DDX_Control(pDX, IDC_COMBO_FLOW_CTRL, m_FlowCtrl);
	DDX_Control(pDX, IDC_EDIT_RET, m_Ret);
	DDX_Control(pDX, IDC_RADIO_TEXT, m_RadioText);
	DDX_Control(pDX, IDC_EDIT_SRC_ID, m_SrcID);
	DDX_Control(pDX, IDC_EDIT_SEND_DATA, m_SendData);
	DDX_Control(pDX, IDC_EDIT_RECEIVE_DATA, m_ReceiveData);
	DDX_Control(pDX, IDC_EDIT_DEST_ID, m_DestID);
	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_BAUDRATE, m_Baudrate);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CModemTxRxDlg, CDialog)
	//{{AFX_MSG_MAP(CModemTxRxDlg)
	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_RECEIVE, OnButtonReceive)
	ON_BN_CLICKED(IDC_BUTTON_END, OnButtonEnd)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CModemTxRxDlg bZ[W nh

// _CAO{bNXɍŏ{^ǉȂ΁AACR`悷
// R[hȉɋLqKv܂BMFC AvP[V document/view
// fgĂ̂ŁȀ̓t[[Nɂ莩Iɏ܂B

void CModemTxRxDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // `p̃foCX ReLXg

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

		// NCAg̋`̈̒
		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;

		// ACR`悵܂B
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// VXéA[U[ŏEBhEhbOĂԁA
// J[\\邽߂ɂĂяo܂B
HCURSOR CModemTxRxDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
//===========================================================
// O[oϐ
//===========================================================
HANDLE	hComm;		// COM|[g̃nh

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

// {[[g
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		}
};

// f[^rbg
STR_NUM	snDataBit[] = {
	{	"7",		7		},
	{	"8",		8		},
	{	"End",		0		}
};

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

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

// t[
#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			}
};

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

	// ̃_CAOp̃ACRݒ肵܂Bt[[N̓AvP[ṼC
	// EBhE_CAOłȂ͎Iɐݒ肵܂B
	SetIcon(m_hIcon, TRUE);			// 傫ACRݒ
	SetIcon(m_hIcon, FALSE);		// ACRݒ
	
	//-----------------------------------------------
	// R{{bNX̏
	//-----------------------------------------------
	int		i;
	char	szText[100];
	// |[g
	for (i=1; i<100; i++) {
		wsprintf(szText, "COM%d", i);
		m_Port.AddString(szText);
	}
	m_Port.SelectString(-1, "COM1");
	// {[[g
	for (i=0; lstrcmp(snBaudrate[i].Str, "End") != 0; i++) {
		m_Baudrate.AddString(snBaudrate[i].Str);
	}
	m_Baudrate.SelectString(-1, "9600");
	// f[^rbg
	for (i=0; lstrcmp(snDataBit[i].Str, "End") != 0; i++) {
		m_DataBit.AddString(snDataBit[i].Str);
	}
	m_DataBit.SelectString(-1, "8");
	// peB
	for (i=0; lstrcmp(snParity[i].Str, "End") != 0; i++) {
		m_Parity.AddString(snParity[i].Str);
	}
	m_Parity.SelectString(-1, "NONE");
	// Xgbvrbg
	for (i=0; lstrcmp(snStopBit[i].Str, "End") != 0; i++) {
		m_StopBit.AddString(snStopBit[i].Str);
	}
	m_StopBit.SelectString(-1, "1");
	// t[
	for (i=0; lstrcmp(snFlowCtrl[i].Str, "End") != 0; i++) {
		m_FlowCtrl.AddString(snFlowCtrl[i].Str);
	}
	m_FlowCtrl.SelectString(-1, "NONE");
	// eLXg`FbN
	m_RadioText.SetCheck(1);
	// @ID
	m_DestID.SetWindowText("001");
	// M@ID
	m_SrcID.SetWindowText("000");
	return TRUE;  // TRUE ԂƃRg[ɐݒ肵tH[JX͎܂B
}

//===========================================================
// I[v
//===========================================================
void CModemTxRxDlg::OnButtonOpen() 
{
	char	szCommPort[100];
	char	szText[100];
	DWORD	dwError;
	//-----------------------------------------------
	// COM|[g̍쐬
	//-----------------------------------------------
	m_Port.GetWindowText(szText, sizeof(szText));
	wsprintf(szCommPort, "\\\\.\\%s", szText);
	//-----------------------------------------------
	// I[v
	//-----------------------------------------------
	hComm = CreateFile(
				szCommPort,
				GENERIC_READ | GENERIC_WRITE,
				0,
				NULL,
				OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL,
				NULL);
	//-----------------------------------------------
	// G[`FbN
	//-----------------------------------------------
	if (hComm == INVALID_HANDLE_VALUE) {
		dwError = GetLastError();
		wsprintf(szText, "CreateFile:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("CreateFile:Success");
}

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

//===========================================================
// ݒ
//===========================================================
void CModemTxRxDlg::OnButtonSetting() 
{
	DWORD	dwBaudrate;
	BYTE	bDataBit;
	BYTE	bParity;
	BYTE	bStopBit;
	DWORD	dwFlowCtrl;
	COMMTIMEOUTS	CommTimeOuts;
	DCB		dcb;
	char	szText[100];
	BOOL	bRet;
	int		i;
	DWORD	dwError;
	//-----------------------------------------------
	// ʂf[^̎擾
	//-----------------------------------------------
	// {[[g
	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;
		}
	}
	// f[^rbg
	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;
		}
	}
	// peB
	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;
		}
	}
	// Xgbvrbg
	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;
		}
	}
	// t[
	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;
		}
	}
	//-----------------------------------------------
	// Mobt@NA
	//-----------------------------------------------
	PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT |
					 PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
	//-----------------------------------------------
	// ^CAEglZbg
	//-----------------------------------------------
	CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 5000;
	CommTimeOuts.WriteTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.WriteTotalTimeoutConstant = 5000;
	SetCommTimeouts(hComm, &CommTimeOuts ) ;
	//-----------------------------------------------
	// ʐMfoCX̏Ԏ擾
	//-----------------------------------------------
	dcb.DCBlength = sizeof( DCB ) ;
	GetCommState(hComm, &dcb ) ;
	//-----------------------------------------
	// ʐMfoCXZbg
	//-----------------------------------------
	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);
	//-----------------------------------------
	// G[`FbN
	//-----------------------------------------
	if (bRet == FALSE ) {
		dwError = GetLastError();
		wsprintf(szText, "SetCommState:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("SetCommState:Success");
}

void CModemTxRxDlg::OnButtonSend() 
{
	char	szWriteData[4000];
	BOOL	bRet;
	DWORD	dwBytesWritten;
	DWORD	nWriteLength;
	DWORD	dwError;
	int		iTextCheck;
	char	szText[4000];
	char	szDest[10];
	char	szSrc[10];
	char	szTmp[100];
	int		iTmp, i, iLen;
	//-----------------------------------------------
	// ʂf[^擾
	//-----------------------------------------------
	m_SendData.GetWindowText(szText, sizeof(szText));
	m_DestID.GetWindowText(szDest, sizeof(szDest));
	m_SrcID.GetWindowText(szSrc, sizeof(szSrc));
	iTextCheck = m_RadioText.GetCheck();
	// ID3̕ɕϊ
	iTmp = atoi(szDest);
	wsprintf(szDest, "%03d", iTmp);
	iTmp = atoi(szSrc);
	wsprintf(szSrc, "%03d", iTmp);
	//-----------------------------------------------
	// M̍쐬
	//-----------------------------------------------
	if (iTextCheck == 1) {	// eLXg
		lstrcpy(szWriteData, "@TXT");
		lstrcat(szWriteData, szDest);
		lstrcat(szWriteData, szSrc);
		lstrcat(szWriteData, szText);
		lstrcat(szWriteData, "\r");
		nWriteLength = lstrlen(szWriteData);
	}
	else {					// oCi
		lstrcpy(szWriteData, "@TXB");
		lstrcat(szWriteData, szDest);
		lstrcat(szWriteData, szSrc);
		iLen = lstrlen(szText) / 2;	// Mf[^
		szWriteData[10] = (char)(iLen & 0xff);
		szWriteData[11] = (char)((iLen >> 8) & 0xff);
		// eLXgoCiϊ
		for (i=0; i<iLen; i++) {
			szTmp[0] = szText[i*2];
			szTmp[1] = szText[i*2+1];
			szTmp[2] = '\0';
			sscanf_s(szTmp, "%X", &iTmp);
			szWriteData[12+i] = (BYTE)iTmp;
		}
		nWriteLength = 12 + iLen;
	}
	//-----------------------------------------------
	// M
	//-----------------------------------------------
	bRet = WriteFile(hComm, (LPCVOID)szWriteData, nWriteLength, &dwBytesWritten, NULL);
	//-----------------------------------------
	// G[`FbN
	//-----------------------------------------
	if (bRet == FALSE ) {
		dwError = GetLastError();
		wsprintf(szText, "WriteFile:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	m_Ret.SetWindowText("WriteFile:Success");
}

//===========================================================
// M
//===========================================================
void CModemTxRxDlg::OnButtonReceive() 
{
	BOOL		bRet;
	DWORD		dwErrorFlags;
	COMSTAT		ComStat;
	DWORD		dwLength = 0;
	char		szReadData[4000];
	DWORD		dwError;
	char		szText[4000];
	char		szTmp[100];
	int			i, iLen;
	//-----------------------------------------------
	// obt@L[ɗ܂ĂH
	//-----------------------------------------------
	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) {
		m_Ret.SetWindowText("ClearCommError:No read data.");
		return;
	}
	//-----------------------------------------------
	// ǂ݂
	//-----------------------------------------------
	dwLength = sizeof(szReadData);
	bRet = ReadFile(hComm, szReadData, dwLength, &dwLength, NULL);
	//-----------------------------------------------
	// G[`FbN
	//-----------------------------------------------
	if (bRet == FALSE) {
		dwError = GetLastError();
		wsprintf(szText, "ReadFile:Error(%d)", dwError);
		m_Ret.SetWindowText(szText);
		return;
	}
	//-----------------------------------------------
	// Mf[^̕\
	//-----------------------------------------------
	if (strncmp(szReadData, "@RXT", 4) == 0) {
		szReadData[dwLength] = '\0';
		m_ReceiveData.SetWindowText(&szReadData[10]);
	}
	else if (strncmp(szReadData, "@RXB", 4) == 0) {
		// f[^
		iLen = (((szReadData[11] << 8) & 0xff00) | (szReadData[10] & 0xff));
		// oCieLXgϊ
		lstrcpy(szText, "");
		for (i=0; i<iLen; i++) {
			wsprintf(szTmp, "%02X", (unsigned int)(szReadData[12 + i] & 0xff));
			lstrcat(szText, szTmp);
		}
		m_ReceiveData.SetWindowText(szText);
	}
	else {
		m_Ret.SetWindowText("Illegal Headder.");
		return;
	}
	wsprintf(szText, "ReadFile:Success(%d)Bytes", dwLength);
	m_Ret.SetWindowText(szText);
}

//===========================================================
// I
//===========================================================
void CModemTxRxDlg::OnButtonEnd() 
{
	//-----------------------------------------------
	// I
	//-----------------------------------------------
	OnCancel();
}
