using CgpibCs;

namespace ConRec
{
    public partial class Form1 : Form
    {
        Cgpib gpib = new Cgpib();
        short m_Id;
        short[] m_EqpId = new short[32];
        short m_SelectEqpId;
        const long GPIB_NOTIFY_MESSAGE = 0x15FF;

        public Form1()
        {
            InitializeComponent();
        }

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

        //**************************************************************************************************
        //   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;
        }

        //**************************************************************************************************
        //   Display transmitted string to list box of received data(sub routine)
        //**************************************************************************************************
        private void funcSetlstSrqRecData(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 (lstEventRec.Items.Count >= 256)
            {
                lstEventRec.Items.RemoveAt(0);
                lstEventRec.Items.Add(strRet);
            }
            else
            {
                lstEventRec.Items.Add(strRet);
            }
            lstRet.SelectedIndex = lstRet.Items.Count - 1;
        }

        //**************************************************************************************************
        //  Set the target (sub routine)
        //   Function: Set Equipment ID, Delimiter and EOI
        //   Return value: ture(normally), false(abnormally)
        //**************************************************************************************************
        private bool funcSetParam()
        {
            short Delim;
            short Eoi;
            short Eos;
            short PrmAddr;
            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;
        }

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

            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 detecte
            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 equipment 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
            {
                //Received 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
            }
        }

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

            //Clear items of list box
            lstEventRec.Items.Clear();
        }

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

        //***************************************************************************
        //   Start manual timing
        //   Function: Send GET command
        //        When the GET command can not operate normally according to different
        //        partner apparatus,  please modify it according with device specification.
        //***************************************************************************
        private void cmdSrqRecTrigger_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            if (funcSetParam() == false) return;

            //Perform transmitting function of 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
            }
        }

        //***************************************************************************
        //   Start SRQ event receiving
        //   Function: Receive data when SRQ is enabled
        //***************************************************************************
        private void cmdEventRecStart_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            //Start timer if "timer" is selected
            if (optTimer.Checked == true)
            {
                tmrTimerEventRec.Interval = short.Parse(txtTimerInterval.Text);
                tmrTimerEventRec.Enabled = true;
            }
            //Perform trigger if "Maximum Speed" is selected
            if (optMaxSpeed.Checked == true)
            {
                cmdSrqRecTrigger_Click(cmdSrqRecTrigger, new System.EventArgs());
            }

            //Perform the function of event setting(enable SRQ event receiving)
            Ret = gpib.SetNotifySignal(m_Id, (uint)Handle, 0x0020);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                cmdEventRecStart.Enabled = false;
                cmdEventRecStop.Enabled = true;
                funcSetlstRet("[Start SRQ event receiving] completed normally");    //Display in list
            }
        }

        //***************************************************************************
        //   Stop SRQ event receiving
        //   Function: Stop event receiving
        //***************************************************************************
        private void cmdEventRecStop_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string strRet;

            //Stop timer if "timer" is selected
            if (optTimer.Checked == true)
            {
                tmrTimerEventRec.Enabled = false;
            }
            //Perform the function of event setting(cancel SRQ event receiving)
            Ret = gpib.SetNotifySignal(m_Id, (uint)Handle, 0x0000);
            if (Ret != 0)
            {
                //error
                gpib.GetErrorString(Ret, out strRet);
                funcSetlstRet(strRet);  //Display in list
            }
            else
            {
                cmdEventRecStart.Enabled = true;
                cmdEventRecStop.Enabled = false;
                funcSetlstRet("[Stop SRQ event receiving] completed normally"); //Display in list
            }
        }

        //***************************************************************************
        //   Save received data to CSV file
        //***************************************************************************
        private void cmdSaveCsv_Click(object sender, System.EventArgs e)
        {
            string strFileDataBuf;
            short i;
            FileStream OutFile;
            StreamWriter FileWriter;

            dlgSaveCsv.FileName = "ConRec.csv";         //Default file name
            dlgSaveCsv.DefaultExt = "csv";
            dlgSaveCsv.Title = "Save Received Data";    //dialog title
                                                        //The folder that opens first is set to the application passing.
            dlgSaveCsv.InitialDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            dlgSaveCsv.Filter = "csv files(*.csv)|*.csv|All files (*.*)|*.*";

            //display dialog
            if (dlgSaveCsv.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            OutFile = new FileStream(dlgSaveCsv.FileName, FileMode.Create, FileAccess.Write);
            FileWriter = new StreamWriter(OutFile, System.Text.Encoding.UTF8);

            //Write received data to ther file
            strFileDataBuf = "Received Times, Received Data\n";
            FileWriter.Write(strFileDataBuf);

            for (i = 0; i < lstEventRec.Items.Count; i++)
            {
                strFileDataBuf = i + "," + lstEventRec.Items[i] + "\n";
                FileWriter.Write(strFileDataBuf);
            }
            //Close file
            FileWriter.Close();
            OutFile.Close();
        }

        //***************************************************************************
        //   Start timer event
        //   Function: Perform trigger at fixed interval
        //***************************************************************************
        private void tmrTimerEventRec_Tick(object sender, System.EventArgs e)
        {
            cmdSrqRecTrigger_Click(cmdSrqRecTrigger, new System.EventArgs());
        }

        //***************************************************************************
        //   SRQ event receiving
        //   Function: Perform serial poll and receive data when SRQ line is enabled
        //***************************************************************************
        protected override void WndProc(ref Message m)
        {
            short Stb;
            short Srq;
            int RecLen;
            int Ret;
            string strRet;
            string RecBuf;

            //----------------------------------------
            //   Process of SRQ receiving
            //----------------------------------------
            if (m.Msg == GPIB_NOTIFY_MESSAGE)
            {
                do
                {
                    if ((m.WParam.ToInt32() & 0x0020) != 0)
                    {
                        //Set equipment ID, delimiter and EOI
                        if (funcSetParam() == false) break;

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

                        //Perform serial poll function
                        Ret = gpib.SPoll(m_SelectEqpId, out Stb, out Srq);
                        if (Ret != 0)
                        {
                            //error
                            gpib.GetErrorString(Ret, out strRet);
                            funcSetlstRet(strRet);  //Display in list
                                                    //Stop SRQ receiving when serial poll occurred error
                            cmdEventRecStop_Click(cmdEventRecStop, new System.EventArgs());
                            return;
                        }
                        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
                        }

                        //Receive data
                        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
                                                    //Stop SRQ receiving when error occurred in receiving data
                            cmdEventRecStop_Click(cmdEventRecStop, new System.EventArgs());
                            return;
                        }
                        else
                        {
                            //Finish receiving data normally
                            RecBuf = RecBuf.Substring(0, RecLen);
                            funcSetlstSrqRecData(RecBuf);   //Display received data in list
                            strRet = "GpibRecData : the number of received data = " + RecLen;
                            funcSetlstRet(strRet);  //Display in list
                            funcSetlstRet("[Receive Data] completed normally"); //Display in list
                        }

                        //Perform trigger if "Maximum Speed" is selected
                        if (optMaxSpeed.Checked == true)
                        {
                            cmdSrqRecTrigger_Click(cmdSrqRecTrigger, new System.EventArgs());
                        }
                    }
                } while (false);

                //----------------------------------------
                //   Setting of waiting next event
                //----------------------------------------
                //Perform the function of event setting
                Ret = gpib.SetNotifySignal(m_Id, (uint)Handle, 0x0020);
                //Process of return code
                if (Ret != 0)
                {
                    //error
                    gpib.GetErrorString(Ret, out strRet);
                    funcSetlstRet(strRet);  //Display in list
                }
            }
            base.WndProc(ref m);
        }
    }
}