Form_Main.cs 24 KB

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