
// MltMeterDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MltMeter.h"
#include "MltMeterDlg.h"
#include "afxdialogex.h"

// Includind files (For Manual)////////////////////////////
#include "Gpibac.h"
#include "SubFunc.h"
///////////////////////////////////////////////////////////

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// Setting //////////////////////////////////////////////////////////
CString		csBuf;						// CString buffer
DWORD		Myadr, Yradr;				// MyAddress,Address of device
DWORD		Delim, Eoi;					// Delimiter
DWORD		status[31];					// Result GpPoll function
DWORD		Srlen, Ret;					// Length of string,return code
DWORD		Cmd[32], Pstb[32];			// Command of array,PollingStatus of array
DWORD		SrqOn;						// SRQ flag
DWORD		regvalue;					// 
WORD		wMsg;						// Message hundle
BYTE		SendBuf[70000];             // Buffer of string
TCHAR		szSendBuf[70000];           
BOOL		bTimerOn;					// BOOL of Timer 
BOOL		ErrorOccured;				// Error count
long		Device;						// Address of device name
UINT_PTR	SetT;						// Guard of double KillTimer()
TCHAR		szBuffer[4096];             // Character buffer

// CMltMeterDlg dialog



CMltMeterDlg::CMltMeterDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CMltMeterDlg::IDD, pParent)
{
	m_TextRet = _T("");
	m_SendData = _T("");
	m_ReceiveData = _T("");

	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMltMeterDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_DELIMBOX, m_DelimBox);
	DDX_Control(pDX, IDC_YRADR_BOX, m_YrAdrBox);
	DDX_Control(pDX, IDC_SELECT_DEVICE, m_SelectDevice);
	DDX_Text(pDX, IDC_TEXT_RET, m_TextRet);
	DDX_Text(pDX, IDC_SEND_DATA, m_SendData);
	DDX_Text(pDX, IDC_RECEIVE_DATA, m_ReceiveData);
}

BEGIN_MESSAGE_MAP(CMltMeterDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_INIT, &CMltMeterDlg::OnBnClickedInit)
	ON_BN_CLICKED(IDC_RECEIVE_START, &CMltMeterDlg::OnBnClickedReceiveStart)
	ON_BN_CLICKED(IDC_RECEIVE_STOP, &CMltMeterDlg::OnBnClickedReceiveStop)
	ON_BN_CLICKED(IDC_DEL_RET, &CMltMeterDlg::OnBnClickedDelRet)
	ON_CBN_SELCHANGE(IDC_YRADR_BOX, &CMltMeterDlg::OnCbnSelchangeYradrBox)
	ON_BN_CLICKED(IDC_EXT, &CMltMeterDlg::OnBnClickedExt)
	ON_CBN_SELENDOK(IDC_SELECT_DEVICE, &CMltMeterDlg::OnCbnSelendokSelectDevice)
	ON_CBN_SELCHANGE(IDC_DELIMBOX, &CMltMeterDlg::OnCbnSelchangeDelimbox)
	ON_WM_TIMER()
	ON_MESSAGE((WM_USER + 0x30), OnSrqEvent)		// Add to this line(1/2)
END_MESSAGE_MAP()


// CMltMeterDlg message handlers

BOOL CMltMeterDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	//***************************************************** [Setting] ***
	m_YrAdrBox.SetCurSel(2);
	m_DelimBox.SetCurSel(1);
	m_SelectDevice.AddString(_T("[ ADVANTEST R6871E Digital Multimeter ]"));
	m_SelectDevice.AddString(_T("[ Sanwa Digital Multimeter 9300MF ]"));
	m_SelectDevice.AddString(_T("[ Iwatsu Digital Multimeter SC-7404 ]"));
	m_SelectDevice.SetCurSel(0);

	Yradr = GetDlgItemInt(IDC_YRADR_BOX);					// Address of device is required

	lstrcpy((TCHAR*)SendBuf, _T("F1R5M2IT1DL0RE7BZ1S0"));	/* Initialize Send Data */
	SendDlgItemMessage(IDC_TIMER, BM_SETCHECK, TRUE, 0L);	/* Select timer */
	m_SendData = (TCHAR*)SendBuf;
	wMsg = WM_USER + 0x30;
	bTimerOn = 0;

	UpdateData(FALSE);
	//*******************************************************************

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMltMeterDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		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;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMltMeterDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

