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

namespace Sampling
{
    public partial class Form1 : Form
    {
        const int           DATA_NUM     = 1000;                                // バスマスタ用バッファサイズ
        public const int    CHANNEL_NUM  = 4;

        public static short Id;                                                 // デバイスID
        uint[,]             SamplingData = new uint[DATA_NUM, CHANNEL_NUM];     // バスマスタ用バッファ

        Ccnt                cnt          = new Ccnt();

        GCHandle            gCh;
        IntPtr              pSamplingData;

        public Form1()
        {
            InitializeComponent();
        }

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

            //-----------------------------------
            // PinnedハンドルをSamplingDataに分配する
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(SamplingData, GCHandleType.Pinned);
            }
        }

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

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

            //-----------------------------------
            // 終了処理
            //-----------------------------------
            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;

            //-----------------------------------
            // デバイス名取得
            //-----------------------------------
            buf = txtDeviceName.Text;
            //-----------------------------------
            // 初期化処理
            //-----------------------------------
            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;
        }

        //---------------------------------------------
        // カウンタモード設定画面表示
        //---------------------------------------------
        private void btnCntMode_Click(object sender, System.EventArgs e)
        {
            //------------------------------
            // カウンタモード設定画面表示
            //------------------------------
            ModeDlg dlg = new ModeDlg();
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // 条件設定
        //===================================================
        private void btnCondition_Click(object sender, System.EventArgs e)
        {
            ConditionDlg dlg = new ConditionDlg();
            //-----------------------------------
            // 条件設定ダイアログを開く
            //-----------------------------------
            dlg.ShowDialog();
            dlg.Dispose();
        }

        //===================================================
        // 転送スタート
        //===================================================
        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;

            //-----------------------------------
            // メッセージ通知設定
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // FIFOのリセット(入力)
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // データバッファを設定
            //-----------------------------------
            Array.Clear(SamplingData, 0, SamplingData.Length);
            //-----------------------------------
            // Pinnedハンドルでオブジェクトのアドレスを取得
            //-----------------------------------
            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;
            }
            //------------------------------
            // パラメータのセット
            //------------------------------
            for (i = 0; i < CHANNEL_NUM; i++)
            {
                ChNo[i] = i;
            }
            //------------------------------
            // カウント開始処理
            //------------------------------
            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;
            }
            //-----------------------------------
            // 転送スタート
            //-----------------------------------
            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      = "";
        }

        //===================================================
        // 転送ストップ
        //===================================================
        private void btnStop_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int    ret;

            //-----------------------------------
            // 転送ストップ
            //-----------------------------------
            ret = cnt.SamplingStop(Id);
            cnt.GetErrorString(ret, out error_string);
            str = string.Format("CntSamplingStop ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
        }

        //===================================================
        // データファイル表示
        //===================================================
        private void btnData_Click(object sender, System.EventArgs e)
        {
            string     buf = new string(' ', 256);
            short      i, j;
            TextWriter fp;
            string     file_name = "SamplingData.csv";

            //-----------------------------------
            // ファイルに転送されたデータを書き込みます
            //-----------------------------------
            //-----------------------------------
            // ファイルを開く
            //-----------------------------------
            try
            {
                fp = File.CreateText(file_name);
            }
            catch (System.IO.IOException)
            {
                txtReturn.Text = "fopen : file open error.";
                return;
            }
            //-----------------------------------
            // データ書き込み
            //-----------------------------------
            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);
            }
            //-----------------------------------
            // ファイルを閉じる
            //-----------------------------------
            fp.Close();

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

        }

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

            //-----------------------------------
            // 転送カウント取得
            //-----------------------------------
            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();
            }
        }

        //===================================================
        // 転送ステータス
        //===================================================
        private void btnStatus_Click(object sender, System.EventArgs e)
        {
            uint   status, err;
            string error_string = new string(' ', 256);
            string str;
            int    ret;

            //-----------------------------------
            // 転送ステータス取得
            //-----------------------------------
            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();
        }

        //===================================================
        // カウンタ イベント通知処理
        //===================================================
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case (int)CcntConst.CNTM_SAMPLING_COUNT:    // 指定個数転送完了
                    btnCount_Click(btnCount, new System.EventArgs());
                    break;
                case (int)CcntConst.CNTM_SAMPLING_STOP:     // 転送完了
                    txtStatus.Text = "Stopped!";
                    btnCount_Click(btnCount, new System.EventArgs());
                    break;
            }

            base.WndProc(ref m);
        }
    }
}