using System.Text;
using System.Runtime.InteropServices;
using CgpibCs;
using CSubFuncCs;

namespace MltMeter
{
    public partial class Form1 : Form
    {
        Cgpib         gpib = new Cgpib();
        CSubFunc      SubFunc = new CSubFunc();

        // zAϐ̐錾 ///////////////////////////////////////////////////////////
        //UINT        nIDTimerEvent;                            // ^C}CxgŎgp
        string        csBuf = "";                               // G[Ȃǂ̃eLXgp
        uint          Yradr, Myadr;                             // }CAhXA@AhX
        uint          Delim, Eoi;                               // f~^
        uint          regvalue;                                 // SRQrbg̗L
        uint          Srlen, Ret;                               // M̃oCgAꂼ̖߂l
        uint[]        Pstb = new uint[32];                      // bZ[W̔z
        uint          SrqOn;                                    // SRQ̗L
        ushort        wMsg;                                     // EBhEbZ[W
        string        SendBuf = new string(' ', 70000);         // Mobt@/read work
        bool          bTimerOn;                                 // ^C}̏(1:^C}~ 2:^C}s)
        bool          ErrorOccured;                             // G[̗L
        int           Device;                                   // @̃CfbNX(ԍFԖڂ͂O)
        //int         Count;                                    // JEg^[v񐔂Ȃ
        //int         SetT;                                     // KillTimer()̊mF(0:~ 1:s)
        string        szBuffer = new string(' ', 4096);         // eLXgobt@
        StringBuilder ReceiveBuf = new StringBuilder(70000);    // Mobt@/read work
        GCHandle      gChCmd;                                   // CmdzpGCHandle
        GCHandle      gChPstb;                                  // PstbzpGCHandle
        IntPtr        pPstb;                                    // PstbzpIntPtr
        ///////////////////////////////////////////////////////////////////////////////

        public Form1()
        {
            InitializeComponent();
        }

        private void MltMeter_Load(object sender, System.EventArgs e)
        {
            // [ݒ]
            cboYrAdrBox.SelectedIndex = 0;
            cboDelimBox.SelectedIndex = 1;
            // I@̒ǉ
            cboSelectDevice.Items.Add("[ ADVANTEST R6871E Digital Multimeter ]");
            cboSelectDevice.Items.Add("[ Sanwa Digital Multimeter 9300MF ]");
            cboSelectDevice.Items.Add("[ Iwatsu Digital Multimeter SC-7404 ]");
            cboSelectDevice.SelectedIndex = 0;                      // ݒ

            SendBuf = "F1R5M2IT1DL0RE7BZ1S0";                       /* Initialize Send Data */
            rdoTimer.Checked = true;                                /* Select timer */
            txtSendData.Text = SendBuf;
            wMsg = 0x0400 + 0x30;                                   // WM_USER + 0x30
            bTimerOn = false;

            // PinnednhCmdɕz
            if (gChCmd.IsAllocated == false)
            {
                gChCmd = GCHandle.Alloc(SubFunc.Cmd, GCHandleType.Pinned);
            }
            // PinnednhPstbɕz
            if (gChPstb.IsAllocated == false)
            {
                gChPstb = GCHandle.Alloc(Pstb, GCHandleType.Pinned);
            }
            // PinnednhŃIuWFNg̃AhX擾
            SubFunc.pCmd = gChCmd.AddrOfPinnedObject();
            pPstb = gChPstb.AddrOfPinnedObject();
        }

