Form1.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. if (hdhBody.Address != "")
  213. {
  214. RemotePath = RemotePath + "\\" + hdhBody.Address;
  215. }
  216. //上传
  217. dncPath = GenPath(RemotePath, sSelectedFile);
  218. //设置临时程序为主程序
  219. m_Automatic.SelectProgram(iChannel, tempDncPath);
  220. try
  221. { //删除上传文件,try异常防止文件不存在
  222. //m_FileSystem.DeleteFile(dncPath);
  223. }
  224. catch (Exception edel)
  225. {
  226. }
  227. //上传
  228. m_FileSystem.TransmitFile(hdhBody.Path, dncPath);
  229. //设当前上传程序为主程序
  230. m_Automatic.SelectProgram(iChannel, dncPath);
  231. }
  232. else if (hdhBody.Type == ActionTypeEnum.DeleteNc.ToString())
  233. {
  234. JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);
  235. string dncPath = GenPath(RemotePath, hdhBody.Path);
  236. m_FileSystem.DeleteFile(dncPath);
  237. }
  238. else if (hdhBody.Type == ActionTypeEnum.SelectNcProgram.ToString())//选中程序
  239. {
  240. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  241. string dncPath = GenPath(RemotePath, hdhBody.Path);
  242. m_Automatic.SelectProgram(iChannel, dncPath);
  243. }
  244. else if (hdhBody.Type == ActionTypeEnum.StartNcProgram.ToString())//启动程序备用
  245. {
  246. JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
  247. //m_Automatic.SelectProgram(iChannel, GenPath(RemotePath, hdhBody.Path));
  248. //Thread.Sleep(1000);
  249. m_Automatic.StartProgram(GenPath(RemotePath, hdhBody.Path));
  250. }
  251. else if (hdhBody.Type == ActionTypeEnum.Read.ToString())
  252. {
  253. }
  254. else if (hdhBody.Type == ActionTypeEnum.Write.ToString())
  255. {
  256. }
  257. else if (hdhBody.Type == ActionTypeEnum.ToolList.ToString())
  258. {
  259. IJHDataEntry2 ToolLine = null;
  260. IJHDataEntry2List ToolCells = null;
  261. //IJHDataEntry2 ToolCell = null;
  262. List<ToolsInfo> toolsList = new List<ToolsInfo>();
  263. JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
  264. dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");
  265. //string ToolColumnNamesAccessor = @"\TABLE\TOOL\T\('1'-'50')"; // see Init()
  266. string ToolColumnNamesAccessor = @"\TABLE\TOOL_P\T\('1'-'50')";
  267. IJHDataEntry2 ToolTable = dataAccess.GetDataEntry2(ToolColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  268. IJHDataEntry2List ToolLines = ToolTable.GetChildList();
  269. int ToolLinesCount = ToolLines.Count >= 50 ? 50 : ToolLines.Count;
  270. //int ToolLinesCount = ToolLines.Count;
  271. for (int i = 0; i < ToolLinesCount; i++)
  272. {
  273. ToolLine = ToolLines[i];
  274. ToolCells = ToolLine.GetChildList();
  275. // get child list from server
  276. ToolsInfo toolsInfo = new ToolsInfo();
  277. //刀位编码
  278. int[] pCode = ToolCells[0].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
  279. toolsInfo.position = string.Join(".", pCode);
  280. toolsInfo.number = ToolCells[1].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  281. toolsInfo.name = ToolCells[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  282. if (!String.IsNullOrEmpty(toolsInfo.name) && !String.IsNullOrEmpty(toolsInfo.number) && pCode.Length > 0 && pCode[1] > 0)
  283. {
  284. string ToolNumberAccessor = @"\TABLE\TOOL\T\" + toolsInfo.number.ToString();
  285. IJHDataEntry2List ToolList = dataAccess.GetDataEntry2(ToolNumberAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false).GetChildList();
  286. //报警期限
  287. toolsInfo.warnLife = ToolList[10].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  288. //刀具寿命目标值
  289. toolsInfo.targetLife = ToolList[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  290. //Cur_Time使用时间
  291. toolsInfo.curTime = ToolList[12].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
  292. toolsList.Add(toolsInfo);
  293. }
  294. }
  295. //获取海德汉的刀具寿命信息
  296. responseBody.toolsInfo = JsonConvert.SerializeObject(toolsList.Distinct().ToList());
  297. } else if (hdhBody.Type == ActionTypeEnum.ReadAndWriteTool.ToString()) {
  298. //机外对刀仪数据
  299. JObject jsonObject = JObject.Parse(hdhBody.CutterData);
  300. JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
  301. dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");
  302. /*刀具表数据修改*/
  303. //刀具表查询语句
  304. string ToolColumnNamesAccessor = @"\TABLE\TOOL\T\"+ jsonObject.GetValue("cutterT");
  305. //刀具表数据
  306. IJHDataEntry2 ToolTable = dataAccess.GetDataEntry2(ToolColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  307. // 获取字段列表
  308. IJHDataEntry2List ToolLines = ToolTable.GetChildList();
  309. //设置刀具名
  310. ToolLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterName"), false);
  311. //刀具长度
  312. ToolLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterZl"), false);
  313. //刀具半径
  314. ToolLines[3].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterXl"), false);
  315. //刀具寿命
  316. ToolLines[11].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterTime2"), false);
  317. //刀具类型
  318. ToolLines[13].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterTypDnc"), false);
  319. //PLC状态
  320. ToolLines[15].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterPlcBit"), false);
  321. //刀具使用寿命,不允许吧超过该值
  322. ToolLines[45].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterOverTime"), false);
  323. /*车刀表数据设置更新*/
  324. //车刀表数据查询语句
  325. string CheDaoColumnNamesAccessor = @"\TABLE\TOOLTURN\T\" + jsonObject.GetValue("cutterT");
  326. // 查询表数据
  327. IJHDataEntry2 CheDaoTable = dataAccess.GetDataEntry2(CheDaoColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  328. // 获取字段列表
  329. IJHDataEntry2List CheDaoLines = CheDaoTable.GetChildList();
  330. // 设置刀具名
  331. CheDaoLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterName"), false);
  332. // 设置刀具长度
  333. CheDaoLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterZl"), false);
  334. // 车刀X方向半径
  335. CheDaoLines[3].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterXl"), false);
  336. // 车刀方向
  337. CheDaoLines[10].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterTo"), false);
  338. // 主轴定向角
  339. CheDaoLines[11].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterOri"), false);
  340. // 设置车刀类型
  341. CheDaoLines[17].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterTypDncSub"), false);
  342. /*刀位表数据设置更新*/
  343. //刀位表数据查询语句
  344. string DaoWeiColumnNamesAccessor = @"\TABLE\TOOL_P\P\" + jsonObject.GetValue("cutterP");
  345. // 查询表数据
  346. IJHDataEntry2 DaoWeiTable = dataAccess.GetDataEntry2(DaoWeiColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
  347. // 获取字段列表
  348. IJHDataEntry2List DaoWeiLines = DaoWeiTable.GetChildList();
  349. // 设置刀号
  350. DaoWeiLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterT"), false);
  351. // 设置刀具名
  352. DaoWeiLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("cutterName"), false);
  353. responseBody.msg = "数据设置成功";
  354. responseBody.result = true;
  355. }
  356. }
  357. else
  358. {
  359. responseBody.msg = m_ControlState.ToString();
  360. responseBody.result = false;
  361. deviceList.Remove(hdhBody.MachineName);
  362. machineList.Remove(hdhBody.MachineName);
  363. }
  364. }
  365. }
  366. catch (Exception opcex)
  367. {
  368. YG.Log.Instance.WriteLogAdd($"海德汉响应异常--->>" + opcex.Message);
  369. AddList(DateTime.Now.ToString(), "POST", request.Url.ToString(), opcex.Message);
  370. responseBody.result = false;
  371. responseBody.msg = opcex.Message;
  372. //发生异常,清空数组,重新连接
  373. deviceList = new Dictionary<string, DNC_STATE>();
  374. machineList = new Dictionary<string, JHMachineInProcess>();
  375. }
  376. finally {
  377. AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":响应数据:" + responseBody.toolsInfo, responseBody.result ? "OK,消息消费成功" : "失败,消息消费失败" + m_ControlState != null ? m_ControlState.ToString() : "");
  378. response.ContentType = "application/json;charset=UTF-8";
  379. response.ContentEncoding = Encoding.UTF8;
  380. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  381. string retJsonData = JsonConvert.SerializeObject(responseBody);
  382. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  383. {
  384. YG.Log.Instance.WriteLogAdd($"海德汉响应结果--->>{JsonConvert.SerializeObject(JsonConvert.SerializeObject(responseBody))}--->>{body}\r\n");
  385. writer.Write(JsonConvert.SerializeObject(responseBody));
  386. writer.Close();
  387. response.Close();
  388. }
  389. }
  390. }
  391. }
  392. else if (request.HttpMethod == "GET")
  393. {
  394. if (!request.Url.ToString().Contains("favicon"))
  395. {
  396. string ip = request.QueryString["ip"];
  397. string port = request.QueryString["port"];
  398. string fun = request.QueryString["fun"];
  399. AddList(DateTime.Now.ToString(), "GET", ip + port + fun, "OK");
  400. }
  401. response.Close();
  402. }
  403. }
  404. private DNC_STATE connect(string connectName)
  405. {
  406. DNC_CNC_TYPE CncType ;
  407. IJHConnectionList connectionList = null;
  408. IJHConnection connection = null;
  409. try
  410. {
  411. JHMachineInProcess Machine = null;
  412. //第一次连接加入数组,以支持多台设备
  413. if (machineList == null || (machineList.Where(m => m.Key == connectName).Count() == 0))
  414. {
  415. Machine = new JHMachineInProcess();
  416. //DNC连接正常,加入数组
  417. machineList.Add(connectName, Machine);
  418. Thread.Sleep(20);
  419. }
  420. else
  421. {
  422. //取对应设备
  423. Machine = machineList.Where(m => m.Key == connectName).FirstOrDefault().Value;
  424. }
  425. Machine.ConnectRequest(connectName);
  426. string sCurrentMachine = Machine.currentMachine;
  427. // Find out control type
  428. connectionList = Machine.ListConnections();
  429. for (int i = 0; i < connectionList.Count; i++)
  430. {
  431. connection = connectionList[i];
  432. if (connection.name == sCurrentMachine)
  433. {
  434. CncType = connection.cncType;
  435. }
  436. if (connection != null)
  437. Marshal.ReleaseComObject(connection);
  438. }
  439. return Machine.GetState();
  440. }
  441. catch (COMException cex)
  442. {
  443. return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
  444. }
  445. catch (Exception ex)
  446. {
  447. return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
  448. }
  449. finally
  450. {
  451. if (connectionList != null)
  452. Marshal.ReleaseComObject(connectionList);
  453. if (connection != null)
  454. Marshal.ReleaseComObject(connection);
  455. }
  456. }
  457. private string GenPath(string part1, string part2)
  458. {
  459. string sFullPath = part1;
  460. switch (part2)
  461. {
  462. case ".":
  463. break;
  464. case "..":
  465. if (part1.EndsWith(@"\") && part1.Length > 5)
  466. part1 = part1.Substring(0, part1.Length - 3);
  467. int iLastFolderPos = part1.LastIndexOf(@"\");
  468. if (iLastFolderPos >= 0)
  469. sFullPath = part1.Substring(0, iLastFolderPos + 1);
  470. break;
  471. default:
  472. if (part1.EndsWith(@"\"))
  473. sFullPath = part1 + part2;
  474. else
  475. sFullPath = part1 + @"\" + part2;
  476. break;
  477. }
  478. return sFullPath;
  479. }
  480. public class Servlet
  481. {
  482. public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
  483. public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
  484. public virtual void onCreate()
  485. {
  486. }
  487. }
  488. public void AddList(string dtime, string type, string url, string res)
  489. {
  490. this.Invoke(new Action(delegate ()
  491. {
  492. listView1.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
  493. ListViewItem lvi = new ListViewItem();
  494. lvi.Text = dtime;
  495. lvi.SubItems.Add(type);
  496. lvi.SubItems.Add(url);
  497. lvi.SubItems.Add(res);
  498. this.listView1.Items.Insert(0, lvi);
  499. if (this.listView1.Items.Count > 100)
  500. {
  501. this.listView1.Items.Clear();
  502. }
  503. this.listView1.EndUpdate(); //结束数据处理,UI界面一次性绘制。}
  504. }));
  505. }
  506. public class MyServlet : Servlet
  507. {
  508. public override void onCreate()
  509. {
  510. base.onCreate();
  511. }
  512. public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
  513. {
  514. Console.WriteLine("GET:" + request.Url);
  515. byte[] buffer = Encoding.UTF8.GetBytes(info);
  516. //string sss = request.QueryString["ty"];
  517. System.IO.Stream output = response.OutputStream;
  518. output.Write(buffer, 0, buffer.Length);
  519. // You must close the output stream.
  520. output.Close();
  521. //listener.Stop();
  522. }
  523. public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
  524. {
  525. Console.WriteLine("POST:" + request.Url);
  526. byte[] res = Encoding.UTF8.GetBytes("OK");
  527. response.OutputStream.Write(res, 0, res.Length);
  528. }
  529. }
  530. }
  531. }