
// GeneratingDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Generating.h"
#include "GeneratingDlg.h"
#include "afxdialogex.h"
#include "ConditionDlg.h"
#include "CDio.h"

#define					DATA_SIZE	1000		// buffer size for busmaster

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

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CGeneratingDlg dialog



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

void CGeneratingDlg::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(CGeneratingDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_DIO_INIT, &CGeneratingDlg::OnBnClickedButtonDioInit)
	ON_BN_CLICKED(IDC_BUTTON_CONDITION, &CGeneratingDlg::OnBnClickedButtonCondition)
	ON_BN_CLICKED(IDC_BUTTON_OUT_DATA, &CGeneratingDlg::OnBnClickedButtonOutData)
	ON_BN_CLICKED(IDC_BUTTON_SET_DATA, &CGeneratingDlg::OnBnClickedButtonSetData)
	ON_BN_CLICKED(IDC_BUTTON_START, &CGeneratingDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CGeneratingDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_COUNT, &CGeneratingDlg::OnBnClickedButtonCount)
	ON_BN_CLICKED(IDC_BUTTON_STATUS, &CGeneratingDlg::OnBnClickedButtonStatus)
	ON_BN_CLICKED(IDC_BUTTON_DIO_EXIT, &CGeneratingDlg::OnBnClickedButtonDioExit)
	ON_BN_CLICKED(IDC_BUTTON_EXIT, &CGeneratingDlg::OnBnClickedButtonExit)
	ON_WM_CLOSE()
END_MESSAGE_MAP()


// CGeneratingDlg message handlers

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


//===================================================
//	DioInit()
//===================================================
void CGeneratingDlg::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 CGeneratingDlg::OnBnClickedButtonCondition()
{
	CConditionDlg	dlg;

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

//===================================================
//	Display output data
//===================================================
void CGeneratingDlg::OnBnClickedButtonOutData()
{
	TCHAR			szFileName[] = _T("Generating.csv");
	char			buf[100];
	CString			str;
	WIN32_FIND_DATA	FindFileData;
	HANDLE			hFind;

	//-----------------------------------
	// Find output data file
	//-----------------------------------
	if ((hFind = FindFirstFile(szFileName, &FindFileData)) == INVALID_HANDLE_VALUE){
		//-----------------------------------
		// Create output data file
		//-----------------------------------
		InitialDataFile(szFileName);
	}
	else{
		FindClose(hFind);
	}
	//-----------------------------------
	// notepad
	//-----------------------------------
	sprintf_s(buf, sizeof(buf), "notepad.exe %S", szFileName);
	WinExec(buf, SW_SHOW);
	return;
}

//===================================================
//	Set output data
//===================================================
void CGeneratingDlg::OnBnClickedButtonSetData()
{
	FILE			*fp;
	TCHAR			szFileName[] = _T("Generating.csv");
	unsigned long	i, dummy;
	CString			str;
	TCHAR			buf[100];
	WIN32_FIND_DATA	FindFileData;
	HANDLE			hFind;

	//-----------------------------------
	// Find output data file
	//-----------------------------------
	if ((hFind = FindFirstFile(szFileName, &FindFileData)) == INVALID_HANDLE_VALUE){
		//-----------------------------------
		// Create output data file
		//-----------------------------------
		InitialDataFile(szFileName);
	}
	else{
		FindClose(hFind);
	}
	//-----------------------------------
	// Open file
	//-----------------------------------
	if ((_tfopen_s(&fp, szFileName, _T("r"))) != 0) {
		str.Format(_T("fopen : file open error"));
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	// Read data from output data file
	//-----------------------------------
	for (i = 0; i < DATA_SIZE; i++) {
		_fgetts(buf, sizeof(buf), fp);
		_stscanf_s(buf, _T("%8d: ,%08X\n"), &dummy, &BmBuffer[i]);
	}
	//-----------------------------------
	// Close file
	//-----------------------------------
	fclose(fp);
}

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

	//-----------------------------------
	// Init
	//-----------------------------------
	m_TransCount.SetWindowText(_T(""));
	m_Status.SetWindowText(_T(""));
	m_Error.SetWindowText(_T(""));
	//-----------------------------------
	// Set transfer stop event
	//-----------------------------------
	ret = DioDmSetStopEvent(Id, DIODM_DIR_OUT, 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;
	}
	//-----------------------------------
	// Set specified number transfer completion event
	//-----------------------------------
	ret = DioDmSetCountEvent(Id, DIODM_DIR_OUT, 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 (output)
	//-----------------------------------
	ret = DioDmFifoReset(Id, DIODM_RESET_FIFO_OUT);
	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
	//-----------------------------------
	ret = DioDmSetBuffer(Id, DIODM_DIR_OUT, BmBuffer, DATA_SIZE, IsRing);
	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_OUT);
	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;
}

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

	//-----------------------------------
	// Stop transfer
	//-----------------------------------
	ret = DioDmTransferStop(Id, DIODM_DIR_OUT);
	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;
}

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

	//-----------------------------------
	// Get transfer count
	//-----------------------------------
	ret = DioDmGetCount(Id, DIODM_DIR_OUT, &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);
	str.Format(_T("%d"), count);
	m_TransCount.SetWindowText(str);
}

//===================================================
//	Transfer status
//===================================================
void CGeneratingDlg::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_OUT, &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 CGeneratingDlg::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 CGeneratingDlg::OnBnClickedButtonExit()
{
	OnOK();
}

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

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

	CDialogEx::OnClose();
}

//===================================================
//	Create output data file
//===================================================
void CGeneratingDlg::InitialDataFile(TCHAR *szFileName)
{
	FILE			*fp;
	TCHAR			buf[100];
	CString			str;
	unsigned long	i;

	//-----------------------------------
	// Open file
	//-----------------------------------
	if (_tfopen_s(&fp, szFileName, _T("w")) != 0) {
		str.Format(_T("fopen : file open error"));
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	// Create file 
	//-----------------------------------
	for (i = 0; i < DATA_SIZE; i++) {
		wsprintf(buf, _T("%8d: ,%08X\n"), i, i);
		_fputts(buf, fp);
	}
	//-----------------------------------
	// Close file
	//-----------------------------------
	fclose(fp);
	return;
}

//===================================================
//	Event message routine
//===================================================
LRESULT CGeneratingDlg::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_OUT, &count, &carry);
		str.Format(_T("%d"), count);
		m_TransCount.SetWindowText(str);
	}

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

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