using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using UAS_MES_NEW.DataOperate; using UAS_MES_NEW.Entity; using UAS_MES_NEW.PublicMethod; namespace UAS_MES_NEW.SystemSetting { public partial class SystemSetting_ScaleTest : Form { Thread thread; bool ReadData = true; SerialPort serialPort1 = new SerialPort(); Regex re = new Regex("\\d+.\\d+\\w+"); public SystemSetting_ScaleTest() { InitializeComponent(); } private void SystemSetting_ScaleTest_Load(object sender, EventArgs e) { SystemSetting_ScaleTest.CheckForIllegalCrossThreadCalls = false; ComList.Text = BaseUtil.GetCacheData("PortName").ToString(); BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString(); } private void StartTest_Click(object sender, EventArgs e) { if (this.ComList.Text == "") { MessageBox.Show("端口号不可为空"); return; } if (this.BaudRate.Text == "") { MessageBox.Show("波特率不可为空"); return; } thread = new Thread(GetSerialData); try { ReadData = true; serialPort1.PortName = this.ComList.Text; serialPort1.BaudRate = int.Parse(BaudRate.Text); BaseUtil.SetCacheData("PortName", this.ComList.Text); BaseUtil.SetCacheData("BaudRate", BaudRate.Text); serialPort1.Open(); thread.Start(); } catch (Exception mes) { MessageBox.Show(mes.Message); } } private void GetSerialData() { if (serialPort1.IsOpen) { if (!SystemInf.OpenPort.Contains(serialPort1.PortName)) { SystemInf.OpenPort.Add(serialPort1.PortName); try { while (ReadData) { try { Thread.Sleep(100); int len = serialPort1.BytesToRead; Byte[] readBuffer = new Byte[len]; serialPort1.Read(readBuffer, 0, len); //将数据读入缓存 string weigh = Encoding.Default.GetString(readBuffer); if (weigh != ""&& weigh.Length>10) { int firstIndex = weigh.IndexOf("="); // 查找第一个"="的索引 int secondIndex = weigh.IndexOf("=", firstIndex + 1); // 查找第二个"="的索引 string result = weigh.Substring(firstIndex + 1, secondIndex - firstIndex - 1);// 提取第一个"="和第二个"="之间的字符 result = new string(result.ToCharArray().Reverse().ToArray()); int index = 0; while (index < result.Length && result[index] == '0') { index++; } result = result.Substring(index); Remark.AppendText(result+"\n"); Weight.Text = result; } } catch (Exception) { ReadData = false; } } } catch (IOException ex) { MessageBox.Show(ex.Message); } } else MessageBox.Show("端口已被占用,请关闭其他窗口"); } } private void SystemSetting_ScaleTest_FormClosing(object sender, FormClosingEventArgs e) { if (serialPort1.IsOpen) { ReadData = false; serialPort1.Close(); SystemInf.OpenPort.Remove(serialPort1.PortName); thread.Interrupt(); } //thread.Abort(); } private void StopTest_Click(object sender, EventArgs e) { if (serialPort1.IsOpen) { ReadData = false; serialPort1.Close(); SystemInf.OpenPort.Remove(serialPort1.PortName); thread.Abort(); } } } }