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) { CheckForIllegalCrossThreadCalls = false; ComList.Text = BaseUtil.GetCacheData("PortName").ToString(); BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString(); } private void StartTest_Click(object sender, EventArgs e) { using (SerialPort port = new SerialPort(ComList.Text, 9600, Parity.None, 8, StopBits.One)) { try { port.Open(); MessageBox.Show("串口打开成功!"); port.Close(); } catch (Exception ex) { MessageBox.Show($"失败: {ex.Message}"); } } //if (this.ComList.Text == "") //{ // MessageBox.Show("端口号不可为空"); // return; //} //if (this.BaudRate.Text == "") //{ // MessageBox.Show("波特率不可为空"); // return; //} //thread = new Thread(GetSerialData); //try //{ // ReadData = true; // serialPort1.PortName = "COM3"; // 确保是存在的端口 // serialPort1.BaudRate = 9600; // 必须与设备一致 // serialPort1.DataBits = 8; // 通常为8 // serialPort1.Parity = Parity.None; // 通常为None // serialPort1.StopBits = StopBits.One; // 通常为1 // serialPort1.Handshake = Handshake.None; // 通常为None // BaseUtil.SetCacheData("PortName", this.ComList.Text); // BaseUtil.SetCacheData("BaudRate", BaudRate.Text); // serialPort1.Open(); // thread.Start(); //} //catch (Exception mes) { MessageBox.Show(mes.Message + mes.StackTrace); } } private void GetSerialData() { if (serialPort1.IsOpen) { if (!SystemInf.OpenPort.Contains(serialPort1.PortName)) { SystemInf.OpenPort.Add(serialPort1.PortName); try { while (ReadData) { try { Weight.Text = re.Match(serialPort1.ReadLine().Trim()).Groups[0].Value.Replace("kg",""); } 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(); } } } }