Form_Main.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. using HslCommunication.Enthernet;
  2. using IMCS.Device;
  3. using IMCS_CCS.Utils.DeviceProtocol;
  4. using Newtonsoft.Json;
  5. using Opc.Ua;
  6. using Opc.Ua.Client;
  7. using SinumerikOpcUaAPI;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.Diagnostics;
  13. using System.Drawing;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Runtime.Serialization.Formatters.Binary;
  18. using System.Runtime.Serialization;
  19. using System.Text;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using System.Windows.Forms;
  23. using YG;
  24. using YG.Device;
  25. using static SinumerikOpcUaAPI.Server;
  26. using System.Collections;
  27. using System.Runtime.Remoting.Messaging;
  28. using System.Reflection.Emit;
  29. using System.Runtime.Remoting.Channels;
  30. namespace IMCS
  31. {
  32. public partial class Form_Main : Form
  33. {
  34. //public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/Work Pieces/";
  35. public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/NCExtend/wks.dir/";
  36. //public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/Work Pieces/WORK_NC/";
  37. public string CHANNEL_NO = "1";
  38. public string TEMP_NC_NAME = "7999.MPF";
  39. private uint currentToolArea = 1;
  40. private ushort mNAMESPACE_INDEX = 2;
  41. // 作为长连接进行bean的存储, key使用ip,
  42. Dictionary<string, Server> opcServerMap = new Dictionary<string, Server>();
  43. Server opcServer = null;
  44. public Dictionary<string, Server> deviceList { get; set; } = new Dictionary<string, Server>();
  45. public Form_Main()
  46. {
  47. InitializeComponent();
  48. }
  49. private void Form1_Load(object sender, EventArgs e)
  50. {
  51. HttpListener httpListenner;
  52. httpListenner = new HttpListener();
  53. httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  54. httpListenner.Prefixes.Add("http://127.0.0.1:8010/opcua/");
  55. httpListenner.Start();
  56. label1.Text = "HttpServer已开启:http://127.0.0.1:8010/opcua/";
  57. new Thread(new ThreadStart(delegate
  58. {
  59. try
  60. {
  61. loop(httpListenner);
  62. }
  63. catch (Exception ex)
  64. {
  65. string ss = ex.ToString();
  66. httpListenner.Stop();
  67. /* Application.ExitThread();
  68. Application.Exit();
  69. Application.Restart();
  70. Process.GetCurrentProcess().Kill();*/
  71. }
  72. })).Start();
  73. }
  74. private void loop(HttpListener httpListenner)
  75. {
  76. while (true)
  77. {
  78. HttpListenerContext context = httpListenner.GetContext();
  79. context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
  80. HttpListenerRequest request = context.Request;
  81. HttpListenerResponse response = context.Response;
  82. Servlet servlet = new MyServlet();
  83. servlet.onCreate();
  84. if (request.HttpMethod == "POST")
  85. {
  86. if (!request.Url.ToString().Contains("favicon"))
  87. {
  88. RequestBody opcBody = null;
  89. try
  90. {
  91. Stream stream = context.Request.InputStream;
  92. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  93. string body = reader.ReadToEnd();
  94. YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);
  95. ResponseBody responseBody = new ResponseBody();
  96. opcBody = JsonConvert.DeserializeObject<RequestBody>(body);
  97. AddList(DateTime.Now.ToString(), "POST", opcBody.ServerUrl + opcBody.Type, "OK");
  98. /*if (deviceList == null || (deviceList.Where(m => m.Key.Equals(opcBody.ServerUrl)).Count() == 0))
  99. {
  100. opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  101. if (opcServer.Session != null)
  102. {
  103. deviceList.Add(opcBody.ServerUrl, opcServer);
  104. }
  105. }
  106. else
  107. {
  108. opcServer = deviceList.Where(m => m.Key.Equals(opcBody.ServerUrl)).FirstOrDefault().Value;
  109. }*/
  110. /*if (opcServer == null || !opcServer.Session.Connected)
  111. {
  112. opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  113. }*/
  114. // 从map中取出opcServer 判断是否存在,以及是否可用
  115. opcServerMap.TryGetValue(opcBody.ServerUrl, out opcServer);
  116. // 如果key不存在,或者存在单连接不上,则需要重新创建连接
  117. if (!opcServerMap.ContainsKey(opcBody.ServerUrl) || !opcServer.Session.Connected)
  118. {
  119. opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  120. if (opcServer != null && opcServer.Session != null && opcServer.Session.Connected) {
  121. // 存储Server bean
  122. opcServerMap.Add(opcBody.ServerUrl, opcServer);
  123. }
  124. }
  125. //opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  126. //opcServer.IsOn
  127. //else
  128. //{
  129. // opcServer.Session.Reconnect();
  130. //}
  131. if (opcServer.Session!=null && opcServer.Session.Connected)
  132. {
  133. if (opcBody.Type == ActionTypeEnum.Connect.ToString()) //连接状态
  134. {
  135. responseBody.result = true;
  136. }
  137. else if (opcBody.Type == ActionTypeEnum.Collect.ToString()) //采集
  138. {
  139. //ETH_S7Simens s7 = new ETH_S7Simens("192.168.11.164");
  140. //responseBody.runDatasInfo = JsonConvert.SerializeObject(s7.deviceInfo);
  141. // 封装需要采集字段的数据
  142. this.addAddress(opcBody);
  143. List<string> values = opcServer.ReadValues(opcBody.Addresses);
  144. responseBody.values = values;
  145. /*RunDatasInfo runDatasInfo = new RunDatasInfo();
  146. for (int i = 0; i < values.Count; i++)
  147. {
  148. if (i == 0)
  149. {
  150. runDatasInfo.feedRate = values[i];
  151. }
  152. else if (i == 1)
  153. {
  154. runDatasInfo.spindleMagnification = values[i];
  155. }
  156. else if (i == 2)
  157. {
  158. runDatasInfo.spindleSpeed = values[i];
  159. }
  160. else if (i == 3)
  161. {
  162. runDatasInfo.spindleLoad = values[i];
  163. }
  164. else if (i == 4)
  165. {
  166. runDatasInfo.mainPro = values[i];
  167. }
  168. else if (i == 5)
  169. {
  170. runDatasInfo.content = values[i];
  171. }
  172. }
  173. responseBody.runDatasInfo = JsonConvert.SerializeObject(runDatasInfo);*/
  174. /*//报警
  175. SinumerikOpcUaAPI.FilterDefinition m_filter = new SinumerikOpcUaAPI.FilterDefinition();
  176. m_filter.AreaId = new NodeId("Sinumerik", (ushort)2);
  177. m_filter.Severity = EventSeverity.Min;
  178. m_filter.IgnoreSuppressedOrShelved = true;
  179. m_filter.EventTypes = (IList<NodeId>)new NodeId[1]
  180. {
  181. ObjectTypeIds.ConditionType
  182. };
  183. m_filter.SelectClauses = m_filter.ConstructSelectClauses(opcServer.Session, ObjectTypeIds.ConditionType);
  184. for (int index = 0; index < m_filter.SelectClauses.Count<SimpleAttributeOperand>(); ++index)
  185. {
  186. responseBody.errorsInfo += m_filter.SelectClauses[index].ToString() + (object)index + " ";
  187. }*/
  188. }
  189. else if (opcBody.Type == ActionTypeEnum.ToolList.ToString())
  190. {
  191. List<string> nums = this.readVariables(opcServer, new string[1]
  192. {
  193. "/Tool/Catalogue/numTools[u<Area index>]".Replace("<Area index>", this.currentToolArea.ToString())
  194. }
  195. );
  196. int num = int.Parse(nums[0]);
  197. List<ToolsInfo> toolInfoList = new List<ToolsInfo>();
  198. for (int index = 1; index <= num; index++)
  199. {
  200. List<string> stringList = this.readVariables(opcServer, new string[10]
  201. {
  202. "/Tool/Catalogue/toolNo[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  203. "/Tool/Catalogue/toolIdent[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  204. "/Tool/Catalogue/toolInMag[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  205. "/Tool/Catalogue/toolInPlace[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  206. "/Tool/Catalogue/nrDuplo[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  207. "/Tool/Catalogue/numCuttEdges[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  208. "/Tool/Compensation/edgeData[u<Area index>,c<Column index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Column index>",index.ToString()).Replace("<Row index>", "3"),
  209. "/Tool/Compensation/edgeData[u<Area index>,c<Column index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Column index>",index.ToString()).Replace("<Row index>", "6"),
  210. "/Tool/Compensation/edgeData[u<Area index>,c<Column index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Column index>",index.ToString()).Replace("<Row index>", "12"),
  211. "/Tool/Compensation/edgeData[u<Area index>,c<Column index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Column index>",index.ToString()).Replace("<Row index>", "15")
  212. }
  213. );
  214. ToolsInfo toolInfo = new ToolsInfo(); ;
  215. toolInfo.number = Convert.ToUInt16(stringList[0]) + "";
  216. toolInfo.name = stringList[1];
  217. toolInfo.length = stringList[6];
  218. toolInfo.radius = stringList[7];
  219. toolInfo.wearLength = stringList[8];
  220. toolInfo.wearRadius = stringList[9];
  221. //toolInfo.toolInMag = Convert.ToUInt16(stringList[2]);
  222. //toolInfo.toolInPlace = Convert.ToUInt16(stringList[3]);
  223. //toolInfo.nrDuplo = Convert.ToUInt16(stringList[4]);
  224. //toolInfo.numCuttEdges = Convert.ToUInt16(stringList[5]);
  225. toolInfoList.Add(toolInfo);
  226. }
  227. responseBody.toolsInfo = JsonConvert.SerializeObject(toolInfoList);
  228. }
  229. else if (opcBody.Type == ActionTypeEnum.Read.ToString())
  230. {
  231. responseBody.values = opcServer.ReadValues(opcBody.Addresses);
  232. }
  233. else if (opcBody.Type == ActionTypeEnum.Write.ToString())
  234. {
  235. opcServer.WriteValues(opcBody.Values, opcBody.Addresses);
  236. }
  237. else if (opcBody.Type == ActionTypeEnum.SelectNc.ToString())
  238. {
  239. string sSelectedFileName = Path.GetFileName(opcBody.Path);
  240. string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + sSelectedFileName, Convert.ToUInt32(CHANNEL_NO)).status;
  241. if (status == "Good")
  242. {
  243. responseBody.msg = "选择成功";
  244. }
  245. else
  246. {
  247. responseBody.msg = "选择失败";
  248. }
  249. }
  250. else if (opcBody.Type == ActionTypeEnum.Upload.ToString())
  251. {
  252. string file = opcBody.Path;
  253. string serverPath = "";
  254. string status = "";
  255. //选择临时文件
  256. status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + TEMP_NC_NAME, Convert.ToUInt32(CHANNEL_NO)).status;
  257. try
  258. {
  259. string extension = Path.GetExtension(file);
  260. if (string.IsNullOrWhiteSpace(extension))
  261. {
  262. responseBody.msg = "文件名不合法";
  263. }
  264. try
  265. {
  266. byte[] data = opcServer.ReadFile(file);
  267. serverPath = UPLOAD_NC_PATH + Path.GetFileName(file);
  268. Server.MethodCallResult methodCallResult = opcServer.MethodCallCopyFileToServer("/Methods/CopyFileToServer", serverPath, data, true);
  269. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  270. {
  271. responseBody.msg = "上传文件成功";
  272. YG.Log.Instance.WriteLogAdd(file + "上传文件成功");
  273. }
  274. else
  275. {
  276. responseBody.msg = "上传文件失败";
  277. YG.Log.Instance.WriteLogAdd(file + "上传文件失败");
  278. }
  279. // }
  280. }
  281. catch (Exception ex)
  282. {
  283. responseBody.msg = "上传文件失败===>" + ex.Message;
  284. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  285. }
  286. }
  287. catch (Exception ex)
  288. {
  289. responseBody.msg = "上传文件失败===>" + ex.Message;
  290. YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
  291. }
  292. //设位主程序
  293. status = opcServer.MethodCallSelectProgram(serverPath, Convert.ToUInt32(CHANNEL_NO)).status;
  294. }
  295. else if (opcBody.Type == ActionTypeEnum.UploadFileList.ToString())
  296. {
  297. //选择临时文件
  298. string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + TEMP_NC_NAME, Convert.ToUInt32(CHANNEL_NO)).status;
  299. for (int i = 0; i < opcBody.subFileList.Count; i++)
  300. {
  301. string file = opcBody.subFileList[i];
  302. string serverPath = "";
  303. try
  304. {
  305. string extension = Path.GetExtension(file);
  306. if (string.IsNullOrWhiteSpace(extension))
  307. {
  308. responseBody.result = false;
  309. responseBody.msg = file + "==文件名不合法";
  310. break;
  311. }
  312. try
  313. {
  314. byte[] data = opcServer.ReadFile(file);
  315. serverPath = UPLOAD_NC_PATH + Path.GetFileName(file);
  316. Server.MethodCallResult methodCallResult = opcServer.MethodCallCopyFileToServer("/Methods/CopyFileToServer", serverPath, data, true);
  317. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  318. {
  319. responseBody.msg = "上传文件成功";
  320. YG.Log.Instance.WriteLogAdd(file + "上传文件成功");
  321. }
  322. else
  323. {
  324. responseBody.msg = "上传文件失败";
  325. responseBody.result = false;
  326. YG.Log.Instance.WriteLogAdd(file + "上传文件失败");
  327. break;
  328. }
  329. }
  330. catch (Exception ex)
  331. {
  332. responseBody.msg = "上传文件失败===>" + ex.Message;
  333. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  334. break;
  335. }
  336. }
  337. catch (Exception ex)
  338. {
  339. responseBody.msg = "上传文件失败===>" + ex.Message;
  340. responseBody.result = false;
  341. YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
  342. }
  343. }
  344. //设为主程序
  345. status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + opcBody.prgName, Convert.ToUInt32(CHANNEL_NO)).status;
  346. if (status != "Good")
  347. {
  348. responseBody.msg = "选择失败";
  349. responseBody.result = false;
  350. }
  351. }
  352. else if (opcBody.Type == ActionTypeEnum.DownLoad.ToString())
  353. {
  354. string file = opcBody.Path;
  355. string serverPath = "";
  356. try
  357. {
  358. string extension = Path.GetExtension(file);
  359. if (string.IsNullOrWhiteSpace(extension))
  360. {
  361. responseBody.msg = "文件名不合法";
  362. }
  363. try
  364. {
  365. //byte[] data = opcServer.ReadFile(file);
  366. serverPath = UPLOAD_NC_PATH + Path.GetFileName(file);
  367. // Server.MethodCallResult methodCallResult = opcServer.MethodCallCopyFileFromServer("/Methods/CopyFileFromServer", serverPath);
  368. //
  369. byte[] op = opcServer.ReadFile(serverPath);
  370. DiagnosticInfoCollection diagnosticInfos = null;
  371. CallMethodRequestCollection callMethodRequestCollection = new CallMethodRequestCollection();
  372. CallMethodResultCollection results = new CallMethodResultCollection();
  373. CallMethodRequest callMethodRequest = new CallMethodRequest();
  374. callMethodRequest.MethodId = new NodeId("/Methods/CopyFileFromServer", mNAMESPACE_INDEX);
  375. callMethodRequest.ObjectId = new NodeId("/Methods", mNAMESPACE_INDEX);
  376. callMethodRequest.InputArguments.Add(serverPath);
  377. //callMethodRequest.InputArguments.Add(data);
  378. callMethodRequestCollection.Add(callMethodRequest);
  379. RequestHeader requestHeader = new RequestHeader();
  380. ResponseHeader responseHeader = opcServer.Session.Call(null, callMethodRequestCollection, out results, out diagnosticInfos);
  381. Server.MethodCallResult methodCallResult = new MethodCallResult(results);
  382. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  383. {
  384. responseBody.msg = "上传文件成功";
  385. YG.Log.Instance.WriteLogAdd(file + "上传文件成功");
  386. Variant result3 = methodCallResult.results;
  387. byte[] buff;
  388. using (MemoryStream ms = new MemoryStream())
  389. {
  390. IFormatter iFormatter = new BinaryFormatter();
  391. iFormatter.Serialize(ms, result3.Value);
  392. buff = ms.GetBuffer();
  393. }
  394. // 将byte[]写入文件
  395. File.WriteAllBytes(file, buff);
  396. // 读取文件内容到字符串
  397. string fileContent = File.ReadAllText(file);
  398. fileContent = fileContent.Trim();
  399. // 去除字符串中的空格
  400. //string trimmedContent = fileContent.Trim(); // 使用Trim去除字符串首尾的空格
  401. // 或者使用Replace去除所有空格
  402. string trimmedContent = fileContent.Replace(" ", "");
  403. // 将处理过的字符串写回文件
  404. File.WriteAllText(file, trimmedContent);
  405. string aa = result3.ToString();
  406. }
  407. else
  408. {
  409. responseBody.msg = "上传文件失败";
  410. YG.Log.Instance.WriteLogAdd(file + "上传文件失败");
  411. }
  412. // }
  413. }
  414. catch (Exception ex)
  415. {
  416. responseBody.msg = "上传文件失败===>" + ex.Message;
  417. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  418. }
  419. }
  420. catch (Exception ex)
  421. {
  422. responseBody.msg = "上传文件失败===>" + ex.Message;
  423. YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
  424. }
  425. }
  426. else if (opcBody.Type == ActionTypeEnum.Delete.ToString())
  427. {
  428. string file = opcBody.Path;
  429. string serverPath = "";
  430. try
  431. {
  432. string extension = Path.GetExtension(file);
  433. if (string.IsNullOrWhiteSpace(extension))
  434. {
  435. responseBody.msg = "文件名不合法";
  436. }
  437. else
  438. {
  439. try
  440. {
  441. //byte[] data = opcServer.ReadFile(file);
  442. serverPath = UPLOAD_NC_PATH + Path.GetFileName(file);
  443. Server.MethodCallResult methodCallResult = opcServer.MethodCallDeleteFile(serverPath);
  444. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  445. {
  446. responseBody.msg = "删除文件成功";
  447. YG.Log.Instance.WriteLogAdd(file + "删除文件成功");
  448. }
  449. else
  450. {
  451. responseBody.msg = "上传文件失败";
  452. YG.Log.Instance.WriteLogAdd(file + "上传文件失败");
  453. }
  454. // }
  455. }
  456. catch (Exception ex)
  457. {
  458. responseBody.msg = "上传文件失败===>" + ex.Message;
  459. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  460. }
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. responseBody.msg = "上传文件失败===>" + ex.Message;
  466. YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
  467. }
  468. }
  469. else if (opcBody.Type == ActionTypeEnum.SynFile.ToString())
  470. {
  471. try
  472. {
  473. Server.MethodCallResult methodCallResult = opcServer.MethodCall("GetAllFiles", UPLOAD_NC_PATH);
  474. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  475. {
  476. responseBody.msg = "同步文件成功";
  477. }
  478. else
  479. {
  480. responseBody.msg = "同步文件失败";
  481. }
  482. // }
  483. }
  484. catch (Exception ex)
  485. {
  486. responseBody.msg = "同步文件失败===>" + ex.Message;
  487. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  488. }
  489. }
  490. }
  491. else
  492. {
  493. responseBody.code = 0;
  494. responseBody.msg = "服务器离线,连不上opcUa";
  495. responseBody.result = false;
  496. }
  497. YG.Log.Instance.WriteLogAdd("Disconnect!");
  498. response.ContentType = "application/json;charset=UTF-8";
  499. response.ContentEncoding = Encoding.UTF8;
  500. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  501. string retJsonData = JsonConvert.SerializeObject(responseBody);
  502. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  503. {
  504. YG.Log.Instance.WriteLogAdd($"WMS--->>{responseBody.Json_SerializeObject()}--->>{body}\r\n");
  505. writer.Write(responseBody.Json_SerializeObject());
  506. writer.Close();
  507. response.Close();
  508. }
  509. }
  510. catch (Exception opcex)
  511. {
  512. // 删除map中对应的bean
  513. opcServerMap.Remove(opcBody.ServerUrl);
  514. // 断开连接
  515. opcServer.Disconnect();
  516. AddList(DateTime.Now.ToString(), "POST", request.Url.ToString(), opcex.Message);
  517. }
  518. }
  519. }
  520. else if (request.HttpMethod == "GET")
  521. {
  522. if (!request.Url.ToString().Contains("favicon"))
  523. {
  524. string ip = request.QueryString["ip"];
  525. string port = request.QueryString["port"];
  526. string fun = request.QueryString["fun"];
  527. AddList(DateTime.Now.ToString(), "GET", ip + port + fun, "OK");
  528. }
  529. }
  530. response.Close();
  531. }
  532. }
  533. private List<string> readVariables(Server server, string[] variables)
  534. {
  535. List<string> nodeIdStrings = new List<string>();
  536. foreach (string variable in variables)
  537. {
  538. NodeId nodeId = new NodeId(variable, (ushort)2);
  539. nodeIdStrings.Add(nodeId.ToString());
  540. }
  541. return server.ReadValues(nodeIdStrings);
  542. }
  543. private void addAddress(RequestBody opcBody)
  544. {
  545. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX310.0");
  546. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX311.0");
  547. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX311.1");
  548. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX311.2");
  549. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX312.0");
  550. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX312.1");
  551. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX313.7");
  552. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX314.0");
  553. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX314.1");
  554. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX314.2");
  555. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX316.7");
  556. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX326.0");
  557. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX326.1");
  558. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX326.2");
  559. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX326.3");
  560. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX491.0");
  561. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX493.0");
  562. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX493.1");
  563. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX495.0");
  564. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX497.0");
  565. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX497.1");
  566. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX499.0");
  567. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX501.0");
  568. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX501.1");
  569. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.0");
  570. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.1");
  571. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.2");
  572. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.3");
  573. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.4");
  574. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.5");
  575. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.6");
  576. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX554.7");
  577. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.0");
  578. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.1");
  579. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.2");
  580. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.3");
  581. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.4");
  582. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.5");
  583. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.6");
  584. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX555.7");
  585. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX556.0");
  586. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX556.1");
  587. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX556.3");
  588. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX556.4");
  589. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX556.6");
  590. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX556.7");
  591. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX557.0");
  592. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX557.1");
  593. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX557.2");
  594. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX557.3");
  595. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX557.4");
  596. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX557.5");
  597. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX558.0");
  598. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX558.2");
  599. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX559.0");
  600. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX559.1");
  601. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX559.2");
  602. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX559.3");
  603. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX560.0");
  604. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX560.1");
  605. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX560.2");
  606. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX560.3");
  607. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX560.4");
  608. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX560.5");
  609. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX570.0");
  610. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.0");
  611. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.1");
  612. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.2");
  613. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.3");
  614. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.4");
  615. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.5");
  616. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.6");
  617. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX574.7");
  618. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX575.0");
  619. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX575.1");
  620. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX578.0");
  621. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX578.1");
  622. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX578.2");
  623. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX579.0");
  624. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX579.1");
  625. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX579.2");
  626. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX579.3");
  627. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX590.1");
  628. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX590.2");
  629. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX590.3");
  630. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX624.0");
  631. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX624.1");
  632. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX626.0");
  633. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX626.1");
  634. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX626.2");
  635. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX626.3");
  636. opcBody.Addresses.Add("ns=2;s=/Plc/DB2.DBX626.4");
  637. opcBody.Addresses.Add("ns=2;s=/Nck/SequencedAlarms/timeBCD");
  638. opcBody.Addresses.Add("ns=2;s=/Nck/SequencedAlarms/textIndex");
  639. opcBody.Addresses.Add("ns=2;s=/Channel/GeometricAxis/feedRateOvr");
  640. opcBody.Addresses.Add("ns=2;s=/Channel/Spindle/speedOvr");
  641. opcBody.Addresses.Add("ns=2;s=/Channel/Spindle/actSpeed");
  642. opcBody.Addresses.Add("ns=2;s=/Channel/MachineAxis/vaLoad");
  643. opcBody.Addresses.Add("ns=2;s=/Nck/ChannelDiagnose/setupTime");
  644. opcBody.Addresses.Add("ns=2;s=/Channel/ChannelDiagnose/operatingTime");
  645. opcBody.Addresses.Add("ns=2;s=/Channel/ProgramInfo/selectedWorkPProg");
  646. }
  647. public class DeviceInfo
  648. {
  649. public string ConnectMsg
  650. { get; set; }
  651. public string ConnectErrorMsg
  652. { get; set; }
  653. public string CncSoftVersion
  654. { get; set; }
  655. public string CncType
  656. { get; set; }
  657. public string CncId
  658. { get; set; }
  659. public string CncMode
  660. { get; set; }
  661. public string RunStatus
  662. { get; set; }
  663. public string Products
  664. { get; set; }
  665. public string CycleTime
  666. { get; set; }
  667. public string RemainTime
  668. { get; set; }
  669. public string MainProg
  670. { get; set; }
  671. public string SetFeedSpeed
  672. { get; set; }
  673. public string ActFeedSpeed
  674. { get; set; }
  675. public string SetSpSpeed
  676. { get; set; }
  677. public string ActSpSpeed
  678. { get; set; }
  679. public string AxisName
  680. { get; set; }
  681. public string FeedRate
  682. { get; set; }
  683. public string SpRate
  684. { get; set; }
  685. public string MaxPos1
  686. { get; set; }
  687. public string MaxPos2
  688. { get; set; }
  689. public string MaxPos3
  690. { get; set; }
  691. public string RelPos1
  692. { get; set; }
  693. public string RelPos2
  694. { get; set; }
  695. public string RelPos3
  696. { get; set; }
  697. public string RemainPos1
  698. { get; set; }
  699. public string RemainPos2
  700. { get; set; }
  701. public string RemainPos3
  702. { get; set; }
  703. public string ToolNo
  704. { get; set; }
  705. public string LenthX
  706. { get; set; }
  707. public string LenthZ
  708. { get; set; }
  709. public string RadiusCompenNum
  710. { get; set; }
  711. public string LengthCompenNum
  712. { get; set; }
  713. public string ToolAbradeRadius
  714. { get; set; }
  715. public string ToolEdgePos
  716. { get; set; }
  717. public string IsAlarm
  718. { get; set; }
  719. public List<AlmInfo> AlmMsg { get; set; } = new List<AlmInfo>();
  720. public string ToolLife
  721. { get; set; }
  722. }
  723. public class AlmInfo
  724. {
  725. public string no { get; set; }
  726. public string msg { get; set; }
  727. }
  728. public class Servlet
  729. {
  730. public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
  731. public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
  732. public virtual void onCreate()
  733. {
  734. }
  735. }
  736. public void AddList(string dtime, string type, string url, string res)
  737. {
  738. this.Invoke(new Action(delegate ()
  739. {
  740. listView1.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
  741. ListViewItem lvi = new ListViewItem();
  742. lvi.Text = dtime;
  743. lvi.SubItems.Add(type);
  744. lvi.SubItems.Add(url);
  745. lvi.SubItems.Add(res);
  746. this.listView1.Items.Insert(0, lvi);
  747. if (this.listView1.Items.Count > 100)
  748. {
  749. this.listView1.Items.Clear();
  750. }
  751. this.listView1.EndUpdate(); //结束数据处理,UI界面一次性绘制。}
  752. }));
  753. }
  754. public class MyServlet : Servlet
  755. {
  756. public override void onCreate()
  757. {
  758. base.onCreate();
  759. }
  760. public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
  761. {
  762. Console.WriteLine("GET:" + request.Url);
  763. byte[] buffer = Encoding.UTF8.GetBytes(info);
  764. //string sss = request.QueryString["ty"];
  765. System.IO.Stream output = response.OutputStream;
  766. output.Write(buffer, 0, buffer.Length);
  767. // You must close the output stream.
  768. output.Close();
  769. //listener.Stop();
  770. }
  771. public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
  772. {
  773. Console.WriteLine("POST:" + request.Url);
  774. byte[] res = Encoding.UTF8.GetBytes("OK");
  775. response.OutputStream.Write(res, 0, res.Length);
  776. }
  777. }
  778. }
  779. }