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

namespace Sync
{
    public partial class Form1 : Form
    {
        Cdio                dio        = new Cdio();
        const int           DATA_SIZE  = 1000;                   // バスマスタ用バッファサイズ
        public static short M_Id;                                // マスターデバイスID
        public static short S_Id;                                // スレーブデバイスID
        static uint[]       M_BmBuffer = new uint[DATA_SIZE];    // マスターバスマスタ用バッファ
        static uint[]       S_BmBuffer = new uint[DATA_SIZE];    // スレーブバスマスタ用バッファ

        GCHandle            M_gCh, S_gCh;
        IntPtr              pM_BmBuf, pS_BmBuf;

        public Form1()
        {
            InitializeComponent();
        }

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

        }

        //===================================================
        // 終了時処理
        //===================================================
        private void Sync_FormClosed(object sender, FormClosedEventArgs e)
        {
            int ret;
            //-----------------------------------
            // 終了処理
            //-----------------------------------
            ret = dio.Exit(M_Id);
            ret = dio.Exit(S_Id);
            //-----------------------------------
            // GCHandleを解放します
            //-----------------------------------
            if (M_gCh.IsAllocated == true)
            {
                M_gCh.Free();
            }
            if (S_gCh.IsAllocated == true)
            {
                S_gCh.Free();
            }
        }

