111
yantian yue
2023-12-28 7820f50a29b75e0704e6e1dcfdaf2e85397c66a8
提交 | 用户 | 时间
e46d3b 1 using System;
2 using System.IO;
3 using YX.BLL;
4 using YX.Entity;
5 using System.Net;
6 using System.Text;
7 using YX.WebService;
8 using Newtonsoft.Json;
9 using System.Net.Sockets;
10 using Newtonsoft.Json.Linq;
11 using System.Security.Cryptography;
12 using System.Drawing;
13 using System.Windows.Forms;
14 using System.Threading;
15 using System.Configuration;
7820f5 16 using EasyModbus; // 引入EasyModbusTCP库 *****
e46d3b 17 using System.IO.Ports;
18 using System.Net.NetworkInformation;
19
20 namespace YX.wt
21 {
22     public partial class Frmwt : WindowParent
23     {
24         Thread receiveDataThread;
25         //声明一个委托类型,该委托类型无输入参数和输出参数
26         public delegate void ProcessDelegate();
27
28         private string ipAddress = ConfigurationManager.AppSettings["IPAddress"]; // 从 App.config 获取 IP 地址配置
29         private int port1 = 502;
30         ModbusClient tcpClient;
31         private bool isTryingToCon = false;
32         private string encryptionKey = "a7x3qsz12edc45tgfrbi67yhnmju89i9";
33
34         public string PSN = "";
35         public string PSN2 = "";
36         public string PSN3 = "";
37         public Frmwt(string ParentId)
38         {
39             InitializeComponent();
40
41             receiveDataThread = new Thread(new ThreadStart(ReceiveSerialData));
42             receiveDataThread.IsBackground = true;
43             try
44             {
45                 receiveDataThread.Start(); // 启动线程
46             }
47             catch (Exception ex)
48             {
49                 Console.WriteLine($"发生错误:{ex}");
50             }
51             dataGridView1.DataSource = System_Bll.GetSystemLog(FrmLogin.LocalIP);
52             macBox.Text = GetMacByNetworkInterface();
53
54         }
55
56         private void ReceiveSerialData()
57         {
58             while (true)
59             {
60                 ProcessDelegate showProcess = new ProcessDelegate(LabelShow);
61                 //string str = "1\n2\n3\n";
62                 //str = str.Replace("\n", string.Empty); // 将 \n 替换为空字符串
63                 string str = ModbusTCPRead(5, 1).Trim("\n".ToCharArray());
64                 if (ModbusTCPRead(5, 1).Trim("\n".ToCharArray()) == "1")
65                 {
66
67                     try
68                     {
69                         //PSN = ModbusTCPRead(5, 20).Replace("\n", string.Empty);
70                         PSN = ModbusTCPReadString(25, 30).Replace("\0", string.Empty);
71                         PSN2 = ModbusTCPReadString(45, 20).Replace("\0", string.Empty);
72                         PSN3 = ModbusTCPReadString(65, 20).Replace("\0", string.Empty);
73                         label1.Invoke(showProcess);
74                         ModbusTCPWrite(5, 10);
75                     }
76                     catch (Exception e)
77                     {
78                         ModbusTCPWrite(5, 11);
79                     }
80                 }
81             }
82         }
83
84         private string ModbusTCPReadString(int startingAddress, int quantity)
85         {
86             ConnectServer(ipAddress, port1);
87             int[] data = tcpClient.ReadHoldingRegisters(startingAddress, quantity); // 读取寄存器数据
88             string strData = ""; // 存储字符串数据
89             //string str = "";
90             //string str1 = "";
91             //string str2 = "";
92
93             for (int i = 0; i < quantity; i++)
94             {
95                 //str= data[i].ToString("X");
96                 //if (str.Length == 4) 
97                 //{
98                 //    str1 = str.Substring(2, 2);
99                 //    str2 = str.Substring(0, 2);
100                 //    strData += str1 + str2;
101                 //}
102                 //if (str.Length == 2)
103                 //{
104                 //    strData += str;
105                 //}
106                 strData += data[i].ToString("X");
107             }
108             string str66 = hexStrToStr(strData);
109             return hexStrToStr(strData); ;
110         }
111
112         private static string hexStrToStr(string str)
113         {
114             //去除字符串中的空格
115             string[] strT = str.Split(' ');
116             string strA = "";
117             foreach (string strB in strT)
118             {
119                 strA += strB;
120             }
121
122             char[] chars = strA.ToCharArray();
123             string returnstr = "";
124             string[] str1 = new string[chars.Length / 2];
125
126             for (int i = 0; i < chars.Length / 2; i++)
127             {
128                 string str111 = chars[2 * i].ToString() + chars[2 * i + 1].ToString();
129                 uint num = uint.Parse(str111, System.Globalization.NumberStyles.AllowHexSpecifier);
130                 char charr = (char)num;
131                 returnstr = returnstr + charr;
132             }
133             return returnstr;
134         }
135
136         public void ConnectServer(string ip, int port)
137         {
138             //防止多个事例去重复连接
139             if (isTryingToCon == true)
140             {
141                 return;
142             }
143             try
144             {
145                 if (tcpClient != null)
146                 {
147                     tcpClient.Disconnect();
148                 }
149                 tcpClient = new ModbusClient(ip, port);
150
151                 tcpClient.UnitIdentifier = 2; //地址
152                 tcpClient.Baudrate = 9600; //波特率
153                 tcpClient.Parity = Parity.None; //校验位
154                 tcpClient.StopBits = StopBits.One; //停止位
155                 tcpClient.ConnectionTimeout = 500;
156                 tcpClient.Connect();
157
158                 ProcessDelegate LimeColor = new ProcessDelegate(ButtonLimeColor);
159                 radioButton1.Invoke(LimeColor);
160
161                 isTryingToCon = true;
162             }
163             catch (Exception e)
164             {
165                 ProcessDelegate RedColor = new ProcessDelegate(ButtonRedColor);
166                 if (this.IsHandleCreated)
167                 {
168                     radioButton1.Invoke(RedColor);
169                 }
170             }
171         }
172
173         private void ButtonRedColor()
174         {
175             radioButton1.BackColor = Color.Red;
176         }
177
178         private void ButtonLimeColor()
179         {
180             radioButton1.BackColor = Color.Lime;
181         }
182
183         /// <param name="startingAddress">寄存器初始地址号</param> 
184         /// <param name="quantity">读取位数</param> 
185         private string ModbusTCPRead(int startingAddress, int quantity)
186         {
187             ConnectServer(ipAddress, port1);
188             string str = "";
189             try
190             {
191                 int[] result = tcpClient.ReadHoldingRegisters(startingAddress, quantity);  //寄存器初始地址号
192                 StringBuilder builder = new StringBuilder();
193                 for (int i = 0; i < result.Length; i++)
194                 {
195                     builder.Append(Convert.ToString(result[i]) + "\n");
196                 }
197                 str = builder.ToString();
198             }
199             catch (Exception ex)
200             {
201                 isTryingToCon = false;
202                 tcpClient.Disconnect();
203             }
204             return str;
205         }
206
207
208
209         /// <param name="address">位置</param> 
210         /// <param name="value">写入值</param> 
211         private void ModbusTCPWrite(int address, int value)
212         {
213             ConnectServer(ipAddress, port1);
214             try
215             {
216                 tcpClient.WriteMultipleRegisters(address, new int[] { value });
217             }
218             catch (Exception ex)
219             {
220                 isTryingToCon = false;
221                 tcpClient.Disconnect();
222             }
223         }
224
225         private void LabelShow()
226         {
227             //string[] aaa = PSN.Split(',');
228             //string bbbb = aaa[0];
229             PSNBox.Text = PSN;
230
231             JObject jo = WI6027();
232             if (jo == null)
233             {
234                 System_Bll.WriteLogToDB(new Entity.Base_Log
235                 {
236                     CreateUserID = FrmLogin.LoginUserID,
237                     CreateUserName = FrmLogin.loginUserName,
238                     LocalIP = FrmLogin.LocalIP,
239                     LogMessage = "WI6027调用失败!",
240                     Type = "称重",
241                     ClassName = typeof(FrmLogin).ToString()
242                 });
243                 return;
244             }
245             var contents = jo["content"];
246             foreach (var content in contents)
247             {
248                 LineNameBox.Text = (string)content["Line"];
249                 StationBox.Text = (string)content["Station"];
250                 StationIDBox.Text = (string)content["StationID"];
251             }
252             if (WI601K(PSNBox.Text))
253             {
254                 JObject jo1032 = WI1032(PSNBox.Text, SNMBox.Text, KPNMBox.Text, KPValueBox.Text);
255                 if (jo1032 != null)
256                 {
257                     if (WI6041(PSNBox.Text, SNMBox.Text, KPNMBox.Text, jo1032))
258                     {
259                         System_Bll.WriteLogToDB(new Entity.Base_Log
260                         {
261                             CreateUserID = FrmLogin.LoginUserID,
262                             CreateUserName = FrmLogin.loginUserName,
263                             LocalIP = FrmLogin.LocalIP,
264                             LogMessage = "重量:" + PSNBox.Text + ",称重条码:" + SNMBox.Text + ",工单号:" + KPNMBox.Text + ",MES条码:" + KPNMBox.Text,
265                             Type = "称重",
266                             ClassName = typeof(FrmLogin).ToString()
267                         });
268                     }
269                 }
270             }
271             dataGridView1.DataSource = System_Bll.GetSystemLog(FrmLogin.LocalIP);
272             Refresh();
273         }
274
275         /// <param name="encryptStr">明文</param> 
276         /// <param name="key">密钥</param> 
277         public static string AES256_Encrypt(string encryptStr, string key)
278         {
279             byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
280             byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr);
281             RijndaelManaged rDel = new RijndaelManaged();
282             rDel.Key = keyArray;
283             rDel.Mode = CipherMode.ECB;
284             rDel.Padding = PaddingMode.PKCS7;
285             ICryptoTransform cTransform = rDel.CreateEncryptor();
286             byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
287             return Convert.ToBase64String(resultArray, 0, resultArray.Length);
288         }
289
290         [Obsolete]
291         private void FrmExpress_FormClosed(object sender, FormClosedEventArgs e)
292         {
293             try
294             {
295                 receiveDataThread.Suspend();
296                 receiveDataThread.Abort();
297             }
298             catch (Exception ex)
299             {
300             }
301         }
302         public JObject MES_Interface(string textToEncrypt, string encryptionKey)
303         {
304             string par = AES256_Encrypt(textToEncrypt, encryptionKey);
305             WMISoapClient wMISoapClient = new WMISoapClient();
306             string text5 = wMISoapClient.WMI01(par);
307             return (JObject)JsonConvert.DeserializeObject(text5);
308         }
309
310         public JObject WI6027()
311         {
312             //string WI6027 = "{ \"user\":\"sys\",\"password\":\"sysuser\",\"method\":\"MES_BA_WI6027\",\"servername\":\"TEST_WTMES_Customer\",\"methodparameter\":{ \"mac\":\"6A:15:63:C3:CC:EA\",\"hostName\":\"liuxingliang-PC\"} }";
313             string a = "D0:8E:79:02:CF:91";
314
315             string WI6027 = "{";
316             WI6027 += "\"user\":\"sys\",";
317             WI6027 += "\"password\":\"sysuser\",";
318             WI6027 += "\"method\":\"MES_BA_WI6027\",";
319             WI6027 += "\"servername\":\"London\",";
320             WI6027 += "\"methodparameter\":{";
321             WI6027 += "\"mac\":\"" + a + "\",";
322             WI6027 += "\"hostName\":\"PC-20230103TQKE\"";
323             WI6027 += "}}";
324
325             JObject jo = MES_Interface(WI6027, encryptionKey);
326             return jo;
327         }
328
329         public bool WI601K(string BarCode)
330         {
331             //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";
332
333             string WI601K = "{";
334             WI601K += "\"user\":\"sys\",";
335             WI601K += "\"password\":\"sysuser\",";
336             WI601K += "\"method\":\"MES_BA_WI601K\",";
337             WI601K += "\"servername\":\"London\",";
338             WI601K += "\"methodparameter\":{";
339             WI601K += "\"BarCode\":\"" + BarCode + "\",";
340             WI601K += "\"HostName\":\"liuxingliang-PC\",";
341             WI601K += "\"Mac\":\"6A:15:63:C3:CC:EA\"";
342             WI601K += "}";
343             WI601K += "}";
344
345             JObject jo = MES_Interface(WI601K, encryptionKey);
346             if (jo["state"].ToString() == "false")
347             {
348                 System_Bll.WriteLogToDB(new Entity.Base_Log
349                 {
350                     CreateUserID = FrmLogin.LoginUserID,
351                     CreateUserName = FrmLogin.loginUserName,
352                     LocalIP = FrmLogin.LocalIP,
353                     LogMessage = "MES接口WI601K,条码比对失败!",
354                     Type = "包装线",
355                     ClassName = typeof(FrmLogin).ToString()
356                 });
357                 return false;
358             }
359             return true;
360         }
361         public JObject WI1032(string PSN, string S_NM, string KP_NM, string KP_Value)
362         {
363             string WI1032 = "{ ";
364             WI1032 += "\"user\":\"sys\",";
365             WI1032 += "\"password\":\"sysuser\",";
366             WI1032 += "\"method\":\"MES_AS_WI1032\",";
367             WI1032 += "\"servername\":\"London\",";
368             WI1032 += "\"methodparameter\":{ ";
369             WI1032 += "\"PSN\":\"" + PSN + "\","; //PLC读到的
370             WI1032 += "\"S_NM\":\"" + S_NM + "\",";
371             WI1032 += "\"KP_NM\":\"" + KP_NM + "\",";
372             WI1032 += "\"KP_Value\":\"" + KP_NM + "\"";
373             WI1032 += "}}";
374
375             JObject jo = MES_Interface(WI1032, encryptionKey);
376             if (jo["state"].ToString() == "false")
377             {
378                 System_Bll.WriteLogToDB(new Entity.Base_Log
379                 {
380                     CreateUserID = FrmLogin.LoginUserID,
381                     CreateUserName = FrmLogin.loginUserName,
382                     LocalIP = FrmLogin.LocalIP,
383                     LogMessage = "MES接口WI1032条码邦定失败",
384                     Type = "包装线",
385                     ClassName = typeof(FrmLogin).ToString()
386                 });
387                 return null;
388             }
389             return jo;
390         }
391
392         public bool WI6041(string Line, string Station, string StationID, JObject outWI1032)
393         {
394             var contents = outWI1032["content"];
395
396             string WI6041 = "{ " +
397                 "\n\"user\":\"sys\", " +
398                 "\n\"password\":\"sysuser\", " +
399                 "\n\"method\":\"MES_BA_WI6041\", " +
400                 "\n\"servername\":\"London\", " +
401                 "\n\"methodparameter\":{ " +
402                 "\n\"content\":{ " +
403                 "\n\"snresult\":{ " +
404                 "\n}, " +
405                 "\n\"testresult\":{ " +
406                 "\n\"psn\":\"" + (string)contents["PSN"] + "\", " +
407                 "\n\"workordernumber\":\"100000236815\", " +
408                 "\n\"testStationId\":\"" + StationID + "\", " +
409                 "\n\"testStationName\":\"" + Station + "\", " +
410                 "\n\"linename\":\"" + Line + "\", " +
411                 "\n\"hostname\":\"admin-PC-0930\", " +
412                 "\n\"testTime\":\"" + string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now) + "\", " +
413                 "\n\"testModel\":\"S87567GB002_BLK1\", " +
414                 "\n\"testWorkID\":\"\", " +
415                 "\n\"Fixture\":\"\", " +
416                 "\n\"FixtureSN\":\"\", " +
417                 "\n\"Powersupply\":\"\", " +
418                 "\n\"PowersupplySN\":\"\", " +
419                 "\n\"Instrument\":\"\", " +
420                 "\n\"InstrumentSN\":\"\", " +
421                 "\n\"Operator\":\"\", " +
422                 "\n\"testVersion\":\"V1.0.1\" " +
423                 "\n}, " +
424                 "\n\"itemresult\":[ " +
425                 "\n]," +
426                 "\n\"specialitem\":[ " +
427                 "\n] " +
428                 "\n}, " +
429                 "\n\"state\":\"pass\", " +
430                 "\n\"errcode\":\"\", " +
431                 "\n\"errmessage\":\"\"} " +
432                 "\n}";
433             JObject jo = MES_Interface(WI6041, encryptionKey);
434             if (jo["state"].ToString() == "false")
435             {
436                 System_Bll.WriteLogToDB(new Entity.Base_Log
437                 {
438                     CreateUserID = FrmLogin.LoginUserID,
439                     CreateUserName = FrmLogin.loginUserName,
440                     LocalIP = FrmLogin.LocalIP,
441                     LogMessage = "MES接口WI6041数据提交失败",
442                     Type = "包装线",
443                     ClassName = typeof(FrmLogin).ToString()
444                 });
445
446                 string a = string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now);
447                 return false;
448             }
449             return true;
450         }
451
452         /// <summary>
453         /// 通过NetworkInterface获取MAC地址
454         /// </summary>
455         /// <returns></returns>
456         public static string GetMacByNetworkInterface()
457         {
458             try
459             {
460                 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
461                 foreach (NetworkInterface ni in interfaces)
462                 {
463                     return BitConverter.ToString(ni.GetPhysicalAddress().GetAddressBytes());
464                 }
465             }
466             catch (Exception)
467             {
468             }
469             return "00-00-00-00-00-00";
470         }
471
472     }
473 }