
// DataLoggerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "DataLogger.h"
#include "DataLoggerDlg.h"
#include "afxdialogex.h"
//-------------------------------------
// Include API-DIG(WDM) header file
//-------------------------------------
#include "cdig.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CDataLoggerDlg dialog



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

void CDataLoggerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_RICHEDIT_DATA, m_EditData);
	DDX_Control(pDX, IDC_EDIT_STATUS, m_Status);
	DDX_Control(pDX, IDC_EDIT_INFO, m_Info);
	DDX_Control(pDX, IDC_EDIT_DEVICE, m_DeviceName);
	DDX_Control(pDX, IDC_EDIT_COUNT, m_Count);
	DDX_Control(pDX, IDC_COMBO_RANGE, m_Range);
}

BEGIN_MESSAGE_MAP(CDataLoggerDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_INIT, &CDataLoggerDlg::OnBnClickedButtonInit)
	ON_CBN_SELCHANGE(IDC_COMBO_RANGE, &CDataLoggerDlg::OnCbnSelchangeComboRange)
	ON_BN_CLICKED(IDC_BUTTON_START, &CDataLoggerDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_INFO, &CDataLoggerDlg::OnBnClickedButtonInfo)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CDataLoggerDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_SAVE, &CDataLoggerDlg::OnBnClickedButtonSave)
	ON_BN_CLICKED(IDC_BUTTON_EXIT, &CDataLoggerDlg::OnBnClickedButtonExit)
	ON_WM_DESTROY()
	ON_WM_CLOSE()
END_MESSAGE_MAP()


// CDataLoggerDlg message handlers

BOOL CDataLoggerDlg::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 device name
	//---------------------------------
	m_DeviceName.SetWindowText(_T("DIG000"));

	//---------------------------------
	// Initialize input range
	//---------------------------------
	m_Range.AddString(_T("+/-20V"));
	m_Range.AddString(_T("+/-10V"));
	m_Range.AddString(_T("+/-5V"));
	m_Range.AddString(_T("+/-2V"));
	m_Range.AddString(_T("+/-1V"));
	m_Range.AddString(_T("+/-0.5V"));
	m_Range.AddString(_T("+/-0.2V"));
	m_Range.AddString(_T("+/-0.1V"));
	m_Range.AddString(_T("+/-0.05V"));
	m_Range.AddString(_T("+/-0.02V"));

	//---------------------------------
	// Initialize the number of acquisition samples
	//---------------------------------
	m_Samples = 0;

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


//===============================================
// Init handling
//===============================================
void CDataLoggerDlg::OnBnClickedButtonInit()
{
	CString cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	char	device_name[256];	// Device name
	TCHAR	szDevice_name[256];
	long	ret;				// Return value

	//---------------------------------
	// Init handling
	//---------------------------------
	m_DeviceName.GetWindowText(szDevice_name, sizeof(szDevice_name));
	sprintf_s(device_name, "%S", szDevice_name);
	ret = DigInit(device_name, &m_Id);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigInit = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}

	//---------------------------------
	// Reset device
	//---------------------------------
	ret = DigResetDevice(m_Id);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigResetDevice = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}

	m_Info.SetWindowText(_T("Init : Normality completion"));
}

//===============================================
// Set input range
//===============================================
void CDataLoggerDlg::OnCbnSelchangeComboRange()
{
	CString	cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	int		index;				// The selected index value of input range combobox
	float	range;				// Input range
	int		ret;				// Return value

	//---------------------------------
	// Get the input range from combobox
	//---------------------------------
	index = m_Range.GetCurSel();
	switch (index){
	case 0:	range = DIG_RANGE_40VPP;	break;
	case 1:	range = DIG_RANGE_20VPP;	break;
	case 2:	range = DIG_RANGE_10VPP;	break;
	case 3:	range = DIG_RANGE_4VPP;		break;
	case 4:	range = DIG_RANGE_2VPP;		break;
	case 5:	range = DIG_RANGE_1VPP;		break;
	case 6:	range = DIG_RANGE_400MVPP;	break;
	case 7: range = DIG_RANGE_200MVPP;	break;
	case 8: range = DIG_RANGE_100MVPP;	break;
	case 9:	range = DIG_RANGE_40MVPP;	break;
	default: break;
	}

	//---------------------------------
	// Set input range of channel0
	//---------------------------------
	ret = DigSetRange(m_Id, DIG_CHANNEL0, range);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetRange = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}

	m_Info.SetWindowText(_T("Set input range : Normality completion"));
}

