using HslCommunication;
using HslCommunication.ModBus;
using Microsoft.Win32;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
//using Excel = Microsoft.Office.Interop.Excel;
using ZXing;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Threading;
using System.Reflection.Emit;
using System.Net.Sockets;
using Timer = System.Windows.Forms.Timer;
using System.Net;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Org.BouncyCastle.Utilities.Net;

namespace C_Windows_1
{
    public partial class Form1 : Form
    {
        public int stage = 10;
        private int write = 0;
        private string timestamp;
        private string fullpressure;
        private string balanpressure;
        public static Form1 f1;
        private double delaytime;
        private float X, Y;

        private string DLeakPressure = "0";
        private string DLeak = "0";
        public OperateResult operateResult21;
        public OperateResult operateResult22;
        public OperateResult<bool> operateResult23;
        public ModbusRtu CH1 = new ModbusRtu();
        // 创建Modbus TCP客户端对象
        //public ModbusTcpNet modbusClient;
        public ModbusRtuOverTcp modbusClient /*= new ModbusRtuOverTcp("192.168.1.174", 9999)*/;
        //产测计数
       // public static Form1 f1;
        public int ChanSum;
        public int ChanPass;

        public static UInt16[] ReadData = new UInt16[3000];
        string codeport;

        private UdpClient udpClient;
        private const int Port = 9999; // 监听端口号
        private const int ReceiveTimeout = 3000; // 超时时间（毫秒）
        private bool isListening = false; // 监听标志位,控制是否继续监听
        private Timer timeoutTimer; // 定时器用于控制超时

        public int connectflag = 0;
        public Form1()
        {
            f1 = this;
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            timeoutTimer = new Timer();
            timeoutTimer.Interval = ReceiveTimeout; // 设置超时时间
            timeoutTimer.Tick += TimeoutTimer_Tick;
        }

        private void TimeoutTimer_Tick(object sender, EventArgs e)
        {
            // 停止监听
            isListening = false;

            timeoutTimer.Stop();

        }