        private void MltMeter_FormClosed(object sender, FormClosedEventArgs e)
        {
            SrqOn = 0;                                              // Event

            Ret = gpib.SetEvent(SrqOn);                             // SRQ event It
            timer.Enabled = false;
            SubFunc.GpibExit();                                     // GpibExit֐R[(SubClass.h)

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

        // [SrqEvent֐] /////////////////////////////////////////////////////////////
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == wMsg)
            {
                ErrorOccured = false;                               // G[̗L`FbN
                SubFunc.Cmd[0] = 1;                                 // @ɑ΂ă|[O
                SubFunc.Cmd[1] = Yradr;
                do
                {
                    Ret = gpib.Poll(SubFunc.pCmd, pPstb);           // |[Os
                    if ((Ret & 0xFF) != 0)
                    {                                               // G[̏
                        SubFunc.CheckRet("GpPoll", Ret, out csBuf);
                        ErrorOccured = true;
                        break;
                    }
                    SubFunc.Cmd[0] = 2;
                    SubFunc.Cmd[1] = Yradr;
                    SubFunc.Cmd[2] = Myadr;
                    ReceiveBuf.Remove(0, ReceiveBuf.Length);        // Mobt@NA܂B
                    Srlen = (uint)ReceiveBuf.Capacity;              // ReceiveBuf̃TCY𑪂
                    Ret = gpib.Listen(SubFunc.pCmd, ref Srlen, ReceiveBuf); // M̎s
                    if ((Ret & 0xFF) >= 3)
                    {
                        SubFunc.CheckRet("GpListen", Ret, out csBuf);
                        ErrorOccured = true;
                        break;
                    }
                    SubFunc.Cmd[0] = 2;
                    SubFunc.Cmd[1] = 0x3f;                          // AX(Xi)
                    SubFunc.Cmd[2] = 0x5f;                          // Ag[N(g[J)
                    Ret = gpib.Comand(SubFunc.pCmd);                // R}h(bZ[W)M
                    if ((Ret & 0xFF) != 0)
                    {                                               // G[̏
                        SubFunc.CheckRet("GpComand", Ret, out csBuf);
                        ErrorOccured = true;
                        break;
                    }
                    Ret = gpib.Get(Yradr);                          // S@ɑ΂[GpGet]s
                    if ((Ret & 0xFF) != 0)
                    {                                               // G[̏
                        SubFunc.CheckRet("GpGet", Ret, out csBuf);
                        ErrorOccured = true;
                        break;
                    }
                    txtRet.Text = csBuf;                            // G[Ε\
                } while (false);

                if (ErrorOccured != false)
                {                                                   // G[̗L
                    SrqOn = 0;
                    Ret = gpib.SetEventSrq(this.Handle.ToInt32(), wMsg, SrqOn);    // SRQ Event̏I
                    return;
                }
                txtReceiveData.Text = ReceiveBuf.ToString().Substring(0, (int)Srlen);    // _CAOɕ\
                szBuffer = string.Format("f[^M܂B[ {0:d} ]oCg擾܂B", Srlen);
                txtRet.Text = szBuffer;

                Ret = gpib.EnableNextEvent();                       // GpEnableNextEvent֐̃R[
            }
            base.WndProc(ref m);
        }

        // [] ///////////////////////////////////////////////////////////////////
        private void btnInit_Click(object sender, System.EventArgs e)
        {
            string DelMyadr = new string(' ', 16);                  // }CAhX폜p

            Ret = (uint)SubFunc.GpibInit(out csBuf);                // Init֐̌ĂяoĂ܂B
            gpib.Boardsts(0x08, out Myadr);                         // }CAhX擾܂B
            DelMyadr = string.Format("{0:d}", Myadr);               // 𕶎ɕϊ
            Ret = (uint)cboYrAdrBox.FindStringExact(DelMyadr, -1);
            if (Ret >= 0)
            {                                                       // vCfbNXΎs
                cboYrAdrBox.Items.Remove(Ret.ToString());           // }CAhXI{bNX폜B
                if (Myadr == Yradr)
                {
                    cboYrAdrBox.SelectedIndex = 0;
                }
            }

            //Ret = gpib.Dcl();                                     // Device CleaŕA@̓Ԃň莞ԑ҂Kv

            SendBuf = txtSendData.Text;
            Srlen = (uint)SendBuf.Length;
            SubFunc.Cmd[0] = 2;                                     // R}h(bZ[W)̐
            SubFunc.Cmd[1] = Myadr;                                 // g[JAhX
            SubFunc.Cmd[2] = Yradr;                                 // XiAhX
            Ret = gpib.Talk(SubFunc.pCmd, Srlen, SendBuf);          // bZ[W𑗐M܂B
            SubFunc.CheckRet("Initialize", Ret, out csBuf);
            if ((Ret & 0xFF) == 0)
            {
                csBuf = "܂B";
            }
            txtRet.Text = csBuf;

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

        // [@ւ̑Mf[^ύX] ///////////////////////////////////////////////
        private void cboSelectDevice_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            Device = cboSelectDevice.SelectedIndex;                 // @햼̃CfbNX
            switch (Device)
            {                                                       // M@̐ݒ
                case 0:
                    szBuffer = "F1R5M2IT1DL0RE7BZ1S0";              // AhoeXg/Advantest
                    break;
                case 1:
                    szBuffer = "F1R0I0C1";                          // T/Sanwa
                    break;
                case 2:
                    szBuffer = "R0";                                // /Iwatsu
                    break;
                default:
                    break;
            }
            txtSendData.Text = szBuffer;
        }

