Form_Main.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. using IMCS.Device;
  2. using IMCS_CCS.Utils.DeviceProtocol;
  3. using Newtonsoft.Json;
  4. using Opc.Ua;
  5. using Opc.Ua.Client;
  6. using SinumerikOpcUaAPI;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.ComponentModel;
  10. using System.Data;
  11. using System.Diagnostics;
  12. using System.Drawing;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Net.NetworkInformation;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. using YG.Device;
  22. namespace IMCS
  23. {
  24. public partial class Form_Main : Form
  25. {
  26. //public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/NCExtend/wks.dir/nc_program/";
  27. public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/Work Pieces/TEST/";
  28. //public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/NCExtend/";
  29. public string CHANNEL_NO = "1";
  30. public string TEMP_NC_NAME = "TEMP1.MPF"; //临时程序
  31. private uint currentToolArea = 1;
  32. string Listener_URL = "http://20.20.47.107:8010/opcua/";
  33. Server opcServer = null;
  34. //public Dictionary<string, Server> deviceList { get; set; } = new Dictionary<string, Server>();
  35. // 作为长连接进行bean的存储, key使用ip,
  36. Dictionary<string, Server> opcServerMap = new Dictionary<string, Server>();
  37. public Form_Main()
  38. {
  39. InitializeComponent();
  40. }
  41. private void Form1_Load(object sender, EventArgs e)
  42. {
  43. HttpListener httpListenner;
  44. httpListenner = new HttpListener();
  45. httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  46. httpListenner.Prefixes.Add(Listener_URL);
  47. httpListenner.Start();
  48. label1.Text = "HttpServer已开启:" + Listener_URL;
  49. new Thread(new ThreadStart(delegate
  50. {
  51. try
  52. {
  53. loop(httpListenner);
  54. }
  55. catch (Exception ex)
  56. {
  57. string ss = ex.ToString();
  58. httpListenner.Stop();
  59. /* Application.ExitThread();
  60. Application.Exit();
  61. Application.Restart();
  62. Process.GetCurrentProcess().Kill();*/
  63. }
  64. })).Start();
  65. }
  66. private void loop(HttpListener httpListenner)
  67. {
  68. while (true)
  69. {
  70. HttpListenerContext context = httpListenner.GetContext();
  71. context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
  72. HttpListenerRequest request = context.Request;
  73. HttpListenerResponse response = context.Response;
  74. Servlet servlet = new MyServlet();
  75. servlet.onCreate();
  76. if (request.HttpMethod == "POST")
  77. {
  78. if (!request.Url.ToString().Contains("favicon"))
  79. {
  80. RequestBody opcBody = null;
  81. ResponseBody responseBody = new ResponseBody();
  82. Server opcServer = null;
  83. try
  84. {
  85. Stream stream = context.Request.InputStream;
  86. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  87. string body = reader.ReadToEnd();
  88. YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);
  89. responseBody = new ResponseBody();
  90. opcBody = JsonConvert.DeserializeObject<RequestBody>(body);
  91. AddList(DateTime.Now.ToString(), "POST", opcBody.ServerUrl + opcBody.Type, "OK");
  92. /*
  93. * if (deviceList == null || (deviceList.Where(m => m.Key.Equals(opcBody.ServerUrl)).Count() == 0))
  94. {
  95. opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  96. if (opcServer.Session != null)
  97. {
  98. deviceList.Add(opcBody.ServerUrl, opcServer);
  99. }
  100. }
  101. else
  102. {
  103. opcServer = deviceList.Where(m => m.Key.Equals(opcBody.ServerUrl)).FirstOrDefault().Value;
  104. }
  105. if (opcServer == null || !opcServer.Session.Connected)
  106. {
  107. opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  108. }
  109. */
  110. //else
  111. //{
  112. // opcServer.Session.Reconnect();
  113. //}
  114. // 从map中取出opcServer 判断是否存在,以及是否可用
  115. opcServerMap.TryGetValue(opcBody.ServerUrl, out opcServer);
  116. // 如果key不存在,或者存在单连接不上,则需要重新创建连接
  117. if (!opcServerMap.ContainsKey(opcBody.ServerUrl) || !opcServer.Session.Connected)
  118. {
  119. Ping pingSender = new Ping();
  120. PingReply reply = pingSender.Send(opcBody.Ip);
  121. if (reply.Status == IPStatus.Success)
  122. {
  123. opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
  124. }
  125. if (opcServer != null && opcServer.Session != null && opcServer.Session.Connected)
  126. {
  127. // 存储Server bean
  128. opcServerMap.Add(opcBody.ServerUrl, opcServer);
  129. }
  130. }
  131. if (opcServer != null && 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. //string s = responseBody.runDatasInfo;
  142. opcBody.Addresses.Add("ns=2;s=/Channel/GeometricAxis/actFeedRate"); //进给倍率
  143. opcBody.Addresses.Add("ns=2;s=/Channel/Spindle/speedOvr");//主轴倍率
  144. opcBody.Addresses.Add("ns=2;s=/Channel/Spindle/actSpeed");//主轴实际速度
  145. opcBody.Addresses.Add("ns=2;s=/Channel/Spindle/driveLoad");//主轴负载
  146. opcBody.Addresses.Add("ns=2;s=/Channel/ProgramInfo/selectedWorkPProg");//主程序
  147. List<string> values = opcServer.ReadValues(opcBody.Addresses);
  148. RunDatasInfo runDatasInfo = new RunDatasInfo();
  149. for (int i = 0; i < values.Count; i++)
  150. {
  151. if (i == 0)
  152. {
  153. runDatasInfo.feedRate = values[i];
  154. }
  155. else if (i == 1)
  156. {
  157. runDatasInfo.spindleMagnification = values[i];
  158. }
  159. else if (i == 2)
  160. {
  161. runDatasInfo.spindleSpeed = values[i];
  162. }
  163. else if (i == 3)
  164. {
  165. runDatasInfo.spindleLoad = values[i];
  166. }
  167. }
  168. responseBody.runDatasInfo = JsonConvert.SerializeObject(runDatasInfo);
  169. //报警
  170. SinumerikOpcUaAPI.FilterDefinition m_filter = new SinumerikOpcUaAPI.FilterDefinition();
  171. m_filter.AreaId = new NodeId("Sinumerik", (ushort)2);
  172. m_filter.Severity = EventSeverity.Min;
  173. m_filter.IgnoreSuppressedOrShelved = true;
  174. m_filter.EventTypes = (IList<NodeId>)new NodeId[1]
  175. {
  176. ObjectTypeIds.ConditionType
  177. };
  178. m_filter.SelectClauses = m_filter.ConstructSelectClauses(opcServer.Session, ObjectTypeIds.ConditionType);
  179. for (int index = 0; index < m_filter.SelectClauses.Count<SimpleAttributeOperand>(); ++index)
  180. {
  181. responseBody.errorsInfo += m_filter.SelectClauses[index].ToString() + (object)index + " ";
  182. }
  183. }
  184. else if (opcBody.Type == ActionTypeEnum.ToolList.ToString())
  185. {
  186. List<ToolsInfo> toolInfoList = new List<ToolsInfo>();
  187. int index = 1;
  188. List<string> stringList = this.readVariables(opcServer, new string[6]
  189. {
  190. "/Tool/Catalogue/toolNo[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  191. "/Tool/Catalogue/toolIdent[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  192. "/Tool/Catalogue/toolInMag[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  193. "/Tool/Catalogue/toolInPlace[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  194. "/Tool/Catalogue/nrDuplo[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString()),
  195. "/Tool/Catalogue/numCuttEdges[u<Area index>, <Row index>]".Replace("<Area index>", this.currentToolArea.ToString()).Replace("<Row index>", index.ToString())
  196. }
  197. );
  198. ToolsInfo toolInfo = new ToolsInfo(); ;
  199. toolInfo.number = Convert.ToUInt16(stringList[0]) + "";
  200. //toolInfo.toolIdent = stringList[1];
  201. //toolInfo.toolInMag = Convert.ToUInt16(stringList[2]);
  202. //toolInfo.toolInPlace = Convert.ToUInt16(stringList[3]);
  203. //toolInfo.nrDuplo = Convert.ToUInt16(stringList[4]);
  204. //toolInfo.numCuttEdges = Convert.ToUInt16(stringList[5]);
  205. toolInfoList.Add(toolInfo);
  206. responseBody.toolsInfo = JsonConvert.SerializeObject(toolInfoList);
  207. }
  208. else if (opcBody.Type == ActionTypeEnum.Read.ToString())
  209. {
  210. responseBody.values = opcServer.ReadValues(opcBody.Addresses);
  211. }
  212. else if (opcBody.Type == ActionTypeEnum.Write.ToString())
  213. {
  214. opcServer.WriteValues(opcBody.Values, opcBody.Addresses);
  215. }
  216. else if (opcBody.Type == ActionTypeEnum.SelectNc.ToString()) // 选中程序
  217. {
  218. string sSelectedFileName = Path.GetFileName(opcBody.Path);
  219. string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + sSelectedFileName, Convert.ToUInt32(CHANNEL_NO)).status;
  220. if (status == "Good")
  221. {
  222. responseBody.msg = "选择程序成功";
  223. }
  224. else
  225. {
  226. responseBody.msg = "选择程序失败";
  227. }
  228. }
  229. else if (opcBody.Type == ActionTypeEnum.Upload.ToString()) //上传文件
  230. {
  231. string file = opcBody.Path;
  232. string serverPath = "";
  233. //选择临时文件
  234. try
  235. {
  236. string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + TEMP_NC_NAME, Convert.ToUInt32(CHANNEL_NO)).status;
  237. string extension = Path.GetExtension(file);
  238. if (string.IsNullOrWhiteSpace(extension))
  239. {
  240. responseBody.msg = "文件名不合法";
  241. }
  242. try
  243. {
  244. byte[] data = opcServer.ReadFile(file);
  245. serverPath = UPLOAD_NC_PATH + Path.GetFileName(file);
  246. Server.MethodCallResult methodCallResult = opcServer.MethodCallCopyFileToServer("/Methods/CopyFileToServer", serverPath, data, true);
  247. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  248. {
  249. responseBody.msg = "上传文件成功";
  250. YG.Log.Instance.WriteLogAdd(file + "上传文件成功");
  251. }
  252. else
  253. {
  254. responseBody.msg = "上传文件失败";
  255. YG.Log.Instance.WriteLogAdd(file + "上传文件失败");
  256. }
  257. // }
  258. }
  259. catch (Exception ex)
  260. {
  261. responseBody.msg = "上传文件失败===>" + ex.Message;
  262. responseBody.code = 0;
  263. responseBody.result = false;
  264. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  265. }
  266. }
  267. catch (Exception ex)
  268. {
  269. responseBody.msg = "上传文件失败===>" + ex.Message;
  270. YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
  271. }
  272. //设为主程序
  273. try
  274. {
  275. Server.MethodCallResult methodCallResult = opcServer.MethodCallSelectProgram(serverPath, Convert.ToUInt32(CHANNEL_NO));
  276. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  277. {
  278. responseBody.msg += "==设为主程序成功";
  279. YG.Log.Instance.WriteLogAdd(serverPath + "设为主程序成功");
  280. }
  281. else
  282. {
  283. responseBody.code = 0;
  284. responseBody.result = false;
  285. responseBody.msg += "==设为主程序失败";
  286. YG.Log.Instance.WriteLogAdd(serverPath + "设为主程序失败");
  287. }
  288. }
  289. catch (Exception ex)
  290. {
  291. responseBody.code = 0;
  292. responseBody.result = false;
  293. responseBody.msg = "设为主程序失败";
  294. YG.Log.Instance.WriteLogAdd($"设为主程序失败-->{ex.Message}");
  295. }
  296. }
  297. }
  298. else
  299. {
  300. responseBody.code = 0;
  301. responseBody.msg = "服务器离线,连不上opcUa";
  302. responseBody.result = false;
  303. }
  304. response.ContentType = "application/json;charset=UTF-8";
  305. response.ContentEncoding = Encoding.UTF8;
  306. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  307. string retJsonData = JsonConvert.SerializeObject(responseBody);
  308. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  309. {
  310. YG.Log.Instance.WriteLogAdd($"WMS--->>{responseBody.Json_SerializeObject()}--->>{body}\r\n");
  311. writer.Write(responseBody.Json_SerializeObject());
  312. writer.Close();
  313. response.Close();
  314. }
  315. }
  316. catch (Exception opcex)
  317. {
  318. AddList(DateTime.Now.ToString(), "POST", request.Url.ToString(), opcex.Message);
  319. }
  320. }
  321. }
  322. else if (request.HttpMethod == "GET")
  323. {
  324. if (!request.Url.ToString().Contains("favicon"))
  325. {
  326. string ip = request.QueryString["ip"];
  327. string port = request.QueryString["port"];
  328. string fun = request.QueryString["fun"];
  329. AddList(DateTime.Now.ToString(), "GET", ip + port + fun, "OK");
  330. }
  331. }
  332. response.Close();
  333. }
  334. }
  335. private List<string> readVariables(Server server, string[] variables)
  336. {
  337. List<string> nodeIdStrings = new List<string>();
  338. foreach (string variable in variables)
  339. {
  340. NodeId nodeId = new NodeId(variable, (ushort)2);
  341. nodeIdStrings.Add(nodeId.ToString());
  342. }
  343. return server.ReadValues(nodeIdStrings);
  344. }
  345. public class DeviceInfo
  346. {
  347. public string ConnectMsg
  348. { get; set; }
  349. public string ConnectErrorMsg
  350. { get; set; }
  351. public string CncSoftVersion
  352. { get; set; }
  353. public string CncType
  354. { get; set; }
  355. public string CncId
  356. { get; set; }
  357. public string CncMode
  358. { get; set; }
  359. public string RunStatus
  360. { get; set; }
  361. public string Products
  362. { get; set; }
  363. public string CycleTime
  364. { get; set; }
  365. public string RemainTime
  366. { get; set; }
  367. public string MainProg
  368. { get; set; }
  369. public string SetFeedSpeed
  370. { get; set; }
  371. public string ActFeedSpeed
  372. { get; set; }
  373. public string SetSpSpeed
  374. { get; set; }
  375. public string ActSpSpeed
  376. { get; set; }
  377. public string AxisName
  378. { get; set; }
  379. public string FeedRate
  380. { get; set; }
  381. public string SpRate
  382. { get; set; }
  383. public string MaxPos1
  384. { get; set; }
  385. public string MaxPos2
  386. { get; set; }
  387. public string MaxPos3
  388. { get; set; }
  389. public string RelPos1
  390. { get; set; }
  391. public string RelPos2
  392. { get; set; }
  393. public string RelPos3
  394. { get; set; }
  395. public string RemainPos1
  396. { get; set; }
  397. public string RemainPos2
  398. { get; set; }
  399. public string RemainPos3
  400. { get; set; }
  401. public string ToolNo
  402. { get; set; }
  403. public string LenthX
  404. { get; set; }
  405. public string LenthZ
  406. { get; set; }
  407. public string RadiusCompenNum
  408. { get; set; }
  409. public string LengthCompenNum
  410. { get; set; }
  411. public string ToolAbradeRadius
  412. { get; set; }
  413. public string ToolEdgePos
  414. { get; set; }
  415. public string IsAlarm
  416. { get; set; }
  417. public List<AlmInfo> AlmMsg { get; set; } = new List<AlmInfo>();
  418. public string ToolLife
  419. { get; set; }
  420. }
  421. public class AlmInfo
  422. {
  423. public string no { get; set; }
  424. public string msg { get; set; }
  425. }
  426. public class Servlet
  427. {
  428. public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
  429. public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
  430. public virtual void onCreate()
  431. {
  432. }
  433. }
  434. public void AddList(string dtime, string type, string url, string res)
  435. {
  436. this.Invoke(new Action(delegate ()
  437. {
  438. listView1.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
  439. ListViewItem lvi = new ListViewItem();
  440. lvi.Text = dtime;
  441. lvi.SubItems.Add(type);
  442. lvi.SubItems.Add(url);
  443. lvi.SubItems.Add(res);
  444. this.listView1.Items.Insert(0, lvi);
  445. if (this.listView1.Items.Count > 100)
  446. {
  447. this.listView1.Items.Clear();
  448. }
  449. this.listView1.EndUpdate(); //结束数据处理,UI界面一次性绘制。}
  450. }));
  451. }
  452. public class MyServlet : Servlet
  453. {
  454. public override void onCreate()
  455. {
  456. base.onCreate();
  457. }
  458. public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
  459. {
  460. Console.WriteLine("GET:" + request.Url);
  461. byte[] buffer = Encoding.UTF8.GetBytes(info);
  462. //string sss = request.QueryString["ty"];
  463. System.IO.Stream output = response.OutputStream;
  464. output.Write(buffer, 0, buffer.Length);
  465. // You must close the output stream.
  466. output.Close();
  467. //listener.Stop();
  468. }
  469. public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
  470. {
  471. Console.WriteLine("POST:" + request.Url);
  472. byte[] res = Encoding.UTF8.GetBytes("OK");
  473. response.OutputStream.Write(res, 0, res.Length);
  474. }
  475. }
  476. }
  477. }