﻿using System.Diagnostics;
using System.Runtime.InteropServices;
using CcntCs;

namespace Sampling
{
    public partial class Form1 : Form
    {
        const int DATA_NUM = 1000;                              // Buffer size for bus-master
        public const int CHANNEL_NUM = 4;

        public static short Id;                                 // Device ID
        uint[,] SamplingData = new uint[DATA_NUM, CHANNEL_NUM]; // Buffer for bus-master

        Ccnt cnt = new Ccnt();

        GCHandle gCh;
        IntPtr pSamplingData;

        public Form1()
        {
            InitializeComponent();
        }

        //===================================================
        // Dialog iniitialization
        //===================================================
        private void Sampling_Load(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // Initialize screen display
            //-----------------------------------
            txtDeviceName.Text = "CNT000";

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

        //===================================================
        // Termination processing
        //===================================================
        private void Sampling_FormClosed(object sender, FormClosedEventArgs e)
        {
            int ret;

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

            //-----------------------------------
            // Termination processing
            //-----------------------------------
            ret = cnt.Exit(Id);
        }

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

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

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

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

            //-----------------------------------
            // Set message notification
            //-----------------------------------
            ret = cnt.NotifySamplingStop(Id, this.Handle);
            if (ret != (int)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, (int)ConditionDlg.NumberOfData, this.Handle);
            if (ret != (int)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 != (int)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);
            //-----------------------------------
            // Get object address by Pinned handle
            //-----------------------------------
            pSamplingData = gCh.AddrOfPinnedObject();
            ret = cnt.SamplingSetBuffer(Id, pSamplingData, CHANNEL_NUM, DATA_NUM, (short)CcntConst.CNTS_WRITE_ONCE);
            if (ret != (int)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 != (int)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;
            }
            //-----------------------------------
            // Transfer start
            //-----------------------------------
            ret = cnt.SamplingStart(Id);
            if (ret != (int)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 = "";
        }

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

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

        //===================================================
        // Display data file
        //===================================================
        private void btnData_Click(object sender, System.EventArgs e)
        {
            string buf = new string(' ', 256);
            short i, j;
            TextWriter fp;
            string file_name = "SamplingData.csv";

            //-----------------------------------
            // Write transferred data to file
            //-----------------------------------
            //-----------------------------------
            // Open file
            //-----------------------------------
            try
            {
                fp = File.CreateText(file_name);
            }
            catch (System.IO.IOException)
            {
                txtReturn.Text = "fopen : file open error.";
                return;
            }
            //-----------------------------------
            // Write data
            //-----------------------------------
            for (i = 0; i < DATA_NUM; i++)
            {
                buf = string.Format("{0:d8}: , ", i);
                for (j = 0; j < CHANNEL_NUM - 1; j++)
                {
                    buf = string.Format("{0}{1:X8}, ", buf, SamplingData[i, j]);
                }
                buf = string.Format("{0}{1:X8}", buf, SamplingData[i, j]);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // Close file
            //-----------------------------------
            fp.Close();

            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);

        }

        //===================================================
        // 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 == (int)CcntConst.CNT_ERR_SUCCESS)
            {
                txtTransCount.Text = count.ToString();
            }
        }

        //===================================================
        // 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 != (int)CcntConst.CNT_ERR_SUCCESS)
            {
                return;
            }

            // Status
            str = "";
            if ((status & (uint)CcntConst.CNTS_STATUS_BMSTOP) != 0) str += "BmStop,";
            if ((status & (uint)CcntConst.CNTS_STATUS_CNTSTART) != 0) str += "CntStart,";
            if ((status & (uint)CcntConst.CNTS_STATUS_CNTSTOP) != 0) str += "CntStop,";
            if ((status & (uint)CcntConst.CNTS_STATUS_TRGIN) != 0) str += "TrgIn,";
            if ((status & (uint)CcntConst.CNTS_STATUS_OVERRUN) != 0) str += "Overrun";
            txtStatus.Text = str;
            // Error
            str = "";
            if ((err & (uint)CcntConst.CNTS_STATUS_FIFOFULL) != 0) str += "FifoFull,";
            if ((err & (uint)CcntConst.CNTS_STATUS_SGOVERIN) != 0) str += "S/GOverIn,";
            if ((err & (uint)CcntConst.CNTS_STATUS_TRGERR) != 0) str += "TrgErr,";
            if ((err & (uint)CcntConst.CNTS_STATUS_CLKERR) != 0) str += "ClkErr,";
            if ((err & (uint)CcntConst.CNTS_STATUS_SLAVEHALT) != 0) str += "SlaveHalt,";
            if ((err & (uint)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)
        {
            this.Close();
        }

        //===================================================
        // Processing of counter event notification
        //===================================================
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case (int)CcntConst.CNTM_SAMPLING_COUNT:    // Stop transfer by specified times
                    btnCount_Click(btnCount, new System.EventArgs());
                    break;
                case (int)CcntConst.CNTM_SAMPLING_STOP:     // Transfer stopped
                    txtStatus.Text = "Stopped!";
                    btnCount_Click(btnCount, new System.EventArgs());
                    break;
            }

            base.WndProc(ref m);
        }
    }
}