CommonUtil.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Forms;
  4. using Newtonsoft.Json;
  5. using System.Net;
  6. using System.Text;
  7. using System.Configuration;
  8. using System.IO;
  9. using EasyModbusClient.businessBody;
  10. using YG.Device;
  11. using YG;
  12. using Newtonsoft.Json.Linq;
  13. using System.Collections;
  14. namespace EasyModbusClient.util
  15. {
  16. class CommonUtil
  17. {
  18. public static char SEPLIT_CHAR = ';';
  19. private static string CONNECT_DEVICEINFO_LIST = ConfigurationManager.AppSettings["ConncetionDeviceListString"];
  20. private static string HttpQuestUrlString = ConfigurationManager.AppSettings["HttpQuestUrlString"];
  21. private static string HttpServerUrlString = ConfigurationManager.AppSettings["HttpServerUrlString"];
  22. private static string ConncetionRedisString = ConfigurationManager.AppSettings["ConncetionRedisString"];
  23. private static string LogFilePath = ConfigurationManager.AppSettings["LogFilePath"] + "access_semens_" + string.Format("{0:yyyyMM}", DateTime.Now) + ".log";
  24. public static int BYTE_UNHSORT_LENGTH = 2;
  25. public static TreeExXMLCls m_ListExXML = new TreeExXMLCls();
  26. public static List<Node> nodeList = new List<Node>();
  27. public static int count = 1;
  28. private static string LocalRedisString = "";
  29. public static void InitXml()
  30. {
  31. nodeList = m_ListExXML.XMLToList(Application.StartupPath + "\\customer.xml");
  32. LocalRedisString= ConfigurationManager.AppSettings["LocalRedisString"];
  33. }
  34. /// <summary>
  35. /// 把当前接受到mes下发的内容转换为字符串存到redis里边,
  36. /// </summary>
  37. /// <param name="body"></param>
  38. /// <summary>
  39. ///
  40. /// </summary>
  41. /// <param name="pbody"></param>
  42. /// <param name="serverUrl"></param>
  43. public static void ResponseTaskList(CcsRequestBody pbody,string serverUrl)
  44. {
  45. CcsRequestBody body = (CcsRequestBody)pbody.clone();
  46. string redisKey = serverUrl + ":callback";
  47. if (body.IsCallBackFlag == 1)
  48. {
  49. try { if (redisKey.StringIsEmpty()) { YG.Log.Instance.WriteLogAdd($"46-->出现空的{body.Json_SerializeObject()}"); } } catch(Exception ex) { YG.Log.Instance.WriteLogAdd($"46--》出现空是{ex.Message}"); }
  50. List<CcsRequestBody> list = GetCallBackRequestList(redisKey);
  51. if (list == null || list.Count == 0)
  52. {
  53. list = new List<CcsRequestBody>();
  54. }
  55. //if (!list.Exists(o => o.TaskId == body.TaskId && o.TaskNodeId == body.TaskNodeId&&o.Uid==body.Uid))
  56. //{
  57. // list.Add(body);
  58. //}
  59. if (!list.Exists(o => o.Uid.Equals(body.Uid)))
  60. {
  61. list.Add(body);
  62. }
  63. string jsonData = JsonConvert.SerializeObject(list);
  64. // YG.Log.Instance.WriteLogAdd($"2222---->>>>");
  65. redis.ServiceStackRedisHelper.SetValue(redisKey, jsonData.ToString(),LocalRedisString);
  66. }
  67. }
  68. /// <summary>
  69. /// 执行回调函数,
  70. /// </summary>
  71. /// <param name="device"></param>
  72. /// <param name="url"></param>
  73. public static void CallBackRequest(DeviceList device)
  74. {
  75. string redisCallBackKey = device.ServerUrl + ":callback";
  76. try { if (redisCallBackKey.StringIsEmpty()) { YG.Log.Instance.WriteLogAdd($"77出现空的{device.ServerUrl}"); } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"77--》出现空是{ex.Message}"); }
  77. List<CcsRequestBody> list = GetCallBackRequestList(redisCallBackKey);
  78. lock (list)
  79. {
  80. foreach (CcsRequestBody body in list)
  81. {
  82. if (body.IsCallBackFlag == 1)
  83. {
  84. Node node = GetTargetNode(device.ServerUrl, body.BusinessType);
  85. if (string.IsNullOrWhiteSpace(node.Address)) { break; }
  86. string targetValue = node.TargetValue;
  87. //回调通知
  88. CallBackReuqestBody callBackBody = new CallBackReuqestBody();
  89. callBackBody.taskId = body.TaskId;
  90. callBackBody.taskNodeId = body.TaskNodeId;
  91. callBackBody.msg = body.Msg;
  92. callBackBody.uid = body.Uid;
  93. callBackBody.bizCallBackData = body.bizCallBackData;
  94. callBackBody.code = body.Data + "";
  95. string jsonData = JsonConvert.SerializeObject(callBackBody);
  96. //当设备是opcua 协议
  97. if (device.Dtype.Equals(DeviceType.OPCUa))
  98. {
  99. List<string> addresses = new List<string>();
  100. List<string> retList = new List<string>();
  101. if (!"uploadProgram".Equals(body.BusinessType) && !"deleteProgram".Equals(body.BusinessType))
  102. {
  103. addresses.Add(node.CheckAddress);
  104. DeviceOPCUat opc = (DeviceOPCUat)device;
  105. retList = opc.OpcUa_Read(addresses);
  106. }
  107. if ((retList != null && retList.Count > 0 && retList[0].Equals(targetValue)) || "uploadProgram".Equals(body.BusinessType) || "deleteProgram".Equals(body.BusinessType))
  108. {
  109. System.Threading.Thread.Sleep(3000);
  110. YG.Log.Instance.WriteLogAdd($"115------>>Start Http--------->>>");
  111. string retJson = HttpPost(jsonData, HttpQuestUrlString);
  112. string code = GetJsonValue(retJson, "code");
  113. if ((!string.IsNullOrEmpty(code) && code.Equals("0")) || retJson.Contains("错误的请求"))
  114. {
  115. list.Remove(body);
  116. }
  117. break;
  118. }
  119. }
  120. else if (device.Dtype.Equals(DeviceType.PLC_S7))//s7协议
  121. {
  122. DeviceS7 s7 = (DeviceS7)device;
  123. if (node==null
  124. ||node.CheckAddress.StringIsEmpty())
  125. {
  126. Log.Instance.WriteLogAdd($"119-->为空->{s7.DeviceName}");
  127. }
  128. string retValue = s7.DeviceRead(node.CheckAddress, node.ReadType);
  129. // YG.Log.Instance.WriteLogAdd($"135------>>Start Http----{node.Address}---{node.Address}---{node.ReadType}----{s7.ServerUrl}-->>>");
  130. if (targetValue.Contains("-"))
  131. {
  132. if (retValue.StringToInt() != targetValue.StringToInt())
  133. {
  134. YG.Log.Instance.WriteLogAdd($"139------>>Start Http-------{node.Address}---{node.Address}---{node.ReadType}----{s7.ServerUrl}------>>>");
  135. string retJson = HttpPost(jsonData, HttpQuestUrlString);
  136. string code = GetJsonValue(retJson, "code");
  137. if ((!string.IsNullOrEmpty(code) && code.Equals("0")) || retJson.Contains("错误的请求"))
  138. {
  139. list.Remove(body);
  140. }
  141. break;
  142. }
  143. }
  144. else if (retValue.Equals(targetValue))
  145. {
  146. YG.Log.Instance.WriteLogAdd($"152------>>Start Http----{node.Address}---{node.Address}---{node.ReadType}----{s7.ServerUrl}-->>>");
  147. string retJson = HttpPost(jsonData, HttpQuestUrlString);
  148. string code = GetJsonValue(retJson, "code");
  149. if ((!string.IsNullOrEmpty(code) && code.Equals("0")) || retJson.Contains("错误的请求"))
  150. {
  151. list.Remove(body);
  152. }
  153. break;
  154. }
  155. }
  156. else if (device.Dtype.Equals(DeviceType.Socket))//Socket协议
  157. {
  158. }
  159. }
  160. }
  161. }
  162. // YG.Log.Instance.WriteLogAdd($"3333---->>>>");
  163. //重置任务列表缓存
  164. redis.ServiceStackRedisHelper.SetValue(redisCallBackKey, JsonConvert.SerializeObject(list).ToString(),LocalRedisString);
  165. }
  166. /// <summary>
  167. /// 根据json字符串的键得到键的值
  168. /// </summary>
  169. /// <param name="strJson"></param>
  170. /// <param name="key"></param>
  171. /// <returns></returns>
  172. private static string GetJsonValue(string strJson, string key)
  173. {
  174. string strResult = "";
  175. if (!strJson.StartsWith("{") && !strJson.EndsWith("{"))
  176. {
  177. return strResult;
  178. }
  179. JObject jsonObj = JObject.Parse(strJson);
  180. strResult = GetNestJsonValue(jsonObj.Children(), key);
  181. return strResult;
  182. }
  183. /// <summary>
  184. /// 判断是否是json字符串
  185. /// </summary>
  186. /// <param name="value"></param>
  187. /// <returns></returns>
  188. private static bool IsJson(string value)
  189. {
  190. bool result = false;
  191. if (!string.IsNullOrWhiteSpace(value) && value.Contains("[") && value.Contains(":"))
  192. {
  193. int leftcount = value.Replace("[", "").Length;
  194. int rightcount = value.Replace("]", "").Length;
  195. if (leftcount == rightcount)
  196. {
  197. result = true;
  198. }
  199. return result;
  200. }
  201. return result;
  202. }
  203. /// <summary>
  204. /// 根据key获取到字符串,并把字符串转换为wsm下发下来的指令类
  205. /// </summary>
  206. /// <param name="redisKey"></param>
  207. /// <returns></returns>
  208. private static List<CcsRequestBody> GetCallBackRequestList(string predisKey)
  209. {
  210. string redisKey = predisKey.Clone().ToString();
  211. //YG.Log.Instance.WriteLogAdd($"4444--->>>{redisKey}");
  212. string json = redis.ServiceStackRedisHelper.GetValue(redisKey, LocalRedisString);
  213. List<CcsRequestBody> list = new List<CcsRequestBody>();
  214. try
  215. {
  216. if (IsJson(json))
  217. {
  218. JsonReader reader = new JsonTextReader(new StringReader(json));
  219. while (reader.Read())
  220. {
  221. JArray array = (JArray)JsonConvert.DeserializeObject(reader.Value.ToString());
  222. list = array.ToObject<List<CcsRequestBody>>();
  223. }
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. YG.Log.Instance.WriteLogAdd($"190-->json:{json} errorMessage-->{ex.Message}");
  229. }
  230. //YG.Log.Instance.WriteLogAdd($"666--->>{list.Json_SerializeObject()}");
  231. return list;
  232. }
  233. /// <summary>
  234. /// 把回调内容发送给IMES
  235. /// </summary>
  236. /// <param name="pcontent"></param>
  237. /// <param name="prequestUrl"></param>
  238. /// <returns></returns>
  239. private static string HttpPost(string pcontent, string prequestUrl)
  240. {
  241. string content = pcontent.Clone().ToString();
  242. string requestUrl = prequestUrl.Clone().ToString();
  243. YG.Log.Instance.WriteLogAdd($"httpPost-->{content}-->>{requestUrl}");
  244. var responseString = "";
  245. try
  246. {
  247. var request = (HttpWebRequest)WebRequest.Create(requestUrl);
  248. request.Method = "POST";
  249. request.ContentType = "application/json;charset=UTF-8";
  250. byte[] byteData = Encoding.UTF8.GetBytes(content);
  251. int length = byteData.Length;
  252. request.ContentLength = length;
  253. Stream writer = request.GetRequestStream();
  254. writer.Write(byteData, 0, length);
  255. writer.Close();
  256. var response = (HttpWebResponse)request.GetResponse();
  257. responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
  258. YG.Log.Instance.WriteLogAdd($"回调--->返回值-->>{responseString}-->>{pcontent}-->>{prequestUrl}");
  259. return responseString;
  260. }
  261. catch (Exception ex)
  262. {
  263. YG.Log.Instance.WriteLogAdd($"215-->{ex.Message}");
  264. responseString = ex.Message;
  265. return responseString;
  266. }
  267. return responseString;
  268. }
  269. public static List<Node> GetTargetList(string pmachine, string pparentKey)
  270. {
  271. string machine = pmachine.ToClone(); string parentKey = pparentKey.ToClone();
  272. List<Node> machineList = new List<Node>();
  273. List<Node> list = new List<Node>();
  274. foreach (Node nd in nodeList)
  275. {
  276. if (nd.Key.ToUpper().Equals(machine.ToUpper()))
  277. {
  278. machineList = nd.Childs;
  279. break;
  280. }
  281. }
  282. foreach (Node nd in machineList)
  283. {
  284. if (nd.Key.ToUpper().Equals(parentKey.ToUpper()))
  285. {
  286. list = nd.Childs;
  287. break;
  288. }
  289. }
  290. return list;
  291. }
  292. public static Node GetTargetNode(string pmachine, string pparentKey)
  293. {
  294. string machine = pmachine.ToClone(); string parentKey = pparentKey.Clone().ToString();
  295. Node machineNode = new Node();
  296. Node targetNode = new Node();
  297. foreach (Node nd in nodeList)
  298. {
  299. if (nd.Key.ToUpper().Equals(machine.ToUpper()))
  300. {
  301. machineNode = nd;
  302. break;
  303. }
  304. }
  305. foreach (Node nd in machineNode.Childs)
  306. {
  307. if (nd.Key.ToUpper().Equals(parentKey.ToUpper()))
  308. {
  309. targetNode = nd;
  310. break;
  311. }
  312. }
  313. return targetNode;
  314. }
  315. public static string GetBinaryBit(int vDecimal, int startPos, int endPos)
  316. {
  317. int retValue = 0;
  318. for (int i = startPos; i <= endPos; i++)
  319. {
  320. int v = vDecimal >> i & 1;
  321. if (v == 1)
  322. {
  323. retValue = i;
  324. break;
  325. }
  326. }
  327. if (startPos > 0)
  328. {
  329. retValue = retValue - startPos;
  330. }
  331. return retValue.ToString();
  332. }
  333. private static string GetNestJsonValue(JEnumerable<JToken> jToken, string key)
  334. {
  335. IEnumerator enumerator = jToken.GetEnumerator();
  336. while (enumerator.MoveNext())
  337. {
  338. JToken jc = (JToken)enumerator.Current;
  339. if (jc is JObject || ((JProperty)jc).Value is JObject)
  340. {
  341. return GetNestJsonValue(jc.Children(), key);
  342. }
  343. else
  344. {
  345. if (((JProperty)jc).Name == key)
  346. {
  347. return ((JProperty)jc).Value.ToString();
  348. }
  349. }
  350. }
  351. return null;
  352. }
  353. public static void WriteAccessLog(string desc)
  354. {
  355. try
  356. {
  357. // 判断文件是否存在,不存在则创建,否则读取值显示到窗体
  358. if (!File.Exists(LogFilePath))
  359. {
  360. FileStream fs1 = new FileStream(LogFilePath, FileMode.Create, FileAccess.Write);//创建写入文件
  361. StreamWriter sw = new StreamWriter(fs1);
  362. sw.WriteLine(desc);//开始写入值
  363. sw.WriteLine(desc);//开始写入值
  364. sw.Close();
  365. fs1.Close();
  366. }
  367. else
  368. {
  369. FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write);
  370. StreamWriter sr = new StreamWriter(fs);
  371. sr.WriteLine(desc);//开始写入值
  372. sr.Close();
  373. fs.Close();
  374. }
  375. }
  376. catch (Exception ex)
  377. {
  378. YG.Log.Instance.WriteLogAdd($"333-->{ex.Message}");
  379. Console.WriteLine(ex.Message);
  380. }
  381. }
  382. }
  383. }