123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410 |
- 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<Node> nodeList = new List<Node>();
- 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"];
- }
- /// <summary>
- /// 把当前接受到mes下发的内容转换为字符串存到redis里边,
- /// </summary>
- /// <param name="body"></param>
- /// <summary>
- ///
- /// </summary>
- /// <param name="pbody"></param>
- /// <param name="serverUrl"></param>
- 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<CcsRequestBody> list = GetCallBackRequestList(redisKey);
- if (list == null || list.Count == 0)
- {
- list = new List<CcsRequestBody>();
- }
- //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);
- }
- }
- /// <summary>
- /// 执行回调函数,
- /// </summary>
- /// <param name="device"></param>
- /// <param name="url"></param>
- 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<CcsRequestBody> 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<string> addresses = new List<string>();
- List<string> retList = new List<string>();
- 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);
- }
- /// <summary>
- /// 根据json字符串的键得到键的值
- /// </summary>
- /// <param name="strJson"></param>
- /// <param name="key"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 判断是否是json字符串
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 根据key获取到字符串,并把字符串转换为wsm下发下来的指令类
- /// </summary>
- /// <param name="redisKey"></param>
- /// <returns></returns>
- private static List<CcsRequestBody> GetCallBackRequestList(string predisKey)
- {
- string redisKey = predisKey.Clone().ToString();
- //YG.Log.Instance.WriteLogAdd($"4444--->>>{redisKey}");
-
- string json = redis.ServiceStackRedisHelper.GetValue(redisKey, LocalRedisString);
- List<CcsRequestBody> list = new List<CcsRequestBody>();
- 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<List<CcsRequestBody>>();
- }
- }
- }
- catch (Exception ex)
- {
- YG.Log.Instance.WriteLogAdd($"190-->json:{json} errorMessage-->{ex.Message}");
- }
- //YG.Log.Instance.WriteLogAdd($"666--->>{list.Json_SerializeObject()}");
- return list;
- }
- /// <summary>
- /// 把回调内容发送给IMES
- /// </summary>
- /// <param name="pcontent"></param>
- /// <param name="prequestUrl"></param>
- /// <returns></returns>
- 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<Node> GetTargetList(string pmachine, string pparentKey)
- {
- string machine = pmachine.ToClone(); string parentKey = pparentKey.ToClone();
- List<Node> machineList = new List<Node>();
- List<Node> list = new List<Node>();
- 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> 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);
- }
- }
- }
- }
|