Form1.cs 35 KB

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