        //窗口自适应分辨率

        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
                if (con.Controls.Count > 0)
                    setTag(con);
            }
        }

        private void setControls(float newx, float newy, Control cons)
        {
            try
            {
                foreach (Control con in cons.Controls)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
                    float a = Convert.ToSingle(mytag[0]) * newx;
                    con.Width = (int)a;
                    a = Convert.ToSingle(mytag[1]) * newy;
                    con.Height = (int)(a);
                    a = Convert.ToSingle(mytag[2]) * newx;
                    con.Left = (int)(a);
                    a = Convert.ToSingle(mytag[3]) * newy;
                    con.Top = (int)(a);
                    Single currentSize = Convert.ToSingle(mytag[4]) * newy;
                    con.Font = new System.Drawing.Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        //窗口改变尺寸事件
        private void Form1_Resize(object sender, EventArgs e)
        {
            // throw new Exception("The method or operation is not implemented.");
            float newx = (this.Width) / X;
            // float newy = (this.Height - this.statusStrip1.Height) / (Y - y);
            float newy = this.Height / Y;
            setControls(newx, newy, this);
            //      this.Text = this.Width.ToString() + " " + this.Height.ToString();
        }

        public enum yiqi
        {
            start,//启动 0
            rst,//复位 1
            prepare,//准备 2
            test,//测试 3
            finish,//完成（导出数据）4
            writedate,//写入数据 5
            standby,//待机 6

        };


        private void CodePort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(50);
                if (!CodePort1.IsOpen) return;
                int len = CodePort1.BytesToRead;//获取可以读取的字节数
                if (MachineStatus.Text == "测试中")
                {
                    CodePort1.DiscardInBuffer();
                }
                else if (len > 1)
                {
                    byte[] buff = new byte[len];//创建缓存数据数组
                    CodePort1.Read(buff, 0, len);//把数据读取到buff数组
                    Invoke((new System.Action(() => //接收计数
                    {
                        string code = Encoding.Default.GetString(buff);
                        if (!code.Contains("ERROR"))
                        {
                            Code.Text = string.Empty;
                            CodeJudge(code, 1);
                        }


                        //CodePort1.DiscardInBuffer();
                    })));
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Code:" + ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void CodeJudge(string code, int ch)
        {
            if (ch == 1)
            {
                Code.Text = code.Replace("/r", "").Replace("/n", "").Replace("/r/n", "").Replace("\r", "").Replace("\n", "").Replace("\r\n", "");
            }
        }


                //UInt16转float
       public static float TwoUInt16ToFloat(UInt16 high, UInt16 low)
        {

            Int32 sum = (high << 16) + (low & 0XFFFF);
            byte[] bs = BitConverter.GetBytes(sum);
            float f1 = BitConverter.ToSingle(BitConverter.GetBytes(sum), 0);
            return f1;

        }


        //Int16转float
        public static float TwoInt16ToFloat(Int16 high, Int16 low)
        {

            Int32 sum = (high << 16) + (low & 0XFFFF);
            byte[] bs = BitConverter.GetBytes(sum);
            float f2 = BitConverter.ToSingle(BitConverter.GetBytes(sum), 0);
            return f2;

        }




        public static float ByteToFloat(byte[] bytes)
        {
            if (bytes.Length != 4)
                return float.MinValue;
            return BitConverter.ToSingle(bytes, 0);
        }
        public int workstation;

        public void Booltomath(int sta, UInt16[] shangweiji)
        {
            try
            {
                OperateResult<bool> reslutget;
                reslutget = modbusClient.ReadBool(Convert.ToString(sta));
                if (reslutget.IsSuccess == true)
                {
                    if (reslutget.Content == true)
                    {
                        shangweiji[sta] = 1;
                    }
                    else
                    {
                        shangweiji[sta] = 0;
                    }
                }
                //return shangweiji[sta];
            }
            catch (Exception)
            {

                throw;
            }

        }


        //sta 起始寄存器
        //number    读取数量
        //shangweiji 存入数组  
        /// <summary>
        /// //////////////////
        /// </summary>
        /// <param name="sta"></起始寄存器>
        /// <param name="number"></读取数量>
        /// <param name="shangweiji"></存入数组>
        public OperateResult<byte[]> Modbusread(int sta, int number, UInt16[] shangweiji)
        {
            try
            {
                int start = number;
                OperateResult<byte[]> reslutget;
                reslutget = modbusClient.Read(Convert.ToString(sta), Convert.ToUInt16(number));
                int i, j;
                i = 0;
                j = 0;
                int aaa2 = sta;
                if (reslutget.IsSuccess == true)
                    for (; sta < aaa2 + number; sta++)
                    {


                        {
                            shangweiji[sta] = (ushort)((reslutget.Content[2 * i] << 8) + reslutget.Content[2 * i + 1]);
                        }


                        i++;
                    }

                return reslutget;
            }
            catch (Exception)
            {

                throw;
            }

        }



        int progressvalue = 0;

        public void ModbusRtuint(ModbusRtu X, byte station, string COM, int Bund, int numberbit, StopBits stopbit, Parity parity)
        {
            try
            {
                X.Close();
                X.Station = station;
                X.SerialPortInni(COM, Bund, numberbit, stopbit, parity);
                //X.ReceiveTimeout = 300;
                X.Open();
                
               
            }
            catch (Exception)
            {
                label6.Text = "未连接";
                //throw;
            }

        }

        float grovalueone, grovalue;
        public void machine2()//主要负责测试数据读取，写入
        {
            //Invoke((new System.Action(() =>

            switch (workstation)
            {
                case (int)yiqi.start:

                    operateResult22 = modbusClient.Write("0", true);
                    //MachineStatus.Text = "开始测试";
                    //Console.WriteLine("当前是启动状态");
                    //if (operateResult22.IsSuccess)
                    //{
                    //    operateResult22 = CH1.Write("85", false);
                    workstation = (int)yiqi.prepare;
                    //}
                    break;
                //return workstation;



                case (int)yiqi.rst:
                    //byte[] data2 = new byte[] { 0xff, 0x00 };
                    operateResult21 = modbusClient.Write("1", true);
                    //Console.WriteLine("当前是复位状态");
                    ////点击复位进度条置为0
                    progressBar2.Value = 0;
                    //MachineStatus.Text = "复位";
                    //LeakPressure.Text = "";
                    //Leak.Text = "";
                    //label2.Text = "";
                    //Tlight.Text = "";
                    if (operateResult21.IsSuccess)
                    {
                        workstation = (int)yiqi.standby;
                    }


                    break;


                case (int)yiqi.prepare://读取检测时间，充气，平衡检测 //扫码枪处理 上传
                    ReadData[1041] = 0;
                    operateResult21 = Modbusread(1006, 4, ReadData);
                    Tlight.Text = "";
                    if (operateResult21.IsSuccess == true)
                    {
                        int aaa;
                        timerbar.Start();
                        // grovalue = 100 / ((ReadData[1006] / 10) + (ReadData[1007] / 10) + (ReadData[1008] / 10) + (ReadData[1009] / 10)) ;
                        //grovalueone = (float)(grovalue * 0.0003);
                        //aaa = ReadData[1006] + ReadData[1007] + ReadData[1008] + ReadData[1009];
                        progressBar2.Value = 0;
                        //progressBar2.Maximum = aaa;
                        Booltomath(2, ReadData);
                        
                            if(ReadData[2]!=0)
                            {
                                workstation = (int)yiqi.test;
                            }
                             else
                            {
                                workstation = (int)yiqi.standby;
                            }
                        
                       
                    }

                    break;



                case (int)yiqi.test://读取检测数据以及判断仪器是否结束
                    //operateResult21=Modbusread(170, 23, ReadData);
                    Booltomath(2, ReadData);
                    progressBar2.Value = progressvalue;
                    progressvalue += 2;
                    Modbusread(1013, 16, ReadData);//各项参数
                    Modbusread(1034, 26, ReadData);
                    //Modbusread(25, 24, ReadData);
                    //test(ReadData);
                    //int ba = progressBar2.Value + 2;
                    if (progressvalue >= progressBar2.Maximum)
                        progressvalue = progressBar2.Maximum;
                    progressBar2.Value = progressvalue;

                    //if (!(grovalue > 99.8))
                    //{
                    //    grovalue += grovalueone;

                    //    progressBar2.Value = (int)grovalue;
                    //}
                    //else
                    //{
                    //    progressBar2.Maximum = (int)grovalue;
                    //}


                    if (ReadData[2] == 0 && (ReadData[1041] == 1 || ReadData[1041] == 2))//当仪器状态位不为0且有结果时
                    {
                        workstation = (int)yiqi.finish;
                        //return workstation;
                    }
                    if (ReadData[2] == 0)
                    {
                        System.Threading.Thread.Sleep(300);
                        Modbusread(1041, 1, ReadData);
                        if (ReadData[1041] == 1 || ReadData[1041] == 2)
                        {
                            workstation = (int)yiqi.finish;
                        }
                        else
                        {
                            progressBar2.Value = 0;
                            workstation = (int)yiqi.standby;
                        }
                    }

                    break;



                case (int)yiqi.standby://读取仪器是否启动
                    Booltomath(2, ReadData);
                    Modbusread(1041, 1, ReadData);
                    MachineStatus.Text = "待机中";
                    if (ReadData[2] != 0 && ReadData[1041] == 0)
                    {
                        workstation = (int)yiqi.prepare;
                    }



                    break;



                case (int)yiqi.finish:
                    Modbusread(1034, 26, ReadData);
                    progressBar2.Value = progressBar2.Maximum;
                    //timerbar.Stop();     
                    DataGridView1.Invoke(new System.Action(Display));
                    CreateFile();
                    //Passzong.Text = ChanPass.ToString();
                    //Sunzong.Text = ChanSum.ToString();
                    //string path = System.Environment.CurrentDirectory + "\\Config\\Config.ini";
                    //ConfigINI config = new ConfigINI(path);
                    //config.IniWriteValue("Config", "Passzong", Passzong.Text);
                    //config.IniWriteValue("Config", "Sunzong", Sunzong.Text);
                    Code.Clear();
                    progressvalue = 0;
                    workstation = (int)yiqi.standby;


                    // return workstation;
                    break;

                default:
                    break;
                    //return 0;break;


            }
            //}
            //        )));
        }

        public void MachineDisplay2()//UI层，吧相应的文本赋值.17.58
        {
            switch (workstation)
            {
                case (int)yiqi.start:

                    MachineStatus.Text = "开始测试";

                    break;
                case (int)yiqi.rst:
                    MachineStatus.Text = "复位";
                    LeakPressure.Text = "";
                    Leak.Text = "";
                    label2.Text = "";
                    Tlight.Text = "";

                    break;
                case (int)yiqi.standby://把状态文本改成文本
                    MachineStatus.Text = "待机中";

                    //  Tlight.Text = "";
                    break;

                case (int)yiqi.prepare://把状态文本改成文本
                    Tlight.Text = "";
                    break;

                case (int)yiqi.test:
                    MachineStatus.Text = "测试中";

                    //判断单位
                    switch (ReadData[41])//
                    {
                        case 1:
                            PressureUnit.Text = "KPa";

                            break;
                        case 2:

                            PressureUnit.Text = "bar";


                            break;
                        case 0:
                            PressureUnit.Text = "Pa";

                            break;
                        case 3:

                            PressureUnit.Text = "atm";


                            break;
                        case 4:

                            PressureUnit.Text = "psi";


                            break;
                        case 5:

                            PressureUnit.Text = "mmHg";



                            break;
                    }

                    switch (ReadData[40])
                    {
                        case 0:

                            LeakUnit.Text = "Pa";
                            break;

                        case 1:

                            LeakUnit.Text = "Kpa";
                            break;

                        case 2:


                            LeakUnit.Text = "mbar";
                            break;

                        case 3:

                            LeakUnit.Text = "atm";
                            break;

                        case 4:

                            LeakUnit.Text = "sccm";
                            break;

                        case 5:

                            LeakUnit.Text = "Pa·m3/s";

                            break;

                        case 6:

                            LeakUnit.Text = "Pa/s";
                            break;
                    }
                    if (ReadData[9] == 2)
                    {

                        Tlight.Text = "NG";
                        Tlight.ForeColor = Color.Red;
                    }
                    if (ReadData[9] == 1)
                    {
                        Tlight.Text = "OK";
                        Tlight.ForeColor = Color.Green;
                    }
                    //CH1文本框读取的压力和泄漏量
                    LeakPressure.Text = TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString();
                    Leak.Text = TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f1");

                    break;

                case (int)yiqi.finish:
                    progressBar2.Value = progressBar2.Maximum;
                    if (ReadData[9] == 2)
                    {
                        Tlight.Enabled = true;
                        Tlight.Visible = true;
                        Tlight.Text = "NG";
                        Tlight.ForeColor = Color.Red;
                    }
                    // if(ReadData[60] == 1 && ReadData[61] == 1)
                    //{
                    //    Tlight.Text = "OK";
                    //    Tlight.ForeColor = Color.Green;
                    //    Tlight2.Text = "OK";
                    //    Tlight2.ForeColor = Color.Green;
                    //}
                    if (ReadData[9] == 1)
                    {
                        Tlight.Text = "OK";
                        Tlight.ForeColor = Color.Green;
                    }
                    LeakPressure.Text = TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString();
                    Leak.Text = TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f1");
                    MachineStatus.Text = "测试结束";


                    break;
                default: break;

            }
        }

        public void machine()//主要负责测试数据读取，写入
        {
            //Invoke((new System.Action(() =>
            //{
                
                switch (workstation)
            {
                case (int)yiqi.start:
                    
                    operateResult22 = CH1.Write("540", true);
                    //MachineStatus.Text = "开始测试";
                    ////Console.WriteLine("当前是启动状态");
                    if (operateResult22.IsSuccess)
                    {
                    //    operateResult22 = CH1.Write("85", false);
                         workstation = (int)yiqi.prepare;
                    }
                    break;
                    //return workstation;



                case (int)yiqi.rst:
                   
                    operateResult21 = CH1.Write("86", true);
                    
                    //点击复位进度条置为0
                    progressBar2.Value = 0;                  
                    if (operateResult21.IsSuccess)
                    {
                         workstation = (int)yiqi.standby;
                    }
                    

                    break;
                    //return workstation;


                case (int)yiqi.prepare://读取检测时间，充气，平衡检测 //扫码枪处理 上传
                    ReadData[9] = 0;
                    operateResult21 = Modbusread(25, 6, ReadData);
                    Tlight.Text = "";
                    if (operateResult21.IsSuccess == true)
                    {
                        int aaa;
                        aaa = ReadData[25] + ReadData[26] + ReadData[27] + ReadData[28] + ReadData[30];
                        progressBar2.Value = 0;
                        progressBar2.Maximum = aaa;
                        //进度条开始，满值是a，一秒进10；
                        //
                         workstation = (int)yiqi.test;
                    }
                    
                    break;
                    //return workstation;



                case (int)yiqi.test://读取检测数据以及判断仪器是否结束
                    //operateResult21=Modbusread(170, 23, ReadData);
                    Modbusread(8, 2, ReadData);
                    Modbusread(16, 4, ReadData);
                    Modbusread(25, 24, ReadData);
                    Booltomath(8, ReadData);
                    Booltomath(9, ReadData);                    
                    int ba = progressBar2.Value + 2;
                    if (ba >= progressBar2.Maximum)
                        ba = progressBar2.Maximum;
                    progressBar2.Value = ba;
                    //MachineStatus.Text = "测试中";

                    ////判断单位
                    //switch (ReadData[41])
                    //{
                    //    case 1:
                    //        PressureUnit.Text = "KPa";

                    //        break;
                    //    case 2:

                    //        PressureUnit.Text = "bar";


                    //        break;
                    //    case 0:
                    //        PressureUnit.Text = "Pa";

                    //        break;
                    //    case 3:

                    //        PressureUnit.Text = "atm";


                    //        break;
                    //    case 4:

                    //        PressureUnit.Text = "psi";


                    //        break;
                    //    case 5:

                    //        PressureUnit.Text = "mmHg";



                    //        break;
                    //}

                    //switch (ReadData[40])
                    //{
                    //    case 0:

                    //        LeakUnit.Text = "Pa";
                    //        break;

                    //    case 1:

                    //        LeakUnit.Text = "Kpa";
                    //        break;

                    //    case 2:


                    //        LeakUnit.Text = "mbar";
                    //        break;

                    //    case 3:

                    //        LeakUnit.Text = "atm";
                    //        break;

                    //    case 4:

                    //        LeakUnit.Text = "sccm";
                    //        break;

                    //    case 5:

                    //        LeakUnit.Text = "Pa·m3/s";

                    //        break;

                    //    case 6:

                    //        LeakUnit.Text = "Pa/s";
                    //        break;
                    //}
                    //if (ReadData[9] == 2)
                    //{
                    //    Tlight.Enabled = true;
                    //    Tlight.Visible = true;
                    //    Tlight.Text = "NG";
                    //    Tlight.ForeColor = Color.Red;
                    //}
                    //if (ReadData[9] == 1)
                    //{
                    //    Tlight.Text = "OK";
                    //    Tlight.ForeColor = Color.Green;
                    //}
                    ////CH1文本框读取的压力和泄漏量
                    //LeakPressure.Text = TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString();
                    //Leak.Text = TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f3");
                    if (ReadData[8] != 0 && (ReadData[9] == 1 || ReadData[9] == 2))//当仪器状态位不为0且有结果时
                    {
                        workstation = (int)yiqi.finish;
                       
                    }
                    if (ReadData[8] == 0)
                    {
                            System.Threading.Thread.Sleep(300);
                            Modbusread(8, 2, ReadData);
                             Booltomath(9, ReadData);
                            if (ReadData[9] == 1 || ReadData[9] == 2)
                            {
                                workstation = (int)yiqi.finish;
                            }
                            else
                            {
                                progressBar2.Value = 0;
                                workstation = (int)yiqi.standby;
                            }
                    }
                    
                    break;



                case (int)yiqi.standby://读取仪器是否启动
                    Modbusread(8, 2, ReadData);
                    Booltomath(8, ReadData);
                    Booltomath(9, ReadData);
                    //MachineStatus.Text = "待机中";
                    if (ReadData[8] != 0 && ReadData[9] == 0)
                    {
                         workstation = (int)yiqi.prepare;
                    }
                  

                    break;
                   


                case (int)yiqi.finish:
                    Modbusread(8, 2, ReadData);
                    Booltomath(8, ReadData);
                    Booltomath(9, ReadData);
                    Modbusread(16, 4, ReadData);
                    progressBar2.Value = progressBar2.Maximum;                      
                    Display();
                    CreateFile();
                    //Passzong.Text = ChanPass.ToString();
                    //Sunzong.Text = ChanSum.ToString();
                    //string path = System.Environment.CurrentDirectory + "\\Config\\Config.ini";
                    //ConfigINI config = new ConfigINI(path);
                    //config.IniWriteValue("Config", "Passzong", Passzong.Text);
                    //config.IniWriteValue("Config", "Sunzong", Sunzong.Text);
                    Code.Clear();
                    workstation = (int)yiqi.standby;


                // return workstation;
                break;

                default:
                    break;
                    //return 0;break;
            

        }
            //}
            //        )));
        }

       

        public void MachineDisplay()//UI层，吧相应的文本赋值.17.58
        {
            switch (workstation)
            {
                case (int)yiqi.start:

                    //MachineStatus.Text = "开始测试";

                    break;
                case (int)yiqi.rst:
                    MachineStatus.Text = "复位";
                    LeakPressure.Text = "";
                    PressureUnit.Text = "";
                    LeakUnit.Text = "";
                    Leak.Text = "";
                    label2.Text = "";
                    Tlight.Text = "";

                    break;
                case (int)yiqi.standby://把状态文本改成文本
                    MachineStatus.Text = "待机中";
                    
                    //  Tlight.Text = "";
                    break;

                case (int)yiqi.prepare://把状态文本改成文本
                    Tlight.Text = "";
                    break;

                case (int)yiqi.test:
                    MachineStatus.Text = "测试中";

                    //判断单位
                    switch (ReadData[1027])//
                    {
                        case 1:
                            PressureUnit.Text = "KPa";

                            break;
                        case 2:

                            PressureUnit.Text = "bar";


                            break;
                        case 0:
                            PressureUnit.Text = "Pa";

                            break;
                        case 3:

                            PressureUnit.Text = "atm";


                            break;
                        case 4:

                            PressureUnit.Text = "psi";


                            break;
                        case 5:

                            PressureUnit.Text = "mmHg";



                            break;
                    }

                    switch (ReadData[1028])
                    {
                        case 0:

                            LeakUnit.Text = "Pa";
                            break;

                        case 1:

                            LeakUnit.Text = "Kpa";
                            break;

                        case 2:


                            LeakUnit.Text = "mbar";
                            break;

                        case 3:

                            LeakUnit.Text = "atm";
                            break;

                        case 4:

                            LeakUnit.Text = "sccm";
                            break;

                        case 5:

                            LeakUnit.Text = "Pa/s";

                            break;

                       
                    }
                    if (ReadData[1041] == 2)
                    {
                        Tlight.Enabled = true;
                        Tlight.Visible = true;
                        Tlight.Text = "NG";
                        Tlight.ForeColor = Color.Red;
                    }
                    if (ReadData[1041] == 1)
                    {
                        Tlight.Text = "OK";
                        Tlight.ForeColor = Color.Green;
                    }
                    //CH1文本框读取的压力和泄漏量
                    LeakPressure.Text = TwoUInt16ToFloat(ReadData[1049], ReadData[1048]).ToString("f3");
                    Leak.Text = TwoUInt16ToFloat(ReadData[1039], ReadData[1038]).ToString("f3");

                    break;

                case (int)yiqi.finish:
                    //progressBar2.Value = progressBar2.Maximum;
                    if (ReadData[1041] == 2)
                    {
                        
                        //ChanSum++;
                        Tlight.Text = "NG";
                        Tlight.ForeColor = Color.Red;
                    }
                   
                    if (ReadData[1041] == 1)
                    {
                        //ChanPass++;
                        //ChanSum++;
                        Tlight.Text = "OK";
                        Tlight.ForeColor = Color.Green;
                    }
                    LeakPressure.Text = TwoUInt16ToFloat(ReadData[1049], ReadData[1048]).ToString("f3");
                    Leak.Text = TwoUInt16ToFloat(ReadData[1039], ReadData[1038]).ToString("f3");



                    MachineStatus.Text = "测试结束";



                    break;
                default: break;

            }
        }


        private void ReadINI()
        {
            string path = System.Environment.CurrentDirectory + "\\Config";
            //生成目录
            //创建文件夹
            if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(path);
            }
            path = path + "\\Config.ini";

            if (File.Exists(path))
            {
                ConfigINI config = new ConfigINI(path);         
                Passzong.Text = config.IniReadValue("Config", "Passzong");
                Sunzong.Text = config.IniReadValue("Config", "Sunzong");
               
                ChanPass = Convert.ToInt32(config.IniReadValue("Config", "Passzong"));
                ChanSum = Convert.ToInt32(config.IniReadValue("Config", "Sunzong"));

            }
        }

        private void setcodeport()
        {
            try
            {

                //设置端口的参数，包括波特率等
                SerialPort1.BaudRate = 9600;
                SerialPort1.PortName = codeport;
                SerialPort1.DataBits = 8;
                SerialPort1.StopBits = System.IO.Ports.StopBits.One;
                SerialPort1.Parity = System.IO.Ports.Parity.None;
                SerialPort1.Open();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }


       

        OperateResult<byte[]> connect;

        //窗口初始化
        private void Form1_Load(object sender, EventArgs e)
        {
            
            Control.CheckForIllegalCrossThreadCalls = false;
            //窗口自适应分辨率
            //窗口自适应分辨率
            this.Resize += new EventHandler(Form1_Resize);
            X = this.Width;
            Y = this.Height;
            // y = this.statusStrip1.Height;
            setTag(this);

            //界面初始化
            label6.Text = "未连接";
            label6.ForeColor = Color.Red;

            Station.SelectedIndex = 0;
            Tlight.Text = "   ";
            MachineStatus.Text = "待机中";
            MachineStatus.ForeColor = Color.Red;
            Leak.Text = "   ";
            LeakPressure.Text = "   ";
            MESStatus.Text = "";
            //Scancode.Checked = true;
            //修改密码ToolStripMenuItem.Enabled = false;
            //串口设置ToolStripMenuItem.Enabled = false;
            //基本设置ToolStripMenuItem.Enabled = false;
            //测试参数ToolStripMenuItem.Enabled = false;
            //存储设置ToolStripMenuItem.Enabled = false;
            //Baudrate.Visible=false;
            label7.Visible=false;
            Read();
            ReadINI();
            udpClient = new UdpClient();
            udpClient.EnableBroadcast = true;
            udpClient.Client.ReceiveTimeout = ReceiveTimeout;
            //modbusClient.ReceiveTimeOut = 1000;



            

           




            Task.Run(() =>
            {
                workstation = (int)yiqi.standby;
                while (true)
                {
                    Thread.Sleep(500);
                    if (connectflag == 1)
                    {

                        connect = modbusClient.Read("1006", 1);//判断连接是否正常
                        if (connect.IsSuccess)
                        {
                            TCPconnect.Enabled = false;
                            PortNum.Text = modbusClient.IpAddress;
                            label6.Text = modbusClient.Port.ToString();
                            label6.ForeColor = Color.Green;
                            //Code.Focus();
                        }
                        else
                        {
                            connectflag = 0;
                            TCPconnect.Enabled = true;
                            PortNum.Text = "";
                            label6.Text = "未连接";
                            label6.ForeColor = Color.Red;
                        }
                        machine2();//仪器读取线程
                        MachineDisplay();//仪器显示线程

                        //    //if (MachineStatus.Text == "待机中" && connect.IsSuccess)
                        //    //{
                        //    //    Thread.Sleep(3000);
                        //    //    workstation = (int)yiqi.start;

                        //    //    MachineStatus.Text = "";
                        //    //}
                        }



                    }

            }
                 );


        }

        public string GetLocalIPAddress()
        {
            string localIP = "";
            foreach (var addr in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (addr.AddressFamily == AddressFamily.InterNetwork) // 选择 IPv4 地址
                {
                    localIP = addr.ToString();
                    break;
                }
            }
            return localIP;
        }
        System.Net.IPAddress ip;
        private static Socket sock;
        Thread UDPlisten;
        string UDPRecvData;
        //点击“连接串口”按钮，连接串口
        private void BtnCon1_Click(object sender, EventArgs e)
        {
            UDPResults.Items.Clear();
            byte[] data = Encoding.ASCII.GetBytes("hello,udp server");
            
            string localip=GetLocalIPAddress();

            // 查找第三个 '.' 符号的位置
            int firstDot = localip.IndexOf('.');
            int secondDot = localip.IndexOf('.', firstDot + 1);
            int thirdDot = localip.IndexOf('.', secondDot + 1);

            // 截取到第三个 '.' 符号
            localip = thirdDot != -1
                ? localip.Substring(0, thirdDot + 1)
                : localip;

            localip = localip/*.Substring(0, 10)*/ + "255";
            //Code.Text = localip;
            ip = System.Net.IPAddress.Parse(localip);
            // 获本机IP频段广播到 .255
            IPEndPoint endPoint = new IPEndPoint(ip, Port);

            //try
            //{
            //    // 发送广播
            //    udpClient.Send(data, data.Length, endPoint);

            //    isListening = true;
            //    // 开始监听返回消息
            //    udpClient.BeginReceive(ReceiveCallback, null);
            //    timeoutTimer.Start();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sock.SetSocketOption(SocketOptionLevel.Socket,
                    SocketOptionName.Broadcast, 1);

            UDPOverTime.Interval = 3000;
            UDPOverTime.Start();
            isListening = true;
            UDPlisten = new Thread(UDP_Listening);
            UDPlisten.Start();
            sock.SendTo(data, endPoint);
            //UDPRead.Interval = 3000;
            //UDPRead.Start();
        }

        private void UDP_Listening()
        {
            while (isListening)
            {
                Invoke(new System.Action(() =>
                {
                    UDPOverTime.Stop();
                }
));
                byte[] data = new byte[1024];
                int recv = sock.Receive(data);
                string RecvData = Encoding.ASCII.GetString(data, 0, recv);
                Invoke(new Action(() =>
                {
                    UDPResults.Items.Add(RecvData); // 将接收到的消息添加到 ComboBox
                    UDPResults.SelectedIndex = UDPResults.Items.Count - 1;
                }));
                //UDPRecvData += RecvData;
                //UDPRecvData += "\n";
            }
        }
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                if (!isListening) return;

                IPEndPoint remoteEndPoint = new IPEndPoint(ip, Port);
                byte[] receivedData = udpClient.EndReceive(ar, ref remoteEndPoint);
                string receivedMessage = Encoding.ASCII.GetString(receivedData);

                // 更新 UI 线程中的 ComboBox
                Invoke(new Action(() =>
                {
                    UDPResults.Items.Add(receivedMessage); // 将接收到的消息添加到 ComboBox
                    UDPResults.SelectedIndex = UDPResults.Items.Count - 1;
                }));

                // 继续接收下一个数据包
                if (isListening)
                {
                    udpClient.BeginReceive(ReceiveCallback, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //关闭串口
        private void BtnBreak_Click(object sender, EventArgs e)
        {
            try
            {
                connectflag = 0;
                //if (connect.IsSuccess)
                {
                    connectflag = 0;
                    modbusClient.ConnectClose();
                    BtnCon1.Enabled = true;
                    TCPconnect.Enabled = true;
                    label6.ForeColor = Color.Red;
                }
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //接收数据
        private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(50);
                if (!SerialPort1.IsOpen) return;
                int len = SerialPort1.BytesToRead;//获取可以读取的字节数
                if (MachineStatus.Text == "测试中")
                {
                    SerialPort1.DiscardInBuffer();
                }
                else if (len > 1)
                {
                    byte[] buff = new byte[len];//创建缓存数据数组
                    SerialPort1.Read(buff, 0, len);//把数据读取到buff数组
                    Invoke((new System.Action(() => //接收计数
                    {
                        string code = Encoding.Default.GetString(buff);
                        if (!code.Contains("ERROR"))
                        {
                            Code.Text = string.Empty;
                            CodeJudge(code, 1);
                        }


                        //CodePort1.DiscardInBuffer();
                    })));
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Code:" + ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        //十六进制接收
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            try
            {
                if (bytes != null)
                {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        returnStr += bytes[i].ToString("X2");//每个字节转换成两位十六进制
                                                             //     returnStr += " ";//两个16进制用空格隔开,方便看数据
                    }
                }
                return returnStr;
            }
            catch (Exception)
            {
                return returnStr;
            }
        }
        Log log = new Log();

        //根据变量判断仪器过程，对读取的数据进行不同的转换
        private void Stagenum()
        {
            //try
            //{
            //    switch (stage)
            //    {
            //        case 0://利用定时器进入状态位读取
            //            Timer1.Interval = 100;
            //            Timer1.Start();
            //            //     Timer2.Interval = 10;
            //            //      Timer2.Start();
            //            stage = 1;
            //            break;

            //        case 1://此时为状态位读取
            //            string str1;
            //            str1 = ReceiveText.Text;

            //            if (str1.Length >= 8 && str1.Substring(6, 2) == "01")
            //            {
            //                Timer1.Stop();
            //                Timer2.Interval = 300;
            //                Timer2.Start();
            //                MachineStatus.ForeColor = Color.Green;
            //                MachineStatus.Text = "启动中";
            //                log.Logmsg(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")+"启动");
            //                Tlight.Text = "  ";
            //                BtnStart.Enabled = false;
            //                Code.Enabled = false;
            //                Leak.Text = "";
            //                LeakPressure.Text = "";
            //                MESStatus.Text = "";
            //                progressBar2.Value = 0;
            //                测试参数ToolStripMenuItem.Enabled = false;
            //                write = 0;
            //                //       sum = 0;
            //            }
            //            break;

            //        case 2://此时为读取参数并数据转换

            //            Timer2.Stop();
            //            string str2;
            //            str2 = ReceiveText.Text;
            //            //     str2 = str2.Replace(" ", "");

            //            if (str2.Length > 122)
            //            {
            //                string hexstring_full = str2.Substring(26, 4);
            //                string hexstring_balan = str2.Substring(30, 4);
            //                string hexstring_test = str2.Substring(34, 4);
            //                string hexstring_exhasut = str2.Substring(38, 4);
            //                string hexstring_bypass = str2.Substring(42, 4);
            //                string hexstring_delay1 = str2.Substring(46, 4);
            //                string hexstring_delay2 = str2.Substring(50, 4);

            //                string hexstring_bleakbalan = str2.Substring(62, 4);
            //                string hexstring_sleakbalan = str2.Substring(66, 4);
            //                string hexstring_bleaktoppre = str2.Substring(70, 4);
            //                string hexstring_bleaklowpre = str2.Substring(74, 4);

            //                //      string hexstring_bleaktest = str2.Substring(124, 4);

            //                string hexstring_lunit = str2.Substring(86, 4);
            //                string hexstring_punit = str2.Substring(90, 4);

            //                //十六进制转十进制
            //                int full = Int32.Parse(hexstring_full, System.Globalization.NumberStyles.HexNumber) / 10;
            //                int balan = Int32.Parse(hexstring_balan, System.Globalization.NumberStyles.HexNumber) / 10;
            //                int test = Int32.Parse(hexstring_test, System.Globalization.NumberStyles.HexNumber) / 10;

            //                double exhaust = Convert.ToDouble(Convert.ToInt32(hexstring_exhasut, 16)) / 10;

            //                int bypass = Int32.Parse(hexstring_bypass, System.Globalization.NumberStyles.HexNumber) / 10;

            //                double delay1 = Int32.Parse(hexstring_delay1, System.Globalization.NumberStyles.HexNumber);
            //                double delay2 = Int32.Parse(hexstring_delay2, System.Globalization.NumberStyles.HexNumber);
            //                double delay11 = delay1 / 10;
            //                double delay22 = delay2 / 10;

            //                int bleakbalan = Int32.Parse(hexstring_bleakbalan, System.Globalization.NumberStyles.HexNumber) / 10;
            //                int sleakbalan = Int32.Parse(hexstring_sleakbalan, System.Globalization.NumberStyles.HexNumber) / 10;
            //                int bleaktoppre = Int32.Parse(hexstring_bleaktoppre, System.Globalization.NumberStyles.HexNumber);
            //                int bleaklowpre = Int32.Parse(hexstring_bleaklowpre, System.Globalization.NumberStyles.HexNumber);

            //                //   int bleaktest = Int32.Parse(hexstring_bleaktest, System.Globalization.NumberStyles.HexNumber) / 10;

            //                int lunit = Int32.Parse(hexstring_lunit, System.Globalization.NumberStyles.HexNumber);
            //                int punit = Int32.Parse(hexstring_punit, System.Globalization.NumberStyles.HexNumber);

            //                delaytime = delay11 + delay22;

            //                FullTime.Text = full.ToString();
            //                BalanTime.Text = balan.ToString();
            //                TestTime1.Text = test.ToString();
            //                ExhaustTime.Text = exhaust.ToString();
            //                BypassTIme.Text = bypass.ToString();
            //                DelayTime1.Text = delay11.ToString();
            //                DelayTime2.Text = delay22.ToString();

            //                BBalanTime.Text = bleakbalan.ToString();
            //                SBalanTime.Text = sleakbalan.ToString();
            //                //   TestTime2 .Text = bleaktest.ToString();
            //                BLeakTPre.Text = bleaktoppre.ToString();
            //                if (bleaklowpre > 32767)
            //                {
            //                    string bleaklowpre2 = "FFFFFFFFFFFF" + hexstring_bleaklowpre;
            //                    long bleaklowpre3 = Convert.ToInt64(bleaklowpre2, 16);
            //                    BLeakLPre.Text = bleaklowpre3.ToString();
            //                }
            //                else
            //                {
            //                    BLeakLPre.Text = bleaklowpre.ToString();
            //                }

            //                if (lunit < 6 && punit < 8)
            //                {
            //                    LUnit.SelectedIndex = lunit;
            //                    PUnit.SelectedIndex = punit;
            //                }
            //                else
            //                {
            //                    Timer2.Interval = 300;
            //                    Timer2.Start();
            //                }

            //                PressureUnit.Text = PUnit.Text;

            //                LeakUnit.Text = LUnit.Text;

            //                string hexstring_fptop1 = str2.Substring(54, 4);
            //                string hexstring_fptop2 = str2.Substring(58, 4);
            //                string hexstring_fptop = hexstring_fptop2 + hexstring_fptop1;

            //                string hexstring_ltop1 = str2.Substring(78, 4);
            //                string hexstring_ltop2 = str2.Substring(82, 4);
            //                string hexstring_ltop = hexstring_ltop2 + hexstring_ltop1;

            //                string hexstring_evol1 = str2.Substring(94, 4);
            //                string hexstringg_evol2 = str2.Substring(98, 4);
            //                string hexstringg_evol = hexstringg_evol2 + hexstring_evol1;

            //                string hexstring_llow1 = str2.Substring(102, 4);
            //                string hexstring_llow2 = str2.Substring(106, 4);
            //                string hexstring_llow = hexstring_llow2 + hexstring_llow1;

            //                string hexstring_fplow1 = str2.Substring(110, 4);
            //                string hexstring_fplow2 = str2.Substring(114, 4);
            //                string hexstring_fplow = hexstring_fplow2 + hexstring_fplow1;

            //                string bleaktesttime = str2.Substring(118, 4);
            //                int testtime2 = Convert.ToInt32(bleaktesttime, 16) / 10;
            //                TestTime2.Text = testtime2.ToString();

            //                UInt32 x1 = Convert.ToUInt32(hexstring_fptop, 16);//字符串转16进制32位无符号整数
            //                FPtoplimit.Text = BitConverter.ToSingle(BitConverter.GetBytes(x1), 0).ToString();//IEEE754 字节转换float
            //                UInt32 x2 = Convert.ToUInt32(hexstring_ltop, 16);//字符串转16进制32位无符号整数
            //                Leaktoplimit.Text = BitConverter.ToSingle(BitConverter.GetBytes(x2), 0).ToString();//IEEE754 字节转换float
            //                UInt32 x3 = Convert.ToUInt32(hexstringg_evol, 16);//字符串转16进制32位无符号整数
            //                Evolume.Text = BitConverter.ToSingle(BitConverter.GetBytes(x3), 0).ToString();//IEEE754 字节转换float
            //                UInt32 x4 = Convert.ToUInt32(hexstring_llow, 16);//字符串转16进制32位无符号整数
            //                Leaklowlimit.Text = BitConverter.ToSingle(BitConverter.GetBytes(x4), 0).ToString();//IEEE754 字节转换float
            //                UInt32 x5 = Convert.ToUInt32(hexstring_fplow, 16);//字符串转16进制32位无符号整数
            //                FPlowlimit.Text = BitConverter.ToSingle(BitConverter.GetBytes(x5), 0).ToString();//IEEE754 字节转换float
            //                                                                                                 //    UInt32 x6 = Convert.ToUInt32(hexstring21, 16);//字符串转16进制32位无符号整数
            //                                                                                                 //    Leaktoplimit.Text = BitConverter.ToSingle(BitConverter.GetBytes(x6), 0).ToString();//IEEE754 字节转换float

            //                int exhausttime = Convert.ToInt32(exhaust);
            //                int a = full + balan + test + testtime2 + exhausttime;
            //                if (a > 50)
            //                {
            //                    progressBar2.Maximum = (full + balan + test + testtime2 + exhausttime - 2) * 10;
            //                }
            //                else
            //                {
            //                    progressBar2.Maximum = (full + balan + test + testtime2 + exhausttime - 1) * 10;
            //                }
            //                Timer4.Interval = Convert.ToInt32((full + balan + test + testtime2 + exhaust) * 1000);
            //                Timer4.Start();
            //                Timer8.Interval = Convert.ToInt32(delaytime * 1000 + 1);
            //                Timer8.Start();

            //                Timer3.Interval = 300;
            //                Timer3.Start();
            //            }
            //            else
            //            {
            //                Timer2.Interval = 300;
            //                Timer2.Start();
            //            }

            //            break;

            //        case 3://循环读取测试结果
            //            string str4;
            //            str4 = ReceiveText.Text;
            //            //   str4 = str4.Replace(" ", "");
            //            Timer3.Stop();
            //            if (str4.Length > 54 && str4.Substring(2, 2) == "03")
            //            {
            //                string status1 = str4.Substring(6, 4);
            //                int status = Convert.ToInt32(status1, 16);
            //                switch (status)
            //                {
            //                    case 1:
            //                        TestStatus.Text = "准备";
            //                        break;

            //                    case 2:
            //                        TestStatus.Text = "充气";
            //                        fullpressure = LeakPressure.Text;
            //                        break;

            //                    case 3:
            //                        TestStatus.Text = "平衡";
            //                        balanpressure = LeakPressure.Text;
            //                        break;

            //                    case 4:
            //                        TestStatus.Text = "检测";
            //                        break;

            //                    case 5:
            //                        TestStatus.Text = "排气";
            //                        break;
            //                }

            //                string lp1 = str4.Substring(42, 4);
            //                string lp2 = str4.Substring(38, 4);
            //                string lp5 = lp1 + lp2;
            //                string lp3 = str4.Substring(50, 4);
            //                string lp4 = str4.Substring(46, 4);
            //                string lp6 = lp3 + lp4;

            //                UInt32 b1 = Convert.ToUInt32(lp5, 16);//字符串转16进制32位无符号整数
            //                LeakPressure.Text = BitConverter.ToSingle(BitConverter.GetBytes(b1), 0).ToString("F3");//IEEE754 字节转换float
            //                Debug.WriteLine("LeakPressure: " + LeakPressure.Text);
            //                UInt32 b2 = Convert.ToUInt32(lp6, 16);//字符串转16进制32位无符号整数
            //                Leak.Text = BitConverter.ToSingle(BitConverter.GetBytes(b2), 0).ToString("F3");//IEEE754 字节转换float
            //                Debug.WriteLine("Leak: " + Leak.Text);
            //                string result1 = str4.Substring(10, 4);
            //                int result = Convert.ToInt32(result1, 16);
            //                if (result == 1)
            //                {
            //                    DLeakPressure = LeakPressure.Text;
            //                    DLeak = Leak.Text;
            //                    Tlight.Text = "OK";
            //                    Tlight.ForeColor = Color.Green;
            //                    Timer11.Start();
            //                    //SendText.Text = Station.Text + "05 02 1D FF 00";
            //                    //Send();
            //                }
            //                else if (result == 2)
            //                {
            //                    DLeakPressure = LeakPressure.Text;
            //                    DLeak = Leak.Text;
            //                    Tlight.Text = "NG";
            //                    SendText.Text = Station.Text + "05 02 1D FF 00";
            //                    Send();
            //                    Tlight.ForeColor = Color.Red;

            //                    if (delaytime > 0)
            //                    {
            //                        Timer9.Interval = Convert.ToInt32(Convert.ToDouble(ExhaustTime.Text) * 2000);
            //                        Timer9.Start();
            //                    }
            //                    else
            //                    {
            //                        Timer9.Interval = Convert.ToInt32(Convert.ToDouble(ExhaustTime.Text) * 1000);
            //                        Timer9.Start();
            //                    }

            //                    Timer11.Start();
            //                }
            //                else
            //                {
            //                    Timer3.Interval = 150;
            //                    Timer3.Start();
            //                }
            //            }
            //            else
            //            {
            //                Timer3.Interval = 150;
            //                Timer3.Start();
            //            }

            //            break;

            //        case 4:
            //            Timer1.Interval = 100;
            //            Timer1.Start();
            //            stage = 5;
            //            break;

            //        case 5:
                        
            //            //对仪器是否结束的判断
            //            /*     string str5;
            //                 str5 = ReceiveText.Text;
            //                 if (str5.Substring(6, 2) == "00")
            //                 {
            //                     Timer1.Stop();

            //                     BtnStart.Enabled = true;
            //                     Code.Enabled = true;

            //                     if (write == 0)
            //                     {
            //                         timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //                         CreateFile();
            //                         Display();
            //                         stage = 10;
            //                         MachineStatus.ForeColor = Color.Red;
            //                         MachineStatus.Text = "待机中";
            //                     }
            //                     else
            //                     {
            //                         stage = 10;
            //                         MachineStatus.ForeColor = Color.Red;
            //                         MachineStatus.Text = "待机中";
            //                     }
            //                     Code.ResetText();
            //                     Code.ScrollToCaret();
            //                     Code.Focus();
            //                     Timer1.Interval = 800;
            //                     Timer1.Start();
            //                     stage = 1;

            //                     if (串口设置ToolStripMenuItem.Enabled is true)
            //                     {
            //                         测试参数ToolStripMenuItem.Enabled = true;
            //                     }
            //                 }
            //            */

            //            string str5;
            //            str5 = ReceiveText.Text;
            //            //if (str5.Substring(6, 2) == "00")
            //            log.Logmsg("进入Case：5" +str5);
            //            if (str5.Length >= 78 && str5.StartsWith("020328"))
            //            {
            //                log.Logmsg("进入Case：5判断" + str5);
            //                Timer11.Stop();
            //                string hex = str5.Substring(6, 74);
            //                string hexString = string.Join(" ", Regex.Matches(hex, @"..").Cast<Match>().ToList());
            //                StringBuilder sbBuffer = new StringBuilder();
            //                string strArr1;
            //                string strArr2;

            //                for (int i = 0; i < hexString.Split(' ').Length - 1; i = i + 2)
            //                {
            //                    strArr1 = hexString.Split(' ')[i];
            //                    strArr2 = hexString.Split(' ')[i + 1];
            //                    sbBuffer.Append(strArr2).Append(" ").Append(strArr1).Append(" ");
            //                }
            //                string hexStringNew = sbBuffer.ToString().TrimEnd();
            //                string tempBarCode = (ToStringFromHexString(hexStringNew, Encoding.UTF8));
            //                string stringNew = string.Empty;

            //                if (tempBarCode.Contains("\0"))
            //                {
            //                    stringNew = Regex.Unescape(tempBarCode);
            //                    int index = stringNew.IndexOf("\0");
            //                    stringNew = stringNew.Remove(index);
            //                }
            //                else
            //                {
            //                    stringNew = tempBarCode;
            //                }
            //                Debug.WriteLine("str:" + str5 + Environment.NewLine);
            //                Debug.WriteLine("hex:" + hex + Environment.NewLine);
            //                Debug.WriteLine("tempBarCode:" + tempBarCode + Environment.NewLine);
            //                Debug.WriteLine("stringNew:" + stringNew + Environment.NewLine);
            //                string barCode = stringNew.Replace("\0", "").Replace("\r", "").Replace("\n", "").Replace("\r\n", "");
            //                Debug.WriteLine("barCode:" + barCode + Environment.NewLine);
            //                if (string.IsNullOrEmpty(barCode))
            //                {
            //                    //MessageBox.Show("录入条码为空");
            //                }
            //                if (!string.IsNullOrEmpty(barCode))
            //                {
            //                    if (barCode.Length > Convert.ToInt32(CodeLength.Text))
            //                    {
            //                       // MessageBox.Show("录入条码长度大于设置条码长度");
            //                    }
            //                }
            //                Code.Text = barCode;
            //                //BtnStart.Enabled = true;
            //                //Code.Enabled = true;
            //                //if (write == 0)
            //                //{
            //                //    timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //                //    CreateFile();
            //                //    Display();
            //                //    stage = 10;
            //                //    MachineStatus.ForeColor = Color.Red;
            //                //    MachineStatus.Text = "待机中";
            //                //}
            //                //else
            //                //{
            //                //    stage = 10;
            //                //    MachineStatus.ForeColor = Color.Red;
            //                //    MachineStatus.Text = "待机中";
            //                //}
            //                //Code.ResetText();
            //                //Code.ScrollToCaret();
            //                //Code.Focus();
            //                stage = 6;

            //                //if (串口设置ToolStripMenuItem.Enabled is true)
            //                //{
            //                //    测试参数ToolStripMenuItem.Enabled = true;
            //                //}
            //            }
            //            break;

            //        case 6://读取条码
            //            string str6;
            //            str6 = ReceiveText.Text;
            //            log.Logmsg("进入Case6：" + str6);
            //            if (str6.Length >= 8 && str6.Substring(6, 2) == "00")
            //            {
            //                Timer1.Stop();

            //                BtnStart.Enabled = true;
            //                Code.Enabled = true;
            //                log.Logmsg("设备待机");
            //                if (write == 0)
            //                {
            //                    timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //                    CreateFile();
            //                    Display();
            //                    State();
            //                    stage = 1;
            //                    MachineStatus.ForeColor = Color.Red;
            //                    MachineStatus.Text = "待机中";
            //                }
            //                else
            //                {
            //                    State();
            //                    stage = 1;
            //                    MachineStatus.ForeColor = Color.Red;
            //                    MachineStatus.Text = "待机中";
            //                }
            //                Code.ResetText();
            //                Code.ScrollToCaret();
            //                Code.Focus();
            //                Timer1.Interval = 800;
            //                Timer1.Start();
            //                stage = 1;

            //                if (串口设置ToolStripMenuItem.Enabled is true)
            //                {
            //                    测试参数ToolStripMenuItem.Enabled = true;
            //                }
            //            }
            //            else
            //            {
            //                State();
            //                stage = 6;
            //                MachineStatus.Text = "未复位";
            //                MachineStatus.ForeColor = Color.Red;
                           
            //            }
            //            break;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
         
        }

        //发送过程
        private void Send()
        {
            //try
            //{
            //    //将CRC冗余码添加进指令中
            //    String str = SendText.Text;
            //    byte[] byt = StrtoHexbyte(str);
            //    int str2;
            //    str2 = Crc16_Modbus(byt, byt.Length);
            //    //byte byte1 =(byte)((str2 >> 8)&0xff);
            //    string str3;
            //    // str3=(( str2 >> 8) & 0xff).ToString ();
            //    str3 = Convert.ToString((str2 >> 8) & 0xff, 16);
            //    string str4;
            //    str4 = Convert.ToString(str2 & 0xff, 16);
            //    // string str4;
            //    // str4 = (str2 & 0xff).ToString();
            //    // string str3;
            //    if (str3.Length == 1)
            //    {
            //        str3 = "0" + str3;
            //        //   textBox2.Text = textBox2.Text + str4 + str3;
            //    }
            //    if (str4.Length == 1)
            //    {
            //        str4 = "0" + str4;
            //        //  textBox2.Text = textBox2.Text + str4 + str3;
            //    }
            //    SendText.Text = SendText.Text + str4 + str3;
            //    String str5 = SendText.Text;
            //    if (str5.Length > 0)
            //    {
            //        byte[] byt2 = StrtoHexbyte(str5);
            //        SerialPort1.Write(byt2, 0, byt2.Length);//发送数据
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Timer1.Stop();
            //    Timer2.Stop();
            //    Timer3.Stop();
            //    Timer4.Stop();

            //    Timer8.Stop();
            //    Timer9.Stop();
            //    Timer10.Stop();
            //    Timer11.Stop();
            //    Timer16.Stop();
            //    MessageBox.Show(ex.Message);
            //}
        }

        //计算CRC冗余码
        private int Crc16_Modbus(byte[] modbusdata, int length)
        {
            int i, j;
            int crc = 0xffff;//0xffff or 0
            for (i = 0; i < length; i++)
            {
                crc ^= modbusdata[i] & 0xff;
                for (j = 0; j < 8; j++)
                {
                    if ((crc & 0x01) == 1)
                    {
                        crc = (crc >> 1) ^ 0xa001;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }

            return crc;
        }

        //将发送数据转为十六进制数据
        private static byte[] StrtoHexbyte(String hexstring)
        {
            int i;
            hexstring = hexstring.Replace(" ", "");

            byte[] returnBytes = new byte[(hexstring.Length) / 2];
            try
            {
                for (i = 0; i < returnBytes.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(hexstring.Substring(i * 2, 2), 16);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
            return returnBytes;
        }

        //启动仪器
        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //if (string.IsNullOrEmpty(Form1.f1.CodeLength.Text))
                //{
                //    MessageBox.Show("请设定条码长度", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return;
                //}
                //if (Convert.ToInt32(Form1.f1.CodeLength.Text) <= 2)
                //{
                //    MessageBox.Show("条码长度设置错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return;
                //}
                modbusClient.Write("0", true);

                //workstation = (int)yiqi.start;


                //workstation = (int)yiqi.start;
                //Code.Focus();


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //将线圈置为0
        private void Timer10_Tick(object sender, EventArgs e)
        {
            ////try
            ////{
            ////    Timer10.Stop();
            ////    SendText.Text = Station.Text + "05 02 1C 00 00";
            ////    Send();
            ////    stage = 0;
            ////    write = 0;
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }

        //读状态位
        private void State()
        {
            //SendText.Text = Station.Text + " 01 02 1E 00 01";

            //Send();
        }

        //一百毫秒读状态位的定时器
        private void Timer1_Tick(object sender, EventArgs e)
        {
            Timer1.Stop();
            workstation = (int)yiqi.start;

        }

        //读参数
        private void Parameters()
        {
            SendText.Text = Station.Text + " 03 00 14 00 1D";
            //    CrcNum();
            Send();
            stage = 2;
        }

        //读参数的定时器
        private void Timer2_Tick(object sender, EventArgs e)
        {
            //try
            //{
            //    Parameters();
            //    //      Timer2.Stop();
            //}
            //catch //(Exception ex)
            //{
            //    Timer2.Stop();
            //}
        }

        //读泄漏量的定时器
        private void Timer3_Tick(object sender, EventArgs e)
        {
            //try
            //{
            //    SendText.Text = Station.Text + " 03 00 08 00 0C";

            //    Send();
            //    stage = 3;
            //}
            //catch //(Exception ex)
            //{
            //    Timer3.Stop();
            //}
        }

        //控制timer3何时关闭的定时器，并读状态位
        private void Timer4_Tick(object sender, EventArgs e)
        {
            //try
            //{
            //    if (Tlight.Text.Contains("OK") || Tlight.Text.Contains("NG"))
            //    {
            //        Timer4.Stop();
            //        Timer9.Stop();
            //        Timer3.Stop();

            //        Timer1.Interval = 200;
            //        Timer1.Start();
            //        stage = 5;

            //        //   stage = 5;
            //        progressBar2.Value = progressBar2.Maximum;
            //        Timer8.Stop();
            //    }
            //    else
            //    {
            //        Timer4.Interval = 100;
            //        Timer4.Start();
            //    }
            //}
            //catch
            //{
            //    Timer4.Stop();
            //}
        }

        //复位按钮
        private void BtnReset_Click(object sender, EventArgs e)
        {
            try
            {
                //workstation = (int)yiqi.rst;

                //Code.Focus();
                modbusClient.Write("1", true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public short Digitalconversion(ushort readdata)
        {
            int Z;
            if (readdata > 32768)
                Z = (int)readdata - 65536;
            else
                Z = readdata;


            return (short)Z;
        }


        //将数据写入Excel表格
        private void AddExcel()
        {
            string FileName;
            string Date = DateTime.Now.ToString("yyyyMMdd");
            string nowdate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            if (path.Text == "")//若路径处不输入则获取桌面路径
            {
                FileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
            }
            else
            {

                FileName = path.Text + "\\" + "leaktest" + Date + ".xlsx";
            }
            if (File.Exists(FileName))
            {


                FileStream file = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                IWorkbook workbook = new XSSFWorkbook(file);
                ISheet sheet = workbook.GetSheet("Sheet1");
                int startRow = sheet.LastRowNum + 1;
                IRow newRow = sheet.CreateRow(startRow);

                

                string[] data = new string[] { nowdate , Code.Text, ReadData[1006] / 10.0 + "s", ReadData[1007] / 10.0 + "s", ReadData[1008] / 10.0 + "s", ReadData[1009] / 10.0 + "s",
                    TwoUInt16ToFloat(ReadData[1014], ReadData[1013]).ToString(), TwoUInt16ToFloat(ReadData[1016], ReadData[1015]).ToString(),
                    TwoUInt16ToFloat(ReadData[1018], ReadData[1017]).ToString(), TwoUInt16ToFloat(ReadData[1020], ReadData[1019]).ToString(), TwoUInt16ToFloat(ReadData[1022], ReadData[1021]).ToString(), TwoUInt16ToFloat(ReadData[1024], ReadData[1023]).ToString(), Tlight.Text,
                    TwoUInt16ToFloat(ReadData[1049], ReadData[1048]).ToString(), PressureUnit.Text, TwoUInt16ToFloat(ReadData[1039], ReadData[1038]).ToString(), LeakUnit.Text  }; //行名
                for (int i = 0; i < data.Length; i++)
                {
                    newRow.CreateCell(i).SetCellValue(data[i]);
                }
                using (FileStream fileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(fileStream);
                    fileStream.Close();
                }


            }
            else
            {
                // 如果文件不存在，则创建文件并添加数据

                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("Sheet1");

                string[] headers = new string[] { "时间", "条形码", "充气时间", "平衡时间", "检测时间", "排气时间", "充气压力上限", "充气压力下限", "平衡压力上限", "平衡压力下限", "泄漏量上限", "泄漏量下限", "测试结果", "测试压力", "测试压力单位", "泄漏量", "泄漏量单位" };//列名;
                IRow headerRow = sheet.CreateRow(0);
                for (int i = 0; i < headers.Length; i++)
                {
                    headerRow.CreateCell(i).SetCellValue(headers[i]);
                }

                string[] data = new string[] {  nowdate, Code.Text, ReadData[6]/10+"s", ReadData[7] / 10 + "s", ReadData[8] / 10 + "s", ReadData[9] / 10 + "s",
                TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString()+ PUnit.Text, TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString()+ PUnit.Text, TwoUInt16ToFloat(ReadData[21], ReadData[20]).ToString()+ PUnit.Text, TwoUInt16ToFloat(ReadData[23], ReadData[22])+ PUnit.Text.ToString(), TwoUInt16ToFloat(ReadData[13], ReadData[12]).ToString()+LUnit.Text, TwoUInt16ToFloat(ReadData[25], ReadData[24]).ToString()+LUnit.Text, Tlight.Text,
                TwoUInt16ToFloat(ReadData[801], ReadData[800]).ToString()+ PUnit.Text, PUnit.Text, TwoUInt16ToFloat(ReadData[293], ReadData[292]).ToString()+LUnit.Text, LUnit.Text  }; //行名
                IRow dataRow = sheet.CreateRow(1);
                for (int i = 0; i < data.Length; i++)
                {
                    dataRow.CreateCell(i).SetCellValue(data[i]);
                }

                using (FileStream file = new FileStream(FileName, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(file);
                    file.Close();
                }
            }



        }



       

        //将数据写入TXT
        private void AddTXT()
        {
            string fileName;
            string file = DateTime.Now.ToString("yyyyMMdd");
            if (path.Text == "")
            {
                fileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\leaktest.txt";
            }
            else
            {
                fileName = path.Text + "\\" + file + ".txt";
            }
            string str1 = "时间 " + DateTime.Now + " 条形码 " + Code.Text + " 充气时间 " + FullTime.Text + "s" + " 平衡时间 " + BalanTime.Text + "s" + " 检测时间 " + TestTime1.Text + "s" + " 排气时间 " + ExhaustTime.Text + "s" + " 充气压力上限 " + FPtoplimit.Text + PressureUnit.Text + " 充气压力下限 " + FPlowlimit.Text + PressureUnit.Text + " 大漏压差上限 " + BLeakTPre.Text + LeakUnit.Text + " 大漏压差下限 " + BLeakLPre.Text + LeakUnit.Text + " 泄漏量上限 " + Leaktoplimit.Text + LeakUnit.Text + " 泄漏量下限 " + Leaklowlimit.Text + LeakUnit.Text + " 测试结果 " + Tlight.Text + " 测试压力 " + DLeakPressure + " 压力单位 " + PressureUnit.Text + " 泄漏量 " + DLeak + " 泄漏量单位 " + LeakUnit.Text + " \n";
            System.IO.File.AppendAllText(fileName, str1);
        }

        //将数据写入数据库
        private void AddDatebase()
        {
            try
            {
                //  Form2 Form2 = new Form2();
                string database = ReadRegistryKey("datasource");
                string userid = ReadRegistryKey("userid");
                string pwd = ReadRegistryKey("pwd");
                string dataname = ReadRegistryKey("dataname");
                string nowday = DateTime.Now.ToString("yyyy_MM_dd");
                string connectionString = "Data source=" + database;
                connectionString += ";Initial Catalog=master;User Id=" + userid + ";Password=" + pwd;//定义连接字符串

                SqlConnection con = new SqlConnection(connectionString);//创建连接
                con.Open();//打开并连接数据库

                if (dataname == "")
                {
                    dataname = "LeakTest";
                }
                string selectString = "Select * FROM master..SYSDATABASES WHERE name ='" + dataname + "'";//输入sql语句,判断是否存在名为LeakTest的数据库

                SqlCommand cmd = new SqlCommand(selectString, con);
                var str1 = cmd.ExecuteScalar();
                if (str1 is null)
                {
                    cmd.CommandText = "CREATE DATABASE " + dataname;//如果不存在则新建数据库
                    cmd.ExecuteNonQuery();
                }
                con.Close();
                connectionString = "Data source=" + database;
                connectionString += ";Initial Catalog=" + dataname + "; User Id=" + userid + ";Password=" + pwd;

                SqlConnection con2 = new SqlConnection(connectionString);//和名为LeakTest的数据库建立连接
                con2.Open();
                string selectString2 = "select * from dbo.sysobjects where name=('test" + "')";//查询是否有名为leaktest+日期的表格
                SqlCommand cmd2 = new SqlCommand(selectString2, con2);
                var str2 = cmd2.ExecuteScalar();
                if (str2 is null)
                {
                    //若没有表格则新建表格
                    cmd2.CommandText = "CREATE TABLE test"  + " ([时间] DATETIME ,[条形码] VarChar(50),[充气时间] INT,[平衡时间] INT,[检测时间] INT,[排气时间] INT,[充气压力上限] FLOAT,[充气压力下限] FLOAT,[大漏压差上限] FLOAT,[大漏压差下限] FLOAT,[泄漏量上限] FLOAT,[泄漏量下限] FLOAT,[测试结果] VarChar(50),[测试压力] FLOAT,[压力单位] VarChar(50),[泄漏量] FLOAT,[泄漏量单位] VarChar(50))"; //Office is the named range.
                    cmd2.ExecuteNonQuery();
                }


                //string[] dataArr = {DateTime.Now.ToString(),Code.Text, ReadData[25] / 10.0 + "s", ReadData[26] / 10.0 + "s", ReadData[27] / 10.0 + "s", ReadData[28] / 10.0 + "s",
                //    TwoUInt16ToFloat(ReadData[33], ReadData[32]).ToString(),  TwoUInt16ToFloat(ReadData[47], ReadData[46]).ToString(),
                //    ReadData[36].ToString() ,  ( Digitalconversion( ReadData[37])).ToString()  ,  TwoUInt16ToFloat(ReadData[39], ReadData[38]).ToString() ,  TwoUInt16ToFloat(ReadData[45], ReadData[44]).ToString() ,Tlight.Text ,
                //    TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString() , PressureUnit.Text , TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString() , LeakUnit.Text};




                //往表格插入数据

                cmd2.CommandText = "INSERT INTO test" /*+ nowday*/ + " (时间, 条形码, 充气时间, 平衡时间, 检测时间, 排气时间, 充气压力上限, 充气压力下限, 大漏压差上限, 大漏压差下限, 泄漏量上限, 泄漏量下限, 测试结果, 测试压力, 压力单位, 泄漏量, 泄漏量单位) VALUES('" + DateTime.Now+ "', '" + Code.Text + "', '"+ ReadData[25] / 10.0+ "', '" + ReadData[26] / 10.0 + "', '" + ReadData[27] / 10.0 + "', '" + ReadData[28] / 10.0  + "', '" +TwoUInt16ToFloat(ReadData[33], ReadData[32]).ToString() + "', '" + TwoUInt16ToFloat(ReadData[47], ReadData[46]).ToString() + "', '" +ReadData[36].ToString() + "', '" + (Digitalconversion(ReadData[37])).ToString() + "', '" + TwoUInt16ToFloat(ReadData[39], ReadData[38]).ToString() + "', '" + TwoUInt16ToFloat(ReadData[45], ReadData[44]).ToString() + "', '" + Tlight.Text + "', '" +TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString() + "', '" + PressureUnit.Text + "', '" + TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString() + "', '" + LeakUnit.Text + "')";

                //cmd2.CommandText = "INSERT INTO leaktest" + nowday + " (时间, 条形码, 充气时间, 平衡时间, 检测时间, 排气时间, 充气压力上限, 充气压力下限, 大漏压差上限, 大漏压差下限, 泄漏量上限, 泄漏量下限, 测试结果, 测试压力, 压力单位, 泄漏量, 泄漏量单位) VALUES('" + DateTime.Now + "', '" + Code.Text + "', '" + Convert.ToInt32(FullTime.Text) + "', '" + Convert.ToInt32(BalanTime.Text) + "', '" + Convert.ToInt32(TestTime1.Text) + "', '" + Convert.ToInt32(ExhaustTime.Text) + "', '" + Convert.ToSingle(FPtoplimit.Text) + "', '" + Convert.ToSingle(FPlowlimit.Text) + "', '" + Convert.ToSingle(BLeakTPre.Text) + "', '" + Convert.ToSingle(BLeakLPre.Text) + "', '" + Convert.ToSingle(Leaktoplimit.Text) + "', '" + Convert.ToSingle(Leaklowlimit.Text) + "', '" + Tlight.Text + "', '" + Convert.ToSingle(DLeakPressure) + "', '" + PressureUnit.Text + "', '" + Convert.ToSingle(DLeak) + "', '" + LeakUnit.Text + "')";
                cmd2.ExecuteNonQuery();
                con2.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //将数据写入CSV文件中
        private void AddCSV()
        {
            try
            {
                string file = DateTime.Now.ToString("yyyyMMdd");
                string fileName;
                if (path.Text == "")
                {
                    fileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + file + ".csv";
                }
                else
                {
                    fileName = path.Text + "\\" + file + ".csv";
                }

                if (File.Exists(fileName) == false)
                {
                    StreamWriter fileWriter1 = new StreamWriter(fileName, true, Encoding.UTF8);
                    fileWriter1.Write("时间,条形码,充气时间,平衡时间,检测时间,排气时间,充气压力上限,充气压力下限,大漏压差上限,大漏压差下限,泄漏量上限,泄漏量下限,测试结果,测试压力,压力单位,泄漏量,泄漏量单位" + "\r\n");
                    fileWriter1.Flush();
                    fileWriter1.Close();
                }
                StreamWriter fileWriter = new StreamWriter(fileName, true, Encoding.UTF8);

                string nowdate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

                fileWriter.Write(nowdate + "," + Code.Text + ",");
                fileWriter.Write(FullTime.Text + "s" + ",");
                fileWriter.Write(BalanTime.Text + "s" + ",");
                fileWriter.Write(TestTime1.Text + "s" + ",");
                fileWriter.Write(ExhaustTime.Text + "s" + ",");
                fileWriter.Write(FPtoplimit.Text + PUnit.Text + ",");
                fileWriter.Write(FPlowlimit.Text + PUnit.Text + ",");
                fileWriter.Write(BLeakTPre.Text + PUnit.Text + ",");
                fileWriter.Write(BLeakLPre.Text + PUnit.Text + ",");
                fileWriter.Write(Leaktoplimit.Text + LUnit.Text + ",");
                fileWriter.Write(Leaklowlimit.Text + LUnit.Text + ",");
                fileWriter.Write(Tlight.Text + ",");
                fileWriter.Write(DLeakPressure + ",");
                fileWriter.Write(PUnit.Text + ",");
                fileWriter.Write(DLeak + ",");
                fileWriter.Write(LUnit.Text + "\n");

                fileWriter.Flush();
                fileWriter.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //将数据上传至MES系统
        private void ADDMES()
        {
            string result;
            if (Tlight.Text.Contains("OK"))
            {
                result = "PASS";
            }
            else
            {
                result = "FAIL";
            }

            string mesresult = MESInfo.MESInformation(URL.Text, appid.Text, appkey.Text, method.Text, Dept.Text,
         Type.Text, Machinemodel.Text, MESStation.Text, timestamp, Code.Text, result, FPtoplimit.Text + PressureUnit.Text, FPlowlimit.Text + PressureUnit.Text,
         fullpressure + PressureUnit.Text, BLeakTPre.Text + "Pa", BLeakLPre.Text + "Pa", balanpressure + "Pa",
         Leaktoplimit.Text + LUnit.Text, Leaklowlimit.Text + LUnit.Text, DLeak + LUnit.Text);
            if (mesresult.Contains("\"code\":200"))
            {
                MESStatus.Text = "PASS";
                MESStatus.ForeColor = Color.Green;
            }
            else
            {
                MESStatus.Text = "FAIL";
                MESStatus.ForeColor = Color.Red;
                MessageBox.Show(mesresult);
            }
        }

        //写入数据
        private void CreateFile()
        {
            if (ChkExcel.Checked)
            {
                AddExcel();
            }
            //if (ChkTXT.Checked)
            //{
            //    AddTXT();
            //}
            if (ChkSql.Checked)
            {
                AddDatebase();
            }
            //if (ChkCSV.Checked)
            //{
            //    AddCSV();
            //}
            if (ChkMES.Checked && Code.TextLength > 0)
            {
                ADDMES();
            }
        }

        //在界面显示数据
        private void Display()
        {
            DataGridView1.Rows.Add(
                DateTime.Now.ToString(), Code.Text, ReadData[1006] / 10.0 + "s", ReadData[1007] / 10.0 + "s", ReadData[1008] / 10.0 + "s", ReadData[1009] / 10.0 + "s",
                    TwoUInt16ToFloat(ReadData[1014], ReadData[1013]).ToString(), TwoUInt16ToFloat(ReadData[1016], ReadData[1015]).ToString(),
                    TwoUInt16ToFloat(ReadData[1018], ReadData[1017]).ToString(), TwoUInt16ToFloat(ReadData[1020], ReadData[1019]).ToString(), TwoUInt16ToFloat(ReadData[1022], ReadData[1021]).ToString(), TwoUInt16ToFloat(ReadData[1024], ReadData[1023]).ToString(), Tlight.Text,
                    TwoUInt16ToFloat(ReadData[1049], ReadData[1048]).ToString(), PressureUnit.Text, TwoUInt16ToFloat(ReadData[1039], ReadData[1038]).ToString(), LeakUnit.Text);
        }
            //条形码
            private void Code_TextChanged(object sender, EventArgs e)
        {

            Code.Focus();
            //if (Scancode.Checked==true&&Code.Text!="")
            //{
            //    System.Threading.Thread.Sleep(200);
            //    workstation = (int)yiqi.start;
            //}
            
                
            
           

            
            
            if(checkBox1.Checked==true)
            {
                if (Code.Text != "" && Code.Text.Length != Convert.ToInt32(codecheck.Text))
                {
                    MessageBox.Show("条形码长度不正确");
                    Code.ResetText();
                    Code.Focus();
                }
            }
            //if (/*Code.Text != "" ||*/Code.Text.Length!=28) //Convert.ToInt32(CodeLength.Text))
            //{
            //    MessageBox.Show("条形码长度不正确");
            //    Code.ResetText();
            //    Code.Focus();
            //}


        }

        //条形码长度验证
        private void Timer16_Tick(object sender, EventArgs e)
        {
            //Timer16.Stop();
            //if (Code.Text.Length <= Convert.ToInt32(CodeLength.Text))
            //{
            //    //TextBox2.Text = Station.Text + "05 00 D0 FF 00";
            //    ////    CrcNum();
            //    //Send();
            //    //stage = 0;
            //    //readpara = 0;
            //    //write = 0;
            //}
            //else if (Code.Text.Length > 0)
            //{
            //    MessageBox.Show("条形码长度不正确");
            //    Code.ResetText();
            //    Code.Focus();
            //}
        }

        private void 登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogOn l1 = new LogOn();
            OpenForm(l1);
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserPassword u1 = new UserPassword();
            OpenForm(u1);
        }

        private void 串口设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            configIP p1 = new configIP();
            OpenForm(p1);
        }

        private void 基本设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config c1 = new Config();
            OpenForm(c1);
        }

        private void 测试参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Timer1.Stop();
            TestPara t1 = new TestPara();
            OpenForm(t1);
        }

        private void 存储设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save s1 = new Save();
            OpenForm(s1);
        }

        private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form3 form3 = new Form3();

            OpenForm(form3);
        }

        private void 注销登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            修改密码ToolStripMenuItem.Enabled = false;
            串口设置ToolStripMenuItem.Enabled = false;
            基本设置ToolStripMenuItem.Enabled = false;
            测试参数ToolStripMenuItem.Enabled = false;
            存储设置ToolStripMenuItem.Enabled = false;
        }

        //说明帮助
        private void Manual_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Form3 form3 = new Form3();
            OpenForm(form3);
        }

        private void timer8_Tick(object sender, EventArgs e)
        {
            //progressBar2.PerformStep();
            //Timer8.Interval = 200;
        }

        //若NG控制所有定时器停止
        private void Timer9_Tick(object sender, EventArgs e)
        {
            //Timer1.Stop();
            //Timer2.Stop();
            //Timer3.Stop();
            //Timer4.Stop();

            //Timer8.Stop();

            //Timer1.Interval = 200;
            //Timer1.Start();
            //stage = 5;

            //progressBar2.Value = progressBar2.Maximum;
            //Timer9.Stop();
        }

        //防止打开多个相同的窗口
        public void OpenForm(System.Windows.Forms.Form frm)
        {
            if (frm == null) return;
            foreach (System.Windows.Forms.Form f in System.Windows.Forms.Application.OpenForms)
            {
                if (f.Name == frm.Name)
                {
                    f.Activate();
                    f.Show();
                    frm.Dispose();
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                    return;
                }
            }
            frm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            frm.Show();
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
        }

        //读取数据库设置的注册表
        private string ReadRegistryKey(string str)
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18", true);

            if (regName.GetValue(str) is null)
            {
                return null;
            }
            else
            {
                regName.OpenSubKey("User");
                string str1 = regName.GetValue(str).ToString();
                //   textBox3.Text = str1;
                regName.Close();
                return str1;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Timer1.Stop();
            //Timer2.Stop();
            //Timer3.Stop();
            //Timer4.Stop();

            //Timer8.Stop();
            //Timer9.Stop();
            //Timer10.Stop();

            //Timer16.Stop();
            //this.Hide();

            SerialPort1.Dispose();
            SerialPort1.Close();
            if (connectflag == 1)
            {
                modbusClient.ConnectClose();
            }

            this.Dispose();
            System.Environment.Exit(0);
        }

        private void Timer11_Tick(object sender, EventArgs e)
        {
            //try
            //{
            //    SendText.Text = Station.Text + " 03 01 38 00 14";
            //    Send();
            //    write = 0;
            //}
            //catch
            //{
            //    Timer11.Stop();
            //}
        }

        //public static void domain2ip()
        //{
        //    try
        //    {
        //    }
        //    catch (Exception e)
        //    {
        //    }
        //}

        //    //测试用的事件，此处调用了类里面的方法
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    //IPHostEntry ipHostInfo = Dns.GetHostEntry("http://xms.be.test.xiaomi.com/xmsapi");
        //    //IPAddress myip = ipHostInfo.AddressList[0];
        //    string ss= MESInfo.MESInformation("https://xms.be.xiaomi.com/xmsapi", "xm_1004", "1a3015121bb93b05de89128de42f98ca", "outrepair.importWRTresult", "XZCN00114", "SA", "Mi8", "3", "2021-03-22 12:10:50",
        //        "8000000022", "FAIL", "53","53","2","111","222",
        //        "32","26","86","464");
        //    MessageBox.Show(ss);
        //}

        //读取系统设置
        private void Read()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.OpenSubKey("User");
            if (regName.GetValue("port") is null)
            {
                PortNum.Text = "COM7";
            }
            else
            {
                PortNum.Text = regName.GetValue("port").ToString();
            }
            if (regName.GetValue("codeport") is null)
            {
                codeport = "COM5";
            }
            else
            {
                codeport = regName.GetValue("codeport").ToString();
            }
            


            if (regName.GetValue("codelengthcheck") is null)
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = Convert.ToBoolean(regName.GetValue("codelengthcheck").ToString());
            }

            if (regName.GetValue("Baudrate") is null)
            {
                Baudrate.Text = "9600";
            }
            else
            {
                Baudrate.Text = regName.GetValue("Baudrate").ToString();
            }

            if (regName.GetValue("station") is null)
            {
                Station.Text = "01";
            }
            else
            {
                Station.Text = regName.GetValue("station").ToString();
            }

            if (regName.GetValue("codelength") is null)
            {
                CodeLength.Text = "40";
                codecheck.Text = "40";
            }
            else
            {
                CodeLength.Text = regName.GetValue("codelength").ToString();
                codecheck.Text = regName.GetValue("codelength").ToString();
            }

            if (regName.GetValue("excel") is null)
            {
                ChkExcel.Checked = false;
            }
            else
            {
                ChkExcel.Checked = Convert.ToBoolean(regName.GetValue("excel").ToString());
            }

            if (regName.GetValue("txt") is null)
            {
                ChkTXT.Checked = false;
            }
            else
            {
                ChkTXT.Checked = Convert.ToBoolean(regName.GetValue("txt").ToString());
            }

            if (regName.GetValue("sql") is null)
            {
                ChkSql.Checked = false;
            }
            else
            {
                ChkSql.Checked = Convert.ToBoolean(regName.GetValue("sql").ToString());
            }
            if (regName.GetValue("mes") is null)
            {
                ChkMES.Checked = false;
            }
            else
            {
                ChkMES.Checked = Convert.ToBoolean(regName.GetValue("mes").ToString());
            }

            if (regName.GetValue("path") is null)
            {
                path.Text = "";
            }
            else
            {
                path.Text = regName.GetValue("path").ToString();
            }
            if (regName.GetValue("csv") is null)
            {
                ChkCSV.Checked = false;
            }
            else
            {
                ChkCSV.Checked = Convert.ToBoolean(regName.GetValue("csv").ToString());
            }

            if (regName.GetValue("url") is null)
            {
                URL.Text = "https://xms.be.xiaomi.com/xmsapi";
            }
            else
            {
                URL.Text = regName.GetValue("url").ToString();
            }

            if (regName.GetValue("appid") is null)
            {
                appid.Text = "xm_1004";
            }
            else
            {
                appid.Text = regName.GetValue("appid").ToString();
            }
            if (regName.GetValue("appkey") is null)
            {
                appkey.Text = "1a3015121bb93b05de89128de42f98ca";
            }
            else
            {
                appkey.Text = regName.GetValue("appkey").ToString();
            }
            if (regName.GetValue("method") is null)
            {
                method.Text = "outrepair.importWRTresult";
            }
            else
            {
                method.Text = regName.GetValue("method").ToString();
            }

            if (regName.GetValue("dept") is null)
            {
                Dept.Text = "";
            }
            else
            {
                Dept.Text = regName.GetValue("dept").ToString();
            }
            if (regName.GetValue("type") is null)
            {
                Type.Text = "";
            }
            else
            {
                Type.Text = regName.GetValue("type").ToString();
            }
            if (regName.GetValue("model") is null)
            {
                Machinemodel.Text = "";
            }
            else
            {
                Machinemodel.Text = regName.GetValue("model").ToString();
            }

            if (regName.GetValue("teststation") is null)
            {
                MESStation.Text = "";
            }
            else
            {
                MESStation.Text = regName.GetValue("teststation").ToString();
                regName.Close();
            }
        }

        /// <summary>
        /// 16进制格式字符串转普通文本
        /// </summary>
        /// <param name="hexString">16进制格式字符串</param>
        /// <param name="encode">编码规则</param>
        /// <returns></returns>
        public static string ToStringFromHexString(string hexString, Encoding encode)
        {
            byte[] _bytes = ToBytesFromHexString(hexString);
            //if (BitConverter.IsLittleEndian) // 若为 小端模式
            //{
            //    Array.Reverse(_bytes); // 转换为 大端模式
            //}
            return encode.GetString(_bytes);
        }


        private void SetcheckBox1()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.SetValue("codecheck", checkBox1.Checked);
            regName.Close();
        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //if (checkBox1.Checked)
            //    if (/*Code.Text != "" ||*/Code.Text.Length != Convert.ToInt32(codecheck.Text))
            //    {
            //        MessageBox.Show("条形码长度不正确");
            //        Code.ResetText();
            //        Code.Focus();
            //    }
            SetcheckBox1();
        }
        private void Setcodecheck()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.SetValue("codecheck", codecheck.Text);
            regName.Close();
        }
        private void codecheck_TextChanged(object sender, EventArgs e)
        {
            Setcodecheck();
        }


        private void SetScancode()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.SetValue("Scancode", Scancode.Checked);
            regName.Close();
        }




        private void Scancode_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void label29_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("确定要清空计数吗？", "确认", MessageBoxButtons.YesNo);

            // 如果用户点了“确定”按钮，则执行某些事件
            if (dialogResult == DialogResult.Yes)
            {
                Sunzong.Text = "0";
                Passzong.Text = "0";
                ChanPass = 0;
                ChanSum = 0;
                string path = System.Environment.CurrentDirectory + "\\Config\\Config.ini";

                ConfigINI config = new ConfigINI(path);
                config.IniWriteValue("Config", "Sunzong", Sunzong.Text);
                config.IniWriteValue("Config", "Passzong", Passzong.Text);
            }
        }

        private void label36_Click(object sender, EventArgs e)
        {

        }
        string stationIP;
        string ipAddress;

        private void TCPconnect_Click(object sender, EventArgs e)
        {
            

           //根据:符号分割站号和IP
            string[] parts = UDPResults.Text.Split(':');

            // 确保分割结果符合预期
            if (parts.Length == 2)
            {
                // 站号
                 stationIP = parts[0];

                // IP 地址
                ipAddress = parts[1];
                

                modbusClient = new ModbusRtuOverTcp(ipAddress, 9999, Convert.ToByte(stationIP));
                //modbusClient.ConnectTimeOut = 1000;
                //modbusClient.ReceiveTimeOut = 1000;
                if (modbusClient.ConnectServer().IsSuccess)
                {
                    connectflag = 1;
                    TCPconnect.Enabled = false;
                    PortNum.Text = modbusClient.IpAddress;
                    label6.Text = modbusClient.Port.ToString();
                    label6.ForeColor = Color.Green;
                    station2 = Convert.ToUInt16(stationIP);
                    station = station2.ToString("X2");
                    Modbusread(360, 4, ReadData);
                    labelruanjian.Text = "软件版本号:" + ReadData[361].ToString("X4") + ReadData[360].ToString("X4");
                    labelyinjian.Text = "硬件版本号:" + ReadData[363].ToString("X4") + ReadData[362].ToString("X4");

                }

            }
            else
            {
               MessageBox.Show("连接格式不正确");
            }
        }

        private void timerbar_Tick(object sender, EventArgs e)
        {
            Invoke(new Action(() =>
            {
                progressBar1.Value += 1;
            }));
           
        }

        OperateResult changestation=new OperateResult();
       public static string station;

        public static ushort station2;

        private void button2_Click(object sender, EventArgs e)
        {
            station2 = Convert.ToUInt16(zhanhao.Text);
            modbusClient.Read("0", (ushort)1);
            changestation =modbusClient.Write("1076", station2);
            if (changestation.IsSuccess)
            {
                
                station = station2.ToString("X2");
                connectflag = 0;
                modbusClient.ConnectClose();
                Thread.Sleep(200);
                modbusClient = new ModbusRtuOverTcp(ipAddress, 9999, Convert.ToByte(station2));
                Thread.Sleep(200);
                if (modbusClient.ConnectServer().IsSuccess)
                {
                    connectflag = 1;
                    TCPconnect.Enabled = false;
                    PortNum.Text = modbusClient.IpAddress;
                    label6.Text = modbusClient.Port.ToString();
                    UDPResults.Text = station2.ToString() + ":" + modbusClient.IpAddress;
                    label6.ForeColor = Color.Green;

                    MessageBox.Show("仪器站号修改为" + station2);
                }
            }
        }

        private void label28_Click(object sender, EventArgs e)
        {
            try
            {

                OperateResult<byte[]> read = modbusClient.ReadFromCoreServer(HslCommunication.BasicFramework.SoftBasic.HexStringToBytes("01 03 00 00 00 03"));
                if (read.IsSuccess)
                {
                    Code.Text = "结果：" + HslCommunication.BasicFramework.SoftBasic.ByteToHexString(read.Content, ' ');
                }
                else
                {
                    MessageBox.Show("读取失败：" + read.ToMessageShowString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取失败：" + ex.Message);
            }
        }

        private void UDPRead_Tick(object sender, EventArgs e)
        {
            UDPRead.Stop();
            UDP_Parse();
        }
        public void UDP_Parse()
        {
            
                if (!String.IsNullOrEmpty(UDPRecvData))
                {
                  
                }
           
        }

        private void UDPOverTime_Tick(object sender, EventArgs e)
        {
            isListening = false;
        }

        private void CodePort1_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {

        }

        /// <summary>
        /// 16进制格式字符串转字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] ToBytesFromHexString(string hexString)
        {
            //以 ' ' 分割字符串，并去掉空字符
            string[] chars = hexString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] returnBytes = new byte[chars.Length];

            //逐个字符变为16进制字节数据
            for (int i = 0; i < chars.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(chars[i], 16);
            }
            // byte[] ss= returnBytes.Reverse().ToArray();

            return returnBytes;
        }
    }
}