Form_Main.cs 27 KB

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