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

namespace Sampling
{
    public partial class Form1 : Form
    {
        Cdio dio = new Cdio();
        const int DATA_SIZE = 1000;                         // Buffer size for busmaster
        public static short m_Id;                           // Device ID
        static uint[] DataBuff = new uint[DATA_SIZE];       // Buffer for busmaster

        GCHandle gCh;
        IntPtr pDataBuff;

        public Form1()
        {
            InitializeComponent();
        }

        //===================================================
        // Dialog init
        //===================================================
        private void Sampling_Load(object sender, System.EventArgs e)
        {
            //-----------------------------------
            // Dialog init
            //-----------------------------------
            txtDeviceName.Text = "DIO000";

            //-----------------------------------
            // Pinned type handle is allocated to DataBuff
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(DataBuff, GCHandleType.Pinned);
            }
        }

        //===================================================
        // Close handle
        //===================================================
        private void Sampling_FormClosed(object sender, FormClosedEventArgs e)
        {
            int Ret;

            //-----------------------------------
            // DioExit()
            //-----------------------------------
            Ret = dio.Exit(m_Id);

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

        //===================================================
        // DioInit()
        //===================================================
        private void btnDioInit_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string ErrorString;
            //-----------------------------------
            // DioInit
            //-----------------------------------
            Ret = dio.Init(txtDeviceName.Text, out m_Id);

            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "DioInit Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            return;

        }