        //===================================================
        // マスター DioInit()
        //===================================================
        private void btnMDioInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int    ret;
            //-----------------------------------
            // 初期化処理
            //-----------------------------------
            ret = dio.Init(txtMDeviceName.Text, out M_Id);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioInit ret = {0:d}: {1}", ret, error_string);
            txtMReturn.Text = str;
            return;
        }

        //===================================================
        // マスター 条件設定
        //===================================================
        private void btnMCondition_Click(object sender, System.EventArgs e)
        {
            MCondition MConditionDlg = new MCondition();
            //-----------------------------------
            // 条件設定ダイアログを開く
            //-----------------------------------
            MConditionDlg.ShowDialog();
            MConditionDlg.Dispose();
            return;
        }

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

            //-----------------------------------
            // メッセージ通知設定
            //-----------------------------------
            ret = dio.DmSetStopEvent(M_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);
                txtMReturn.Text = str;
                return;
            }
            ret = dio.DmSetCountEvent(M_Id, (short)CdioConst.DIODM_DIR_IN, MCondition.M_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);
                txtMReturn.Text = str;
                return;
            }
            //-----------------------------------
            // FIFOのリセット(入力)
            //-----------------------------------
            ret = dio.DmFifoReset(M_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);
                txtMReturn.Text = str;
                return;
            }
            //-----------------------------------
            // データバッファを設定
            //-----------------------------------
            Array.Clear(M_BmBuffer, 0, M_BmBuffer.Length);
            pM_BmBuf = M_gCh.AddrOfPinnedObject();
            ret = dio.DmSetBuffer(M_Id, (short)CdioConst.DIODM_DIR_IN, pM_BmBuf, DATA_SIZE, MCondition.M_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);
                txtMReturn.Text = str;
                return;
            }
            //-----------------------------------
            // 転送スタート
            //-----------------------------------
            ret = dio.DmTransferStart(M_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);
                txtMReturn.Text = str;
                return;
            }
            txtMCount.Text  = "";
            txtMStatus.Text = "";
            txtMError.Text  = "";
            return;
        }

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

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

        //===================================================
        // マスター 取得データ
        //===================================================
        private void btnMData_Click(object sender, System.EventArgs e)
        {
            StreamWriter fp;
            string       file_name = "MSamplingData.csv";
            string       buf = new string(' ', 100);
            uint         i;

            //-----------------------------------
            // ファイルを開く
            //-----------------------------------
            fp = File.CreateText(file_name);
            //-----------------------------------
            // ファイルに取得データを書き込みます。
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = string.Format("{0:d8}: ,{1:X8}", i, M_BmBuffer[i]);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // ファイルを閉じる
            //-----------------------------------
            fp.Close();
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);
            return;
        }

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

            //-----------------------------------
            // 転送カウント取得
            //-----------------------------------
            ret = dio.DmGetCount(M_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);
            txtMReturn.Text = str;
            if (ret == (int)CdioConst.DIO_ERR_SUCCESS)
            {
                str = string.Format("{0:d}", count);
                txtMCount.Text = str;
            }
            return;
        }

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

            //-----------------------------------
            // 転送ステータス取得
            //-----------------------------------
            ret = dio.DmGetStatus(M_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);
            txtMReturn.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";
            txtMStatus.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";
            txtMError.Text = str;
            return;
        }

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

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

        //===================================================
        // スレーブ DioInit()
        //===================================================
        private void btnSDioInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int    ret;
            //-----------------------------------
            // 初期化処理
            //-----------------------------------
            ret = dio.Init(txtSDeviceName.Text, out S_Id);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioInit ret = {0:d}: {1}", ret, error_string);
            txtSReturn.Text = str;
            return;
        }

        //===================================================
        // スレーブ 条件設定
        //===================================================
        private void btnSCondition_Click(object sender, System.EventArgs e)
        {
            SCondition SConditionDlg = new SCondition();
            //-----------------------------------
            // 条件設定ダイアログを開く
            //-----------------------------------
            SConditionDlg.ShowDialog();
            SConditionDlg.Dispose();
            return;
        }

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

            //-----------------------------------
            // メッセージ通知設定
            //-----------------------------------
            ret = dio.DmSetStopEvent(S_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);
                txtSReturn.Text = str;
                return;
            }
            ret = dio.DmSetCountEvent(S_Id, (short)CdioConst.DIODM_DIR_IN, SCondition.S_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);
                txtSReturn.Text = str;
                return;
            }
            //-----------------------------------
            // FIFOのリセット(入力)
            //-----------------------------------
            ret = dio.DmFifoReset(S_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);
                txtSReturn.Text = str;
                return;
            }
            //-----------------------------------
            // データバッファを設定
            //-----------------------------------
            Array.Clear(S_BmBuffer, 0, S_BmBuffer.Length);
            pS_BmBuf = S_gCh.AddrOfPinnedObject();
            ret = dio.DmSetBuffer(S_Id, (short)CdioConst.DIODM_DIR_IN, pS_BmBuf, DATA_SIZE, SCondition.S_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);
                txtSReturn.Text = str;
                return;
            }
            //-----------------------------------
            // 転送スタート
            //-----------------------------------
            ret = dio.DmTransferStart(S_Id, (short)CdioConst.DIODM_DIR_IN);
            if (ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(ret, out error_string);
                str = string.Format("DioDmTransferStart ret = %d: %s", ret, error_string);
                txtSReturn.Text = str;
                return;
            }
            txtSCount.Text  = "";
            txtSStatus.Text = "";
            txtSError.Text  = "";
            return;
        }

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

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

        //===================================================
        // スレーブ 取得データ
        //===================================================
        private void btnSData_Click(object sender, System.EventArgs e)
        {
            StreamWriter fp;
            string       file_name = "SSamplingData.csv";
            string       buf = new string(' ', 100);
            uint         i;

            //-----------------------------------
            // ファイルを開く
            //-----------------------------------
            fp = File.CreateText(file_name);
            //-----------------------------------
            // ファイルに取得データを書き込みます。
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = string.Format("{0:d8}: ,{1:X8}", i, S_BmBuffer[i]);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // ファイルを閉じる
            //-----------------------------------
            fp.Close();
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);
            return;
        }

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

            //-----------------------------------
            // 転送カウント取得
            //-----------------------------------
            ret = dio.DmGetCount(S_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);
            txtSReturn.Text = str;
            if (ret == (int)CdioConst.DIO_ERR_SUCCESS)
            {
                str = string.Format("{0:d}", count);
                txtSCount.Text = str;
            }
            return;
        }

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

            //-----------------------------------
            // 転送ステータス取得
            //-----------------------------------
            ret = dio.DmGetStatus(S_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);
            txtSReturn.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";
            txtSStatus.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";
            txtSError.Text = str;
            return;
        }

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

            //-----------------------------------
            // DioExit
            //-----------------------------------
            ret = dio.Exit(S_Id);
            dio.GetErrorString(ret, out error_string);
            str = string.Format("DioExit ret = {0:d}: {1}", ret, error_string);
            txtSReturn.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:
                    //-----------------------------------
                    // デバイスIDにより対象デバイスを判別
                    //-----------------------------------
                    //-----------------------------------
                    // マスター
                    //-----------------------------------
                    if (m.WParam.ToInt32() == M_Id)
                    {
                        txtMStatus.Text = "Stopped!";
                        goto case (int)CdioConst.DIO_DMM_COUNT;
                    }
                    //-----------------------------------
                    // スレーブ
                    //-----------------------------------
                    else
                    {
                        txtSStatus.Text = "Stopped!";
                        goto case (int)CdioConst.DIO_DMM_COUNT;
                    }

                //===================================================
                // 指定個数転送完了メッセージ
                //===================================================
                case (int)CdioConst.DIO_DMM_COUNT:
                    int    ret;
                    uint   count, carry;
                    string str;
                    //-----------------------------------
                    // デバイスIDにより対象デバイスを判別
                    //-----------------------------------
                    //-----------------------------------
                    // マスター
                    //-----------------------------------
                    if (m.WParam.ToInt32() == M_Id)
                    {
                        ret = dio.DmGetCount(M_Id, (short)CdioConst.DIODM_DIR_IN, out count, out carry);
                        str = string.Format("{0:d}", count);
                        txtMCount.Text = str;
                    }
                    //-----------------------------------
                    // スレーブ
                    //-----------------------------------
                    else
                    {
                        ret = dio.DmGetCount(S_Id, (short)CdioConst.DIODM_DIR_IN, out count, out carry);
                        str = string.Format("{0:d}", count);
                        txtSCount.Text = str;
                    }
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
    }
}