/////////////////////////////////////////////////////////////////////
// This Sample Code is here.
/////////////////////////////////////////////////////////////////////

// ******************************** [SrqEvent] function ***
LRESULT CMltMeterDlg::OnSrqEvent(WPARAM nDummy, LPARAM lDummy)
{
	UpdateData(TRUE);

	ErrorOccured = 0;										// there is no error
	Cmd[0] = 1;												// Command count
	Cmd[1] = Yradr;											// Address of device
	Ret = GpPoll(Cmd, status);								// execute GpPoll function					
	if (CheckRet(_T("GpPoll"), Ret, &csBuf) != 0){			// Error check
		ErrorOccured = 1;
		goto ErrorOnSrq;
	}
	Cmd[0] = 2;
	Cmd[1] = Yradr;
	Cmd[2] = Myadr;
	Srlen = sizeof(SendBuf);								// Length of SendBuf
	Ret = GpListen(Cmd, &Srlen, SendBuf);					// Execute GpListen function
	if (CheckRet(_T("GpListen"), Ret, &csBuf) != 0){		// Error check
		ErrorOccured = 1;
		goto ErrorOnSrq;
	}
	Cmd[0] = 2;
	Cmd[1] = 0x3f;											// UNL / Unlisten
	Cmd[2] = 0x5f;											// UNT / Untalken
	Ret = GpComand(Cmd);									// Execute GpComand function
	if (CheckRet(_T("GpComand"), Ret, &csBuf) != 0){		// Error check
		ErrorOccured = 1;
		goto ErrorOnSrq;
	}
	Ret = GpGet(Yradr);										// Execute GpGet function
	if (CheckRet(_T("GpGet"), Ret, &csBuf) != 0){			// Error check
		ErrorOccured = 1;
		goto ErrorOnSrq;
	}
	m_TextRet = csBuf;

ErrorOnSrq:
	if (ErrorOccured != 0){
		SrqOn = 0;
		Ret = GpSetEventSrq(m_hWnd, wMsg, SrqOn);			// SRQ Event
		UpdateData(FALSE);
		return TRUE;
	}
	SendBuf[Srlen] = 0x0;									// NULL is put at the end of reception data.
	m_ReceiveData = SendBuf;
	wsprintf(szBuffer, _T("Data was received. Get [ %d ] byte data."), Srlen);
	m_TextRet = szBuffer;

	Ret = GpEnableNextEvent();								// Enable next event

	UpdateData(FALSE);

	return TRUE;
}

//////////////////////////////////////////// Initialize ///
void CMltMeterDlg::OnBnClickedInit()
{
	TCHAR DelMyadr[8];

	UpdateData(TRUE);

	GpibInit(&csBuf);
	GpBoardsts(0x08, &Myadr);								// My Address is acquired

	GpDcl();
	GpWaittime(10);

	lstrcpy(szSendBuf, m_SendData);
	Srlen = lstrlen(szSendBuf);
	sprintf_s((char*)SendBuf, Srlen + 1, "%S", szSendBuf);
	Cmd[0] = 2;												// Talker + Listener    
	Cmd[1] = Myadr;											// MyAddress    
	Cmd[2] = Yradr;											// Address of device
	Ret = GpTalk(Cmd, Srlen, SendBuf);						// Execute GpTalk function         
	CheckRet(_T("Initialize"), Ret, &csBuf);
	if ((Ret & 0xFF) == 0){
		csBuf = _T("Initialize is ended.");
		GetDlgItem(IDC_RECEIVE_START)->EnableWindow(TRUE);
		GetDlgItem(IDC_TIMER)->EnableWindow(TRUE);
		GetDlgItem(IDC_ON_SRQ)->EnableWindow(TRUE);
	}

	wsprintf(DelMyadr, _T("%d"), Myadr);					// Show MyAddress
	Ret = m_YrAdrBox.FindStringExact(-1, DelMyadr);
	if (Ret >= 0){											// Searching MyAddress
		m_YrAdrBox.DeleteString(Ret);						// Delete MyAddress 
		if (Myadr == Yradr){
			m_YrAdrBox.SetCurSel(0);
		}
	}
	m_TextRet = csBuf;

	UpdateData(FALSE);

	OnCbnSelchangeDelimbox();
}

