﻿// High-performance Counter Sample
// Counter Header
using CcntCs;

namespace Counter
{
    public partial class Form1 : Form
    {
        public static short                     Id;                                  // Device ID
        public static short                     ChannelNum;                          // Total number of channels
        uint[]                                  CountMatch = new uint[CHANNEL_NUM];  // Count match number
        public const int                        CHANNEL_NUM = 4;
        public static IntPtr                    hMainWnd;
        const int                               WM_NOTIFY_COUNTUP = 0x0500;
        const int                               WM_NOTIFY_ERROR = 0x0501;
        const int                               WM_NOTIFY_CARRY = 0x0502;
        Ccnt                                    cnt = new Ccnt();
        private System.Windows.Forms.TextBox[]  txt_Count = new System.Windows.Forms.TextBox[CHANNEL_NUM];    // Count value control
        private System.Windows.Forms.TextBox[]  txt_Status = new System.Windows.Forms.TextBox[CHANNEL_NUM];   // Count status control

        public Form1()
        {
            InitializeComponent();
            
            //-----------------------------------
            // Control array settings
            //-----------------------------------
            //------------------
            // Count value control
            //------------------
            txt_Count[0] = txtCountValue0;
            txt_Count[1] = txtCountValue1;
            txt_Count[2] = txtCountValue2;
            txt_Count[3] = txtCountValue3;
            //------------------
            // Count status control
            //------------------
            txt_Status[0] = txtCountStatus0;
            txt_Status[1] = txtCountStatus1;
            txt_Status[2] = txtCountStatus2;
            txt_Status[3] = txtCountStatus3;
        }

        //===================================================
        // Dialog initialization
        //===================================================
        private void frmCounter_Load(object sender, System.EventArgs e)
        {
            short   ch;

            //-----------------------------------
            // Initialize dialog display
            //-----------------------------------
            txtDeviceName.Text = "CNT000";
            //-----------------------------------
            // For each channel
            //-----------------------------------
            for(ch = 0; ch < CHANNEL_NUM; ch++){
                //------------------
                // Count value control
                //------------------
                txt_Count[ch].Text = "";
                //------------------
                // Count status control
                //------------------
                txt_Status[ch].Text = "";
            }
            //-----------------------------------
            // Initializing Parameters
            //-----------------------------------
            ChannelNum = CHANNEL_NUM;
            //-----------------------------------
            // Copy window's handle
            //-----------------------------------
            hMainWnd = this.Handle;
        }

        //---------------------------------------------
        // CntInit()
        //---------------------------------------------
        private void btnCntInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string buf = new string(' ', 100);
            string error_string = new string(' ', 256);
            int    ret;
            short  i;

            //-----------------------------------
            // Get device name
            //-----------------------------------
            buf = txtDeviceName.Text;

            //------------------------------
            // Initialization
            //------------------------------
            ret = cnt.Init(buf, out Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntInit ret = {0:d}: {1}", ret, error_string);
            txtRet.Text = str;
            
            if(ret != 0){
                return;
            }
            //-----------------------------
            // Get number of channels
            //-----------------------------
            cnt.GetMaxChannels(Id, out ChannelNum);
            //-----------------------------
            // If the sample control count is exceeded, 
            // the total channel count is corrected to the control count.
            //-----------------------------
            if(ChannelNum > CHANNEL_NUM){
                ChannelNum = CHANNEL_NUM;
            }
            //-----------------------------
            // Toggles the count value and status display according to the total number of channels.
            //-----------------------------
            for(i = 0; i < CHANNEL_NUM; i++){
                //-----------------------------
                // Disables the display when the number of loops exceeds the total number of channels.
                //-----------------------------
                if(i >= ChannelNum){
                    txt_Count[i].Enabled = false;
                    txt_Status[i].Enabled = false;
                //-----------------------------
                // Enables the display when the number of loops is less than or equal to the total number of channels.
                //-----------------------------
                }else{
                    txt_Count[i].Enabled = true;
                    txt_Status[i].Enabled = true;
                }
            }
        }

        //---------------------------------------------
        // Display Counter Mode Setting dialog
        //---------------------------------------------
        private void btnCntMode_Click(object sender, System.EventArgs e)
        {
            //------------------------------
            // Display Counter Mode Setting dialog
            //------------------------------
            Mode frm = new Mode();
            frm.ShowDialog();
            frm.Dispose();
        }

