Form1.cs 38 KB

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