﻿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.Globalization;
using System.Runtime.InteropServices;

using CdioCs;

namespace Generating
{
	/// <summary>
	/// Generating の概要の説明です。
	/// </summary>
	public class Generating : System.Windows.Forms.Form
	{
		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.Label label2;
		private System.Windows.Forms.TextBox txtDeviceName;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.Button btnExit;
		private System.Windows.Forms.Button btnDioExit;
		private System.Windows.Forms.Button btnStatus;
		private System.Windows.Forms.Button btnCondition;
		private System.Windows.Forms.Button btnDioInit;
		private System.Windows.Forms.TextBox txtReturn;
		private System.Windows.Forms.Button btnStop;
		private System.Windows.Forms.Button btnStart;
		private System.Windows.Forms.Button btnSetData;
		private System.Windows.Forms.Button btnOutData;
		private System.Windows.Forms.Button btnCount;
		private System.Windows.Forms.TextBox txtCount;
		/// <summary>
		/// 必要なデザイナ変数です。
		/// </summary>
		private System.ComponentModel.Container components = null;

		Cdio				dio			= new Cdio();
		const int			DATA_SIZE	= 1000;					// バスマスタ用バッファサイズ
		public static short	Id;
		static uint[]		BmBuffer	= new uint[DATA_SIZE];	// バスマスタ用バッファ

		GCHandle			    gCh;
		IntPtr				    pBmBuf;

