
// SamplingDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Sampling.h"
#include "SamplingDlg.h"
#include "ConditionDlg.h"
#include "ModeDlg.h"
#include "afxdialogex.h"
#include "CCnt.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

short					Id;										// Device ID
unsigned long			SamplingData[DATA_NUM][CHANNEL_NUM];	// Buffer for bus-master

extern unsigned long	NumberOfData;

// CSamplingDlg dialog



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

void CSamplingDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT_TRANS_COUNT, m_TransCount);
	DDX_Control(pDX, IDC_EDIT_STATUS, m_Status);
	DDX_Control(pDX, IDC_EDIT_RETURN, m_Return);
	DDX_Control(pDX, IDC_EDIT_ERROR, m_Error);
	DDX_Control(pDX, IDC_EDIT_DEV_NAME, m_DeviceName);
}

BEGIN_MESSAGE_MAP(CSamplingDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_BUTTON_CNT_INIT, &CSamplingDlg::OnBnClickedButtonCntInit)
	ON_BN_CLICKED(IDC_BUTTON_CNTMODE, &CSamplingDlg::OnBnClickedButtonCntmode)
	ON_BN_CLICKED(IDC_BUTTON_CONDITION, &CSamplingDlg::OnBnClickedButtonCondition)
	ON_BN_CLICKED(IDC_BUTTON_START, &CSamplingDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CSamplingDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_DATA, &CSamplingDlg::OnBnClickedButtonData)
	ON_BN_CLICKED(IDC_BUTTON_COUNT, &CSamplingDlg::OnBnClickedButtonCount)
	ON_BN_CLICKED(IDC_BUTTON_STATUS, &CSamplingDlg::OnBnClickedButtonStatus)
	ON_BN_CLICKED(IDC_BUTTON_CNT_EXIT, &CSamplingDlg::OnBnClickedButtonCntExit)
	ON_BN_CLICKED(IDC_BUTTON_EXIT, &CSamplingDlg::OnBnClickedButtonExit)
END_MESSAGE_MAP()


// CSamplingDlg message handlers

//===================================================
// Dialog iniitialization
//===================================================
BOOL CSamplingDlg::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

	//-----------------------------------
	// Initialize screen display
	//-----------------------------------
	m_DeviceName.SetWindowText(_T("CNT000"));

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

//===================================================
// Termination processing
//===================================================
void CSamplingDlg::OnClose()
{
	long	ret;

	//-----------------------------------
	// Termination processing
	//-----------------------------------
	ret = CntExit(Id);

	CDialogEx::OnClose();
}

