lu
2025-08-22 931767239577c1a81f298ddccd65e3137c80b326
DevApp/Gs.DevApp/DevFrm/Work/Frm_Work09.cs
@@ -1,45 +1,193 @@
using System;
using DevExpress.Utils;
using Gs.DevApp.Entity;
using Gs.DevApp.ToolBox;
using Microsoft.Win32;
using Newtonsoft.Json;
using NModbus;
using NModbus.Serial;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using DevExpress.Utils;
using Gs.DevApp.Entity;
using Gs.DevApp.ToolBox;
using Newtonsoft.Json;
namespace Gs.DevApp.DevFrm.Work
{
    public partial class Frm_Work09 : DevExpress.XtraEditors.XtraForm
    {
        string _webServiceName = "WorkWeight/";
        string value = string.Empty;
        /// <summary>
        /// 串口类
        /// </summary>
        private SerialPort Sp = new SerialPort();
        /// <summary>
        /// gridview定时刷新
        /// </summary>
        System.Timers.Timer timer = new System.Timers.Timer(10000);
        public Frm_Work09()
        public System.IO.Ports.SerialPort Sp = new System.IO.Ports.SerialPort();
        public delegate void HandleInterfaceUpdataDelegate(string text);
        private Frm_Work09.HandleInterfaceUpdataDelegate interfaceUpdataHandle;
        private Dictionary<string, Thread> dicThread = new Dictionary<string, Thread>();
        private System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
        System.Timers.Timer timerGridview = new System.Timers.Timer(10000);
        public Frm_Work09(string strType)
        {
            InitializeComponent();
            GetComList();
            comLine.getSuppler("");
            #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.comLine.IsReadly = false;
            this.cmbSerialPortNum.Enabled = true;
            this.cmbBaudRate.Enabled = true;
            this.cmbBaudRate.SelectedIndex = 1;
            #endregion
            this.timer1.Tick += (s, e) =>
            {
                if (this.dicThread.Keys.Contains<string>("GetWeight"))
                    return;
                Thread thread1 = new Thread(new ThreadStart(this.GetWeight));
                thread1.Start();
                this.dicThread.Add("GetWeight", thread1);
            };
            this.button1.Click += (s, e) =>
            {
                string _comLine = comLine.GetId();
                if (string.IsNullOrEmpty(_comLine))
                {
                    Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择线体");
                    this.comLine.Focus();
                    return;
                }
                try
                {
                    ToolBox.LogHelper.Debug(this.ToString(), " 开始采集");
                    if (this.cmbBaudRate.Text.Trim() != "" && this.cmbSerialPortNum.Text != "")
                    {
                        ToolBox.LogHelper.Debug(this.ToString(), "配置串口通信");
                        this.interfaceUpdataHandle = new Frm_Work09.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.comLine.IsReadly = true;
                        this.cmbSerialPortNum.Enabled = false;
                        this.cmbBaudRate.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<string>("GetWeight"))
                    {
                        Thread thread = this.dicThread["GetWeight"];
                        if (thread.IsAlive)
                            thread.Abort();
                        this.dicThread.Remove("GetWeight");
                    }
                    this.button1.Enabled = true;
                    this.button2.Enabled = false;
                    this.comLine.IsReadly = false;
                    this.cmbSerialPortNum.Enabled = true;
                    this.cmbBaudRate.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 (timer != null)
                if (timer1 != null)
                {
                    timer.Stop();
                    timer.Dispose();
                    timer1.Stop();
                    timer1.Dispose();
                }
                if (timerGridview != null)
                {
                    timerGridview.Stop();
                    timerGridview.Dispose();
                }
                try
                {
                    if (this.dicThread.Keys.Contains<string>("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);
                }
            };
            GetComList();
            this.comLine.getSuppler("");
            #region gridview设置
            timerGridview.Elapsed += (s, e) => {
                var _obj = new
                {
                    lineId = comLine.GetId(),
                };
                try
                {
                    var strReturn = UtilityHelper.HttpPost("", _webServiceName + "GetModelList", JsonConvert.SerializeObject(_obj), false);
                    var dd = UtilityHelper.ReturnToList(strReturn);
                    var dt = dd.rtnData;
                    BeginInvoke(new Action(() =>
                    {
                        gcMx1.BindingContext = new BindingContext();
                        gcMx1.DataSource = dt;
                        gcMx1.ForceInitialize();
                        gvMx1.BestFitColumns();
                    }));
                    BeginInvoke(new Action(() => {
                        this.txtMsg.Text = "最近刷新列表时间:" + DateTime.Now.ToString();
                    }));
                }
                catch (Exception ex)
                {
                    Toast vm = new Toast(-1, "gvMx1:" + ex.Message);
                    vm.Show();
                }
            };
            timerGridview.AutoReset = true; // 设置为true表示重复执行,false表示执行一次后停止
            timerGridview.Enabled = true; // 开始计时
            gvMx1.OptionsFind.ShowSearchNavButtons = false;
            gvMx1.OptionsView.ShowAutoFilterRow = false;
            gvMx1.OptionsView.ShowGroupPanel = false;
@@ -65,175 +213,65 @@
                if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
            };
        }
        /// <summary>
        /// 从注册表获取系统串口列表
        /// </summary>
        private void GetComList()
        {
            this.cmbSerialPortNum.Clear();
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                cmbSerialPortNum.Properties.Items.Add(port);
            }
        }
        /// <summary>
        /// 启动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            Sp.DataReceived -= new SerialDataReceivedEventHandler(Sp_DataReceived);
            string _comLine = comLine.GetId();
            string _cmbSerialPortNum = cmbSerialPortNum.Text.Trim();
            string _cmbBaudRate = cmbBaudRate.Text.Trim();
            string _comSjw = comSjw.Text.Trim();
            string _comStopBits = comStopBits.Text.Trim();
            string _comParity = comParity.Text.Trim();
            if (string.IsNullOrEmpty(_comLine))
            {
                Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择线体");
                this.comLine.Focus();
                return;
            }
            if (cmbSerialPortNum.SelectedIndex < 0)
            {
                Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择串口号");
                this.cmbSerialPortNum.Focus();
                return;
            }
            if (cmbBaudRate.SelectedIndex < 0)
            {
                Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择波特率");
                this.cmbBaudRate.Focus();
                return;
            }
            if (comSjw.SelectedIndex < 0)
            {
                Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择数据位");
                this.comSjw.Focus();
                return;
            }
            if (comStopBits.SelectedIndex < 0)
            {
                Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择停止位");
                this.comStopBits.Focus();
                return;
            }
            if (comParity.SelectedIndex < 0)
            {
                Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择校验");
                this.comParity.Focus();
                return;
            }
            try
            {
                Sp.ReceivedBytesThreshold = 1;
                Sp.PortName = _cmbSerialPortNum;
                Sp.BaudRate = Convert.ToInt32(_cmbBaudRate);//设置波特率
                if (Enum.TryParse(_comParity, out Parity pt1))
                {
                    Sp.Parity = pt1;// 设置校验位
                }
                else
                {
                    Gs.DevApp.ToolBox.MsgHelper.ShowError("无法识别的校验");
                }
                if (Enum.TryParse(_comStopBits, out StopBits pt2))
                {
                    Sp.StopBits = pt2;//设置停止位
                }
                else
                {
                    Gs.DevApp.ToolBox.MsgHelper.ShowError("无法识别的停止位");
                }
                Sp.DataBits = int.Parse(_comSjw); // 设置数据位
                //Sp.ReadTimeout = 500; // 设置超时时间,例如500毫秒
                //Sp.ReadBufferSize = 4096; // 设置缓冲区大小
                Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
                Sp.ReceivedBytesThreshold = 1;
                LogHelper.Debug(this.ToString(), "打开串口通信PortName-" + Sp.PortName.ToString() + ",BaudRate-" + Sp.BaudRate.ToString() + ",StopBits-" + Sp.StopBits.ToString() + ",Parity-" + Sp.Parity.ToString());
                if (!Sp.IsOpen)
                    Sp.Open();
                setEnable(false);
                timer.Elapsed += OnTimedEvent;
                timer.AutoReset = true; // 设置为true表示重复执行,false表示执行一次后停止
                timer.Enabled = true; // 开始计时
                Gs.DevApp.ToolBox.MsgHelper.ShowInformation("打开成功!");
            }
            catch (Exception exe)
            {
                LogHelper.Debug(this.ToString(), "打开串口通信失败:" + exe.Message);
                Gs.DevApp.ToolBox.MsgHelper.ShowError("打开失败" + exe.Message);
            }
            #endregion
        }
        /// <summary>
        /// 串口收到数据
        /// 获取重量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        public void GetWeight()
        {
            string _tmpStr = string.Empty;
            try
            ModbusFactory factory = new ModbusFactory();
            ToolBox.LogHelper.Debug(this.ToString(), "GetWeight创建modbus对象");
            IModbusMaster rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp);
            bool flag = true;
            while (true)
            {
                int i = Sp.BytesToRead;
                if (i > 0)
                // addModel("1", "2");
                //ToolBox.LogHelper.Debug(this.ToString(), "GetWeight创建modbus对象");
                try
                {
                    _tmpStr = Sp.ReadExisting();
                   // Thread.Sleep(1000);
                    LogHelper.Debug(this.ToString(), $"监听到数据,字节长度:{i.ToString()},{_tmpStr}");
                    this.BeginInvoke(new Action(() =>
                    if (!this.Sp.IsOpen)
                    {
                        txtMsg.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff->字节数字" + i.ToString() + "->") + _tmpStr);
                        //ST,GS,+  250.2kg
                        if (_tmpStr.Length <= 0)
                        {
                            LogHelper.Debug(this.ToString(), "_tmpStr长度<=0,退出上报");
                            return;
                        }
                        if (!_tmpStr.Contains("ST"))
                        {
                            LogHelper.Debug(this.ToString(), "_tmpStr重量状态不为ST,退出上报");
                            return;
                        }
                        if (!_tmpStr.Contains("+"))
                        {
                            LogHelper.Debug(this.ToString(), "_tmpStr不包含重量+,退出上报");
                            return;
                        }
                        string[] _ary=_tmpStr.Split('+');
                        string abc = _ary.Last();//ST,GS,
                        txtNum.Text = (abc.Trim().Replace("k", "").Replace("g", "").Replace("S","").Replace("T","").Replace("G","").Replace(",",""));
                        addModel(txtNum.Text, _tmpStr);
                    }));
                        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);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(this.ToString(), $"监听到数据error:{ex.Message}");
                return;
            }
        }
        /// <summary>
        /// 启用或禁用
        /// </summary>
        /// <param name="bl"></param>
        private void setEnable(bool bl)
        {
            comLine.Enabled = bl;
            cmbSerialPortNum.Enabled = bl;
            cmbBaudRate.Enabled = bl;
            comSjw.Enabled = bl;
            comStopBits.Enabled = bl;
            comParity.Enabled = bl;
            btnStart.Enabled = false;
        }
        /// <summary>
        /// 上传称重数据
@@ -242,7 +280,7 @@
        /// <param name="_realWeightTxt">原子串</param>
        private void addModel(string _realWeight, string _realWeightTxt)
        {
            string _lineId = comLine.GetId();
            string _lineId = "0";
            var _obj = new
            {
                lineId = _lineId,
@@ -251,50 +289,63 @@
            };
            try
            {
                string strJson = UtilityHelper.HttpPost("", _webServiceName + "EditModel", JsonConvert.SerializeObject(_obj));
                string strJson = UtilityHelper.HttpPost("", "WorkWeight/EditModel", JsonConvert.SerializeObject(_obj));
                ReturnModel<dynamic> _rtn = ToolBox.UtilityHelper.ReturnToDynamic(strJson);
                if (_rtn.rtnCode <= 0)
                {
                    Toast vm = new Toast(-1, _rtn.rtnMsg);
                    vm.Show();
                    ToolBox.LogHelper.Debug(this.ToString(), "WorkWeight/EditModel:" + strJson);
                }
            }
            catch (Exception ex)
            {
                ToolBox.MsgHelper.ShowError("提示:" + ex.Message);
                ToolBox.LogHelper.Debug(this.ToString(), ex.Message);
            }
        }
        /// <summary>
        /// 定时读取列表
        /// 更新UI
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        /// <param name="text"></param>
        private void UpdateTextBox(string text)
        {
            var _obj = new
            {
                lineId = comLine.GetId(),
            };
            try
            {
                var lst = new List<string>();
                var strReturn = UtilityHelper.HttpPost("", _webServiceName + "GetModelList", JsonConvert.SerializeObject(_obj), false);
                var dd = UtilityHelper.ReturnToList(strReturn);
                var dt = dd.rtnData;
                BeginInvoke(new Action(() =>
                {
                    gcMx1.BindingContext = new BindingContext();
                    gcMx1.DataSource = dt;
                    gcMx1.ForceInitialize();
                    gvMx1.BestFitColumns();
                }));
                this.txtMsg.Text ="最近称重时间:"+ DateTime.Now.ToString();
                if (this.txtNum.Text == text)
                    return;
                this.txtNum.Text = text;
            }
            catch (Exception ex)
            {
                Toast vm = new Toast(-1, "gvMx1:" + ex.Message);
                vm.Show();
                ToolBox.LogHelper.Debug(this.ToString(), ex.Message);
            }
        }
        private void GetComList()
        {
            this.cmbSerialPortNum.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);
                cmbSerialPortNum.Properties.Items.Add(description);
            }
            if (this.cmbSerialPortNum.Properties.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;
        }
    }
}