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

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

        // Setting ///////////////////////////////////////
        string szBuffer = new string(' ', 1024);            // Buffer
        uint Ret;                                           // Return value
        uint Myadr, /*Yradr, */MasterMode;                  // MyAddress,Address of device,ModeSelect(Master=0,Slave=1)
        uint Delim, Eoi;                                    // Delimiter
        uint            /*Timeout, Ifctime,Dmamode, */Srlen;//10000,1,1(Default),Length of str
        uint P_stb, P_eoi;                                  // 
        string srBuffer = new string(' ', 10000);           // Buffer
        //uint uTimerTrm;                                   // Used Timer
        //uint uTimerEvent;                                 // Used Timer
        string csBuf = "";                                  // csBuf is String type
        string pStb = "";                                   // Status Byte
        StringBuilder rvBuffer = new StringBuilder(10000);  // Buffer
        GCHandle gChCmd;                                    // GCHandle for cmd array
        //////////////////////////////////////////////////

        public Form1()
        {
            InitializeComponent();
        }

        private void Slave_Load(object sender, System.EventArgs e)
        {
            // ****************************************************** Setting ***
            cboDelimBox.SelectedIndex = 1;
            txtSendData.Text = "_0123456789_ Test Data / 33 Bytes";
            cboStsByte.Text = "40";                             // Default
            // ******************************************************************

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

        private void Slave_FormClosed(object sender, FormClosedEventArgs e)
        {
            SubFunc.GpibExit();                                 // Function of SubClass

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

        //////////////////////////////////////////// Initialize ///
        private void btnInit_Click(object sender, System.EventArgs e)
        {
            SubFunc.GpibInit(out csBuf);                        // Some Initialize
            gpib.Boardsts(0x0a, out MasterMode);
            gpib.Boardsts(0x08, out Myadr);
            txtMyAddress.Text = Myadr.ToString();

            if (MasterMode == 0)
            {                                                   // Not Slave
                txtRet.Text = "This is not Slave.";
                return;
            }
            else
            {
                btnSend.Enabled = true;
                btnReceive.Enabled = true;
                btnSrqOn.Enabled = true;
                txtRet.Text = csBuf;
            }

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

        //////////////////////////////////////////////// SRQ ON ///
        private void btnSrqOn_Click(object sender, System.EventArgs e)
        {
            btnSrqOn.Enabled = false;
            btnSrqOff.Enabled = true;
            btnExt.Enabled = false;

            pStb = cboStsByte.Text;                             // Get count of m_StsByte
            P_stb = SubFunc.chr2hex(pStb);                      // SubClass Files
            Ret = gpib.Ppollmode(2);                            // Parelell mode set
            SubFunc.CheckRet("GpPollmode", Ret, out csBuf);     // Error check 
            Ret = gpib.SrqEx(P_stb, 1, 1);                      // SRQ mode set
            SubFunc.CheckRet("GpSrqEx", Ret, out csBuf);        // Error check

            timer.Enabled = true;                               // TimerEvent

            btnSend.Enabled = false;
            btnReceive.Enabled = false;
            btnInit.Enabled = false;
            txtRet.Text = "Waitting for polling by Master...";
        }

        /////////////////////////////////////////////// SRQ OFF ///
        private void btnSrqOff_Click(object sender, System.EventArgs e)
        {
            btnSrqOn.Enabled = true;
            btnSrqOff.Enabled = false;

            timer.Enabled = false;                              // Stop Timer
            txtRet.Text = "Send to SRQ stopped.";

            btnSend.Enabled = true;
            btnReceive.Enabled = true;
            btnInit.Enabled = true;
            btnSrqOn.Enabled = true;
            btnExt.Enabled = true;
        }

        ////////////////////////////////////////////////// Send ///
        private void btnSend_Click(object sender, System.EventArgs e)
        {
            txtRet.Text = "Data sending...";
            txtRet.Refresh();                                   // Redraw

            srBuffer = txtSendData.Text;                        // Copy srBuffer down from m_SendData
            Srlen = (uint)srBuffer.Length;                      // Length of srBuffer

            if (Srlen != 0x0)
            {                                                   // Srlen is not 0
                SubFunc.Cmd[0] = 0;                             // Total commands
                Ret = gpib.Talk(SubFunc.pCmd, Srlen, srBuffer); // Send data
                SubFunc.CheckRet("GpTalk", Ret, out csBuf);     // Error Check
            }
            else
                csBuf = "There is no data.";

            txtRet.Text = csBuf;
        }

        /////////////////////////////////////////////// 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;
            btnSrqOn.Enabled = false;
            btnExt.Enabled = false;

            txtRet.Text = "Data Receiving...";
            txtRet.Refresh();                                   // Redraw

            SubFunc.Cmd[0] = 0x00;                              // Total commands
            rvBuffer.Remove(0, rvBuffer.Length);                // Clear receive buffer
            Srlen = (uint)rvBuffer.Capacity;                    // Length of Srlen
            Ret = gpib.Listen(SubFunc.pCmd, ref Srlen, rvBuffer);// Receive Data
            if (SubFunc.CheckRet("GpListen", Ret, out csBuf) == 0)
            {                                                   // Error check
                StartIndex = Convert.ToInt32(Srlen);
                Strlen = rvBuffer.Length - StartIndex;
                txtReceiveData.Text = rvBuffer.Remove(StartIndex, Strlen).ToString();
                szBuffer = string.Format("Data Receiving is Finished. Get [ {0:d} ] byte.", Srlen);
                csBuf = szBuffer;
            }
            txtRet.Text = csBuf;
            btnSend.Enabled = true;
            btnReceive.Enabled = true;
            btnInit.Enabled = true;
            btnSrqOn.Enabled = true;
            btnExt.Enabled = true;
        }

        ///////////////////////////////////////////////// Timer ///
        private void timer_Tick(object sender, System.EventArgs e)
        {
            Ret = gpib.Chkstb(out P_stb, out P_eoi);
            SubFunc.CheckRet("StatusByte", Ret, out csBuf);

            if ((P_stb & 0x40) != 0x40)
            {                                                   // 0x40 mask
                txtRet.Text = "[SRQ] was received by master.";
                timer.Enabled = false;                          // TimerKill

                btnSend.Enabled = true;
                btnReceive.Enabled = true;
                btnInit.Enabled = true;
                btnSrqOn.Enabled = true;
                btnSrqOff.Enabled = false;
                btnExt.Enabled = true;
            }
        }

        ///////////////////////////////////////// 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 = "";
        }

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

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