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

namespace Generating
{
    public partial class Form1 : Form
    {
        Cdio                dio       = new Cdio();
        const int           DATA_SIZE = 1000;                   // バスマスタ用バッファサイズ
        public static short Id;
        static uint[]       BmBuffer  = new uint[DATA_SIZE];    // バスマスタ用バッファ

        GCHandle            gCh;
        IntPtr              pBmBuf;

        public Form1()
        {
            InitializeComponent();
        }

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

        //===================================================
        // 終了時処理
        //===================================================
        private void Generating_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;
        }

        //===================================================
        // 出力データ表示
        //===================================================
        private void btnOutData_Click(object sender, System.EventArgs e)
        {
            string szFileName = "Generating.csv";
            string buf = new string(' ', 100);

            //-----------------------------------
            // 出力データファイルが存在しなければ
            //-----------------------------------
            if (File.Exists(szFileName) == false)
            {
                //-----------------------------------
                // 出力データファイル作成
                //-----------------------------------
                InitialDataFile(szFileName);
            }
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", szFileName);
            return;
        }

        //===================================================
        // 出力データ設定
        //===================================================
        private void btnSetData_Click(object sender, System.EventArgs e)
        {
            StreamReader fp;
            string       szFileName = "Generating.csv";
            uint         i;
            string       buf = new string(' ', 100);

            //-----------------------------------
            // 出力データファイルが存在しなければ
            //-----------------------------------
            if (File.Exists(szFileName) == false)
            {
                //-----------------------------------
                // 出力データファイル作成
                //-----------------------------------
                InitialDataFile(szFileName);
            }
            //-----------------------------------
            // ファイルオープン
            //-----------------------------------
            fp = new StreamReader(szFileName);
            //-----------------------------------
            // 出力データファイルからバスマスタ用バッファにデータを設定
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = fp.ReadLine() ?? string.Empty;
                if (buf != string.Empty)
                {
                    buf = buf.Substring(11, 8);
                    BmBuffer[i] = uint.Parse(buf, NumberStyles.HexNumber);
                }
            }
            //-----------------------------------
            // ファイルクローズ
            //-----------------------------------
            fp.Close();
        }

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

            //-----------------------------------
            // 表示初期化
            //-----------------------------------
            txtCount.Text  = "";
            txtStatus.Text = "";
            txtError.Text  = "";
            //-----------------------------------
            // 転送完了イベント設定
            //-----------------------------------
            ret = dio.DmSetStopEvent(Id, (short)CdioConst.DIODM_DIR_OUT, 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_OUT, 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_OUT);
            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;
            }
            //-----------------------------------
            // データバッファの設定
            //-----------------------------------
            pBmBuf = gCh.AddrOfPinnedObject();
            ret = dio.DmSetBuffer(Id, (short)CdioConst.DIODM_DIR_OUT, pBmBuf, DATA_SIZE, Condition.IsRing);
            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;
            }
            //-----------------------------------
            // バスマスタ転送開始
            //-----------------------------------
            ret = dio.DmTransferStart(Id, (short)CdioConst.DIODM_DIR_OUT);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioDmTransferStart ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            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_OUT);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioDmTransferStop ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            return;
        }

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

            //-----------------------------------
            // 転送カウント数取得
            //-----------------------------------
            ret = dio.DmGetCount(Id, (short)CdioConst.DIODM_DIR_OUT, out count, out carry);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioDmGetCount ret = {0:d}: {1}", ret, error_string);
            txtReturn.Text = str;
            str = string.Format("{0:d}", count);
            txtCount.Text = str;
        }

        //===================================================
        // 転送ステータス取得
        //===================================================
        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_OUT, 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)
        {
            this.Close();
        }

        //===================================================
        // メッセージハンドラー
        //===================================================
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                //===================================================
                // 転送完了メッセージ
                //===================================================
                case (int)CdioConst.DIO_DMM_STOP:
                    txtStatus.Text = "Stopped!";
                    goto case (int)CdioConst.DIO_DMM_COUNT;

                //===================================================
                // 指定個数転送完了メッセージ
                //===================================================
                case (int)CdioConst.DIO_DMM_COUNT:
                    int    ret;
                    uint   count, carry;
                    string str;
                    //-----------------------------------
                    // get count
                    //-----------------------------------
                    ret = dio.DmGetCount(Id, (short)CdioConst.DIODM_DIR_OUT, out count, out carry);
                    str = string.Format("{0:d}", count);
                    txtCount.Text = str;
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }

        //===================================================
        // 出力データファイル作成
        //===================================================
        private void InitialDataFile(string szFileName)
        {
            StreamWriter fp;
            string       buf = new string(' ', 100);
            uint         i;

            //-----------------------------------
            // ファイルオープン
            //-----------------------------------
            fp = File.CreateText(szFileName);
            //-----------------------------------
            // ファイル作成
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = string.Format("{0:d8}: ,{1:X8}", i, i);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // ファイルクローズ
            //-----------------------------------
            fp.Close();
            return;
        }
    }
}