//===================================================
// CntInit()
//===================================================
void CSamplingDlg::OnBnClickedButtonCntInit()
{
	CString	str;
	char	buf[100], error_string[256];
	TCHAR	szBuf[100], szError_string[256];
	long	ret;

	//-----------------------------------
	// Get device name
	//-----------------------------------
	m_DeviceName.GetWindowText(szBuf, sizeof(szBuf));
	sprintf_s(buf, "%S", szBuf);
	//-----------------------------------
	// Initialization
	//-----------------------------------
	ret = CntInit(buf, &Id);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntInit ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
// Dispaly "Counter Mode Setting" dialog
//===================================================
void CSamplingDlg::OnBnClickedButtonCntmode()
{
	//------------------------------
	// Dispaly "Counter Mode Setting" dialog
	//------------------------------
	CModeDlg	dlg;
	dlg.DoModal();
	return;
}

//=====================================================
// Display "Infinite Sampling Condition Setting" dialog
//=====================================================
void CSamplingDlg::OnBnClickedButtonCondition()
{
	CConditionDlg	dlg;
	//-----------------------------------
	// Display "Infinite Sampling Condition Setting" dialog
	//-----------------------------------
	dlg.DoModal();
	return;
}

//===================================================
// Transfer start
//===================================================
void CSamplingDlg::OnBnClickedButtonStart()
{
	short	ChNo[CHANNEL_NUM], i;
	char	error_string[256];
	TCHAR	szError_string[256];
	CString	str;
	long	ret;

	//-----------------------------------
	// Set message notification
	//-----------------------------------
	ret = CntNotifySamplingStop(Id, m_hWnd);
	if (ret != CNT_ERR_SUCCESS) {
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntNotifySamplingStop ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	ret = CntNotifySamplingCount(Id, NumberOfData, m_hWnd);
	if (ret != CNT_ERR_SUCCESS) {
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntNotifySamplingCount ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	// Reset FIFO (Input)
	//-----------------------------------
	ret = CntSamplingFifoReset(Id);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntSamplingFifoReset ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	// Set data buffer
	//-----------------------------------
	ZeroMemory((PVOID)SamplingData, DATA_NUM * CHANNEL_NUM * sizeof(unsigned long));
	ret = CntSamplingSetBuffer(Id, &SamplingData[0][0], CHANNEL_NUM, DATA_NUM, CNTS_WRITE_ONCE);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntSamplingSetBuffer ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//------------------------------
	// Set parameter
	//------------------------------
	for (i = 0; i<CHANNEL_NUM; i++) {
		ChNo[i] = i;
	}
	//------------------------------
	// Start count
	//------------------------------
	ret = CntStartCount(Id, &ChNo[0], CHANNEL_NUM);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntStartCount ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	// Transfer start
	//-----------------------------------
	ret = CntSamplingStart(Id);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntSamplingStart ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	m_TransCount.SetWindowText(_T(""));
	m_Status.SetWindowText(_T(""));
	m_Error.SetWindowText(_T(""));
	return;
}

//===================================================
// Transfer stop
//===================================================
void CSamplingDlg::OnBnClickedButtonStop()
{
	char	error_string[256];
	TCHAR	szError_string[256];
	CString	str;
	long	ret;

	//-----------------------------------
	// Transfer stop
	//-----------------------------------
	ret = CntSamplingStop(Id);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntSamplingStop ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
// Display data file
//===================================================
void CSamplingDlg::OnBnClickedButtonData()
{
	char	buf[256];
	TCHAR	szBuf[256];
	short	i, j;
	FILE	*fp;
	TCHAR	file_name[] = _T("SamplingData.csv");
	CString	str;

	//-----------------------------------
	// Write transferred data to file
	//-----------------------------------
	//-----------------------------------
	// Open file
	//-----------------------------------
	if ((_tfopen_s(&fp, file_name, _T("w"))) != 0) {
		str.Format(_T("fopen : file open error."));
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	// Write data
	//-----------------------------------
	for (i = 0; i < DATA_NUM; i++){
		wsprintf(szBuf, _T("%8d: , "), i);
		for (j = 0; j < CHANNEL_NUM - 1; j++){
			wsprintf(szBuf, _T("%s%08X, "), szBuf, SamplingData[i][j]);
		}
		wsprintf(szBuf, _T("%s%08X\n"), szBuf, SamplingData[i][j]);
		_fputts(szBuf, fp);
	}
	//-----------------------------------
	// Close file
	//-----------------------------------
	fclose(fp);

	//-----------------------------------
	// notepad
	//-----------------------------------
	sprintf_s(buf, sizeof(buf), "notepad.exe %S", file_name);
	WinExec(buf, SW_SHOW);
	return;
}

//===================================================
// Transfer count
//===================================================
void CSamplingDlg::OnBnClickedButtonCount()
{
	unsigned long	count = 0, carry = 0;
	char			error_string[256];
	TCHAR			szError_string[256];
	CString			str;
	long			ret;

	//-----------------------------------
	// Get transfer count
	//-----------------------------------
	ret = CntGetSamplingCount(Id, &count, &carry);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntGetSamplingCount ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	if (ret == CNT_ERR_SUCCESS){
		str.Format(_T("%lu"), count);
		m_TransCount.SetWindowText(str);
	}
	return;
}

//===================================================
// Transfer status
//===================================================
void CSamplingDlg::OnBnClickedButtonStatus()
{
	unsigned long	status, err;
	char			error_string[256];
	TCHAR			szError_string[256];
	CString			str;
	long			ret;

	//-----------------------------------
	// Get transfer status
	//-----------------------------------
	ret = CntGetSamplingStatus(Id, &status, &err);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntGetSamplingStatus ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	if (ret != CNT_ERR_SUCCESS){
		return;
	}

	// Status
	str = "";
	if (status & CNTS_STATUS_BMSTOP)	str += "BmStop,";
	if (status & CNTS_STATUS_CNTSTART)	str += "CntStart,";
	if (status & CNTS_STATUS_CNTSTOP)	str += "CntStop,";
	if (status & CNTS_STATUS_TRGIN)		str += "TrgIn,";
	if (status & CNTS_STATUS_OVERRUN)	str += "Overrun";
	m_Status.SetWindowText(str);
	// Error
	str = "";
	if (err & CNTS_STATUS_FIFOFULL)		str += "FifoFull,";
	if (err & CNTS_STATUS_SGOVERIN)		str += "S/GOverIn,";
	if (err & CNTS_STATUS_TRGERR)		str += "TrgErr,";
	if (err & CNTS_STATUS_CLKERR)		str += "ClkErr,";
	if (err & CNTS_STATUS_SLAVEHALT)	str += "SlaveHalt,";
	if (err & CNTS_STATUS_MASTERHALT)	str += "MasterHalt";

	m_Error.SetWindowText(str);
	return;
}

//===================================================
// CntExit
//===================================================
void CSamplingDlg::OnBnClickedButtonCntExit()
{
	char			error_string[256];
	TCHAR			szError_string[256];
	CString			str;
	long			ret;

	//-----------------------------------
	// CntExit
	//-----------------------------------
	ret = CntExit(Id);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntExit ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
// Exit
//===================================================
void CSamplingDlg::OnBnClickedButtonExit()
{
	OnOK();
	return;
}

//===================================================
// Processing of counter event notification
//===================================================
LRESULT CSamplingDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	CString			str;

	switch (message) {
	case CNTM_SAMPLING_COUNT:	// Stop transfer by specified times
		OnBnClickedButtonCount();
		break;

	case CNTM_SAMPLING_STOP:	// Transfer stopped
		m_Status.SetWindowText(_T("Stopped!"));
		::PostMessage(m_hWnd, CNTM_SAMPLING_COUNT, wParam, lParam);
		break;
	}

	return CDialogEx::DefWindowProc(message, wParam, lParam);
}