lu
2 天以前 5a7f68bf4dbbdca1abbb939bd43e1fb695bc7c0b
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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.WeightLine
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        string _webServiceName = "WorkWeight/";
        public System.IO.Ports.SerialPort Sp = new System.IO.Ports.SerialPort();
        public delegate void HandleInterfaceUpdataDelegate(string text);
        private Form1.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 Form1()
        {
            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))
                {
                    MessageBox.Show("请选择线体");
                    this.comLine.Focus();
                    return;
                }
                try
                {
                    LogHelper.Debug(this.ToString(), " 开始采集");
                    if (this.cmbBaudRate.Text.Trim() != "" && this.cmbSerialPortNum.Text != "")
                    {
                        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;
                        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;
                        LogHelper.Debug(this.ToString(), "启动刷新数据定时器");
                        this.timer1.Start();
                    }
                    else
                    {
                        LogHelper.Debug(this.ToString(), "请输入正确的串口号和波特率");
                        int num = (int)MessageBox.Show("请输入正确的串口号和波特率!");
                        this.cmbSerialPortNum.Focus();
                    }
                }
                catch (Exception ex)
                {
                    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);
                    LogHelper.Debug(this.ToString(), ex.Message);
                }
            };
            this.FormClosing += (s, e) =>
            {
                if (Sp.IsOpen)
                    Sp.Close();
                if (timer1 != null)
                {
                    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);
                }
            };
            #region gridview设置
            timerGridview.Elapsed += (s, e) =>
            {
                string _lineId = comLine.GetId();
                if (string.IsNullOrEmpty(_lineId))
                    return;
                var _obj = new
                {
                    lineId = _lineId,
                };
                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)
                {
                    MessageBox.Show("gvMx1:" + ex.Message);
                }
            };
            timerGridview.AutoReset = true; // 设置为true表示重复执行,false表示执行一次后停止
            timerGridview.Enabled = true; // 开始计时
            gvMx1.OptionsFind.ShowSearchNavButtons = false;
            gvMx1.OptionsView.ShowAutoFilterRow = false;
            gvMx1.OptionsView.ShowGroupPanel = false;
            gvMx1.RowStyle += (s, e) =>
            {
                //默认选中行不变色
                gvMx1.OptionsSelection.EnableAppearanceFocusedRow = false;
                //默认选中单元格不变色
                gvMx1.OptionsSelection.EnableAppearanceFocusedCell = false;
                if (e.RowHandle >= 0)
                {
                    DataRow row = gvMx1.GetDataRow(e.RowHandle);
                    if (row == null)
                        return;
                    string colorString = row["bgColor"].ToString(); // 使用十六进制表示颜色的ARGB值
                    Color color = ColorTranslator.FromHtml(colorString);
                    e.Appearance.BackColor = color;
                }
            };
            gvMx1.IndicatorWidth = 60;
            gvMx1.CustomDrawRowIndicator += (s, e) =>
            {
                if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
            };
            #endregion
        }
 
        /// <summary>
        /// 获取重量
        /// </summary>
        public void GetWeight()
        {
            ModbusFactory factory = new ModbusFactory();
            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)
                    {
                        LogHelper.Debug(this.ToString(), "GetWeight 重新打开串口连接");
                        this.Sp.Open();
                        rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp);
                    }
                    if (rtuMaster == null)
                    {
                        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());
                    LogHelper.Debug(this.ToString(), "single:" + single.ToString() + ",flag:" + flag.ToString() + ",int32:" + int32.ToString());
                    Thread.Sleep(2000);
                }
                catch (Exception ex)
                {
                    Thread.Sleep(2000);
                }
            }
        }
        /// <summary>
        /// 上传称重数据
        /// </summary>
        /// <param name="_realWeight">截取后的数量</param>
        /// <param name="_realWeightTxt">原子串</param>
        private void addModel(string _realWeight, string _realWeightTxt)
        {
            string _lineId = comLine.GetId();
            var _obj = new
            {
                lineId = _lineId,
                realWeight = _realWeight.Trim(),
                realWeightTxt = _realWeightTxt.Trim(),
            };
            try
            {
                string strJson = UtilityHelper.HttpPost("", "WorkWeight/EditModel", JsonConvert.SerializeObject(_obj));
                ReturnModel<dynamic> _rtn = UtilityHelper.ReturnToDynamic(strJson);
                if (_rtn.rtnCode <= 0)
                {
                    LogHelper.Debug(this.ToString(), "WorkWeight/EditModel:" + strJson);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(this.ToString(), ex.Message);
            }
        }
 
 
        /// <summary>
        /// 更新UI
        /// </summary>
        /// <param name="text"></param>
 
        private void UpdateTextBox(string text)
        {
            try
            {
                this.txtMsg.Text = "最近获取称重时间:" + DateTime.Now.ToString();
                if (this.txtNum.Text == text)
                    return;
                this.txtNum.Text = text;
            }
            catch (Exception ex)
            {
                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;
        }
 
 
    }
}