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.XSSF.UserModel; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; using System.Runtime.InteropServices; using DHDMesApi; using DHDMesApi.Data; namespace C_Windows_1 { public partial class Form1 : Form { // Token: 0x06000003 RID: 3 [DllImport("ATS_Station_Managment.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int ATS_SelectTestYorN_Batch_LineName(string MainSN, string ATSStationName, string MaterialCode, string Batch, string LineName, string Value2, string Value3, out char TestYorN); // Token: 0x06000004 RID: 4 [DllImport("ATS_Station_Managment.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int ATS_InsertDataRow_JIG_V2(string strlinename, string strbatch, string strlocation, string strstation, string strsn, int iresult, string errorinfo, string JIG_Number, string strswversion, string strremark, string strkeys, string strvalues); 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"; //泄漏量 private string DPressureDiff = "0"; //压差 public OperateResult operateResult21; public OperateResult operateResult22; public OperateResult operateResult23; public ModbusRtu CH1 = new ModbusRtu(); //产测计数 public string codeBaudrate; public int ChanSum; public int ChanPass; public static UInt16[] ReadData = new UInt16[1000]; public string codeport; public static int TIME; //已经使用时间 public static int timeflag = 0; public static int Stipulatetime;//规定时间 public static string tablename; string CODE; public bool checkINI; //选中ini导出 public bool checkTxt; //选中txt导出 //得辉达MES信息 public string strURL = "http://192.168.1.21:8080/PlMesRf/RfEntry.jws?wsdl"; //MES服务器地址 public string productionOrder = ""; //生产工单 public string lineNumber = ""; //产线编号 public string processNumber = ""; //工序号 public string tester = ""; //测试员 public string machineNumber = ""; //测试设备编号 public Form1() { f1 = this; InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } //窗口自适应分辨率 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 reslutget; reslutget = CH1.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 存入数组 /// /// ////////////////// /// /// /// /// public OperateResult Modbusread(int sta, int number, UInt16[] shangweiji) { try { int start = number; OperateResult reslutget; reslutget = CH1.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; } } 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.Open(); X.ReceiveTimeout = 300; } catch (Exception ex) { MessageBox.Show(ex.Message); label6.Text = "未连接"; } } public void machine2()//主要负责测试数据读取,写入 { //Invoke((new System.Action(() => switch (workstation) { case (int)yiqi.start: operateResult22 = CH1.WriteCoil("208", true); if (operateResult22.IsSuccess) { workstation = (int)yiqi.prepare; } break; //return workstation; case (int)yiqi.rst: //byte[] data2 = new byte[] { 0xff, 0x00 }; operateResult21 = CH1.WriteCoil("86", 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; //return workstation; case (int)yiqi.prepare://读取检测时间,充气,平衡检测 //扫码枪处理 上传 Code.Enabled = false; ReadData[9] = 0; operateResult21 = Modbusread(25, 6, ReadData); Tlight.Text = ""; CODE= Code.Text; if (operateResult21.IsSuccess == true) { int aaa; aaa = ReadData[25] + ReadData[26] + ReadData[27] + ReadData[28] + ReadData[30]; progressBar2.Value = 0; progressBar2.Maximum = aaa; Modbusread(8, 1, ReadData); if (operateResult21.IsSuccess == true) { if(ReadData[8]!=0) { workstation = (int)yiqi.test; } else { workstation = (int)yiqi.standby; } } } break; //return workstation; case (int)yiqi.test://读取检测数据以及判断仪器是否结束 //operateResult21=Modbusread(170, 23, ReadData); Modbusread(8, 2, ReadData); Modbusread(16, 4, ReadData); Modbusread(25, 12, ReadData); Modbusread(37, 1, ReadData); Modbusread(38, 12, ReadData); Modbusread(161, 2, ReadData); //test(ReadData); int ba = progressBar2.Value + 2; if (ba >= progressBar2.Maximum) ba = progressBar2.Maximum; progressBar2.Value = ba; MachineStatus.Text = "测试中"; //泄漏量 if (ReadData[19] !=0 || ReadData[18] != 0) { DLeak = TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f1"); } //压差 if (ReadData[161] != 0 || ReadData[162] != 0) { DPressureDiff = TwoUInt16ToFloat(ReadData[162], ReadData[161]).ToString("f3"); } if (ReadData[8] == 0) { System.Threading.Thread.Sleep(200); Modbusread(8, 2, ReadData); if (ReadData[9] == 1 || ReadData[9] == 2) { workstation = (int)yiqi.finish; } else { progressBar2.Value = 0; workstation = (int)yiqi.standby; DLeak = "0.0"; DPressureDiff = "0.000"; } } break; case (int)yiqi.standby://读取仪器是否启动 Modbusread(8, 2, ReadData); MachineStatus.Text = "待机中"; if (ReadData[8] != 0 && ReadData[9] == 0) { workstation = (int)yiqi.prepare; } break; case (int)yiqi.finish: Modbusread(16, 4, ReadData); progressBar2.Value = progressBar2.Maximum; DataGridView1.Invoke(new System.Action(Display)); //Display(); CreateFile(); //UpMES(1); Code.Clear(); CODE = ""; Code.Enabled = true; Code.Focus(); workstation = (int)yiqi.standby; 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.WriteCoil("540", true); //MachineStatus.Text = "开始测试"; ////Console.WriteLine("当前是启动状态"); if (operateResult22.IsSuccess) { // operateResult22 = CH1.WriteCoil("85", false); workstation = (int)yiqi.prepare; } break; //return workstation; case (int)yiqi.rst: operateResult21 = CH1.WriteCoil("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; 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 = "待机中"; Code.Enabled = true; // Tlight.Text = ""; break; case (int)yiqi.prepare://把状态文本改成文本 Tlight.Text = ""; //CH1Tlight.Text = ""; //CH1Tlight.BackColor = Color.White; textBox3.Text = ""; textBox3.BackColor = Color.White; //button1.BackColor = Color.White; //button2.BackColor = Color.White; //button3.BackColor = Color.White; //button4.BackColor = Color.White; break; case (int)yiqi.test: MachineStatus.Text = "测试中"; /* //bool flag = Form1.ReadData[8] == 2; //if (flag) //{ // this.Invoke(new Action(() => this.button1.BackColor = Color.Yellow)); // //this.button1.BackColor = Color.Yellow; //} //else //{ // this.Invoke(new Action(() => this.button1.BackColor = Color.White)); // //button1.BackColor = Color.White; //} //bool flag2 = Form1.ReadData[8] == 3; //if (flag2) //{ // this.Invoke(new Action(() => this.button2.BackColor = Color.Yellow)); // //this.button2.BackColor = Color.Yellow; //} //else //{ // this.Invoke(new Action(() => this.button2.BackColor = Color.White)); // //this.button2.BackColor = Color.White; //} //bool flag3 = Form1.ReadData[8] == 4; //if (flag3) //{ // this.Invoke(new Action(() => this.button3.BackColor = Color.Yellow)); // //this.button3.BackColor = Color.Yellow; //} //else //{ // this.Invoke(new Action(() => this.button3.BackColor = Color.White)); // //this.button3.BackColor = Color.White; //} //bool flag4 = Form1.ReadData[8] == 5; //if (flag4) //{ // this.Invoke(new Action(() => this.button4.BackColor = Color.Yellow)); // //this.button4.BackColor = Color.Yellow; //} //else //{ // this.Invoke(new Action(() => this.button4.BackColor = Color.White)); // //this.button4.BackColor = Color.White; //} */ //判断单位 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 = "sccm"; break; case 4: LeakUnit.Text = "CCM/S"; break; case 5: LeakUnit.Text = "Pa/s"; break; } if (ReadData[9] == 2) { //Tlight.Enabled = true; //Tlight.Visible = true; Tlight.Text = "NG"; Tlight.ForeColor = Color.Red; //this.CH1Tlight.Text = "NG"; //this.CH1Tlight.BackColor = Color.Red; //this.Invoke(new Action(() => this.CH1Tlight.BackColor = Color.Red)); } if (ReadData[9] == 1) { Tlight.Text = "OK"; Tlight.ForeColor = Color.Green; //this.CH1Tlight.Text = "OK"; //this.CH1Tlight.BackColor = Color.Green; //this.Invoke(new Action(() => this.CH1Tlight.BackColor = Color.Green)); } //CH1文本框读取的压力和泄漏量 LeakPressure.Text = TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString("f3"); Leak.Text = TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f1"); break; case (int)yiqi.finish: //progressBar2.Value = progressBar2.Maximum; if (ReadData[9] == 2) { //ChanSum++; Tlight.Text = "NG"; Tlight.ForeColor = Color.Red; //this.Invoke(new Action(() => button3.BackColor = Color.Red)); //button3.BackColor = Color.Red; } if (ReadData[9] == 1) { //ChanPass++; //ChanSum++; Tlight.Text = "OK"; Tlight.ForeColor = Color.Green; } LeakPressure.Text = TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString("f3"); Leak.Text = TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f1"); 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"; if (File.Exists(path)) { ConfigINI config = new ConfigINI(path); this.JIG_Number1.Text = config.IniReadValue("Mes", "JIG_Number1"); this.strlinename.Text = config.IniReadValue("Mes", "strlinename"); this.strbatch.Text = config.IniReadValue("Mes", "strbatch"); this.strlocation.Text = config.IniReadValue("Mes", "strlocation"); this.strbatch.Text = config.IniReadValue("Mes", "strbatch"); this.strstation.Text = config.IniReadValue("Mes", "strstation"); } } 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); } } //窗口初始化 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 = ""; CH1Tlight.Text = ""; CH1Tlight.BackColor = Color.White; button1.BackColor = Color.White; button2.BackColor = Color.White; button3.BackColor = Color.White; button4.BackColor = Color.White; pictureBox1.BackColor = Color.Green; //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(); try { Form1.f1.ModbusRtuint(Form1.f1.CH1, Convert.ToByte(Station.Text),/* "COM19"*/PortNum.Text, Convert.ToInt32(Baudrate.Text), 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None); } catch (Exception ex) { MessageBox.Show(ex.Message); } if (Form1.f1.CH1.IsOpen()) { BtnCon1.Enabled = false; label6.Text = "已连接"; label6.ForeColor = Color.Green; } //if (CeckScanning.Checked){ // try // { // CodePort1.PortName = codeport; // CodePort1.BaudRate = int.Parse(codeBaudrate); // CodePort1.DataBits = 8; // CodePort1.StopBits = System.IO.Ports.StopBits.One; // CodePort1.Parity = System.IO.Ports.Parity.None; // CodePort1.Open(); // } // catch (Exception ex) // { // MessageBox.Show(ex.Message); // } //} Task.Run(() => { workstation = (int)yiqi.standby; while (true) { machine2();//仪器读取线程 MachineDisplay();//仪器显示线程 } } ); } public void ReadTIME() { 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("使用天数") is null) { Stipulatetime = 144;//三天的时间 } else { Stipulatetime = Convert.ToInt32(regName.GetValue("使用天数")); } TIME = Convert.ToInt32(regName.GetValue("time")); timeflag = Convert.ToInt32(regName.GetValue("timeflag")); regName.Close(); } //点击“连接串口”按钮,连接串口 private void BtnCon1_Click(object sender, EventArgs e) { try { Form1.f1.ModbusRtuint(Form1.f1.CH1, Convert.ToByte(Form1.f1.Station.Text), PortNum.Text, Convert.ToInt32(Baudrate.Text), 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None); if (CH1.IsOpen() is true) { label6.Text = "已连接"; label6.ForeColor = Color.Green; BtnCon1.Enabled = false; //Timer1.Interval = 800; //Timer1.Start(); //stage = 1; } // label7.Text = SerialPort1.IsOpen.ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } //关闭串口 private void BtnBreak_Click(object sender, EventArgs e) { try { if(CH1.IsOpen()) { CH1.Close(); } if (CH1.IsOpen() is false) { label6.Text = "未连接"; label6.ForeColor = Color.Red; BtnCon1.Enabled = true; } } 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().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) { bool bStart = true; try { //检测设备是否已过站 if (checkBox2.Checked) { bStart = MesCheck(Code.Text); } if (bStart) { workstation = (int)yiqi.start; } } 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) { TIME++; if (TIME >= Stipulatetime) { Timer1.Stop(); this.Hide(); Activationcode atc = new Activationcode(); atc.ShowDialog(); } } //读参数 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 //{ // Timer3.Stop(); // if (checkBox1.Checked == true) // { // if (Code.Text != "" && Code.Text.Length != Convert.ToInt32(codecheck.Text)) // { // MessageBox.Show("条形码长度不正确"); // Code.Clear(); // Code.Focus(); // } // } //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} } //控制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.Clear(); Code.Focus(); Code.Enabled = 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; } private void AddExcel2() { try { 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") + ".xls"; } else { FileName = path.Text + "\\" + "leaktest" + Date + ".xls"; } if (File.Exists(FileName)) { FileStream file = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite); HSSFWorkbook workbook = new HSSFWorkbook(file); ISheet sheet = workbook.GetSheet("Sheet1"); int startRow = sheet.LastRowNum + 1; IRow newRow = sheet.CreateRow(startRow); string[] data = new string[] { DateTime.Now.ToString(),CODE, 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("f1") , 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 { // 如果文件不存在,则创建文件并添加数据 HSSFWorkbook workbook = new HSSFWorkbook(); 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[] { DateTime.Now.ToString(),CODE, 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("f1") , LeakUnit.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(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void AddExcel() { if (path.Text.Length == 0) { path.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } string FileDialog = path.Text; //创建文件夹 if(!Directory.Exists(FileDialog))//如果不存在就创建file文件夹 { Directory.CreateDirectory(FileDialog); } string file = DateTime.Now.ToString("yyyyMMdd"); string FileName = FileDialog + "\\" + file+"测试记录" + ".xlsx"; string filepath; filepath = FileName; Excel.Application xapp = new Excel.Application(); if (!File.Exists(filepath))//判断所选路径是否有文件 { //若不存在该文件,则创建新文件 var str1 = new Microsoft.Office.Interop.Excel.Application(); Excel.Workbooks xbook1 = str1.Workbooks; Excel.Workbook xbook2 = str1.Workbooks.Add(true); xbook2.SaveAs(filepath);//按照指定路径存储新文件 xbook2.Close(); } //若存在该文件,则打开文件并写入数据 Excel.Workbook xbook = xapp.Workbooks._Open(filepath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); Excel.Worksheet xsheet = (Excel.Worksheet)xbook.Sheets[1]; string nowdate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); //string[] fieldArr = { "时间", "条形码", "充气时间", "平衡时间", "检测时间", "排气时间", "充气压力上限", "充气压力下限", "大漏压差上限", "大漏压差下限", "泄漏量上限", "泄漏量下限", "测试结果", "测试压力", "压力单位", "泄漏量", "泄漏量单位" };//列名 //string[] dataArr = { DateTime.Now.ToString(), Code.Text, FullTime.Text + "s", BalanTime.Text + "s", TestTime1.Text + "s", ExhaustTime.Text + "s", FPtoplimit.Text + PressureUnit.Text, FPlowlimit.Text + PressureUnit.Text, BLeakTPre.Text + "Pa", BLeakLPre.Text + "Pa", Leaktoplimit.Text + LeakUnit.Text, Leaklowlimit.Text + LeakUnit.Text, Tlight.Text, DLeakPressure, PressureUnit.Text, DLeak, LeakUnit.Text }; //行名 string[] fieldArr = { "时间", "条形码", "充气时间", "平衡时间", "检测时间", "排气时间", "充气压力上限", "充气压力下限", "大漏压差上限", "大漏压差下限", "泄漏量上限", "泄漏量下限", "测试结果", "测试压力", "压力单位", "泄漏量", "泄漏量单位" };//列名 //string[] fieldArr = { I18N.GetLangText(dicLang, "时间"), I18N.GetLangText(dicLang, "条形码"), I18N.GetLangText(dicLang, "充气时间"), I18N.GetLangText(dicLang, "平衡时间"), I18N.GetLangText(dicLang, "检测时间"), I18N.GetLangText(dicLang, "排气时间"), // I18N.GetLangText(dicLang, "充气压力上限"), I18N.GetLangText(dicLang, "充气压力下限"), I18N.GetLangText(dicLang, "大漏压差上限"), I18N.GetLangText(dicLang, "大漏压差下限"), // I18N.GetLangText(dicLang, "泄漏量上限") , I18N.GetLangText(dicLang, "泄漏量下限"),I18N.GetLangText(dicLang, "测试结果"), I18N.GetLangText(dicLang, "测试压力"), I18N.GetLangText(dicLang, "压力单位"), I18N.GetLangText(dicLang, "泄漏量"), // I18N.GetLangText(dicLang, "泄漏量单位") };//列名 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}; int c = xsheet.UsedRange.Rows.Count; // label1.Text = c.ToString(); int a; for (a = 0; a < fieldArr.Length; a++) { xsheet.Cells[a + 1][1] = fieldArr[a]; } int b; // int j; for (b = 0; b < dataArr.Length; b++) { Excel.Range cell = (Excel.Range)xsheet.Cells[b + 1][c + 1]; cell.NumberFormat = "@"; xsheet.Cells[b + 1][c + 1] = dataArr[b];//将数据插入 } // string result="40"; // xsheet.Cells[1][1] = result; xbook.Save(); xsheet = null; xbook.Close(); xapp.DisplayAlerts = false; xapp.Quit(); xapp = null; GC.Collect(); } /// /// 添加配置文件 /// /// 0:INI; 1:TXT private void AddINI(int iType = 0) { try { // 文件路径 // string basePath = string.IsNullOrEmpty(path.Text) ? Environment.GetFolderPath(Environment.SpecialFolder.Desktop) : path.Text; //桌面 string basePath = string.IsNullOrEmpty(path.Text) ? Application.StartupPath : path.Text; string logDirectory = Path.Combine(basePath, "MES"); Directory.CreateDirectory(logDirectory); // 文件名 string fileName = $"{CODE}_{DateTime.Now:yyMMdd_HHmmss}."; fileName += iType == 0 ? "ini" : "txt"; string fullPath = Path.Combine(logDirectory, fileName); string testResult = Tlight.Text; if(string.IsNullOrEmpty(testResult.Trim())) { testResult = "fail"; } // INI内容 StringBuilder iniContent = new StringBuilder(); iniContent.AppendLine("[Info]"); iniContent.AppendLine($"sn={CODE} ");//#SN号码 iniContent.AppendLine($"type= ");//#当前工站名称 //iniContent.AppendLine("wifi_mac= ");//#wifimac //iniContent.AppendLine("bt_mac= "); //#btmac string testDetails = $"检测压力={TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString()};" + $"充气时间={ReadData[25] / 10.0 + "s"};" + $"平衡时间={ReadData[26] / 10.0 + "s"};" + $"检测时间={ReadData[27] / 10.0 + "s"};" + $"排气时间={ReadData[28] / 10.0 + "s"};" + $"当前压差={DPressureDiff};" + $"泄露量={DLeak};"; // TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString("f1") iniContent.AppendLine($"message={testDetails}");//#测试项目与结果记录 float totalTime = (ReadData[25] + ReadData[26] + ReadData[27] + ReadData[28]) / 10.0f; iniContent.AppendLine($"totaltime={totalTime}"); //#测试所用时间 iniContent.AppendLine($"starttime={DateTime.Now:yyyy/MM/dd HH:mm:ss}");// #开始时间 iniContent.AppendLine($"endtime={DateTime.Now.AddSeconds(totalTime):yyyy/MM/dd HH:mm:ss} ");//#结束时间 iniContent.AppendLine($"result={testResult}");//#Pass or Fail // 7. 写入文件 File.WriteAllText(fullPath, iniContent.ToString(), Encoding.UTF8); } catch (Exception ex) { MessageBox.Show($"生成日志失败:{ex.Message}"); } } //将数据写入数据库 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=('{tablename}')"; SqlCommand cmd2 = new SqlCommand(selectString2, con2); var str2 = cmd2.ExecuteScalar(); if (str2 is null) { //若没有表格则新建表格 cmd2.CommandText = $"CREATE TABLE {tablename} ([时间] 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(); } //往表格插入数据 cmd2.CommandText = $"INSERT INTO {tablename} (时间, 条形码, 充气时间, 平衡时间, 检测时间," + " 排气时间, 充气压力上限, 充气压力下限, 大漏压差上限, 大漏压差下限, 泄漏量上限, 泄漏量下限, 测试结果, 测试压力, 压力单位, 泄漏量, 泄漏量单位) 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.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); // MessageBox.Show(this, ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); 强制置顶 } } //写入数据 private void CreateFile() { //if (ChkExcel.Checked) //{ // AddExcel2(); //} //Console.WriteLine("ChkTXT.Checked:" + ChkTXT.Checked); //Console.WriteLine("ChkINI:" + ChkINI); if (checkTxt) { AddINI(1); } if(checkINI) { AddINI(0); } //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[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); DataGridViewRow row = new DataGridViewRow(); row.CreateCells(DataGridView1); row.SetValues( DateTime.Now.ToString(), CODE, (ReadData[25] / 10.0).ToString() + "s", (ReadData[26] / 10.0).ToString() + "s", (ReadData[27] / 10.0).ToString() + "s", (ReadData[28] / 10.0).ToString() + "s", TwoUInt16ToFloat(ReadData[33], ReadData[32]).ToString() + PressureUnit.Text, TwoUInt16ToFloat(ReadData[47], ReadData[46]).ToString() + PressureUnit.Text, ReadData[36].ToString()+"Pa", Digitalconversion(ReadData[37]).ToString()+"Pa", TwoUInt16ToFloat(ReadData[39], ReadData[38]).ToString()+ LeakUnit.Text, TwoUInt16ToFloat(ReadData[45], ReadData[44]).ToString() + LeakUnit.Text, Tlight.Text, TwoUInt16ToFloat(ReadData[17], ReadData[16]).ToString() + PressureUnit.Text, PressureUnit.Text, TwoUInt16ToFloat(ReadData[19], ReadData[18]).ToString() + LeakUnit.Text, LeakUnit.Text ); // 将新行插入到第一行位置 DataGridView1.Rows.Insert(0, row); } //条形码 private void Code_TextChanged(object sender, EventArgs e) { if (Code.Text.Length > 0) { timerCH1.Stop(); timerCH1.Start(); } } //条形码长度验证 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) { PortSetting p1 = new PortSetting(); 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) { 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("time", TIME); regName.SetValue("timeflag", 1); regName.Close(); Timer1.Stop(); Timer2.Stop(); Timer3.Stop(); Timer4.Stop(); Timer8.Stop(); Timer9.Stop(); Timer10.Stop(); Timer16.Stop(); this.Hide(); SerialPort1.Dispose(); SerialPort1.Close(); 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 = "COM2"; } else { PortNum.Text = regName.GetValue("port").ToString(); } if (regName.GetValue("codeport") is null) { codeport = "COM1"; } else { codeport = regName.GetValue("codeport").ToString(); } if (regName.GetValue("codeBaudrate") is null) { codeBaudrate = "9600"; } else { codeBaudrate = regName.GetValue("codeBaudrate").ToString(); } if (regName.GetValue("codelengthcheck") is null) { checkBox1.Checked = true; } else { checkBox1.Checked = Convert.ToBoolean(regName.GetValue("codelengthcheck")); } if (regName.GetValue("codeRepeatCheck") is null) { checkCodeRepeat.Checked = true; } else { checkCodeRepeat.Checked = Convert.ToBoolean(regName.GetValue("codeRepeatCheck")); } if (regName.GetValue("codeTestCheck") is null) { checkBox2.Checked = true; } else { checkBox2.Checked = Convert.ToBoolean(regName.GetValue("codeTestCheck")); } 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 = "21"; codecheck.Text = "21"; } 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) { checkTxt = false; } else { checkTxt = Convert.ToBoolean(regName.GetValue("txt").ToString()); } if (regName.GetValue("ini") is null) { checkINI = false; } else { checkINI = Convert.ToBoolean(regName.GetValue("ini").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(); } if (regName.GetValue("CeckScanning") is null) { CeckScanning.Checked = false; } else { CeckScanning.Checked = Convert.ToBoolean(regName.GetValue("CeckScanning").ToString()); } //读取MES信息 var regVal = regName.GetValue("productionOrder"); if (regVal != null) { productionOrder = regVal.ToString(); } regVal = regName.GetValue("processNumber"); if (regVal != null) { processNumber = regVal.ToString(); } regVal = regName.GetValue("machineNumber"); if (regVal != null) { machineNumber = regVal.ToString(); } regVal = regName.GetValue("lineNumber"); if (regVal != null) { lineNumber = regVal.ToString(); } regVal = regName.GetValue("tester"); if (regVal != null) { tester = regVal.ToString(); } regVal = regName.GetValue("URL"); if (regVal != null) { strURL = regVal.ToString(); } regName.Close(); } /// /// 16进制格式字符串转普通文本 /// /// 16进制格式字符串 /// 编码规则 /// public static string ToStringFromHexString(string hexString, Encoding encode) { byte[] _bytes = ToBytesFromHexString(hexString); //if (BitConverter.IsLittleEndian) // 若为 小端模式 //{ // Array.Reverse(_bytes); // 转换为 大端模式 //} return encode.GetString(_bytes); } /// /// 打开注册表 SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set /// private RegistryKey openRegedit() { 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"); } return regName; } 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(); // } RegistryKey regName; regName = openRegedit(); regName.SetValue("codelengthcheck", checkBox1.Checked); regName.Close(); } 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("codelength", 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 CodePort1_DataReceived_1(object sender, SerialDataReceivedEventArgs e) { try { System.Threading.Thread.Sleep(50); int len = CodePort1.BytesToRead;//获取可以读取的字节数 if (len > 1) { byte[] buff = new byte[len];//创建缓存数据数组 CodePort1.Read(buff, 0, len);//把数据读取到buff数组 Invoke((new System.Action(() => //接收计数 { string code = Encoding.Default.GetString(buff); string CODE = code.Replace("\r", ""); CODE = CODE.Replace("\n", ""); if (Code.Text == "") { Code.Text = CODE; } CodePort1.DiscardInBuffer(); } ))); } else { return; } } catch (Exception ex) { MessageBox.Show(":" + ex.Message); } } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void Code_TextAlignChanged(object sender, EventArgs e) { } private void label32_Click(object sender, EventArgs e) { AddDatebase(); } private void button1_Click_1(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { if (checkBox2.Checked) { pictureBox1.BackColor = Color.Green; } else { pictureBox1.BackColor = Color.Red; } RegistryKey regName; regName = openRegedit(); regName.SetValue("codeTestCheck", checkBox2.Checked); regName.Close(); } private void strlinename_TextChanged(object sender, EventArgs e) { string path = System.Environment.CurrentDirectory + "\\Config\\Config"; ConfigINI config = new ConfigINI(path); config.IniWriteValue("Mes", "strlinename", this.strlinename.Text); } private void strlocation_TextChanged(object sender, EventArgs e) { string path = System.Environment.CurrentDirectory + "\\Config\\Config"; ConfigINI config = new ConfigINI(path); config.IniWriteValue("Mes", "strlocation", this.strlocation.Text); } private void strbatch_TextChanged(object sender, EventArgs e) { string path = System.Environment.CurrentDirectory + "\\Config\\Config"; ConfigINI config = new ConfigINI(path); config.IniWriteValue("Mes", "strbatch", this.strbatch.Text); } private void strstation_TextChanged(object sender, EventArgs e) { string path = System.Environment.CurrentDirectory + "\\Config\\Config"; ConfigINI config = new ConfigINI(path); config.IniWriteValue("Mes", "strstation", this.strstation.Text); } private void JIG_Number1_TextChanged(object sender, EventArgs e) { string path = System.Environment.CurrentDirectory + "\\Config\\Config"; ConfigINI config = new ConfigINI(path); config.IniWriteValue("Mes", "JIG_Number1", this.JIG_Number1.Text); } private async void timer5_Tick(object sender, EventArgs e) { timerCH1.Stop(); bool flag = this.codecheck.Text == ""; if (flag) { this.codecheck.Text = "21"; } //条码长度检测 if (checkBox1.Checked && this.Code.TextLength != int.Parse(this.CodeLength.Text)) { MessageBox.Show(string.Format("条形码长度错误!当前条码长度:{0},设置长度为:{1}", this.Code.Text.Length, this.CodeLength.Text)); this.Code.ResetText(); this.Code.Focus(); } //条码重复检测 if (checkCodeRepeat.Checked) { int Count = BarcodeInfo.QueryBarcodeCount(Code.Text); if (Count > 0) { this.Code.ResetText(); this.Code.Focus(); MessageBox.Show("条形码重码,请检查"); } if (Code.TextLength == int.Parse(this.CodeLength.Text)) { string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); BarcodeInfo.InsertBarcodeData(time, Code.Text, "", "", "", "", "", ""); } } } public async Task InMes(int CH) { //测试上传 try { bool flag = CH == 1; string text; string text2; string text3; string text4; string text5; text = this.Code.Text; text2 = this.strstation.Text; text3 = this.strlocation.Text; text4 = this.strbatch.Text; text5 = this.strlinename.Text; char c; /*int obj =*/ return await Task.Run(() => ATS_SelectTestYorN_Batch_LineName(text, text2, text3, text4, text5, "NA", "NA", out c)); } catch (Exception ex) { MessageBox.Show(ex.Message); return 0; } } public void UpMES(int CH) { try { bool flag = CH == 1; string text; string text2; string text3; string text4; string text5; string text6; string text7; string text8; string text9; int iresult; string text10; string text11; text = this.strlinename.Text; text2 = this.strbatch.Text; text3 = this.strlocation.Text; text4 = this.strstation.Text; text5 = CODE; text6 = "LL18"; text7 = "result"; text8 = string.Concat(new string[] { "'", CODE, "','", this.LeakPressure.Text, this.PressureUnit.Text, "''", this.Leak.Text, this.LeakUnit.Text, "'" }); text9 = "ONE,H0H,H1H"; bool flag2 = this.Tlight.Text == "OK"; if (flag2) { iresult = 1; text10 = "NA"; text11 = this.JIG_Number1.Text; } else { iresult = 0; text10 = "泄漏量"; text11 = this.JIG_Number1.Text; } //bool @checked = this.checkBox1.Checked; if (checkBox2.Checked) { object obj = ATS_InsertDataRow_JIG_V2(text, text2, text3, text4, text5, iresult, text10, text11, text6, text7, text9, text8); bool flag5 = obj.ToString() == "0"; if (flag5) { this.textBox3.Text = "OK " + obj.ToString(); this.textBox3.BackColor = Color.Green; } else { this.textBox3.Text = "NG -1"; this.textBox3.BackColor = Color.Red; } this.log.Logmsg(string.Concat(new string[] { DateTime.Now.ToString(), " ", text, ",", text2, ",", text3, ",", text4, ",", text5, ",", iresult.ToString(), ",", text10, ",", text11, ",", text6, ",", text7, ",", text9, ",", text8 })); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void Form1_Activated(object sender, EventArgs e) { Code.Focus(); } private void label33_Click(object sender, EventArgs e) { //CreateFile(); } private void checkCodeRepeat_CheckedChanged(object sender, EventArgs e) { RegistryKey regName; regName = openRegedit(); regName.SetValue("codeRepeatCheck", checkCodeRepeat.Checked); regName.Close(); } private void mESSetToolStripMenuItem_Click(object sender, EventArgs e) { MESConfig mes = new MESConfig(); mes.productionOrder.Text = productionOrder; mes.processNumber.Text = processNumber; mes.machineNumber.Text = machineNumber; mes.lineNumber.Text = lineNumber; mes.tester.Text = tester; mes.URL.Text = strURL; OpenForm(mes); } /// /// 16进制格式字符串转字节数组 /// /// /// 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; } //过站检测 private bool MesCheck(string sCode) { //string sData = processNumber + "@" + lineNumber + "@" + processNumber + "@" + // tester + "@" + machineNumber + "@" + sCode; //string sResponse = MESInfo.HttpPost(strURL, sData); string sResponse = ""; try { sResponse = DHDMes_IFLYTEK_Data.GetAllData(sCode); } catch (Exception e) { Console.WriteLine(e); sResponse = e.Message; } textBox3.Text = sResponse; return sResponse.Contains("OK"); } } }