
// LoadConfigDlg.cpp : implementation file
//

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

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CLoadConfigDlg dialog



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

void CLoadConfigDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATUS, m_Status);
	DDX_Control(pDX, IDC_EDIT_INFO, m_Info);
	DDX_Control(pDX, IDC_EDIT_DEVICE_INFO, m_DeviceInfo);
	DDX_Control(pDX, IDC_EDIT_DEVICE, m_DeviceName);
}

BEGIN_MESSAGE_MAP(CLoadConfigDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_INIT, &CLoadConfigDlg::OnBnClickedButtonInit)
	ON_BN_CLICKED(IDC_BUTTON_LOAD, &CLoadConfigDlg::OnBnClickedButtonLoad)
	ON_BN_CLICKED(IDC_BUTTON_START, &CLoadConfigDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_INFO, &CLoadConfigDlg::OnBnClickedButtonInfo)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CLoadConfigDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_EXIT, &CLoadConfigDlg::OnBnClickedButtonExit)
	ON_WM_DESTROY()
	ON_WM_CLOSE()
END_MESSAGE_MAP()


// CLoadConfigDlg message handlers

BOOL CLoadConfigDlg::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"));

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


//===============================================
// Init handling
//===============================================
void CLoadConfigDlg::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"));
}

//===============================================
// Read setting file
//===============================================
void CLoadConfigDlg::OnBnClickedButtonLoad()
{
	CString cstr;				// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	char	file_name[256];		// File name
	long	ret;				// Return value

	//---------------------------------
	// Show FileOpen dialog
	//---------------------------------
	CFileDialog dlg(TRUE, _T("xml"), NULL,
		OFN_HIDEREADONLY | OFN_FILEMUSTEXIST,
		_T("xml file (*.xml)|*.xml|"), this);
	if (dlg.DoModal() == IDOK){
		//---------------------------------
		// When OK button was clicked, read the setting file
		//---------------------------------
		CString file_path;				// File path
		file_path = dlg.GetPathName();	// Get the file path

		//---------------------------------
		// Read the setting file
		//---------------------------------
		sprintf_s(file_name, "%S", file_path.GetBuffer(0));
		ret = DigLoadConfig(m_Id, file_name);
		if (ret != 0){
			DigGetErrorString(ret, error_string);
			wsprintf(szError_string, _T("%S"), error_string);
			cstr.Format(_T("DigLoadConfig = %d : %s"), ret, szError_string);
			m_Info.SetWindowText(cstr);
			return;
		}
		m_Info.SetWindowText(_T("Read Setting file : Normality completion"));
	}
}

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

	//---------------------------------
	// Initialize variable
	//---------------------------------
	m_Records = 0;

	//---------------------------------
	// Get the setup information and display
	//---------------------------------
	OnBnClickedButtonInfo();

	//---------------------------------
	// 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;				// 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 records which are being stored in driver memory
		//---------------------------------
		ret = DigGetDriverMemoryRecords(m_Id, &m_Records);
		if (ret != 0){
			DigGetErrorString(ret, error_string);
			wsprintf(szError_string, _T("%S"), error_string);
			cstr.Format(_T("DigGetDriverMemoryRecords = %d : %s"), ret, szError_string);
			m_Info.SetWindowText(cstr);
			return;
		}
		//---------------------------------
		// If there are records in driver memory, retrieve the data from the new side
		//---------------------------------
		if (m_Records > 0 || m_Records == -1){
			ret = DigReadLatestRecords(m_Id, DIG_RECORD_DATA, 1, &m_Data[0], NULL, NULL);
			if (ret != 0){
				DigGetErrorString(ret, error_string);
				wsprintf(szError_string, _T("%S"), error_string);
				cstr.Format(_T("DigReadLatestRecords = %d : %s"), ret, szError_string);
				m_Info.SetWindowText(cstr);
				return;
			}
			//-----------------------------------
			// Draw graph
			//-----------------------------------
			DrawGraph();
		}
		//---------------------------------
		// 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 records which are being stored in driver memory
	//---------------------------------
	ret = DigGetDriverMemoryRecords(m_Id, &m_Records);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetDriverMemoryRecords = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	//---------------------------------
	// If there are records in driver memory, retrieve the data
	//---------------------------------
	if (m_Records > 0 || m_Records == -1){
		ret = DigReadLatestRecords(m_Id, DIG_RECORD_DATA, 1, &m_Data[0], NULL, NULL);
		if (ret != 0){
			DigGetErrorString(ret, error_string);
			wsprintf(szError_string, _T("%S"), error_string);
			cstr.Format(_T("DigReadLatestRecords = %d : %s"), ret, szError_string);
			m_Info.SetWindowText(cstr);
			return;
		}
		//-----------------------------------
		// Draw graph
		//-----------------------------------
		DrawGraph();
	}
}