        //---------------------------------------------
        // Display Notification Setting dialog
        //---------------------------------------------
        private void btnCntNotify_Click(object sender, System.EventArgs e)
        {
            //------------------------------
            // Display Notification Setting dialog
            //------------------------------
            Notify frm = new Notify();
            frm.ShowDialog();
            frm.Dispose();
        }

        //---------------------------------------------
        // Display Event Setting dialog
        //---------------------------------------------
        private void btnCntEvent_Click(object sender, System.EventArgs e)
        {
            //------------------------------
            // Display Event Setting dialog
            //------------------------------
            Event frm = new Event();
            frm.ShowDialog();
            frm.Dispose();
        }

        //---------------------------------------------
        // Start count
        //---------------------------------------------
        private void btnCntStart_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;
            short[] ChNo = new short[CHANNEL_NUM];
            short i;

            //------------------------------
            // Set parameter
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                ChNo[i] = i;
            }

            //------------------------------
            // Start count
            //------------------------------
            ret = cnt.StartCount(Id, ChNo, ChannelNum);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntStartCount ret = {0:d}: {1}", ret, error_string);
            txtRet.Text = str;
            if (ret == 0)
            {
                //------------------------------
                // Consider a device that does not have a timer notification function,
                // we use the window timer.
                // Please switch and use, according to the use.
                //------------------------------
                //------------------------------
                // Start timer
                //------------------------------
                timer1.Start();
                //------------------------------
                // When using the timer notification event of device,
                // please use the following function.
                //------------------------------
                //cnt.NotifyTimer(Id, 100, hMainWnd);
            }
        }

        //---------------------------------------------
        // Preset counter
        //---------------------------------------------
        private void btnCntPreset_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;
            short[] ChNo = new short[CHANNEL_NUM];
            uint[] PresetData = new uint[CHANNEL_NUM];
            short i;

            //------------------------------
            // Set preset value
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                ChNo[i] = i;
                PresetData[i] = (uint)i * 0x100;
            }

            //------------------------------
            // Set preset
            //------------------------------
            ret = cnt.Preset(Id, ChNo, ChannelNum, PresetData);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntPreset ret = {0:d}: {1}", ret, error_string);
            txtRet.Text = str;
        }

        //---------------------------------------------
        // Reset counter
        //---------------------------------------------
        private void btnCntReset_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;
            short[] ChNo = new short[CHANNEL_NUM];
            short i;

            //------------------------------
            // Set parameter
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                ChNo[i] = i;
            }

            //------------------------------
            // Reset counter
            //------------------------------
            ret = cnt.ZeroClearCount(Id, ChNo, ChannelNum);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntZeroClearCount ret = {0:d}: {1}", ret, error_string);
            txtRet.Text = str;
        }

        //---------------------------------------------
        // Stop count
        //---------------------------------------------
        private void btnCntStop_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;
            short[] ChNo = new short[CHANNEL_NUM];
            short i;

            //------------------------------
            // Set parameter
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                ChNo[i] = i;
            }

            //------------------------------
            // Stop counter
            //------------------------------
            ret = cnt.StopCount(Id, ChNo, ChannelNum);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntStopCount ret = {0:d}: {1}", ret, error_string);
            txtRet.Text = str;

            //------------------------------
            // Consider a device that does not have a timer notification function,
            // we use the window timer.
            // Please switch and use, according to the use.
            //------------------------------
            //------------------------------
            // Stop timer
            //------------------------------
            timer1.Stop();
            //------------------------------
            // When using the timer notification event of device,
            // please use the following function.
            //------------------------------
            //cnt.StopNotifyTimer(Id);
        }

        //---------------------------------------------
        // CntExit()
        //---------------------------------------------
        private void btnCntExit_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;

            //------------------------------
            // Consider a device that does not have a timer notification function,
            // we use the window timer.
            // Please switch and use, according to the use.
            //------------------------------
            //------------------------------
            // Stop timer
            //------------------------------
            timer1.Stop();
            //------------------------------
            // When using the timer notification event of device,
            // please use the following function.
            //------------------------------
            //cnt.StopNotifyTimer(Id);

            //------------------------------
            // Counter termination processing
            //------------------------------
            ret = cnt.Exit(Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntExit ret = {0:d}: {1}", ret, error_string);
            txtRet.Text = str;
        }

        //---------------------------------------------
        //  Exit sample program
        //---------------------------------------------
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            int ret;

            //------------------------------
            // Consider a device that does not have a timer notification function,
            // we use the window timer.
            // Please switch and use, according to the use.
            //------------------------------
            //------------------------------
            // Stop timer
            //------------------------------
            timer1.Stop();
            //------------------------------
            // When using the timer notification event of device,
            // please use the following function.
            //------------------------------
            //cnt.StopNotifyTimer(Id);

            //------------------------------
            // Counter termination processing
            //------------------------------
            ret = cnt.Exit(Id);
            this.Close();
        }

        //---------------------------------------------
        // Consider a device that does not have a timer notification function,
        // we use the window timer.
        // When using the timer notification function, please comment out the following method.
        //---------------------------------------------
        private void timer1_Tick(object sender, EventArgs e)
        {
            short[] ChNo = new short[CHANNEL_NUM];
            uint[] CntData = new uint[CHANNEL_NUM];
            uint[] StatusData = new uint[CHANNEL_NUM];
            short i;
            int ret;
            string str;
            string error_string = new string(' ', 256);

            //------------------------------
            // Set parameter
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                ChNo[i] = i;
                CntData[i] = 0;
                StatusData[i] = 0;
            }
            //------------------------------
            // Get count value
            //------------------------------
            ret = cnt.ReadCount(Id, ChNo, ChannelNum, CntData);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntReadCount ret = {0:d}: {1}", ret, error_string);
                txtRet.Text = str;
                //------------------------------
                // Stop timer
                //------------------------------
                timer1.Stop();
            }
            //------------------------------
            // Get count status
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                ret = cnt.ReadStatusEx(Id, i, out StatusData[i]);
                if (ret != 0)
                {
                    cnt.GetErrorString(ret, out error_string);
                    str = string.Format("CntReadStatus ret = {0:d}: {1}", ret, error_string);
                    txtRet.Text = str;
                    //------------------------------
                    // Stop timer
                    //------------------------------
                    timer1.Stop();
                }
            }
            //------------------------------
            // Display data
            //------------------------------
            for (i = 0; i < ChannelNum; i++)
            {
                str = string.Format("{0:D8}", CntData[i]);
                txt_Count[i].Text = str;
                str = string.Format("{0:X8}H", StatusData[i]);
                txt_Status[i].Text = str;
            }
        }

        //---------------------------------------------
        // Counter event notification processing
        //---------------------------------------------
        protected override void WndProc(ref Message m)
        {
            uint[] CntData = new uint[CHANNEL_NUM];
            uint[] StatusData = new uint[CHANNEL_NUM];
            string str;
            string error_string = new string(' ', 256);

            switch (m.Msg)
            {
                // Count Match
                case (int)CcntConst.CNTM_COUNTUP_CH0:   // Count match: 0CH
                    CountMatch[0]++;
                    if (((m.WParam.ToInt32() & 0x0ffff0000) >> 16) == 1)
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 0, UP, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[0]);
                    }
                    else
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 0, DOWN, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[0]);
                    }
                    lblNotify.Text = str;
                    break;
                // Counter Error
                case (int)CcntConst.CNTM_COUNTUP_CH1:   // Count match: 1CH
                    CountMatch[1]++;
                    if (((m.WParam.ToInt32() & 0x0ffff0000) >> 16) == 1)
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 1, UP, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[1]);
                    }
                    else
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 1, DOWN, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[1]);
                    }
                    lblNotify.Text = str;
                    break;
                case (int)CcntConst.CNTM_COUNTUP_CH2:   // Count match: 2CH
                    CountMatch[2]++;
                    if (((m.WParam.ToInt32() & 0x0ffff0000) >> 16) == 1)
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 2, UP, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[2]);
                    }
                    else
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 2, DOWN, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[2]);
                    }
                    lblNotify.Text = str;
                    break;
                case (int)CcntConst.CNTM_COUNTUP_CH3:   // Count match: 3CH
                    CountMatch[3]++;
                    if (((m.WParam.ToInt32() & 0x0ffff0000) >> 16) == 1)
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 3, UP, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[3]);
                    }
                    else
                    {
                        str = string.Format("Event:\nCount Match!\nChannel No.: 3, DOWN, Count: {0:X8}(Hex)\n Matched: {1:d} times", Convert.ToUInt32(m.LParam.ToInt64() & 0x00000000ffffffff), CountMatch[3]);
                    }
                    lblNotify.Text = str;
                    break;
                case (int)CcntConst.CNTM_COUNTER_ERROR: // Counter error
                    switch (m.LParam.ToInt32() & 0x0000ffff)
                    {
                        case (int)CcntConst.CNT_AI_ERROR:       // Abnormal input
                            str = string.Format("Event:\nAbnormal input error!\nChannel No.: {0:d}", (m.WParam.ToInt32() & 0x0ffff0000) >> 16);
                            lblNotify.Text = str;
                            break;
                        case (int)CcntConst.CNT_FLT_ERROR:      // Filter
                            str = string.Format("Event:\nFilter error!\nChannel No.: {0:d}", (m.WParam.ToInt32() & 0x0ffff0000) >> 16);
                            lblNotify.Text = str;
                            break;
                        case (int)CcntConst.CNT_ALM_ERROR:      // Alarm
                            str = string.Format("Event:\nAlarm error!\nChannel No.: {0:d}", (m.WParam.ToInt32() & 0x0ffff0000) >> 16);
                            lblNotify.Text = str;
                            break;
                    }
                    break;
                case (int)CcntConst.CNTM_CARRY_BORROW:      // Carry/Borrow
                    switch (m.LParam.ToInt32() & 0x0000ffff)
                    {
                        case (int)CcntConst.CNT_CB_CARRY:       // Carry
                            str = string.Format("Event:\nCarry!\nChannel No.: {0:d}", (m.WParam.ToInt32() & 0x0ffff0000) >> 16);
                            lblNotify.Text = str;
                            break;
                        case (int)CcntConst.CNT_CB_BORROW:      // Borrow
                            str = string.Format("Event:\nBorrow!\nChannel No.: {0:d}", (m.WParam.ToInt32() & 0x0ffff0000) >> 16);
                            lblNotify.Text = str;
                            break;
                    }
                    break;

                    /*
                    //------------------------------
                    // Consider a device that does not have a timer notification function,
                    // When using the timer notification event of device,
                    // please use the following message.
                    //------------------------------
                    case (int)CcntConst.CNTM_TIMER:    // Timer notification
                        short[] ChNo = new short[CHANNEL_NUM];
                        short i;
                        int ret;
                        //------------------------------
                        // Set parameter
                        //------------------------------
                        for (i=0; i<ChannelNum; i++) 
                        {
                            ChNo[i] = i;
                            CntData[i] = 0;
                            StatusData[i] = 0;
                        }
                        //------------------------------
                        // Get count value
                        //------------------------------
                        ret = cnt.ReadCount(Id, ChNo, ChannelNum, CntData);
                        if (ret != 0) 
                        {
                            cnt.GetErrorString(ret, out error_string);
                            str = string.Format("CntReadCount ret = {0:d}: {1}", ret, error_string);
                            txtRet.Text = str;
                            cnt.StopNotifyTimer(Id);
                        }
                        //------------------------------
                        // Get count status
                        //------------------------------
                        for (i=0; i<ChannelNum; i++) 
                        {
                            ret = cnt.ReadStatusEx(Id, i, out StatusData[i]);
                            if (ret != 0) 
                            {
                                cnt.GetErrorString(ret, out error_string);
                                str = string.Format("CntReadStatus ret = {0:d}: {1}", ret, error_string);
                                txtRet.Text = str;
                                cnt.StopNotifyTimer(Id);
                            }
                        }
                        //------------------------------
                        // Display data
                        //------------------------------
                        for (i = 0; i < ChannelNum; i++)
                        {
                            str = string.Format("{0:D8}", CntData[i]);
                            txt_Count[i].Text = str;
                            str = string.Format("{0:X8}H", StatusData[i]);
                            txt_Status[i].Text = str;
                        }
                        break;
                    */
            }
            base.WndProc(ref m);
        }
    }
}