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

namespace Infinite
{
    public partial class Form1 : Form
    {
        delegate void SetTextDelegate(string str);

        Cdio                dio       = new Cdio();
        const int           DATA_SIZE = 1000;                   // バスマスタ用バッファサイズ
        public static short Id;                                 // デバイスID
        static uint[]       BmBuffer  = new uint[DATA_SIZE];    // バスマスタ用バッファ
        static uint         ReadIndex;                          // リードポインタ
        static uint         WriteIndex;                         // ライトポインタ
        static uint         PreCount;                           // 前回の転送カウント
        static uint         PreCarry;                           // 前回のキャリーカウント
        static string       file_name = "infinite.csv";         // データファイル名
        GCHandle            gCh;
        IntPtr              pBmBuf;

        public Form1()
        {
            InitializeComponent();
        }

        //===================================================
        // ダイアログ初期化
        //===================================================
        unsafe private void Infinite_Load(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // 画面表示の初期化
            //-----------------------------------
            txtDeviceName.Text = "DIO000";
            //-----------------------------------
            // BmBufferにPinnedタイプハンドルを割り当てます
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(BmBuffer, GCHandleType.Pinned);
            }
        }

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

            //-----------------------------------
            // 終了処理
            //-----------------------------------
            ret = dio.Exit(Id);
            //-----------------------------------
            // GCHandleを解放します
            //-----------------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
        }

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

            //-----------------------------------
            // 初期化処理
            //-----------------------------------
            ret = dio.Init(txtDeviceName.Text, out Id);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioInit ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            return;
        }

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

        //===================================================
        // 転送スタート
        //===================================================
        unsafe private void btnStart_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int    ret;

            //-----------------------------------
            // メッセージ通知設定
            //-----------------------------------
            ret = dio.DmSetStopEvent(Id, (short)CdioConst.DIODM_DIR_IN, this.Handle);
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(ret, out error_string);
                str = string.Format("DioDmSetStopEvent ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            ret = dio.DmSetCountEvent(Id, (short)CdioConst.DIODM_DIR_IN, Condition.NumberOfData, this.Handle);
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(ret, out error_string);
                str = string.Format("DioDmSetCountEvent ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //-----------------------------------
            // FIFOのリセット(入力)
            //-----------------------------------
            ret = dio.DmFifoReset(Id, (short)CdioConst.DIODM_RESET_FIFO_IN);
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(ret, out error_string);
                str = string.Format("DioDmFifoReset ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //-----------------------------------
            // データバッファを設定
            //-----------------------------------
            Array.Clear(BmBuffer, 0, BmBuffer.Length);
            pBmBuf = gCh.AddrOfPinnedObject();
            ret = dio.DmSetBuffer(Id, (short)CdioConst.DIODM_DIR_IN, pBmBuf, DATA_SIZE, (short)CdioConst.DIODM_WRITE_RING);
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(ret, out error_string);
                str = string.Format("DioDmSetBuffer ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            //-----------------------------------
            // カウント初期化
            //-----------------------------------
            ReadIndex  = 0;    // リードポインタ
            WriteIndex = 0;    // ライトポインタ
            PreCount   = 0;    // 前回の転送カウント
            PreCarry   = 0;    // 前回のキャリーカウント
           //-----------------------------------
           // データファイル削除
           //-----------------------------------
            File.Delete(file_name);
            //-----------------------------------
            // 転送スタート
            //-----------------------------------
            ret = dio.DmTransferStart(Id, (short)CdioConst.DIODM_DIR_IN);
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(ret, out error_string);
                str = string.Format("DioDmTransferStart ret = {0:d}: {1}", ret, error_string);
                txtReturn.Text = str;
                return;
            }
            txtCount.Text  = "";
            txtStatus.Text = "";
            txtError.Text  = "";
            return;
        }

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

            //-----------------------------------
            // 転送ストップ
            //-----------------------------------
            ret = dio.DmTransferStop(Id, (short)CdioConst.DIODM_DIR_IN);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioDmTransferStop ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            return;
        }

        //===================================================
        // データファイル表示
        //===================================================
        private void btnData_Click(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);
            return;
        }

        //===================================================
        // 転送カウント
        //===================================================
        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 = dio.DmGetCount(Id, (short)CdioConst.DIODM_DIR_IN, out count, out carry);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioDmGetCount ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            if (ret == (int)CdioConst.DIO_ERR_SUCCESS)
            {
                str = string.Format("{0:d}", count);
                txtCount.Text = str;
            }
            return;
        }

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

            //-----------------------------------
            // 転送ステータス取得
            //-----------------------------------
            ret = dio.DmGetStatus(Id, (short)CdioConst.DIODM_DIR_IN, out status, out err);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioDmGetStatus ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                return;
            }
            // Status
            str = "";
            if ((status & (uint)CdioConst.DIODM_STATUS_BMSTOP) != 0)   str += "BmStop,";
            if ((status & (uint)CdioConst.DIODM_STATUS_PIOSTART) != 0) str += "PioStart,";
            if ((status & (uint)CdioConst.DIODM_STATUS_PIOSTOP) != 0)  str += "PioStop,";
            if ((status & (uint)CdioConst.DIODM_STATUS_TRGIN) != 0)    str += "TrgIn,";
            if ((status & (uint)CdioConst.DIODM_STATUS_OVERRUN) != 0)  str += "Overrun";
            txtStatus.Text = str;
            // Error
            str = "";
            if ((err & (uint)CdioConst.DIODM_STATUS_FIFOEMPTY) != 0)   str += "FifoEmpty,";
            if ((err & (uint)CdioConst.DIODM_STATUS_FIFOFULL) != 0)    str += "FifoFull,";
            if ((err & (uint)CdioConst.DIODM_STATUS_SGOVERIN) != 0)    str += "S/GOverIn,";
            if ((err & (uint)CdioConst.DIODM_STATUS_TRGERR) != 0)      str += "TrgErr,";
            if ((err & (uint)CdioConst.DIODM_STATUS_CLKERR) != 0)      str += "ClkErr,";
            if ((err & (uint)CdioConst.DIODM_STATUS_SLAVEHALT) != 0)   str += "SlaveHalt,";
            if ((err & (uint)CdioConst.DIODM_STATUS_MASTERHALT) != 0)  str += "MasterHalt";
            txtError.Text = str;
            return;
        }

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

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

        //===================================================
        // Exit
        //===================================================
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // GCHandleを解放します
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(BmBuffer, GCHandleType.Pinned);
            }
            this.Close();
        }

        //===================================================
        // コントロール操作用同期関数
        //===================================================
        void SetCountText(string str)
        {
            txtCount.Text  = str;
        }
        void SetStatusText(string str)
        {
            txtStatus.Text = str;
        }
        void SetErrText(string str)
        {
            txtError.Text  = str;
        }

        //===================================================
        // メッセージ処理
        //===================================================
        protected override void WndProc(ref Message m)
        {
            StreamWriter fp;
            string       buf = new string(' ', 100);
            string       str;
            uint         count, carry;
            uint         i, cnt;
            int          ret;

            switch (m.Msg)
            {
                //---------------------------------------------------
                // 指定個数転送完了メッセージ
                //---------------------------------------------------
                case ((int)CdioConst.DIO_DMM_COUNT):
                   //-----------------------------------
                    // データバッファ上における転送位置を取得
                    //-----------------------------------
                    ret = dio.DmGetWritePointer(Id, (short)CdioConst.DIODM_DIR_IN, out WriteIndex, out count, out carry);
                    //-----------------------------------
                    // オーバーランエラーをチェック
                    //-----------------------------------
                    if (carry == PreCarry)
                    {
                        if (count > (PreCount + DATA_SIZE))
                        {
                            str = string.Format("Overrun Error!(count = {0:d})", count);
                            txtError.Text = str;
                            return;
                        }
                    }
                    //-----------------------------------
                    // 前回と同じカウント値であれば終了
                    // (転送完了メッセージから呼ばれた場合のため)
                    //-----------------------------------
                    if ((count == PreCount) && (carry == PreCarry))
                    {
                        return;
                    }
                    //-----------------------------------
                    // ファイルに転送されたデータを書き込みます
                    //-----------------------------------
                    //-----------------------------------
                    // ファイルを開く
                    //-----------------------------------
                    fp = File.AppendText(file_name);
                    //-----------------------------------
                    // データ書き込み
                    //-----------------------------------
                    if (WriteIndex > ReadIndex)
                    {
                        cnt = count - (WriteIndex - ReadIndex);
                        for (i = ReadIndex; i < WriteIndex; i++)
                        {
                            buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
                            fp.WriteLine(buf);
                            cnt++;
                        }
                    }
                    else
                    {
                        cnt = count - (DATA_SIZE - ReadIndex + WriteIndex);
                        for (i = ReadIndex; i < DATA_SIZE; i++)
                        {
                            buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
                            fp.WriteLine(buf);
                            cnt++;
                        }
                        for (i = 0; i < WriteIndex; i++)
                        {
                            buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
                            fp.WriteLine(buf);
                            cnt++;
                        }
                    }
                    //-----------------------------------
                    // ファイルを閉じる
                    //-----------------------------------
                    fp.Close();
                    //-----------------------------------
                    // リードポインタを設定
                    //-----------------------------------
                    ReadIndex = WriteIndex;
                    PreCount  = count;
                    PreCarry  = carry;
                    //-----------------------------------
                    // 転送カウント値を表示
                    //-----------------------------------
                    str = string.Format("{0:d}", count);
                    txtCount.Text = str;
                    break;
                //---------------------------------------------------
                // 転送完了メッセージ
                //---------------------------------------------------
                case ((int)CdioConst.DIO_DMM_STOP):
                    //-----------------------------------
                    // 転送完了メッセージ
                    //-----------------------------------
                    txtStatus.Text = "Stopped!";
                    //-----------------------------------
                    // データバッファ上における転送位置を取得
                    //-----------------------------------
                    ret = dio.DmGetWritePointer(Id, (short)CdioConst.DIODM_DIR_IN, out WriteIndex, out count, out carry);
                    //-----------------------------------
                    // オーバーランエラーをチェック
                    //-----------------------------------
                    if (carry == PreCarry)
                    {
                        if (count > (PreCount + DATA_SIZE))
                        {
                            str = string.Format("Overrun Error!(count = {0:d})", count);
                            txtError.Text = str;
                            return;
                        }
                    }
                    //-----------------------------------
                    // 前回と同じカウント値であれば終了
                    // (転送完了メッセージから呼ばれた場合のため)
                    //-----------------------------------
                    if ((count == PreCount) && (carry == PreCarry))
                    {
                        return;
                    }
                    //-----------------------------------
                    // ファイルに転送されたデータを書き込みます
                    //-----------------------------------
                    //-----------------------------------
                    // ファイルを開く
                    //-----------------------------------
                    fp = File.AppendText(file_name);
                    //-----------------------------------
                    // データ書き込み
                    //-----------------------------------
                    if (WriteIndex > ReadIndex)
                    {
                        cnt = count - (WriteIndex - ReadIndex);
                        for (i = ReadIndex; i < WriteIndex; i++)
                        {
                            buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
                            fp.WriteLine(buf);
                            cnt++;
                        }
                    }
                    else
                    {
                        cnt = count - (DATA_SIZE - ReadIndex + WriteIndex);
                        for (i = ReadIndex; i < DATA_SIZE; i++)
                        {
                            buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
                            fp.WriteLine(buf);
                            cnt++;
                        }
                        for (i = 0; i < WriteIndex; i++)
                        {
                            buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
                            fp.WriteLine(buf);
                            cnt++;
                        }
                    }
                    //-----------------------------------
                    // ファイルを閉じる
                    //-----------------------------------
                    fp.Close();
                    //-----------------------------------
                    // リードポインタを設定
                    //-----------------------------------
                    ReadIndex = WriteIndex;
                    PreCount  = count;
                    PreCarry  = carry;
                    //-----------------------------------
                    // 転送カウント値を表示
                    //-----------------------------------
                    str = string.Format("{0:d}", count);
                    txtCount.Text = str;
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
    }
}