﻿using System.Diagnostics;
using System.Runtime.InteropServices;
// Counter Header
using CcntCs;

namespace Infinite
{
    public partial class Form1 : Form
    {
        public static short Id;                                 // Device ID
        uint[] CountMatch = new uint[CHANNEL_NUM];              // Count match number
        public const int CHANNEL_NUM = 4;
        public const int DATA_NUM = 1000;
        int NumberOfData = 500;
        uint[,] SamplingData = new uint[DATA_NUM, CHANNEL_NUM]; // Buffer for sampling
        public static uint ReadIndex;                           // Read pointer
        public static uint WriteIndex;                          // Write pointer
        public static uint PreCount;                            // Previous transfer count
        public static uint PreCarry;                            // Previous carry count
        public static string file_name = "infinite.csv";

        Ccnt cnt = new Ccnt();

        GCHandle gCh;
        IntPtr pSamplingData;

        public Form1()
        {
            InitializeComponent();
        }

        //===================================================
        // Dialog initialization
        //===================================================
        private void Infinite_Load(object sender, System.EventArgs e)
        {

            //-----------------------------------
            // Initialize dialog display
            //-----------------------------------
            txtDeviceName.Text = "CNT000";

            //-----------------------------------
            // Specify Pinned handle to SamplingData
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(SamplingData, GCHandleType.Pinned);
            }
        }

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

