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 bool t = true; 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[] b_str = PSN.Split(','); PSNBox.Text = b_str[1]; 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, b_str[0])) { 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 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; } /// /// 通过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"; } } }