//===============================================
// Start acquisition
//===============================================
void CDataLoggerDlg::OnBnClickedButtonStart()
{
	CString cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	int		ret;				// Return value

	//---------------------------------
	// Initialize variable
	//---------------------------------
	m_Samples = 0;

	//---------------------------------
	// Set operation mode : Data logger mode
	//---------------------------------
	ret = DigSetDigitizerMode(m_Id, DIG_MODE_LOGGER);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetDigitizerMode = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set sampling clock source : Crystal oscillator of board
	//---------------------------------
	ret = DigSetClockSource(m_Id, DIG_ECU_SRC_CLOCK);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetClockSource = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set sampling clock : 1000usec  (set value * 10 + 10 (nsec))
	//---------------------------------
	ret = DigSetSampleClock(m_Id, 99999);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetSampleClock = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set the number of acquiring records : 1
	//---------------------------------
	ret = DigSetRecordNumber(m_Id, 1);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetRecordNumber = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set the number of pre-trigger samples : 1000
	//---------------------------------
	ret = DigSetPreSampleTimes(m_Id, MAX_SAMPLES);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetPreSampleTimes = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set the number of post-trigger samples : 0
	//---------------------------------
	ret = DigSetPostSampleTimes(m_Id, 0);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetPostSampleTimes = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set channel : Enable channel0 only
	//---------------------------------
	// Enable channel0
	ret = DigSetChannel(m_Id, DIG_CHANNEL0, DIG_ENABLE);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetChannel = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	// Disable channel1
	ret = DigSetChannel(m_Id, DIG_CHANNEL1, DIG_DISABLE);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetChannel = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Set the type of pre-trigger : Auto
	//---------------------------------
	ret = DigSetPreTriggerType(m_Id, DIG_TRIGGERTYPE_AUTO);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigSetPreTriggerType = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Operation start
	//---------------------------------
	ret = DigStart(m_Id);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigStart = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	m_Info.SetWindowText(_T("Start acquisition : Normality completion"));

	//---------------------------------
	// Polling until the operation status is changed to be OFF
	//---------------------------------
	long status;

	do{
		//---------------------------------
		// In order to enable the dialog operation
		//---------------------------------
		MSG msg;
		while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)){
			if (!GetMessage(&msg, NULL, NULL, NULL)){
				break;
			}
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		//---------------------------------
		// Get the number of samples stored in driver memory
		//---------------------------------
		ret = DigGetDriverMemorySamples(m_Id, &m_Samples);
		if (ret != 0){
			DigGetErrorString(ret, error_string);
			wsprintf(szError_string, _T("%S"), error_string);
			cstr.Format(_T("DigGetDriverMemorySamples = %d : %s"), ret, szError_string);
			m_Info.SetWindowText(cstr);
			return;
		}
		cstr.Format(_T("%d"), m_Samples);
		m_Count.SetWindowText(cstr);
		//---------------------------------
		// Get the operation status
		//---------------------------------
		ret = DigGetStatus(m_Id, &status);
		if (ret != 0){
			DigGetErrorString(ret, error_string);
			wsprintf(szError_string, _T("%S"), error_string);
			cstr.Format(_T("DigGetStatus = %d : %s"), ret, szError_string);
			m_Info.SetWindowText(cstr);
			return;
		}
		cstr.Format(_T("%xH"), status);
		m_Status.SetWindowText(cstr);
	} while ((status & DIG_STATUS_BUSY) == DIG_STATUS_BUSY);

	//---------------------------------
	// After operation stop, get the number of samples which are being stored in driver memory
	//---------------------------------
	ret = DigGetDriverMemorySamples(m_Id, &m_Samples);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetDriverMemorySamples = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// Retrieve the acquisition data
	//---------------------------------
	long trigger_point;			// Position of the first data after the establishment of the post-trigger

	if (m_Samples > 0){
		// Adjust to prevent the retrieved number of sampling from exceeding the size of array for storing data
		if (m_Samples > MAX_SAMPLES){
			m_Samples = MAX_SAMPLES;
		}
		ret = DigReadSamples(m_Id, &m_Samples, &m_Data[0], &trigger_point);
		if (ret != 0){
			DigGetErrorString(ret, error_string);
			wsprintf(szError_string, _T("%S"), error_string);
			cstr.Format(_T("DigReadSamples = %d : %s"), ret, szError_string);
			m_Info.SetWindowText(cstr);
			return;
		}
		//---------------------------------
		// Display the retrieved data
		//---------------------------------
		CString temp;
		for (int i = 0; i < m_Samples; i++){
			cstr.Format(_T("%d\t%6.3f\r\n"), i + 1, m_Data[i]);
			temp += cstr;
		}
		m_EditData.SetWindowText(temp);
	}
}

