using CdigCs;

namespace WaveformJudgement1
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// Creat the instance of class Cdig
        /// </summary>
        Cdig dig = new Cdig();
        public const int MAX_SAMPLES = 512;                     // The definition of the maximum number of acquiring samples  : 512

        public short m_Id;                                      // Device ID
        public int[] m_Data = new int[MAX_SAMPLES];             // Array of retrieving data
        public int[] m_UpperData = new int[MAX_SAMPLES];        // Array which the upper bound data for waveform judgment are stored in
        public int[] m_LowerData = new int[MAX_SAMPLES];        // Array which the lower bound data for waveform judgment are stored in
        public short[] m_Judge = new short[1];                  // Result of judgement
        public short[] m_JudgeDetail = new short[MAX_SAMPLES];  // Details result of judgement
        public int m_Records;                                   // Number of retrieved record
        public int m_Resolution;
        public Bitmap bmp;                                      // Bitmap

        public Form1()
        {
            InitializeComponent();
            bmp = new Bitmap(Graph.Size.Width, Graph.Size.Height);   // Create the bitmap which is compatible with the graph
        }

        /// <summary>
        /// Init handling
        /// </summary>
        private void buttonInit_Click(object sender, System.EventArgs e)
        {
            int Ret;
            string ErrorString;

            //--------------------------------
            // Init handling
            //--------------------------------
            Ret = dig.Init(textBoxDevice.Text, out m_Id);
            if (Ret != 0)
            {
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.Init = " + Ret.ToString() + " : " + ErrorString;
                return;
            }

            //--------------------------------
            // Reset device
            //--------------------------------
            Ret = dig.ResetDevice(m_Id);
            if (Ret != 0)
            {
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.ResetDevice = " + Ret.ToString() + " : " + ErrorString;
                return;
            }

            textBoxInfo.Text = "Init : Normality completion";
        }

        /// <summary>
        /// Device Setting
        /// </summary>
        private void buttonSetting_Click(object sender, System.EventArgs e)
        {
            int Ret;

            //----------------------------------
            // Initialize variable
            //----------------------------------
            m_Records = 0;
            m_Resolution = 1024;   // Fixed setting of DIG-100M1002-PCI

            //---------------------------------
            // Set the operation mode : waveform judgment instrument mode
            //---------------------------------
            Ret = dig.SetDigitizerMode(m_Id, Cdig.DIG_MODE_JUDGE);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetDigitizerMode = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set the emergency halt factor of digitizer : Sampling clock error, Waveform judgment count match,
            //                                              Device memory overflow
            //---------------------------------
            Ret = dig.SetHaltCondition(m_Id, Cdig.DIG_HALT_CLOCK_ERROR | Cdig.DIG_HALT_JUDGE_COUNT | Cdig.DIG_HALT_DEVMEM_OVERFLOW);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetHaltCondition = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set sampling clock source : Crystal oscillator of board
            //---------------------------------
            Ret = dig.SetClockSource(m_Id, Cdig.DIG_ECU_SRC_CLOCK);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetClockSource = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set sampling rate : 1MHz
            //---------------------------------
            Ret = dig.SetSampleRate(m_Id, 1000000);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetSampleRate = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set the length of record : 512
            //---------------------------------
            Ret = dig.SetRecordLength(m_Id, MAX_SAMPLES);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetRecordLength = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set the number of records : Infinite
            //---------------------------------
            Ret = dig.SetRecordNumber(m_Id, 0);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetRecordNumber = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set duty ratio : 50%
            //---------------------------------
            Ret = dig.SetDutyCycle(m_Id, 50.0f);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetDutyCycle = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set channel : Enable channel0 only
            //---------------------------------
            // Enable channel0
            Ret = dig.SetChannel(m_Id, Cdig.DIG_CHANNEL0, Cdig.DIG_ENABLE);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetChannel = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            // Disable channel1
            Ret = dig.SetChannel(m_Id, Cdig.DIG_CHANNEL1, Cdig.DIG_DISABLE);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetChannel = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set range : +/-20V
            //---------------------------------
            Ret = dig.SetRange(m_Id, Cdig.DIG_CHANNEL0, Cdig.DIG_RANGE_40VPP);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetRange = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set the type of pre-trigger : Auto
            //---------------------------------
            Ret = dig.SetPreTriggerType(m_Id, Cdig.DIG_TRIGGERTYPE_AUTO);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetPreTriggerType = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set the type of post-trigger : Analog edge trigger
            //---------------------------------
            Ret = dig.SetPostTriggerType(m_Id, Cdig.DIG_TRIGGERTYPE_AIEDGE);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetPostTriggerType = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Detailed setting for the post-trigger : TriggerSource : channel0, Trigger level : 0V, Rising edge, 1
            //---------------------------------
            Ret = dig.SetPostTriggerAiEdge(m_Id, Cdig.DIG_CHANNEL0, 0.0f, Cdig.DIG_TRIGGER_SLOPE_RISE, 1);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetPostTriggerAiEdge = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Specifies the channel to perform waveform judgment : Channel0
            //---------------------------------
            Ret = dig.SetJudgeChannel(m_Id, Cdig.DIG_CHANNEL0, Cdig.DIG_ENABLE);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetJudgeChannel = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Set the upper bound value for counting the waveform judgment result : Count the FAIL records, The upper bound value of count times is 1
            //---------------------------------
            Ret = dig.SetJudgeCountLimit(m_Id, Cdig.DIG_CHANNEL0, Cdig.DIG_JUDGE_NG, 1);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetJudgeCountLimit = " + Ret.ToString() + " : " + ErrorString;
                return;
            }

            //----------------------------------
            // Generates the data for waveform judgment automatically : 
            // Margin of horizontal axis : -10V to +10V,
            // Margin of vertical axis : -50V to +50V,
            // New
            //----------------------------------
            Ret = dig.SetAutoMask(m_Id, Cdig.DIG_CHANNEL0, 10, 50, Cdig.DIG_AUTOMASK_NEW);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.SetAutoMask = " + Ret.ToString() + " : " + ErrorString;
                return;
            }

            // Retrieve the data for waveform judgment which has been set to digitizer
            Ret = dig.GetJudgeData32(m_Id, Cdig.DIG_CHANNEL0, MAX_SAMPLES, ref m_UpperData, ref m_LowerData);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetJudgeData = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            textBoxInfo.Text = "Setting : Normality completion";
        }

        /// <summary>
        /// Start judgement
        /// </summary>
        private void buttonStart_Click(object sender, System.EventArgs e)
        {
            int Ret;        // Return value
            //---------------------------------
            // Initialize variable
            //---------------------------------
            m_Records = 0;

            //---------------------------------
            // Operation start
            //---------------------------------
            Ret = dig.Start(m_Id);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.Start = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            textBoxInfo.Text = "Start judgement : Normality completion";

            //---------------------------------
            // Polling until the operation status is changed to be OFF
            //---------------------------------
            int Status;
            int NgCount;

            do
            {
                //---------------------------------
                // In order to enable the dialog operation
                //---------------------------------
                System.Windows.Forms.Application.DoEvents();
                //---------------------------------
                // Get the number of records which are being stored in driver memory
                //---------------------------------
                Ret = dig.GetDriverMemoryRecords(m_Id, out m_Records);
                if (Ret != 0)
                {
                    string ErrorString;
                    dig.GetErrorString(Ret, out ErrorString);
                    textBoxInfo.Text = "dig.GetDriverMemoryRecords = " + Ret.ToString() + " : " + ErrorString;
                    return;
                }
                //---------------------------------
                // Retrieve the acquisition data : retrieve the data of 1 record from the new data
                //---------------------------------
                if (m_Records > 0 || m_Records == -1)
                {
                    Ret = dig.ReadLatestRecords32(m_Id, Cdig.DIG_RECORD_ALL, 1, ref m_Data, ref m_Judge, ref m_JudgeDetail);
                    if (Ret != 0)
                    {
                        string ErrorString;
                        dig.GetErrorString(Ret, out ErrorString);
                        textBoxInfo.Text = "dig.ReadEarliestRecords = " + Ret.ToString() + " : " + ErrorString;
                        return;
                    }
                    DrawGraph();
                }
                //---------------------------------
                // Acquires fail times for the waveform judgment
                //---------------------------------
                Ret = dig.GetJudgeCount(m_Id, out NgCount);
                if (Ret != 0)
                {
                    string ErrorString;
                    dig.GetErrorString(Ret, out ErrorString);
                    textBoxInfo.Text = "dig.GetJudgeCount = " + Ret.ToString() + " : " + ErrorString;
                    return;
                }
                labelJudgeCount.Text = NgCount.ToString();
                //---------------------------------
                // Get the operation status
                //---------------------------------
                Ret = dig.GetStatus(m_Id, out Status);
                if (Ret != 0)
                {
                    string ErrorString;
                    dig.GetErrorString(Ret, out ErrorString);
                    textBoxInfo.Text = "dig.GetStatus = " + Ret.ToString() + " : " + ErrorString;
                    return;
                }
                labelStatus.Text = Status.ToString("X") + "H";
            } while ((Status & Cdig.DIG_STATUS_BUSY) == Cdig.DIG_STATUS_BUSY);
            //---------------------------------
            // Acquires fail times for the waveform judgment
            //---------------------------------
            Ret = dig.GetJudgeCount(m_Id, out NgCount);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetJudgeCount = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            labelJudgeCount.Text = NgCount.ToString();
            //---------------------------------
            // Acquires the number of records not yet acquired in the driver memory
            //---------------------------------
            Ret = dig.GetDriverMemoryRecords(m_Id, out m_Records);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetDriverMemoryRecords = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Retrieve the acquisition data : retrieve the data of 1 record from the new data
            //---------------------------------
            if (m_Records > 0 || m_Records == -1)
            {
                Ret = dig.ReadLatestRecords32(m_Id, Cdig.DIG_RECORD_ALL, 1, ref m_Data, ref m_Judge, ref m_JudgeDetail);
                if (Ret != 0)
                {
                    string ErrorString;
                    dig.GetErrorString(Ret, out ErrorString);
                    textBoxInfo.Text = "dig.ReadEarliestRecords = " + Ret.ToString() + " : " + ErrorString;
                    return;
                }
                DrawGraph();
            }
        }

        /// <summary>
        /// Show information
        /// </summary>
        private void buttonInfo_Click(object sender, System.EventArgs e)
        {
            int Ret;        // Return value
            int Status;     // Status

            //---------------------------------
            // Get the operation status
            //---------------------------------
            Ret = dig.GetStatus(m_Id, out Status);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetStatus = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            labelStatus.Text = Status.ToString("X") + "H";
            textBoxInfo.Text = "Get information : Normality completion";
        }

        /// <summary>
        /// Stop judgement
        /// </summary>
        private void buttonStop_Click(object sender, System.EventArgs e)
        {
            int Ret;        // Return value
            Ret = dig.Stop(m_Id);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.Stop = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            textBoxInfo.Text = "Stop judgement : Normality completion";
        }

        /// <summary>
        /// Exit handling
        /// </summary>
        private void buttonExit_Click(object sender, System.EventArgs e)
        {
            int Ret;    // Return value
            Ret = dig.Exit(m_Id);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.Exit = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            textBoxInfo.Text = "Exit : Normality completion";
        }

        /// <summary>
        /// Close Form
        /// </summary>
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // Exit handling
            dig.Exit(m_Id);
        }

        /// <summary>
        /// Draw graph
        /// </summary>
        private void DrawGraph()
        {
            float XUnit;    // Drawing unit of X axis
            float PosX;     // Drawing coordinate of X axis
            float PosY;     // Drawing coordinate of Y axis
            float OldX;     // For saving the drawing coordinate of X axis
            float OldY;     // For saving the drawing coordinate of Y axis

            //----------------------------------------------------
            // Draw the current data in graph
            //----------------------------------------------------
            Pen pen = new Pen(System.Drawing.Color.Red, 1);                 // Create red pen
            Graph.Image = bmp;
            Graphics grp = Graphics.FromImage(Graph.Image);                 // Creat a new graphics object from the specified image object
            grp.Clear(Graph.BackColor);                                     // Clear the graph
            XUnit = Graph.Size.Width / (float)(MAX_SAMPLES);                // Calculate the moving pixel number of X axis for data 1

            for (int i = 0; i < 3; i++)
            {
                OldX = 0;
                switch (i)
                {
                    // Set the origin position of upper bound data
                    case 0:
                        OldY = Graph.Height * (m_Resolution - m_UpperData[0]) / (float)m_Resolution;    // Calculate the coordinate of Y axis
                        break;
                    // Set the origin position of lower bound data
                    case 1:
                        OldY = Graph.Height * (m_Resolution - m_LowerData[0]) / (float)m_Resolution;    // Calculate the coordinate of Y axis
                        break;
                    // Set the origin position of retrieving data
                    default:
                        OldY = Graph.Height * (m_Resolution - m_Data[0]) / (float)m_Resolution;     // Calculate the coordinate of Y axis
                        break;
                }
                // If the initial value of Y axis exceeds the drawing rect of graph
                if (OldY >= Graph.Height)
                {
                    OldY = Graph.Height - 1;            // Modify the drawing position
                }
                // If the coordinate of Y axis is lower than the drawing rect
                else if (OldY < 0)
                {
                    OldY = 0;                           // Modify the drawing position
                }
                //----------------------------------------------------
                // Repeat the drawing handling only for the times which is equal to the numer of acquisition data
                //----------------------------------------------------
                for (int j = 1; j < MAX_SAMPLES; j++)
                {
                    PosX = OldX + XUnit;    // Calculate the coordinate of X axis
                    switch (i)
                    {
                        // Set the drawing position of upper bound data
                        case 0:
                            PosY = Graph.Height * (m_Resolution - m_UpperData[j]) / (float)m_Resolution;    // Calculate the coordinate of Y axis
                            break;
                        // Set the drawing position of lower bound data
                        case 1:
                            PosY = Graph.Height * (m_Resolution - m_LowerData[j]) / (float)m_Resolution;    // Calculate the coordinate of Y axis
                            break;
                        // Set the drawing position of retrieving data
                        default:
                            PosY = Graph.Height * (m_Resolution - m_Data[j]) / (float)m_Resolution;     // Calculate the coordinate of Y axis
                            break;
                    }
                    // If the coordinate of Y axis exceeds the drawing rect
                    if (PosY >= Graph.Height)
                    {
                        PosY = Graph.Height - 1;        // Modify the drawing position
                    }
                    // If the coordinate of Y axis is lower than the drawing rect
                    else if (PosY < 0)
                    {
                        PosY = 0;                               // Modify the drawing position
                    }
                    grp.DrawLine(pen, OldX, OldY, PosX, PosY);  // Draw

                    OldX = PosX;            // Save the drawing coordinate of X axis
                    OldY = PosY;            // Save the drawing coordinate of Y axis
                }
            }

            pen.Dispose();  // Reales all resoures used by this pen object
            grp.Dispose();  // Reales all resoures used by this graphics object
        }
    }
}