using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Jdas_Mbic.Bluecell_BootProtocol;
using Excel = Microsoft.Office.Interop.Excel;
namespace Jdas_Mbic
{
    public partial class Hidden : Form
    {
        public const byte BLUECELL_HEADER = 0xBE;
        public const byte BLUECELL_TAILER = 0xEB;
        const byte TableGetMaxLength = 1 + 7 + 1;
        public JdasMbic main;

        public Hidden()
        {
            InitializeComponent();
        }

        private void comboBox_TableName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = (ComboBox)sender;
            string tempstr = comboBox.Text;

            switch (tempstr)
            {
                case "ATT_DL1":
                case "ATT_UL1":
                case "ATT_DL2":
                case "ATT_UL2":
                case "ATT_DL3":
                case "ATT_UL3":
                case "ATT_DL4":
                case "ATT_UL4":
                    dataGridView_TableSetting.Rows.Clear();
                    ATT_TableLayoutSetting();
                    break;
                case "DET_DL1":
                case "DET_DL2":
                case "DET_DL3":
                case "DET_DL4":
                    dataGridView_TableSetting.Rows.Clear();
                    DET_TableLayoutSetting(JdasMbic.DLUL_Category.DL_DET);
                    break;
                case "DET_UL1":
                case "DET_UL2":
                case "DET_UL3":
                case "DET_UL4":
                    dataGridView_TableSetting.Rows.Clear();
                    DET_TableLayoutSetting(JdasMbic.DLUL_Category.UL_DET);
                    break;
                case "TEMP_DL1":
                case "TEMP_UL1":
                case "TEMP_DL2":
                case "TEMP_UL2":
                case "TEMP_DL3":
                case "TEMP_UL3":
                case "TEMP_DL4":
                case "TEMP_UL4":
                    dataGridView_TableSetting.Rows.Clear();
                    Temp_TableLayoutSetting();
                    break;
                default:
                    MessageBox.Show("존재하지 않는 ComboBox 입니다.\r\n 확인해주세요.");
                    break;
            }

