using System;
using System.IO;
using System.Windows.Forms;
using Ivi.Visa.Interop;         // VISA library namespace specification

//  Sample code for measuring instrument (power supply, load device, etc.) using KI-VISA
//  Copyright by Kikusui Electronics Corp. 2015-2020
//  Code Creation: SE2 Section Yajima

//  2020.09.01 Ver1.00e (Ver1.05 base)


namespace SampleCode_KIVISA
{
     public partial class Form1 : Form
    {
        // Create resource manager object
        IResourceManager3 rm;
        IMessage msg;

        // Dialog box title
        readonly string sAppTitle = "KI-VISA Sample for CSharp";

        // Main form
        public Form1()
        {
            InitializeComponent();
            //Set the form display position to the center of the screen.
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        // Processing when displaying form
        private void Form1_Load(object sender, EventArgs e)
        {

            // A storage variable for the VISA resource list found by FindResource
            string[] foundResources;

            // Initialize the Resource Manager
            rm = new ResourceManager();

            // Get the name of a VISA resource containing an INSTR available in FindResource
            // For more information, please refer to KI-VISA Library 
            // VISA COM Guidebook 8 - Dynamically Setting VISA Addresses (starting on page 48).
            try
            {
                foundResources = rm.FindRsrc("?*INSTR");
            }
            catch (Exception)
            {
				MessageBox.Show("No available VISA resources found on the computer." + "\r"
					+ "Make sure your device is connected",
                    sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }



			// Add the acquired VISA resource name to the VISA Resource Name combo box.
            cmb_Resources.DataSource = foundResources;

            // Add a setting command to the combo box.
            // Commands not listed in the combo box can be entered manually at run time.
            // If you edit the commands here, you can select any command from the pull-down menu.
            // As a typical example, the following commands are available for the 
            // PMX18-5A (DC power supply 18V/5A model).
            cmb_CommandString.Items.Add("SYST:REMOTE");
            cmb_CommandString.Items.Add("SYST:LOCAL");
            cmb_CommandString.Items.Add("*CLS");
            cmb_CommandString.Items.Add("OUTP ON");
            cmb_CommandString.Items.Add("OUTP OFF");
            cmb_CommandString.Items.Add("VOLT 10");
            cmb_CommandString.Items.Add("VOLT 1");
            cmb_CommandString.Items.Add("CURR 1");
            cmb_CommandString.Items.Add("CURR 0.1");
            cmb_CommandString.SelectedIndex = 0;        // Display the first command

            // Add a query command to the combo box
            cmb_QueryString.Items.Add("*IDN?");
            cmb_QueryString.Items.Add("*STB?");
            cmb_QueryString.Items.Add("SYST:ERR?");
            cmb_QueryString.Items.Add("OUTP?");
            cmb_QueryString.Items.Add("VOLT?");
            cmb_QueryString.Items.Add("CURR?");
            cmb_QueryString.Items.Add("READ:VOLT?");
            cmb_QueryString.Items.Add("READ:CURR?");
            cmb_QueryString.SelectedIndex = 0;            // Display the first command

            // Disable button before opening a VISA session.
            btn_SendCommand.Enabled = false;
            btn_SendQuery.Enabled = false;
            btn_SerialPolling.Enabled = false;

            //----------------------------------------------------------------------
            // [Caution] Searching for LAN Devices
            // Dynamic search may not be available for LAN devices.
            // In that case, you can use it by Finding with KI-VISA Instruments Explorer.
            //----------------------------------------------------------------------
        }

        // Open VISA session
        private void btn_Open_Click(object sender, EventArgs e)
        {
            // For more information, see KI-VISA Library VISA COM Guidebook 6 - Opening VISA Sessions (starting on page 35).
            IGpib gpib;
            ISerial seri;
            ITcpipInstr tcp;
            IUsb usb;

            // Open a VISA session with the resource name specified in the combo box
            try
            {
                msg = (IMessage)rm.Open(cmb_Resources.Text, AccessMode.NO_LOCK, 0, ""); // Support the change of timeout specification in NI-VISA
                MessageBox.Show("VISA session opened successfully!" + "\r" + cmb_Resources.Text, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception)
            {
                MessageBox.Show("VISA session opening failed." + "\r" + cmb_Resources.Text, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            // Configuration by Interface Type
            // Please refer to KI-VISA Library VISA COM Guidebook 7 - Basic IO (from page 39 onwards) for details.
            msg.TerminationCharacter = 10;
            msg.TerminationCharacterEnabled = true; // When performing ReadString() on an IEEE 488.2 measuring instrument,
                                                // "true" setting is recommended for correct terminating.
            msg.SendEndEnabled = true;

            // Configure interface type by HardwareInterfaceType
            switch (msg.HardwareInterfaceType)
            {
                case 1:
                    // GPIB
                    gpib = (IGpib)msg;
                    gpib.RepeatAddressingEnabled = true;
                    gpib.UnaddressingEnabled = false;

                    // Enable the serial polling button (since only GPIB and USB can be used)
                    btn_SerialPolling.Enabled = true;
                   
                    break;

                case 4:
                    // ASRL(Serial port)
                    // You can set the baud rate by changing the parameters here.
                    seri = (ISerial)msg;
                    seri.BaudRate = 19200;								// baud rate 19200bps
                    seri.DataBits = 8;								// Data Bits 8bit
                    seri.StopBits = SerialStopBits.ASRL_STOP_ONE;			// Stop Bits 1bit
                    seri.Parity = SerialParity.ASRL_PAR_NONE;			// No parity
                    seri.FlowControl = SerialFlowControl.ASRL_FLOW_NONE;	// Without flow control

					// Disabling the serial polling button
                    btn_SerialPolling.Enabled = false;   
                   
                    break;

                case 6:
                    // LAN
					//  [Caution] Dynamic search may not be available for LAN devices.
					// In that case, you can use it by Finding with KI-VISA Instruments Explorer.
                    tcp = (ITcpipInstr)msg;

					//Disabling the serial polling button
                    btn_SerialPolling.Enabled = false; 
                     
                    break;

                case 7:
                    // USB
                    usb = (IUsb)msg;

					// Enable the serial polling button(since only GPIB and USB can be used)
                    btn_SerialPolling.Enabled = true;
       
                    break;
            }

			// Enable the button.
            btn_SendCommand.Enabled = true;
            btn_SendQuery.Enabled = true;

        }

		// Sending commands
        private void btn_writeString_Click(object sender, EventArgs e)
        {
            int r;

			// Send the command selected by cmb_CommandString
			r = msg.WriteString(cmb_CommandString.Text + "\n");   // Add a delimiter after the command message

			// If you want to write the command directly, you can also write it like this.
            // r = msg.WriteString("VOLT 10\n");
            // r = msg.WriteString("OUTP ON\n");
        }

		// Example of sending query command and receiving result
        private void btn_SendQuery_Click(object sender, EventArgs e)
        {
            int r;
            string strret = "";

			// query command sending
			r = msg.WriteString(cmb_QueryString.Text + "\n");   //  Add a delimiter after the command message

			// Receive query results
            try
            {
				strret = msg.ReadString(1024); // Buffer size 1024 bytes
            }
            catch (Exception)
            {
				MessageBox.Show("Failed to receive query message."
                    + "\r" + cmb_Resources.Text,
                    sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }


			//Returns the value received by ReadString.
            tb_Result.Text = strret;
        }

		//Example of serial polling the status byte register
        private void btn_SerialPolling_Click(object sender, EventArgs e)
        {
            short stb;

			// Serial polling the status byte register.
			// ReadSTB is only available for GPIB and USB interfaces.
			// For other interfaces, the button are disabled. (because exception is occur)
            stb = msg.ReadSTB();

			// Write result data to text box
            tb_Result.Text = stb.ToString();
        }

		// Processing when the form was closed
        private void quitQToolStripMenuItem_Click(object sender, EventArgs e)
        {
			// Close the VISA session    
            if (msg != null)
            {
                msg.Close();
            }
			// Close the form
            this.Close();
        }

		// Clear the Result text box
        private void btn_ClearRersult_Click(object sender, EventArgs e)
        {
			// Clear the Result text box
            tb_Result.Text = "";
        }

		// AboutBox Version/Contact Information Display
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show(
                "Samplecode for KI-VISA CSharp Ver1.00e" + "\r"
                + "Copyright by Kikusui Electronics Corp. 2015-2020" + "\r", sAppTitle);
 
        }
    }


}