//===============================================
// Get status
//===============================================
void CDataLoggerDlg::OnBnClickedButtonInfo()
{
	CString cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	int		ret;				// Return value
	long	status;				// Status
	long	samples;			// Number of retrieved samples

	//---------------------------------
	// Get the number of samples stored in driver memory
	//---------------------------------
	ret = DigGetDriverMemorySamples(m_Id, &samples);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetDriverMemorySamples = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("%d"), samples);
	m_Count.SetWindowText(cstr);
	//---------------------------------
	// Get the operation status
	//---------------------------------
	ret = DigGetStatus(m_Id, &status);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetStatus = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("%xH"), status);
	m_Status.SetWindowText(cstr);
	m_Info.SetWindowText(_T("Get status : Normality completion"));
}

//===============================================
// Stop acquisition
//===============================================
void CDataLoggerDlg::OnBnClickedButtonStop()
{
	CString cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	int		ret;				// Return value

	//---------------------------------
	// Operation stop
	//---------------------------------
	ret = DigStop(m_Id);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigStop = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	m_Info.SetWindowText(_T("Stop acquisition : Normality completion"));
}

//===============================================
// Save file
//===============================================
void CDataLoggerDlg::OnBnClickedButtonSave()
{
	//---------------------------------
	// When there is no data error is returned
	//---------------------------------
	if (m_Samples == 0){
		m_Info.SetWindowText(_T("There are no acquisition data"));
		return;
	}
	//---------------------------------
	// Save file
	//---------------------------------
	CStdioFile file;				// File name
	CString file_path;				// File Path
	CString cstr;					// For saving string temporarily

	file_path = "DataLogger.csv";	// Set the file path
	//---------------------------------
	// Open file
	//---------------------------------
	if (!file.Open(file_path, CStdioFile::modeCreate | CStdioFile::modeWrite)){
		m_Info.SetWindowText(_T("Open file : Failed"));
		return;
	}
	//---------------------------------
	// Write file
	//---------------------------------
	for (long i = 0; i < m_Samples; i++){
		cstr.Format(_T("%6.3f\n"), m_Data[i]);
		file.WriteString(cstr);
	}
	//---------------------------------
	// Close file
	//---------------------------------
	file.Close();
	m_Info.SetWindowText(_T("Save file : Normality completion"));
}

//===============================================
// Exit handling
//===============================================
void CDataLoggerDlg::OnBnClickedButtonExit()
{
	CString cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	int		ret;				// Return value

	ret = DigExit(m_Id);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigExit = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	m_Info.SetWindowText(_T("Exit : Normality completion"));
}


void CDataLoggerDlg::OnDestroy()
{
	//---------------------------------
	// Exit handling
	//---------------------------------
	DigExit(m_Id);
	CDialogEx::OnDestroy();
}


void CDataLoggerDlg::OnClose()
{
	//---------------------------------
	// Exit handling
	//---------------------------------
	DigExit(m_Id);
	CDialogEx::OnClose();
}
