Form1.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. using HeidenhainDNCLib;
  2. using IMCS.HeidenHain;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. using HEIDENHAIN.body;
  18. using System.Net.NetworkInformation;
  19. namespace HEIDENHAIN
  20. {
  21. public partial class Form1 : Form
  22. {
  23. private int iChannel = 0;
  24. private string RemotePath = "TNC:\\nc_prog\\ATUO";//ConfigurationManager.AppSettings["RemotePath"];
  25. //连接设备列表
  26. public Dictionary<string, DNC_STATE> deviceList { get; set; } = new Dictionary<string, DNC_STATE>();
  27. private DNC_STATE m_ControlState;
  28. public Dictionary<string, JHMachineInProcess> machineList { get; set; } = new Dictionary<string, JHMachineInProcess>();
  29. //private JHMachineInProcess Machine = new JHMachineInProcess();
  30. // private JHAutomatic m_Automatic = null;
  31. // private JHFileSystem m_FileSystem = null;
  32. //private JHProcessData m_ProcessData = null;
  33. //private JHError m_Error = null;
  34. string Http_Request_Url = "http://127.0.0.1:8011/heidenhain/";
  35. bool _contine = true;//用于线程循环
  36. private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);//此处需要调用System.Threading;用于触发等待的线程已发生的事件(连接)
  37. public delegate void RecvAndSendHandler(HttpListenerContext s);//此处需要调用System.Net用于请求和响应HttpListener类
  38. public event RecvAndSendHandler RecvAndSend;
  39. AsyncCallback callback;
  40. HttpListenerContext context = null;
  41. public Form1()
  42. {
  43. InitializeComponent();
  44. }
  45. private void Form1_Load(object sender, EventArgs e)
  46. {
  47. this.RecvAndSend += new RecvAndSendHandler(HttpListen_RecvAndSend);
  48. #region 添加监听的信息线程添加到线程池
  49. WaitCallback wc = new WaitCallback(http_Listen);
  50. ThreadPool.QueueUserWorkItem(wc);
  51. label1.Text = "HttpServer已开启:" + Http_Request_Url;
  52. #endregion
  53. }
  54. /// <summary>
  55. /// 监听的线程
  56. /// </summary>
  57. /// <param name="ob"></param>
  58. private void http_Listen(object ob)
  59. {
  60. callback = new AsyncCallback(acceptCallback);
  61. HttpListener httpListenner;
  62. httpListenner = new HttpListener();
  63. httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  64. httpListenner.Prefixes.Add(Http_Request_Url);
  65. httpListenner.Start();
  66. while (_contine)
  67. {
  68. try
  69. {
  70. httpListenner.BeginGetContext(callback, httpListenner);
  71. autoConnectEvent.WaitOne();
  72. }
  73. catch (Exception)
  74. {
  75. }
  76. Thread.Sleep(10);
  77. }
  78. }
  79. /// <summary>
  80. /// 回调函数
  81. /// </summary>
  82. /// <param name="ar"></param>
  83. private void acceptCallback(IAsyncResult ar)
  84. {
  85. try
  86. {
  87. context = ((HttpListener)ar.AsyncState).EndGetContext(ar);
  88. }
  89. catch (Exception)
  90. {
  91. autoConnectEvent.Set();
  92. }
  93. if (context != null)
  94. {
  95. RecvAndSend(context);//触发我们一开始声明的事件
  96. autoConnectEvent.Set();
  97. }
  98. }
  99. /// <summary>
  100. /// 接听到消息的方法
  101. /// </summary>
  102. /// <param name="cont"></param>
  103. private void HttpListen_RecvAndSend(HttpListenerContext cont)
  104. {
  105. HttpListenerRequest request = cont.Request;
  106. HttpListenerResponse response = context.Response;
  107. Servlet servlet = new MyServlet();
  108. servlet.onCreate();
  109. if (request.HttpMethod == "POST")
  110. {
  111. if (!request.Url.ToString().Contains("favicon"))
  112. {
  113. try
  114. {
  115. Stream stream = context.Request.InputStream;
  116. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  117. string body = reader.ReadToEnd();
  118. //YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);
  119. ResponseBody responseBody = new ResponseBody();
  120. RequestBody hdhBody = JsonConvert.DeserializeObject<RequestBody>(body);
  121. AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":设备:" + hdhBody.MachineName, "OK");
  122. if (hdhBody.Type == ActionTypeEnum.Connect.ToString())
  123. {
  124. Ping pingSender = new Ping();
  125. PingReply reply = pingSender.Send(hdhBody.ServerUrl);
  126. if (reply.Status != IPStatus.Success)
  127. {
  128. responseBody.result = false;
  129. }
  130. }
  131. else
  132. {
  133. //第一次连接加入数组,以支持多台设备
  134. if (deviceList == null || (deviceList.Where(m => m.Key == hdhBody.MachineName).Count() == 0))
  135. {
  136. m_ControlState = connect(hdhBody.MachineName);
  137. //DNC连接正常,加入数组
  138. if (m_ControlState.ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE")
  139. {
  140. deviceList.Add(hdhBody.MachineName, m_ControlState);
  141. }
  142. Thread.Sleep(500);
  143. }
  144. else
  145. {
  146. //取设备对应的状态
  147. m_ControlState = deviceList.Where(m => m.Key == hdhBody.MachineName).FirstOrDefault().Value;
  148. }
  149. JHMachineInProcess Machine = machineList.Where(m => m.Key == hdhBody.MachineName).FirstOrDefault().Value;
  150. if (m_ControlState != null && m_ControlState.ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE")
  151. {
  152. JHError m_Error = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHERROR);
  153. JHErrorEntry2List errorsList = m_Error.GetErrorList();
  154. IJHErrorEntry2 pErrorEntry = null;
  155. for (int i = 0; i < errorsList.Count; i++)
  156. {
  157. pErrorEntry = errorsList[i];
  158. if (pErrorEntry != null && pErrorEntry.Text != null)
  159. {
  160. //Console.WriteLine("===" + pErrorEntry.Text.ToString());
  161. responseBody.errorsInfo += pErrorEntry.Text.ToString() + " ";
  162. }
  163. }
  164. if (hdhBody.Type == ActionTypeEnum.Collect.ToString())
  165. {
  166. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  167. JHProcessData m_ProcessData = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHPROCESSDATA);
  168. object pFeed = new object();
  169. object pSpeed = new object();
  170. object pRapid = new object();
  171. object proStatus = new object();
  172. //进出倍率 主轴倍率
  173. m_Automatic.GetOverrideInfo(ref pFeed, ref pSpeed, ref pRapid);
  174. m_Automatic.GetExecutionMode();
  175. DNC_STS_PROGRAM dncProgram = m_Automatic.GetProgramStatus();
  176. RunDatasInfo runDatasInfo = new RunDatasInfo();
  177. runDatasInfo.feedRate = pFeed.ToString();
  178. runDatasInfo.spindleMagnification = pSpeed.ToString();
  179. runDatasInfo.spindleSpeed = pRapid.ToString();
  180. responseBody.runDatasInfo = JsonConvert.SerializeObject(runDatasInfo);
  181. object oHours = new object();
  182. object oMinutes = new object();
  183. // --- NC uptime --------------------------------------------------------------------------
  184. m_ProcessData.GetNcUpTime(ref oHours, ref oMinutes);
  185. string ncUpTime = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString()));
  186. // --- Machine uptime ---------------------------------------------------------------------
  187. m_ProcessData.GetMachineUpTime(ref oHours, ref oMinutes);
  188. string machineUpTime = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString()));
  189. // --- Machine running time ---------------------------------------------------------------
  190. m_ProcessData.GetMachineRunningTime(ref oHours, ref oMinutes);
  191. string runningTimes = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString()));
  192. }
  193. else if (hdhBody.Type == ActionTypeEnum.Upload.ToString())
  194. {
  195. JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);
  196. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  197. string sSelectedFile = Path.GetFileName(hdhBody.Path);
  198. string dncPath = GenPath(RemotePath, sSelectedFile);
  199. string tempDncPath = RemotePath + "\\2.h";
  200. //设置临时程序为主程序
  201. m_Automatic.SelectProgram(iChannel, tempDncPath);
  202. try
  203. { //删除上传文件,try异常防止文件不存在
  204. //m_FileSystem.DeleteFile(dncPath);
  205. }
  206. catch (Exception edel)
  207. {
  208. }
  209. //上传
  210. m_FileSystem.TransmitFile(hdhBody.Path, dncPath);
  211. //设当前上传程序为主程序
  212. m_Automatic.SelectProgram(iChannel, dncPath);
  213. }
  214. else if (hdhBody.Type == ActionTypeEnum.DeleteNc.ToString())
  215. {
  216. JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);
  217. string dncPath = GenPath(RemotePath, hdhBody.Path);
  218. m_FileSystem.DeleteFile(dncPath);
  219. }
  220. else if (hdhBody.Type == ActionTypeEnum.SelectNcProgram.ToString())//选中程序
  221. {
  222. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  223. string dncPath = GenPath(RemotePath, hdhBody.Path);
  224. m_Automatic.SelectProgram(iChannel, dncPath);
  225. }
  226. else if (hdhBody.Type == ActionTypeEnum.StartNcProgram.ToString())//启动程序备用
  227. {
  228. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  229. //m_Automatic.SelectProgram(iChannel, GenPath(RemotePath, hdhBody.Path));
  230. //Thread.Sleep(1000);
  231. m_Automatic.StartProgram(GenPath(RemotePath, hdhBody.Path));
  232. }
  233. else if (hdhBody.Type == ActionTypeEnum.Read.ToString())
  234. {
  235. }
  236. else if (hdhBody.Type == ActionTypeEnum.Write.ToString())
  237. {
  238. }
  239. else if (hdhBody.Type == ActionTypeEnum.ToolList.ToString())
  240. {
  241. IJHDataEntry2 ToolLine = null;
  242. IJHDataEntry2List ToolCells = null;
  243. //IJHDataEntry2 ToolCell = null;
  244. List<ToolsInfo> toolsList = new List<ToolsInfo>();
  245. JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
  246. dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");
  247. //string ToolColumnNamesAccessor = @"\TABLE\TOOL\T\('1'-'50')"; // see Init()
  248. string ToolColumnNamesAccessor = @"\TABLE\TOOL_P\T\('1'-'50')";
  249. IJHDataEntry2 ToolTable = dataAccess.GetDataEntry2(ToolColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  250. IJHDataEntry2List ToolLines = ToolTable.GetChildList();
  251. int ToolLinesCount = ToolLines.Count >= 50 ? 50 : ToolLines.Count;
  252. //int ToolLinesCount = ToolLines.Count;
  253. for (int i = 0; i < ToolLinesCount; i++)
  254. {
  255. ToolLine = ToolLines[i];
  256. ToolCells = ToolLine.GetChildList();
  257. // get child list from server
  258. ToolsInfo toolsInfo = new ToolsInfo();
  259. //刀位编码
  260. int[] pCode = ToolCells[0].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
  261. toolsInfo.position = string.Join(".", pCode);
  262. toolsInfo.number = ToolCells[1].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  263. toolsInfo.name = ToolCells[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  264. if (!String.IsNullOrEmpty(toolsInfo.name) && !String.IsNullOrEmpty(toolsInfo.number) && pCode.Length>0 && pCode[1]>0)
  265. {
  266. string ToolNumberAccessor = @"\TABLE\TOOL\T\"+ toolsInfo.number.ToString();
  267. IJHDataEntry2List ToolList = dataAccess.GetDataEntry2(ToolNumberAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false).GetChildList();
  268. //报警期限
  269. toolsInfo.warnLife = ToolList[10].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  270. //刀具寿命目标值
  271. toolsInfo.targetLife = ToolList[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  272. //Cur_Time使用时间
  273. toolsInfo.curTime = ToolList[12].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  274. toolsList.Add(toolsInfo);
  275. }
  276. }
  277. //获取海德汉的刀具寿命信息
  278. responseBody.toolsInfo = JsonConvert.SerializeObject(toolsList.Distinct().ToList());
  279. }
  280. }
  281. else
  282. {
  283. responseBody.msg = m_ControlState.ToString();
  284. responseBody.result = false;
  285. deviceList.Remove(hdhBody.MachineName);
  286. }
  287. }
  288. AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":响应数据:" + responseBody.toolsInfo, responseBody.result ? "OK" : "失败:"+ m_ControlState != null ? m_ControlState.ToString():"");
  289. response.ContentType = "application/json;charset=UTF-8";
  290. response.ContentEncoding = Encoding.UTF8;
  291. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  292. string retJsonData = JsonConvert.SerializeObject(responseBody);
  293. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  294. {
  295. YG.Log.Instance.WriteLogAdd($"海德汉响应结果--->>{JsonConvert.SerializeObject(JsonConvert.SerializeObject(responseBody))}--->>{body}\r\n");
  296. writer.Write(JsonConvert.SerializeObject(responseBody));
  297. writer.Close();
  298. response.Close();
  299. }
  300. }
  301. catch (Exception opcex)
  302. {
  303. YG.Log.Instance.WriteLogAdd($"海德汉响应异常--->>" + opcex.Message);
  304. AddList(DateTime.Now.ToString(), "POST", request.Url.ToString(), opcex.Message);
  305. //发生异常,清空数组,重新连接
  306. deviceList = new Dictionary<string, DNC_STATE>();
  307. }
  308. }
  309. }
  310. else if (request.HttpMethod == "GET")
  311. {
  312. if (!request.Url.ToString().Contains("favicon"))
  313. {
  314. string ip = request.QueryString["ip"];
  315. string port = request.QueryString["port"];
  316. string fun = request.QueryString["fun"];
  317. AddList(DateTime.Now.ToString(), "GET", ip + port + fun, "OK");
  318. }
  319. response.Close();
  320. }
  321. }
  322. private DNC_STATE connect(string connectName)
  323. {
  324. DNC_CNC_TYPE CncType ;
  325. IJHConnectionList connectionList = null;
  326. IJHConnection connection = null;
  327. try
  328. {
  329. JHMachineInProcess Machine = null;
  330. //第一次连接加入数组,以支持多台设备
  331. if (machineList == null || (machineList.Where(m => m.Key == connectName).Count() == 0))
  332. {
  333. Machine = new JHMachineInProcess();
  334. //DNC连接正常,加入数组
  335. machineList.Add(connectName, Machine);
  336. Thread.Sleep(20);
  337. }
  338. else
  339. {
  340. //取对应设备
  341. Machine = machineList.Where(m => m.Key == connectName).FirstOrDefault().Value;
  342. }
  343. Machine.ConnectRequest(connectName);
  344. string sCurrentMachine = Machine.currentMachine;
  345. // Find out control type
  346. connectionList = Machine.ListConnections();
  347. for (int i = 0; i < connectionList.Count; i++)
  348. {
  349. connection = connectionList[i];
  350. if (connection.name == sCurrentMachine)
  351. {
  352. CncType = connection.cncType;
  353. }
  354. if (connection != null)
  355. Marshal.ReleaseComObject(connection);
  356. }
  357. return Machine.GetState();
  358. }
  359. catch (COMException cex)
  360. {
  361. return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
  362. }
  363. catch (Exception ex)
  364. {
  365. return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
  366. }
  367. finally
  368. {
  369. if (connectionList != null)
  370. Marshal.ReleaseComObject(connectionList);
  371. if (connection != null)
  372. Marshal.ReleaseComObject(connection);
  373. }
  374. }
  375. private string GenPath(string part1, string part2)
  376. {
  377. string sFullPath = part1;
  378. switch (part2)
  379. {
  380. case ".":
  381. break;
  382. case "..":
  383. if (part1.EndsWith(@"\") && part1.Length > 5)
  384. part1 = part1.Substring(0, part1.Length - 3);
  385. int iLastFolderPos = part1.LastIndexOf(@"\");
  386. if (iLastFolderPos >= 0)
  387. sFullPath = part1.Substring(0, iLastFolderPos + 1);
  388. break;
  389. default:
  390. if (part1.EndsWith(@"\"))
  391. sFullPath = part1 + part2;
  392. else
  393. sFullPath = part1 + @"\" + part2;
  394. break;
  395. }
  396. return sFullPath;
  397. }
  398. public class Servlet
  399. {
  400. public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
  401. public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
  402. public virtual void onCreate()
  403. {
  404. }
  405. }
  406. public void AddList(string dtime, string type, string url, string res)
  407. {
  408. this.Invoke(new Action(delegate ()
  409. {
  410. listView1.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
  411. ListViewItem lvi = new ListViewItem();
  412. lvi.Text = dtime;
  413. lvi.SubItems.Add(type);
  414. lvi.SubItems.Add(url);
  415. lvi.SubItems.Add(res);
  416. this.listView1.Items.Insert(0, lvi);
  417. if (this.listView1.Items.Count > 100)
  418. {
  419. this.listView1.Items.Clear();
  420. }
  421. this.listView1.EndUpdate(); //结束数据处理,UI界面一次性绘制。}
  422. }));
  423. }
  424. public class MyServlet : Servlet
  425. {
  426. public override void onCreate()
  427. {
  428. base.onCreate();
  429. }
  430. public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
  431. {
  432. Console.WriteLine("GET:" + request.Url);
  433. byte[] buffer = Encoding.UTF8.GetBytes(info);
  434. //string sss = request.QueryString["ty"];
  435. System.IO.Stream output = response.OutputStream;
  436. output.Write(buffer, 0, buffer.Length);
  437. // You must close the output stream.
  438. output.Close();
  439. //listener.Stop();
  440. }
  441. public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
  442. {
  443. Console.WriteLine("POST:" + request.Url);
  444. byte[] res = Encoding.UTF8.GetBytes("OK");
  445. response.OutputStream.Write(res, 0, res.Length);
  446. }
  447. }
  448. }
  449. }