///////////////////////////////////////// Receive Start ///
void CMltMeterDlg::OnBnClickedReceiveStart()
{
	DWORD	SrqOn;											// SRQ Event flag

	UpdateData(TRUE);

	SrqOn = 1;												// Running SrqOn
	GetDlgItem(IDC_RECEIVE_START)->EnableWindow(FALSE);
	GetDlgItem(IDC_RECEIVE_STOP)->EnableWindow(TRUE);
	GetDlgItem(IDC_TIMER)->EnableWindow(FALSE);
	GetDlgItem(IDC_ON_SRQ)->EnableWindow(FALSE);
	GetDlgItem(IDC_INIT)->EnableWindow(FALSE);
	GetDlgItem(IDC_EXT)->EnableWindow(FALSE);

	if (SendDlgItemMessage(IDC_TIMER, BM_GETCHECK, 0, 0L)){	// A timer is chosen
		if (!bTimerOn){
			SetT = SetTimer(ID_TIMER, TIMERCOUNT, NULL);
			bTimerOn = 1;
		}
	}
	else{
		SrqOn = 1;
		Ret = GpSetEventSrq(m_hWnd, wMsg, SrqOn);			// Execute GpSetEventSrq() function 
		if ((Ret & 0xFF) != 0){
			CheckRet(_T("GpSetEventSrq"), Ret, &csBuf);
			m_TextRet = csBuf;
			UpdateData(FALSE);
			return;
		}
		Ret = GpSetEvent(SrqOn);							// Execute GpSetEvent() function 
		if ((Ret & 0xFF) != 0){
			CheckRet(_T("GpSetEvent"), Ret, &csBuf);
			m_TextRet = csBuf;
			UpdateData(FALSE);
			return;
		}
		Ret = GpGet(Yradr);									// Execute GpGet() function
		if ((Ret & 0xFF) != 0){
			CheckRet(_T("GpGet"), Ret, &csBuf);
			SrqOn = 0;
			Ret = GpSetEvent(SrqOn);
			m_TextRet = csBuf;
			UpdateData(FALSE);
			return;
		}
	}
	m_TextRet = _T("Data is receiving.");
	UpdateData(FALSE);
}

////////////////////////////////////////// Receive Stop ///
void CMltMeterDlg::OnBnClickedReceiveStop()
{
	GetDlgItem(IDC_RECEIVE_START)->EnableWindow(TRUE);
	GetDlgItem(IDC_RECEIVE_STOP)->EnableWindow(FALSE);
	GetDlgItem(IDC_TIMER)->EnableWindow(TRUE);
	GetDlgItem(IDC_ON_SRQ)->EnableWindow(TRUE);
	GetDlgItem(IDC_INIT)->EnableWindow(TRUE);
	GetDlgItem(IDC_EXT)->EnableWindow(TRUE);

	m_TextRet = _T("Data receiving was stopped.");
	if (SendDlgItemMessage(IDC_TIMER, BM_GETCHECK, 0, 0L)){	// Timer stopped
		KillTimer(ID_TIMER);
		SetT = 0;
		bTimerOn = 0;
	}
	else{
		SrqOn = 0;
		Ret = GpSetEvent(SrqOn);							// Event stopped
	}

	UpdateData(FALSE);
}

///////////////////////////////////////// Delete Return ///
void CMltMeterDlg::OnBnClickedDelRet()
{
	UpdateData(TRUE);
	m_TextRet = "";
	UpdateData(FALSE);
}

//////////////////////////////////////// Address of device Change ///
void CMltMeterDlg::OnCbnSelchangeYradrBox()
{
	UpdateData(TRUE);
	Yradr = GetDlgItemInt(IDC_YRADR_BOX);					// Address of device is required
	GetDlgItem(IDC_RECEIVE_START)->EnableWindow(FALSE);
}

