﻿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;                     // Buffer size
        public static short M_Id;                       // Master device ID
        public static short S_Id;                       // Slave device ID
        static uint[] M_BmBuffer = new uint[DATA_SIZE]; // Master buffer
        static uint[] S_BmBuffer = new uint[DATA_SIZE]; // Slave buffer

        GCHandle gCh1, gCh2;
        IntPtr pMBmBuffer, pSBmBuffer;

        public Form1()
        {
            InitializeComponent();
        }

        //===================================================
        // Dialog init
        //===================================================
        private void Sync_Load(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // Dialog init
            //-----------------------------------
            txtMDeviceName.Text = "DIO000";
            txtSDeviceName.Text = "DIO001";

            //-----------------------------------
            // Pinned type handle is allocated to M_BmBuffer
            //-----------------------------------
            if (gCh1.IsAllocated == false)
            {
                gCh1 = GCHandle.Alloc(M_BmBuffer, GCHandleType.Pinned);
            }
            //-----------------------------------
            // Pinned type handle is allocated to S_BmBuffer
            //-----------------------------------
            if (gCh2.IsAllocated == false)
            {
                gCh2 = GCHandle.Alloc(S_BmBuffer, GCHandleType.Pinned);
            }
        }

        //===================================================
        // Close handle
        //===================================================
        private void Sync_FormClosed(object sender, FormClosedEventArgs e)
        {
            int ret;
            //-----------------------------------
            // DioExit()
            //-----------------------------------
            ret = dio.Exit(M_Id);
            ret = dio.Exit(S_Id);

            //-----------------------------------
            // GCHandle is freed
            //-----------------------------------
            if (gCh1.IsAllocated == true)
            {
                gCh1.Free();
            }
            if (gCh2.IsAllocated == true)
            {
                gCh2.Free();
            }
        }

        //===================================================
        // Master dioInit()
        //===================================================
        private void btnMDioInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;
            //-----------------------------------
            // DioInit()
            //-----------------------------------
            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;
        }

        //===================================================
        // Master set condition
        //===================================================
        private void btnMCondition_Click(object sender, System.EventArgs e)
        {
            MCondition MConditionDlg = new MCondition();
            //-----------------------------------
            // Show set condition dialog
            //-----------------------------------
            MConditionDlg.ShowDialog();
            MConditionDlg.Dispose();
            return;
        }

        //===================================================
        // Master start transfer
        //===================================================
        private void btnMStart_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Set notification of message
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // Reset FIFO (input)
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // Set data buffer
            //-----------------------------------
            Array.Clear(M_BmBuffer, 0, DATA_SIZE);
            //-----------------------------------
            // The fixed pointer to an object is acquired
            //-----------------------------------
            pMBmBuffer = gCh1.AddrOfPinnedObject();
            ret = dio.DmSetBuffer(M_Id, (short)CdioConst.DIODM_DIR_IN, pMBmBuffer, 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;
            }
            //-----------------------------------
            // Start transfer
            //-----------------------------------
            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;
        }

        //===================================================
        // Master stop transfer
        //===================================================
        private void btnMStop_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int ret;

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

        //===================================================
        // Master get data
        //===================================================
        private void btnMData_Click(object sender, System.EventArgs e)
        {
            StreamWriter fp;
            string file_name = "MSamplingData.csv";
            string buf = new string(' ', 100);
            uint i;

            //-----------------------------------
            // Open file
            //-----------------------------------
            fp = File.CreateText(file_name);
            //-----------------------------------
            // Write data into file
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = string.Format("{0:d8}: ,{1:X8}", i, M_BmBuffer[i]);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // Close file
            //-----------------------------------
            fp.Close();
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);
            return;
        }

        //===================================================
        // Master transfer count
        //===================================================
        private void btnMCount_Click(object sender, System.EventArgs e)
        {
            uint count = 0, carry = 0;
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Get transfer count
            //-----------------------------------
            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;
        }

        //===================================================
        // Master transfer status
        //===================================================
        private void btnMStatus_Click(object sender, System.EventArgs e)
        {
            uint status, err;
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Get transfer status
            //-----------------------------------
            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;
        }

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

        //===================================================
        // Slave dioInit()
        //===================================================
        private void btnSDioInit_Click(object sender, System.EventArgs e)
        {
            string str;
            string error_string = new string(' ', 256);
            int ret;
            //-----------------------------------
            // DioInit()
            //-----------------------------------
            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;
        }

        //===================================================
        // Slave set condition
        //===================================================
        private void btnSCondition_Click(object sender, System.EventArgs e)
        {
            SCondition SConditionDlg = new SCondition();
            //-----------------------------------
            // Show set condition dialog
            //-----------------------------------
            SConditionDlg.ShowDialog();
            SConditionDlg.Dispose();
            return;
        }

        //===================================================
        // Slave start transfer
        //===================================================
        private void btnSStart_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Set notification of message
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // Reset FIFO (input)
            //-----------------------------------
            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;
            }
            //-----------------------------------
            // Set data buffer
            //-----------------------------------
            Array.Clear(S_BmBuffer, 0, DATA_SIZE);
            //-----------------------------------
            // The fixed pointer to an object is acquired
            //-----------------------------------
            pSBmBuffer = gCh2.AddrOfPinnedObject();
            ret = dio.DmSetBuffer(S_Id, (short)CdioConst.DIODM_DIR_IN, pSBmBuffer, 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;
            }
            //-----------------------------------
            // Start transfer
            //-----------------------------------
            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;
        }

        //===================================================
        // Slave stop transfer
        //===================================================
        private void btnSStop_Click(object sender, System.EventArgs e)
        {
            string error_string = new string(' ', 256);
            string str;
            int ret;

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

        //===================================================
        // Slave get data
        //===================================================
        private void btnSData_Click(object sender, System.EventArgs e)
        {
            StreamWriter fp;
            string file_name = "SSamplingData.csv";
            string buf = new string(' ', 100);
            uint i;

            //-----------------------------------
            // Open file
            //-----------------------------------
            fp = File.CreateText(file_name);
            //-----------------------------------
            // Write data into file
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = string.Format("{0:d8}: ,{1:X8}", i, S_BmBuffer[i]);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // Close file
            //-----------------------------------
            fp.Close();
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", file_name);
            return;
        }

        //===================================================
        // Slave transfer count
        //===================================================
        private void btnSCount_Click(object sender, System.EventArgs e)
        {
            uint count = 0, carry = 0;
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Get transfer count
            //-----------------------------------
            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;
        }

        //===================================================
        // Slave transfer status
        //===================================================
        private void btnSStatus_Click(object sender, System.EventArgs e)
        {
            uint status, err;
            string error_string = new string(' ', 256);
            string str;
            int ret;

            //-----------------------------------
            // Get transfer status
            //-----------------------------------
            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;
        }

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

        //---------------------------------------------------
        // Message handler
        //---------------------------------------------------
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                //===================================================
                // Transfer stop message
                //===================================================
                case (int)CdioConst.DIO_DMM_STOP:
                    //-----------------------------------
                    // Distingnish device object according to device name 
                    //-----------------------------------
                    //-----------------------------------
                    // Master
                    //-----------------------------------
                    if (m.WParam.ToInt32() == M_Id)
                    {
                        txtMStatus.Text = "Stopped!";
                        goto case (int)CdioConst.DIO_DMM_COUNT;
                    }
                    //-----------------------------------
                    // Slave
                    //-----------------------------------
                    else
                    {
                        txtSStatus.Text = "Stopped!";
                        goto case (int)CdioConst.DIO_DMM_COUNT;
                    }

                //===================================================
                // Transfer specified number of data completion message
                //===================================================
                case (int)CdioConst.DIO_DMM_COUNT:
                    int ret;
                    uint count, carry;
                    string str;
                    //-----------------------------------
                    // Distingnish device object according to device name 
                    //-----------------------------------
                    //-----------------------------------
                    // Master
                    //-----------------------------------
                    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;
                    }
                    //-----------------------------------
                    // Slave
                    //-----------------------------------
                    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);
        }
    }
}