            //-----------------------------------
            // 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);
            txtReturn.Text = str;
        }

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

        //===================================================
        // Condition Setting
        //===================================================
        private void btnCondition_Click(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // Display Condition Setting dialog
            //-----------------------------------
            frmCondition dlg = new frmCondition();
            dlg.ShowDialog();
            dlg.Dispose();
        }

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


            //-----------------------------------
            // Set message notification
            //-----------------------------------
            ret = cnt.NotifySamplingStop(Id, this.Handle);
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntNotifySamplingStop ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            ret = cnt.NotifySamplingCount(Id, NumberOfData, this.Handle);
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntNotifySamplingCount ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //-----------------------------------
            // Reset FIFO (Input)
            //-----------------------------------
            ret = cnt.SamplingFifoReset(Id);
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingFifoReset ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //-----------------------------------
            // Set data buffer
            //-----------------------------------
            Array.Clear(SamplingData, 0, SamplingData.Length);
            pSamplingData = gCh.AddrOfPinnedObject();
            ret = cnt.SamplingSetBuffer(Id, pSamplingData, CHANNEL_NUM, DATA_NUM, (short)CcntConst.CNTS_WRITE_RING);
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingSetBuffer ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //------------------------------
            // Set parameter
            //------------------------------
            for (i = 0; i < CHANNEL_NUM; i++)
            {
                ChNo[i] = i;
            }
            //------------------------------
            // Start count
            //------------------------------
            ret = cnt.StartCount(Id, ChNo, CHANNEL_NUM);
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntStartCount ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //-----------------------------------
            // Initialize count
            //-----------------------------------
            ReadIndex = 0;      // Read pointer
            WriteIndex = 0;     // Write pointer
            PreCount = 0;       // Previous transfer count
            PreCarry = 0;       // Previous carry count
                                //-----------------------------------
                                // Delete data file
                                //-----------------------------------
            File.Delete(file_name);
            //-----------------------------------
            // Start transfer
            //-----------------------------------
            ret = cnt.SamplingStart(Id);
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingStart ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            txtTransCount.Text = "";
            txtStatus.Text = "";
            txtError.Text = "";
            return;
        }

        //===================================================
        // Stop transfer
        //===================================================
        private void btnStop_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Stop transfer
            //-----------------------------------
            ret = cnt.SamplingStop(Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntSamplingStop ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            return;
        }

        //===================================================
        // Display data file
        //===================================================
        private void btnData_Click(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);
            return;
        }

        //===================================================
        // Transfer count
        //===================================================
        private void btnCount_Click(object sender, System.EventArgs e)
        {
            uint count = 0, carry = 0;
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Get transfer count
            //-----------------------------------
            ret = cnt.GetSamplingCount(Id, out count, out carry);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntGetSamplingCount ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            if (ret == (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                str = string.Format("{0:d}", count);
                txtTransCount.Text = str;
            }
            return;
        }

        //===================================================
        // Transfer status
        //===================================================
        private void btnStatus_Click(object sender, System.EventArgs e)
        {
            uint status, err;
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Get transfer status
            //-----------------------------------
            ret = cnt.GetSamplingStatus(Id, out status, out err);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntGetSamplingStatus ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            if (ret != (uint)CcntConst.CNT_ERR_SUCCESS)
            {
                return;
            }

            // Status
            str = "";
            if ((status & (short)CcntConst.CNTS_STATUS_BMSTOP) != 0)
            {
                str += "BmStop,";
            }
            if ((status & (short)CcntConst.CNTS_STATUS_CNTSTART) != 0)
            {
                str += "CntStart,";
            }
            if ((status & (short)CcntConst.CNTS_STATUS_CNTSTOP) != 0)
            {
                str += "CntStop,";
            }
            if ((status & (short)CcntConst.CNTS_STATUS_TRGIN) != 0)
            {
                str += "TrgIn,";
            }
            if ((status & (short)CcntConst.CNTS_STATUS_OVERRUN) != 0)
            {
                str += "Overrun";
            }
            txtStatus.Text = str;
            // Error
            str = "";
            if ((err & (short)CcntConst.CNTS_STATUS_FIFOFULL) != 0)
            {
                str += "FifoFull,";
            }
            if ((err & (short)CcntConst.CNTS_STATUS_SGOVERIN) != 0)
            {
                str += "S/GOverIn,";
            }
            if ((err & (short)CcntConst.CNTS_STATUS_TRGERR) != 0)
            {
                str += "TrgErr,";
            }
            if ((err & (short)CcntConst.CNTS_STATUS_CLKERR) != 0)
            {
                str += "ClkErr,";
            }
            if ((err & (short)CcntConst.CNTS_STATUS_SLAVEHALT) != 0)
            {
                str += "SlaveHalt,";
            }
            if ((err & (short)CcntConst.CNTS_STATUS_MASTERHALT) != 0)
            {
                str += "MasterHalt";
            }

            txtError.Text = str;
        }

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

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

        //===================================================
        // Exit
        //===================================================
        private void btnExit_Click(object sender, System.EventArgs e)
        {

            //-----------------------------------
            // Free GCHandle
            //-----------------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            this.Close();
        }

        //===================================================
        // Counter Event notification processing
        //===================================================
        protected override void WndProc(ref Message m)
        {
            int ret;
            uint count, carry;
            uint data_count, ch_no, Cnt;
            TextWriter fp;
            string buf = new string(' ', 100);
            string str;

            switch (m.Msg)
            {
                case (short)CcntConst.CNTM_SAMPLING_COUNT:  // Specified number transfer completion
                                                            //-----------------------------------
                                                            // Retrieve transfer position on data buffer
                                                            //-----------------------------------
                    ret = cnt.GetSamplingWritePointer(Id, out WriteIndex, out count, out carry);
                    //-----------------------------------
                    // Check overflow error
                    //-----------------------------------
                    if (carry == PreCarry)
                    {
                        if (count > (PreCount + DATA_NUM))
                        {
                            str = string.Format("Overrun Error!(count = {0:d})", count);
                            txtError.Text = str;
                            return;
                        }
                    }
                    //-----------------------------------
                    // If count value is same as previous, exit current operation
                    // (When it was called from the transfer completion message)
                    //-----------------------------------
                    if ((count == PreCount) && (carry == PreCarry))
                    {
                        return;
                    }
                    //-----------------------------------
                    // Write transferred data to file
                    //-----------------------------------
                    //-----------------------------------
                    // Open file
                    //-----------------------------------
                    try
                    {
                        fp = File.AppendText(file_name);
                    }
                    catch (System.IO.IOException)
                    {
                        txtReturn.Text = "fopen : file open error.";
                        return;
                    }
                    //-----------------------------------
                    // Write data
                    //-----------------------------------
                    if (WriteIndex > ReadIndex)
                    {
                        Cnt = count - (WriteIndex - ReadIndex);
                        for (data_count = ReadIndex; data_count < WriteIndex; data_count++)
                        {
                            buf = string.Format("{0:d8}: , ", Cnt);
                            for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++)
                            {
                                buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count, ch_no]);
                            }
                            buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count, ch_no]);
                            fp.WriteLine(buf);

                            Cnt++;
                        }
                    }
                    else
                    {
                        Cnt = count - (DATA_NUM - ReadIndex + WriteIndex);
                        for (data_count = ReadIndex; data_count < DATA_NUM; data_count++)
                        {
                            buf = string.Format("{0:d8} , ", Cnt);
                            for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++)
                            {
                                buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count, ch_no]);

                            }
                            buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count, ch_no]);
                            fp.WriteLine(buf);

                            Cnt++;
                        }
                        for (data_count = 0; data_count < WriteIndex; data_count++)
                        {
                            buf = string.Format("{0:d8} , ", Cnt);
                            for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++)
                            {
                                buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count, ch_no]);
                            }
                            buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count, ch_no]);
                            fp.WriteLine(buf);

                            Cnt++;
                        }
                    }
                    //-----------------------------------
                    // Close file
                    //-----------------------------------
                    fp.Close();
                    //-----------------------------------
                    // Set read pointer
                    //-----------------------------------
                    ReadIndex = WriteIndex;
                    PreCount = count;
                    PreCarry = carry;
                    //-----------------------------------
                    // Display transfer count value
                    //-----------------------------------
                    str = string.Format("{0:d}", count);
                    txtTransCount.Text = str;
                    break;

                case (short)CcntConst.CNTM_SAMPLING_STOP:   // Transfer completion
                    txtStatus.Text = "Stopped!";
                    //-----------------------------------
                    // Retrieve transfer position on data buffer
                    //-----------------------------------
                    ret = cnt.GetSamplingWritePointer(Id, out WriteIndex, out count, out carry);
                    //-----------------------------------
                    // Check overflow error
                    //-----------------------------------
                    if (carry == PreCarry)
                    {
                        if (count > (PreCount + DATA_NUM))
                        {
                            str = string.Format("Overrun Error!(count = {0:d})", count);
                            txtError.Text = str;
                            return;
                        }
                    }
                    //-----------------------------------
                    // If count value is same as previous, exit current operation
                    //  (In case of called from transfer completion message)
                    //-----------------------------------
                    if ((count == PreCount) && (carry == PreCarry))
                    {
                        return;
                    }
                    //-----------------------------------
                    // Write transferred data to file
                    //-----------------------------------
                    //-----------------------------------
                    // Open file
                    //-----------------------------------
                    try
                    {
                        fp = File.AppendText(file_name);
                    }
                    catch (System.IO.IOException)
                    {
                        txtReturn.Text = "fopen : file open error.";
                        return;
                    }
                    //-----------------------------------
                    // Write data
                    //-----------------------------------
                    if (WriteIndex > ReadIndex)
                    {
                        Cnt = count - (WriteIndex - ReadIndex);
                        for (data_count = ReadIndex; data_count < WriteIndex; data_count++)
                        {
                            buf = string.Format("{0:d8}: , ", Cnt);
                            for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++)
                            {
                                buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count, ch_no]);
                            }
                            buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count, ch_no]);
                            fp.WriteLine(buf);

                            Cnt++;
                        }
                    }
                    else
                    {
                        Cnt = count - (DATA_NUM - ReadIndex + WriteIndex);
                        for (data_count = ReadIndex; data_count < DATA_NUM; data_count++)
                        {
                            buf = string.Format("{0:d8} , ", Cnt);
                            for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++)
                            {
                                buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count, ch_no]);
                            }
                            buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count, ch_no]);
                            fp.WriteLine(buf);

                            Cnt++;
                        }
                        for (data_count = 0; data_count < WriteIndex; data_count++)
                        {
                            buf = string.Format("{0:d8} , ", Cnt);
                            for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++)
                            {
                                buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count, ch_no]);
                            }
                            buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count, ch_no]);
                            fp.WriteLine(buf);

                            Cnt++;
                        }
                    }
                    //-----------------------------------
                    // Close file
                    //-----------------------------------
                    fp.Close();
                    //-----------------------------------
                    // Set read pointer
                    //-----------------------------------
                    ReadIndex = WriteIndex;
                    PreCount = count;
                    PreCarry = carry;
                    //-----------------------------------
                    // Display transf counter value
                    //-----------------------------------
                    str = string.Format("{0:d}", count);
                    txtTransCount.Text = str;
                    break;
            }
            base.WndProc(ref m);
        }
    }
}