            button_FileLoad_Click(sender, null);
        }
        private void Temp_TableLayoutSetting()
        {
            string tempstr = "";

            double Temp_Data = JdasMbic.Table_Temp_DefaultValue;
            for (int i = 0; i < 14; i++)
            {
                dataGridView_TableSetting.Rows.Add();
                tempstr = string.Format("{0:0}", Temp_Data);
                dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " ℃";
                Temp_Data = Temp_Data + 5;
                dataGridView_TableSetting[1, i].Value = "0";

            }
            foreach (DataGridViewRow row in this.dataGridView_TableSetting.Rows)
            {
                row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            }
            this.dataGridView_TableSetting.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            this.dataGridView_TableSetting.TopLeftHeaderCell.Value = "No.";
            dataGridView_TableSetting.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView_TableSetting.ClearSelection();
        }
        private void DET_TableLayoutSetting(JdasMbic.DLUL_Category cat)
        {
            string tempstr = "";
            JdasMbic.DLUL_Category tempenum = cat;

            switch (tempenum)
            {
                case JdasMbic.DLUL_Category.DL_DET:
                    double Temp_DL_Data = JdasMbic.Table_DL_DefaultValue;
                    for (int i = 0; i < 33; i++)
                    {
                        dataGridView_TableSetting.Rows.Add();
                        tempstr = string.Format("{0:0}", Temp_DL_Data);
                        dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " dBm";
                        Temp_DL_Data = Temp_DL_Data - 1;
                        dataGridView_TableSetting[1, i].Value = "0";

                    }
                    break;
                case JdasMbic.DLUL_Category.UL_DET:
                    double Temp_UL_Data = JdasMbic.Table_UL_DefaultValue;
                    for (int i = 0; i < 46; i++)
                    {
                        dataGridView_TableSetting.Rows.Add();
                        tempstr = string.Format("{0:0}", Temp_UL_Data);
                        dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " dBm";
                        Temp_UL_Data = Temp_UL_Data - 1;
                        dataGridView_TableSetting[1, i].Value = "0";
                    }
                    break;
            }
            foreach (DataGridViewRow row in this.dataGridView_TableSetting.Rows)
            {
                row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            }
            this.dataGridView_TableSetting.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            this.dataGridView_TableSetting.TopLeftHeaderCell.Value = "No.";
            dataGridView_TableSetting.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView_TableSetting.ClearSelection();

        }
        private void button_Initalize_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView_TableSetting.RowCount; i++)
            {
                dataGridView_TableSetting[1, i].Value = 0;
            }
        }
        private void ATT_TableLayoutSetting()
        {
            double TempDbmData = JdasMbic.Table_Dbm_DefaultValue;
            string tempstr = "";
            for (int i = 0; i < 64; i++)
            {
                dataGridView_TableSetting.Rows.Add();
                tempstr = string.Format("{0:0.0}", TempDbmData);
                dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " dBm"; ;
                dataGridView_TableSetting[1, i].Value = "0";
                TempDbmData = TempDbmData + 0.5;
            }

            foreach (DataGridViewRow row in this.dataGridView_TableSetting.Rows)
            {
                row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            }
            this.dataGridView_TableSetting.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            this.dataGridView_TableSetting.TopLeftHeaderCell.Value = "No.";
            dataGridView_TableSetting.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView_TableSetting.ClearSelection();
        }

        private void button_Expansion_Click(object sender, EventArgs e)
        {
            List<int> TmpList = new List<int>();
            int Count = 0;
            double MaxVal = 0, MinVal = 0, Result = 0;
            double Tmpdata = 0;

            TmpList = DataGridViewIndexOutput();
            TmpList.Sort();

            Count = (TmpList[TmpList.Count - 1] - TmpList[0]);
            MaxVal = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[TmpList.Count - 1]].Value);
            MinVal = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[0]].Value);

            Result = (MaxVal - MinVal) / Count;

            for (int i = 0; i < (Count - 1); i++)
            {
                Tmpdata = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[0] + i].Value);
                if (comboBox_TableName.Text.Contains("DET") == true)
                {
                    dataGridView_TableSetting[1, TmpList[0] + (i + 1)].Value = string.Format("{0:0.000}", Math.Round(Tmpdata + Result, 3));
                }
                else
                {
                    dataGridView_TableSetting[1, TmpList[0] + (i + 1)].Value = string.Format("{0:0.0}", Math.Round(Tmpdata + Result, 1));
                }
            }

            /* for (int i = 0; i < TmpList.Count; i++)
             {
                 dataGridView_TableSetting[1, TmpList[i]].Value = numericUpDown_MultiSet.Value.ToString();
             }*/
        }

        private void button_FileSave_Click(object sender, EventArgs e)
        {
            byte[] temp_buf = new byte[JdasMbic.DET_TableMaxLength];
            string tempstr;
            Int16 detret;
            int a = 0, i = 0;
            int addsendLength = 0;
            byte tmp_h, tmp_l, attret;
            
            try
            {

                ComboBox cb = (ComboBox)comboBox_TableName;
                tempstr = cb.Text;
            }
            catch { tempstr = comboBox_TableName.Text; }
            byte type = 0;
            switch (tempstr)
            {
                case "ATT_DL1": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P1_ATT_Accuracy_Table_Number; break;
                case "ATT_DL2": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P2_ATT_Accuracy_Table_Number; break;
                case "ATT_DL3": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P3_ATT_Accuracy_Table_Number; break;
                case "ATT_DL4": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P4_ATT_Accuracy_Table_Number; break;
                case "ATT_UL1": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P1_ATT_Accuracy_Table_Number; break;
                case "ATT_UL2": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P2_ATT_Accuracy_Table_Number; break;
                case "ATT_UL3": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P3_ATT_Accuracy_Table_Number; break;
                case "ATT_UL4": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P4_ATT_Accuracy_Table_Number; break;
                case "DET_DL1": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P1_Level_Table_Number; break;
                case "DET_DL2": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P2_Level_Table_Number; break;
                case "DET_DL3": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P3_Level_Table_Number; break;
                case "DET_DL4": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P4_Level_Table_Number; break;
                case "DET_UL1": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P1_Level_Table_Number; break;
                case "DET_UL2": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P2_Level_Table_Number; break;
                case "DET_UL3": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P3_Level_Table_Number; break;
                case "DET_UL4": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P4_Level_Table_Number; break;
                case "TEMP_DL1": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P1_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_DL2": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P2_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_DL3": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P3_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_DL4": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P4_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL1": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P1_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL2": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P2_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL3": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P3_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL4": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P4_ATT_Temp_guarantee_Table_Number; break;

                default:
                    MessageBox.Show("존재하지 않는 ComboBox 입니다.\r\n 확인해주세요.");
                    break;
            }
            //temp_buf[] = dataGridView_TableSetting.Rows[r - 1].Cells[1].Value
            Int16 Length = Convert.ToByte(JdasMbic.DET_TableMaxLength - 4);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type] = (byte)Bluecell_BootProtocol.DATATYPE.ATT_TableSet;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = Convert.ToByte((Length & 0xFF00) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = Convert.ToByte((Length & 0x00FF));
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = JdasMbic.DET_TableMaxLength - 2;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = (byte)type;

            if (comboBox_TableName.Text.Contains("DET") == true)
            {
                for (i = 0; i < dataGridView_TableSetting.RowCount; i++)
                {
                    detret = Convert.ToInt16(Convert.ToDouble(dataGridView_TableSetting[1, i].Value) * 1000);
                    tmp_h = Convert.ToByte((detret & 0xFF00) >> 8);
                    tmp_l = Convert.ToByte((detret & 0x00FF));
                    temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i * 2] = tmp_h;
                    temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + (i * 2) + 1] = tmp_l;
                }
                addsendLength = 160 - i;
                for (a = i * 2; a < i + addsendLength - 2; a++)
                {
                    attret = 0;
                    temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a] = (attret);
                }
                sbyte tmp = (sbyte)numericUpDown_TableRef.Value;
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 0] = (byte)(tmp & 0xFF);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 1] = Convert.ToByte(numericUpDown_TableLength.Value);
                UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 2] = Convert.ToByte((CRCRET & 0xFF00) >> 8);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 3] = Convert.ToByte(CRCRET & 0x00FF);
                ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, JdasMbic.DET_TableMaxLength);
            }
            else if (comboBox_TableName.Text.Contains("TEMP") == true)
            {
                Length = Convert.ToByte(JdasMbic.ATT_TableMaxLength - 4);

                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = Convert.ToByte((Length & 0xFF00) >> 8);
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = Convert.ToByte((Length & 0x00FF));
                //for (i = 0; i < dataGridView_TableSetting.RowCount; i++)
                for (i = 0; i < 0x40; i++)
                {
                    try
                    {
                        attret = Convert.ToByte(Convert.ToSByte(Convert.ToDouble(dataGridView_TableSetting[1, i].Value) * 4) & 0xFF);

                        temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i] = (attret);
                    }
                    catch { }
                }

                for (a = i; a < i + 30; a++)
                {
                    attret = 0;

                    temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i] = (attret);
                }
                sbyte tmpdata = (sbyte)(numericUpDown_TableRef.Value);
                byte data = Convert.ToByte(tmpdata & 0xFF);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 0] = data;
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 1] = Convert.ToByte(numericUpDown_TableLength.Value);

                UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 2] = Convert.ToByte((CRCRET & 0xFF00) >> 8);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 3] = Convert.ToByte(CRCRET & 0x00FF);
                ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, JdasMbic.ATT_TableMaxLength);

            }
            else 
            {
                Length = Convert.ToByte(JdasMbic.ATT_TableMaxLength - 4);

                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = Convert.ToByte((Length & 0xFF00) >> 8);
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = Convert.ToByte((Length & 0x00FF));
                //for (i = 0; i < dataGridView_TableSetting.RowCount; i++)
                for (i = 0; i < 0x40; i++)
                {
                    try
                    {
                        attret = Convert.ToByte(Convert.ToSByte(Convert.ToDouble(dataGridView_TableSetting[1, i].Value) * 2) & 0xFF);

                        temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i] = (attret);
                    }
                    catch { }
                }

                for (a = i; a < i + 30; a++)
                {
                    attret = 0;

                    temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i] = (attret);
                }
                sbyte tmpdata = (sbyte)(numericUpDown_TableRef.Value);
                byte data = Convert.ToByte(tmpdata & 0xFF);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 0] = data;
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 1] = Convert.ToByte(numericUpDown_TableLength.Value);

                UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 2] = Convert.ToByte((CRCRET & 0xFF00) >> 8);
                temp_buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + a + 3] = Convert.ToByte(CRCRET & 0x00FF);
                ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, JdasMbic.ATT_TableMaxLength);

            }


            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;
        }
        private Thread cpuThread;
        //private double[] cpuArray = new double[64];

        private void getPerformanceCounters()
        {
            var cpuPerfCounter = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");

            while (true)
            {
                //cpuArray[cpuArray.Length - 1] = Math.Round(cpuPerfCounter.NextValue(), 0);

                //Array.Copy(cpuArray, 1, cpuArray, 0, cpuArray.Length - 1);

                if (chart_Table.IsHandleCreated)
                {
                    main.Invoke((MethodInvoker)delegate { UpdateCpuChart(); });
                }
                else
                {
                    //......
                }

                Thread.Sleep(1000);
            }
        }
        private void UpdateCpuChart()
        {
            try
            {
                chart_Table.Series[0].Points.Clear();
                for (int i = 0; i < dataGridView_TableSetting.RowCount; ++i)
                {
                    chart_Table.Series[0].Points.AddY(dataGridView_TableSetting[1, i].Value);
                }
            }
            catch { }
        }
        private void button_CurrentOutput_Click(object sender, EventArgs e)
        {
            int columnIndex = dataGridView_TableSetting.CurrentCell.ColumnIndex;
            int rowIndex = dataGridView_TableSetting.CurrentCell.RowIndex;

            dataGridView_TableSetting[1, rowIndex].Value
                = numericUpDown_CurrentOutput.Value;
        }
        private void TableChart_Create()
        {
            cpuThread = new Thread(new ThreadStart(this.getPerformanceCounters));
            cpuThread.IsBackground = true;
            cpuThread.Start();
        }


        private delegate void StringSend(object label, String str);
        private delegate String Stringreturn(object combobox);
        private void Numeric_Text_Set(object label, String str)
        {
            NumericUpDown Temp_label = (NumericUpDown)label;
            Temp_label.Text = str;
        }
        private String ComboBox_Text_Get(object data)
        {
            ComboBox Temp_data = (ComboBox)data;
            return Temp_data.Text;
        }
        public void TableDataStatusSet(byte[] buf)
        {
#if true
            Int16 TableValue = 0;
            double ret = 0;
            sbyte tempdata = 0;
            string data = Convert.ToString(main.Invoke(new Stringreturn(ComboBox_Text_Get), comboBox_TableName));
            bool Det_Att_Set = false;
            byte datalen_div = 2;
            int Length = 0;
            int i = 0;
            int TableLength = 0;
            sbyte TableRef = 0;


            if (data.Contains("DET") == true)
            {
                Det_Att_Set = false;
                datalen_div = 2;
                Length = buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] << 8 | buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L];
                TableRef = (sbyte)buf[Length - 1];
                TableLength = buf[(Length)];
                Length -= 4;
                Length /= datalen_div;

            }
            else
            {
                Det_Att_Set = true;
                datalen_div = 1;
                Length = (buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] + 1 - 4) / datalen_div;
                TableRef = (sbyte)buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L + 1 + Length + 1];
                TableLength = buf[Length + 2];
            }
            main.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_TableRef, TableRef.ToString("N2"));
            main.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_TableLength, TableLength.ToString("N2"));

            for (i = 0; i < Length; i++)
            {
                if (Det_Att_Set == false)
                {
                    TableValue = (short)((buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + (i * 2)] << 8) | buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 2) + (i * 2)]);
                    /*TableValue <<= 8;

                    TableValue = buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 2) +( i *  2) ];*/
                    ret = Convert.ToDouble(TableValue) / 1000;
                    if (ret > 4 || ret < 0)
                        TableValue = 0;



                }
                else if (data.Contains("TEMP") == true)
                {
                    tempdata = (SByte)((buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i]));//Convert.ToSByte((buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i]));

                    ret = Convert.ToDouble(tempdata) / 4;
                }
                else
                {
                    tempdata = (SByte)((buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i]));//Convert.ToSByte((buf[(int)(Bluecell_ProtIndex_p.Bluecell_data + 1) + i]));

                    ret = Convert.ToDouble(tempdata) / 2;
                }
                try
                {
                    dataGridView_TableSetting[1, i].Value = ret.ToString("N3");
                    // DET_TableSetting(dataGridView_TableSetting[0, i].Value, dataGridView_TableSetting[1, i].Value, i);
                }
                catch { }


                //main.Invoke(new StringSend(Table_Text_Set), dataGridView_TableSetting[1, i].Value, TableValue.ToString("N2"));
            }


            TableChart_Create();

            /*dataGridView_TableSetting[1, i].Value
            main.Invoke(new StringSend(Table_Text_Set), dataGridView_TableSetting, adcdata.ToString("N2"));*/



