
using FANUC;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO; 
using System.Reflection;
using System.Threading;

namespace fanuc采集
{
    public class ConDevice
    {
        private int FANUC_RETARDO_MANUAL = 20;

        private int FANUC_RETARDO = 200;

        //发那科远程文件路径
        private string FanucRemotePath = ConfigurationManager.AppSettings["FanucRemotePath"];

        //发那科本地文件路径
        private string FanucLocalPath = ConfigurationManager.AppSettings["FanucLocalPath"];

        //pmc位置类型
        Dictionary<int, String> pmcAddress = new Dictionary<int, string>();

        //不能删除程序
        StringCollection unDelProcs = new StringCollection();
        public ConDevice() {
            pmcAddress.Add(0, "G");
            pmcAddress.Add(1, "F");
            pmcAddress.Add(2, "Y");
            pmcAddress.Add(3, "X");
            pmcAddress.Add(4, "A");
            pmcAddress.Add(5, "R");
            pmcAddress.Add(6, "T");
            pmcAddress.Add(7, "K");
            pmcAddress.Add(8, "C");
            pmcAddress.Add(9, "D");

            unDelProcs.Add("O1");
            unDelProcs.Add("O7");
            unDelProcs.Add("O1234");
            unDelProcs.Add("O1235");
            unDelProcs.Add("O7999");
            unDelProcs.Add("O8000");
            unDelProcs.Add("O8001");
            unDelProcs.Add("O8002");
            unDelProcs.Add("O8003");
            unDelProcs.Add("O8004");
            unDelProcs.Add("O8005");
            unDelProcs.Add("O8006");
            unDelProcs.Add("O8014");
            unDelProcs.Add("O7999");
        }
        //选择程序
        public int SelectedNcProg(string IP, string port,string fileName)
        {
            
            ushort h = 0;

            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);  //object file_path = "//CNC_MEM/USER/PATH1/O0999";  

            if (ret == Focas1.EW_OK)
            {
                string fullPath = @FanucLocalPath + fileName;

                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);

                ret = Focas1.cnc_pdf_slctmain(h, FanucRemotePath + "O" + fileNameWithoutExtension); 

