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

namespace Sync
{
    public partial class Form1 : Form
    {
        public const int CHANNEL_NUM = 8;
        const int DATA_NUM = 1000;

        public static short M_Id;                       // Device ID of mater
        public static short S_Id;                       // Device ID of slave


        uint[,] M_SampData = new uint[DATA_NUM, CHANNEL_NUM];
        uint[,] S_SampData = new uint[DATA_NUM, CHANNEL_NUM];

        Ccnt cnt = new Ccnt();

        GCHandle M_gCh, S_gCh;
        IntPtr pM_SampData, pS_SampData;

        public Form1()
        {
            InitializeComponent();
        }

        //===================================================
        // Dialog initialization
        //===================================================
        private void Sync_Load(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // Initialize dialog display
            //-----------------------------------
            txtMDeviceName.Text = "CNT000";
            txtSDeviceName.Text = "CNT001";

            //-----------------------------------
            // Specify Pinned handle to M_SampData and S_SampData
            //-----------------------------------
            if (M_gCh.IsAllocated == false)
            {
                M_gCh = GCHandle.Alloc(M_SampData, GCHandleType.Pinned);
            }
            if (S_gCh.IsAllocated == false)
            {
                S_gCh = GCHandle.Alloc(S_SampData, GCHandleType.Pinned);
            }
        }

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

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

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

        //===================================================
        // CntInit() for master
        //===================================================
        private void btnMInit_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 = txtMDeviceName.Text;

            //-----------------------------------
            // Initialization
            //-----------------------------------
            ret = cnt.Init(buf, out M_Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntInit ret = {0:d}: {1}", ret, error_string);
            txtMRet.Text = str;
        }

        //===================================================
        // CntInit() for slave
        //===================================================
        private void btnSInit_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 = txtSDeviceName.Text;

            //-----------------------------------
            // Initialization
            //-----------------------------------
            ret = cnt.Init(buf, out S_Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntInit ret = {0:d}: {1}", ret, error_string);
            txtSRet.Text = str;
        }

        //===================================================
        // Condition setting for master
        //===================================================
        private void btnMCntMode_Click(object sender, System.EventArgs e)
        {
            ModeDlg dlg = new ModeDlg();

            //-----------------------------------
            // Open "Counter Mode" dialog
            //-----------------------------------
            dlg.Id = M_Id;
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // Condition setting for slave
        //===================================================
        private void btnSCntMode_Click(object sender, System.EventArgs e)
        {
            ModeDlg dlg = new ModeDlg();

            //-----------------------------------
            // Open "Counter Mode" dialog
            //-----------------------------------
            dlg.Id = S_Id;
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // Sampling mode setting for master
        //===================================================
        private void btnMSmpMode_Click(object sender, System.EventArgs e)
        {
            MSampMode dlg = new MSampMode();
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // Sampling mode setting for slave
        //===================================================
        private void btnSSmpMode_Click(object sender, System.EventArgs e)
        {
            SSampMode dlg = new SSampMode();
            dlg.ShowDialog();
            dlg.Dispose();
        }

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

            //-----------------------------------
            // Set notification
            //-----------------------------------
            ret = cnt.NotifySamplingStop(M_Id, this.Handle);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntNotifySamplingStop ret = {0:d}: {1}", ret, error_string);
                txtMRet.Text = str;
                return;
            }

            ret = cnt.NotifySamplingCount(M_Id, (int)MSampMode.M_NotifyCount, this.Handle);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntNotifySamplingCount ret = {0:d}: {1}", ret, error_string);
                txtMRet.Text = str;
                return;
            }

            //-----------------------------------
            // Reset FIFO
            //-----------------------------------
            ret = cnt.SamplingFifoReset(M_Id);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingFifoReset ret = {0:d}: {1}", ret, error_string);
                txtMRet.Text = str;
                return;
            }

