﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using CdioCs;

namespace Sampling
{
	/// <summary>
	/// Summary description for Sampling.
	/// </summary>
	public class Sampling : System.Windows.Forms.Form
	{
		private System.Windows.Forms.TextBox txtReturnCode;
		private System.Windows.Forms.TextBox txtError;
		private System.Windows.Forms.TextBox txtStatus;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox txtCount;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtDeviceName;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button btnExit;
		private System.Windows.Forms.Button btnDioExit;
		private System.Windows.Forms.Button btnStatus;
		private System.Windows.Forms.Button btnCount;
		private System.Windows.Forms.Button btnData;
		private System.Windows.Forms.Button btnStop;
		private System.Windows.Forms.Button btnStart;
		private System.Windows.Forms.Button btnCondition;
		private System.Windows.Forms.Button btnDioInit;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		Cdio				dio = new Cdio();
		const int			DATA_SIZE =	1000;					// Buffer size for busmaster
		public static short	m_Id;								// Device ID
		static uint[]		DataBuff = new uint[DATA_SIZE];		// Buffer for busmaster

		GCHandle			gCh;
		IntPtr				pDataBuff;

		public Sampling()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.txtReturnCode = new System.Windows.Forms.TextBox();
			this.txtError = new System.Windows.Forms.TextBox();
			this.txtStatus = new System.Windows.Forms.TextBox();
			this.label5 = new System.Windows.Forms.Label();
			this.label4 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.txtCount = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.txtDeviceName = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.btnExit = new System.Windows.Forms.Button();
			this.btnDioExit = new System.Windows.Forms.Button();
			this.btnStatus = new System.Windows.Forms.Button();
			this.btnCount = new System.Windows.Forms.Button();
			this.btnData = new System.Windows.Forms.Button();
			this.btnStop = new System.Windows.Forms.Button();
			this.btnStart = new System.Windows.Forms.Button();
			this.btnCondition = new System.Windows.Forms.Button();
			this.btnDioInit = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// txtReturnCode
			// 
			this.txtReturnCode.Location = new System.Drawing.Point(88, 272);
			this.txtReturnCode.Name = "txtReturnCode";
			this.txtReturnCode.Size = new System.Drawing.Size(232, 20);
			this.txtReturnCode.TabIndex = 20;
			this.txtReturnCode.Text = "";
			// 
			// txtError
			// 
			this.txtError.Location = new System.Drawing.Point(88, 240);
			this.txtError.Name = "txtError";
			this.txtError.Size = new System.Drawing.Size(232, 20);
			this.txtError.TabIndex = 19;
			this.txtError.Text = "";
			// 
			// txtStatus
			// 
			this.txtStatus.Location = new System.Drawing.Point(88, 207);
			this.txtStatus.Name = "txtStatus";
			this.txtStatus.Size = new System.Drawing.Size(232, 20);
			this.txtStatus.TabIndex = 18;
			this.txtStatus.Text = "";
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(6, 273);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(72, 19);
			this.label5.TabIndex = 34;
			this.label5.Text = "Return Code:";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(6, 241);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 18);
			this.label4.TabIndex = 33;
			this.label4.Text = "Error:";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(6, 208);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 19);
			this.label3.TabIndex = 31;
			this.label3.Text = "Status:";
			// 
			// txtCount
			// 
			this.txtCount.Location = new System.Drawing.Point(88, 174);
			this.txtCount.Name = "txtCount";
			this.txtCount.Size = new System.Drawing.Size(232, 20);
			this.txtCount.TabIndex = 17;
			this.txtCount.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(6, 176);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(88, 18);
			this.label2.TabIndex = 28;
			this.label2.Text = "Transfer Count:";
			// 
			// txtDeviceName
			// 
			this.txtDeviceName.Location = new System.Drawing.Point(88, 12);
			this.txtDeviceName.Name = "txtDeviceName";
			this.txtDeviceName.Size = new System.Drawing.Size(96, 20);
			this.txtDeviceName.TabIndex = 16;
			this.txtDeviceName.Text = "DIO000";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(6, 13);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(80, 18);
			this.label1.TabIndex = 26;
			this.label1.Text = "Device Name:";
			// 
			// btnExit
			// 
			this.btnExit.Location = new System.Drawing.Point(348, 270);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(96, 25);
			this.btnExit.TabIndex = 32;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnDioExit
			// 
			this.btnDioExit.Location = new System.Drawing.Point(348, 237);
			this.btnDioExit.Name = "btnDioExit";
			this.btnDioExit.Size = new System.Drawing.Size(96, 26);
			this.btnDioExit.TabIndex = 30;
			this.btnDioExit.Text = "DioExit";
			this.btnDioExit.Click += new System.EventHandler(this.btnDioExit_Click);
			// 
			// btnStatus
			// 
			this.btnStatus.Location = new System.Drawing.Point(348, 205);
			this.btnStatus.Name = "btnStatus";
			this.btnStatus.Size = new System.Drawing.Size(96, 25);
			this.btnStatus.TabIndex = 29;
			this.btnStatus.Text = "Transfer Status";
			this.btnStatus.Click += new System.EventHandler(this.btnStatus_Click);
			// 
			// btnCount
			// 
			this.btnCount.Location = new System.Drawing.Point(348, 172);
			this.btnCount.Name = "btnCount";
			this.btnCount.Size = new System.Drawing.Size(96, 26);
			this.btnCount.TabIndex = 27;
			this.btnCount.Text = "Transfer Count";
			this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
			// 
			// btnData
			// 
			this.btnData.Location = new System.Drawing.Point(348, 140);
			this.btnData.Name = "btnData";
			this.btnData.Size = new System.Drawing.Size(96, 25);
			this.btnData.TabIndex = 25;
			this.btnData.Text = "Get Data...";
			this.btnData.Click += new System.EventHandler(this.btnData_Click);
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(348, 107);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(96, 26);
			this.btnStop.TabIndex = 24;
			this.btnStop.Text = "Stop Transfer";
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// btnStart
			// 
			this.btnStart.Location = new System.Drawing.Point(348, 74);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(96, 26);
			this.btnStart.TabIndex = 23;
			this.btnStart.Text = "Start Transfer";
			this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
			// 
			// btnCondition
			// 
			this.btnCondition.Location = new System.Drawing.Point(348, 42);
			this.btnCondition.Name = "btnCondition";
			this.btnCondition.Size = new System.Drawing.Size(96, 25);
			this.btnCondition.TabIndex = 22;
			this.btnCondition.Text = "Set Conditions...";
			this.btnCondition.Click += new System.EventHandler(this.btnCondition_Click);
			// 
			// btnDioInit
			// 
			this.btnDioInit.Location = new System.Drawing.Point(348, 9);
			this.btnDioInit.Name = "btnDioInit";
			this.btnDioInit.Size = new System.Drawing.Size(96, 26);
			this.btnDioInit.TabIndex = 21;
			this.btnDioInit.Text = "DioInit";
			this.btnDioInit.Click += new System.EventHandler(this.btnDioInit_Click);
			// 
			// Sampling
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(456, 302);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.txtReturnCode,
																		  this.txtError,
																		  this.txtStatus,
																		  this.label5,
																		  this.label4,
																		  this.label3,
																		  this.txtCount,
																		  this.label2,
																		  this.txtDeviceName,
																		  this.label1,
																		  this.btnExit,
																		  this.btnDioExit,
																		  this.btnStatus,
																		  this.btnCount,
																		  this.btnData,
																		  this.btnStop,
																		  this.btnStart,
																		  this.btnCondition,
																		  this.btnDioInit});
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "Sampling";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Sampling";
			this.Load += new System.EventHandler(this.Sampling_Load);
			this.Closed += new System.EventHandler(this.Sampling_Closed);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Sampling());
		}

		//===================================================
		//	Dialog init
		//===================================================
		private void Sampling_Load(object sender, System.EventArgs e)
		{
			//-----------------------------------
			// Dialog init
			//-----------------------------------
			txtDeviceName.Text= "DIO000";

			//-----------------------------------
			// Pinned type handle is allocated to DataBuff
			//-----------------------------------
			if (gCh.IsAllocated == false)
			{
				gCh = GCHandle.Alloc(DataBuff, GCHandleType.Pinned);
			}
		}

		//===================================================
		//	Close handle
		//===================================================
		private void Sampling_Closed(object sender, System.EventArgs e)
		{
			int	Ret;

			//-----------------------------------
			// DioExit()
			//-----------------------------------
			Ret	= dio.Exit(m_Id);

			//-----------------------------------
			// GCHandle is freed
			//-----------------------------------
			if (gCh.IsAllocated == true)
			{
				gCh.Free();
			}
		}

		//===================================================
		//	DioInit()
		//===================================================
		private void btnDioInit_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			string	ErrorString;
			//-----------------------------------
			// DioInit
			//-----------------------------------
			Ret = dio.Init(txtDeviceName.Text, out m_Id);

			dio.GetErrorString(Ret, out ErrorString);
			txtReturnCode.Text = "DioInit Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
			return;
		
		}


		//===================================================
		//	DioExit
		//===================================================
		private void btnDioExit_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			string	ErrorString;
			//-----------------------------------
			// DioExit
			//-----------------------------------
			Ret = dio.Exit(m_Id);
			dio.GetErrorString(Ret, out ErrorString);
			txtReturnCode.Text = "DioExit Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
		}

		//===================================================
		//	Exit
		//===================================================
		private void btnExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		//===================================================
		//	Set condition
		//===================================================
		private void btnCondition_Click(object sender, System.EventArgs e)
		{
			Condition	ConditionDlg = new Condition();
			//-----------------------------------
			// Show set condition dialog
			//-----------------------------------
			ConditionDlg.ShowDialog();
			ConditionDlg.Dispose();
		}

		//===================================================
		//	Start transfer
		//===================================================
		private void btnStart_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			string	ErrorString;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			//-----------------------------------
			// Set notification of message
			//-----------------------------------
			Ret = dio.DmSetStopEvent(m_Id, Direction, this.Handle);
			if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(Ret, out ErrorString);
				txtReturnCode.Text = "DioDmSetStopEvent Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
				return;
			}
			Ret = dio.DmSetCountEvent(m_Id, Direction, Condition.dwNumberOfData, this.Handle);
			if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(Ret, out ErrorString);
				txtReturnCode.Text = "DioDmSetCountEvent Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
				return;
			}
			//-----------------------------------
			// Reset FIFO (input)
			//-----------------------------------
			Ret = dio.DmFifoReset(m_Id, (short)CdioConst.DIODM_RESET_FIFO_IN);
			if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(Ret, out ErrorString);
				txtReturnCode.Text = "DioDmFifoReset Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
				return;
			}
			//-----------------------------------
			// Set data buffer
			//-----------------------------------
			Array.Clear(DataBuff, 0, DATA_SIZE);
			//-----------------------------------
			// The fixed pointer to an object is acquired
			//-----------------------------------
			pDataBuff = gCh.AddrOfPinnedObject();
			Ret = dio.DmSetBuffer(m_Id, Direction, pDataBuff, DATA_SIZE, (short)CdioConst.DIODM_WRITE_ONCE);
			if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(Ret, out ErrorString);
				txtReturnCode.Text = "DioDmSetBuffer Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
				return;
			}
			//-----------------------------------
			// Start transfer
			//-----------------------------------
			Ret = dio.DmTransferStart(m_Id, Direction);
			if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(Ret, out ErrorString);
				txtReturnCode.Text = "DioDmTransferStart Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
				return;
			}
			txtCount.Text = "";
			txtStatus.Text = "";
			txtError.Text = "";
		}

		//===================================================
		//	Stop transfer
		//===================================================
		private void btnStop_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			string	ErrorString;
			//-----------------------------------
			// Stop transfer
			//-----------------------------------
			Ret = dio.DmTransferStop(m_Id, Direction);
			dio.GetErrorString(Ret, out ErrorString);
			txtReturnCode.Text = "DioDmTransferStop Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
			return;
		}

		//===================================================
		//	Get data
		//===================================================
		private void btnData_Click(object sender, System.EventArgs e)
		{
			uint			i;
			StreamWriter	fp;
			string			szFileName = "SamplingData.csv";
			string			buf = new string(' ', 100);
			//-----------------------------------
			// Open file
			//-----------------------------------
			fp = File.CreateText(szFileName);
			//-----------------------------------
			// Write data into file
			//-----------------------------------
			for (i = 0; i < DATA_SIZE; i++)
			{
				buf = string.Format("{0:d8}: ,{1:X8}", i, DataBuff[i]);
				fp.WriteLine(buf); 
			}
			//-----------------------------------
			// Close file
			//-----------------------------------
			fp.Close();
			//-----------------------------------
			// notepad
			//-----------------------------------
			Process Pro = Process.Start("notepad.exe", szFileName);
			return;
		}

		

		//===================================================
		//	Transfer count
		//===================================================
		private void btnCount_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			uint	Count = 0, Carry = 0;
			string	csMsg;
			string	ErrorString;
			//-----------------------------------
			// Get transfer count
			//-----------------------------------
			Ret = dio.DmGetCount(m_Id, Direction, out Count,  out Carry);
			dio.GetErrorString(Ret, out ErrorString);
			txtReturnCode.Text = "DioDmGetCount Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
			if (Ret == (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				csMsg = string.Format("{0:d}", Count);
				txtCount.Text = csMsg;
			}
			return;
		}

		//===================================================
		//	Transfer status
		//===================================================
		private void btnStatus_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			uint	Status, Err;
			string	csMsg;
			string	ErrorString;
			//-----------------------------------
			// Get transfer status
			//-----------------------------------
			Ret = dio.DmGetStatus(m_Id, Direction, out Status, out Err);
			dio.GetErrorString(Ret, out ErrorString);
			txtReturnCode.Text = "DioDmGetStatus Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
			if (Ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				return;
			}
			//-----------------------------------
			// Status
			//-----------------------------------
			csMsg = "";
			if ((Status & (uint)CdioConst.DIODM_STATUS_BMSTOP) != 0)
			{
				csMsg += "BmStop,";
			}
			if ((Status & (uint)CdioConst.DIODM_STATUS_PIOSTART) != 0)
			{
				csMsg += "PioStart,";
			}
			if ((Status & (uint)CdioConst.DIODM_STATUS_PIOSTOP) != 0)
			{
				csMsg += "PioStop,";
			}
			if ((Status & (uint)CdioConst.DIODM_STATUS_TRGIN) != 0)
			{
				csMsg += "TrgIn,";
			}
			if ((Status & (uint)CdioConst.DIODM_STATUS_OVERRUN) != 0)
			{
				csMsg += "Overrun";
			}
			txtStatus.Text = csMsg;
			//-----------------------------------
			// Error
			//-----------------------------------
			csMsg = "";
			if ((Err & (uint)CdioConst.DIODM_STATUS_FIFOEMPTY) != 0)
			{
				csMsg += "FifoEmpty,";
			}
			if ((Err & (uint)CdioConst.DIODM_STATUS_FIFOFULL) != 0)
			{
				csMsg += "FifoFull,";
			}
			if ((Err & (uint)CdioConst.DIODM_STATUS_SGOVERIN) != 0)
			{
				csMsg += "S/GOverIn,";
			}
			if ((Err & (uint)CdioConst.DIODM_STATUS_TRGERR) != 0)
			{
				csMsg += "TrgErr,";
			}
			if ((Err & (uint)CdioConst.DIODM_STATUS_CLKERR) != 0)
			{
				csMsg += "ClkErr,";
			}
			if ((Err & (uint)CdioConst.DIODM_STATUS_SLAVEHALT) != 0)
			{
				csMsg += "SlaveHalt,";
			}
			if ((Err & (uint)CdioConst.DIODM_STATUS_MASTERHALT) != 0)
			{
				csMsg += "MasterHalt";
			}
			txtError.Text = csMsg;
		}
		
		//===================================================
		//	Messange handler
		//===================================================
		protected override void WndProc(ref Message m)
		{
			int		dwRet;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			uint	Count, Carry;
			string	csMsg;
			switch (m.Msg)
			{
				//---------------------------------------------------
				// Transfer stop message
				//---------------------------------------------------
				case ((int)CdioConst.DIO_DMM_STOP):
					txtStatus.Text = "Stopped!";
					goto case ((int)CdioConst.DIO_DMM_COUNT);
				
				//---------------------------------------------------
				// Transfer specified number of data completion message
				//---------------------------------------------------
				case ((int)CdioConst.DIO_DMM_COUNT):			
					//-----------------------------------
					// get count
					//-----------------------------------
					dwRet = dio.DmGetCount(m_Id, Direction, out Count, out Carry);
					csMsg = string.Format("{0:d}", Count);
					txtCount.Text = csMsg;
					break;
				default:
					break;
			}
			base.WndProc(ref m);
		}
	}
}
