bug
lu
7 天以前 51e2e408fd48c6454334a90c5dff0e5d0960da0c
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
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<string, Thread> dicThread = new Dictionary<string, Thread>();
        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<string>("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<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.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<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);
                }
            };
        }
 
 
 
        /// <summary>
        /// 获取重量
        /// </summary>
        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);
                }
            }
        }
        /// <summary>
        /// 上传称重数据
        /// </summary>
        /// <param name="_realWeight">截取后的数量</param>
        /// <param name="_realWeightTxt">原子串</param>
        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<dynamic> _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);
            }
        }
 
 
        /// <summary>
        /// 更新UI
        /// </summary>
        /// <param name="text"></param>
 
        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;
        }
    }
}