using CdigCs;

namespace OscilloScope
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// Creat the instance of class Cdig
        /// </summary>
        Cdig dig = new Cdig();

        public short m_Id;                              // Device ID
        public float[] m_Data;                          // Array of retrieving data
        public int m_Records;                           // Number of retrieved record
        public float m_Range;                           // Input voltage range
        public int m_RecordLength;                      // Record length
        public short m_TriggerChannel;                  // Post-trigger channel
        public short m_Channels;                        // Number of effective channels
        public Bitmap bmp;                              // Bitmap

        public Form1()
        {
            InitializeComponent();
            m_Data = [];
            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>
        ///  Start acquisition
        /// </summary>
        private void buttonStart_Click(object sender, System.EventArgs e)
        {
            int Ret;        // Return value

            //---------------------------------
            // Auto setup
            //---------------------------------
            Ret = dig.AutoSetup(m_Id);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.AutoSetup = " + Ret.ToString() + " : " + ErrorString;
                return;
            }

            //---------------------------------
            // Get the setup information and display
            //---------------------------------
            buttonInfo_Click(buttonInfo, new System.EventArgs());

            //---------------------------------
            // Insure the array of retrieving data
            //---------------------------------
            m_Data = new float[m_RecordLength * m_Channels];

            //---------------------------------
            // 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 acquisition : Normality completion";

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

            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;
                }
                //---------------------------------
                // If there are records in driver memory, retrieve the data from the new side
                //---------------------------------
                if (m_Records > 0 || m_Records == -1)
                {
                    Ret = dig.ReadLatestRecords(m_Id, Cdig.DIG_RECORD_DATA, 1, ref m_Data, 0, 0);
                    if (Ret != 0)
                    {
                        string ErrorString;
                        dig.GetErrorString(Ret, out ErrorString);
                        textBoxInfo.Text = "dig.ReadLatestRecordss = " + Ret.ToString() + " : " + ErrorString;
                        return;
                    }
                    //------------------------------------
                    // Draw graph
                    //------------------------------------
                    DrawGraph();
                }
                //---------------------------------
                // 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);
            //---------------------------------
            // After operation stop, 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;
            }
            //---------------------------------
            // If there are records in driver memory, retrieve the data
            //---------------------------------
            if (m_Records > 0 || m_Records == -1)
            {
                Ret = dig.ReadLatestRecords(m_Id, Cdig.DIG_RECORD_DATA, 1, ref m_Data, 0, 0);
                if (Ret != 0)
                {
                    string ErrorString;
                    dig.GetErrorString(Ret, out ErrorString);
                    textBoxInfo.Text = "dig.ReadLatestRecordss = " + Ret.ToString() + " : " + ErrorString;
                    return;
                }
                //------------------------------------
                // Draw graph
                //------------------------------------
                DrawGraph();
            }
        }

        /// <summary>
        /// Show information
        /// </summary>
        private void buttonInfo_Click(object sender, System.EventArgs e)
        {
            int Ret;            // Return value
            float SampleRate;   // Sample rate
            float Duty;         // Duty ratio
            float Level;        // Trigger level
            short Slope;        // Trigger direction
            int Count;          // Trigger count
            int Status;         // Status
            string Str = "";

            //---------------------------------
            // 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";

            //-------------------------------------------
            // Get the information set by DigAutoSetup function automatically
            //-------------------------------------------
            //---------------------------------
            // Get the sample rate
            //---------------------------------
            Ret = dig.GetSampleRate(m_Id, out SampleRate);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetSampleRate = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            Str = String.Format("Sample rate : {0:F3}Hz\r\n", SampleRate);
            //---------------------------------
            // Get the record length
            //---------------------------------
            Ret = dig.GetRecordLength(m_Id, out m_RecordLength);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetRecordLength = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            Str = Str + String.Format("Record length : {0:D}\r\n", m_RecordLength);
            //---------------------------------
            // Get duty ratio
            //---------------------------------
            Ret = dig.GetDutyCycle(m_Id, out Duty);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetRecordLength = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            Str = Str + String.Format("Duty ratio : {0:F3}%\r\n", Duty);
            //---------------------------------
            // Gets the number of effective channels
            //---------------------------------
            Ret = dig.GetChannels(m_Id, out m_Channels);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetChannels = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            //---------------------------------
            // Get the trigger information
            //---------------------------------
            Ret = dig.GetPostTriggerAiEdge(m_Id, out m_TriggerChannel, out Level, out Slope, out Count);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetPostTriggerAiEdge = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            Str = Str + String.Format("Channel : {0:D}\r\n", m_TriggerChannel);
            Str = Str + String.Format("Trigger level : {0:F3}V\r\n", Level);
            //---------------------------------
            // Get the range information
            //---------------------------------
            Ret = dig.GetRange(m_Id, m_TriggerChannel, out m_Range);
            if (Ret != 0)
            {
                string ErrorString;
                dig.GetErrorString(Ret, out ErrorString);
                textBoxInfo.Text = "dig.GetRange = " + Ret.ToString() + " : " + ErrorString;
                return;
            }
            Str = Str + String.Format("Input range : {0:F3}VPP\r\n", m_Range);
            //---------------------------------
            // Show the information
            //---------------------------------
            textBoxDeviceInfo.Text = Str;

            textBoxInfo.Text = "Get information : Normality completion";
        }

        /// <summary>
        /// Stop acquisition
        /// </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 acquisition : 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

            //----------------------------------------------------
            // Repeat the drawing handling only for the times which is equal to the numer of acquisition data
            // In the effective channels, only the data of the least channel number will be shown
            //----------------------------------------------------
            XUnit = Graph.Size.Width / (float)(m_RecordLength);             // Calculate the moving pixel number of X axis for data 1
            OldY = Graph.Height * ((m_Range / 2) - m_Data[0]) / m_Range;    // Calculate the coordinate of Y axis
                                                                            // If the initial value of Y axis exceeds the drawing rect of graph
            if (OldY >= Graph.Height)
            {
                OldY = Graph.Height - 1;            // modify the position
            }
            // If the coordinate of Y axis is lower than the drawing rect
            else if (OldY < 0)
            {
                OldY = 0;                           // modify the drawing position
            }
            OldX = 0;
            for (int i = m_Channels; i < m_RecordLength * m_Channels; i += m_Channels)
            {
                PosX = OldX + XUnit;                // Calculate the coordinate of X axis
                PosY = Graph.Height * ((m_Range / 2) - m_Data[i]) / m_Range;    // Calculate the coordinate of Y axis
                                                                                // 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
        }
    }
}