        // [MJn] /////////////////////////////////////////////////////////////////
        private void btnReceiveStart_Click(object sender, System.EventArgs e)
        {
            uint SrqOn;                                             // SRQ Event ̏

            SrqOn = 1;                                              // s()

            if (rdoTimer.Checked == true)
            {                                                       // M^C~O
                if (!bTimerOn)
                {                                                   // ^C}I
                    timer.Enabled = true;
                    bTimerOn      = true;
                }
            }
            else
            {
                SrqOn = 1;                                          // Cxg(On SRQ)I
                Ret = gpib.SetEventSrq(this.Handle.ToInt32(), wMsg, SrqOn); // SRQ event I
                if ((Ret & 0xFF) != 0)
                {                                                   // GpSetEventSrq̖߂l`FbN
                    SubFunc.CheckRet("GpSetEventSrq", Ret, out csBuf);
                    txtRet.Text = csBuf;
                    return;
                }
                Ret = gpib.SetEvent(SrqOn);                         // GpSetEvent()֐̃R[
                if ((Ret & 0xFF) != 0)
                {
                    SubFunc.CheckRet("GpSetEvent", Ret, out csBuf);
                    txtRet.Text = csBuf;
                    return;
                }
                Ret = gpib.Get(Yradr);                              // [GET]R}hs
                if ((Ret & 0xFF) != 0)
                {                                                   // GpGet̖߂l`FbN
                    SubFunc.CheckRet("GpGet", Ret, out csBuf);
                    SrqOn = 0;                                      // ~()
                    Ret = gpib.SetEvent(SrqOn);
                    txtRet.Text = csBuf;
                    return;
                }
            }
            txtRet.Text = "MJn܂B";
        }

        // [M~] /////////////////////////////////////////////////////////////////
        private void btnReceiveStop_Click(object sender, System.EventArgs e)
        {
            txtRet.Text = "f[^M~܂B";
            if (rdoTimer.Checked == true)
            {                                                       // M^C~O
                timer.Enabled = false;                              // ^C}~
                bTimerOn      = false;
            }
            else
            {
                SrqOn = 0;
                Ret   = gpib.SetEvent(SrqOn);                       // SRQ event It
            }
        }

        // [I] /////////////////////////////////////////////////////////////////////
        private void btnExt_Click(object sender, System.EventArgs e)
        {
            SrqOn = 0;                                              // Event

            Ret = gpib.SetEvent(SrqOn);                             // SRQ event It
            timer.Enabled = false;
            SubFunc.GpibExit();                                     // GpibExit֐R[(SubClass.h)

            this.Close();                                           // _CAO܂B(vOI)
        }

