﻿using CdioCs;
using System.Runtime.InteropServices;

namespace InterruptCallback
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.TextBox[] m_UpCountText = new System.Windows.Forms.TextBox[4];     // UpCounter Express
        private System.Windows.Forms.TextBox[] m_DownCountText = new System.Windows.Forms.TextBox[4];   // DownCounter Express

        delegate void SetCountDelegate(int BitNo, int Kind);

        Cdio dio = new Cdio();

        short m_Id;                     // Device ID
        int Ret;                        // Return Code
        string ErrorString = "";        // Error String
        int[] m_UpCount = new int[4];   // UpCounter
        int[] m_DownCount = new int[4]; // DownCounter
        public GCHandle gCh;
        public PINTCALLBACK pdelegate_func;
        public IntPtr pfunc;

        unsafe public Form1()
        {
            InitializeComponent();

            //-----------------------------------
            // Screen Item Initialization
            //-----------------------------------
            txtDeviceName.Text = "DIO000";
            txtReturnCode.Text = "";
            // Up counter
            m_UpCountText[0] = txtUpCount_0;
            m_UpCountText[1] = txtUpCount_1;
            m_UpCountText[2] = txtUpCount_2;
            m_UpCountText[3] = txtUpCount_3;
            // Down counter
            m_DownCountText[0] = txtDownCount_0;
            m_DownCountText[1] = txtDownCount_1;
            m_DownCountText[2] = txtDownCount_2;
            m_DownCountText[3] = txtDownCount_3;

            rdoRise.Checked = true;
            //-----------------------------------
            // Initialize the delegate for interrupt processing
            //-----------------------------------
            pdelegate_func = new PINTCALLBACK(CallBackProc);
            //-----------------------------------
            // Do not release the delegate
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(pdelegate_func);
            }
        }

        //---------------------------------------------------------
        // DioInit()
        //---------------------------------------------------------
        private void btnDioInit_Click(object sender, System.EventArgs e)
        {
            //-----------------------------
            // Execute initialization function and get ID
            //-----------------------------
            Ret = dio.Init(txtDeviceName.Text, out m_Id);
            //-----------------------------
            // Error process
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                return;
            }
        }

        //---------------------------------------------------------
        // Start monitoring interrupt
        //---------------------------------------------------------
        unsafe private void btnIntStart_Click(object sender, System.EventArgs e)
        {
            short BitNo;
            short Kind;

            //-----------------------------
            // Get the fixed pointer of the delegate for interrupt processing
            //-----------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //-----------------------------
            // Set callback routine
            //-----------------------------
            // Test of using void * parameter
            fixed (short* Temp = &m_Id)
                Ret = dio.SetInterruptCallBackProc(m_Id, pfunc, Temp);
            if (Ret != 0)
            {
                dio.GetErrorString(Ret, out ErrorString);
                txtReturnCode.Text = "dio.SetInterruptCallBackProc = " + Ret.ToString() + " : " + ErrorString;
                return;
            }

            //-----------------------------
            // Parameters initialization
            //-----------------------------
            for (BitNo = 0; BitNo < 4; BitNo++)
            {
                m_UpCount[BitNo] = 0;       // Up counter
                m_DownCount[BitNo] = 0;     // Down counter
            }
            if (rdoRise.Checked == true)
            {
                Kind = (short)CdioConst.DIO_INT_RISE;
            }
            else
            {
                Kind = (short)CdioConst.DIO_INT_FALL;
            }
            //-----------------------------
            // Start interrupt
            //-----------------------------
            for (BitNo = 0; BitNo < 4; BitNo++)
            {
                Ret = dio.NotifyInterrupt(m_Id, BitNo, Kind, (IntPtr)0);
                if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
                {
                    break;
                }
            }
            //-----------------------------
            // Error process
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //---------------------------------------------------------
        // Stop monitoring interrupt
        //---------------------------------------------------------
        private void btnIntStop_Click(object sender, System.EventArgs e)
        {
            short BitNo;

            //-----------------------------
            // Stop interrupt
            //-----------------------------
            for (BitNo = 0; BitNo < 4; BitNo++)
            {
                Ret = dio.NotifyInterrupt(m_Id, BitNo, (short)CdioConst.DIO_INT_NONE, (IntPtr)0);
                if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
                {
                    break;
                }
            }
            //-----------------------------
            // Error process
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //---------------------------------------------------------
        // DioExit()
        //---------------------------------------------------------
        private void btnDioExit_Click(object sender, System.EventArgs e)
        {
            //-----------------------------
            // Perform exit-process
            //-----------------------------
            Ret = dio.Exit(m_Id);
            //-----------------------------
            // Error process
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //---------------------------------------------------------
        // Dialog exit
        //---------------------------------------------------------
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            //-----------------------------
            // Perform exit-process
            //-----------------------------
            Ret = dio.Exit(m_Id);
            //-----------------------------
            // Release the garbage collection handle of the delegate for interrupt processing
            //-----------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            //-----------------------------
            // Dialog exit
            //-----------------------------
            this.Close();
        }

        //---------------------------------------------------------
        // Synchronous function for control operation
        //---------------------------------------------------------
        void SetCountText(int BitNo, int Kind)
        {
            m_UpCountText[BitNo].Text = System.Convert.ToString(m_UpCount[BitNo]);
            m_DownCountText[BitNo].Text = System.Convert.ToString(m_DownCount[BitNo]);
        }

        //---------------------------------------------------------
        // Callback routine
        //---------------------------------------------------------
        unsafe public void CallBackProc(short Id, int wParam, int lParam, void* Param)
        {
            int BitNo = (int)(lParam & 0x0000ffff);         // Interrupt BitNo
            int Kind = (int)((lParam & 0x0ffff0000) >> 16); // Rise: 1, Fall: 2, Both:
            if ((Kind & (int)CdioConst.DIO_INT_RISE) == (int)CdioConst.DIO_INT_RISE)
            {
                m_UpCount[BitNo]++;     // Up counter
            }
            if ((Kind & (int)CdioConst.DIO_INT_FALL) == (int)CdioConst.DIO_INT_FALL)
            {
                m_DownCount[BitNo]++;   // Down counter
            }

            //-----------------------------
            // Expression
            //-----------------------------
            this.Invoke(new SetCountDelegate(SetCountText), new Object[] { BitNo, Kind });

            return;
        }
    }
}