//===============================================
// Show information
//===============================================
void CLoadConfigDlg::OnBnClickedButtonInfo()
{
	CString cstr, cstr_info;	// For saving string temporarily
	char	error_string[256];	// Error string
	TCHAR	szError_string[256];
	long	ret;				// Return value
	long	status;				// Status
	float	sample_rate;		// Sample rate
	float	duty;				// Duty ratio
	float	level;				// Trigger level
	short	slope;				// Trigger direction
	long	count;				// Trigger count

	//---------------------------------
	// 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);
	//-------------------------------------------
	// Display the device information
	//-------------------------------------------
	//---------------------------------
	// Get the sample rate
	//---------------------------------
	ret = DigGetSampleRate(m_Id, &sample_rate);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetSampleRate = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("Sample rate : %.3fHz\r\n"), sample_rate);
	cstr_info += cstr;
	//---------------------------------
	// Get the record length
	//---------------------------------
	ret = DigGetRecordLength(m_Id, &m_RecordLength);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetSampleRate = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("Record length : %d\r\n"), m_RecordLength);
	cstr_info += cstr;
	//---------------------------------
	// Get duty ratio
	//---------------------------------
	ret = DigGetDutyCycle(m_Id, &duty);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetDutyCycle = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("Duty ratio : %.1f\r\n"), duty);
	cstr_info += cstr;
	//---------------------------------
	// Get the number of effective channels
	//---------------------------------
	ret = DigGetChannels(m_Id, &m_Channels);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetSampleRate = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("Number of effective channels : %d\r\n"), m_Channels);
	cstr_info += cstr;
	//---------------------------------
	// Get the trigger information
	//---------------------------------
	ret = DigGetPostTriggerAiEdge(m_Id, &m_TriggerChannel, &level, &slope, &count);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetPostTriggerAiEdge = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("Trigger channel : %d\r\n"), m_TriggerChannel);
	cstr_info += cstr;
	cstr.Format(_T("Trigger level : %.3f\r\n"), level);
	cstr_info += cstr;
	//---------------------------------
	// Get the range information
	//---------------------------------
	ret = DigGetRange(m_Id, m_TriggerChannel, &m_Range);
	if (ret != 0){
		DigGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		cstr.Format(_T("DigGetRange = %d : %s"), ret, szError_string);
		m_Info.SetWindowText(cstr);
		return;
	}
	cstr.Format(_T("Input range : %.3fVPP\r\n"), m_Range);
	cstr_info += cstr;
	//---------------------------------
	// Show the information
	//---------------------------------
	m_DeviceInfo.SetWindowText(cstr_info);
	m_Info.SetWindowText(_T("Show information : Normality completion"));
}

//===============================================
// Stop acquisition
//===============================================
void CLoadConfigDlg::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"));
}

//===============================================
// Exit handling
//===============================================
void CLoadConfigDlg::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 CLoadConfigDlg::OnDestroy()
{
	//---------------------------------
	// Exit handling
	//---------------------------------
	DigExit(m_Id);
	CDialogEx::OnDestroy();
}


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

