using System.Text;
using CGpCmDeclCs;

namespace GpibTest
{
    public partial class Form1 : Form
    {
        CGpCmDecl GpCmDecl = new CGpCmDecl();

        int Dev;
        int Ret;

        public Form1()
        {
            InitializeComponent();
        }

        private void GpibTest_Load(object sender, System.EventArgs e)
        {
            txtAddress.Text = "1";
            txtMaster.Text = "*IDN?";
            txtSlave.Text = "";
            txtSPoll.Text = "0";
        }

        private void GpibTest_FormClosed(object sender, FormClosedEventArgs e)
        {
            GpCmDecl.Pkibonl(Dev, 0);
        }

        private void btnInit_Click(object sender, System.EventArgs e)
        {
            string address = new string(' ', 100);
            int pad;

            address = txtAddress.Text;
            try
            {
                pad = Convert.ToInt32(address);
            }
            catch (System.FormatException)
            {
                pad = 0;
            }

            Dev = GpCmDecl.Pkibdev(0, pad, 0, (int)CGpCmDeclConst.T10s, 1, 0);

            Ret = GpCmDecl.PkThreadIbsta();
            if ((Ret & (int)CGpCmDeclConst.ERR) != 0)
            {
                MessageBox.Show("Unable to open device");
            }
        }

        private void btnMaster_Click(object sender, System.EventArgs e)
        {
            string wrtbuf = new string(' ', 100);
            int nCnt;

            wrtbuf = txtMaster.Text;

            nCnt = wrtbuf.Length;
            GpCmDecl.Pkibwrt(Dev, wrtbuf, nCnt);

            Ret = GpCmDecl.PkThreadIbsta();
            if ((Ret & (int)CGpCmDeclConst.ERR) != 0)
            {
                MessageBox.Show("Unable to write to device");
            }
        }

        private void btnSlave_Click(object sender, System.EventArgs e)
        {
            StringBuilder rdbuf = new StringBuilder("", 100);

            GpCmDecl.Pkibrd(Dev, rdbuf, rdbuf.Capacity);
            int nCnt = GpCmDecl.PkThreadIbcntl();

            Ret = GpCmDecl.PkThreadIbsta();
            if ((Ret & (int)CGpCmDeclConst.ERR) != 0)
            {
                MessageBox.Show("Unable to read from device");
            }

            txtSlave.Text = rdbuf.ToString(0, nCnt);
        }

        private void btnSPoll_Click(object sender, System.EventArgs e)
        {
            char spr;
            string szBuff = new string(' ', 10);

            GpCmDecl.Pkibrsp(Dev, out spr);

            Ret = GpCmDecl.PkThreadIbsta();
            if ((Ret & (int)CGpCmDeclConst.ERR) != 0)
            {
                MessageBox.Show("Unable to serial poll");
            }

            txtSPoll.Text = string.Format("{0:x} H", (int)spr);
        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            GpCmDecl.Pkibonl(Dev, 0);
            this.Close();
        }
    }
}