
// SamplingDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Sampling.h"
#include "SamplingDlg.h"
#include "afxdialogex.h"
#include "ConditionDlg.h"
#include "CDio.h"								// DIO header file

#define					DATA_SIZE	1000		// buffer size for busmaster

short					Id;						// Device ID
unsigned long			BmBuffer[DATA_SIZE];	// Buffer for busmaster
extern unsigned long	NumberOfData;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 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_RETURN, m_Return);
	DDX_Control(pDX, IDC_EDIT_TRANS_COUNT, m_TransCount);
	DDX_Control(pDX, IDC_EDIT_STATUS, m_Status);
	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_BN_CLICKED(IDC_BUTTON_DIO_INIT, &CSamplingDlg::OnBnClickedButtonDioInit)
	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_DIO_EXIT, &CSamplingDlg::OnBnClickedButtonDioExit)
	ON_BN_CLICKED(IDC_BUTTON_EXIT, &CSamplingDlg::OnBnClickedButtonExit)
	ON_WM_CLOSE()
END_MESSAGE_MAP()


// CSamplingDlg message handlers

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

	//-----------------------------------
	//	Dialog init
	//-----------------------------------
	m_DeviceName.SetWindowText(_T("DIO000"));

	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);
}


//===================================================
//	DioInit()
//===================================================
void CSamplingDlg::OnBnClickedButtonDioInit()
{
	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);
	//-----------------------------------
	//	DioInit
	//-----------------------------------
	ret = DioInit(buf, &Id);
	DioGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("DioInit ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
//	Set condition
//===================================================
void CSamplingDlg::OnBnClickedButtonCondition()
{
	CConditionDlg	dlg;

	//-----------------------------------
	//	Show set condition dialog
	//-----------------------------------
	dlg.DoModal();
	return;
}

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

	//-----------------------------------
	// Set notification of message
	//-----------------------------------
	ret = DioDmSetStopEvent(Id, DIODM_DIR_IN, m_hWnd);
	if (ret != DIO_ERR_SUCCESS) {
		DioGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("DioDmSetStopEvent ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	ret = DioDmSetCountEvent(Id, DIODM_DIR_IN, NumberOfData, m_hWnd);
	if (ret != DIO_ERR_SUCCESS) {
		DioGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("DioDmSetCountEvent ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	//	Reset FIFO (input)
	//-----------------------------------
	ret = DioDmFifoReset(Id, DIODM_RESET_FIFO_IN);
	if (ret != DIO_ERR_SUCCESS){
		DioGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("DioDmFifoReset ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	//	Set data buffer
	//-----------------------------------
	ZeroMemory((PVOID)BmBuffer, DATA_SIZE * sizeof(unsigned long));
	ret = DioDmSetBuffer(Id, DIODM_DIR_IN, BmBuffer, DATA_SIZE, DIODM_WRITE_ONCE);
	if (ret != DIO_ERR_SUCCESS){
		DioGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("DioDmSetBuffer ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	//	Start transfer
	//-----------------------------------
	ret = DioDmTransferStart(Id, DIODM_DIR_IN);
	if (ret != DIO_ERR_SUCCESS){
		DioGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("DioDmTransferStart ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	m_TransCount.SetWindowText(_T(""));
	m_Status.SetWindowText(_T(""));
	m_Error.SetWindowText(_T(""));
	return;
}

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

	//-----------------------------------
	//	Stop transfer
	//-----------------------------------
	ret = DioDmTransferStop(Id, DIODM_DIR_IN);
	DioGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("DioDmTransferStop ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
//	Get data
//===================================================
void CSamplingDlg::OnBnClickedButtonData()
{
	FILE			*fp;
	TCHAR			file_name[] = _T("SamplingData.csv");
	char			buf[100];
	TCHAR			szBuf[100];
	CString			str;
	unsigned long	i;

	//-----------------------------------
	//	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 into file
	//-----------------------------------
	for (i = 0; i<DATA_SIZE; i++) {
		wsprintf(szBuf, _T("%8d: ,%08X\n"), i, BmBuffer[i]);
		_fputts(szBuf, fp);
	}
	//-----------------------------------
	// Close file
	//-----------------------------------
	fclose(fp);
	//-----------------------------------
	// Notepad
	//-----------------------------------
	sprintf_s(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 = DioDmGetCount(Id, DIODM_DIR_IN, &count, &carry);
	DioGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("DioDmGetCount ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	if (ret == DIO_ERR_SUCCESS){
		str.Format(_T("%d"), 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 = DioDmGetStatus(Id, DIODM_DIR_IN, &status, &err);
	DioGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("DioDmGetStatus ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	if (ret != DIO_ERR_SUCCESS){
		return;
	}
	// Status
	str = "";
	if (status & DIODM_STATUS_BMSTOP)	str += "BmStop,";
	if (status & DIODM_STATUS_PIOSTART)	str += "PioStart,";
	if (status & DIODM_STATUS_PIOSTOP)	str += "PioStop,";
	if (status & DIODM_STATUS_TRGIN)	str += "TrgIn,";
	if (status & DIODM_STATUS_OVERRUN)	str += "Overrun";
	m_Status.SetWindowText(str);
	// Error
	str = "";
	if (err & DIODM_STATUS_FIFOEMPTY)	str += "FifoEmpty,";
	if (err & DIODM_STATUS_FIFOFULL)	str += "FifoFull,";
	if (err & DIODM_STATUS_SGOVERIN)	str += "S/GOverIn,";
	if (err & DIODM_STATUS_TRGERR)		str += "TrgErr,";
	if (err & DIODM_STATUS_CLKERR)		str += "ClkErr,";
	if (err & DIODM_STATUS_SLAVEHALT)	str += "SlaveHalt,";
	if (err & DIODM_STATUS_MASTERHALT)	str += "MasterHalt";
	m_Error.SetWindowText(str);
	return;
}

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

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

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

//===================================================
//	Close handle
//===================================================
void CSamplingDlg::OnClose()
{
	long	ret;

	//-----------------------------------
	//	DioExit()
	//-----------------------------------
	ret = DioExit(Id);

	CDialogEx::OnClose();
}

//=====================================================
// Event message routine
//=====================================================
LRESULT CSamplingDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	long			ret;
	unsigned long	count, carry;
	CString			str;

	//---------------------------------------------------
	// Transfer stop message
	//---------------------------------------------------
	if (message == DIO_DMM_STOP) {
		m_Status.SetWindowText(_T("Stopped!"));
		ret = DioDmGetCount(Id, DIODM_DIR_IN, &count, &carry);
		str.Format(_T("%d"), count);
		m_TransCount.SetWindowText(str);
	}
	//---------------------------------------------------
	// Transfer specified number of data completion message
	//---------------------------------------------------
	else if (message == DIO_DMM_COUNT) {
		//-----------------------------------
		// get count
		//-----------------------------------
		ret = DioDmGetCount(Id, DIODM_DIR_IN, &count, &carry);
		str.Format(_T("%d"), count);
		m_TransCount.SetWindowText(str);
	}

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