////////////////////////////////////////////////// Exit ///
void CMltMeterDlg::OnBnClickedExt()
{
	SrqOn = 0;

	Ret = GpSetEvent(SrqOn);
	if (SetT != 0)
		KillTimer(ID_TIMER);
	GpibExit();												// GpibExit function

	CDialog::OnCancel();									// End of program
}

void CMltMeterDlg::OnCbnSelendokSelectDevice()
{
	UpdateData(TRUE);

	Device = m_SelectDevice.GetCurSel();					// Chenge device
	switch (Device){
	case 0:
		lstrcpy(szBuffer, _T("F1R5M2IT1DL0RE7BZ1S0"));		// Advantest
		break;
	case 1:
		lstrcpy(szBuffer, _T("F1R0I0C1"));					// Sanwa
		break;
	case 2:
		lstrcpy(szBuffer, _T("R0"));						// Iwatsu
		break;
	default:
		break;
	}
	m_SendData = szBuffer;

	UpdateData(FALSE);
}

///////////////////////////////////////////////// Timer ///
void CMltMeterDlg::OnTimer(UINT_PTR nIDEvent)
{
	UpdateData(TRUE);

	ErrorOccured = 0;
	m_YrAdrBox.GetDlgItem(Yradr);

	Ret = GpGet(Yradr);
	if (CheckRet(_T("GpGet"), Ret, &csBuf) != 0){
		ErrorOccured = 1;
		goto ErrorOnTimer;
	}

	regvalue = 0;
	while (regvalue == 0){
		if (GetAsyncKeyState(VK_ESCAPE) || (GetAsyncKeyState(VK_ESCAPE) << 1)){
			ErrorOccured = 1;
			csBuf = _T("Please click the key named [Esc]");
			goto ErrorOnTimer;
		}
		Ret = GpBoardsts(0x12, &regvalue);
		if (CheckRet(_T("GpBoardsts"), Ret, &csBuf) != 0){
			ErrorOccured = 1;
			goto ErrorOnTimer;
		}
	}

	do{
		Cmd[0] = 1;
		Cmd[1] = Yradr;
		Ret = GpPoll(Cmd, status);
		GpWaittime(10);
		if (bTimerOn == 0){
			break;
		}
	} while (Ret == 128);

	if (CheckRet(_T("GpPoll"), Ret, &csBuf) != 0){
		ErrorOccured = 1;
		goto ErrorOnTimer;
	}
	Cmd[0] = 2;
	Cmd[1] = Yradr;
	Cmd[2] = Myadr;
	Srlen = sizeof(SendBuf);
	Ret = GpListen(Cmd, &Srlen, SendBuf);
	if (CheckRet(_T("GpListen"), Ret, &csBuf) != 0){
		ErrorOccured = 1;
		goto ErrorOnTimer;
	}
	Cmd[0] = 2;
	Cmd[1] = 0x3f;
	Cmd[2] = 0x5f;
	Ret = GpComand(Cmd);
	if (CheckRet(_T("GpComand"), Ret, &csBuf) != 0){
		ErrorOccured = 1;
		goto ErrorOnTimer;
	}

ErrorOnTimer:												// Error										
	if (ErrorOccured != 0){
		SetT = KillTimer(ID_TIMER);
		m_TextRet = csBuf;
		UpdateData(FALSE);
		return;
	}
	SendBuf[Srlen] = 0x0;
	m_ReceiveData = SendBuf;
	wsprintf(szBuffer, _T("Data is received.[ %d ] bytes get."), Srlen);
	m_TextRet = szBuffer;

	UpdateData(FALSE);

	CDialog::OnTimer(nIDEvent);
}

BOOL CMltMeterDlg::PreTranslateMessage(MSG* pMsg)
{
	if (pMsg->message == WM_KEYDOWN)
	{
		switch (pMsg->wParam)
		{
		case VK_ESCAPE: 									// ESC Key is disebled.
			return TRUE;
		default:
			break;
		}
	}
	return CDialog::PreTranslateMessage(pMsg);
}

////////////////////////////////////// Delimiter Change ///
void CMltMeterDlg::OnCbnSelchangeDelimbox()
{
	UpdateData(TRUE);

	Eoi = 1;												// EOI : USE
	Delim = m_DelimBox.GetCurSel();
	Ret = GpDelim(Delim, Eoi);
}
