Form_Main.cs 51 KB

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