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