using System; using System.Collections.Generic; using System.Windows.Forms; using Newtonsoft.Json; using System.Net; using System.Text; using System.Configuration; using System.IO; using EasyModbusClient.businessBody; using YG.Device; using YG; using Newtonsoft.Json.Linq; using System.Collections; namespace EasyModbusClient.util { class CommonUtil { public static char SEPLIT_CHAR = ';'; private static string CONNECT_DEVICEINFO_LIST = ConfigurationManager.AppSettings["ConncetionDeviceListString"]; private static string HttpQuestUrlString = ConfigurationManager.AppSettings["HttpQuestUrlString"]; private static string HttpServerUrlString = ConfigurationManager.AppSettings["HttpServerUrlString"]; private static string ConncetionRedisString = ConfigurationManager.AppSettings["ConncetionRedisString"]; private static string LogFilePath = ConfigurationManager.AppSettings["LogFilePath"] + "access_semens_" + string.Format("{0:yyyyMM}", DateTime.Now) + ".log"; public static int BYTE_UNHSORT_LENGTH = 2; public static TreeExXMLCls m_ListExXML = new TreeExXMLCls(); public static List nodeList = new List(); public static int count = 1; private static string LocalRedisString = ""; public static void InitXml() { nodeList = m_ListExXML.XMLToList(Application.StartupPath + "\\customer.xml"); LocalRedisString= ConfigurationManager.AppSettings["LocalRedisString"]; } /// /// 把当前接受到mes下发的内容转换为字符串存到redis里边, /// /// /// /// /// /// /// public static void ResponseTaskList(CcsRequestBody pbody,string serverUrl) { CcsRequestBody body = (CcsRequestBody)pbody.clone(); string redisKey = serverUrl + ":callback"; if (body.IsCallBackFlag == 1) { try { if (redisKey.StringIsEmpty()) { YG.Log.Instance.WriteLogAdd($"46-->出现空的{body.Json_SerializeObject()}"); } } catch(Exception ex) { YG.Log.Instance.WriteLogAdd($"46--》出现空是{ex.Message}"); } List list = GetCallBackRequestList(redisKey); if (list == null || list.Count == 0) { list = new List(); } //if (!list.Exists(o => o.TaskId == body.TaskId && o.TaskNodeId == body.TaskNodeId&&o.Uid==body.Uid)) //{ // list.Add(body); //} if (!list.Exists(o => o.Uid.Equals(body.Uid))) { list.Add(body); } string jsonData = JsonConvert.SerializeObject(list); // YG.Log.Instance.WriteLogAdd($"2222---->>>>"); redis.ServiceStackRedisHelper.SetValue(redisKey, jsonData.ToString(),LocalRedisString); } } /// /// 执行回调函数, /// /// /// public static void CallBackRequest(DeviceList device) { string redisCallBackKey = device.ServerUrl + ":callback"; try { if (redisCallBackKey.StringIsEmpty()) { YG.Log.Instance.WriteLogAdd($"77出现空的{device.ServerUrl}"); } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"77--》出现空是{ex.Message}"); } List list = GetCallBackRequestList(redisCallBackKey); lock (list) { foreach (CcsRequestBody body in list) { if (body.IsCallBackFlag == 1) { Node node = GetTargetNode(device.ServerUrl, body.BusinessType); if (string.IsNullOrWhiteSpace(node.Address)) { break; } string targetValue = node.TargetValue; //回调通知 CallBackReuqestBody callBackBody = new CallBackReuqestBody(); callBackBody.taskId = body.TaskId; callBackBody.taskNodeId = body.TaskNodeId; callBackBody.msg = body.Msg; callBackBody.uid = body.Uid; callBackBody.bizCallBackData = body.bizCallBackData; callBackBody.code = body.Data + ""; string jsonData = JsonConvert.SerializeObject(callBackBody); //当设备是opcua 协议 if (device.Dtype.Equals(DeviceType.OPCUa)) { List addresses = new List(); List retList = new List(); if (!"uploadProgram".Equals(body.BusinessType) && !"deleteProgram".Equals(body.BusinessType)) { addresses.Add(node.CheckAddress); DeviceOPCUat opc = (DeviceOPCUat)device; retList = opc.OpcUa_Read(addresses); } if ((retList != null && retList.Count > 0 && retList[0].Equals(targetValue)) || "uploadProgram".Equals(body.BusinessType) || "deleteProgram".Equals(body.BusinessType)) { System.Threading.Thread.Sleep(3000); YG.Log.Instance.WriteLogAdd($"115------>>Start Http--------->>>"); string retJson = HttpPost(jsonData, HttpQuestUrlString); string code = GetJsonValue(retJson, "code"); if ((!string.IsNullOrEmpty(code) && code.Equals("0")) || retJson.Contains("错误的请求")) { list.Remove(body); } break; } } else if (device.Dtype.Equals(DeviceType.PLC_S7))//s7协议 { DeviceS7 s7 = (DeviceS7)device; if (node==null ||node.CheckAddress.StringIsEmpty()) { Log.Instance.WriteLogAdd($"119-->为空->{s7.DeviceName}"); } string retValue = s7.DeviceRead(node.CheckAddress, node.ReadType); // YG.Log.Instance.WriteLogAdd($"135------>>Start Http----{node.Address}---{node.Address}---{node.ReadType}----{s7.ServerUrl}-->>>"); if (targetValue.Contains("-")) { if (retValue.StringToInt() != targetValue.StringToInt()) { YG.Log.Instance.WriteLogAdd($"139------>>Start Http-------{node.Address}---{node.Address}---{node.ReadType}----{s7.ServerUrl}------>>>"); string retJson = HttpPost(jsonData, HttpQuestUrlString); string code = GetJsonValue(retJson, "code"); if ((!string.IsNullOrEmpty(code) && code.Equals("0")) || retJson.Contains("错误的请求")) { list.Remove(body); } break; } } else if (retValue.Equals(targetValue)) { YG.Log.Instance.WriteLogAdd($"152------>>Start Http----{node.Address}---{node.Address}---{node.ReadType}----{s7.ServerUrl}-->>>"); string retJson = HttpPost(jsonData, HttpQuestUrlString); string code = GetJsonValue(retJson, "code"); if ((!string.IsNullOrEmpty(code) && code.Equals("0")) || retJson.Contains("错误的请求")) { list.Remove(body); } break; } } else if (device.Dtype.Equals(DeviceType.Socket))//Socket协议 { } } } } // YG.Log.Instance.WriteLogAdd($"3333---->>>>"); //重置任务列表缓存 redis.ServiceStackRedisHelper.SetValue(redisCallBackKey, JsonConvert.SerializeObject(list).ToString(),LocalRedisString); } /// /// 根据json字符串的键得到键的值 /// /// /// /// private static string GetJsonValue(string strJson, string key) { string strResult = ""; if (!strJson.StartsWith("{") && !strJson.EndsWith("{")) { return strResult; } JObject jsonObj = JObject.Parse(strJson); strResult = GetNestJsonValue(jsonObj.Children(), key); return strResult; } /// /// 判断是否是json字符串 /// /// /// private static bool IsJson(string value) { bool result = false; if (!string.IsNullOrWhiteSpace(value) && value.Contains("[") && value.Contains(":")) { int leftcount = value.Replace("[", "").Length; int rightcount = value.Replace("]", "").Length; if (leftcount == rightcount) { result = true; } return result; } return result; } /// /// 根据key获取到字符串,并把字符串转换为wsm下发下来的指令类 /// /// /// private static List GetCallBackRequestList(string predisKey) { string redisKey = predisKey.Clone().ToString(); //YG.Log.Instance.WriteLogAdd($"4444--->>>{redisKey}"); string json = redis.ServiceStackRedisHelper.GetValue(redisKey, LocalRedisString); List list = new List(); try { if (IsJson(json)) { JsonReader reader = new JsonTextReader(new StringReader(json)); while (reader.Read()) { JArray array = (JArray)JsonConvert.DeserializeObject(reader.Value.ToString()); list = array.ToObject>(); } } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"190-->json:{json} errorMessage-->{ex.Message}"); } //YG.Log.Instance.WriteLogAdd($"666--->>{list.Json_SerializeObject()}"); return list; } /// /// 把回调内容发送给IMES /// /// /// /// private static string HttpPost(string pcontent, string prequestUrl) { string content = pcontent.Clone().ToString(); string requestUrl = prequestUrl.Clone().ToString(); YG.Log.Instance.WriteLogAdd($"httpPost-->{content}-->>{requestUrl}"); var responseString = ""; try { var request = (HttpWebRequest)WebRequest.Create(requestUrl); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; byte[] byteData = Encoding.UTF8.GetBytes(content); int length = byteData.Length; request.ContentLength = length; Stream writer = request.GetRequestStream(); writer.Write(byteData, 0, length); writer.Close(); var response = (HttpWebResponse)request.GetResponse(); responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd(); YG.Log.Instance.WriteLogAdd($"回调--->返回值-->>{responseString}-->>{pcontent}-->>{prequestUrl}"); return responseString; } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"215-->{ex.Message}"); responseString = ex.Message; return responseString; } return responseString; } public static List GetTargetList(string pmachine, string pparentKey) { string machine = pmachine.ToClone(); string parentKey = pparentKey.ToClone(); List machineList = new List(); List list = new List(); foreach (Node nd in nodeList) { if (nd.Key.ToUpper().Equals(machine.ToUpper())) { machineList = nd.Childs; break; } } foreach (Node nd in machineList) { if (nd.Key.ToUpper().Equals(parentKey.ToUpper())) { list = nd.Childs; break; } } return list; } public static Node GetTargetNode(string pmachine, string pparentKey) { string machine = pmachine.ToClone(); string parentKey = pparentKey.Clone().ToString(); Node machineNode = new Node(); Node targetNode = new Node(); foreach (Node nd in nodeList) { if (nd.Key.ToUpper().Equals(machine.ToUpper())) { machineNode = nd; break; } } foreach (Node nd in machineNode.Childs) { if (nd.Key.ToUpper().Equals(parentKey.ToUpper())) { targetNode = nd; break; } } return targetNode; } public static string GetBinaryBit(int vDecimal, int startPos, int endPos) { int retValue = 0; for (int i = startPos; i <= endPos; i++) { int v = vDecimal >> i & 1; if (v == 1) { retValue = i; break; } } if (startPos > 0) { retValue = retValue - startPos; } return retValue.ToString(); } private static string GetNestJsonValue(JEnumerable jToken, string key) { IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken)enumerator.Current; if (jc is JObject || ((JProperty)jc).Value is JObject) { return GetNestJsonValue(jc.Children(), key); } else { if (((JProperty)jc).Name == key) { return ((JProperty)jc).Value.ToString(); } } } return null; } public static void WriteAccessLog(string desc) { try { // 判断文件是否存在,不存在则创建,否则读取值显示到窗体 if (!File.Exists(LogFilePath)) { FileStream fs1 = new FileStream(LogFilePath, FileMode.Create, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fs1); sw.WriteLine(desc);//开始写入值 sw.WriteLine(desc);//开始写入值 sw.Close(); fs1.Close(); } else { FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write); StreamWriter sr = new StreamWriter(fs); sr.WriteLine(desc);//开始写入值 sr.Close(); fs.Close(); } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"333-->{ex.Message}"); Console.WriteLine(ex.Message); } } } }