using HeidenhainDNCLib;
using IMCS.HeidenHain;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HEIDENHAIN.body;
using System.Net.NetworkInformation;
using System.Diagnostics.PerformanceData;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Security.Cryptography;

namespace HEIDENHAIN
{
    public partial class Form1 : Form
    {
        private int iChannel = 0;
        //private string RemotePath = "TNC:\\nc_prog\\ATUO";//ConfigurationManager.AppSettings["RemotePath"]; 
        private string RemotePath = "TNC:\\SMG80SKCX";//ConfigurationManager.AppSettings["RemotePath"]; 

        //连接设备列表
        public Dictionary<string, DNC_STATE> deviceList { get; set; } = new Dictionary<string, DNC_STATE>();
        private DNC_STATE m_ControlState;
        public Dictionary<string, JHMachineInProcess> machineList { get; set; } = new Dictionary<string, JHMachineInProcess>();
        //private JHMachineInProcess Machine = new JHMachineInProcess();
        // private JHAutomatic m_Automatic = null;
        // private JHFileSystem m_FileSystem = null;
        //private JHProcessData m_ProcessData = null;
        //private JHError m_Error = null; 
       

        string Http_Request_Url = "http://127.0.0.1:8011/heidenhain/";
        bool _contine = true;//用于线程循环
        private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);//此处需要调用System.Threading;用于触发等待的线程已发生的事件(连接)
        public delegate void RecvAndSendHandler(HttpListenerContext s);//此处需要调用System.Net用于请求和响应HttpListener类
        public event RecvAndSendHandler RecvAndSend;

