Form_Main.cs 22 KB

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