123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- 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)
- {
- 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
- {
- Weight.Text = re.Match(serialPort1.ReadLine().Trim()).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();
- }
- }
- }
- }
|