﻿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>
	/// Sampling の概要の説明です。
	/// </summary>
	public class Sampling : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnCondition;
		private System.Windows.Forms.Button btnStart;
		private System.Windows.Forms.Button btnStop;
		private System.Windows.Forms.Button btnData;
		private System.Windows.Forms.Button btnCount;
		private System.Windows.Forms.Button btnStatus;
		private System.Windows.Forms.Button btnExit;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtCount;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.TextBox txtStatus;
		private System.Windows.Forms.TextBox txtError;
		private System.Windows.Forms.Button btnDioInit;
		private System.Windows.Forms.TextBox txtDeviceName;
		private System.Windows.Forms.TextBox txtReturnCode;
		/// <summary>
		/// 必要なデザイナ変数です。
		/// </summary>
		private System.ComponentModel.Container components = null;

		Cdio  dio = new Cdio();
		public static short	m_Id;								//デバイスID

		private System.Windows.Forms.Button btnDioExit;			
		const	int			DATA_SIZE		=	1000;			//バスマスタ用バッファサイズ
		static uint[]		DataBuff = new uint[DATA_SIZE];	//バスマスタ用バッファ

		GCHandle			    gCh;
		IntPtr				    pDataBuff;


		public Sampling()
		{
			//
			// Windows フォーム デザイナ サポートに必要です。
			//
			InitializeComponent();

			//
			// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
			//
		}

		/// <summary>
		/// 使用されているリソースに後処理を実行します。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディタで変更しないでください。
		/// </summary>
		private void InitializeComponent()
		{
			this.btnDioInit = new System.Windows.Forms.Button();
			this.btnCondition = new System.Windows.Forms.Button();
			this.btnStart = new System.Windows.Forms.Button();
			this.btnStop = new System.Windows.Forms.Button();
			this.btnData = new System.Windows.Forms.Button();
			this.btnCount = new System.Windows.Forms.Button();
			this.btnStatus = new System.Windows.Forms.Button();
			this.btnDioExit = new System.Windows.Forms.Button();
			this.btnExit = new System.Windows.Forms.Button();
			this.label1 = new System.Windows.Forms.Label();
			this.txtDeviceName = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.txtCount = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.label4 = new System.Windows.Forms.Label();
			this.label5 = new System.Windows.Forms.Label();
			this.txtStatus = new System.Windows.Forms.TextBox();
			this.txtError = new System.Windows.Forms.TextBox();
			this.txtReturnCode = new System.Windows.Forms.TextBox();
			this.SuspendLayout();
			// 
			// btnDioInit
			// 
			this.btnDioInit.Location = new System.Drawing.Point(364, 14);
			this.btnDioInit.Name = "btnDioInit";
			this.btnDioInit.Size = new System.Drawing.Size(96, 22);
			this.btnDioInit.TabIndex = 5;
			this.btnDioInit.Text = "DioInit";
			this.btnDioInit.Click += new System.EventHandler(this.btnDioInit_Click);
			// 
			// btnCondition
			// 
			this.btnCondition.Location = new System.Drawing.Point(364, 42);
			this.btnCondition.Name = "btnCondition";
			this.btnCondition.Size = new System.Drawing.Size(96, 22);
			this.btnCondition.TabIndex = 6;
			this.btnCondition.Text = "条件設定...";
			this.btnCondition.Click += new System.EventHandler(this.btnCondition_Click);
			// 
			// btnStart
			// 
			this.btnStart.Location = new System.Drawing.Point(364, 70);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(96, 22);
			this.btnStart.TabIndex = 7;
			this.btnStart.Text = "転送スタート";
			this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(364, 98);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(96, 22);
			this.btnStop.TabIndex = 8;
			this.btnStop.Text = "転送ストップ";
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// btnData
			// 
			this.btnData.Location = new System.Drawing.Point(364, 126);
			this.btnData.Name = "btnData";
			this.btnData.Size = new System.Drawing.Size(96, 22);
			this.btnData.TabIndex = 9;
			this.btnData.Text = "取得データ...";
			this.btnData.Click += new System.EventHandler(this.btnData_Click);
			// 
			// btnCount
			// 
			this.btnCount.Location = new System.Drawing.Point(364, 154);
			this.btnCount.Name = "btnCount";
			this.btnCount.Size = new System.Drawing.Size(96, 22);
			this.btnCount.TabIndex = 10;
			this.btnCount.Text = "転送カウント";
			this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
			// 
			// btnStatus
			// 
			this.btnStatus.Location = new System.Drawing.Point(364, 182);
			this.btnStatus.Name = "btnStatus";
			this.btnStatus.Size = new System.Drawing.Size(96, 22);
			this.btnStatus.TabIndex = 11;
			this.btnStatus.Text = "転送ステータス";
			this.btnStatus.Click += new System.EventHandler(this.btnStatus_Click);
			// 
			// btnDioExit
			// 
			this.btnDioExit.Location = new System.Drawing.Point(364, 210);
			this.btnDioExit.Name = "btnDioExit";
			this.btnDioExit.Size = new System.Drawing.Size(96, 22);
			this.btnDioExit.TabIndex = 12;
			this.btnDioExit.Text = "DioExit";
			this.btnDioExit.Click += new System.EventHandler(this.btnDioExit_Click);
			// 
			// btnExit
			// 
			this.btnExit.Location = new System.Drawing.Point(364, 238);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(96, 22);
			this.btnExit.TabIndex = 13;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(24, 17);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(64, 16);
			this.label1.TabIndex = 9;
			this.label1.Text = "デバイス名：";
			// 
			// txtDeviceName
			// 
			this.txtDeviceName.Location = new System.Drawing.Point(104, 16);
			this.txtDeviceName.Name = "txtDeviceName";
			this.txtDeviceName.Size = new System.Drawing.Size(96, 19);
			this.txtDeviceName.TabIndex = 0;
			this.txtDeviceName.Text = "DIO000";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(24, 157);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(72, 16);
			this.label2.TabIndex = 11;
			this.label2.Text = "転送カウント：";
			// 
			// txtCount
			// 
			this.txtCount.Location = new System.Drawing.Point(104, 156);
			this.txtCount.Name = "txtCount";
			this.txtCount.Size = new System.Drawing.Size(232, 19);
			this.txtCount.TabIndex = 1;
			this.txtCount.Text = "";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(24, 185);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 16);
			this.label3.TabIndex = 13;
			this.label3.Text = "ステータス：";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(24, 213);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 16);
			this.label4.TabIndex = 14;
			this.label4.Text = "エラー：";
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(24, 241);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(72, 16);
			this.label5.TabIndex = 15;
			this.label5.Text = "戻り値：";
			// 
			// txtStatus
			// 
			this.txtStatus.Location = new System.Drawing.Point(104, 184);
			this.txtStatus.Name = "txtStatus";
			this.txtStatus.Size = new System.Drawing.Size(232, 19);
			this.txtStatus.TabIndex = 2;
			this.txtStatus.Text = "";
			// 
			// txtError
			// 
			this.txtError.Location = new System.Drawing.Point(104, 212);
			this.txtError.Name = "txtError";
			this.txtError.Size = new System.Drawing.Size(232, 19);
			this.txtError.TabIndex = 3;
			this.txtError.Text = "";
			// 
			// txtReturnCode
			// 
			this.txtReturnCode.Location = new System.Drawing.Point(104, 240);
			this.txtReturnCode.Name = "txtReturnCode";
			this.txtReturnCode.Size = new System.Drawing.Size(232, 19);
			this.txtReturnCode.TabIndex = 4;
			this.txtReturnCode.Text = "";
			// 
			// Sampling
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
			this.ClientSize = new System.Drawing.Size(482, 278);
			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 = "サンプリング";
			this.Load += new System.EventHandler(this.Sampling_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// アプリケーションのメイン エントリ ポイントです。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Sampling());
		}

		//===================================================
		//	ダイアログの初期化
		//===================================================
		private void Sampling_Load(object sender, System.EventArgs e)
		{
			//-----------------------------------
			//	画面表示の初期化
			//-----------------------------------
			txtDeviceName.Text= "DIO000";

			//-----------------------------------
			// DataBuffにPinnedタイプハンドルを割り当てます
			//-----------------------------------
			if (gCh.IsAllocated == false)
			{
				gCh = GCHandle.Alloc(DataBuff, GCHandleType.Pinned);
			}

		}

		//===================================================
		//	DioInit()
		//===================================================
		private void btnDioInit_Click(object sender, System.EventArgs e)
		{
			int	Ret;
			string	ErrorString;
			//-----------------------------------
			//	初期化処理
			//-----------------------------------
			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)
		{
			//-----------------------------------
			// GCHandleを解放します
			//-----------------------------------
			if (gCh.IsAllocated == true)
			{
				gCh.Free();
			}

			this.Close();
		}

		//===================================================
		//	条件設定
		//===================================================
		private void btnCondition_Click(object sender, System.EventArgs e)
		{
			Condition	ConditionDlg = new Condition();
			//-----------------------------------
			// 条件設定ダイアログを開く
			//-----------------------------------
			ConditionDlg.ShowDialog();
			ConditionDlg.Dispose();
		}

		//===================================================
		//	転送スタート
		//===================================================
		private void btnStart_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			string	ErrorString;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			//-----------------------------------
			// メッセージ通知設定
			//-----------------------------------
			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;
			}
			//-----------------------------------
			// FIFOのリセット(入力)
			//-----------------------------------
			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;
			}
			//-----------------------------------
			// データバッファを設定
			//-----------------------------------
			Array.Clear(DataBuff, 0, DataBuff.Length);
			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;
			}
			//-----------------------------------
			// 転送スタート
			//-----------------------------------
			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 = "";
		}

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

		//===================================================
		//	取得データ
		//===================================================
		private void btnData_Click(object sender, System.EventArgs e)
		{
			uint	i;
			StreamWriter	fp;
			string	szFileName = "SamplingData.csv";
			string	buf = new string(' ', 100);
			//-----------------------------------
			// ファイルを開く
			//-----------------------------------
			fp = File.CreateText(szFileName);
			//-----------------------------------
			// ファイルに取得データを書き込みます。
			//-----------------------------------
			for (i = 0; i < DATA_SIZE; i++)
			{
				buf = string.Format("{0:d8}: ,{1:X8}", i, DataBuff[i]);
				fp.WriteLine(buf); 
			}
			//-----------------------------------
			// ファイルを閉じる
			//-----------------------------------
			fp.Close();
			//-----------------------------------
			// notepad
			//-----------------------------------
			Process Pro = Process.Start("notepad.exe", szFileName);
			return;
		}

		

		//===================================================
		//	転送カウント
		//===================================================
		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;
			//-----------------------------------
			// 転送カウント取得
			//-----------------------------------
			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;
		}

		//===================================================
		//	転送ステータス
		//===================================================
		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;
			//-----------------------------------
			// 転送ステータス取得
			//-----------------------------------
			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;
			}
			//-----------------------------------
			// ステータス
			//-----------------------------------
			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;
			//-----------------------------------
			// エラー
			//-----------------------------------
			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;
		}
		
		//===================================================
		// メッセージ処理
		//===================================================
		protected override void WndProc(ref Message m)
		{
			int	dwRet;
			short	Direction = (short)CdioConst.DIODM_DIR_IN;
			uint	Count, Carry;
			string	csMsg;
			switch (m.Msg)
			{
				//---------------------------------------------------
				// 転送完了メッセージ
				//---------------------------------------------------
				case ((int)CdioConst.DIO_DMM_STOP):
					txtStatus.Text = "Stopped!";
					goto case ((int)CdioConst.DIO_DMM_COUNT);
				
				//---------------------------------------------------
				// 指定個数転送完了メッセージ
				//---------------------------------------------------
				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);
		}

	}
}