                Fanuc.cnc_freelibhndl(h);
            }
            return ret;

        }
        //删除程序
        public int DeleteNcProg(string IP, string port, string prgname)
        {
            ushort h = 0;

            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);

            if (ret == Focas1.EW_OK)
            {
                Fanuc.cnc_freelibhndl(h);
                ret = Focas1.cnc_pdf_del(h, FanucRemotePath + prgname);
            }
            return ret;
        }
        //上传程序
        public int UploadNcProg(string IP, string port, string prgname)
        {
            string fullPath = @FanucLocalPath + prgname;

            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
            string prg = File.ReadAllText(fullPath);

            ushort h = 0;

            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 120, out h);

            if (ret == Focas1.EW_OK) 
            {                
                int n = 0;
                // Focas1.cnc_pdf_slctmain(h, FanucRemotePath + "O" + fileNameWithoutExtension);  ////CNC_MEM/USER/PATH1/O111
                //主程序换成临时文件
                ret = Focas1.cnc_pdf_slctmain(h, FanucRemotePath + "O7999");

                //查询所有程序,删除已存在文件
                StringCollection procs = GetAllProgrammFileName(FanucRemotePath, h);
                if (procs != null && procs.Count > 0)
                {
                    foreach (string proc in procs)
                    {
                        Console.WriteLine(proc);
                        if (!unDelProcs.Contains(proc))
                        {
                            ret = Focas1.cnc_pdf_del(h, FanucRemotePath + proc);
                        }
                    }
                } 
                
                //开始上传
                ret = Focas1.cnc_dwnstart4(h, 0, FanucRemotePath);
                //ret = Focas1.cnc_dwnstart3(h, 0);

                if (ret != Focas1.EW_OK) { 
                    return ret;
                }

                int len = prg.Length;
                int j = len;
                while (len > 0)
                {
                    j = len;
                    ret = Focas1.cnc_download4(h, ref j, prg);
                    if (ret == (short)Focas1.focas_ret.EW_BUFFER)
                    {
                        continue;
                    }
                    if (ret == Focas1.EW_OK)
                    {                       
                        len -= j;
                        prg = prg.Substring(j, len);
                    }
                    if (ret != Focas1.EW_OK)
                    {
                        break;
                    }
                }
                ret = Focas1.cnc_dwnend4(h);
                Fanuc.cnc_freelibhndl(h);
            }
            
            return ret;
        }

        //启动程序
        public int StartNcProg(string IP, string port)
        {
           
            // 复位x01
            string[] data = "1 1 0 0 0".Split(' ');
            byte[] buf = new byte[5];
            for (int i = 0; i < 5; i++)
            {
                buf[i] = Convert.ToByte(data[i], 16);
            }

            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {

            }
            return 0;
        }

        //获取程序列表
        public StringCollection GetAllProgrammFileName(string path, ushort FlibHndl)
        {
            short top_prg_2 = 1;
            StringCollection strNames = new StringCollection();
            List<Focas1.ODBPDFADIR> _dir_list = new List<Focas1.ODBPDFADIR>();
            Focas1.IDBPDFADIR prgin = new Focas1.IDBPDFADIR();
            Focas1.ODBPDFADIR prgout2 = new Focas1.ODBPDFADIR();
            prgin.path = path;
            prgin.type = 0;
            prgin.size_kind = 0;
            prgin.req_num = 0;
            short num_prg = 0;
            while (true)
            {
                prgout2 = new Focas1.ODBPDFADIR();
                prgin.req_num = num_prg;
                switch (Focas1.cnc_rdpdf_alldir(FlibHndl, ref top_prg_2, prgin, prgout2))
                {
                    case 3:
                        return strNames;
                    default:
                        return strNames;
                    case 0:
                        if (prgout2.data_kind.ToString() == "1")
                        {
                            try
                            {
                                strNames.Add(prgout2.d_f.ToString());
                            }
                            catch (Exception e)
                            {

                            }
                        }

                        num_prg = (short)(num_prg + 1);
                        if (top_prg_2 <= 0)
                        {
                            return strNames;
                        }
                        break;
                }
            }
        }

        // 参照soflex读写监听PMC,marco宏变量,启动用
        public int ReadPmcMarco(string IP, string port, String proName)
        { 
            ushort h = 0;
            
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                // 选中程序 
                string fullPath = @FanucLocalPath + proName;

                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);

                ret = Focas1.cnc_pdf_slctmain(h, FanucRemotePath + "O" + fileNameWithoutExtension);

                // 执行程序启动，写PMC变量、宏变量通知机床启动程序 
                string writeAddress = "R0372";
                string readAddress1 = "R0373";
                string readAddress2 = "R0374";
                string writeValue = "00000000";
                ret = WriterPmc(writeAddress, writeValue);
                if (ret == Fanuc.EW_OK)
                {
                    while (true)
                    {
                        char[] chars = ReadPmc(readAddress1);
                        if (chars != null && chars[7].ToString() == "1")
                        {

                        }
                        else {
                            continue;
                        }
                    }
                 }
                 
                Fanuc.cnc_freelibhndl(h);
                return ret;
            } 
            return ret;
        }

        public int ReadMacroRange(string IP, string port, String address)
        {
            List<int> values = new List<int>();
            Focas1.IODBMR odbmr = new Focas1.IODBMR();

            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                short ncdataAddress = (short)Convert.ToUInt16(address);
                // 读取ncdata地址
                ret = Fanuc.cnc_rdmacror(h, ncdataAddress, ncdataAddress, 8 + (8 * 1), odbmr);
                if (ret == 0)
                {
                    values.Add(GetMacroValue(odbmr.data.data1));

                }
                else
                {
                    // 记录日志
                }

                // 写ncdataC变量
                odbmr.data.data1.mcr_val = 654900000;
                odbmr.data.data1.dec_val = 5;
                ret = Fanuc.cnc_wrmacror(h, 12 + (8 * 1), odbmr);
            }
            Fanuc.cnc_freelibhndl(h);
            return ret;
        }

        public char[] ReadPmc(string address)
        {
            char[] chars = null;
            try
            {
                string addressKindStr = address.Substring(0, 1);
                int addressKindInt = 0;
                int addressNo = int.Parse(address.Substring(1, 4).TrimStart('0') == "" ? "0" : address.Substring(1, 4).TrimStart('0'));
                for (int i = 0; i < pmcAddress.Keys.Count; i++)
                {
                    if (pmcAddress[i].ToString() == addressKindStr)
                    {
                        addressKindInt = i;
                        break;
                    }
                }
                short a = Convert.ToInt16(addressKindInt);
                short b = 0;
                ushort start = Convert.ToUInt16(addressNo);
                ushort end = Convert.ToUInt16(addressNo + 1);
                ushort f = 0;
                ushort N = (ushort)(end - start + 1);
                switch (b)
                {
                    case 0:
                        f = (ushort)(8 + N);
                        break;
                    case 1:
                        f = (ushort)(8 + N * 2);
                        break;
                    case 2:
                        f = (ushort)(8 + N * 4);
                        break;
                }
                Fanuc.IODBPMC0 iodbpmc0 = new Focas1.IODBPMC0(); 
                int ret = Fanuc.pmc_rdpmcrng(Fanuc.h, a, b, start, end, f, iodbpmc0);
                if (ret == Fanuc.EW_OK)
                {
                    byte[] data = iodbpmc0.cdata;
                    int j = 0;
                    for (ushort i = start; i < end; i++, j++)
                    {
                        string add = getpmcadd(iodbpmc0.type_a, i);
                        int value = Convert.ToInt32(Convert.ToString(data[j], 16).ToString());
                        string temp = Convert.ToString(value, 2).PadLeft(8, '0');
                        chars = temp.ToCharArray();

                       /* textBox9.Text = chars[7].ToString();
                        textBox8.Text = chars[6].ToString();
                        textBox7.Text = chars[5].ToString();
                        textBox6.Text = chars[4].ToString();
                        textBox5.Text = chars[3].ToString();
                        textBox4.Text = chars[2].ToString();
                        textBox3.Text = chars[1].ToString();
                        textBox2.Text = chars[0].ToString();*/
                    }
                }
                
            }
            catch (Exception e)
            {
                e.ToString();
                return chars;
            }
            return chars;
        }
        //写pmc地址
        public int WriterPmc(string address, string oneData)
        { 
            //提示数据长度错误，但是对象中没有相应的属性可以设置
            //Specify the type of the PMC data.
            string addressKindStr = address.Substring(0, 1);
            int addressKindInt = 0;
            int addressNo = int.Parse(address.Substring(1, 4).TrimStart('0') == "" ? "0" : address.Substring(1, 4).TrimStart('0'));
            for (int i = 0; i < pmcAddress.Keys.Count; i++)
            {
                if (pmcAddress[i].ToString() == addressKindStr)
                {
                    addressKindInt = i;
                    break;
                }
            }
            ushort a = 8 + 2 * 1;
            Fanuc.IODBPMC0 iodbpmc0 = new Focas1.IODBPMC0();
            iodbpmc0.datano_s = Convert.ToInt16(addressNo);
            iodbpmc0.datano_e = Convert.ToInt16(addressNo + 1);
            iodbpmc0.type_a = Convert.ToInt16(addressKindInt);
            iodbpmc0.type_d = 0;
            string[] data = { oneData };
            byte[] buf = new byte[5];
            for (int i = 0; i < 1; i++)
            {
                buf[i] = Convert.ToByte(data[i], 16);
            }
            iodbpmc0.cdata = buf;
            int ret = Fanuc.pmc_wrpmcrng(Fanuc.h, a, iodbpmc0);

            return ret;

         }
        public int GetMacroValue(Focas1.IODBMR_data data)
        {
            if (data.mcr_val == 0 && data.dec_val == -1)
            {
                return 0;
            }
            else
            {
                return (int)(data.mcr_val / Math.Pow(10.0, data.dec_val));
            }
        }
        // 读取工件坐标系
        public int ReadWriteZofs(string IP, string port)
        {
            ushort h = 0;
            Focas1.IODBZOR zofsX = new Focas1.IODBZOR();
            Focas1.IODBZOR zofsZ = new Focas1.IODBZOR();
            Focas1.IODBZOR zofsAbsX = new Focas1.IODBZOR();
            Focas1.IODBZOR zofsAbsZ = new Focas1.IODBZOR();
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                // 读取工件坐标系

                ret = Focas1.cnc_rdzofsr(h, 1, 1, 1, 8 + 4, zofsX);
                if (ret == Focas1.EW_OK)
                {

                }
                ret = Focas1.cnc_rdzofsr(h, 1, 2, 1, 8 + 4, zofsZ);
                if (ret == Focas1.EW_OK)
                {

                }

                ret = Focas1.cnc_rdzofsr(h, 0, 1, 0, 8 + 4, zofsAbsX);
                if (ret == Focas1.EW_OK)
                {

                }
                ret = Focas1.cnc_rdzofsr(h, 0, 2, 0, 8 + 4, zofsAbsZ);
                if (ret == Focas1.EW_OK)
                {

                }

                // 写工件坐标系
/*
                zofsX.data[0] = 666666;
                ret = Focas1.cnc_wrzofsr(h, 8 + 4, zofsX);

                zofsZ.data[0] = 666666;
                ret = Focas1.cnc_wrzofsr(h, 8 + 4, zofsZ);

                zofsAbsX.data[0] = 666;
                ret = Focas1.cnc_wrzofsr(h, 8 + 4, zofsAbsX);

                zofsAbsZ.data[0] = 666;
                ret = Focas1.cnc_wrzofsr(h, 8 + 4, zofsAbsZ);
                return (ret);*/
            }
            return ret;


        }

        public string MainProg(string IP, string port)
        {
            ushort h = 0; 
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBPRO pnum = new Focas1.ODBPRO();
                ret = Focas1.cnc_rdprgnum(h, pnum);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return pnum.data.ToString().PadLeft(4, '0');
                }
                else
                {
                    return "error";
                }

            }
            else

            { return "error2"; } 

        }


        public string ActSpindle(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBACT pindle = new Focas1.ODBACT();

                ret = Focas1.cnc_acts(h, pindle);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return pindle.data.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }

        public string Status(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBST cncStatus = new Focas1.ODBST();
                string[] str = new string[3];
                ret = Focas1.cnc_statinfo(h, cncStatus);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return cncStatus.run.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }
        public string Mode(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBST cncStatus = new Focas1.ODBST();
                string[] str = new string[3];
                ret = Focas1.cnc_statinfo(h, cncStatus);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return cncStatus.aut.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }


        public string EMG(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPMC0 iodbpmc0 = new Focas1.IODBPMC0();
                ret = Focas1.pmc_rdpmcrng(h, 0, 0, 7, 12, 14, iodbpmc0);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    byte[] data = iodbpmc0.cdata;
                    string value = Convert.ToString(data[1], 16).ToString().PadLeft(2, '0').ToUpper();
                    string str = Convert.ToString(Convert.ToInt32(value.ToString().Substring(0, 1)), 2).PadLeft(4, '0').Substring(3, 1);
                    if (str == "1")
                        return "1";
                    else
                        return "0";
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }



        public string ActFeed(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPMC0 iodbpmco = new Focas1.IODBPMC0();
                ret = Focas1.pmc_rdpmcrng(h, 0, 1, 12, 13, 10, iodbpmco);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return (100 - (iodbpmco.cdata[0] - 155)).ToString();                    
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }






        public string ServoLoadX(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBSVLOAD sv = new Focas1.ODBSVLOAD();
                short a = 6;//伺服轴的数量
                ret = Focas1.cnc_rdsvmeter(h, ref a, sv);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return sv.svload1.data.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }

        public string ServoLoadY(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBSVLOAD sv = new Focas1.ODBSVLOAD();
                short a = 6;//伺服轴的数量
                ret = Focas1.cnc_rdsvmeter(h, ref a, sv);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return sv.svload2.data.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }
        public string ServoLoadZ(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBSVLOAD sv = new Focas1.ODBSVLOAD();
                short a = 6;//伺服轴的数量
                ret = Focas1.cnc_rdsvmeter(h, ref a, sv);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return sv.svload3.data.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }


        public string PowerOnTime(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPSD_1 iodbpsd = new Focas1.IODBPSD_1();
                ret = Focas1.cnc_rdparam(h, 6750, 0, 8, iodbpsd);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return iodbpsd.ldata.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }
        }



        public string AccumulateCuttingTime(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPSD_1 iodbpsd = new Focas1.IODBPSD_1();
                ret = Focas1.cnc_rdparam(h, 6754, 0, 8, iodbpsd);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return iodbpsd.ldata.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }


        }



        public string CuttingTimePerCycle(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPSD_1 iodbpsd = new Focas1.IODBPSD_1();
                int min = 0;
                int sec = 0;
                ret = Focas1.cnc_rdparam(h, 6757, 0, 8, iodbpsd);//秒
                if (ret == Focas1.EW_OK)
                {
                    sec = iodbpsd.ldata;
                    ret = Focas1.cnc_rdparam(h, 6758, 0, 8, iodbpsd);//分
                    if (ret == Focas1.EW_OK)
                    {
                        min = iodbpsd.ldata;
                        Fanuc.cnc_freelibhndl(h);
                        return (min * 60 * 1000 + sec).ToString();
                    }
                    else
                    { return "error"; }

                }
                else { return "error"; }

            }
            else

            { return "error"; }


        }





        public string WorkTime(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPSD_1 iodbpsd = new Focas1.IODBPSD_1();
                ret = Focas1.cnc_rdparam(h, 6752, -1, 8, iodbpsd);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return iodbpsd.ldata.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }


        }
        public string Part_Count(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.IODBPSD_1 iodbpsd = new Focas1.IODBPSD_1();
                ret = Focas1.cnc_rdparam(h, 6712, 0, 8, iodbpsd);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return iodbpsd.ldata.ToString();
                }
                else
                {
                    return "error";
                }
            }
            else

            { return "error"; }

        }


        public string ToolNo(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                Focas1.ODBM odb = new Focas1.ODBM();

                ret = Focas1.cnc_rdmacro(h, 523, 10, odb);
                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    return (odb.mcr_val * Math.Pow(10, -odb.dec_val)).ToString();
                }
                else
                {
                    return "error";
                }



            }
            else

            { return "error"; }


        }

        public List<Tool> ToolLife(string IP, string port)
        {
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            List<Tool> tools = new List<Tool>();
            Tool toolEntity = new Tool();
            if (ret == Fanuc.EW_OK)
            {

                Fanuc.ODBTLIFE5 tool = new Focas1.ODBTLIFE5();//读取刀片组的序号
                Fanuc.ODBTLIFE2 tool1 = new Focas1.ODBTLIFE2();//读取刀片组的全部数量
                Fanuc.ODBTLIFE3 tool2 = new Focas1.ODBTLIFE3();//刀具的数量
                Fanuc.ODBTG btg = new Focas1.ODBTG();
                Fanuc.ODBUSEGRP grp = new Focas1.ODBUSEGRP();
                int m = 1;
                Fanuc.cnc_rdgrpid2(h, m, tool);
                int group_numer = tool.data;
                int all = Fanuc.cnc_rdngrp(Fanuc.h, tool1);//刀片组的全部数量
                short b = Convert.ToInt16(group_numer);
                Fanuc.cnc_rdntool(h, b, tool2);//刀具的数量
                toolEntity.number = tool2.data.ToString();
                Fanuc.cnc_rdlife(h, b, tool2);//刀具寿命
                Fanuc.cnc_rdcount(h, b, tool2);//刀具计时器
                Fanuc.cnc_rdtoolgrp(h, 2, 20 + 20 * 1, btg);//根据刀组号读出所有信息，很重要；

                Fanuc.cnc_rdtlusegrp(h, grp);//读出正在使用的到组号；


                if (ret == Fanuc.EW_OK)
                {
                    Fanuc.cnc_freelibhndl(h);
                    toolEntity.targetLife = tool2.data.ToString();
                    tools.Add(toolEntity);
                    return tools;
                }
                else
                {
                    return tools;
                }
            }
            else

            { return tools; }



        }
        public string getpmcadd(short a, ushort b)
        {
            string tempa = "";
            switch (a)
            {
                case 0:
                    tempa = "G";
                    break;
                case 1:
                    tempa = "F";
                    break;
                case 2:
                    tempa = "Y";
                    break;
                case 3:
                    tempa = "X";
                    break;
                case 4:
                    tempa = "A";
                    break;
                case 5:
                    tempa = "R";
                    break;
                case 6:
                    tempa = "T";
                    break;
                case 7:
                    tempa = "K";
                    break;
                case 8:
                    tempa = "C";
                    break;
                case 9:
                    tempa = "D";
                    break;
                default:
                    tempa = "n";
                    break;
            }
            string tempb = b.ToString().PadLeft(4, '0');
            return tempa + tempb;
        }
        public List<AlmInfo> AlmMsg(string IP, string port, out string IsAlarm)
        {
            List<AlmInfo> stateinfo = new List<AlmInfo>();
            IsAlarm = "0";
            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                short b = -1;//哪一类报警，-1所有报警
                short num = 11;//设大一些没关系
                Focas1.ODBALMMSG odbalmmsg2 = new Focas1.ODBALMMSG();
                ret = Focas1.cnc_rdalmmsg(h, b, ref num, odbalmmsg2);
                System.Type type = odbalmmsg2.GetType();
                if (ret == 0)
                {
                    if (num > 0)
                    {
                        IsAlarm = "1";
                        for (int i = 0; i <= num - 1; i++)
                        {
                            string str1 = "msg";
                            str1 = str1 + (i + 1);
                            object obj = type.GetField(str1).GetValue(odbalmmsg2);
                            //if(obj.)
                            System.Type type1 = obj.GetType();
                            if (type1.GetField("alm_msg").GetValue(obj).ToString() != "")
                            {
                                AlmInfo s = new AlmInfo();
                                s.no = Convert.ToInt32(type1.GetField("alm_no").GetValue(obj).ToString()).ToString();
                                s.msg = type1.GetField("alm_msg").GetValue(obj).ToString();
                                stateinfo.Add(s);
                            }
                        }
                        Fanuc.cnc_freelibhndl(h);
                        return stateinfo;
                    }
                    else
                    {
                        IsAlarm = "0";
                        AlmInfo s2 = new AlmInfo();
                        s2.no = "0";
                        s2.msg = "无报警";
                        stateinfo.Add(s2);
                        Fanuc.cnc_freelibhndl(h);

                        return stateinfo;
                    }
                }
                else
                {
                    IsAlarm = "0";
                    AlmInfo s3 = new AlmInfo();
                    s3.no = "0";
                    s3.msg = "无报警";
                    stateinfo.Add(s3);
                    return stateinfo;
                }
            }
            else
            {
                return stateinfo;
            }
        }

        public List<NcInfo> NcList(string IP, string port)
        {
            Focas1.PRGDIR2 prgdir2 = new Focas1.PRGDIR2();

            short Prg_type = 2;
            short num_prog = 10;
            short top_prog = 0;

            List<NcInfo> ncinfo = new List<NcInfo>();

            ushort h = 0;
            int ret = Fanuc.cnc_allclibhndl3(IP, Convert.ToUInt16(port), 1, out h);
            if (ret == Fanuc.EW_OK)
            {
                do
                {
                    ret = Focas1.cnc_rdprogdir2(h, Prg_type, ref top_prog, ref num_prog, prgdir2);
                    if (ret == Focas1.EW_OK)
                    {
                        string sprgdir2 = "dir";
                        string sprgdir2_data = "number";
                        string sprgdir2_data2 = "length";
                        string sprgdir2_data3 = "comment";
                        int Endnum = 0;
                        if (ret == Focas1.EW_OK)
                        {
                            System.Type type = prgdir2.GetType();
                            for (int j = 1; j < num_prog + 1; j++)
                            {
                                sprgdir2 = "dir" + j;
                                FieldInfo fieidinfo = type.GetField(sprgdir2);
                                object ob = fieidinfo.GetValue(prgdir2);
                                System.Type typeob = ob.GetType();
                                string ncNumber = "O" + typeob.GetField(sprgdir2_data).GetValue(ob).ToString().PadLeft(4, '0');

                                double temp = Convert.ToDouble(typeob.GetField(sprgdir2_data2).GetValue(ob).ToString());
                                temp = temp / 1024.0 + 0.5;
                                if (temp < 1)
                                    temp += 0.5;

                                string ncLength = ((int)temp).ToString();

                                Endnum = Convert.ToInt32(ncNumber.Remove(0, 1));
                                string ncComment = typeob.GetField(sprgdir2_data3).GetValue(ob).ToString();




                                NcInfo nc = new NcInfo { no = ncNumber, lentgh = ncLength, comment = ncComment };
                                ncinfo.Add(nc);

                            }
                            top_prog = (short)(Endnum + 1);
                        }
                    }
                } while (num_prog != 0);

                Fanuc.cnc_freelibhndl(h);
            }
            return ncinfo;


        }

        public class AlmInfo
        {
            public string no { get; set; }
            public string msg { get; set; }

        }

        public class NcInfo
        {
            public string no { get; set; }
            public string lentgh { get; set; }
            public string comment { get; set; }

        }
        public class Tool
        {

            /// <summary>
            /// 刀具号
            /// </summary>
            public string number { get; set; }

            /// <summary>
            /// 刀具名称
            /// </summary>
            public string name { get; set; }

            /// <summary>
            /// 刀具寿命预警
            /// </summary>
            public string warnLife { get; set; }

            /// <summary>
            /// 刀具寿命目标值
            /// </summary>
            public string targetLife { get; set; }

            /// <summary>
            /// 工件数
            /// </summary>
            public string workPiece { get; set; }

            /// <summary>
            /// 工件数预警值
            /// </summary>
            public string workPieceWarn { get; set; }

            /// <summary>
            /// 工件数目标值
            /// </summary>
            public string workPieceTarget { get; set; }

            /// <summary>
            /// 磨损量
            /// </summary>
            public string wear { get; set; }

            /// <summary>
            /// 磨损量预警值
            /// </summary>
            public string wearWarn { get; set; }

            /// <summary>
            /// 磨损量目标值
            /// </summary>
            public string wearTarget { get; set; }

            /// <summary>
            /// 姊妹刀号
            /// </summary>
            public string sisterNo { get; set; }

            /// <summary>
            /// 刀沿号
            /// </summary>
            public string toolEdgeNo { get; set; }

            /// <summary>
            /// 刀具位置
            /// </summary>
            public string toolPosition { get; set; }

            /// <summary>
            /// 刀具半径
            /// </summary>
            public string toolRadius { get; set; }

        }
    }
}