            //-----------------------------------
            // Set buffer
            //-----------------------------------
            Array.Clear(M_SampData, 0, M_SampData.Length);
            //-----------------------------------
            // Get object address by Pinned handle
            //-----------------------------------
            pM_SampData = M_gCh.AddrOfPinnedObject();
            ret = cnt.SamplingSetBuffer(M_Id, pM_SampData, CHANNEL_NUM, DATA_NUM, MSampMode.M_IsRing);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingSetBuffer ret = {0:d}: {1}", ret, error_string);
                txtMRet.Text = str;
                return;
            }
            //-----------------------------------
            // Start counter
            //-----------------------------------
            for (i = 0; i < CHANNEL_NUM; i++)
            {
                ChNo[i] = i;
            }
            ret = cnt.StartCount(M_Id, ChNo, CHANNEL_NUM);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntStartCount ret = {0:d}: {1}", ret, error_string);
                txtMRet.Text = str;
                return;
            }

            //-----------------------------------
            // Start sampling
            //-----------------------------------
            ret = cnt.SamplingStart(M_Id);
            csMsg = string.Format("CntStartSampling : RetCode = {0:X}H", ret);
            txtMRet.Text = csMsg;
            txtMCount.Text = "";
            txtMStatus.Text = "";
            txtMError.Text = "";
        }

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

            //-----------------------------------
            // Set notification
            //-----------------------------------
            ret = cnt.NotifySamplingStop(S_Id, this.Handle);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntNotifySamplingStop ret = {0:d}: {1}", ret, error_string);
                txtSRet.Text = str;
                return;
            }
            ret = cnt.NotifySamplingCount(S_Id, (int)SSampMode.S_NotifyCount, this.Handle);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntNotifySamplingCount ret = {0:d}: {1}", ret, error_string);
                txtSRet.Text = str;
                return;
            }

            //-----------------------------------
            // Reset FIFO
            //-----------------------------------
            ret = cnt.SamplingFifoReset(S_Id);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingFifoReset ret = {0:d}: {1}", ret, error_string);
                txtMRet.Text = str;
                return;
            }
            //-----------------------------------
            // Set buffer
            //-----------------------------------
            Array.Clear(S_SampData, 0, M_SampData.Length);
            //-----------------------------------
            // Get object address by Pinned handle
            //-----------------------------------
            pS_SampData = S_gCh.AddrOfPinnedObject();
            ret = cnt.SamplingSetBuffer(S_Id, pS_SampData, CHANNEL_NUM, DATA_NUM, SSampMode.S_IsRing);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntSamplingSetBuffer ret = {0:d}: {1}", ret, error_string);
                txtSRet.Text = str;
                return;
            }
            //-----------------------------------
            // Start counter
            //-----------------------------------
            for (i = 0; i < CHANNEL_NUM; i++)
            {
                ChNo[i] = i;
            }
            ret = cnt.StartCount(S_Id, ChNo, CHANNEL_NUM);
            if (ret != 0)
            {
                cnt.GetErrorString(ret, out error_string);
                str = string.Format("CntStartCount ret = {0:d}: {1}", ret, error_string);
                txtSRet.Text = str;
                return;
            }
            //-----------------------------------
            // Start sampling
            //-----------------------------------
            ret = cnt.SamplingStart(S_Id);
            csMsg = string.Format("CntStartSampling : RetCode = {0:X}H", ret);
            txtSRet.Text = csMsg;
            txtSCount.Text = "";
            txtSStatus.Text = "";
            txtSError.Text = "";
        }

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

            ret = cnt.SamplingStop(M_Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntSamplingStop ret = {0:d}: {1}", ret, error_string);
            txtMRet.Text = str;
        }

        //===================================================
        // Slave stop
        //===================================================
        private void btnSStop_Click(object sender, System.EventArgs e)
        {
            int ret;
            string csMsg;

            ret = cnt.SamplingStop(S_Id);
            csMsg = string.Format("CntStopSampling : Ret = {0:X}H", ret);
            txtSRet.Text = csMsg;
        }

        //===================================================
        // Get master data
        //===================================================
        private void btnMData_Click(object sender, System.EventArgs e)
        {
            uint i, j;
            TextWriter fp;
            string szFileName = "Sampling1.txt";
            string szLine = new string(' ', 500);
            string szTmp = new string(' ', 100);

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

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

        //===================================================
        // Get slave data
        //===================================================
        private void btnSData_Click(object sender, System.EventArgs e)
        {
            uint i, j;
            TextWriter fp;
            string szFileName = "Sampling2.txt";
            string szLine = new string(' ', 500);
            string szTmp = new string(' ', 100);

            //-----------------------------------
            // Open file
            //-----------------------------------
            try
            {
                fp = File.CreateText(szFileName);
            }
            catch (System.IO.IOException)
            {
                txtSRet.Text = "fopen : file open error.";
                return;
            }
            //-----------------------------------
            // Write data to file
            //-----------------------------------
            for (i = 0; i < DATA_NUM; i++)
            {
                szLine = string.Format("{0:d8} : ", i);
                for (j = 0; j < CHANNEL_NUM; j++)
                {
                    szTmp = string.Format("{0:X8},", S_SampData[i, j]);
                    szLine += szTmp;
                }
                fp.WriteLine(szLine);
            }

            //-----------------------------------
            // Close file
            //-----------------------------------
            fp.Close();

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

        //===================================================
        // Get master count value
        //===================================================
        private void btnMCount_Click(object sender, System.EventArgs e)
        {
            int ret;
            uint Count;
            uint ScanCarry;
            string csMsg;

            //-----------------------------------
            // Get count value
            //-----------------------------------
            ret = cnt.GetSamplingCount(M_Id, out Count, out ScanCarry);
            csMsg = string.Format("CntGetSamplingCount : Ret = {0:X}H", ret);
            txtMRet.Text = csMsg;
            csMsg = Count.ToString();
            txtMCount.Text = csMsg;
        }

        //===================================================
        // Get slave count value
        //===================================================
        private void btnSCount_Click(object sender, System.EventArgs e)
        {
            int ret;
            uint Count;
            uint ScanCarry;
            string csMsg;

            //-----------------------------------
            // Get count value
            //-----------------------------------
            ret = cnt.GetSamplingCount(S_Id, out Count, out ScanCarry);
            csMsg = string.Format("CntGetSamplingCount : Ret = {0:X}H", ret);
            txtSRet.Text = csMsg;
            csMsg = Count.ToString();
            txtSCount.Text = csMsg;
        }

        //===================================================
        // Get master status
        //===================================================
        private void btnMStatus_Click(object sender, System.EventArgs e)
        {
            int ret;
            uint Status, Err;
            string csMsg;

            //-----------------------------------
            // Get status information
            //-----------------------------------
            ret = cnt.GetSamplingStatus(M_Id, out Status, out Err);
            csMsg = string.Format("CntGetSamplingStatus : Ret = {0:X}H", ret);
            txtMRet.Text = csMsg;
            // Status
            csMsg = "";
            if ((Status & (uint)CcntConst.CNTS_STATUS_BMSTOP) != 0) csMsg += "BmStop,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_CNTSTART) != 0) csMsg += "CntStart,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_CNTSTOP) != 0) csMsg += "CntStop,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_TRGIN) != 0) csMsg += "TrgIn,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_OVERRUN) != 0) csMsg += "Overrun";
            txtMStatus.Text = csMsg;
            // Error
            csMsg = "";
            if ((Err & (uint)CcntConst.CNTS_STATUS_FIFOFULL) != 0) csMsg += "FifoFull,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_SGOVERIN) != 0) csMsg += "S/GOverIn,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_TRGERR) != 0) csMsg += "TrgErr,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_CLKERR) != 0) csMsg += "ClkErr,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_SLAVEHALT) != 0) csMsg += "SlaveHalt,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_MASTERHALT) != 0) csMsg += "MasterHalt";
            txtMError.Text = csMsg;
        }

        //===================================================
        // Get slave status
        //===================================================
        private void btnSStatus_Click(object sender, System.EventArgs e)
        {
            int ret;
            uint Status, Err;
            string csMsg;

            //-----------------------------------
            // Get status information
            //-----------------------------------
            ret = cnt.GetSamplingStatus(S_Id, out Status, out Err);
            csMsg = string.Format("CntGetSamplingStatus : Ret = {0:X}H", ret);
            txtSRet.Text = csMsg;
            // Status
            csMsg = "";
            if ((Status & (uint)CcntConst.CNTS_STATUS_BMSTOP) != 0) csMsg += "BmStop,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_CNTSTART) != 0) csMsg += "CntStart,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_CNTSTOP) != 0) csMsg += "CntStop,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_TRGIN) != 0) csMsg += "TrgIn,";
            if ((Status & (uint)CcntConst.CNTS_STATUS_OVERRUN) != 0) csMsg += "Overrun";
            txtSStatus.Text = csMsg;
            // Error
            csMsg = "";
            if ((Err & (uint)CcntConst.CNTS_STATUS_FIFOFULL) != 0) csMsg += "FifoFull,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_SGOVERIN) != 0) csMsg += "S/GOverIn,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_TRGERR) != 0) csMsg += "TrgErr,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_CLKERR) != 0) csMsg += "ClkErr,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_SLAVEHALT) != 0) csMsg += "SlaveHalt,";
            if ((Err & (uint)CcntConst.CNTS_STATUS_MASTERHALT) != 0) csMsg += "MasterHalt";
            txtSError.Text = csMsg;
        }

        //===================================================
        // Exit master
        //===================================================
        private void btnMExit_Click(object sender, System.EventArgs e)
        {
            string szMsg = new string(' ', 100);
            int ret;

            //------------------------------
            // Exit processing
            //------------------------------
            ret = cnt.Exit(M_Id);
            szMsg = string.Format("CntClose : Ret = {0:X} h", ret);
            txtMRet.Text = szMsg;
        }

        //===================================================
        // Exit slave
        //===================================================
        private void btnSExit_Click(object sender, System.EventArgs e)
        {
            string szMsg = new string(' ', 100);
            int ret;

            //------------------------------
            // Exit processing
            //------------------------------
            ret = cnt.Exit(S_Id);
            szMsg = string.Format("CntClose : Ret = {0:X} h", ret);
            txtSRet.Text = szMsg;
        }

        //===================================================
        // Exit program
        //===================================================
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            int ret;
            ret = cnt.Exit(M_Id);
            ret = cnt.Exit(S_Id);
            this.Close();
        }

        //===================================================
        // Processing of counter event notification
        //===================================================
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case (int)CcntConst.CNTM_SAMPLING_COUNT:
                    if ((m.WParam.ToInt32() & 0x0000ffff) == M_Id)
                    {
                        btnMCount_Click(btnMCount, new System.EventArgs());
                    }
                    else
                    {
                        btnSCount_Click(btnSCount, new System.EventArgs());
                    }
                    break;
                case (int)CcntConst.CNTM_SAMPLING_STOP:
                    if ((m.WParam.ToInt32() & 0x0000ffff) == M_Id)
                    {
                        btnMCount_Click(btnMCount, new System.EventArgs());
                        txtMStatus.Text = "Stopped!";
                    }
                    else
                    {
                        btnSCount_Click(btnSCount, new System.EventArgs());
                        txtSStatus.Text = "Stopped!";
                    }
                    break;
            }

            base.WndProc(ref m);
        }
    }
}