using HeidenhainDNCLib; using Newtonsoft.Json; using RequestServer.HttpServer; using ResponseServer.HttpServer; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Fanuc_HttpServer.hedidenain { class HeidenhainServer { private int iChannel = 0; private string RemotePath = "TNC:\\nc_prog\\ATUO";//ConfigurationManager.AppSettings["RemotePath"]; private static string ON_LINE_STATE = "在线"; private Dictionary> jcIpDict = new Dictionary>(); //连接设备列表 public Dictionary deviceList { get; set; } = new Dictionary(); private DNC_STATE m_ControlState; public static Dictionary machineList { get; set; } = new Dictionary(); public HeidenhainServer() { List ip1 = new List(); ip1.Add("\\PLC\\memory\\D\\17600"); ip1.Add("\\PLC\\memory\\D\\4448"); jcIpDict.Add("192.168.10.109", ip1); List ip2 = new List(); ip2.Add("\\PLC\\memory\\D\\368"); ip2.Add("\\PLC\\memory\\D\\5048"); jcIpDict.Add("192.168.10.101", ip2); } public ResponseBody requestHttpServer(RequestBody requestBody) { string ip = requestBody.serverUrl; string port = requestBody.port; string fun = requestBody.type; ResponseBody responseBody = new ResponseBody(); JHMachineInProcess Machine = null; if (fun == ActionTypeEnum.Collect.ToString()) { Ping pingSender = new Ping(); PingReply reply = pingSender.Send(requestBody.serverUrl); if (reply.Status != IPStatus.Success) { //responseBody.result = false; responseBody.msg = "调用失败"; } else { //第一次连接加入数组,以支持多台设备 if (machineList == null || (machineList.Where(m => m.Key == requestBody.machineName).Count() == 0)) { DNC_STATE m_ControlState = connect(requestBody.machineName); Thread.Sleep(100); } //DNC连接正常,获取连接Machine = machineList.Where(m => m.Key == requestBody.machineName).FirstOrDefault().Value; Machine = machineList.Where(m => m.Key == requestBody.machineName).FirstOrDefault().Value; if (Machine != null) { try { if (Machine.GetState().ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE") { responseBody.deviceState = ON_LINE_STATE; JHError m_Error = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHERROR); JHErrorEntry2List errorsList = m_Error.GetErrorList(); IJHErrorEntry2 pErrorEntry = null; for (int i = 0; i < errorsList.Count; i++) { pErrorEntry = errorsList[i]; if (pErrorEntry != null && pErrorEntry.Text != null) { //Console.WriteLine("===" + pErrorEntry.Text.ToString()); responseBody.errorsInfo += pErrorEntry.Text.ToString() + " "; } } if (fun == ActionTypeEnum.Collect.ToString()) { JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC); JHProcessData m_ProcessData = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHPROCESSDATA); object pFeed = new object(); object pSpeed = new object(); object pRapid = new object(); object proStatus = new object(); //进出倍率 主轴倍率 m_Automatic.GetOverrideInfo(ref pFeed, ref pSpeed, ref pRapid); //主程序 object pSelectedProgram = new object(); ; m_Automatic.GetExecutionPoint(ref pSelectedProgram); responseBody.mainProg = pSelectedProgram.ToString(); m_Automatic.GetExecutionMode(); DNC_STS_PROGRAM dncProgram = m_Automatic.GetProgramStatus(); RunDatasInfo runDatasInfo = new RunDatasInfo(); responseBody.feedRateOvr = pFeed.ToString(); responseBody.spindleMagnification = pSpeed.ToString(); //responseBody.actSpindle = pRapid.ToString(); //计算开机时长 object oHours = new object(); object oMinutes = new object(); // --- NC uptime -------------------------------------------------------------------------- m_ProcessData.GetNcUpTime(ref oHours, ref oMinutes); string ncUpTime = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString())); // --- Machine uptime --------------------------------------------------------------------- m_ProcessData.GetMachineUpTime(ref oHours, ref oMinutes); string machineUpTime = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString())); // --- Machine running time --------------------------------------------------------------- m_ProcessData.GetMachineRunningTime(ref oHours, ref oMinutes); string runningTimes = oHours.ToString() + ":" + (Convert.ToInt32(oMinutes) > 9 ? oMinutes.ToString() : ("0" + oMinutes.ToString())); responseBody.powerOnTime = (Convert.ToInt32(oHours) * 60 + Convert.ToInt32(oMinutes)).ToString(); JHDataAccess m_DataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS); HeidenhainDNCLib.DNC_ACCESS_MODE accessModeEnum = (HeidenhainDNCLib.DNC_ACCESS_MODE)Enum.Parse(typeof(HeidenhainDNCLib.DNC_ACCESS_MODE), "DNC_ACCESS_MODE_PLCDATAACCESS"); m_DataAccess.SetAccessMode(accessModeEnum, "807667"); List param = jcIpDict[ip]; for (int j = 0; j < param.Count; j++) { IJHDataEntry m_DataEntry = m_DataAccess.GetDataEntry(param[j]); IJHDataEntryPropertyList dataEntryPropertyList = m_DataEntry.propertyList; for (int i = 0; i < dataEntryPropertyList.Count; i++) { IJHDataEntryProperty dataEntryProperty = dataEntryPropertyList[i]; if (dataEntryProperty.kind == DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA) { if (j == 0) { if (ip == "192.168.10.109") { responseBody.actSpindle = (Convert.ToInt32(dataEntryProperty.varValue) / 1000).ToString(); } else { responseBody.actSpindle = dataEntryProperty.varValue.ToString(); } } else if (j == 1) { responseBody.actFeed = dataEntryProperty.varValue.ToString(); } } } } } else if (fun == ActionTypeEnum.Upload.ToString()) { JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM); JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC); string sSelectedFile = Path.GetFileName(requestBody.path); string dncPath = GenPath(RemotePath, sSelectedFile); string tempDncPath = RemotePath + "\\2.h"; //设置临时程序为主程序 // m_Automatic.SelectProgram(iChannel, tempDncPath); try { //删除上传文件,try异常防止文件不存在 //m_FileSystem.DeleteFile(dncPath); } catch (Exception edel) { } //上传 m_FileSystem.TransmitFile(requestBody.path, dncPath); //设当前上传程序为主程序 // m_Automatic.SelectProgram(iChannel, dncPath); } else if (fun == ActionTypeEnum.StartNcProgram.ToString())//启动程序备用 { JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC); //m_Automatic.SelectProgram(iChannel, GenPath(RemotePath, hdhBody.Path)); //Thread.Sleep(1000); m_Automatic.StartProgram(GenPath(RemotePath, requestBody.path)); } else if (fun == ActionTypeEnum.ToolList.ToString()) { IJHDataEntry2 ToolLine = null; IJHDataEntry2List ToolCells = null; //IJHDataEntry2 ToolCell = null; List toolsList = new List(); JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS); dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, ""); //string ToolColumnNamesAccessor = @"\TABLE\TOOL\T\('1'-'50')"; // see Init() string ToolColumnNamesAccessor = @"\TABLE\TOOL_P\T\('1'-'50')"; IJHDataEntry2 ToolTable = dataAccess.GetDataEntry2(ToolColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false); IJHDataEntry2List ToolLines = ToolTable.GetChildList(); int ToolLinesCount = ToolLines.Count >= 50 ? 50 : ToolLines.Count; //int ToolLinesCount = ToolLines.Count; for (int i = 0; i < ToolLinesCount; i++) { ToolLine = ToolLines[i]; ToolCells = ToolLine.GetChildList(); // get child list from server ToolsInfo toolsInfo = new ToolsInfo(); //刀位编码 int[] pCode = ToolCells[0].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA); toolsInfo.position = string.Join(".", pCode); toolsInfo.number = ToolCells[1].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString(); toolsInfo.name = ToolCells[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString(); if (!String.IsNullOrEmpty(toolsInfo.name) && !String.IsNullOrEmpty(toolsInfo.number) && pCode.Length > 0 && pCode[1] > 0) { string ToolNumberAccessor = @"\TABLE\TOOL\T\" + toolsInfo.number.ToString(); IJHDataEntry2List ToolList = dataAccess.GetDataEntry2(ToolNumberAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false).GetChildList(); //报警期限 toolsInfo.warnLife = ToolList[10].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString(); //刀具寿命目标值 toolsInfo.targetLife = ToolList[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString(); //Cur_Time使用时间 toolsInfo.curTime = ToolList[12].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString(); toolsList.Add(toolsInfo); } } //获取海德汉的刀具寿命信息 responseBody.toolsInfo = toolsList; } } else if (Machine.GetState().ToString() != "DNC_STATE_MACHINE_IS_AVAILABLE") //机床状态不可用 断开连接 { responseBody.msg = Machine.GetState().ToString(); responseBody.result = false; Machine.Disconnect(); Marshal.ReleaseComObject(Machine); Machine = null; machineList.Remove(requestBody.machineName); } } catch(Exception e) { YG.Log.Instance.WriteLogAdd($"海德汉响应结果-e-->> " + e.Message); //responseBody.msg = Machine.GetState().ToString(); responseBody.msg = "海德汉响应失败"; responseBody.result = false; //Machine.Disconnect(); //Marshal.ReleaseComObject(Machine); Machine = null; if (machineList.ContainsKey(requestBody.machineName)) { machineList.Remove(requestBody.machineName); } } } } } return responseBody; } private DNC_STATE connect(string connectName) { DNC_CNC_TYPE CncType; IJHConnectionList connectionList = null; IJHConnection connection = null; try { JHMachineInProcess Machine = new JHMachineInProcess(); Machine.ConnectRequest(connectName); string sCurrentMachine = Machine.currentMachine; // Find out control type connectionList = Machine.ListConnections(); for (int i = 0; i < connectionList.Count; i++) { connection = connectionList[i]; if (connection.name == sCurrentMachine) { CncType = connection.cncType; } if (connection != null) Marshal.ReleaseComObject(connection); } // //DNC连接正常,加入数组 第一次连接加入数组,以支持多台设备 machineList.Add(connectName, Machine); Thread.Sleep(20); return Machine.GetState(); } catch (COMException cex) { YG.Log.Instance.WriteLogAdd($"海德汉响应结果-cex-->> " + cex.Message); return DNC_STATE.DNC_STATE_NOT_INITIALIZED; } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"海德汉响应结果-ex-->> " + ex.Message); return DNC_STATE.DNC_STATE_NOT_INITIALIZED; } finally { if (connectionList != null) Marshal.ReleaseComObject(connectionList); if (connection != null) Marshal.ReleaseComObject(connection); } } private string GenPath(string part1, string part2) { string sFullPath = part1; switch (part2) { case ".": break; case "..": if (part1.EndsWith(@"\") && part1.Length > 5) part1 = part1.Substring(0, part1.Length - 3); int iLastFolderPos = part1.LastIndexOf(@"\"); if (iLastFolderPos >= 0) sFullPath = part1.Substring(0, iLastFolderPos + 1); break; default: if (part1.EndsWith(@"\")) sFullPath = part1 + part2; else sFullPath = part1 + @"\" + part2; break; } return sFullPath; } } }