lu
2025-05-21 d1fde218cd82d4e64f8e15accbafa11ed1efd780
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Timers;
using System.Windows.Forms;
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>
        /// 更新UI委托,只定义,不实现
        /// </summary>
        /// <param name="text"></param>
        public delegate void HandleInterfaceUpdataDelegate(string text);
        /// <summary>
        /// 更新UI委托,实现
        /// </summary>
        private HandleInterfaceUpdataDelegate interfaceUpdataHandle;
 
        System.Timers.Timer timer = new System.Timers.Timer(10000); // 1000毫秒间隔
        public Frm_Work09()
        {
            InitializeComponent();
            this.FormClosing += (s, e) =>
            {
                if (Sp.IsOpen)
                    Sp.Close();
                if (timer != null)
                {
                    timer.Stop();
                    timer.Dispose();
                }
            };
            GetComList();
            this.comLine.getSuppler("");
            Gs.DevApp.ToolBox.UtilityHelper.SetGridViewParameterMx(gvMx1);
          
        }
 
        /// <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)
        {
            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
            {
                interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象 
                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.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);
            }
        }
 
        /// <summary>
        /// 串口收到数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string abc = string.Empty;
            try
            {
                int i = Sp.BytesToRead;
                if (i > 0)
                {
                    abc = Sp.ReadExisting();
                    LogHelper.Debug(this.ToString(), $"监听到数据:{abc}");
                    this.Invoke(interfaceUpdataHandle, abc);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(this.ToString(), $"监听到数据error:{ex.Message}");
                return;
            }
        }
 
        /// <summary>
        /// 接受到数据,开始处理数据
        /// </summary>
        /// <param name="text"></param>
        private void UpdateTextBox(string text)
        {
            //ST,GS,+  250.2kg
            string _tmpStr = text.Trim();
            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;
            }
            _tmpStr = _tmpStr.Substring(7);
            txtNum.Text = _tmpStr;
            addModel(_tmpStr);
        }
        /// <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>
        /// 上传称重数据
        /// </summary>
        private void addModel(string _realWeight)
        {
            string _lineId = comLine.GetId();
            var _obj = new
            {
                lineId = _lineId,
                realWeight = _realWeight,
            };
            try
            {
                string strJson = UtilityHelper.HttpPost("", _webServiceName + "EditModel", JsonConvert.SerializeObject(_obj));
                ReturnModel<dynamic> _rtn = ToolBox.UtilityHelper.ReturnToDynamic(strJson);
                if (_rtn.rtnCode <= 0)
                {
                    Toast vm = new Toast(-1, _rtn.rtnMsg);
                    vm.Show();
                }
            }
            catch (Exception ex)
            {
                ToolBox.MsgHelper.Warning("提示:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 定时读取列表
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            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();
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show("gvMx1:" + ex.Message);
            }
        }
 
    }
}