//===============================================
// Draw graph
//===============================================
void CLoadConfigDlg::DrawGraph()
{
	float	x_unit;				// Drawing unit of X axis
	float	pos_x;				// Drawing coordinate of X axis
	float	pos_y;				// Drawing coordinate of Y axis
	float	old_x;				// For saving the drawing coordinate of X axis
	int		color;				// Pen color
	CWnd	*graph;				// Graph object
	CRect	rect;				// Rect of graph object
	CDC		*dc;				// Device context
	CDC		mem_dc;				// Device context for buffer
	CBitmap	bitmap;				// Bitmap class object
	CPen	*oldpen = NULL;
	//-------------------------------------------
	// Draw the current data in graph
	//-------------------------------------------
	if (m_Channels == 0){
		m_Info.SetWindowText(_T("There are not effective channels."));
		return;
	}
	graph = GetDlgItem(IDC_GRAPH);											// Get the handle of graph object
	dc = graph->GetDC();													// Get the device context of graph object
	graph->GetClientRect(&rect);											// Get the rect of graph object
	bitmap.CreateCompatibleBitmap(dc, rect.right, rect.bottom);				// Create the bitmap which is compatible with the rect of graph object
	mem_dc.CreateCompatibleDC(dc);											// Copy the device context
	HBITMAP h_old_bitmap = (HBITMAP)mem_dc.SelectObject(&bitmap);			// Setup the created bitmap in order to be written
	mem_dc.FillSolidRect(&rect, RGB(255, 255, 255));						// Fill the graph rect with white

	//---------------------------------------------
	// Repeat the drawing handling only for the times which is equal to the number of channels
	//---------------------------------------------
	for (int i = 0; i < m_Channels; i++){
		if (i == 0){
			color = RGB(255, 0, 0);		// Red
		}
		else{
			color = RGB(0, 0, 255);		// Blue
		}
		CPen pen(PS_SOLID, 1, color);											// Create pen
		oldpen = mem_dc.SelectObject(&pen);
		x_unit = (float)rect.Width() / (float)(m_RecordLength);					// Calculate the moving pixel number of X axis for data 1
		pos_y = (float)rect.Height() * ((m_Range / 2) - m_Data[i]) / m_Range;	// Calculate the initial value of Y axis
		if (pos_y >= rect.Height()){
			pos_y = (float)(rect.Height() - 1);									// If the initial value of Y axis exceeds the drawing rect of graph, modify the position
		}
		if (pos_y <= 0){
			pos_y = 1;															// If the initial value of Y axis is lower than the drawing rect of graph, modify the position
		}
		old_x = 0;
		mem_dc.MoveTo((int)old_x, (int)pos_y);									// Move to the initial value
		//---------------------------------------------
		// Repeat the drawing handling only for the times which is equal to the number of acquisition data
		//---------------------------------------------
		for (int j = i; j < m_RecordLength * m_Channels; j += m_Channels){
			pos_x = old_x + x_unit;
			pos_y = (float)rect.Height() * ((m_Range / 2) - m_Data[j]) / m_Range; // Calculate the coordinate of Y axis
			// If the coordinate of Y axis exceeds the drawing rect
			if (pos_y >= rect.Height()){
				pos_y = (float)(rect.Height() - 1);								// Modify the drawing position
			}
			// If the coordinate of Y axis is lower than the drawing rect
			else if (pos_y <= 0){
				pos_y = 1;														// Modify the drawing position
			}
			mem_dc.LineTo((int)pos_x, (int)pos_y);								// Draw in buffer
			old_x = pos_x;
		}
		mem_dc.SelectObject(oldpen);
	}
	//----------------------------------------------
	// Transmit to form
	//----------------------------------------------
	dc->BitBlt(0, 0, rect.right, rect.bottom, &mem_dc, 0, 0, SRCCOPY);

	mem_dc.SelectObject(oldpen);											// Select the defualt pen
	mem_dc.SelectObject(&h_old_bitmap);										// Select the defualt bitmap
	graph->ReleaseDC(dc);													// Release the device context
}