        //===================================================
        // DioExit
        //===================================================
        private void btnDioExit_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string ErrorString;
            //-----------------------------------
            // DioExit
            //-----------------------------------
            Ret = dio.Exit(m_Id);
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "DioExit Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
        }

        //===================================================
        // Exit
        //===================================================
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        //===================================================
        // Set condition
        //===================================================
        private void btnCondition_Click(object sender, System.EventArgs e)
        {
            Condition ConditionDlg = new Condition();
            //-----------------------------------
            // Show set condition dialog
            //-----------------------------------
            ConditionDlg.ShowDialog();
            ConditionDlg.Dispose();
        }

        //===================================================
        // Start transfer
        //===================================================
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string ErrorString;
            short Direction = (short)CdioConst.DIODM_DIR_IN;
            //-----------------------------------
            // Set notification of message
            //-----------------------------------
            Ret = dio.DmSetStopEvent(m_Id, Direction, this.Handle);
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(Ret, out ErrorString);
                txtReturnCode.Text = "DioDmSetStopEvent Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
                return;
            }
            Ret = dio.DmSetCountEvent(m_Id, Direction, Condition.dwNumberOfData, this.Handle);
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(Ret, out ErrorString);
                txtReturnCode.Text = "DioDmSetCountEvent Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
                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 ErrorString);
                txtReturnCode.Text = "DioDmFifoReset Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
                return;
            }
            //-----------------------------------
            // Set data buffer
            //-----------------------------------
            Array.Clear(DataBuff, 0, DATA_SIZE);
            //-----------------------------------
            // The fixed pointer to an object is acquired
            //-----------------------------------
            pDataBuff = gCh.AddrOfPinnedObject();
            Ret = dio.DmSetBuffer(m_Id, Direction, pDataBuff, DATA_SIZE, (short)CdioConst.DIODM_WRITE_ONCE);
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(Ret, out ErrorString);
                txtReturnCode.Text = "DioDmSetBuffer Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
                return;
            }
            //-----------------------------------
            // Start transfer
            //-----------------------------------
            Ret = dio.DmTransferStart(m_Id, Direction);
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                dio.GetErrorString(Ret, out ErrorString);
                txtReturnCode.Text = "DioDmTransferStart Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
                return;
            }
            txtCount.Text = "";
            txtStatus.Text = "";
            txtError.Text = "";
        }

        //===================================================
        // Stop transfer
        //===================================================
        private void btnStop_Click(object sender, System.EventArgs e)
        {
            int Ret;
            short Direction = (short)CdioConst.DIODM_DIR_IN;
            string ErrorString;
            //-----------------------------------
            // Stop transfer
            //-----------------------------------
            Ret = dio.DmTransferStop(m_Id, Direction);
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "DioDmTransferStop Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            return;
        }

        //===================================================
        // Get data
        //===================================================
        private void btnData_Click(object sender, System.EventArgs e)
        {
            uint i;
            StreamWriter fp;
            string szFileName = "SamplingData.csv";
            string buf = new string(' ', 100);
            //-----------------------------------
            // Open file
            //-----------------------------------
            fp = File.CreateText(szFileName);
            //-----------------------------------
            // Write data into file
            //-----------------------------------
            for (i = 0; i < DATA_SIZE; i++)
            {
                buf = string.Format("{0:d8}: ,{1:X8}", i, DataBuff[i]);
                fp.WriteLine(buf);
            }
            //-----------------------------------
            // Close file
            //-----------------------------------
            fp.Close();
            //-----------------------------------
            // notepad
            //-----------------------------------
            Process Pro = Process.Start("notepad.exe", szFileName);
            return;
        }



        //===================================================
        // Transfer count
        //===================================================
        private void btnCount_Click(object sender, System.EventArgs e)
        {
            int Ret;
            short Direction = (short)CdioConst.DIODM_DIR_IN;
            uint Count = 0, Carry = 0;
            string csMsg;
            string ErrorString;
            //-----------------------------------
            // Get transfer count
            //-----------------------------------
            Ret = dio.DmGetCount(m_Id, Direction, out Count, out Carry);
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "DioDmGetCount Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            if (Ret == (int)CdioConst.DIO_ERR_SUCCESS)
            {
                csMsg = string.Format("{0:d}", Count);
                txtCount.Text = csMsg;
            }
            return;
        }

        //===================================================
        // Transfer status
        //===================================================
        private void btnStatus_Click(object sender, System.EventArgs e)
        {
            int Ret;
            short Direction = (short)CdioConst.DIODM_DIR_IN;
            uint Status, Err;
            string csMsg;
            string ErrorString;
            //-----------------------------------
            // Get transfer status
            //-----------------------------------
            Ret = dio.DmGetStatus(m_Id, Direction, out Status, out Err);
            dio.GetErrorString(Ret, out ErrorString);
            txtReturnCode.Text = "DioDmGetStatus Ret = " + System.Convert.ToString(Ret) + " : " + ErrorString;
            if (Ret != (int)CdioConst.DIO_ERR_SUCCESS)
            {
                return;
            }
            //-----------------------------------
            // Status
            //-----------------------------------
            csMsg = "";
            if ((Status & (uint)CdioConst.DIODM_STATUS_BMSTOP) != 0)
            {
                csMsg += "BmStop,";
            }
            if ((Status & (uint)CdioConst.DIODM_STATUS_PIOSTART) != 0)
            {
                csMsg += "PioStart,";
            }
            if ((Status & (uint)CdioConst.DIODM_STATUS_PIOSTOP) != 0)
            {
                csMsg += "PioStop,";
            }
            if ((Status & (uint)CdioConst.DIODM_STATUS_TRGIN) != 0)
            {
                csMsg += "TrgIn,";
            }
            if ((Status & (uint)CdioConst.DIODM_STATUS_OVERRUN) != 0)
            {
                csMsg += "Overrun";
            }
            txtStatus.Text = csMsg;
            //-----------------------------------
            // Error
            //-----------------------------------
            csMsg = "";
            if ((Err & (uint)CdioConst.DIODM_STATUS_FIFOEMPTY) != 0)
            {
                csMsg += "FifoEmpty,";
            }
            if ((Err & (uint)CdioConst.DIODM_STATUS_FIFOFULL) != 0)
            {
                csMsg += "FifoFull,";
            }
            if ((Err & (uint)CdioConst.DIODM_STATUS_SGOVERIN) != 0)
            {
                csMsg += "S/GOverIn,";
            }
            if ((Err & (uint)CdioConst.DIODM_STATUS_TRGERR) != 0)
            {
                csMsg += "TrgErr,";
            }
            if ((Err & (uint)CdioConst.DIODM_STATUS_CLKERR) != 0)
            {
                csMsg += "ClkErr,";
            }
            if ((Err & (uint)CdioConst.DIODM_STATUS_SLAVEHALT) != 0)
            {
                csMsg += "SlaveHalt,";
            }
            if ((Err & (uint)CdioConst.DIODM_STATUS_MASTERHALT) != 0)
            {
                csMsg += "MasterHalt";
            }
            txtError.Text = csMsg;
        }

        //===================================================
        // Messange handler
        //===================================================
        protected override void WndProc(ref Message m)
        {
            int dwRet;
            short Direction = (short)CdioConst.DIODM_DIR_IN;
            uint Count, Carry;
            string csMsg;
            switch (m.Msg)
            {
                //---------------------------------------------------
                // Transfer stop message
                //---------------------------------------------------
                case ((int)CdioConst.DIO_DMM_STOP):
                    txtStatus.Text = "Stopped!";
                    goto case ((int)CdioConst.DIO_DMM_COUNT);

                //---------------------------------------------------
                // Transfer specified number of data completion message
                //---------------------------------------------------
                case ((int)CdioConst.DIO_DMM_COUNT):
                    //-----------------------------------
                    // get count
                    //-----------------------------------
                    dwRet = dio.DmGetCount(m_Id, Direction, out Count, out Carry);
                    csMsg = string.Format("{0:d}", Count);
                    txtCount.Text = csMsg;
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
    }
}