
// DemoVCDlg.cpp : implementation file
//

#include "stdafx.h"
#include "DemoVC.h"
#include "DemoVCDlg.h"
#include "afxdialogex.h"
#include "visa.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define MAX_REC_SIZE 1024

// CAboutDlg dialog used for App About

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

// Dialog Data
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

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

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CDemoVCDlg dialog



CDemoVCDlg::CDemoVCDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(IDD_DEMOVC_DIALOG, pParent)
	, m_strResponse(_T(""))
	, m_strInstrAddr(_T(""))
	, m_strCommand(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDemoVCDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT_INSTRUMENT_ADDRESS, m_editInstrAddr);
	DDX_Control(pDX, IDC_EDIT_COMMAND, m_editCommand);
	DDX_Control(pDX, IDC_EDIT_RESPONSE, m_editResponse);
}

BEGIN_MESSAGE_MAP(CDemoVCDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDOK, &CDemoVCDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDCANCEL, &CDemoVCDlg::OnBnClickedCancel)
	ON_BN_CLICKED(IDC_BTN_CONNECT, &CDemoVCDlg::OnBnClickedBtnConnect)
	ON_BN_CLICKED(IDC_BTN_SEND_COMMAND, &CDemoVCDlg::OnBnClickedBtnSendCommand)
	ON_BN_CLICKED(IDC_BTN_READ_RESPONSE, &CDemoVCDlg::OnBnClickedBtnReadResponse)
	ON_BN_CLICKED(IDC_BTN_SEND_AND_READ, &CDemoVCDlg::OnBnClickedBtnSendAndRead)
END_MESSAGE_MAP()


// CDemoVCDlg message handlers

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

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 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

	// TODO: Add extra initialization here
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDemoVCDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 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 CDemoVCDlg::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 CDemoVCDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CDemoVCDlg::OnBnClickedOk()
{
	// TODO: 在此添加控件通知处理程序代码
	CDialogEx::OnOK();
}


void CDemoVCDlg::OnBnClickedCancel()
{
	// TODO: 在此添加控件通知处理程序代码
	CDialogEx::OnCancel();
}

bool CDemoVCDlg::InstrWrite(CString strAddr, CString strContent)
{
	USES_CONVERSION;

	ViSession defaultRM, instr;
	ViStatus status;
	ViUInt32 retCount;
	
	bool bWriteOK = false;
	CString str;
	strContent += _T("\n");
	char * SendBuf = T2A(strContent);
	//open a VISA resource
	status = viOpenDefaultRM(&defaultRM);
	if (status < VI_SUCCESS)
	{
		AfxMessageBox(_T("No VISA resource was opened!"));
		return false;
	}

	status = viOpen(defaultRM, T2A(strAddr), VI_NULL, VI_NULL, &instr);

	//Write command to the instrument
	status = viWrite(instr, (unsigned char *)SendBuf, strlen(SendBuf), &retCount);
	if (VI_SUCCESS == status)
		bWriteOK = true;
	//Close the system
	status = viClose(instr);
	status = viClose(defaultRM);
	return bWriteOK;
}

bool CDemoVCDlg::InstrRead(CString strAddr, CString *pstrResult)
{
	USES_CONVERSION; 
	ViSession defaultRM, instr;
	ViStatus status;
	ViUInt32 retCount;
	unsigned char RecBuf[MAX_REC_SIZE];
	bool bReadOK = false;
	CString str;

	memset(RecBuf, 0, MAX_REC_SIZE);
	//Open a VISA resource
	status = viOpenDefaultRM(&defaultRM);
	if (status < VI_SUCCESS)
	{
		// Error Initializing VISA...exiting 
		AfxMessageBox(_T("No VISA resource was opened!"));
		return false;
	}	
	//Open the instrument
	status = viOpen(defaultRM, T2A(strAddr), VI_NULL, VI_NULL, &instr);
	//Read from the instrument
	status = viRead(instr, RecBuf, MAX_REC_SIZE, &retCount);	
	if (status == VI_SUCCESS || status == VI_SUCCESS_TERM_CHAR || status == VI_SUCCESS_MAX_CNT)
		bReadOK = true;
	//close the system
	status = viClose(instr);
	status = viClose(defaultRM);	
	(*pstrResult).Format(_T("%s"), A2T((char*)RecBuf));
	return bReadOK;
}


void CDemoVCDlg::OnBnClickedBtnConnect()
{
	// TODO: 在此添加控件通知处理程序代码
	USES_CONVERSION;
	ViStatus status;
	ViSession defaultRM;
	ViString expr = "?*";
	ViPFindList findList = new unsigned long;
	ViPUInt32 retcnt = new unsigned long;
	ViChar instrDesc[1000];
	CString strSrc = L"";
	CString strInstr = L"";
	unsigned long i = 0;
	bool bFind = false;

	status = viOpenDefaultRM(&defaultRM);
	if (status < VI_SUCCESS)
	{
		// Error Initializing VISA...exiting 
		AfxMessageBox(L"No VISA instrument was opened !");
		return;
	}

	memset(instrDesc, 0, 1000);

	//Find resource
	status = viFindRsrc(defaultRM, expr, findList, retcnt, instrDesc);

	for (i = 0; i < (*retcnt); i++)
	{
		//Get instrument name
		strSrc.Format(L"%s", A2T(instrDesc));
		InstrWrite(strSrc, L"*IDN?");
		::Sleep(200);
		InstrRead(strSrc, &strInstr);

		//If the instrument(resource) belongs to the XXXX series then jump out from the loop
		strInstr.MakeUpper();
		if (strInstr.Find(L"HDM") >= 0)
		{
			bFind = true;
			m_strInstrAddr = strSrc;
			break;
		}
		//Find next resource
		status = viFindNext(*findList, instrDesc);
	}
	if (bFind == false)
	{
		AfxMessageBox(L"Didn't find any device!");
		m_editInstrAddr.SetWindowText(_T(""));
	}
	else
	{
		m_editInstrAddr.SetWindowText(m_strInstrAddr);
	}
}


void CDemoVCDlg::OnBnClickedBtnSendCommand()
{
	// TODO: 在此添加控件通知处理程序代码
	if (m_strInstrAddr.IsEmpty())
	{
		AfxMessageBox(L"Please connect the instrument first!");
	}
	m_editCommand.GetWindowText(m_strCommand);
	if (!m_strCommand.IsEmpty())
	{
		InstrWrite(m_strInstrAddr, m_strCommand);
	}
	m_strResponse.Empty();
}


void CDemoVCDlg::OnBnClickedBtnReadResponse()
{
	// TODO: 在此添加控件通知处理程序代码
	if (m_strInstrAddr.IsEmpty())
	{
		AfxMessageBox(L"Please connect the instrument first!");
	}
	InstrRead(m_strInstrAddr, &m_strResponse);
	m_editResponse.SetWindowText(m_strResponse);
}


void CDemoVCDlg::OnBnClickedBtnSendAndRead()
{
	// TODO: 在此添加控件通知处理程序代码
	OnBnClickedBtnSendCommand();
	OnBnClickedBtnReadResponse();
}