		public Generating()
		{
			//
			// 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.txtReturn = 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.label6 = 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.btnStop = new System.Windows.Forms.Button();
			this.btnStart = new System.Windows.Forms.Button();
			this.btnSetData = new System.Windows.Forms.Button();
			this.btnOutData = new System.Windows.Forms.Button();
			this.btnCondition = new System.Windows.Forms.Button();
			this.btnDioInit = new System.Windows.Forms.Button();
			this.btnCount = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// txtReturn
			// 
			this.txtReturn.Location = new System.Drawing.Point(100, 288);
			this.txtReturn.Name = "txtReturn";
			this.txtReturn.Size = new System.Drawing.Size(232, 19);
			this.txtReturn.TabIndex = 4;
			this.txtReturn.Text = "";
			// 
			// txtError
			// 
			this.txtError.Location = new System.Drawing.Point(100, 258);
			this.txtError.Name = "txtError";
			this.txtError.Size = new System.Drawing.Size(232, 19);
			this.txtError.TabIndex = 3;
			this.txtError.Text = "";
			// 
			// txtStatus
			// 
			this.txtStatus.Location = new System.Drawing.Point(100, 228);
			this.txtStatus.Name = "txtStatus";
			this.txtStatus.Size = new System.Drawing.Size(232, 19);
			this.txtStatus.TabIndex = 2;
			this.txtStatus.Text = "";
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(18, 289);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(72, 16);
			this.label5.TabIndex = 34;
			this.label5.Text = "戻り値：";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(18, 259);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 16);
			this.label4.TabIndex = 33;
			this.label4.Text = "エラー：";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(18, 229);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 16);
			this.label3.TabIndex = 32;
			this.label3.Text = "ステータス：";
			// 
			// txtCount
			// 
			this.txtCount.Location = new System.Drawing.Point(100, 198);
			this.txtCount.Name = "txtCount";
			this.txtCount.Size = new System.Drawing.Size(232, 19);
			this.txtCount.TabIndex = 1;
			this.txtCount.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(18, 199);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(72, 16);
			this.label2.TabIndex = 30;
			this.label2.Text = "転送カウント：";
			// 
			// txtDeviceName
			// 
			this.txtDeviceName.Location = new System.Drawing.Point(100, 18);
			this.txtDeviceName.Name = "txtDeviceName";
			this.txtDeviceName.Size = new System.Drawing.Size(96, 19);
			this.txtDeviceName.TabIndex = 0;
			this.txtDeviceName.Text = "";
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(18, 19);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(64, 16);
			this.label6.TabIndex = 28;
			this.label6.Text = "デバイス名：";
			// 
			// btnExit
			// 
			this.btnExit.Location = new System.Drawing.Point(356, 286);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(96, 22);
			this.btnExit.TabIndex = 14;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnDioExit
			// 
			this.btnDioExit.Location = new System.Drawing.Point(356, 256);
			this.btnDioExit.Name = "btnDioExit";
			this.btnDioExit.Size = new System.Drawing.Size(96, 22);
			this.btnDioExit.TabIndex = 13;
			this.btnDioExit.Text = "DioExit";
			this.btnDioExit.Click += new System.EventHandler(this.btnDioExit_Click);
			// 
			// btnStatus
			// 
			this.btnStatus.Location = new System.Drawing.Point(356, 226);
			this.btnStatus.Name = "btnStatus";
			this.btnStatus.Size = new System.Drawing.Size(96, 22);
			this.btnStatus.TabIndex = 12;
			this.btnStatus.Text = "転送ステータス";
			this.btnStatus.Click += new System.EventHandler(this.btnStatus_Click);
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(356, 166);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(96, 22);
			this.btnStop.TabIndex = 10;
			this.btnStop.Text = "転送ストップ";
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// btnStart
			// 
			this.btnStart.Location = new System.Drawing.Point(356, 136);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(96, 22);
			this.btnStart.TabIndex = 9;
			this.btnStart.Text = "転送スタート";
			this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
			// 
			// btnSetData
			// 
			this.btnSetData.Location = new System.Drawing.Point(356, 106);
			this.btnSetData.Name = "btnSetData";
			this.btnSetData.Size = new System.Drawing.Size(96, 22);
			this.btnSetData.TabIndex = 8;
			this.btnSetData.Text = "データセット";
			this.btnSetData.Click += new System.EventHandler(this.btnSetData_Click);
			// 
			// btnOutData
			// 
			this.btnOutData.Location = new System.Drawing.Point(356, 76);
			this.btnOutData.Name = "btnOutData";
			this.btnOutData.Size = new System.Drawing.Size(96, 22);
			this.btnOutData.TabIndex = 7;
			this.btnOutData.Text = "出力データ...";
			this.btnOutData.Click += new System.EventHandler(this.btnOutData_Click);
			// 
			// btnCondition
			// 
			this.btnCondition.Location = new System.Drawing.Point(356, 46);
			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);
			// 
			// btnDioInit
			// 
			this.btnDioInit.Location = new System.Drawing.Point(356, 16);
			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);
			// 
			// btnCount
			// 
			this.btnCount.Location = new System.Drawing.Point(356, 196);
			this.btnCount.Name = "btnCount";
			this.btnCount.Size = new System.Drawing.Size(96, 22);
			this.btnCount.TabIndex = 11;
			this.btnCount.Text = "転送カウント";
			this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
			// 
			// Generating
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
			this.ClientSize = new System.Drawing.Size(472, 326);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.btnCount,
																		  this.txtReturn,
																		  this.txtError,
																		  this.txtStatus,
																		  this.label5,
																		  this.label4,
																		  this.label3,
																		  this.txtCount,
																		  this.label2,
																		  this.txtDeviceName,
																		  this.label6,
																		  this.btnExit,
																		  this.btnDioExit,
																		  this.btnStatus,
																		  this.btnStop,
																		  this.btnStart,
																		  this.btnSetData,
																		  this.btnOutData,
																		  this.btnCondition,
																		  this.btnDioInit});
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "Generating";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "ジェネレーティング";
			this.Load += new System.EventHandler(this.Generating_Load);
			this.Closed += new System.EventHandler(this.Generating_Closed);
			this.ResumeLayout(false);

		}
		#endregion

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

		//===================================================
		//	ダイアログ初期化
		//===================================================
		private void Generating_Load(object sender, System.EventArgs e)
		{
			//-----------------------------------
			// 画面表示の初期化
			//-----------------------------------
			txtDeviceName.Text = "DIO000";
			//-----------------------------------
			// BmBufferにPinnedタイプハンドルを割り当てます
			//-----------------------------------
			if (gCh.IsAllocated == false)
			{
				gCh = GCHandle.Alloc(BmBuffer, GCHandleType.Pinned);
			}
		}

		//===================================================
		//	終了時処理
		//===================================================
		private void Generating_Closed(object sender, System.EventArgs e)
		{
			int	ret;

			//-----------------------------------
			// 終了処理
			//-----------------------------------
			ret	= dio.Exit(Id);
			//-----------------------------------
			// GCHandleを解放します
			//-----------------------------------
			if (gCh.IsAllocated == true)
			{
				gCh.Free();
			}	
		}

		//===================================================
		//	DioInit()
		//===================================================
		private void btnDioInit_Click(object sender, System.EventArgs e)
		{
			string	str;
			string	error_string = new string(' ', 256);
			int		ret;
	
			//-----------------------------------
			// 初期化処理
			//-----------------------------------
			ret = dio.Init(txtDeviceName.Text, out Id);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioInit ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

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

		//===================================================
		//	出力データ表示
		//===================================================
		private void btnOutData_Click(object sender, System.EventArgs e)
		{
			string	szFileName = "Generating.csv";
			string	buf = new string(' ', 100);

			//-----------------------------------
			// 出力データファイルが存在しなければ
			//-----------------------------------
			if (File.Exists(szFileName) == false)
			{
				//-----------------------------------
				// 出力データファイル作成
				//-----------------------------------
				InitialDataFile(szFileName);
			}
			//-----------------------------------
			// notepad
			//-----------------------------------
			Process Pro = Process.Start("notepad.exe", szFileName);
			return;
		}

		//===================================================
		//	出力データ設定
		//===================================================
		private void btnSetData_Click(object sender, System.EventArgs e)
		{
			StreamReader	fp;
			string			szFileName = "Generating.csv";
			uint			i;
			string			buf = new string(' ', 100);

			//-----------------------------------
			// 出力データファイルが存在しなければ
			//-----------------------------------
			if (File.Exists(szFileName) == false)
			{
				//-----------------------------------
				// 出力データファイル作成
				//-----------------------------------
				InitialDataFile(szFileName);
			}
			//-----------------------------------
			// ファイルオープン
			//-----------------------------------
			fp = new StreamReader(szFileName);
			//-----------------------------------
			// 出力データファイルからバスマスタ用バッファにデータを設定
			//-----------------------------------
			for (i = 0; i < DATA_SIZE; i++) 
			{
				buf = fp.ReadLine();
				buf = buf.Substring(11, 8);
				BmBuffer[i] = uint.Parse(buf, NumberStyles.HexNumber);
			}
			//-----------------------------------
			// ファイルクローズ
			//-----------------------------------
			fp.Close();
		}

		//===================================================
		//	バスマスタ転送開始
		//===================================================
		private void btnStart_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			string	str;
			int		ret;

			//-----------------------------------
			// 表示初期化
			//-----------------------------------
			txtCount.Text = "";
			txtStatus.Text = "";
			txtError.Text = "";
			//-----------------------------------
			// 転送完了イベント設定
			//-----------------------------------
			ret = dio.DmSetStopEvent(Id, (short)CdioConst.DIODM_DIR_OUT, this.Handle);
			if (ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmSetStopEvent ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// 指定個数転送完了イベント設定
			//-----------------------------------
			ret = dio.DmSetCountEvent(Id, (short)CdioConst.DIODM_DIR_OUT, Condition.NumberOfData, this.Handle);
			if (ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmSetCountEvent ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// FIFOのリセット
			//-----------------------------------
			ret = dio.DmFifoReset(Id, (short)CdioConst.DIODM_RESET_FIFO_OUT);
			if (ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmFifoReset ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// データバッファの設定
			//-----------------------------------
			pBmBuf = gCh.AddrOfPinnedObject();
			ret = dio.DmSetBuffer(Id, (short)CdioConst.DIODM_DIR_OUT, pBmBuf, DATA_SIZE, Condition.IsRing);
			if (ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmSetBuffer ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// バスマスタ転送開始
			//-----------------------------------
			ret = dio.DmTransferStart(Id, (short)CdioConst.DIODM_DIR_OUT);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmTransferStart ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

		//===================================================
		//	バスマスタ転送停止
		//===================================================
		private void btnStop_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			string	str;
			int		ret;

			//-----------------------------------
			// バスマスタ転送停止
			//-----------------------------------
			ret = dio.DmTransferStop(Id, (short)CdioConst.DIODM_DIR_OUT);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmTransferStop ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

		//===================================================
		//	転送カウント数取得
		//===================================================
		private void btnCount_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			int		ret;
			string	str;
			uint	count, carry;

			//-----------------------------------
			// 転送カウント数取得
			//-----------------------------------
			ret = dio.DmGetCount(Id, (short)CdioConst.DIODM_DIR_OUT, out count, out carry);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmGetCount ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			str = string.Format("{0:d}", count);
			txtCount.Text = str;
		}

		//===================================================
		//	転送ステータス取得
		//===================================================
		private void btnStatus_Click(object sender, System.EventArgs e)
		{
			uint	status, err;
			string	error_string = new string(' ', 256);
			string	str;
			int		ret;

			//-----------------------------------
			// 転送ステータス取得
			//-----------------------------------
			ret = dio.DmGetStatus(Id, (short)CdioConst.DIODM_DIR_OUT, out status, out err);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmGetStatus ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			if(ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				return;
			}
			// Status
			str = "";
			if ((status & (uint)CdioConst.DIODM_STATUS_BMSTOP) != 0)	str += "BmStop,";
			if ((status & (uint)CdioConst.DIODM_STATUS_PIOSTART) != 0)	str += "PioStart,";
			if ((status & (uint)CdioConst.DIODM_STATUS_PIOSTOP) != 0)	str += "PioStop,";
			if ((status & (uint)CdioConst.DIODM_STATUS_TRGIN) != 0)		str += "TrgIn,";
			if ((status & (uint)CdioConst.DIODM_STATUS_OVERRUN) != 0)	str += "Overrun";
			txtStatus.Text = str;
			// Error
			str = "";
			if ((err & (uint)CdioConst.DIODM_STATUS_FIFOEMPTY) != 0)	str += "FifoEmpty,";
			if ((err & (uint)CdioConst.DIODM_STATUS_FIFOFULL) != 0)		str += "FifoFull,";
			if ((err & (uint)CdioConst.DIODM_STATUS_SGOVERIN) != 0)		str += "S/GOverIn,";
			if ((err & (uint)CdioConst.DIODM_STATUS_TRGERR) != 0)		str += "TrgErr,";
			if ((err & (uint)CdioConst.DIODM_STATUS_CLKERR) != 0)		str += "ClkErr,";
			if ((err & (uint)CdioConst.DIODM_STATUS_SLAVEHALT) != 0)	str += "SlaveHalt,";
			if ((err & (uint)CdioConst.DIODM_STATUS_MASTERHALT) != 0)	str += "MasterHalt";
			txtError.Text = str;
			return;
		}

		//===================================================
		//	DioExit
		//===================================================
		private void btnDioExit_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			string	str;
			int		ret;
	
			//-----------------------------------
			// DioExit
			//-----------------------------------
			ret = dio.Exit(Id);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioExit ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

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

		//===================================================
		//	メッセージハンドラー
		//===================================================
		protected override void WndProc(ref Message m)
		{
			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:
					int		ret;
					uint	count, carry;
					string	str;
					//-----------------------------------
					// get count
					//-----------------------------------
					ret = dio.DmGetCount(Id, (short)CdioConst.DIODM_DIR_OUT, out count, out carry);
					str = string.Format("{0:d}", count);
					txtCount.Text = str;
					break;
				default:
					break;
			}
			base.WndProc(ref m);
		}

		//===================================================
		//	出力データファイル作成
		//===================================================
		private void InitialDataFile(string szFileName)
		{
			StreamWriter	fp;
			string			buf = new string(' ', 100);
			uint			i;

			//-----------------------------------
			// ファイルオープン
			//-----------------------------------
			fp = File.CreateText(szFileName);
			//-----------------------------------
			// ファイル作成
			//-----------------------------------
			for (i = 0; i < DATA_SIZE; i++) 
			{
				buf = string.Format("{0:d8}: ,{1:X8}", i, i);
				fp.WriteLine(buf); 
			}
			//-----------------------------------
			// ファイルクローズ
			//-----------------------------------
			fp.Close();
			return;
		}
	}
}
