Form_Main.cs 26 KB

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