        // [^C}] ///////////////////////////////////////////////////////////////////
        private void timer_Tick(object sender, System.EventArgs e)
        {
            ErrorOccured = false;
            Yradr = Convert.ToUInt32(cboYrAdrBox.Text);

            do
            {
                Ret = gpib.Get(Yradr);
                if ((Ret & 0xFF) != 0)
                {                                                   // [GpGet]̖߂l`FbN
                    SubFunc.CheckRet("GpGet", Ret, out csBuf);
                    ErrorOccured = true;
                    break;
                }
                regvalue = 0;
                while (regvalue == 0)
                {                                                   // SRQ rbg`FbN
                    if (EscCheck() == 1)
                    {
                        ErrorOccured = true;
                        csBuf = "[Esc] L[܂B";
                        break;
                    }
                    Ret = gpib.Boardsts(0x12, out regvalue);        // WX^̃AhXXe[^Xǂݍ݂܂B
                    if ((Ret & 0xFF) != 0)
                    {
                        SubFunc.CheckRet("GpBoardsts", Ret, out csBuf);
                        ErrorOccured = true;
                        break;
                    }
                }
                if (ErrorOccured == true)
                {
                    break;
                }

                do
                {
                    SubFunc.Cmd[0] = 1;
                    SubFunc.Cmd[1] = Yradr;
                    Ret = gpib.Poll(SubFunc.pCmd, pPstb);
                    gpib.Waittime(10);
                    if (bTimerOn == false)
                    {
                        break;
                    }
                } while (Ret == 128);

                if ((Ret & 0xFF) != 0)
                {                                                   // [GpPoll]̖߂l`FbN
                    SubFunc.CheckRet("GpPoll", Ret, out csBuf);
                    ErrorOccured = true;
                    break;
                }
                SubFunc.Cmd[0] = 2;
                SubFunc.Cmd[1] = Yradr;
                SubFunc.Cmd[2] = Myadr;
                ReceiveBuf.Remove(0, ReceiveBuf.Length);            // Mobt@NA܂B
                Srlen = (uint)ReceiveBuf.Capacity;
                Ret = gpib.Listen(SubFunc.pCmd, ref Srlen, ReceiveBuf);
                if ((Ret & 0xFF) >= 3)
                {                                                   // [GpListen]̖߂l`FbN
                    SubFunc.CheckRet("GpListen", Ret, out csBuf);
                    ErrorOccured = true;
                    break;
                }
                SubFunc.Cmd[0] = 2;
                SubFunc.Cmd[1] = 0x3f;
                SubFunc.Cmd[2] = 0x5f;
                Ret = gpib.Comand(SubFunc.pCmd);
                if ((Ret & 0xFF) != 0)
                {                                                   // [GpComand]̖߂l`FbN
                    SubFunc.CheckRet("GpComand", Ret, out csBuf);
                    ErrorOccured = true;
                    break;
                }
            } while (false);

                                                                    // G[ꍇ̏
            if (ErrorOccured != false)
            {
                timer.Enabled = false;
                txtRet.Text = csBuf;
                return;
            }
            txtReceiveData.Text = ReceiveBuf.ToString().Substring(0, (int)Srlen);
            szBuffer = string.Format("f[^MB[ {0:d} ]oCgM܂B", Srlen);
            txtRet.Text = szBuffer;
        }

        // [߂l] /////////////////////////////////////////////////////////////
        private void btnDelRet_Click(object sender, System.EventArgs e)
        {
            txtRet.Text = "";
        }

        // [@AhXύX] /////////////////////////////////////////////////////
        private void cboYrAdrBox_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            Yradr = Convert.ToUInt32(cboYrAdrBox.Text);             // @AhX擾
        }

        ///// [ESC]L[̐ //////////////////////////////////////////////////////////////////
        private int EscCheck()
        {
            int vKey;

            vKey = 0x1B;                                            // ESC̃AXL[R[h
            if (gpib.gpGetAsyncKeyState(vKey) != 0)
            {
                return 1;                                           // ESCL[o(߂l)
            }
            else
            {
                return 0;                                           // ESCL[Ȃ(߂l)
            }
        }

        // [f~^ύX] /////////////////////////////////////////////////////
        private void cboDelimBox_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            Eoi = 1;                                                // EOI Fgp
            Delim = (uint)cboDelimBox.SelectedIndex;
            Ret = gpib.Delim(Delim, Eoi);
        }
    }
}