using NPOI.SS.Formula.Functions; 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+"); public SystemSetting_ScaleTest() { InitializeComponent(); } private void SystemSetting_ScaleTest_Load(object sender, EventArgs e) { 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 { int len = serialPort1.BytesToRead; Byte[] readBuffer = new Byte[len]; serialPort1.Read(readBuffer, 0, len); //将数据读入缓存 string weigh = Encoding.Default.GetString(readBuffer); Remark.AppendText(weigh+"\n"); if (weigh != "") { Weight.Text = re.Match(weigh).Groups[0].Value; } } 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(); } } } }