yantian yue
2023-12-28 fd5f7c86beec35f6b7cde3f16f23c6cf1279a447
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
using System;
using System.IO;
using YX.BLL;
using YX.Entity;
using System.Net;
using System.Text;
using YX.WebService;
using Newtonsoft.Json;
using System.Net.Sockets;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Configuration;
using EasyModbus; // 引入EasyModbusTCP库
using System.IO.Ports;
using System.Net.NetworkInformation;
 
namespace YX
{
 
    public partial class FrmExpress : WindowParent
    {
        Thread receiveDataThread;
        //声明一个委托类型,该委托类型无输入参数和输出参数
        public delegate void ProcessDelegate();
 
        private string ipAddress = ConfigurationManager.AppSettings["IPAddress"]; // 从 App.config 获取 IP 地址配置
        private int port1 = 502;
        ModbusClient tcpClient;
        private bool isTryingToCon = false;
        private string encryptionKey = "a7x3qsz12edc45tgfrbi67yhnmju89i9";
 
        public string PSN = "";
        public string PSN2 = "";
        public bool t = true;
 
 
        public FrmExpress(string ParentId)
        {
            InitializeComponent();
            receiveDataThread = new Thread(new ThreadStart(ReceiveSerialData));
            receiveDataThread.IsBackground = true;
            try
            {
                receiveDataThread.Start(); // 启动线程
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误:{ex}");
            }
            dataGridView1.DataSource = System_Bll.GetSystemLog(FrmLogin.LocalIP, "称重");
            macBox.Text = GetMacByNetworkInterface();
        }
        private void ReceiveSerialData()
        {
            while (true)
            {
                ProcessDelegate showProcesslogo = new ProcessDelegate(LabelShowlogo);
                //string str = "1\n2\n3\n";
                //str = str.Replace("\n", string.Empty); // 将 \n 替换为空字符串
                //ModbusTCPWrite(5, 1);
                if (ModbusTCPRead(5,1).Trim("\n".ToCharArray()) == "1")
                {
 
                    try
                    {
                        //PSN = ModbusTCPRead(5, 20).Replace("\n", string.Empty);
                        PSN = ModbusTCPReadString(25,20).Replace("\0", string.Empty); 
                        //PSN2 = ModbusTCPReadString(45, 20).Replace("\0", string.Empty);
                        label1.Invoke(showProcesslogo);
                        if (t)
                         ModbusTCPWrite(5, 10); 
                        else 
                         ModbusTCPWrite(5, 11); 
                    }
                    catch (Exception e)
                    {
                        ModbusTCPWrite(5, 11);
                    }
                }
            }
        }
 
        public void ConnectServer(string ip, int port)
        {
            //防止多个事例去重复连接
            if (isTryingToCon == true)
            {
                return;
            }
            try
            {
                if (tcpClient != null)
                {
                    tcpClient.Disconnect();
                }
                tcpClient = new ModbusClient(ip, port);
 
                tcpClient.UnitIdentifier = 2; //地址
                tcpClient.Baudrate = 9600; //波特率
                tcpClient.Parity = Parity.None; //校验位
                tcpClient.StopBits = StopBits.One; //停止位
                tcpClient.ConnectionTimeout = 500;
                tcpClient.Connect();
 
                ProcessDelegate LimeColor = new ProcessDelegate(ButtonLimeColor);
                radioButton1.Invoke(LimeColor);
 
                isTryingToCon = true;
            }
            catch (Exception e)
            {
                ProcessDelegate RedColor = new ProcessDelegate(ButtonRedColor);
                if (this.IsHandleCreated)
                {
                    radioButton1.Invoke(RedColor);
                }
            }
        }
 
        private void ButtonRedColor()
        {
            radioButton1.BackColor = Color.Red;
        }
 
        private void ButtonLimeColor()
        {
            radioButton1.BackColor = Color.Lime;
        }
 
