﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CaioCs;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace AoGeneratingOnceUser
{
    public partial class Form1 : Form
    {
        //----------------------------------------
        // Create instance Caio class
        //----------------------------------------
        Caio aio = new Caio();

        //----------------------------------------
        // Macro definition
        //----------------------------------------
        public const int MAX_AO_RANGE_NUM = 31;    // Maximum number of elements in analog output range array

        //----------------------------------------
        // Declaration of global variables
        //----------------------------------------
        public short    g_id;                                                                  // ID for device access
        public string   g_file_name = "GeneratingData.csv";                                    // Generating data output file name
        public int      g_generating_count;                                                    // Total generating count
        public int[]    g_generating_buffer = null;                                            // User buffer
        public int      g_generating_buffer_size;                                              // User buffer size
        public GCHandle gCh;                                                                   // GCHandle for g_sampling_buffer array
        public IntPtr   pBuffer;                                                               // IntPtr for g_sampling_buffer array
        public short[]  g_ao_range = new short[MAX_AO_RANGE_NUM]{(short)CaioConst.PM10,        // +/-10V
                                                                 (short)CaioConst.PM5,         // +/-5V
                                                                 (short)CaioConst.PM25,        // +/-2.5V
                                                                 (short)CaioConst.PM125,       // +/-1.25V
                                                                 (short)CaioConst.PM1,         // +/-1V
                                                                 (short)CaioConst.PM0625,      // +/-0.625V
                                                                 (short)CaioConst.PM05,        // +/-0.5V
                                                                 (short)CaioConst.PM03125,     // +/-0.3125V
                                                                 (short)CaioConst.PM025,       // +/-0.25V
                                                                 (short)CaioConst.PM0125,      // +/-0.125V
                                                                 (short)CaioConst.PM01,        // +/-0.1V
                                                                 (short)CaioConst.PM005,       // +/-0.05V
                                                                 (short)CaioConst.PM0025,      // +/-0.025V
                                                                 (short)CaioConst.PM00125,     // +/-0.0125V
                                                                 (short)CaioConst.PM001,       // +/-0.01V
                                                                 (short)CaioConst.P10,         // 0 ~ 10V
                                                                 (short)CaioConst.P5,          // 0 ~ 5V
                                                                 (short)CaioConst.P4095,       // 0 ~ 4.095V
                                                                 (short)CaioConst.P25,         // 0 ~ 2.5V
                                                                 (short)CaioConst.P125,        // 0 ~ 1.25V
                                                                 (short)CaioConst.P1,          // 0 ~ 1V
                                                                 (short)CaioConst.P05,         // 0 ~ 0.5V
                                                                 (short)CaioConst.P025,        // 0 ~ 0.25V
                                                                 (short)CaioConst.P01,         // 0 ~ 0.1V
                                                                 (short)CaioConst.P005,        // 0 ~ 0.05V
                                                                 (short)CaioConst.P0025,       // 0 ~ 0.025V
                                                                 (short)CaioConst.P00125,      // 0 ~ 0.0125V
                                                                 (short)CaioConst.P001,        // 0 ~ 0.01V
                                                                 (short)CaioConst.P20MA,       // 0 ~ 20mA
                                                                 (short)CaioConst.P4TO20MA,    // 4 ~ 20mA
                                                                 (short)CaioConst.P1TO5 };     // 1 ~ 5V

        public Form1()
        {
            InitializeComponent();
        }

        private void AoGeneratingOnceUser_Load(object sender, EventArgs e)
        {
            //----------------------------------------
            // Set the default button
            //----------------------------------------
            AcceptButton = button_Close;
            //----------------------------------------
            // Update the initial display of device name
            //----------------------------------------
            textBox_DeviceName.Text = "AIO000";
            //----------------------------------------
            // Update the initial display of number of channels for analog output
            //----------------------------------------
            textBox_ChNum.Text = "1";
            //----------------------------------------
            // Update the initial display of generating clock
            //----------------------------------------
            textBox_GeneratingClock.Text = "1000";
            //----------------------------------------
            // Update the initial display of output data generating times
            //----------------------------------------
            textBox_GeneratingTimes.Text = "1000";
            //----------------------------------------
            // Create the combobox for analog output range
            //----------------------------------------
            comboBox_RangeValue.Items.Add("-10 - +10V");
            comboBox_RangeValue.Items.Add("-5 - +5V");
            comboBox_RangeValue.Items.Add("-2.5 - +2.5V");
            comboBox_RangeValue.Items.Add("-1.25 - +1.25V");
            comboBox_RangeValue.Items.Add("-1 - +1V");
            comboBox_RangeValue.Items.Add("-0.625 - +0.625V");
            comboBox_RangeValue.Items.Add("-0.5 - +0.5V");
            comboBox_RangeValue.Items.Add("-0.3125 - +0.3125V");
            comboBox_RangeValue.Items.Add("-0.25 - +0.25V");
            comboBox_RangeValue.Items.Add("-0.125 - +0.125V");
            comboBox_RangeValue.Items.Add("-0.1 - +0.1V");
            comboBox_RangeValue.Items.Add("-0.05 - +0.05V");
            comboBox_RangeValue.Items.Add("-0.025 - +0.025V");
            comboBox_RangeValue.Items.Add("-0.0125 - +0.0125V");
            comboBox_RangeValue.Items.Add("-0.01 - +0.01V");
            comboBox_RangeValue.Items.Add("0 - +10V");
            comboBox_RangeValue.Items.Add("0 - +5V");
            comboBox_RangeValue.Items.Add("0 - +4.095V");
            comboBox_RangeValue.Items.Add("0 - +2.5V");
            comboBox_RangeValue.Items.Add("0 - +1.25V");
            comboBox_RangeValue.Items.Add("0 - +1V");
            comboBox_RangeValue.Items.Add("0 - +0.5V");
            comboBox_RangeValue.Items.Add("0 - +0.25V");
            comboBox_RangeValue.Items.Add("0 - +0.1V");
            comboBox_RangeValue.Items.Add("0 - +0.05V");
            comboBox_RangeValue.Items.Add("0 - +0.025V");
            comboBox_RangeValue.Items.Add("0 - +0.0125V");
            comboBox_RangeValue.Items.Add("0 - +0.01V");
            comboBox_RangeValue.Items.Add("0 - +20mA");
            comboBox_RangeValue.Items.Add("4 - +20mA");
            comboBox_RangeValue.Items.Add("1 - +5V");
            //----------------------------------------
            // Change the selection of analog output range combobox to 0
            //----------------------------------------
            comboBox_RangeValue.SelectedIndex = 0;
            //----------------------------------------
            // Initialize global variables
            //----------------------------------------
            g_id               = 0;
            g_generating_count = 0;
        }

        //================================================================================
        // It is the process when the AioInit button is clicked
        // Initialize the device
        //================================================================================
        private void button_AioInit_Click(object sender, EventArgs e)
        {
            string device_name;     // Device name
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Get device name from textbox
            //----------------------------------------
            device_name = textBox_DeviceName.Text;
            //----------------------------------------
            // Device initialization
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.Init(device_name, out g_id);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.Init = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioResetDevice button is clicked
        // Reset the device
        //================================================================================
        private void button_ResetDevice_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Reset device
            //----------------------------------------
            ret = aio.ResetDevice(g_id);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.ResetDevice = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioSetAoRangeAll button is clicked
        // Set the output range of analog output
        //================================================================================
        private void button_SetAoRangeAll_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code
            int    index;           // Index of combobox

            //----------------------------------------
            // Update GUI information
            //----------------------------------------
            this.Refresh();
            //----------------------------------------
            // Get the index of range setting value from combobox
            //----------------------------------------
            index = comboBox_RangeValue.SelectedIndex;
            //----------------------------------------
            // Set the analog output range (all channels)
            //----------------------------------------
            ret = aio.SetAoRangeAll(g_id, g_ao_range[index]);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAoRangeAll = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioSetAoChannels button is clicked
        // Set the number of analog output channels used for generating
        //================================================================================
        private void button_SetAoChannels_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code
            short  ao_channels;     // Number of channels

            //----------------------------------------
            // Get the number of channels from textbox
            //----------------------------------------
            if(short.TryParse(textBox_ChNum.Text, out ao_channels) == false)
            {
                ao_channels = 1;
            }
            //----------------------------------------
            // Set the number of analog output channels used for conversion
            //----------------------------------------
            ret = aio.SetAoChannels(g_id, ao_channels);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAoChannels = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioSetAoSamplingClock button is clicked
        // Set the internal clock conversion speed used for generating
        //================================================================================
        private void button_SetAoSamplingClock_Click(object sender, EventArgs e)
        {
            string error_string;        // Error code string
            int    ret;                 // For return code
            float  generating_clock;    // Internal clock conversion speed

            //----------------------------------------
            // Get the internal clock conversion speed from textbox
            //----------------------------------------
            if (float.TryParse(textBox_GeneratingClock.Text, out generating_clock) == false)
            {
                generating_clock = 1000;
            }
            //----------------------------------------
            // Set the internal clock conversion speed
            //----------------------------------------
            ret = aio.SetAoSamplingClock(g_id, generating_clock);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAoSamplingClock = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the Basic Settings button is clicked
        // Performs the basic settings required for generating
        // (Basic setting must be performed after initialization processing/reset processing and before starting the first generating)
        //================================================================================
        private void button_BasicSettings_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Set the analog output conversion data transfer mode to user buffer mode
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAoTransferMode(g_id, 1);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Basic Settings: aio.SetAoTransferMode = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Set the data storage memory type to Not repeat output
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAoMemoryType(g_id, 0);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Basic Settings: aio.SetAoMemoryType = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Set the generating start condition to Software
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAoStartTrigger(g_id, 0);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Basic Settings: aio.SetAoStartTrigger = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Set the clock type to Internal Clock
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAoClockType(g_id, 0);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Basic Settings: aio.SetAoClockType = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Set the generating stop condition to Stop conversion by the specified times
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAoStopTrigger(g_id, 0);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Basic Settings: aio.SetAoStopTrigger = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Set the event factor to 'Event that device operation end',
            // 'Event that sampling clock error', and 'Event that DA conversion error'.
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAoEvent(g_id, Handle, (int)(CaioConst.AOE_END | CaioConst.AOE_SCERR | CaioConst.AOE_DAERR));
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Basic Settings: aio.SetAoEvent = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display the message that basic setting is completed
            //----------------------------------------
            textBox_ReturnCode.Text = "Basic Settings: Successful completion";
        }

        //================================================================================
        // It is the process when the User Buffer Set button is clicked
        // Generate output data and set the user buffer that stores the output data
        //================================================================================
        private void button_UserBufferSettings_Click(object sender, EventArgs e)
        {
            string       error_string;        // Error code string
            string       text_string;         // For updating the textbox
            StreamWriter fp;                  // File pointer
            long         i, j;                // Loop count
            int          ret;                 // For return code
            int          generating_times;    // Generating times of output data
            short        ao_channels;         // Number of channels
            short        data_size;           // Data size
            short        ao_resolution;       // Analog output resolution
            long         data1, data2;        // Temporary output data
            long         gain, offset;        // Coefficient of sine waveform

            //----------------------------------------
            // Get generating times from textbox
            //----------------------------------------
            if (int.TryParse(textBox_GeneratingTimes.Text, out generating_times) == false)
            {
                generating_times = 1000;
            }
            //----------------------------------------
            // Get the number of channels
            //----------------------------------------
            ret = aio.GetAoChannels(g_id, out ao_channels);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Set: aio.GetAoChannels = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // When the user buffer mode is used to transfer data, get data size that is necessary for one sampling
            //----------------------------------------
            ret = aio.GetAoSamplingDataSize(g_id, out data_size);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Set: aio.GetAoSamplingDataSize = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Allocate a user buffer to store conversion data
            //----------------------------------------
            if (g_generating_buffer != null)
            {
                //----------------------------------------
                // GCHandle free
                //----------------------------------------
                if (gCh.IsAllocated == true)
                {
                    gCh.Free();
                }
                g_generating_buffer = null;
            }
            //--------------------
            // User buffer size: number of packets that is necessary for one generating x generating times
            //--------------------
            g_generating_buffer_size = data_size * generating_times;
            try
            {
                g_generating_buffer = new int[g_generating_buffer_size];
            }
            catch
            {
                textBox_ReturnCode.Text = "User Buffer Set: Failed to allocate the user buffer";
                return;
            }
            //----------------------------------------
            // Get the resolution of the analog output
            //----------------------------------------
            ret = aio.GetAoResolution(g_id, out ao_resolution);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Set: aio.GetAoResolution = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Create analog output data: sine waveform
            //----------------------------------------
            //--------------------
            // 16 bit resolution
            //--------------------
            if (ao_resolution == 16)
            {
                gain = 0xffff / 2;
                offset = gain;
            }
            //--------------------
            // 12 bit resolution
            //--------------------
            else
            {
                gain = 0xfff / 2;
                offset = gain;
            }
            //--------------------
            // Create data
            //--------------------
            for (i = 0; i < generating_times; i++)
            {
                for (j = 0; j < data_size; j++)
                {
                    if ((j * 2 + 1) >= ao_channels)
                    {
                        data1 = (long)(gain * Math.Sin(2 * 3.14159265358979 * i / generating_times + 3.14159265358979 / 2 * ((j * 2) % 4)) + offset);
                        data2 = 0;
                    }
                    else
                    {
                        data1 = (long)(gain * Math.Sin(2 * 3.14159265358979 * i / generating_times + 3.14159265358979 / 2 * ((j * 2) % 4)) + offset);
                        data2 = (long)(gain * Math.Sin(2 * 3.14159265358979 * i / generating_times + 3.14159265358979 / 2 * ((j * 2 + 1) % 4)) + offset);
                    }
                    g_generating_buffer[i * data_size + j] = (int)(data2 & 0x0000ffff) << 16 | (int)(data1 & 0x0000ffff);
                }
            }
            //----------------------------------------
            // Open file
            //----------------------------------------
            try
            {
                fp = File.CreateText(g_file_name);
            }
            catch
            {
                textBox_ReturnCode.Text = "User Buffer Set: File.CreateText = file open error.";
                return;
            }
            //----------------------------------------
            // Create file
            //----------------------------------------
            for (i = 0; i < generating_times; i++)
            {
                text_string = "";
                //--------------------
                // Generate display string
                //--------------------
                text_string += string.Format("{0,5},", (i + 1));
                //--------------------
                // Repeat the process for the specified number of packets
                //--------------------
                for (j = 0; j < data_size; j++)
                {
                    text_string += string.Format(" {0:X8}", g_generating_buffer[i * data_size + j]);
                    //--------------------
                    // Add newline character for the last packet
                    //--------------------
                    if (j == (data_size - 1))
                    {
                        text_string += "\r\n";
                    }
                    //--------------------
                    // Add comma for channels other than the last channel
                    //--------------------
                    else
                    {
                        text_string += ",";
                    }
                }
                //----------------------------------------
                // Write data
                //----------------------------------------
                try
                {
                    fp.Write(text_string);
                }
                catch
                {
                    textBox_ReturnCode.Text = "User Buffer Set: fp.Write = file write error.";
                    fp.Close();
                    return;
                }
            }
            //----------------------------------------
            // Close file
            //----------------------------------------
            fp.Close();
            //----------------------------------------
            // Specify Pinned handle to g_sampling_buffer
            //----------------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(g_generating_buffer, GCHandleType.Pinned);
            }
            //----------------------------------------
            // Get address object by Pinned handle
            //----------------------------------------
            pBuffer = gCh.AddrOfPinnedObject();
            //----------------------------------------
            // Set the user buffer
            //----------------------------------------
            ret = aio.SetAoTransferData(g_id, g_generating_buffer_size, pBuffer);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Set: aio.SetAoTransferData = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "User Buffer Set: Successful completion";
        }

        //================================================================================
        // It is the process when the Generating Start button is clicked
        // After clearing the memory and status, start generating.
        //================================================================================
        private void button_GeneratingStart_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            string text_string;     // For updating the textbox
            int    ao_status;       // Analog output status
            int    ret;             // For return code

            //----------------------------------------
            // Reset the analog output status
            //----------------------------------------
            ret = aio.ResetAoStatus(g_id);
            //----------------------------------------
            // Error process
            //----------------------------------------
            //--------------------
            // Exit the process if not completed successfully
            //--------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Generating Start: aio.ResetAoStatus = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Initialize the total generating count
            //----------------------------------------
            g_generating_count = 0;
            //----------------------------------------
            // Start generating
            //----------------------------------------
            ret = aio.StartAo(g_id);
            //----------------------------------------
            // Error process
            //----------------------------------------
            //--------------------
            // Exit the process if not completed successfully
            //--------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Generating Start: aio.StartAo = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Get status
            //----------------------------------------
            ret = aio.GetAoStatus(g_id, out ao_status);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Generating Start: aio.GetAoStatus = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display status
            //----------------------------------------
            text_string = string.Format("{0:x8}H (", ao_status);
            //--------------------
            // When status 'Device is running' is ON
            //--------------------
            if ((ao_status & (int)CaioConst.AOS_BUSY) == (int)CaioConst.AOS_BUSY)
            {
                text_string += "Operating";
            }
            //--------------------
            // When status 'Device is running' is OFF
            //--------------------
            else
            {
                text_string += "Stop";
            }
            //--------------------
            // When status 'Wait the start trigger' is ON
            //--------------------
            if ((ao_status & (int)CaioConst.AOS_START_TRG) == (int)CaioConst.AOS_START_TRG)
            {
                text_string += ", Wait the start trigger";
            }
            //--------------------
            // When status 'The specified number of data are output' is ON
            //--------------------
            if ((ao_status & (int)CaioConst.AOS_DATA_NUM) == (int)CaioConst.AOS_DATA_NUM)
            {
                text_string += ", The specified number of data are output";
            }
            //--------------------
            // When status 'Sampling clock error' is ON
            //--------------------
            if ((ao_status & (int)CaioConst.AOS_SCERR) == (int)CaioConst.AOS_SCERR)
            {
                text_string += ", Sampling clock error";
            }
            //--------------------
            // When status 'DA conversion error' is ON
            //--------------------
            if ((ao_status & (int)CaioConst.AOS_AOERR) == (int)CaioConst.AOS_AOERR)
            {
                text_string += ", DA conversion error";
            }
            //--------------------
            // When status 'Driver spec error' is ON
            //--------------------
            if ((ao_status & (int)CaioConst.AOS_DRVERR) == (int)CaioConst.AOS_DRVERR)
            {
                text_string += ", Driver spec error";
            }
            text_string += ")";
            textBox_Status.Text = text_string;
            //----------------------------------------
            // Update generating count
            //----------------------------------------
            textBox_TransferCount.Text = "0";
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "Generating Start: Successful completion";
        }

        //================================================================================
        // It is the process when the AioGetAoTransferCount button is clicked
        // Get the number of data that are transferred from the user memory and display it on the dialog
        //================================================================================
        private void button_GetAoTransferCount_Click(object sender, EventArgs e)
        {
            string error_string;         // Error code string
            int    ret;                  // For return code
            int    ao_transfer_count;    // Tansfer count

            //----------------------------------------
            // Get the number of data that are transferred from the user memory
            //----------------------------------------
            ret = aio.GetAoTransferCount(g_id, out ao_transfer_count);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.GetAoTransferCount = " + ret.ToString() + " : " + error_string;
            //----------------------------------------
            // When the function for getting the number of data transferred from the user memory is completed successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Update transfer position
                //--------------------
                textBox_TransferCount.Text = ao_transfer_count.ToString();
            }
        }

        //================================================================================
        // It is the process when the AioGetAoStatus button is clicked
        // Get the analog output status and display it on the dialog
        //================================================================================
        private void button_GetAoStatus_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            string text_string;     // For updating the textbox
            int    ao_status;       // Analog output status
            int    ret;             // For return code

            //----------------------------------------
            // Get status
            //----------------------------------------
            ret = aio.GetAoStatus(g_id, out ao_status);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.GetAoStatus = " + ret.ToString() + " : " + error_string;
            //----------------------------------------
            // When the status acquisition function is completed successfully
            //----------------------------------------
            if (ret == 0)
            {
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ao_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_BUSY) == (int)CaioConst.AOS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_START_TRG) == (int)CaioConst.AOS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are output' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DATA_NUM) == (int)CaioConst.AOS_DATA_NUM)
                {
                    text_string += ", The specified number of data are output";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_SCERR) == (int)CaioConst.AOS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'DA conversion error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_AOERR) == (int)CaioConst.AOS_AOERR)
                {
                    text_string += ", DA conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DRVERR) == (int)CaioConst.AOS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
            }
        }

        //================================================================================
        // It is the process when the Generating Stop button is clicked
        // Stop generating
        //================================================================================
        private void button_GeneratingStop_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Stop generating
            //----------------------------------------
            ret = aio.StopAo(g_id);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Generating Stop: aio.StopAo = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display the message that generating stop is completed
            //----------------------------------------
            textBox_ReturnCode.Text = "Generating Stop: Successful completion";
        }

        //================================================================================
        // It is the process when the AioExit button is clicked
        // Perform the exit process of device
        //================================================================================
        private void button_AioExit_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Release the output data buffer
            //----------------------------------------
            if (g_generating_buffer != null)
            {
                //----------------------------------------
                // GCHandle free
                //----------------------------------------
                if (gCh.IsAllocated == true)
                {
                    gCh.Free();
                }
                g_generating_buffer = null;
            }
            //----------------------------------------
            // Exit process
            //----------------------------------------
            ret = aio.Exit(g_id);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.Exit = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the Close button is clicked
        // Perform the exit process of device and terminate the application
        //================================================================================
        private void button_Close_Click(object sender, EventArgs e)
        {
            //----------------------------------------
            // Release the output data buffer
            //----------------------------------------
            if (g_generating_buffer != null)
            {
                //----------------------------------------
                // GCHandle free
                //----------------------------------------
                if (gCh.IsAllocated == true)
                {
                    gCh.Free();
                }
                g_generating_buffer = null;
            }
            //----------------------------------------
            // Exit process
            //----------------------------------------
            aio.Exit(g_id);
            //----------------------------------------
            // Close dialog
            //----------------------------------------
            this.Close();
        }

        //================================================================================
        // Operation when event occurred
        // Process for each event occurred
        //================================================================================
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protected override void WndProc(ref Message m)
        {
            string error_string;         // Error code string
            string text_string;          // For updating the textbox
            int    ao_transfer_count;    // Transfer count
            int    ao_status;            // Analog output status
            int    ret;                  // For return code

            //----------------------------------------
            // Event that device operation end
            // Acquire and display data
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AOE_END)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAoStatus(g_id, out ao_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Device Operation End Event Process: aio.GetAoStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ao_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_BUSY) == (int)CaioConst.AOS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_START_TRG) == (int)CaioConst.AOS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are output' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DATA_NUM) == (int)CaioConst.AOS_DATA_NUM)
                {
                    text_string += ", The specified number of data are output";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_SCERR) == (int)CaioConst.AOS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'DA conversion error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_AOERR) == (int)CaioConst.AOS_AOERR)
                {
                    text_string += ", DA conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DRVERR) == (int)CaioConst.AOS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Get the number of data that are transferred from the user memory
                //----------------------------------------
                ret = aio.GetAoTransferCount(g_id, out ao_transfer_count);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Device Operation End Event Process: aio.GetAoTransferCount = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display transfer count
                //----------------------------------------
                textBox_TransferCount.Text = ao_transfer_count.ToString();
                //----------------------------------------
                // Update the total generating count
                //----------------------------------------
                g_generating_count = ao_transfer_count;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Device Operation End Event Process: Successful completion";
            }
            //----------------------------------------
            // Event that sampling clock error
            // Display the status
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AOE_SCERR)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAoStatus(g_id, out ao_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Sampling Clock Error Occurrence Process: aio.GetAoStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ao_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_BUSY) == (int)CaioConst.AOS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_START_TRG) == (int)CaioConst.AOS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are output' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DATA_NUM) == (int)CaioConst.AOS_DATA_NUM)
                {
                    text_string += ", The specified number of data are output";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_SCERR) == (int)CaioConst.AOS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'DA conversion error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_AOERR) == (int)CaioConst.AOS_AOERR)
                {
                    text_string += ", DA conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DRVERR) == (int)CaioConst.AOS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Sampling Clock Error Occurrence Process: Successful completion";
            }
            //----------------------------------------
            // Event that DA conversion error
            // Display the status
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AOE_DAERR)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAoStatus(g_id, out ao_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "DA Conversion Error Occurrence Process: aio.GetAoStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ao_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_BUSY) == (int)CaioConst.AOS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_START_TRG) == (int)CaioConst.AOS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are output' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DATA_NUM) == (int)CaioConst.AOS_DATA_NUM)
                {
                    text_string += ", The specified number of data are output";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_SCERR) == (int)CaioConst.AOS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'DA conversion error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_AOERR) == (int)CaioConst.AOS_AOERR)
                {
                    text_string += ", DA conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ao_status & (int)CaioConst.AOS_DRVERR) == (int)CaioConst.AOS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "DA Conversion Error Occurrence Process: Successful completion";
            }
            base.WndProc(ref m);
        }
    }
}
