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.wt { public partial class Frmwt : 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 string PSN3 = ""; public Frmwt(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 showProcess = new ProcessDelegate(LabelShow); //string str = "1\n2\n3\n"; //str = str.Replace("\n", string.Empty); // 将 \n 替换为空字符串 string str = ModbusTCPRead(5, 1).Trim("\n".ToCharArray()); if (ModbusTCPRead(5, 1).Trim("\n".ToCharArray()) == "1") { try { //PSN = ModbusTCPRead(5, 20).Replace("\n", string.Empty); PSN = ModbusTCPReadString(25, 30).Replace("\0", string.Empty); PSN2 = ModbusTCPReadString(45, 20).Replace("\0", string.Empty); PSN3 = ModbusTCPReadString(65, 20).Replace("\0", string.Empty); label1.Invoke(showProcess); ModbusTCPWrite(5, 10); } catch (Exception e) { ModbusTCPWrite(5, 11); } } } } 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; } 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; } /// 寄存器初始地址号 /// 读取位数 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 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 LabelShow() { //string[] aaa = PSN.Split(','); //string bbbb = aaa[0]; PSNBox.Text = PSN; JObject jo = WI6027(); if (jo == null) { 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(PSNBox.Text)) { JObject jo1032 = WI1032(PSNBox.Text, SNMBox.Text, KPNMBox.Text, KPValueBox.Text); if (jo1032 != null) { if (WI6041(PSNBox.Text, SNMBox.Text, KPNMBox.Text, jo1032)) { System_Bll.WriteLogToDB(new Entity.Base_Log { CreateUserID = FrmLogin.LoginUserID, CreateUserName = FrmLogin.loginUserName, LocalIP = FrmLogin.LocalIP, LogMessage = "重量:" + PSNBox.Text + ",称重条码:" + SNMBox.Text + ",工单号:" + KPNMBox.Text + ",MES条码:" + KPNMBox.Text, Type = "称重", ClassName = typeof(FrmLogin).ToString() }); } } } dataGridView1.DataSource = System_Bll.GetSystemLog(FrmLogin.LocalIP); Refresh(); } /// 明文 /// 密钥 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 WI6027 = "{ \"user\":\"sys\",\"password\":\"sysuser\",\"method\":\"MES_BA_WI6027\",\"servername\":\"TEST_WTMES_Customer\",\"methodparameter\":{ \"mac\":\"6A:15:63:C3:CC:EA\",\"hostName\":\"liuxingliang-PC\"} }"; string a = "D0:8E:79:02:CF:91"; string WI6027 = "{"; WI6027 += "\"user\":\"sys\","; WI6027 += "\"password\":\"sysuser\","; WI6027 += "\"method\":\"MES_BA_WI6027\","; WI6027 += "\"servername\":\"London\","; WI6027 += "\"methodparameter\":{"; WI6027 += "\"mac\":\"" + a + "\","; WI6027 += "\"hostName\":\"PC-20230103TQKE\""; WI6027 += "}}"; JObject jo = MES_Interface(WI6027, encryptionKey); return jo; } 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 WI601K = "{"; WI601K += "\"user\":\"sys\","; WI601K += "\"password\":\"sysuser\","; WI601K += "\"method\":\"MES_BA_WI601K\","; WI601K += "\"servername\":\"London\","; WI601K += "\"methodparameter\":{"; WI601K += "\"BarCode\":\"" + BarCode + "\","; WI601K += "\"HostName\":\"liuxingliang-PC\","; WI601K += "\"Mac\":\"6A:15:63:C3:CC:EA\""; WI601K += "}"; WI601K += "}"; JObject jo = MES_Interface(WI601K, encryptionKey); if (jo["state"].ToString() == "false") { System_Bll.WriteLogToDB(new Entity.Base_Log { CreateUserID = FrmLogin.LoginUserID, CreateUserName = FrmLogin.loginUserName, LocalIP = FrmLogin.LocalIP, LogMessage = "MES接口WI601K,条码比对失败!", 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") { System_Bll.WriteLogToDB(new Entity.Base_Log { CreateUserID = FrmLogin.LoginUserID, CreateUserName = FrmLogin.loginUserName, LocalIP = FrmLogin.LocalIP, LogMessage = "MES接口WI1032条码邦定失败", Type = "包装线", ClassName = typeof(FrmLogin).ToString() }); return null; } return jo; } public bool WI6041(string Line, string Station, string StationID, JObject outWI1032) { var contents = outWI1032["content"]; string WI6041 = "{ " + "\n\"user\":\"sys\", " + "\n\"password\":\"sysuser\", " + "\n\"method\":\"MES_BA_WI6041\", " + "\n\"servername\":\"London\", " + "\n\"methodparameter\":{ " + "\n\"content\":{ " + "\n\"snresult\":{ " + "\n}, " + "\n\"testresult\":{ " + "\n\"psn\":\"" + (string)contents["PSN"] + "\", " + "\n\"workordernumber\":\"100000236815\", " + "\n\"testStationId\":\"" + StationID + "\", " + "\n\"testStationName\":\"" + Station + "\", " + "\n\"linename\":\"" + Line + "\", " + "\n\"hostname\":\"admin-PC-0930\", " + "\n\"testTime\":\"" + string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now) + "\", " + "\n\"testModel\":\"S87567GB002_BLK1\", " + "\n\"testWorkID\":\"\", " + "\n\"Fixture\":\"\", " + "\n\"FixtureSN\":\"\", " + "\n\"Powersupply\":\"\", " + "\n\"PowersupplySN\":\"\", " + "\n\"Instrument\":\"\", " + "\n\"InstrumentSN\":\"\", " + "\n\"Operator\":\"\", " + "\n\"testVersion\":\"V1.0.1\" " + "\n}, " + "\n\"itemresult\":[ " + "\n]," + "\n\"specialitem\":[ " + "\n] " + "\n}, " + "\n\"state\":\"pass\", " + "\n\"errcode\":\"\", " + "\n\"errmessage\":\"\"} " + "\n}"; JObject jo = MES_Interface(WI6041, encryptionKey); if (jo["state"].ToString() == "false") { System_Bll.WriteLogToDB(new Entity.Base_Log { CreateUserID = FrmLogin.LoginUserID, CreateUserName = FrmLogin.loginUserName, LocalIP = FrmLogin.LocalIP, LogMessage = "MES接口WI6041数据提交失败", Type = "包装线", ClassName = typeof(FrmLogin).ToString() }); string a = string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now); return false; } return true; } /// /// 通过NetworkInterface获取MAC地址 /// /// 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"; } } }