        /// <param name="startingAddress">寄存器初始地址号</param> 
        /// <param name="quantity">读取位数</param> 
        private string ModbusTCPRead(int startingAddress, int quantity)
        {
            ConnectServer(ipAddress, port1);
            string str = "";
            try
            {
                int[] result = tcpClient.ReadHoldingRegisters(startingAddress, quantity);  //寄存器初始地址号
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < result.Length; i++)
                {
                    builder.Append(Convert.ToString(result[i]) + "\n");
                }
                str = builder.ToString();
            }
            catch (Exception ex)
            {
                isTryingToCon = false;
                tcpClient.Disconnect();
            }
            return str;
        }
 
        private string ModbusTCPReadString(int startingAddress, int quantity)
        {
            ConnectServer(ipAddress, port1);
            int[] data = tcpClient.ReadHoldingRegisters(startingAddress, quantity); // 读取寄存器数据
            string strData = ""; // 存储字符串数据
            //string str = "";
            //string str1 = "";
            //string str2 = "";
 
            for (int i = 0; i < quantity; i++)
            {
                //str= data[i].ToString("X");
                //if (str.Length == 4) 
                //{
                //    str1 = str.Substring(2, 2);
                //    str2 = str.Substring(0, 2);
                //    strData += str1 + str2;
                //}
                //if (str.Length == 2)
                //{
                //    strData += str;
                //}
                strData += data[i].ToString("X");
            }
            string str66 = hexStrToStr(strData);
            return hexStrToStr(strData); ;
        }
 
        private static string hexStrToStr(string str)
        {
            //去除字符串中的空格
            string[] strT = str.Split(' ');
            string strA = "";
            foreach (string strB in strT)
            {
                strA += strB;
            }
 
            char[] chars = strA.ToCharArray();
            string returnstr = "";
            string[] str1 = new string[chars.Length / 2];
 
            for (int i = 0; i < chars.Length / 2; i++)
            {
                string str111 = chars[2 * i].ToString() + chars[2 * i + 1].ToString();
                uint num = uint.Parse(str111, System.Globalization.NumberStyles.AllowHexSpecifier);
                char charr = (char)num;
                returnstr = returnstr + charr;
            }
            return returnstr;
        }
 
/// <param name="address">位置</param> 
/// <param name="value">写入值</param> 
private void ModbusTCPWrite(int address, int value)
        {
            ConnectServer(ipAddress, port1);
            try
            {
                tcpClient.WriteMultipleRegisters(address, new int[] { value });
            }
            catch (Exception ex)
            {
                isTryingToCon = false;
                tcpClient.Disconnect();
            }
        }
 
        private void LabelShowlogo()
        {
            string[] b_str = PSN.Split(',');
            PSNBox.Text = b_str[1];
 
            JObject jo = WI6027();
            if (jo == null) 
            {
                t = false;
                System_Bll.WriteLogToDB(new Entity.Base_Log
                {
                    CreateUserID = FrmLogin.LoginUserID,
                    CreateUserName = FrmLogin.loginUserName,
                    LocalIP = FrmLogin.LocalIP,
                    LogMessage = "WI6027调用失败!",
                    Type = "称重",
                    ClassName = typeof(FrmLogin).ToString()
                });
                return;
            }
            var contents = jo["content"];
            foreach (var content in contents)
            {
                LineNameBox.Text = (string)content["Line"];
                StationBox.Text = (string)content["Station"];
                StationIDBox.Text = (string)content["StationID"];
            }
            if (WI601K(b_str[0]))
            {
                JObject jo1032 = WI1032(b_str[0], SNMBox.Text, KPNMBox.Text, KPValueBox.Text);
                if (jo1032 != null) 
                {
                    if (WI6041(LineNameBox.Text, StationBox.Text, KPNMBox.Text, b_str[0])) 
                    {
                        System_Bll.WriteLogToDB(new Entity.Base_Log
                        {
                            CreateUserID = FrmLogin.LoginUserID,
                            CreateUserName = FrmLogin.loginUserName,
                            LocalIP = FrmLogin.LocalIP,
                            LogMessage = "PSN:"+b_str[0]+ "过站成功!",
                            Type = "称重",
                            ClassName = typeof(FrmLogin).ToString()
                        });
                    }
                }
            }
            dataGridView1.DataSource = System_Bll.GetSystemLog(FrmLogin.LocalIP, "称重");
            Refresh();
        }
 
