using Microsoft.Win32; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Threading; using System.Windows.Forms; using System.Xml; using System.Text; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.IO.Ports; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Windows.Media.Media3D; using System.Runtime.InteropServices; namespace FileWatcher { public partial class AutoMakeQTYRZ : Form { DataHelper dh; DataTable dt; DataTable DB; /// /// 用户编号 /// string iusercode; /// /// 岗位资源 /// string isource; Thread InitDB; /// 当前工序 /// string istepcode; StringBuilder sql = new StringBuilder(); /// /// 缓存的文件 /// public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml"; /// /// 缓存的文件夹 /// public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/"; ftpOperater ftp = new ftpOperater(); public AutoMakeQTYRZ() { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; } DataTable Dbfind; string IPAddress = ""; bool writedata = true; private void nr_rule_DBChange(object sender, EventArgs e) { Dbfind = li_code.ReturnData; BaseUtil.SetFormValue(this.Controls, Dbfind); } private void Form1_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; InitDB = new Thread(ConnectDB); SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序"); stw.StartPosition = FormStartPosition.CenterScreen; stw.ShowDialog(); //string[] str = new string[] { "AA001097796643D67FE43D4185C74185EB47429A63783F64", // "AA001097796643D67FE43D4185C74185EB47429A63783F64", // "AA001097796643D67FE43D4185C74185EB47429A63783F64", // "AA001097796643D67FE43D4185C74185EB47429A63783F64", // "AA0010685B664300000000BE2BC74185EB47423655783F1E", // "AA001097796643D67FE43D4185C74185EB47429A63783F64", // "AA001097796643D67FE43D4185C74185EB47429A63783F64"}; //for (int i = 0; i < str.Length; i++) //{ // float 电压数据 = getdata(str[i].Substring(6, 8)); // float 电流数据 = getdata(str[i].Substring(14, 8)); // float 功率数据 = getdata(str[i].Substring(22, 8)); // float 频率数据 = getdata(str[i].Substring(30, 8)); // float 功率因素 = getdata(str[i].Substring(38, 8)); // OperateResult.AppendText(str[i]); // OperateResult.AppendText(电压数据.ToString() + "\n"); // OperateResult.AppendText(电流数据.ToString() + "\n"); // OperateResult.AppendText(功率数据.ToString() + "\n"); // OperateResult.AppendText(频率数据.ToString() + "\n"); // OperateResult.AppendText(功率因素.ToString() + "\n"); // //如果电流是0,则下次重新获取数据 // if (电流数据 == 0) // { // writedata = false; // if (电流数据 == 0 && !writedata) { // writedata = true; // } // } // if (writedata) // { // if (电流数据 != 0) { // dh.ExecuteSql("insert into currenttest(CT_ID, CT_MAKECODE, CT_VOLTAGE, CT_CURRENT, CT_POWER, CT_FREQUENCY, CT_POWER1)" + // "VALUES(currenttest_SEQ.NEXTVAL,'" + ma_code.Text + "','" + 电压数据 + "','" + 电流数据 + "','" + 功率数据 + "','" + 频率数据 + "','" + 功率因素 + "')", "insert"); // writedata = false; // } // } //} FormBorderStyle = FormBorderStyle.FixedSingle; serialPort1.DataReceived += SerialPort1_DataReceived; //添加监控事件 XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created); //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created); List CacheInf = new List(); IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); for (int i = 0; i < IpEntry.AddressList.Length; i++) { if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) IPAddress = IpEntry.AddressList[i].ToString(); } //获取缓存信息 try { Type.Text = BaseUtil.GetCacheData("Type").ToString(); ComPort.Text = BaseUtil.GetCacheData("ComPort").ToString(); BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString(); li_code.Text = BaseUtil.GetCacheData("Line").ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private float getdata(string tmp_b2) { byte[] b2 = new byte[4]; float f2 = 0; tmp_b2 = tmp_b2.Replace(" ", "");//删除字符串中间的空格 if (tmp_b2.Length != 8) { //判断输入字符串的长度是否合适 MessageBox.Show("输入Byte长度错误,为连续8位4个字节,高位为0的补齐0"); } else { //将收到的字符串分成4个字节,这4个字节是字符串的形式 string tmp_char1 = tmp_b2.Substring(6, 2); string tmp_char2 = tmp_b2.Substring(4, 2); string tmp_char3 = tmp_b2.Substring(2, 2); string tmp_char4 = tmp_b2.Substring(0, 2); //将4字节的字符串格式转换成16进制的byte格式 b2[3] = Convert.ToByte(tmp_char1, 16); b2[2] = Convert.ToByte(tmp_char2, 16); b2[1] = Convert.ToByte(tmp_char3, 16); b2[0] = Convert.ToByte(tmp_char4, 16); //将16进制byte转换成浮点数格式 f2 = BitConverter.ToSingle(b2, 0); } return f2; } double lastqty = 0; string data = ""; bool getSeconddata = false; bool realwritedata = false; private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { int len = serialPort1.BytesToRead; Byte[] readBuffer = new Byte[len]; serialPort1.Read(readBuffer, 0, len); //将数据读入缓存 data = BitConverter.ToString(readBuffer, 0, readBuffer.Length).Replace("-", ""); if (data.Length > 48) { data = data.Substring(0, 48); } if (data.Length == 48) { float 电压数据 = getdata(data.Substring(6, 8)); float 电流数据 = getdata(data.Substring(14, 8)); float 功率数据 = getdata(data.Substring(22, 8)); float 频率数据 = getdata(data.Substring(30, 8)); float 功率因素 = getdata(data.Substring(38, 8)); //如果电流是0,则下次重新获取数据 if (电流数据 == 0) { writedata = false; if (电流数据 == 0 && !writedata) { writedata = true; } } if (writedata) { if (电流数据 != 0) { realwritedata = true; writedata = false; Thread.Sleep(2000); OperateResult.AppendText("获取数据\n"); byte[] data = HexStringToBytes("55 00 10 65"); serialPort1.Write(data, 0, data.Length); } } if (realwritedata) { if (电流数据 > 0) { double num; double num1; if (double.TryParse(FunctionNum.Text, out num) && double.TryParse(FunctionNum1.Text, out num1)) { if (功率数据 > num && 功率数据 < num1) { OperateResult.AppendText("数据上传成功,功率[" + 功率数据 + "]\n"); dh.ExecuteSql("insert into currenttest(CT_ID,ct_linecode, CT_MAKECODE, CT_VOLTAGE, CT_CURRENT, CT_POWER, CT_FREQUENCY, CT_POWER1)" + "VALUES(currenttest_SEQ.NEXTVAL,'" + li_code.Text + "','" + ma_code.Text + "','" + 电压数据 + "','" + 电流数据 + "','" + 功率数据 + "','" + 频率数据 + "','" + 功率因素 + "')", "insert"); NowQTY.Text = dh.getRowCount("currenttest", "ct_makecode='" + ma_code.Text + "'").ToString(); realwritedata = false; } else { OperateResult.AppendText("功率数据异常\n"); } } else { OperateResult.AppendText("请填写功率标准值\n"); } } } } else { //realwritedata = true; //writedata = false; //Thread.Sleep(1000); //OperateResult.AppendText("获取数据1\n"); //byte[] data = HexStringToBytes("55 00 10 65"); //serialPort1.Write(data, 0, data.Length); //OperateResult.AppendText(data + "数据格式异常\n"); } } catch (Exception ex) { OperateResult.AppendText(ex.Message + data + "\n"); } } private void ConnectDB() { dh = new DataHelper(); SystemInf.dh = dh; ma_code.TableName = "make"; ma_code.SelectField = "ma_code # 工单号"; ma_code.FormName = Name; ma_code.DBTitle = "工单查询"; ma_code.SetValueField = new string[] { "ma_code" }; ma_code.Condition = ""; ma_code.DbChange += nr_rule_DBChange; li_code.TableName = "line"; li_code.SelectField = "li_code # 线别编号,li_name # 线别名称"; li_code.FormName = Name; li_code.DBTitle = "线别查询"; li_code.SetValueField = new string[] { "li_code" }; li_code.Condition = ""; li_code.DbChange += nr_rule_DBChange; } SerialPort serialPort1 = new SerialPort(); private void StartWatch_Click(object sender, EventArgs e) { BaseUtil.SetCacheData("Type", Type.Text); BaseUtil.SetCacheData("ComPort", ComPort.Text); BaseUtil.SetCacheData("BaudRate", BaudRate.Text); BaseUtil.SetCacheData("Line", li_code.Text); if (!dh.CheckExist("Make", "ma_code='" + ma_code.Text + "'")) { OperateResult.AppendText("工单号不能为空\n"); return; } //if (!dh.CheckExist("line", "li_code='" + li_code.Text + "'")) //{ // OperateResult.AppendText("线别不能为空\n"); // return; //} //string ExitConfirm = MessageBox.Show(this, "确认计数器是否置为0?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString(); //if (ExitConfirm != "Yes") //{ // return; //} //设置按钮不可点击 StartWatch.Enabled = false; ma_code.Enabled = false; StopWatch.Enabled = true; try { serialPort1.PortName = ComPort.Text; serialPort1.BaudRate = int.Parse(BaudRate.Text); serialPort1.Open(); Timer.Start(); } catch (Exception mes) { if (BaudRate.Text == "" || BaudRate.Text == "") OperateResult.AppendText(">>请先维护波特率和串口\n"); else OperateResult.AppendText(">>" + mes.Message + "\n"); } OperateResult.AppendText("开始执行监控\n"); } private void XmlWatcher_Created(object sender, FileSystemEventArgs e) { OperateResult.AppendText("文件修改:" + e.FullPath + "\n"); TxtHandleProcess(e.FullPath); } string nextLine; private void TxtHandleProcess(string FileName) { List badcode = new List(); List badlocation = new List(); List badprod = new List(); } private void StopWatch_Click(object sender, EventArgs e) { XmlWatcher.EnableRaisingEvents = false; StartWatch.Enabled = true; ma_code.Enabled = true; StopWatch.Enabled = false; OperateResult.AppendText("停止执行监控\n"); } private void Clean_Click(object sender, EventArgs e) { OperateResult.Clear(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString(); if (ExitConfirm != "Yes") { WindowState = FormWindowState.Minimized; e.Cancel = true; } } private void Timer_Tick(object sender, EventArgs e) { if (serialPort1.IsOpen) { if (!realwritedata) { byte[] data = HexStringToBytes("55 00 10 65"); serialPort1.Write(data, 0, data.Length); } } } private void AutoStart_CheckedChanged(object sender, EventArgs e) { SetAutoRun(); } private void SetAutoRun() { if (AutoStart.Checked) //设置开机自启动 { string path = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.SetValue("FileWatcher.exe", path); rk2.Close(); rk.Close(); } else //取消开机自启动 { string path = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.DeleteValue("FileWatcher.exe", false); rk2.Close(); rk.Close(); } } private byte[] HexStringToBytes(string hs)//十六进制字符串转byte { string a = hs.Replace(" ", ""); int bytelength = 0; if (a.Length % 2 == 0) { bytelength = a.Length / 2; } else { bytelength = a.Length / 2 + 1; } byte[] b = new byte[bytelength]; //逐个字符变为16进制字节数据 for (int i = 0; i < bytelength; i++) { if (i == bytelength - 1) { b[i] = Convert.ToByte(a.Substring(i * 2), 16); } else { b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16); } } //按照指定编码将字节数组变为字符串 return b; } private void GetData_Click(object sender, EventArgs e) { } } }