using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;
using CgpibCs;
using CSubFuncCs;

namespace Master
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Master : System.Windows.Forms.Form
	{
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.GroupBox groupBox3;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.TextBox txtMyAddress;
		private System.Windows.Forms.ComboBox cboYrAdrBox;
		private System.Windows.Forms.Button btnInit;
		private System.Windows.Forms.Button btnPolling;
		private System.Windows.Forms.Button btnGet;
		private System.Windows.Forms.TextBox txtSendData;
		private System.Windows.Forms.Button btnSend;
		private System.Windows.Forms.Button btnReceive;
		private System.Windows.Forms.TextBox txtReceiveData;
		private System.Windows.Forms.Button btnDelData;
		private System.Windows.Forms.Button btnDelRet;
		private System.Windows.Forms.TextBox txtRet;
		private System.Windows.Forms.ComboBox cboDelimBox;
		private System.Windows.Forms.Button btnExt;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		Cgpib			gpib = new Cgpib();
		CSubFunc		SubFunc = new CSubFunc();

		/////////////////////////////////////////////////////////////////////////////
		string			szBuffer = new string(' ', 1024);		// For words of buffers
		uint			Ret;									// Return code
		int				Count;									// Count
		uint			Myadr, Yradr, MyMaster;					// MyAddress,Address of device,(Master(0) or Slave(1))
		uint			Delim, Eoi;								// Delimiter
		uint			Srlen;									// Length of buffers
		//uint			P_stb, P_eoi;							// StatusByte,EOI
		uint[]			Pstb = new uint[32];					// StatusByte array
		string			srBuffer = new string(' ', 10000);		// buffer of send data
		string			csBuf;									// string of csBuf
		StringBuilder	rvBuffer = new StringBuilder(10000);	// buffer of receive data
		GCHandle     	gChCmd;                 				// GCHandle for cmd array
    	GCHandle        gChPstb;             					// GCHandle for Pstb array
    	IntPtr     		pPstb;                   				// IntPtr for Pstb array
		/////////////////////////////////////////////////////////////////////////////

		public Master()
		{
			//
			// 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.groupBox1 = new System.Windows.Forms.GroupBox();
			this.txtMyAddress = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.cboYrAdrBox = new System.Windows.Forms.ComboBox();
			this.label2 = new System.Windows.Forms.Label();
			this.btnInit = new System.Windows.Forms.Button();
			this.btnPolling = new System.Windows.Forms.Button();
			this.btnGet = new System.Windows.Forms.Button();
			this.btnExt = new System.Windows.Forms.Button();
			this.groupBox3 = new System.Windows.Forms.GroupBox();
			this.btnReceive = new System.Windows.Forms.Button();
			this.txtReceiveData = new System.Windows.Forms.TextBox();
			this.btnSend = new System.Windows.Forms.Button();
			this.txtSendData = new System.Windows.Forms.TextBox();
			this.btnDelData = new System.Windows.Forms.Button();
			this.btnDelRet = new System.Windows.Forms.Button();
			this.label3 = new System.Windows.Forms.Label();
			this.txtRet = new System.Windows.Forms.TextBox();
			this.label4 = new System.Windows.Forms.Label();
			this.cboDelimBox = new System.Windows.Forms.ComboBox();
			this.groupBox1.SuspendLayout();
			this.groupBox2.SuspendLayout();
			this.groupBox3.SuspendLayout();
			this.SuspendLayout();
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.txtMyAddress,
																					this.label1});
			this.groupBox1.Location = new System.Drawing.Point(8, 8);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(168, 48);
			this.groupBox1.TabIndex = 0;
			this.groupBox1.TabStop = false;
			// 
			// txtMyAddress
			// 
			this.txtMyAddress.Location = new System.Drawing.Point(102, 16);
			this.txtMyAddress.Name = "txtMyAddress";
			this.txtMyAddress.ReadOnly = true;
			this.txtMyAddress.Size = new System.Drawing.Size(32, 22);
			this.txtMyAddress.TabIndex = 1;
			this.txtMyAddress.TabStop = false;
			this.txtMyAddress.Text = "0";
			this.txtMyAddress.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(16, 19);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(88, 17);
			this.label1.TabIndex = 0;
			this.label1.Text = "MyAddress =";
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.cboYrAdrBox,
																					this.label2});
			this.groupBox2.Location = new System.Drawing.Point(174, 8);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(216, 48);
			this.groupBox2.TabIndex = 1;
			this.groupBox2.TabStop = false;
			// 
			// cboYrAdrBox
			// 
			this.cboYrAdrBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.cboYrAdrBox.Items.AddRange(new object[] {
															 "0",
															 "1",
															 "2",
															 "3",
															 "4",
															 "5",
															 "6",
															 "7",
															 "8",
															 "9",
															 "10",
															 "11",
															 "12",
															 "13",
															 "14",
															 "15",
															 "16",
															 "17",
															 "18",
															 "19",
															 "20",
															 "21",
															 "22",
															 "23",
															 "24",
															 "25",
															 "26",
															 "27",
															 "28",
															 "29",
															 "30"});
			this.cboYrAdrBox.Location = new System.Drawing.Point(141, 15);
			this.cboYrAdrBox.Name = "cboYrAdrBox";
			this.cboYrAdrBox.Size = new System.Drawing.Size(48, 24);
			this.cboYrAdrBox.TabIndex = 1;
			this.cboYrAdrBox.SelectedIndexChanged += new System.EventHandler(this.cboYrAdrBox_SelectedIndexChanged);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(16, 19);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(128, 17);
			this.label2.TabIndex = 0;
			this.label2.Text = "Address of device =";
			// 
			// btnInit
			// 
			this.btnInit.Location = new System.Drawing.Point(400, 17);
			this.btnInit.Name = "btnInit";
			this.btnInit.Size = new System.Drawing.Size(102, 30);
			this.btnInit.TabIndex = 2;
			this.btnInit.Text = "&Initialize";
			this.btnInit.Click += new System.EventHandler(this.btnInit_Click);
			// 
			// btnPolling
			// 
			this.btnPolling.Enabled = false;
			this.btnPolling.Location = new System.Drawing.Point(400, 120);
			this.btnPolling.Name = "btnPolling";
			this.btnPolling.Size = new System.Drawing.Size(102, 30);
			this.btnPolling.TabIndex = 3;
			this.btnPolling.Text = "&Polling";
			this.btnPolling.Click += new System.EventHandler(this.btnPolling_Click);
			// 
			// btnGet
			// 
			this.btnGet.Enabled = false;
			this.btnGet.Location = new System.Drawing.Point(400, 160);
			this.btnGet.Name = "btnGet";
			this.btnGet.Size = new System.Drawing.Size(102, 30);
			this.btnGet.TabIndex = 4;
			this.btnGet.Text = "&GET";
			this.btnGet.Click += new System.EventHandler(this.btnGet_Click);
			// 
			// btnExt
			// 
			this.btnExt.Location = new System.Drawing.Point(400, 200);
			this.btnExt.Name = "btnExt";
			this.btnExt.Size = new System.Drawing.Size(102, 30);
			this.btnExt.TabIndex = 5;
			this.btnExt.Text = "E&xit";
			this.btnExt.Click += new System.EventHandler(this.btnExt_Click);
			// 
			// groupBox3
			// 
			this.groupBox3.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.btnReceive,
																					this.txtReceiveData,
																					this.btnSend,
																					this.txtSendData});
			this.groupBox3.Location = new System.Drawing.Point(8, 64);
			this.groupBox3.Name = "groupBox3";
			this.groupBox3.Size = new System.Drawing.Size(382, 94);
			this.groupBox3.TabIndex = 6;
			this.groupBox3.TabStop = false;
			this.groupBox3.Text = "Send / Receive";
			// 
			// btnReceive
			// 
			this.btnReceive.Enabled = false;
			this.btnReceive.Location = new System.Drawing.Point(288, 56);
			this.btnReceive.Name = "btnReceive";
			this.btnReceive.Size = new System.Drawing.Size(88, 26);
			this.btnReceive.TabIndex = 3;
			this.btnReceive.Text = "&Receive";
			this.btnReceive.Click += new System.EventHandler(this.btnReceive_Click);
			// 
			// txtReceiveData
			// 
			this.txtReceiveData.Location = new System.Drawing.Point(8, 58);
			this.txtReceiveData.Name = "txtReceiveData";
			this.txtReceiveData.Size = new System.Drawing.Size(272, 22);
			this.txtReceiveData.TabIndex = 2;
			this.txtReceiveData.Text = "";
			// 
			// btnSend
			// 
			this.btnSend.Enabled = false;
			this.btnSend.Location = new System.Drawing.Point(288, 24);
			this.btnSend.Name = "btnSend";
			this.btnSend.Size = new System.Drawing.Size(88, 26);
			this.btnSend.TabIndex = 1;
			this.btnSend.Text = "&Send";
			this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
			// 
			// txtSendData
			// 
			this.txtSendData.Location = new System.Drawing.Point(8, 26);
			this.txtSendData.Name = "txtSendData";
			this.txtSendData.Size = new System.Drawing.Size(272, 22);
			this.txtSendData.TabIndex = 0;
			this.txtSendData.Text = "";
			// 
			// btnDelData
			// 
			this.btnDelData.Location = new System.Drawing.Point(176, 163);
			this.btnDelData.Name = "btnDelData";
			this.btnDelData.Size = new System.Drawing.Size(104, 24);
			this.btnDelData.TabIndex = 7;
			this.btnDelData.Text = "&Del Data";
			this.btnDelData.Click += new System.EventHandler(this.btnDelData_Click);
			// 
			// btnDelRet
			// 
			this.btnDelRet.Location = new System.Drawing.Point(288, 163);
			this.btnDelRet.Name = "btnDelRet";
			this.btnDelRet.Size = new System.Drawing.Size(104, 24);
			this.btnDelRet.TabIndex = 8;
			this.btnDelRet.Text = "D&el Return";
			this.btnDelRet.Click += new System.EventHandler(this.btnDelRet_Click);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(8, 186);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(88, 16);
			this.label3.TabIndex = 9;
			this.label3.Text = "Return value";
			// 
			// txtRet
			// 
			this.txtRet.Location = new System.Drawing.Point(8, 208);
			this.txtRet.Name = "txtRet";
			this.txtRet.Size = new System.Drawing.Size(384, 22);
			this.txtRet.TabIndex = 10;
			this.txtRet.Text = "";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(400, 57);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(88, 16);
			this.label4.TabIndex = 11;
			this.label4.Text = "Delimiter";
			// 
			// cboDelimBox
			// 
			this.cboDelimBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.cboDelimBox.Items.AddRange(new object[] {
															 "Not Use",
															 "CR+LF",
															 "CR",
															 "LF"});
			this.cboDelimBox.Location = new System.Drawing.Point(400, 75);
			this.cboDelimBox.Name = "cboDelimBox";
			this.cboDelimBox.Size = new System.Drawing.Size(102, 24);
			this.cboDelimBox.TabIndex = 12;
			this.cboDelimBox.SelectedIndexChanged += new System.EventHandler(this.cboDelimBox_SelectedIndexChanged);
			// 
			// Master
			// 
			this.ClientSize = new System.Drawing.Size(510, 240);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.cboDelimBox,
																		  this.label4,
																		  this.txtRet,
																		  this.label3,
																		  this.btnDelRet,
																		  this.btnDelData,
																		  this.groupBox3,
																		  this.btnExt,
																		  this.btnGet,
																		  this.btnPolling,
																		  this.btnInit,
																		  this.groupBox2,
																		  this.groupBox1});
			this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "Master";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Master Mode";
			this.Load += new System.EventHandler(this.Master_Load);
			this.Closed += new System.EventHandler(this.Master_Closed);
			this.groupBox1.ResumeLayout(false);
			this.groupBox2.ResumeLayout(false);
			this.groupBox3.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

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

		private void Master_Load(object sender, System.EventArgs e)
		{
			// ****************************************************** Setting ***
			txtSendData.Text = "_ABCDEFGHIJK_ Test Data / 34 Bytes";
			// ******************************************************************
			cboYrAdrBox.SelectedIndex = 1;
			Yradr = Convert.ToUInt32(cboYrAdrBox.Text);
			cboDelimBox.SelectedIndex = 1;

			// Specify Pinned handle to Cmd
			if (gChCmd.IsAllocated == false) {
				gChCmd = GCHandle.Alloc(SubFunc.Cmd, GCHandleType.Pinned);
			}
			// Specify Pinned handle to Pstb
			if (gChPstb.IsAllocated == false) {
				gChPstb = GCHandle.Alloc(Pstb, GCHandleType.Pinned);
			}
			// Get address object by Pinned handle
			SubFunc.pCmd = gChCmd.AddrOfPinnedObject();
			pPstb = gChPstb.AddrOfPinnedObject();
		}

		private void Master_Closed(object sender, System.EventArgs e)
		{
			SubFunc.GpibExit();											// [GpibExit] Function

			// GCHandle free
			if (gChCmd.IsAllocated == true) {
				gChCmd.Free();
			}
			if (gChPstb.IsAllocated == true) {
				gChPstb.Free();
			}
		}

		//////////////////////////////////////////// Initialize ///
		private void btnInit_Click(object sender, System.EventArgs e)
		{
			string	DelMyadr = new string(' ', 8);
			SubFunc.GpibInit(out csBuf);								// [GpibInit] Function
			gpib.Boardsts(0x08, out Myadr);								// Get MyAddress
			gpib.Boardsts(0x0a, out MyMaster);							// Get Am I Master(=0) or Slave(=1)?
	
	
			if (MyMaster == 1)
			{															// A case of Slave
				txtRet.Text = "This Partner is not Master.";
				return;
			}
			else
			{
				btnSend.Enabled = true;
				btnReceive.Enabled = true;
				btnPolling.Enabled = true;
				btnGet.Enabled = true;
		
				DelMyadr = string.Format("{0:d}", Myadr);				// Show MyAddress
				txtMyAddress.Text = Myadr.ToString();
				Ret = (uint)cboYrAdrBox.FindStringExact(DelMyadr, -1);
				if (Ret >= 0)
				{														// Seaching MyAddress
					cboYrAdrBox.Items.Remove(Ret.ToString());			// Delete MyAddress 
					if (Myadr == Yradr)
					{
						cboYrAdrBox.SelectedIndex = 0;
						Yradr = Convert.ToUInt32(cboYrAdrBox.Text);
					}
				}
				txtRet.Text = csBuf;									// Show csBuf
			}

			cboDelimBox_SelectedIndexChanged(cboDelimBox, new System.EventArgs());
		}

		//////////////////////////////////////////////// Polling ///
		private void btnPolling_Click(object sender, System.EventArgs e)
		{
			txtRet.Text = "Polling...";
			txtRet.Refresh();											// Redraw
			for (Count = 0; Count < 16; Count++)
			{
				Pstb[Count] = 0x00;										// Parameter Initialize
			}
			SubFunc.Cmd[0] = 1;											// Number of commands 
			SubFunc.Cmd[1] = Yradr;										// Address of device
			Ret = gpib.Poll(SubFunc.pCmd, pPstb);						// Start Polling
			if ((Ret & 0xFF) == 0)										// [SRQ] Found
			{
				csBuf = string.Format("Found [SRQ] Talker Address =[ {0:x} ]:StatusByte =[ {1:x} ]H", SubFunc.Cmd[Pstb[0]], Pstb[Pstb[0]]);
			}
			else if ((Ret & 0xFF) == 1)									// [SRQ] [EOI] Found
			{
				csBuf = string.Format("Found [SRQ] Talker Address =[ {0:x} ]:StatusByte =[ {1:x} ]H", SubFunc.Cmd[Pstb[0]], Pstb[Pstb[0]]);
			}
			else if ((Ret & 0xFF) == 128)								// [PM]Series is return this code
			{
				csBuf = string.Format("Found Only [SRQ]");
			}
			else
			{															// Except for 0,1,128
				SubFunc.CheckRet("GpPoll", Ret, out csBuf);
			}
			txtRet.Text = csBuf;										// Show Error or Return	code
		}

		////////////////////////////////////////////////// Send ///
		private void btnSend_Click(object sender, System.EventArgs e)
		{
			btnSend.Enabled = false;
			btnReceive.Enabled = false;
			btnInit.Enabled = false;
			btnPolling.Enabled = false;
			btnGet.Enabled = false;

			srBuffer = txtSendData.Text;								// Make a copy of m_SendData
			Srlen = (uint)srBuffer.Length;								// measure of srBuffer
			if (Srlen != 0x0)
			{															// A case of Srlen is 0
				txtRet.Text = "Data sending...";
				txtRet.Refresh();										// Redraw

				SubFunc.Cmd[0] = 2;										// Talker + Listener
				SubFunc.Cmd[1] = Myadr;									// MyAddress
				SubFunc.Cmd[2] = Yradr;									// Address of device
				Ret = gpib.Talk(SubFunc.pCmd, Srlen, srBuffer);			// Send Data
				SubFunc.CheckRet("GpTalk", (Ret & 0xFF), out csBuf);	// Check of [GpTalk]
				txtRet.Text = csBuf;
			}
			else
				txtRet.Text = "There is no data.";

			btnSend.Enabled = true;
			btnReceive.Enabled = true;
			btnInit.Enabled = true;
			btnPolling.Enabled = true;
			btnGet.Enabled = true;
		}

		/////////////////////////////////////////////// Receive ///
		private void btnReceive_Click(object sender, System.EventArgs e)
		{
			int StartIndex=0;
			int Strlen=0;
	
			btnSend.Enabled = false;
			btnReceive.Enabled = false;
			btnInit.Enabled = false;
			btnPolling.Enabled = false;
			btnGet.Enabled = false;
	
			txtRet.Text = "Receiving...";
			txtRet.Refresh();
			SubFunc.Cmd[0] = 2;											// Talker + Listener
			SubFunc.Cmd[1] = Yradr;										// Address of device
			SubFunc.Cmd[2] = Myadr;										// MyAddress
			rvBuffer.Remove(0, rvBuffer.Length);						// Clear receive buffer
			Srlen = (uint)rvBuffer.Capacity;							// rvBuffer of measure
			Ret = gpib.Listen(SubFunc.pCmd, ref Srlen, rvBuffer);		// Receive Data
			if (SubFunc.CheckRet("GpListen", (Ret & 0xFF), out csBuf) == 0)
			{															// Check of [GpListen]
				StartIndex=Convert.ToInt32(Srlen);
				Strlen=rvBuffer.Length-StartIndex;
				txtReceiveData.Text = rvBuffer.Remove(StartIndex,Strlen).ToString();  //Show Buffer
				csBuf = string.Format("[ {0:d} ] Bytes Received.", Srlen);
				txtRet.Text = csBuf;									// Show Srbuff
			}
			else
			{
				txtRet.Text = csBuf;
			}
			btnSend.Enabled = true;
			btnReceive.Enabled = true;
			btnInit.Enabled = true;
			btnPolling.Enabled = true;
			btnGet.Enabled = true;
		}

		/////////////////////////////////////////////////// GET ///
		private void btnGet_Click(object sender, System.EventArgs e)
		{
			Yradr = Convert.ToUInt32(cboYrAdrBox.Text);
			Ret = gpib.Get(Yradr);										// Begin to Trigger
			Ret = (uint)SubFunc.CheckRet("GpGet", Ret, out csBuf);		// Check of [GpGet]
			txtRet.Text = csBuf;	
		}

		////////////////////////////////////////////////// Exit ///
		private void btnExt_Click(object sender, System.EventArgs e)
		{
			SubFunc.GpibExit();											// [GpibExit] Function
			this.Close();												// End of Program
		}

		///////////////////////////////////////// Delete Return ///
		private void btnDelRet_Click(object sender, System.EventArgs e)
		{
			txtRet.Text = "";
		}

		/////////////////////////////////////////// Delete Data ///
		private void btnDelData_Click(object sender, System.EventArgs e)
		{
			txtSendData.Text = "";
			txtReceiveData.Text = "";
		}

		///////////////////////////////////////// Address of device Change ///
		private void cboYrAdrBox_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Yradr = Convert.ToUInt32(cboYrAdrBox.Text);
		}

		/////////////////////////////////////////////// Delimiter Change ///
		private void cboDelimBox_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Eoi = 1;													// EOI : USE
			Delim = (uint)cboDelimBox.SelectedIndex;
			Ret = gpib.Delim(Delim, Eoi);
		}
	}
}
