using Gs.WeightIqc.ToolBox; using Microsoft.Win32; using Newtonsoft.Json; using NModbus; using NModbus.Serial; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Drawing; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace Gs.WeightIqc { public partial class Form1 : Form { public System.IO.Ports.SerialPort Sp = new System.IO.Ports.SerialPort(); public delegate void HandleInterfaceUpdataDelegate(string text); private Form1.HandleInterfaceUpdataDelegate interfaceUpdataHandle; private Dictionary dicThread = new Dictionary(); private System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer(); public Form1() { InitializeComponent(); GetComList(); #region MyRegion int int32 = 10000; string _vanishingSeconds = ConfigurationManager.AppSettings["TimingMailInterval"]; if (!string.IsNullOrEmpty(_vanishingSeconds)) int32 = int.Parse(_vanishingSeconds); this.timer1.Interval = int32; this.button1.Enabled = true; this.button2.Enabled = false; this.cmbBaudRate.SelectedIndex = 1; #endregion this.timer1.Tick += (s, e) => { if (this.dicThread.Keys.Contains("GetWeight")) return; Thread thread1 = new Thread(new ThreadStart(this.GetWeight)); thread1.Start(); this.dicThread.Add("GetWeight", thread1); }; this.button1.Click += (s, e) => { try { ToolBox.LogHelper.Debug(this.ToString(), " 开始采集"); if (this.cmbBaudRate.Text.Trim() != "" && this.cmbSerialPortNum.Text != "") { ToolBox.LogHelper.Debug(this.ToString(), "配置串口通信"); this.interfaceUpdataHandle = new Form1.HandleInterfaceUpdataDelegate(this.UpdateTextBox); this.Sp.PortName = this.cmbSerialPortNum.Text.Trim(); this.Sp.BaudRate = Convert.ToInt32(this.cmbBaudRate.Text.Trim()); this.Sp.Parity = Parity.None; this.Sp.StopBits = StopBits.One; ToolBox.LogHelper.Debug(this.ToString(), "打开串口同通信"); this.Sp.Open(); this.button1.Enabled = false; this.button2.Enabled = true; this.timer1.Enabled = false; this.cmbBaudRate.Enabled = false; this.cmbSerialPortNum.Enabled = false; ToolBox.LogHelper.Debug(this.ToString(), "启动刷新数据定时器"); this.timer1.Start(); } else { ToolBox.LogHelper.Debug(this.ToString(), "请输入正确的串口号和波特率"); int num = (int)MessageBox.Show("请输入正确的串口号和波特率!"); this.cmbSerialPortNum.Focus(); } } catch (Exception ex) { ToolBox.LogHelper.Debug(this.ToString(), ex.Message); int num = (int)MessageBox.Show($"串口{this.cmbSerialPortNum.Text.Trim()}打开失败!{ex.Message}"); } }; this.button2.Click += (s, e) => { try { if (this.dicThread.Keys.Contains("GetWeight")) { Thread thread = this.dicThread["GetWeight"]; if (thread.IsAlive) thread.Abort(); this.dicThread.Remove("GetWeight"); } this.button1.Enabled = true; this.button2.Enabled = false; this.cmbBaudRate.Enabled = true; this.cmbSerialPortNum.Enabled = true; this.timer1.Stop(); this.Sp.Close(); } catch (Exception ex) { //int num = (int)MessageBox.Show(ex.Message); //Application.Exit(); MessageBox.Show(ex.Message); ToolBox.LogHelper.Debug(this.ToString(), ex.Message); } }; this.FormClosing += (s, e) => { if (Sp.IsOpen) Sp.Close(); if (timer1 != null) { timer1.Stop(); timer1.Dispose(); } try { if (this.dicThread.Keys.Contains("GetWeight")) { Thread thread = this.dicThread["GetWeight"]; if (thread.IsAlive) thread.Abort(); this.dicThread.Remove("GetWeight"); } this.timer1.Stop(); this.Sp.Close(); } catch (Exception ex) { //int num = (int)MessageBox.Show(ex.Message); //Application.Exit(); MessageBox.Show(ex.Message); } }; } /// /// 获取重量 /// public void GetWeight() { ModbusFactory factory = new ModbusFactory(); ToolBox.LogHelper.Debug(this.ToString(), "GetWeight创建modbus对象"); IModbusMaster rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp); bool flag = true; while (true) { // addModel("1", "2"); //ToolBox.LogHelper.Debug(this.ToString(), "GetWeight创建modbus对象"); try { if (!this.Sp.IsOpen) { ToolBox.LogHelper.Debug(this.ToString(), "GetWeight 重新打开串口连接"); this.Sp.Open(); rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp); } if (rtuMaster == null) { ToolBox.LogHelper.Debug(this.ToString(), "GetWeight 重新创建modbus对象2"); rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp); } byte slaveAddress3 = byte.Parse("1"); ushort startAddress3 = ushort.Parse("0002"); ushort numberOfPoints1 = ushort.Parse("2"); ushort[] numArray = rtuMaster.ReadHoldingRegisters(slaveAddress3, startAddress3, numberOfPoints1); float single = BitConverter.ToSingle(this.CombomBinaryArray(BitConverter.GetBytes(numArray[1]), BitConverter.GetBytes(numArray[0])), 0); this.Invoke((Delegate)this.interfaceUpdataHandle, (object)single.ToString()); byte slaveAddress4 = byte.Parse("1"); ushort startAddress4 = ushort.Parse("0001"); ushort numberOfPoints2 = ushort.Parse("1"); int int32 = Convert.ToInt32(rtuMaster.ReadHoldingRegisters(slaveAddress4, startAddress4, numberOfPoints2)[0].ToString()); string str = Convert.ToString(int32, 2).PadLeft(16 /*0x10*/, '0'); char ch1 = str[1]; char ch2 = str[6]; if (ch1 == '0' && ch2 == '0') { flag = true; } else if (flag) { flag = false; } addModel(single.ToString(), int32.ToString()); ToolBox.LogHelper.Debug(this.ToString(), "single:" + single.ToString() + ",flag:" + flag.ToString() + ",int32:" + int32.ToString()); Thread.Sleep(2000); } catch (Exception ex) { Thread.Sleep(2000); } } } /// /// 上传称重数据 /// /// 截取后的数量 /// 原子串 private void addModel(string _realWeight, string _realWeightTxt) { string _lineId = "0"; var _obj = new { lineId = _lineId, realWeight = _realWeight.Trim(), realWeightTxt = _realWeightTxt.Trim(), }; try { string strJson = UtilityHelper.HttpPost("", "WorkWeight/EditModel", JsonConvert.SerializeObject(_obj)); ReturnModel _rtn = ToolBox.UtilityHelper.ReturnToDynamic(strJson); if (_rtn.rtnCode <= 0) { ToolBox.LogHelper.Debug(this.ToString(), "WorkWeight/EditModel:" + strJson); } } catch (Exception ex) { ToolBox.LogHelper.Debug(this.ToString(), ex.Message); } } /// /// 更新UI /// /// private void UpdateTextBox(string text) { try { this.txtDt.Text = DateTime.Now.ToString(); if (this.txtNum.Text == text) return; this.txtNum.Text = text; } catch (Exception ex) { ToolBox.LogHelper.Debug(this.ToString(), ex.Message); } } private void GetComList() { this.cmbSerialPortNum.Items.Clear(); RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); if (registryKey == null) return; foreach (string valueName in registryKey.GetValueNames()) { string description = (string)registryKey.GetValue(valueName); this.cmbSerialPortNum.Items.Add(description); } if (this.cmbSerialPortNum.Items.Count > 0) this.cmbSerialPortNum.SelectedIndex = 0; } private byte[] CombomBinaryArray(byte[] srcArray1, byte[] srcArray2) { byte[] destinationArray = new byte[srcArray1.Length + srcArray2.Length]; Array.Copy((Array)srcArray1, 0, (Array)destinationArray, 0, srcArray1.Length); Array.Copy((Array)srcArray2, 0, (Array)destinationArray, srcArray1.Length, srcArray2.Length); return destinationArray; } } }