#endif

        }
       
        private void button_FileLoad_Click(object sender, EventArgs e)
        {
            byte[] temp_buf = new byte[TableGetMaxLength];
            string tempstr;
            try
            {

                ComboBox cb = (ComboBox)sender;
                tempstr = cb.Text;
            }
            catch { tempstr = comboBox_TableName.Text; }
            byte type = 0;
            switch (tempstr)
            {
                case "ATT_DL1": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P1_ATT_Accuracy_Table_Number; break;
                case "ATT_DL2": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P2_ATT_Accuracy_Table_Number; break;
                case "ATT_DL3": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P3_ATT_Accuracy_Table_Number; break;
                case "ATT_DL4": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P4_ATT_Accuracy_Table_Number; break;
                case "ATT_UL1": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P1_ATT_Accuracy_Table_Number; break;
                case "ATT_UL2": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P2_ATT_Accuracy_Table_Number; break;
                case "ATT_UL3": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P3_ATT_Accuracy_Table_Number; break;
                case "ATT_UL4": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P4_ATT_Accuracy_Table_Number; break;
                case "DET_DL1": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P1_Level_Table_Number; break;
                case "DET_DL2": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P2_Level_Table_Number; break;
                case "DET_DL3": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P3_Level_Table_Number; break;
                case "DET_DL4": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P4_Level_Table_Number; break;
                case "DET_UL1": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P1_Level_Table_Number; break;
                case "DET_UL2": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P2_Level_Table_Number; break;
                case "DET_UL3": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P3_Level_Table_Number; break;
                case "DET_UL4": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P4_Level_Table_Number; break;
                case "TEMP_DL1": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P1_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_DL2": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P2_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_DL3": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P3_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_DL4": type = (byte)JdasMbic.MBIC_TableNumber.DLI_P4_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL1": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P1_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL2": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P2_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL3": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P3_ATT_Temp_guarantee_Table_Number; break;
                case "TEMP_UL4": type = (byte)JdasMbic.MBIC_TableNumber.ULO_P4_ATT_Temp_guarantee_Table_Number; break;

                default:
                    MessageBox.Show("존재하지 않는 ComboBox 입니다.\r\n 확인해주세요.");
                    break;
            }


            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type] = (byte)Bluecell_BootProtocol.DATATYPE.ATT_TableGet;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = Convert.ToByte((TableGetMaxLength - 4) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = Convert.ToByte((TableGetMaxLength - 4) & 0x00FF);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = TableGetMaxLength - 2;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = type;
            UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 1] = Convert.ToByte((CRCRET & 0xFF00) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 2] = Convert.ToByte(CRCRET & 0x00FF);
            ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, temp_buf.Length);
            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;
        }
        private List<int> DataGridViewIndexOutput()
        {
            List<int> Tmplist = new List<int>();

            Int32 selectedCellCount =
            dataGridView_TableSetting.GetCellCount(DataGridViewElementStates.Selected);
            if (selectedCellCount > 0)
            {
                System.Text.StringBuilder sb =
                    new System.Text.StringBuilder();

                //for (int i = 0;i < selectedCellCount; i++)
                for (int i = 0; i < selectedCellCount; i += 2)
                {
                    sb.Append("Row: ");
                    sb.Append(dataGridView_TableSetting.SelectedCells[i].RowIndex.ToString());
                    Tmplist.Add(dataGridView_TableSetting.SelectedCells[i].RowIndex);
                    /*sb.Append(", Column: ");
                    sb.Append(dataGridView_TableSetting.SelectedCells[i].ColumnIndex.ToString());*/
                    sb.Append(Environment.NewLine);
                }

                // sb.Append("Total: " + selectedCellCount.ToString());
                // MessageBox.Show(sb.ToString(), "Selected Cells");
            }
            return Tmplist;
        }
        private void button_MultiSet_Click(object sender, EventArgs e)
        {
            List<int> TmpList = new List<int>();
            TmpList = DataGridViewIndexOutput();
            for (int i = 0; i < TmpList.Count; i++)
            {
                dataGridView_TableSetting[1, TmpList[i]].Value = numericUpDown_MultiSet.Value.ToString();
            }
        }

        private void button_MultiOffset_Click(object sender, EventArgs e)
        {
            List<int> TmpList = new List<int>();
            TmpList = DataGridViewIndexOutput();
            double CurrentVal = 0, SumVal = 0;

            for (int i = 0; i < TmpList.Count; i++)
            {
                CurrentVal = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[i]].Value);
                SumVal = Convert.ToDouble(numericUpDown_MultiOffset.Value);
                dataGridView_TableSetting[1, TmpList[i]].Value = Convert.ToString(CurrentVal + SumVal);
            }
        }



        private void button_TableDL_Click(object sender, EventArgs e)
        {

        }

        private void button_TableUL_Click(object sender, EventArgs e)
        {

        }
        public void GridViewExcel(DataGridView grid)
        {
            Excel.Application oXL;
            Excel._Workbook oWB;
            Excel._Worksheet oSheet;
            //Excel.Range oRng;
            object missingType = Type.Missing;

            this.saveFileDialog1.FileName = Application.StartupPath + "\\" + comboBox_TableName.Text;
            this.saveFileDialog1.DefaultExt = "xls";
            this.saveFileDialog1.Filter = "Excel files (*.xls)|*.xls";
            this.saveFileDialog1.InitialDirectory = "{Desktop}";
            //DialogResult result = saveFileDialog1.ShowDialog();
            //if (result == DialogResult.OK)
            {
                try
                {
                    //Start Excel and get Application object.
                    oXL = new Excel.Application();
                    oXL.Visible = false;

                    //Get a new workbook.
                    oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
                    //oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
                    oSheet = (Excel._Worksheet)oWB.ActiveSheet;
                    //oSheet = oWB.Worksheets.get_Item(1) as Excel.Worksheet;
                    //oSheet = (Excel.Worksheet)oWB.Worksheets.Item[2] as Excel._Worksheet;

                    //oWB.Worksheets.Item[1] as Excel._Worksheet;

                    //Add table headers going cell by cell.
                    int k = 0;
                    string[] colHeader = new string[grid.ColumnCount];
                    for (int i = 0; i < grid.Columns.Count; i++)
                    {
                        oSheet.Cells[1, i + 1] = grid.Columns[i].HeaderText;

                        k = i + 65;
                        colHeader[i] = Convert.ToString((char)k);
                    }
                    //Format A1:D1 as bold, vertical alignment = center.
                    oSheet.get_Range("A1", colHeader[colHeader.Length - 1] + "1").Font.Bold = true;
                    oSheet.get_Range("A1", colHeader[colHeader.Length - 1] + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;

                    // Create an array to multiple values at once.
                    object[,] saNames = new object[grid.RowCount, grid.ColumnCount];

                    string tp;
                    for (int i = 0; i < grid.RowCount; i++)
                    {
                        for (int j = 0; j < grid.ColumnCount; j++)
                        {
                            tp = grid.Rows[i].Cells[j].ValueType.Name;
                            if (tp == "String") //2000-01-01 형태의 날짜 필터하기 위함(숫자로 변환 방지)
                                saNames[i, j] = "'" + grid.Rows[i].Cells[j].Value.ToString();
                            else
                                saNames[i, j] = grid.Rows[i].Cells[j].Value;
                        }
                    }

                    //Fill A2:B6 with an array of values (First and Last Names).
                    //oSheet.get_Range("A2", "B6").Value2 = saNames;
                    oSheet.get_Range(colHeader[0] + "2", colHeader[colHeader.Length - 1] + (grid.RowCount + 1)).Value2 = saNames;

                    oXL.Visible = false;
                    oXL.UserControl = false;
                    oWB.SaveAs(saveFileDialog1.FileName,
                    Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
                    missingType, missingType, missingType, missingType,
                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                    missingType, missingType, missingType, missingType, missingType);
                    oWB.Close(false, missingType, missingType);
                    //Cursor.Current = Cursors.Default;
                    //MessageBox.Show("Save Success!!!");
                    AutoClosingMessageBox.Show("Save Success", "알림", 100);
                }
                catch (Exception theException)
                {
                    String errorMessage;
                    errorMessage = "Error: ";
                    errorMessage = String.Concat(errorMessage, theException.Message);
                    errorMessage = String.Concat(errorMessage, " Line: ");
                    errorMessage = String.Concat(errorMessage, theException.Source);

                    MessageBox.Show(errorMessage, "Error");
                }
            }

        }
        private void button_ExcelSave_Click(object sender, EventArgs e)
        {
            GridViewExcel(this.dataGridView_TableSetting);
            button_ExcelKill_Click(null, null);
        }
        public void ReadExcelData(string path)
        { // path는 Excel파일의 전체 경로입니다.
          // 예. D:\test\test.xslx
            Excel.Application excelApp = null;
            Excel.Workbook wb = null;
            Excel.Worksheet ws = null;
            try
            {
                excelApp = new Excel.Application();
                wb = excelApp.Workbooks.Open(path);
                // path 대신 문자열도 가능합니다
                // 예. Open(@"D:\test\test.xslx");
                ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;
                // 첫번째 Worksheet를 선택합니다.
                Excel.Range rng = ws.UsedRange;   // '여기'
                                                  // 현재 Worksheet에서 사용된 셀 전체를 선택합니다.
                object[,] data = rng.Value;
                // 열들에 들어있는 Data를 배열 (One-based array)로 받아옵니다.
                for (int r = 1; r < data.GetLength(0); r++)
                {
                    for (int c = 1; c <= data.GetLength(1); c++)
                    {
                        if (data[r, c] == null)
                        {
                            continue;
                        }
                        //dataGridView_TableSetting.SelectedRows(r - 1).Cells(c - 1).Value = data[r + 1, c];


                        // Data 빼오기
                        // data[r, c] 는 excel의 (r, c) 셀 입니다.
                        // data.GetLength(0)은 엑셀에서 사용되는 행의 수를 가져오는 것이고,
                        // data.GetLength(1)은 엑셀에서 사용되는 열의 수를 가져오는 것입니다.
                        // GetLength와 [ r, c] 의 순서를 바꿔서 사용할 수 있습니다.
                    }
                    dataGridView_TableSetting.Rows[r - 1].Cells[1].Value = data[r + 1, 2];
                }
                wb.Close(true);
                excelApp.Quit();
            }
            catch (Exception ex)
            {
                ReleaseExcelObject(ws);
                ReleaseExcelObject(wb);
                ReleaseExcelObject(excelApp);
                button_ExcelKill_Click(null, null);
                return;
                throw ex;
            }
            finally
            {
                ReleaseExcelObject(ws);
                ReleaseExcelObject(wb);
                ReleaseExcelObject(excelApp);
                button_ExcelKill_Click(null, null);
            }
        }
        private void ReleaseExcelObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

        private void button_ExcelLoad_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "\\" + comboBox_TableName.Text + ".xls";
            ReadExcelData(path);
        }

        private void button_ExcelKill_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            foreach (System.Diagnostics.Process p in process)
            {
                if (!string.IsNullOrEmpty(p.ProcessName))
                {
                    try
                    {
                        p.Kill();
                    }
                    catch { }
                }
            }
        }
        private Thread[] rTh = new Thread[2];
        // Thread로 수행할 작업
        private void ExcellTableAllSave()
        {
            for (int i = 0; i < comboBox_TableName.Items.Count; i++)
            {
                CheckForIllegalCrossThreadCalls = false;
                comboBox_TableName.SelectedIndex = i;
                Thread.Sleep(1000);
                button_ExcelSave_Click(null, null);
            }
            rTh[0].Abort(); //쓰레드 강제 종료
            Console.WriteLine("Thread 종료~");
        }
        private void button_AllExcelSave_Click(object sender, EventArgs e)
        {
            //Thread 객체 생성. 생성시 이 Thread가 실행할 메소드를 지정해 준다. 
            //여기서는 Count라는 메소드를 rTh라는 쓰레드가 실행하게 될 것이다.

            rTh[0] = new Thread(ExcellTableAllSave);
            rTh[0].Start();
        }

        private void button_AllExcelLoad_Click(object sender, EventArgs e)
        {
            //Thread 객체 생성. 생성시 이 Thread가 실행할 메소드를 지정해 준다. 
            //여기서는 Count라는 메소드를 rTh라는 쓰레드가 실행하게 될 것이다.

            rTh[1] = new Thread(ExcellTableAllLoad);
            rTh[1].Start();
        }
        private void ExcellTableAllLoad()
        {
            for (int i = 0; i < comboBox_TableName.Items.Count; i++)
            {
                CheckForIllegalCrossThreadCalls = false;
                comboBox_TableName.SelectedIndex = i;
                Thread.Sleep(1000);
                button_ExcelLoad_Click(null, null);
                Thread.Sleep(1000);
                button_FileSave_Click(null, null);
                Thread.Sleep(2000);
            }
            rTh[1].Abort(); //쓰레드 강제 종료
            Console.WriteLine("Thread 종료~");
        }
        private void button_TableAttribute_Default_Click(object sender, EventArgs e)
        {
            string targetStr = dataGridView_TableSetting.Rows[0].Cells[0].Value.ToString();
            string text = targetStr;
            var match = Regex.Match(text, "-?\\d+");

            ///정수형 변환
            // int rstInt = int.Parse(tempStr);

            //_body = Regex.Replace(dataGridView_TableSetting.Rows[0].Cells[0].Value.ToString(), @"[^0-9]", "");

            numericUpDown_TableLength.Value = dataGridView_TableSetting.Rows.Count;
            numericUpDown_TableRef.Value = Convert.ToDecimal(match.Value);


        }

        private void button_Down_Click(object sender, EventArgs e)
        {
            object[] temp = new object[dataGridView_TableSetting.RowCount];
            for (int i = 0; i < dataGridView_TableSetting.RowCount; i++)
            {
                temp[i] = dataGridView_TableSetting[1, i].Value;
            }
            dataGridView_TableSetting[1, 0].Value = 0;
            dataGridView_TableSetting[1, 1].Value = 0;
            for (int i = 0; i < dataGridView_TableSetting.RowCount - 2; i++)
            {
                dataGridView_TableSetting[1, i + 2].Value = temp[i];
            }
        }

        private void Hidden_Load(object sender, EventArgs e)
        {
            ATT_TableLayoutSetting();
        }
        private void numericUpDown_User_KeyDown(object sender, KeyEventArgs e)
        {
            NumericUpDown numeric = (NumericUpDown)sender;
            const byte TableGetMaxLength = 9;
            byte tmp_H = 0;
            byte tmp_L = 0;
            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;
            if (e.KeyCode == Keys.Enter)
            {

                byte[] temp_buf = new byte[TableGetMaxLength];

                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = Convert.ToByte(((TableGetMaxLength - 3) & 0xFF00) >> 8);
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = Convert.ToByte((TableGetMaxLength - 3) & 0x00FF);
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = TableGetMaxLength - 2;

                if (numeric.Name == "numericUpDown_Temp_Threshold"
                    || numeric.Name == "numericUpDown_Temp_Threshold_Default"
                    || numeric.Name == "numericUpDown_Temperature_Offset"
                    || numeric.Name.Contains("TableOffset") == true
                    || numeric.Name.Contains("Default") == true)
                {
                    Int16 UserData = Convert.ToInt16(numeric.Value);
                    //tmp_H = Convert.ToByte((UserData & 0xFF00) >> 8);
                    tmp_L = Convert.ToByte((UserData & 0x00FF));
                    //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = tmp_H;
                    temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = tmp_L;
                }
                else
                {
                    Int16 UserData = Convert.ToInt16(numeric.Value * 10);
                    tmp_H = Convert.ToByte((UserData & 0xFF00) >> 8);
                    tmp_L = Convert.ToByte((UserData & 0x00FF));
                    temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = tmp_H;
                    temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 1] = tmp_L;
                }

                switch (numeric.Name)
                {
                    case "numericUpDown_Temp_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_Temp_High_Threshold;
                        break;
                    case "numericUpDown_Temp_Threshold_Default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_Temp_High_Threshold_Default;
                        break;
                    case "numericUpDown_Temperature_Offset":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_Temperature_Offset;
                        break;

                    case "numericUpDown_DL1_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DL1_USER;
                        break;
                    case "numericUpDown_DL2_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DL2_USER;
                        break;
                    case "numericUpDown_DL3_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DL3_USER;
                        break;
                    case "numericUpDown_DL4_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DL4_USER;
                        break;

                    case "numericUpDown_UL1_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL1_USER;

                        break;
                    case "numericUpDown_UL2_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL2_USER;
                        break;
                    case "numericUpDown_UL3_User":

                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL3_USER;
                        break;
                    case "numericUpDown_UL4_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL4_USER;
                        break;
                    case "numericUpDown_TEMP_User":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_TEMP_USER;
                        break;
                    case "numericUpDown_DLI_Level_High_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_Level_High_Threshold;
                        break;
                    case "numericUpDown_DLI_Level_Low_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_Level_Low_Threshold;
                        break;
                    case "numericUpDown_DLI_Level_High_Low_Threshold_default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_Level_High_Low_Threshold_default;
                        break;
                    case "numericUpDown_DLI_AGC_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_AGC_Threshold;
                        break;
                    case "numericUpDown_DLI_AGC_Threshold_Default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_AGC_Threshold_Default;
                        break;
                    case "numericUpDown_DLI_Shutdown_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_Shutdown_Threshold;
                        break;
                    case "numericUpDown_DLI_Shutdown_Threshold_Default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_Shutdown_Threshold_Default;
                        break;
                    case "numericUpDown_ULO_Level_High_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_ULO_Level_High_Threshold;
                        break;
                    case "numericUpDown_DLI_Level_High_Threshold_default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DLI_Level_High_Low_Threshold_default;
                        break;
                    case "numericUpDown_ULO_ALC_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_ULO_ALC_Threshold;
                        break;
                    case "numericUpDown_ULO_ALC_Threshold_Default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_ULO_ALC_Threshold_Default;
                        break;
                    case "numericUpDown_ULO_Shutdown_Threshold":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_ULO_Shutdown_Threshold;
                        break;
                    case "numericUpDown_ULO_Shutdown_Threshold_Default":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_ULO_Shutdown_Threshold_Default;
                        break;
                    case "numericUpDown_MASK":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_Alarm_Mask;
                        break;
                    case "numericUpDown_ALC1":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                            = (byte)Bluecell_BootProtocol.DATATYPE.BLuecell_ATT_ALC1;
                        break;
                    case "numericUpDown_ALC2":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.BLuecell_ATT_ALC2;
                        break;
                    case "numericUpDown_ALC3":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.BLuecell_ATT_ALC3;
                        break;
                    case "numericUpDown_ALC4":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                           = (byte)Bluecell_BootProtocol.DATATYPE.BLuecell_ATT_ALC4;
                        break;
                    case "numericUpDown_DL_TableOffset":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                          = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_DL_Det_ALL_Offset;
                        break;
                    case "numericUpDown_UL1_TableOffset":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                          = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL_Det_Path1_Offset;
                        break;
                    case "numericUpDown_UL2_TableOffset":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                          = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL_Det_Path2_Offset;
                        break;
                    case "numericUpDown_UL3_TableOffset":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                          = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL_Det_Path3_Offset;
                        break;
                    case "numericUpDown_UL4_TableOffset":
                        temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]
                          = (byte)Bluecell_BootProtocol.DATATYPE.Bluecell_UL_Det_Path4_Offset;
                        break;


                    default: break;
                }
                Crc16 crc = new Crc16();
                UInt16 CRCRET = crc.CRC16_Generate(temp_buf, Convert.ToByte((TableGetMaxLength - 3) & 0x00FF));
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 2] = Convert.ToByte((CRCRET & 0xFF00) >> 8);
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 3] = Convert.ToByte(CRCRET & 0x00FF);

                ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, temp_buf.Length);
                ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;

                //to do
            }
            else if (e.KeyCode == Keys.Escape)
            {
                ((JdasMbic)(this.Owner)).Activi_Change__Setting(null, null);
            }
            else
            {
                return;
            }
        }
        public void TableCurrentOutputSetting()
        {
            ComboBox comboBox = (ComboBox)comboBox_TableName;
            CheckForIllegalCrossThreadCalls = false;
            string tempstr = comboBox_TableName.Text;
            //this.Invoke(new StringSend(String_Text_Set), tempstr, );
            switch (tempstr)
            {
                case "DET_DL1":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_DL1.Text);
                    break;
                case "DET_DL2":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_DL2.Text);
                    break;
                case "DET_DL3":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_DL3.Text);
                    break;
                case "DET_DL4":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_DL4.Text);
                    break;
                case "DET_UL1":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_UL1.Text);
                    break;
                case "DET_UL2":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_UL2.Text);
                    break;
                case "DET_UL3":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_UL3.Text);
                    break;
                case "DET_UL4":
                    this.Invoke(new StringSend(Numeric_Text_Set), numericUpDown_CurrentOutput, main.textBox_DET_UL4.Text);
                    break;

                default:
                    //MessageBox.Show("존재하지 않는 ComboBox 입니다.\r\n 확인해주세요.");
                    break;
            }
        }
        private void radioButton_ATT_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radioButton = (RadioButton)sender;

            switch (radioButton.Name)
            {
                case "ATT1":
                    label_Table_ATTDL.Text = "ATT_DL1";
                    label_Table_ATTUL.Text = "ATT_UL1";
                    break;
                case "ATT2":
                    label_Table_ATTDL.Text = "ATT_DL2";
                    label_Table_ATTUL.Text = "ATT_UL2";
                    break;
                case "ATT3":
                    label_Table_ATTDL.Text = "ATT_DL3";
                    label_Table_ATTUL.Text = "ATT_UL3";
                    break;
                case "ATT4":
                    label_Table_ATTDL.Text = "ATT_DL4";
                    label_Table_ATTUL.Text = "ATT_UL4";
                    break;

            }
        }

        private void button_ManufactureSet_Click(object sender, EventArgs e)
        {
            byte[] temp_buf = new byte[10];
            Button button = (Button)sender;
            DATATYPE datatype;
            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;
            char[] tempchardata;
            string s3 = DateTime.Now.ToString("yyMMdd");

            tempchardata = s3.ToCharArray();
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = ((JdasMbic)(this.Owner)).DataToConvertHex(s3)[0];
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 1] = ((JdasMbic)(this.Owner)).DataToConvertHex(s3)[1];
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 2] = ((JdasMbic)(this.Owner)).DataToConvertHex(s3)[2];
            datatype = DATATYPE.Bluecell_ManufactureDateSet;

            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type] = Convert.ToByte(datatype);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = ((7 & 0xFF00) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = (7 & 0x00FF);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = 5;
            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = 0;
            UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 3] = Convert.ToByte((CRCRET & 0xFF00) >> 8);//CRC
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 4] = Convert.ToByte(CRCRET & 0x00FF);//CRC
            ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, temp_buf.Length);
        }
        //Serial Number : BL-J37C00-20050004  Example 
        private void button_SerialNumverSet_Click(object sender, EventArgs e)
        {
            byte[] temp_buf = new byte[27];
            int i = 0;
            Button button = (Button)sender;
            DATATYPE datatype;
            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;
            char[] data = textBox_SerialNumber.Text.ToCharArray();

            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = textBox_SerialNumber.Text.Split();
            datatype = DATATYPE.Bluecell_SerialNumberSet;
            for (i = 0; i < data.Length; i++)
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i] = (Byte)data[i];

            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + (i++)] = (Byte)0x20;

            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type] = Convert.ToByte(datatype);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = ((24 & 0xFF00) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = (24 & 0x00FF);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = 5;
            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = 0;
            UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i++] = Convert.ToByte((CRCRET & 0xFF00) >> 8);//CRC
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i++] = Convert.ToByte(CRCRET & 0x00FF);//CRC
            ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, temp_buf.Length);
        }

        private void button_PCBVersionSet_Click(object sender, EventArgs e)
        {
            byte[] temp_buf = new byte[9];
            int i = 0;
            Button button = (Button)sender;
            DATATYPE datatype;
            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;
            string[] data = textBox_PcbVersion.Text.Split('.');

            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = textBox_SerialNumber.Text.Split();
            datatype = DATATYPE.Bluecell_PCBVersionSet;
            for (i = 0; i < data.Length; i++)
                temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i] = Convert.ToByte(data[i]);

            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type] = Convert.ToByte(datatype);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = ((6 & 0xFF00) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = (6 & 0x00FF);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = 5;
            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = 0;
            UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i++] = Convert.ToByte((CRCRET & 0xFF00) >> 8);//CRC
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i++] = Convert.ToByte(CRCRET & 0x00FF);//CRC
            ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, temp_buf.Length);
        }


        
        private void button_ZeroWrite_Click(object sender, EventArgs e)
        {
            byte[] temp_buf = new byte[7];
            int i = 0;
            Button button = (Button)sender;
            DATATYPE datatype;
            ((JdasMbic)(this.Owner)).ReqTimer_Cnt = 0;

            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = textBox_SerialNumber.Text.Split();
            datatype = DATATYPE.Bluecell_StatusSave;

            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header] = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type] = Convert.ToByte(datatype);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_H] = ((4 & 0xFF00) >> 8);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L] = (4 & 0x00FF);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = 5;
            //temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data] = 0;
            UInt16 CRCRET = ((JdasMbic)(this.Owner)).crc.CRC16_Generate(temp_buf, temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length_L]);
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i++] = Convert.ToByte((CRCRET & 0xFF00) >> 8);//CRC
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + i++] = Convert.ToByte(CRCRET & 0x00FF);//CRC
            ((JdasMbic)(this.Owner)).serial.Serial_DataSend(temp_buf, temp_buf.Length);
        }
    }
}