        /// <param name="encryptStr">明文</param> 
        /// <param name="key">密钥</param> 
        public static string AES256_Encrypt(string encryptStr, string key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
 
        [Obsolete]
        private void FrmExpress_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                receiveDataThread.Suspend();
                receiveDataThread.Abort();
            }
            catch (Exception ex)
            {
            }
        }
        public JObject MES_Interface(string textToEncrypt, string encryptionKey)
        {
            string par = AES256_Encrypt(textToEncrypt, encryptionKey);
            WMISoapClient wMISoapClient = new WMISoapClient();
            string text5 = wMISoapClient.WMI01(par);
            return (JObject)JsonConvert.DeserializeObject(text5);
        }
 
        public JObject WI6027()
        {
            string a = "a0:36:9F:6c:0e:95";
            string WI6027 = "{";
                   WI6027 += "\"user\":\"sys\",";
                   WI6027 += "\"password\":\"sysuser\",";
                   WI6027 += "\"method\":\"MES_BA_WI6027\","; 
                   WI6027 += "\"servername\":\"London\",";
                   WI6027 += "\"methodparameter\":{";
                   WI6027 += "\"mac\":\""+ a +"\",";
                   WI6027 += "\"hostName\":\"DESKTOP-UV8I1I0\"";
                   WI6027 += "}}";
 
            return MES_Interface(WI6027, encryptionKey);
        }
 
        public bool WI601K(string BarCode)
        {
            //string WI601K = "{\"user\":\"sys\", \"password\":\"sysuser\",\"method\":\"MES_BA_WI601K\",\"servername\":\"TEST_WTMES_Customer\", \"methodparameter\":{\"BarCode\":\"123456789\", \"HostName\":\"liuxingliang-PC\", \"Mac\":\"6A:15:63:C3:CC:EA\" }}\n";
            string a = "a0:36:9F:6c:0e:95";
            string WI601K = "{";
                   WI601K += "\"user\":\"sys\",";
                   WI601K += "\"password\":\"sysuser\",";
                   WI601K += "\"method\":\"MES_BA_WI601K\",";
                   WI601K += "\"servername\":\"London\",";
                   WI601K += "\"methodparameter\":{";
                   WI601K += "\"BarCode\":\""+ BarCode + "\",";
                   WI601K += "\"HostName\":\"DESKTOP-UV8I1I0\",";
                   WI601K += "\"Mac\":\"" + a + "\"";
                   WI601K += "}";
                   WI601K += "}";
 
            JObject jo = MES_Interface(WI601K, encryptionKey);
            if (jo["state"].ToString() == "false")
            {
                t = false;
                System_Bll.WriteLogToDB(new Entity.Base_Log
 
                {
                    CreateUserID = FrmLogin.LoginUserID,
                    CreateUserName = FrmLogin.loginUserName,
                    LocalIP = FrmLogin.LocalIP,
                    LogMessage = "WI601K接口调用失败:" + jo["content"].ToString(),
                    Type = "称重",
                    ClassName = typeof(FrmLogin).ToString()
                });
                return false;
            }
            return true;
        }
        public JObject WI1032(string PSN, string S_NM, string KP_NM, string KP_Value)
        {
            string WI1032 = "{ ";
                   WI1032 += "\"user\":\"sys\",";
                   WI1032 += "\"password\":\"sysuser\",";
                   WI1032 += "\"method\":\"MES_AS_WI1032\",";
                   WI1032 += "\"servername\":\"London\",";
                   WI1032 += "\"methodparameter\":{ ";
                   WI1032 += "\"PSN\":\""+ PSN +"\","; //PLC读到的
                   WI1032 += "\"S_NM\":\""+ S_NM +"\",";
                   WI1032 += "\"KP_NM\":\""+ KP_NM +"\",";
                   WI1032 += "\"KP_Value\":\""+ KP_NM +"\"";
                   WI1032 += "}}";
 
            JObject jo = MES_Interface(WI1032, encryptionKey);
            if (jo["state"].ToString() == "false")
            {
                t = false;
                System_Bll.WriteLogToDB(new Entity.Base_Log
                {
                    CreateUserID = FrmLogin.LoginUserID,
                    CreateUserName = FrmLogin.loginUserName,
                    LocalIP = FrmLogin.LocalIP,
                    LogMessage = "WI1032接口调用失败:" + jo["content"].ToString(),
                    Type = "称重",
                    ClassName = typeof(FrmLogin).ToString()
                });
                return null;
            }
            return jo;
        }
 
        public bool WI6041(string Line,string Station,string StationID, string PSN)
        {
            string WI6041 = "{ ";
            WI6041 += "\n\"user\":\"sys\", ";
            WI6041 += "\n\"password\":\"sysuser\", ";
            WI6041 += "\n\"method\":\"MES_BA_WI6041\", ";
            WI6041 += "\n\"servername\":\"London\", ";
            WI6041 += "\n\"methodparameter\":{ ";
            WI6041 += "\n\"content\":{ ";
            WI6041 += "\n\"snresult\":{ ";
            WI6041 += "\n}, ";
            WI6041 += "\n\"testresult\":{ ";
            WI6041 += "\n\"psn\":\"" + PSN + "\", ";
            WI6041 += "\n\"workordernumber\":\"100000236815\", ";
            WI6041 += "\n\"testStationId\":\"" + StationID + "\", ";
            WI6041 += "\n\"testStationName\":\"" + Station + "\", ";
            WI6041 += "\n\"linename\":\"" + Line + "\", ";
            WI6041 += "\n\"hostname\":\"admin-PC-0930\", ";
            WI6041 += "\n\"testTime\":\"" + string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now) + "\", ";
            WI6041 += "\n\"testModel\":\"S87567GB002_BLK1\", ";
            WI6041 += "\n\"testWorkID\":\"\", ";
            WI6041 += "\n\"Fixture\":\"\", ";
            WI6041 += "\n\"FixtureSN\":\"\", ";
            WI6041 += "\n\"Powersupply\":\"\", ";
            WI6041 += "\n\"PowersupplySN\":\"\", ";
            WI6041 += "\n\"Instrument\":\"\", ";
            WI6041 += "\n\"InstrumentSN\":\"\", ";
            WI6041 += "\n\"Operator\":\"\", ";
            WI6041 += "\n\"testVersion\":\"V1.0.1\" ";
            WI6041 += "\n}, ";
            WI6041 += "\n\"itemresult\":[ ";
            WI6041 += "\n],";
            WI6041 += "\n\"specialitem\":[ ";
            WI6041 += "\n] ";
            WI6041 += "\n}, ";
            WI6041 += "\n\"state\":\"pass\", ";
            WI6041 += "\n\"errcode\":\"\", ";
            WI6041 += "\n\"errmessage\":\"\"} ";
            WI6041 += "\n}";
            JObject jo = MES_Interface(WI6041, encryptionKey);
            if (jo["state"].ToString() == "false")
            {
                t = false;
                System_Bll.WriteLogToDB(new Entity.Base_Log
                {
                    CreateUserID = FrmLogin.LoginUserID,
                    CreateUserName = FrmLogin.loginUserName,
                    LocalIP = FrmLogin.LocalIP,
                    LogMessage = "WI6041接口调用失败:" + jo["content"].ToString(),
                    Type = "称重",
                    ClassName = typeof(FrmLogin).ToString()
                });
                return false;
            }
            return true;
        }
 
        /// <summary>
        /// 通过NetworkInterface获取MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetMacByNetworkInterface()
        {
            try
            {
                NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface ni in interfaces)
                {
                    return BitConverter.ToString(ni.GetPhysicalAddress().GetAddressBytes());
                }
            }
            catch (Exception)
            {
            }
            return "00-00-00-00-00-00";
        }
 
    }
}