﻿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[8];
        private System.Windows.Forms.TextBox[] m_DownCountText = new System.Windows.Forms.TextBox[8];

        delegate void SetCountDelegate(int BitNo, int Kind);
        /// <summary>
        /// Create instance Cdio class
        /// </summary>
        Cdio dio = new Cdio();

        public short        m_Id;                        // デバイスID
        public int[]        m_UpCount   = new int[8];    // アップカウント
        public int[]        m_DownCount = new int[8];    // ダウンカウント
        public GCHandle     gCh;
        public PINTCALLBACK pdelegate_func;
        public IntPtr       pfunc;

        unsafe public Form1()
        {
            InitializeComponent();

            m_UpCountText[0] = txtUpCount_0;
            m_UpCountText[1] = txtUpCount_1;
            m_UpCountText[2] = txtUpCount_2;
            m_UpCountText[3] = txtUpCount_3;

            m_DownCountText[0] = txtDownCount_0;
            m_DownCountText[1] = txtDownCount_1;
            m_DownCountText[2] = txtDownCount_2;
            m_DownCountText[3] = txtDownCount_3;

            rdoRise.Checked = true;

            txtReturnCode.Text = "";
            //-----------------------------------
            // 割り込み処理用デリゲート初期化
            //-----------------------------------
            pdelegate_func = new PINTCALLBACK(CallBackProc);
            //-----------------------------------
            // デリゲートが開放されないように設定します。
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(pdelegate_func);
            }
        }

        //---------------------------------------------------------
        // DioInit()
        //---------------------------------------------------------
        private void btnDioInit_Click(object sender, System.EventArgs e)
        {
            int    Ret;
            string ErrorString;

            //-----------------------------
            // 初期化処理、デバイスID取得
            //-----------------------------
            Ret = dio.Init(txtDeviceName.Text, out m_Id);
            //-----------------------------
            // エラー処理
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                return;
            }
        }

        //---------------------------------------------------------
        // 割り込み開始
        //---------------------------------------------------------
        unsafe private void btnIntStart_Click(object sender, System.EventArgs e)
        {
            int    Ret = 0;
            short  BitNo;
            short  Kind;
            string ErrorString;

            //-----------------------------
            // 割り込み処理用デリゲートの固定ポインタを取得
            //-----------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //-----------------------------
            // コールバックルーチン
            //-----------------------------
            // 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;
            }
            //-----------------------------
            // パラメータ初期化
            //-----------------------------
            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;
            }
            //-----------------------------
            // 各ビットごとに
            //-----------------------------
            for (BitNo = 0; BitNo < 4; BitNo++)
            {
                //-----------------------------
                // 割り込みイベント設定
                //-----------------------------
                Ret = dio.NotifyInterrupt(m_Id, BitNo, Kind, (IntPtr)0);
                if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
                {
                    break;
                }
            }
            //-----------------------------
            // エラー処理
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //---------------------------------------------------------
        // 割り込み停止
        //---------------------------------------------------------
        private void btnIntStop_Click(object sender, System.EventArgs e)
        {
            int   Ret = 0;
            short BitNo;

            //-----------------------------
            // 各ビットごとに
            //-----------------------------
            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;
                }
            }
            //-----------------------------
            // エラー処理
            //-----------------------------
            string ErrorString;
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //---------------------------------------------------------
        // DioExit()
        //---------------------------------------------------------
        private void btnDioExit_Click(object sender, System.EventArgs e)
        {
            int    Ret;
            string ErrorString;

            //-----------------------------
            // DioExit処理
            //-----------------------------
            Ret = dio.Exit(m_Id);
            //-----------------------------
            // エラー処理
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //---------------------------------------------------------
        // ダイアログExit
        //---------------------------------------------------------
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            int    Ret;
            string ErrorString;

            //-----------------------------
            // DioExit処理
            //-----------------------------
            Ret = dio.Exit(m_Id);
            //-----------------------------
            // エラー処理
            //-----------------------------
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            //-----------------------------
            // 割り込み処理用デリゲートのガベージコレクションハンドルを開放
            //-----------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            this.Close();
        }

        //---------------------------------------------------------
        // コントロール操作用同期関数
        //---------------------------------------------------------
        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]);
        }

        //---------------------------------------------------------
        // コールバックルーチン
        //---------------------------------------------------------
        unsafe public void CallBackProc(short Id, int wParam, int lParam, void* Param)
        {
            int BitNo;
            int Kind;

            BitNo = (int)(lParam & 0x0000ffff);
            Kind  = (int)((lParam & 0x0ffff0000) >> 16);
            //-----------------------------
            // 立ち上がり
            //-----------------------------
            if ((Kind & (int)CdioConst.DIO_INT_RISE) == (int)CdioConst.DIO_INT_RISE)
            {
                m_UpCount[BitNo]++;
            }
            //-----------------------------
            // 立ち下がり
            //-----------------------------
            if ((Kind & (int)CdioConst.DIO_INT_FALL) == (int)CdioConst.DIO_INT_FALL)
            {
                m_DownCount[BitNo]++;
            }
            //-----------------------------
            // カウント値表示
            //-----------------------------
            this.Invoke(new SetCountDelegate(SetCountText), new Object[] { BitNo, Kind });
            return;
        }
    }
}