        AsyncCallback callback;
        HttpListenerContext context = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        { 
            this.RecvAndSend += new RecvAndSendHandler(HttpListen_RecvAndSend);
            #region 添加监听的信息线程添加到线程池
            WaitCallback wc = new WaitCallback(http_Listen);
            ThreadPool.QueueUserWorkItem(wc);
            label1.Text = "HttpServer已开启：" + Http_Request_Url;
 
            #endregion 

        }
        /// <summary>
        /// 监听的线程
        /// </summary>
        /// <param name="ob"></param>
        private void http_Listen(object ob)
        {
            callback = new AsyncCallback(acceptCallback);

            HttpListener httpListenner;
            httpListenner = new HttpListener();
            httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListenner.Prefixes.Add(Http_Request_Url);
            httpListenner.Start();

            while (_contine)
            {
                try
                {
                    httpListenner.BeginGetContext(callback, httpListenner);
                    autoConnectEvent.WaitOne();
                }
                catch (Exception)
                {

                }
                Thread.Sleep(10);
            }
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void acceptCallback(IAsyncResult ar)
        {
            try
            {
                context = ((HttpListener)ar.AsyncState).EndGetContext(ar);
            }
            catch (Exception)
            {
                autoConnectEvent.Set();
            }
            if (context != null)
            {
                RecvAndSend(context);//触发我们一开始声明的事件
                autoConnectEvent.Set();
            }
        }

        /// <summary>
        /// 接听到消息的方法
        /// </summary>
        /// <param name="cont"></param>
        private void HttpListen_RecvAndSend(HttpListenerContext cont)
        {
            HttpListenerRequest request = cont.Request;
            HttpListenerResponse response = context.Response;
            Servlet servlet = new MyServlet();
            servlet.onCreate();

            if (request.HttpMethod == "POST")
            {
                if (!request.Url.ToString().Contains("favicon"))
                {
                    ResponseBody responseBody = new ResponseBody();
                    string body = null;
                    RequestBody hdhBody =null;
                    try
                    {
                        Stream stream = context.Request.InputStream;
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        body = reader.ReadToEnd();

                        //YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);

                        hdhBody = JsonConvert.DeserializeObject<RequestBody>(body);

                        AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":设备:" + hdhBody.MachineName, "OK：数据接受");

                        if (hdhBody.Type == ActionTypeEnum.Connect.ToString())
                        {
                            Ping pingSender = new Ping();
                            PingReply reply = pingSender.Send(hdhBody.ServerUrl);
                            if (reply.Status != IPStatus.Success)
                            {
                                responseBody.result = false;
                            }
                        }
                        else
                        {
                            //第一次连接加入数组,以支持多台设备
                            if (deviceList == null || (deviceList.Where(m => m.Key == hdhBody.MachineName).Count() == 0))
                            {
                                m_ControlState = connect(hdhBody.MachineName);

                                //DNC连接正常,加入数组
                                if (m_ControlState.ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE")
                                {
                                    deviceList.Add(hdhBody.MachineName, m_ControlState);
                                }
                                Thread.Sleep(500);
                            }
                            else
                            {
                                //取设备对应的状态
                                m_ControlState = deviceList.Where(m => m.Key == hdhBody.MachineName).FirstOrDefault().Value;
                            }

                            // ping 不通则位离线状态
                            Ping pingSender = new Ping();
                            PingReply reply = pingSender.Send(hdhBody.ServerUrl,500);
                            if (reply.Status != IPStatus.Success)
                            {
                                m_ControlState = DNC_STATE.DNC_STATE_NOT_INITIALIZED;
                            }


                            if (m_ControlState != null && m_ControlState.ToString() == "DNC_STATE_MACHINE_IS_AVAILABLE")
                            {
                                JHMachineInProcess Machine = machineList.Where(m => m.Key == hdhBody.MachineName).FirstOrDefault().Value;
                                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 (hdhBody.Type == 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);
                                    m_Automatic.GetExecutionMode();
                                    DNC_STS_PROGRAM dncProgram = m_Automatic.GetProgramStatus();

                                    RunDatasInfo runDatasInfo = new RunDatasInfo();
                                    runDatasInfo.feedRate = pFeed.ToString();
                                    runDatasInfo.spindleMagnification = pSpeed.ToString();
                                    runDatasInfo.spindleSpeed = pRapid.ToString();

                                    responseBody.runDatasInfo = JsonConvert.SerializeObject(runDatasInfo);

                                    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()));


                                }
                                else if (hdhBody.Type == 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(hdhBody.Path);
                                    string dncPath = null;
                                    string tempDncPath = RemotePath + "\\2.h";
                                    //防止地址内容累加
                                    string newRemotePath = null;
                                    if (hdhBody.Address != "")
                                    {
                                        newRemotePath = RemotePath + "\\" + hdhBody.Address;
                                    }
                                    //上传
                                    dncPath = GenPath(RemotePath, sSelectedFile);
                                    //设置临时程序为主程序
                                    m_Automatic.SelectProgram(iChannel, tempDncPath);
                                    try
                                    { //删除上传文件，try异常防止文件不存在
                                      //m_FileSystem.DeleteFile(dncPath);
                                    }
                                    catch (Exception edel)
                                    {
                                    }

                                    YG.Log.Instance.WriteLogAdd($"海德汉nc上传位置--->>" + dncPath, "海德汉nc上传");

                                    //上传
                                    m_FileSystem.TransmitFile(hdhBody.Path, dncPath);
                                    //设当前上传程序为主程序
                                    m_Automatic.SelectProgram(iChannel, dncPath);
                                }
                                else if (hdhBody.Type == ActionTypeEnum.DeleteNc.ToString())
                                {

                                    JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);

                                    string dncPath = GenPath(RemotePath, hdhBody.Path);
                                    m_FileSystem.DeleteFile(dncPath);
                                }
                                else if (hdhBody.Type == ActionTypeEnum.SelectNcProgram.ToString())//选中程序
                                {

                                    JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);

                                    string dncPath = GenPath(RemotePath, hdhBody.Path);

                                    YG.Log.Instance.WriteLogAdd($"海德汉设置nc--->>" + dncPath, "海德汉机床nc设置");
                                    m_Automatic.SelectProgram(iChannel, dncPath);
                                }
                                else if (hdhBody.Type == 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);
                                    string sSelectedFile = Path.GetFileName(hdhBody.Path);
                                    string bstrProgramName = GenPath(RemotePath, sSelectedFile);
                                    YG.Log.Instance.WriteLogAdd($"海德汉执行启动--->>" + bstrProgramName, "海德汉机床启动");
                                    m_Automatic.StartProgram(bstrProgramName);
                                }
                                else if (hdhBody.Type == ActionTypeEnum.Read.ToString())
                                {

                                }
                                else if (hdhBody.Type == ActionTypeEnum.Write.ToString())
                                {

                                }
                                else if (hdhBody.Type == ActionTypeEnum.ToolList.ToString())
                                {
                                    IJHDataEntry2 ToolLine = null;
                                    IJHDataEntry2List ToolCells = null;
                                    //IJHDataEntry2 ToolCell = null;                                    
                                    List<ToolsInfo> toolsList = new List<ToolsInfo>();
                                    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[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
                                            //刀具寿命目标值
                                            toolsInfo.targetLife = ToolList[12].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
                                            //Cur_Time使用时间
                                            toolsInfo.curTime = ToolList[13].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
                                            // 刀具锁定状态，
                                            toolsInfo.tl = ToolList[8].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();
                                            // 刀具使用完毕此刀位可以换刀，
                                            toolsInfo.doc = ToolList[14].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA).ToString();

                                            toolsList.Add(toolsInfo);
                                        }
                                    }
                                    //获取海德汉的刀具寿命信息
                                    responseBody.toolsInfo = JsonConvert.SerializeObject(toolsList.Distinct().ToList());

                                }
                                else if (hdhBody.Type == ActionTypeEnum.ReadAndWriteTool.ToString())
                                {

                                    //机外对刀仪数据
                                    JObject jsonObject = JObject.Parse(hdhBody.CutterData);
                                    // 返回的结果,数据
                                    var returnData = new Dictionary<string, object>();

                                    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\" + jsonObject.GetValue("cutterT");
                                    //刀具表数据
                                    IJHDataEntry2 ToolTable = dataAccess.GetDataEntry2(ToolColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
                                    // 获取字段列表
                                    IJHDataEntry2List ToolLines = ToolTable.GetChildList();


                                    //设置刀具名-对应机床表name
                                    var data1 = ToolLines[1].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterName", data1);
                                    ToolLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterName", out JToken cutterName) ? jsonObject.GetValue("cutterName") : "" , false);

                                    //刀具类型 - 对应机床TYP
                                    var data2 = ToolLines[13].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterTypDnc", data2);
                                    ToolLines[13].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterTypDnc", out JToken cutterTypDnc) ? jsonObject.GetValue("cutterTypDnc") : "0", false);

                                    //刀具长度 - 对应机床 L
                                    var data3 = ToolLines[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterZl", data3);
                                    ToolLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterZl", out JToken cutterZl) ? jsonObject.GetValue("cutterZl") : "0", false);

                                    //刀具半径  - 对应机床R
                                    var data4 = ToolLines[3].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterXl", data4);
                                    ToolLines[3].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterXl", out JToken cutterXl) ?  jsonObject.GetValue("cutterXl") : "0", false);

                                    //刀具寿命 - 对应机床time1
                                    var data5 = ToolLines[10].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterTime1", data5);
                                    ToolLines[10].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterTime1", out JToken cutterTime1) ? jsonObject.GetValue("cutterTime1") : "0", false);

                                    //刀具寿命 - 对应机床time2
                                    var data6 = ToolLines[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterTime2", data6);
                                    ToolLines[11].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterTime2", out JToken cutterTime2) ? jsonObject.GetValue("cutterTime2") : "0", false);

                                    //PLC状态 - 对应机床
                                    var data7 = ToolLines[15].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterPlcBit", data7);
                                    ToolLines[15].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterPlcBit", out JToken cutterPlcBit) ? jsonObject.GetValue("cutterPlcBit") : "0", false);

                                    //刀具使用寿命，不允许超过该值 -- 对应机床
                                    var data8 = ToolLines[45].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("cutterOverTime", data8);
                                    ToolLines[45].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterOverTime", out JToken cutterOverTime) ? jsonObject.GetValue("cutterOverTime") : "0", false);

                                    //在刀具轴方向上的刀齿长
                                    var data9 = ToolLines[16].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("lcuts", data9);
                                    ToolLines[16].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("lcuts", out JToken lcuts) ? jsonObject.GetValue("lcuts") : "0", false);

                                    //准确定义刀具的切削刃正面宽度
                                    var data10 = ToolLines[46].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("rcuts", data10);
                                    ToolLines[46].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("rcuts", out JToken rcuts) ? jsonObject.GetValue("rcuts") : "0", false);

                                    //准确定义刀具的刀具可用长度
                                    var data11 = ToolLines[17].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("lu", data11);
                                    ToolLines[17].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("lu", out JToken lu) ? jsonObject.GetValue("lu") : "0", false);

                                    //准确定义刀具的刀颈半径
                                    var data12 = ToolLines[18].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("rn", data12);
                                    ToolLines[18].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("rn", out JToken rn) ? jsonObject.GetValue("rn") : "0", false);

                                    //最大的切入角度
                                    var data13 = ToolLines[19].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("angle", data13);
                                    ToolLines[19].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("angle", out JToken angle) ? jsonObject.GetValue("angle") : "0", false);

                                    var data14 = ToolLines[31].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    returnData.Add("nmax", data14);
                                    ToolLines[31].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("nmax", out JToken nmax) ? jsonObject.GetValue("nmax") : "0", false);


                                    // 如果没有子车刀类型，不需要往车刀表添加
                                    if (jsonObject.TryGetValue("cutterTypSubDnc", out JToken value))
                                    {
                                        /*车刀表数据设置更新*/
                                        // 车刀表数据查询语句
                                        string CheDaoColumnNamesAccessor = @"\TABLE\TOOLTURN\T\" + jsonObject.GetValue("cutterT");
                                        // 查询表数据
                                        IJHDataEntry2 CheDaoTable = dataAccess.GetDataEntry2(CheDaoColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
                                        // 获取字段列表
                                        IJHDataEntry2List CheDaoLines = CheDaoTable.GetChildList();

                                        // 设置刀具名-对应机床表name
                                        CheDaoLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterName", out JToken cutterName_cd) ? jsonObject.GetValue("cutterName") : "", false);

                                        // 设置刀具在Z轴方向上的长度 - 对应机床 ZL
                                        var cdData1 = CheDaoLines[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterZl"] = cdData1;
                                        CheDaoLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterZl", out JToken cutterZl_cd) ? jsonObject.GetValue("cutterZl") : "0", false);

                                        // 车刀在X轴方向上的长度  - 对应机床XL
                                        var cdData2 = CheDaoLines[3].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterXl"] = cdData2;
                                        CheDaoLines[3].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterXl", out JToken cutterXl_cd) ? jsonObject.GetValue("cutterXl") : "0", false);

                                        // 车刀在y轴方向上的长度  - 对应机床yL
                                        var cdData3 = CheDaoLines[4].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterYl"] = cdData3;
                                        CheDaoLines[4].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterYl", out JToken cutterYl_cd) ? jsonObject.GetValue("cutterYl") : "0", false);

                                        // 切削刃半径  - 对应机床rs
                                        var cdData4 = CheDaoLines[8].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterRs"] = cdData4;
                                        CheDaoLines[8].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterRs", out JToken cutterRs_cd) ? jsonObject.GetValue("cutterRs") : "0", false);

                                        // 设置车刀子类型
                                        var cdData5 = CheDaoLines[18].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterTypSubDnc"] = cdData5;
                                        CheDaoLines[18].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterTypSubDnc", out JToken cutterTypSubDnc_cd) ? jsonObject.GetValue("cutterTypSubDnc") : "", false);

                                        // 车刀方向 TO 刀具定向?
                                        var cdData6 = CheDaoLines[10].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterTo"] = cdData6;
                                        CheDaoLines[10].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterTo", out JToken cutterTo_cd) ? jsonObject.GetValue("cutterTo") : "0", false);

                                        //刀具长度1的差值
                                        var cdData7 = CheDaoLines[5].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["dzl"] = cdData7;
                                        CheDaoLines[5].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("dzl", out JToken dzl_cd) ? jsonObject.GetValue("dzl") : "0", false);

                                        //刀具长度2的差值
                                        var cdData8 = CheDaoLines[6].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["dxl"] = cdData8;
                                        CheDaoLines[6].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("dxl", out JToken dxl_cd) ? jsonObject.GetValue("dxl") : "0", false);

                                        //刀具长度3的差值
                                        var cdData9 = CheDaoLines[7].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["dyl"] = cdData9;
                                        CheDaoLines[7].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("dyl", out JToken dyl_cd) ? jsonObject.GetValue("dyl") : "0", false);

                                        //刀具半径的差值
                                        var cdData10 = CheDaoLines[9].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["drs"] = cdData10;
                                        CheDaoLines[9].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("drs", out JToken drs_cd) ? jsonObject.GetValue("drs") : "0", false);

                                        //开槽刀宽度的差值
                                        var cdData11 = CheDaoLines[17].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["dcw"] = cdData11;
                                        CheDaoLines[17].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("dcw", out JToken dcw_cd) ? jsonObject.GetValue("dcw") : "0", false);

                                        // 主轴定向角 0ri
                                        var cdData12 = CheDaoLines[11].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutterOri"] = cdData12;
                                        CheDaoLines[11].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterOri", out JToken cutterOri_cd) ? jsonObject.GetValue("cutterOri") : "0", false);

                                        // 下刀角
                                        var cdData13 = CheDaoLines[16].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["tangle"] = cdData13;
                                        CheDaoLines[16].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("tangle", out JToken tangle_cd) ? jsonObject.GetValue("tangle") : "0", false);

                                        // 刀尖角
                                        var cdData14 = CheDaoLines[15].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["pangle"] = cdData14;
                                        CheDaoLines[15].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("pangle", out JToken pangle_cd) ? jsonObject.GetValue("pangle") : "0", false);

                                        // 切槽刀的切削长度
                                        var cdData15 = CheDaoLines[17].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutlength"] = cdData15;
                                        CheDaoLines[17].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutlength", out JToken cutlength_cd) ? jsonObject.GetValue("cutlength") : "0", false);

                                        // 切槽刀的切削长度
                                        var cdData16 = CheDaoLines[18].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                        returnData["cutwidth"] = cdData16;
                                        CheDaoLines[18].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutwidth", out JToken cutwidth_cd) ? jsonObject.GetValue("cutwidth") : "0", false);

                                    }

                                    /*刀位表数据设置更新*/
                                    //刀位表数据查询语句

                                    string writeOrDel = jsonObject.GetValue("writeOrDel").ToString();
                                    string DaoWeiColumnNamesAccessor = @"\TABLE\TOOL_P\P\" + jsonObject.GetValue("cutterP");
                                    if (writeOrDel == "2") {
                                        DaoWeiColumnNamesAccessor = @"\TABLE\TOOL_P\T\" + jsonObject.GetValue("cutterT");
                                    }
                                    // 查询表数据
                                    IJHDataEntry2 DaoWeiTable = dataAccess.GetDataEntry2(DaoWeiColumnNamesAccessor, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
                                    // 获取字段列表
                                    IJHDataEntry2List DaoWeiLines = DaoWeiTable.GetChildList();

                                    // 设置刀号
                                    DaoWeiLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterT", out JToken cutterT_dw) ? jsonObject.GetValue("cutterT") : "0", false);
                                    // 设置刀具名
                                    DaoWeiLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.TryGetValue("cutterT", out JToken cutterName_dw) ? jsonObject.GetValue("cutterName") : "", false);

                                    responseBody.msg = "数据设置成功";
                                    responseBody.returnData = JsonConvert.SerializeObject(returnData);
                                    responseBody.result = true;
                                }
                                else if (hdhBody.Type == ActionTypeEnum.WriteDeviationValue.ToString())
                                { // 给机床写偏差值
                                    JObject jsonObject = JObject.Parse(hdhBody.DeviationValue);


                                    JHDataAccess dataAccess1 = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
                                    dataAccess1.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");

                                    //*偏差值表数据修改*//*
                                    //偏差值表查询语句
                                    string ToolColumnNamesAccessor1 = @"\TABLE\HAN121601\NR\'1'";
                                    //偏差值表数据
                                    IJHDataEntry2 ToolTable = dataAccess1.GetDataEntry2(ToolColumnNamesAccessor1, DNC_DATA_UNIT_SELECT.DNC_DATA_UNIT_SELECT_METRIC, false);
                                    // 获取字段列表
                                    IJHDataEntry2List ToolLines = ToolTable.GetChildList();

                                    //设置偏差值，先设置偏差值为零
                                    ToolLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, 0, false);
                                    ToolLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, 0, false);
                                    ToolLines[3].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, 0, false);
                                    ToolLines[4].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, 0, false);
                                    ToolLines[5].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, 0, false);
                                    ToolLines[6].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, 0, false);

                                    ToolLines[1].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("exactXaxisOffset"), false);
                                    ToolLines[2].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("exactYaxisOffset"), false);
                                    ToolLines[3].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("exactZaxisOffset"), false);
                                    ToolLines[4].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("exactAaxisOffset"), false);
                                    ToolLines[5].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("exactBaxisOffset"), false);
                                    ToolLines[6].SetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA, jsonObject.GetValue("exactCaxisOffset"), false);

                                    // 校验偏差值
                                    Thread.Sleep(50);

                                    Boolean checkThrough = true;
                                    string isreason = null;

                                    var data1 = ToolLines[1].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    if (data1 != Convert.ToDouble(jsonObject.GetValue("exactXaxisOffset"))) { checkThrough = false; isreason = "exactXaxisOffset"; }

                                    var data2 = ToolLines[2].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    if (data2 != Convert.ToDouble(jsonObject.GetValue("exactYaxisOffset"))) { checkThrough = false; isreason = "exactYaxisOffset"; }

                                    var data3 = ToolLines[3].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    if (data3 != Convert.ToDouble(jsonObject.GetValue("exactZaxisOffset"))) { checkThrough = false; isreason = "exactZaxisOffset"; }

                                    var data4 = ToolLines[4].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);
                                    if (data4 != Convert.ToDouble(jsonObject.GetValue("exactAaxisOffset"))) { checkThrough = false; isreason = "exactAaxisOffset"; }

                                    var data5 = ToolLines[5].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);

                                    if (data5 != Convert.ToDouble(jsonObject.GetValue("exactBaxisOffset"))) { checkThrough = false; isreason = "exactBaxisOffset"; }
                                    var data6 = ToolLines[6].GetPropertyValue(DNC_DATAENTRY_PROPKIND.DNC_DATAENTRY_PROPKIND_DATA);

                                    if (data6 != Convert.ToDouble(jsonObject.GetValue("exactCaxisOffset"))) { checkThrough = false; isreason = "exactCaxisOffset"; }

                                    if (!checkThrough)
                                    {
                                        responseBody.msg = "数据校验不成功,异常字段"+ isreason;
                                        responseBody.result = false;
                                    }
                                    else {
                                        responseBody.msg = "数据设置成功";
                                        responseBody.result = true;
                                    }
                                }
                                else if (hdhBody.Type == ActionTypeEnum.ReadProbeData.ToString())
                                {
                                    IJHDataEntry2 ToolLine = null;
                                    IJHDataEntry2List ToolCells = null;
                                    JHDataAccess dataAccess = Machine.GetInterface(HeidenhainDNCLib.DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHDATAACCESS);
                                    dataAccess.SetAccessMode(DNC_ACCESS_MODE.DNC_ACCESS_MODE_TABLEDATAACCESS, "");

                                    /*探头检测结果表数据修改*/
                                    //探头检测结果表查询语句
                                    string ToolColumnNamesAccessor = @"\TABLE\TOOL_P\P\('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;
                                    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();


                                        YG.Log.Instance.WriteLogAdd($"海德汉读取探头检测数据--->>" + JsonConvert.SerializeObject(toolsInfo), "海德汉机床探头检测数据");
                                    }

                                }
                            }
                            else
                            {
                                responseBody.msg = m_ControlState.ToString();
                                responseBody.result = false;
                                deviceList.Remove(hdhBody.MachineName);
                                machineList.Remove(hdhBody.MachineName);
                            }
                        }


                    }
                    catch (Exception opcex)
                    {
                        YG.Log.Instance.WriteLogAdd($"海德汉响应异常--->>" + opcex.Message);
                        AddList(DateTime.Now.ToString(), "POST", request.Url.ToString(), "响应异常:" + opcex.Message);
                        responseBody.result = false;
                        responseBody.msg = opcex.Message;
                        //发生异常,清空数组,重新连接
                        deviceList = new Dictionary<string, DNC_STATE>();
                        machineList = new Dictionary<string, JHMachineInProcess>();
                    }
                    finally {

                        AddList(DateTime.Now.ToString(), "POST", hdhBody.ServerUrl + ":响应数据:" + responseBody.toolsInfo, responseBody.result ? "OK，消息消费成功" : "失败，消息消费失败" + m_ControlState != null ? m_ControlState.ToString() : "");

                        response.ContentType = "application/json;charset=UTF-8";
                        response.ContentEncoding = Encoding.UTF8;
                        response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
                        string retJsonData = JsonConvert.SerializeObject(responseBody);

                        using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
                        {
                            YG.Log.Instance.WriteLogAdd($"海德汉响应结果--->>{JsonConvert.SerializeObject(JsonConvert.SerializeObject(responseBody))}--->>{body}\r\n");
                            
                            writer.Write(JsonConvert.SerializeObject(responseBody));
                            writer.Close();
                            response.Close();
                        }
                    }


                }
            }
            else if (request.HttpMethod == "GET")
            {
                if (!request.Url.ToString().Contains("favicon"))
                {
                    string ip = request.QueryString["ip"];
                    string port = request.QueryString["port"];
                    string fun = request.QueryString["fun"];

                    AddList(DateTime.Now.ToString(), "GET", ip + port + fun, "OK");

                }
                response.Close();
            }
            
         
    }
 
        private DNC_STATE connect(string connectName)
        { 
            DNC_CNC_TYPE CncType ;

            IJHConnectionList connectionList = null;
            IJHConnection connection = null;
            try
            {
                JHMachineInProcess Machine = null;
                //第一次连接加入数组,以支持多台设备
                if (machineList == null || (machineList.Where(m => m.Key == connectName).Count() == 0))
                {
                    Machine = new JHMachineInProcess(); 
                    //DNC连接正常,加入数组 
                    machineList.Add(connectName, Machine); 
                    Thread.Sleep(20);
                }
                else
                {
                    //取对应设备 
                    Machine = machineList.Where(m => m.Key == connectName).FirstOrDefault().Value;
                }
                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);
                }
                return Machine.GetState();
            }
            catch (COMException cex)
            {
                return DNC_STATE.DNC_STATE_NOT_INITIALIZED;
            }
            catch (Exception ex)
            {
                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;
        }

        public class Servlet
        {
            public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
            public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }

            public virtual void onCreate()
            {

            }
        }


        public void AddList(string dtime, string type, string url, string res)
        {
            this.Invoke(new Action(delegate ()
            {
                listView1.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
                ListViewItem lvi = new ListViewItem();
                lvi.Text = dtime;
                lvi.SubItems.Add(type);
                lvi.SubItems.Add(url);
                lvi.SubItems.Add(res);
                this.listView1.Items.Insert(0, lvi);
                if (this.listView1.Items.Count > 100)
                {
                    this.listView1.Items.Clear();
                }

                this.listView1.EndUpdate();  //结束数据处理，UI界面一次性绘制。}

            }));

        }


        public class MyServlet : Servlet
        {
            public override void onCreate()
            {
                base.onCreate();
            }

            public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
            {
                Console.WriteLine("GET:" + request.Url);


                byte[] buffer = Encoding.UTF8.GetBytes(info);
                //string sss = request.QueryString["ty"];
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
                //listener.Stop();
            }

            public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
            {
                Console.WriteLine("POST:" + request.Url);
                byte[] res = Encoding.UTF8.GetBytes("OK");
                response.OutputStream.Write(res, 0, res.Length);
            }



        }

    }
}
