﻿using System.Diagnostics;
using System.Runtime.InteropServices;
// Counter headder
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;                                             // マスターデバイスID
        public static short S_Id;                                             // スレーブデバイスID


        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();
        }

        //===================================================
        // ダイアログ初期化
        //===================================================
        private void Sync_Load(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // 画面表示の初期化
            //-----------------------------------
            txtMDeviceName.Text = "CNT000";
            txtSDeviceName.Text = "CNT001";

            //-----------------------------------
            // PinnedハンドルをM_SampDataと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);
            }
        }

        //===================================================
        // 終了時処理
        //===================================================
        private void Sync_FormClosed(object sender, FormClosedEventArgs e)
        {
            int ret;

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

            //-----------------------------------
            // 終了処理
            //-----------------------------------
            ret = cnt.Exit(M_Id);
            ret = cnt.Exit(S_Id);
        }

        //===================================================
        // マスター CntInit()
        //===================================================
        private void btnMInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string buf = new string(' ', 100);
            string error_string = new string(' ', 256);
            int    ret;

            //-----------------------------------
            // デバイス名取得
            //-----------------------------------
            buf = txtMDeviceName.Text;

            //-----------------------------------
            // 初期化処理
            //-----------------------------------
            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()
        //===================================================
        private void btnSInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string buf = new string(' ', 100);
            string error_string = new string(' ', 256);
            int    ret;

            //-----------------------------------
            // デバイス名取得
            //-----------------------------------
            buf = txtSDeviceName.Text;

            //-----------------------------------
            // 初期化処理
            //-----------------------------------
            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;
        }

        //===================================================
        // マスター 条件設定
        //===================================================
        private void btnMCntMode_Click(object sender, System.EventArgs e)
        {
            ModeDlg dlg = new ModeDlg();

            //-----------------------------------
            // 条件設定ダイアログを開く
            //-----------------------------------
            dlg.Id = M_Id;
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // スレーブ 条件設定
        //===================================================
        private void btnSCntMode_Click(object sender, System.EventArgs e)
        {
            ModeDlg dlg = new ModeDlg();

            //-----------------------------------
            // 条件設定ダイアログを開く
            //-----------------------------------
            dlg.Id = S_Id;
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // マスター サンプリングモード設定
        //===================================================
        private void btnMSmpMode_Click(object sender, System.EventArgs e)
        {
            MSampMode dlg = new MSampMode();
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // スレーブ サンプリングモード設定
        //===================================================
        private void btnSSmpMode_Click(object sender, System.EventArgs e)
        {
            SSampMode dlg = new SSampMode();
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // マスター 開始
        //===================================================
        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;

            //-----------------------------------
            // 通知設定
            //-----------------------------------
            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;
            }

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

            //-----------------------------------
            // バッファセット
            //-----------------------------------
            Array.Clear(M_SampData, 0, M_SampData.Length);
            //-----------------------------------
            // Pinnedハンドルでオブジェクトのアドレスを取得
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // カウンタ開始
            //-----------------------------------
            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;
            }

            //-----------------------------------
            // サンプリング開始
            //-----------------------------------
            ret = cnt.SamplingStart(M_Id);
            csMsg = string.Format("CntStartSampling : RetCode = {0:X}H", ret);
            txtMRet.Text    = csMsg;
            txtMCount.Text  = "";
            txtMStatus.Text = "";
            txtMError.Text  = "";
        }

        //===================================================
        // スレーブ 開始
        //===================================================
        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;

            //-----------------------------------
            // 通知設定
            //-----------------------------------
            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;
            }

            //-----------------------------------
            // バッファセット
            //-----------------------------------
            Array.Clear(S_SampData, 0, M_SampData.Length);
            //-----------------------------------
            // Pinnedハンドルでオブジェクトのアドレスを取得
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // カウンタ開始
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // サンプリング開始
            //-----------------------------------
            ret = cnt.SamplingStart(S_Id);
            csMsg = string.Format("CntStartSampling : RetCode = {0:X}H", ret);
            txtSRet.Text    = csMsg;
            txtSCount.Text  = "";
            txtSStatus.Text = "";
            txtSError.Text  = "";
        }

        //===================================================
        // マスター 停止
        //===================================================
        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;
        }

        //===================================================
        // スレーブ 停止
        //===================================================
        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;
        }

        //===================================================
        // マスター データ取得
        //===================================================
        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);

            //-----------------------------------
            // ファイルオープン
            //-----------------------------------
            try
            {
                fp = File.CreateText(szFileName);
            }
            catch (System.IO.IOException)
            {
                txtMRet.Text = "fopen : file open error.";
                return;
            }
            //-----------------------------------
            // ファイルへデータの書き込み
            //-----------------------------------
            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);
            }
            //-----------------------------------
            // ファイルクローズ
            //-----------------------------------
            fp.Close();

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

        //===================================================
        // スレーブ データ取得
        //===================================================
        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);

            //-----------------------------------
            // ファイルオープン
            //-----------------------------------
            try
            {
                fp = File.CreateText(szFileName);
            }
            catch (System.IO.IOException)
            {
                txtSRet.Text = "fopen : file open error.";
                return;
            }
            //-----------------------------------
            // ファイルへデータの書き込み
            //-----------------------------------
            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);
            }

            //-----------------------------------
            // ファイルクローズ
            //-----------------------------------
            fp.Close();

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

        //===================================================
        // マスター カウント値取得
        //===================================================
        private void btnMCount_Click(object sender, System.EventArgs e)
        {
            int    ret;
            uint   Count;
            uint   ScanCarry;
            string csMsg;

            //-----------------------------------
            // カウント値取得
            //-----------------------------------
            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;
        }

        //===================================================
        // スレーブ カウント値取得
        //===================================================
        private void btnSCount_Click(object sender, System.EventArgs e)
        {
            int    ret;
            uint   Count;
            uint   ScanCarry;
            string csMsg;

            //-----------------------------------
            // カウント値取得
            //-----------------------------------
            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;
        }

        //===================================================
        // マスター ステータス情報取得
        //===================================================
        private void btnMStatus_Click(object sender, System.EventArgs e)
        {
            int    ret;
            uint   Status, Err;
            string csMsg;

            //-----------------------------------
            // ステータス情報取得
            //-----------------------------------
            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;
        }

        //===================================================
        // スレーブ ステータス情報取得
        //===================================================
        private void btnSStatus_Click(object sender, System.EventArgs e)
        {
            int    ret;
            uint   Status, Err;
            string csMsg;

            //-----------------------------------
            // ステータス情報取得
            //-----------------------------------
            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;
        }

        //===================================================
        // マスター 終了処理
        //===================================================
        private void btnMExit_Click(object sender, System.EventArgs e)
        {
            string szMsg = new string(' ', 100);
            int    ret;

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

        //===================================================
        // スレーブ 終了処理
        //===================================================
        private void btnSExit_Click(object sender, System.EventArgs e)
        {
            string szMsg = new string(' ', 100);
            int    ret;

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

        //===================================================
        // プログラム終了
        //===================================================
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            int ret;
            ret = cnt.Exit(M_Id);
            ret = cnt.Exit(S_Id);
            this.Close();
        }

        //===================================================
        // カウンタ イベント通知処理
        //===================================================
        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);
        }
    }
}