using CgpibCs;

namespace Master
{
    public partial class Form1 : Form
    {
        Cgpib gpib = new Cgpib();

        short m_Id;
        short[] m_EqpId = new short[32];
        short m_SelectEqpId;

        public Form1()
        {
            InitializeComponent();
        }

        //**************************************************************************************************
        //   Display transmitted string to list box of "Return code"(sub routine)
        //**************************************************************************************************
        private void funcSetlstRet(string strRet)
        {
            //Add the item to the end of list box
            //Clear all of the items if the number of items more than 256
            if (lstRet.Items.Count >= 256)
            {
                lstRet.Items.RemoveAt(0);
                lstRet.Items.Add(strRet);
            }
            else
            {
                lstRet.Items.Add(strRet);
            }
            lstRet.SelectedIndex = lstRet.Items.Count - 1;
        }

        //**************************************************************************************************
        //   Set the target (sub routine)
        //   Function: Set Equipment ID, Delimiter and EOI
        //   Return value: TRUE(normally), FALSE(abnormally)
        //**************************************************************************************************
        private bool funcSetParam()
        {
            short Delim;
            short PrmAddr;
            short Eoi;
            short Eos;
            int Ret;
            string strRet;

            //If the other party equipment has been detected, the equipment that has been detected is specified. 
            if (cboAddr.Items.Count != 0)
            {
                //Get Equipment ID of the device specified in combo box
                m_SelectEqpId = m_EqpId[cboAddr.SelectedIndex];
            }
            else
            {
                //Get Equipment ID of device address specified in edit box
                Delim = (short)cboDelim.SelectedIndex;
                PrmAddr = short.Parse(txtAddr.Text);
                Ret = gpib.SetEquipment(m_Id,                   //Device ID
                                            out m_SelectEqpId,  //Retrieved equipment ID
                                            PrmAddr,            //Primary address 
                                            0,                  //Secondary address 
                                            Delim);             //Set delimiter
                if (Ret != 0)
                {
                    //Error
                    gpib.GetErrorString(Ret, out strRet);
                    funcSetlstRet(strRet);      //Display in list
                    return false;
                }
            }
            //Set delimiter code and EOI line
            Delim = (short)cboDelim.SelectedIndex;
            Eoi = (short)cboEoi.SelectedIndex;
            Eos = 0;
            Ret = gpib.SetDelim(m_SelectEqpId,
                Delim,          //Set delimiter code
                Eoi,            //Set EOI line
                Eos);           //Set EOS(reserved)
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);          //Display in list
            }
            else
            {
                funcSetlstRet("[Partner apparatus setting] completed normally");    //Display in list
            }
            return true;
        }

        //***************************************************************************
        //   Initializing
        //***************************************************************************
        private void Form_master_Load(object sender, System.EventArgs e)
        {
            txtDevName.Text = "GPIB000";
            txtAddr.Text = "1";
            cboDelim.SelectedIndex = 1; //Set "CR+LF" as default
            cboEoi.SelectedIndex = 1;   //Set "Use" as default
            txtSend.Text = "CONTEC Master Sample";
        }

        //***************************************************************************
        //   Initialize
        //   Function: Get device ID from device name
        //***************************************************************************
        private void cmdInit_Click(object sender, System.EventArgs e)
        {
            int Ret;
            int Data;
            string strRet;

            //Initialization function execution
            Ret = gpib.Init(txtDevName.Text, out m_Id);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                //If get device ID normally
                strRet = "GpibInit : DeviceID = " + m_Id;
                funcSetlstRet(strRet);  //Display in list
                                        //Get device address
                Ret = gpib.GetStatus(m_Id, 0x08, out Data);
                if (Ret == 0)
                {
                    txtMyAddr.Text = Data.ToString();
                }
                //Confirm whether it is set to master
                Ret = gpib.GetStatus(m_Id, 0x0A, out Data);
                if ((Ret == 0) && (Data == 1))
                {
                    MessageBox.Show("It is not a master. Please set it to master in property page.");
                }
                else
                {
                    strRet = "[Initialize] completed normally";
                    funcSetlstRet(strRet);  //Display in list
                }
            }

            gpib.SendIFC(m_Id, 1);  //Send IFC
        }

        //***************************************************************************
        //   Exit
        //   Function: Disable device ID
        //***************************************************************************
        private void cmdExit_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            Ret = gpib.Exit(m_Id);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            this.Close();
        }

        //***************************************************************************
        //   Detect partner apparatus
        //   FuntionF Detect partner apparatus from device ID and get equipment ID.
        //         Send the [*IDN?] command according with IEEE488.2 standard to partner apparatus with
        //         the equipment ID and get device ID(maker and module number etc.).
        //***************************************************************************
        private void cmdSearch_Click(object sender, System.EventArgs e)
        {
            short PrmAddr;
            short ScdAddr;
            short ArraySize;
            short ArrayCount;
            short[] AddrArray = new short[32];
            int Ret;
            int SendLen;
            int RecLen;
            string RecBuf;
            string strRet;
            string SendBuf;
            string EqpInforBuf;

            PrmAddr = -1;   //Search all primary address
            ScdAddr = 0;    //Do not search secondary address
            ArraySize = 32; //Specify the number of devices to be detected
            Ret = gpib.FindListener(m_Id, PrmAddr, ScdAddr, ref ArraySize, AddrArray);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
                return;
            }
            //Display detected partner apparatus when finishing detecting normally
            strRet = "GpibFindListener : the number of detected partner apparatus = " + ArraySize;
            funcSetlstRet(strRet);  //Display in list

            //Get device information of detected device
            cboAddr.ResetText();    //Initialize combo box items
            for (ArrayCount = 0; ArrayCount < ArraySize; ArrayCount++)
            {
                //Get Equipent ID
                Ret = gpib.SetEquipment(
                                        m_Id,                           //Device ID
                                        out m_EqpId[ArrayCount],        //Retrieved equipment ID
                                        AddrArray[ArrayCount],          //Primary address
                                        0,                              //Secondary address
                                        (short)cboDelim.SelectedIndex   //Set delimiter
                                        );
                if (Ret != 0)
                {
                    //error
                    gpib.GetErrorString(Ret, out strRet);
                    funcSetlstRet(strRet);  //Display in list
                    continue;
                }

                //Inquiry device information(data sending)
                SendBuf = "*IDN?";          //Data to be sent
                SendLen = SendBuf.Length;   //The number of sent data
                Ret = gpib.SendData(m_EqpId[ArrayCount], ref SendLen, SendBuf);
                if (Ret != 0)
                {
                    //error
                    gpib.GetErrorString(Ret, out strRet);
                    funcSetlstRet(strRet);  //Display in list
                    continue;
                }

                //Inquiry device information(data receiving)
                RecLen = 256;   //Specify buffer size for receiving data
                Ret = gpib.RecData(m_EqpId[ArrayCount], ref RecLen, out RecBuf);
                if (Ret != 0)
                {
                    //error
                    gpib.GetErrorString(Ret, out strRet);
                    funcSetlstRet(strRet);  //Display in list
                    continue;
                }

                //Confirm whether receiving data accords with IEEE488.2 standard
                if (RecBuf.IndexOf(",") != -1)
                {
                    //Combine with address information
                    EqpInforBuf = "Address:" + AddrArray[ArrayCount] + RecBuf;
                }
                else
                {
                    //Include only address information if receiving data does not accord with IEEE488.2 standard
                    EqpInforBuf = "Address:" + AddrArray[ArrayCount];
                }
                //Add detected device to the list
                cboAddr.Items.Insert(ArrayCount, EqpInforBuf);
                cboAddr.SelectedIndex = ArrayCount;
            }

            //Reflect detected device to combo box and edit box
            if (cboAddr.SelectedIndex != -1)
            {
                txtAddr.Text = AddrArray[cboAddr.SelectedIndex].ToString();
            }

        }

        //***************************************************************************
        //   Send Data
        //   Function: Send data to slave device
        //***************************************************************************
        private void cmdSend_Click(object sender, System.EventArgs e)
        {
            int SendLen;
            int Ret;
            string strRet;
            string SendBuf;

            //Set equipment ID, delimiter and EOI
            if (funcSetParam() == false) return;

            //Get sending data from edit box
            SendBuf = txtSend.Text;
            SendLen = SendBuf.Length;
            if (SendLen == 0)
            {
                strRet = "GpibSendData : sending data does not exist";
                funcSetlstRet(strRet);  //Display in list
                return;
            }

            funcSetlstRet("GpibSendData : sending data...");    //Display in list
                                                                //Send data
            Ret = gpib.SendData(m_SelectEqpId, ref SendLen, SendBuf);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                //Sent data normally
                strRet = "GpibSendData : the number of sent data = " + SendLen;
                funcSetlstRet(strRet);  //Display in list
                funcSetlstRet("[Send data] completed normally");    //Display in list
            }
        }

        //***************************************************************************
        //   Receive data
        //   Function: Receive data from slave device
        //***************************************************************************
        private void cmdRec_Click(object sender, System.EventArgs e)
        {
            int RecLen;
            int Ret;
            string strRet;
            string RecBuf;

            //Set equipment ID, delimiter and EOI
            if (funcSetParam() == false) return;

            RecLen = 256;   //Set recieving buffer size
            funcSetlstRet("GpibRecData : receiving data...");   //Display in list
                                                                //Receive data
            Ret = gpib.RecData(m_SelectEqpId, ref RecLen, out RecBuf);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                //Receiv data normally
                txtRec.Text = RecBuf.Substring(0, RecLen);
                strRet = "GpibRecData : the number of received data = " + RecLen;
                funcSetlstRet(strRet);  //Display in list
                strRet = "[Receive data] completed normally";
                funcSetlstRet(strRet);  //Display in list
            }
        }

        //***************************************************************************
        //   Send GET Command
        //   Function: Performs transfer of command (GET) starts the matter decided by slave device.
        //***************************************************************************
        private void cmdGet_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            if (funcSetParam() == false) return;

            //Perform the function of sending GET command
            Ret = gpib.SendTrigger(m_SelectEqpId);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                funcSetlstRet("[Send GET command] completed normally"); //Display in list
            }
        }

        //***************************************************************************
        //   Send SDC Command
        //   Function: Perform transfer of commands (SDC) that make slave device to initial states (when power is supplied)
        //***************************************************************************
        private void cmdSdc_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            if (funcSetParam() == false) return;

            //Perform the function of sending SDC command
            Ret = gpib.SendDeviceClear(m_SelectEqpId);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                funcSetlstRet("[Send SDC command] completed normally"); //Display in list
            }
        }

        //***************************************************************************
        //   Send GTL command
        //   Function: Transmit the command(GTL) that make slave device return to local mode
        //***************************************************************************
        private void cmdGtl_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            if (funcSetParam() == false) return;

            //Perform the function of sending GTL command
            Ret = gpib.ChangeLocal(m_SelectEqpId);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                funcSetlstRet("[Send GTL command] completed normally"); //Display in list
            }
        }

        //***************************************************************************
        //   Send DCL command
        //   Function: Perform transfer of command (DCL) that make all slave devices to initial states (when power is supplied)
        //***************************************************************************
        private void cmdDcl_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            //Perform the function of sending DCL command
            Ret = gpib.SendDeviceClear(m_Id);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                funcSetlstRet("[Send DCL command] completed normally"); //Display in list
            }
        }

        //***************************************************************************
        //   Send LLO command
        //   Function: Perform transfer of command (LLO) that disables the transition to local mode by switch on device of all slave devices
        //***************************************************************************
        private void cmdLlo_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            //Perform the function of Sending LLO command
            Ret = gpib.SendLocalLockout(m_Id);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                funcSetlstRet("[Send LLO command] completed normally"); //Display in list
            }
        }

        //***************************************************************************
        //   Perform serial poll
        //   Function: Get status byte of slave device
        //***************************************************************************
        private void cmdSPoll_Click(object sender, System.EventArgs e)
        {
            short Stb;
            short Srq;
            int Ret;
            string strRet;

            if (funcSetParam() == false) return;

            funcSetlstRet("GpibSPoll : serial polling..."); //Display in list

            //Perform the function of serial poll
            Ret = gpib.SPoll(m_SelectEqpId, out Stb, out Srq);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                strRet = string.Format("GpibSPoll : status byte = {0:X2}(H) SRQ line = {1:X2}(H)", Stb, Srq);
                funcSetlstRet(strRet);  //Display in list
                funcSetlstRet("[Serial poll] completed normally");  //Display in list
            }
        }

        //***************************************************************************
        //   Construct parallel poll
        //   Function: set the line of parallel poll response
        //***************************************************************************
        private void cmdSetPPoll_Click(object sender, System.EventArgs e)
        {
            short[] AddrArray = new short[9];
            short[] DataLineArray = new short[9];
            short[] PolarityArray = new short[9];
            int i;
            int Ret;
            string strRet;

            //Set by device address in edit box
            i = 0;
            AddrArray[i] = short.Parse(txtAddr.Text);       //Device address
            DataLineArray[i] = (short)(i + 1);              //DIO line number
            PolarityArray[i] = 1;                           //Set as inphase
            i++;

            //Set the end of the array
            AddrArray[i] = -1;
            DataLineArray[i] = -1;
            PolarityArray[i] = -1;

            //Perform the function of counstructing parallel poll
            Ret = gpib.SetPPoll(m_Id, AddrArray, DataLineArray, PolarityArray);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                funcSetlstRet("[Construct parallel poll] completed normally");  //Display in list
            }
        }

        //***************************************************************************
        //   Perform parallel poll
        //   Function: Perform parallel poll and get DIO line data
        //***************************************************************************
        private void cmdPPoll_Click(object sender, System.EventArgs e)
        {
            short Ppr;
            int Ret;
            string strRet;

            //Perform the function of parallel poll
            Ret = gpib.PPoll(m_Id, out Ppr);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                strRet = string.Format("GpibPPoll : DIO line data = {0:X2}(H)", Ppr);
                funcSetlstRet(strRet);  //Display in list
                funcSetlstRet("[Parallel poll] completed normally");    //Display in list
            }
        }

        //***************************************************************************
        //   Clear send/receive text data
        //***************************************************************************
        private void cmdDataDel_Click(object sender, System.EventArgs e)
        {
            txtSend.Text = "";
            txtRec.Text = "";
        }

        //***************************************************************************
        //   Clear return code
        //***************************************************************************
        private void cmdRetDel_Click(object sender, System.EventArgs e)
        {
            lstRet.Items.Clear();
        }
    }
}