ADS与C#通信

       https://download.csdn.net/download/weixin_42415843/12843951 这个是ADS3.1 DLL的下载地址

        private TcAdsClient adsClient = null;
        private String strIP = "10.168.3.66:5.75.86.128.1.1:851";

        public Dev1()
        {

            ConnectDev(strIP);
        }


        public bool CheckConnected()
        {
            int ret = -1;
            if (adsClient == null)
            {
                ret = ConnectDev(strIP);
            }
            else
            {
                try
                {
                    DeviceInfo di = adsClient.ReadDeviceInfo();
                    StateInfo si = adsClient.ReadState();
                    if (si.AdsState == AdsState.Run && si.DeviceState == 0)
                    {
                        return true;
                    }
                    else
                    {
                        //assert(0);
                        //Debug.Assert(false);
                        Log.WriteLog("<CheckConnected> " + " AdsState: " + si.AdsState.ToString() + " DeviceState: " + si.DeviceState.ToString());
                        return false;
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLog("<CheckConnected> " + e.Message.ToString());
                    DisconnectDev();
                    return false;
                }
            }
            if (ret == 0)
            {
                Log.WriteLog("<CheckConnected> ret==0");
                DisconnectDev();
                return false;
            }
            return true;
        }
        public int ConnectDev(String IPAddr)
        {
            if (IPAddr == null)
                return 0;
            string[] strNetIDPort = IPAddr.Split(':');

            try
            {

                if (!PingOC(strNetIDPort[0]))
                {
                    Log.WriteLog("<ConnectDev> " + " Fail");
                    return 0;
                }
            }
            catch (Exception e)
            {
                //Log.WriteLog("<ConnectDev> " + pingReply.Status.ToString());
                return 0;
            }//2020.04.23 by Irving

            try
            {
                if (adsClient == null)
                {
                    adsClient = new TcAdsClient();
                    AmsNetId netID = new AmsNetId(strNetIDPort[1]);
                    int nPort = Convert.ToInt32(strNetIDPort[2]);
                    strIP = IPAddr;
                    adsClient.Connect(netID, nPort);
                }
                StateInfo si = adsClient.ReadState();
                DeviceInfo di = adsClient.ReadDeviceInfo();

                if (si.AdsState == AdsState.Run && si.DeviceState == 0)
                {
                    //SetupNotification();
                    return -1;
                }
                else
                {
                    //assert(0);
                    //Debug.Assert(false);
                    DisconnectDev();
                    Log.WriteLog("<ConnectDev> " + " AdsState: " + si.AdsState.ToString() + " DeviceState: " + si.DeviceState.ToString());
                    return 0;
                }
                //int hander;
                // hander = adsClient.CreateVariableHandle("GVL.Botton_motorenable");

            }
            catch (Exception err)
            {
                //adsClient = null;
                Log.WriteLog("<ConnectDev> " + err.Message.ToString());
                DisconnectDev();
                return 0;
                //MessageBox.Show(err.Message);
            }
            return -1;
        }
        public void DisconnectDev()
        {
            try
            {
                if (adsClient != null)
                {
                    adsClient.Disconnect();
                    adsClient.Dispose();
                }
                adsClient = null;
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 读字符串
        /// strValue = adsReadString("PLCname", 20);
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <param name="nLength">字符串长度要大于等于读出来的字符串长度</param>
        /// <returns></returns>
        String adsReadString(String strVName, int nLength)
        {
            String strRet = null;
            int hander = adsClient.CreateVariableHandle(strVName);
            try
            {
                AdsStream adsStream = new AdsStream(nLength);
                AdsBinaryReader reader = new AdsBinaryReader(adsStream);
                adsClient.Read(hander, adsStream);
                strRet = reader.ReadPlcString(nLength);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

            if (DEBUG_LOG)
            {
                string strWriteString;
                DateTime dt = DateTime.Now;
                strWriteString = "\t adsReadRReal " + strVName.ToString() + " = " + strRet.ToString();
                Log.WriteLog(strWriteString);
            }

            adsClient.DeleteVariableHandle(hander);
            return strRet;
        }
        /// <summary>
        /// 写字符串
        /// adsWriteString("GVL.MoveInitPosition_Pick", srcData, 20);
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <param name="strBuffer">字符串值</param>
        /// <param name="nLength">字符串长度(需要大于等于strBuffer长度)</param>
        /// <returns></returns>
       public bool adsWriteString(String strVName, String strBuffer, int nLength)
        {
            bool bRet = false;
            String strWriteBuffer = strBuffer;
            if (strBuffer == null)
            {
                strWriteBuffer = "";
            }
            //  return false;
            int hander = adsClient.CreateVariableHandle(strVName);
            try
            {
                AdsStream adsStream = new AdsStream(nLength);
                AdsBinaryWriter writer = new AdsBinaryWriter(adsStream);
                writer.WritePlcString(strWriteBuffer, nLength);
                adsClient.Write(hander, adsStream);
                bRet = true;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                bRet = false;
            }
            Log.WriteLog(Log.LogLevel.INFO, "WriteString " + strVName + " " + strBuffer + " " + bRet, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
            adsClient.DeleteVariableHandle(hander);
            return bRet;
        }
        /// <summary>
        /// 读int值
        ///   int a= adsReadInt("gvl.Temp_liquid_nitrogen_high");
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <returns></returns>
        public int adsReadInt(String strVName)
        {
            //return 1;
            short ret = 0;
            bool bRead = false;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    hander = adsClient.CreateVariableHandle(strVName);
                    ret = (short)adsClient.ReadAny(hander, typeof(short));
                    adsClient.DeleteVariableHandle(hander);
                    bRead = true;
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    //Log.WriteLog("\t adsReadInt " + strVName.ToString() + " " + e.Message.ToString());
                    bRead = false;
                    Thread.Sleep(1000);
                }
            }
            Log.WriteLog(Log.LogLevel.INFO, "ReadInt " + strVName + " " + ret.ToString() + " " + bRead, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
            return (int)ret;
        }
        /// <summary>
        /// 写Int值
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="nValue"></param>
        /// <returns></returns>
       public bool adsWriteInt(String strVName, int nValue)
        {
            //return true;
            bool ret = false;

            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    short sValue = (short)nValue;
                    hander = adsClient.CreateVariableHandle(strVName);
                    adsClient.WriteAny(hander, sValue);
                    ret = true;
                    adsClient.DeleteVariableHandle(hander);
                    Log.WriteLog(Log.LogLevel.INFO, "Write " + strVName + " " + nValue + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    ret = false;
                }
            }
            return ret;
        }
        /// <summary>
        /// 读布尔值
        /// </summary>
        /// <param name="strVName"></param>
        /// <returns></returns>
        public bool adsReadBool(String strVName)
        {
            //return true;
            bool ret = false;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    hander = adsClient.CreateVariableHandle(strVName);

                    ret = (bool)adsClient.ReadAny(hander, typeof(bool));
                    adsClient.DeleteVariableHandle(hander);
                    if (DEBUG_LOG)
                    {
                        string strWriteString;
                        DateTime dt = DateTime.Now;
                        strWriteString = "\t adsReadBool " + strVName.ToString() + " = " + ret.ToString();
                        Log.WriteLog(strWriteString);
                    }
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    Thread.Sleep(1000);
                }
            }
            return ret;
        }
        /// <summary>
        /// 写布尔值
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="bValue"></param>
        /// <returns></returns>
        bool adsWriteBool(String strVName, bool bValue)
        {
            //return true;
            bool ret = false;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    hander = adsClient.CreateVariableHandle(strVName);
                    adsClient.WriteAny(hander, bValue);
                    ret = true;
                    adsClient.DeleteVariableHandle(hander);
                    if (DEBUG_LOG)
                    {
                        string strWriteString;
                        DateTime dt = DateTime.Now;
                        strWriteString = "\t adsWriteBool" + strVName.ToString() + " = " + bValue.ToString();
                        Log.WriteLog(strWriteString);
                    }
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    Thread.Sleep(1000);
                }
            }
            return ret;
        }


        /// <summary>
        /// 读double值
        /// </summary>
        /// <param name="strVName"></param>
        /// <returns></returns>
        double adsReadRReal(String strVName)
        {
            //return 1.0d;
            int hander;
            double ret = 0;
            for (int i = 0; i < 2; i++)
            {
                try
                {

                    hander = adsClient.CreateVariableHandle(strVName);

                    ret = (double)adsClient.ReadAny(hander, typeof(double));
                    adsClient.DeleteVariableHandle(hander);
                    if (DEBUG_LOG)
                    {
                        string strWriteString;
                        DateTime dt = DateTime.Now;
                        strWriteString = "\t adsReadRReal " + strVName.ToString() + " = " + ret.ToString();
                        Log.WriteLog(strWriteString);
                    }
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    Thread.Sleep(1000);
                }
            }
            return ret;
        }
        private bool DEBUG_LOG = true;
        /// <summary>
        /// 写double值
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="dValue"></param>
        /// <returns></returns>
        bool adsWriteReal(String strVName, double dValue)
        {
            bool ret = false;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    hander = adsClient.CreateVariableHandle(strVName);
                    adsClient.WriteAny(hander, dValue);
                    ret = true;
                    adsClient.DeleteVariableHandle(hander);
                    if (DEBUG_LOG)
                    {
                        string strWriteString;
                        DateTime dt = DateTime.Now;
                        strWriteString = "\t adsWriteReal" + strVName.ToString() + " = " + dValue.ToString();
                        Log.WriteLog(strWriteString);
                    }
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    Thread.Sleep(1000);
                }
            }
            return ret;
        }
        public bool PingOC(String ips)//2020.04.23 by Irving
        {
            bool ret;
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            int i = 0;
            p.Start();
            p.StandardInput.WriteLine("ping -n 1 " + ips);
            p.StandardInput.WriteLine("exit");
            string strRst = p.StandardOutput.ReadToEnd();
            if (strRst.IndexOf("(100%") == -1)
            {
                ret = true;
            }
            else
            {
                ret = false;
            }
            p.Close();
            return ret;
        }

        #region 获取ACF-1 温湿度,液氮量,压差等基础数据 byzkz 20202,08,31
        /// <summary>
        /// Index为0时返回冰柜1的温度
        /// Index为1时返回冰柜2的温度
        /// </summary>
        /// <param name="Index"></param>
        /// <returns></returns>
        public double GetPTTemperature(int Index)
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0xffff;
            }
            int hander;
            // hander = adsClient.CreateVariableHandle("GVL.Botton_motorenable");
            //hander = adsClient.CreateVariableHandle("GVL.Temperature_cabinlow");
            if (Index == 0)//2018.09.25 by sim
                hander = adsClient.CreateVariableHandle("GVL.Temperature_icelocker1");
            else
                hander = adsClient.CreateVariableHandle("GVL.Temperature_icelocker2");

            //bool ret = Convert.ToBoolean(adsClient.ReadAny(hander, typeof(bool)).ToString());
            short ret = (short)adsClient.ReadAny(hander, typeof(short));
            double ret1 = (double)ret / 10;
            adsClient.DeleteVariableHandle(hander);

            return ret1;
        }
        /// <summary>
        /// 获取冰柜1温度(与传递窗同一水平线的储存区)
        /// </summary>
        /// <returns></returns>
        public int getTemperature_icelocker1()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temperature_icelocker1");
        }
        /// <summary>
        /// 获取冰柜2温度
        /// </summary>
        /// <returns></returns>
        public int getTemperature_icelocker2()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temperature_icelocker2");
        }
        /// <summary>
        /// 液氮总管路温度
        /// </summary>
        /// <returns></returns>
        public int getTemperature_vale()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temperature_vale");
        }
        /// <summary>
        /// 获取吸头温度
        /// </summary>
        /// <returns></returns>
        public int getTemperature_nollzer()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temperature_nollzer");
        }
        /// <summary>
        /// 获取板架暂存区温度
        /// </summary>
        /// <returns></returns>
        public int getTemperature_stagingarea()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temperature_stagingarea");
        }
        /// <summary>
        /// 获取液氮杯液氮高位温度
        /// </summary>
        /// <returns></returns>
        public int getTemp_liquid_nitrogen_high()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temp_liquid_nitrogen_high");
        }
        /// <summary>
        /// 获取液氮杯液氮低位温度
        /// </summary>
        /// <returns></returns>
        public int getTemp_liquid_nitrogen_low()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temp_liquid_nitrogen_low");
        }
        //该方法需要在液位确定之后改正
        public double GetLNLevel(int index)
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            if (!CheckConnected())
            {
                //Connect error !
                return 0xffff;
            }
            return 32;
            int HH = getHeight_liquid_nitrogen_HH();
            //判断当前液位是否在这里
            if (true)
            {

            }


        }
        /// <summary>
        /// 获取程序降温液氮高度HH
        /// </summary>
        /// <returns></returns>
        public int getHeight_liquid_nitrogen_HH()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Height_liquid_nitrogen_HH");
        }
        /// <summary>
        /// 获取程序降温液氮高度H
        /// </summary>
        /// <returns></returns>
        public int getHeight_liquid_nitrogen_H()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Height_liquid_nitrogen_H");
        }
        /// <summary>
        /// 获取程序降温液氮高度L
        /// </summary>
        /// <returns></returns>
        public int getHeight_liquid_nitrogen_L()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Height_liquid_nitrogen_L");
        }
        /// <summary>
        /// 获取程序降温液氮高度LL
        /// </summary>
        /// <returns></returns>
        public int getHeight_liquid_nitrogen_LL()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Height_liquid_nitrogen_LL");
        }
        /// <summary>
        /// 粘氮罐液位H
        /// </summary>
        /// <returns></returns>
        public int getTank_liquid_level_H()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Tank_liquid_level_H");
        }
        /// <summary>
        /// 获取粘氮罐液位L
        /// </summary>
        /// <returns></returns>
        public int getTank_liquid_level_L()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Tank_liquid_level_L");
        }
        /// <summary>
        /// 获取上腔室温度
        /// </summary>
        /// <returns></returns>
        public int getTemp_Upper_Plenum()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Temp_Upper_Plenum");
        }
        /// <summary>
        /// 获取露点
        /// </summary>
        /// <returns></returns>
        public int getDew_point()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Dew_point");
        }
        /// <summary>
        /// 获取压差
        /// </summary>
        /// <returns></returns>
        public int getPressure_different()
        {
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            return adsReadInt("gvl.Pressure_different");
        }

        #endregion

        public int[] adsReadArrInt(String strVName,int length)
        {
            if (!CheckConnected())
            {
                //Connect error !
                return null;
            }
            
            //return 1.0d;
            int hander;
            int[] arr=new int[]{length};
            for (int i = 0; i < 2; i++)
            {
                try
                {

                    hander = adsClient.CreateVariableHandle(strVName);

                    arr = (int [])adsClient.ReadAny(hander, typeof(short[]),new int[]{length});
                    adsClient.DeleteVariableHandle(hander);
                    if (DEBUG_LOG)
                    {
                        string strWriteString;
                        DateTime dt = DateTime.Now;
                        string ret="";
                        for (int j = 0; j < arr.Length; j++)
                        {
                            ret += arr[j];
                        }
                        strWriteString = "\t adsReadArr " + strVName.ToString() + " = " + ret.ToString();
                        Log.WriteLog(strWriteString);
                    }
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    Thread.Sleep(1000);
                }
            }
            return arr;
        }

       public bool adsWriteArrInt(String strVName, int[] arr)
        {
            if (!CheckConnected())
            {
                //Connect error !
                return false;
            }
            bool ret = false;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    hander = adsClient.CreateVariableHandle(strVName);
                    adsClient.WriteAny(hander, arr);
                    ret = true;
                    adsClient.DeleteVariableHandle(hander);
                    if (DEBUG_LOG)
                    {
                        string strWriteString;
                        string arrstr = "";
                        DateTime dt = DateTime.Now;
                        for (int j = 0; j < arr.Length; j++)
                        {
                            arrstr += arr[j];
                        }
                        strWriteString = "\t adsWriteReal" + strVName.ToString() + " = " + arrstr.ToString();
                        Log.WriteLog(strWriteString);
                    }
                    break;
                }
                catch (Exception e)
                {
                    //contiue;
                    Thread.Sleep(1000);
                }
            }
            return ret;
        }
        /// <summary>
       /// 读结构值,结构体需要特别定义
       /// ComplexStruct structure1 = dev.adsReadStructInt("gvl.BoardPosition");
        /// </summary>
        /// <param name="strVName"></param>
        /// <returns></returns>
       public ComplexStruct adsReadStructInt(String strVName)
       {
           //return 1.0d;
           int hander;
           ComplexStruct complexStruct=new ComplexStruct();
           for (int i = 0; i < 2; i++)
           {
               try
               {

                   hander = adsClient.CreateVariableHandle(strVName);

                   complexStruct = (ComplexStruct)adsClient.ReadAny(hander, typeof(ComplexStruct));
                   adsClient.DeleteVariableHandle(hander);
                   if (DEBUG_LOG)
                   {
                       string strWriteString;
                       DateTime dt = DateTime.Now;
                       string ret = complexStruct.a + "," + complexStruct.b + "," + complexStruct.c; 
                       strWriteString = "\t adsReadArr " + strVName.ToString() + " = " + ret.ToString();
                       Log.WriteLog(strWriteString);
                   }
                   break;
               }
               catch (Exception e)
               {
                   //contiue;
                   Thread.Sleep(1000);
               }
           }
           return complexStruct;
       }
        /// <summary>
        /// 写结构体值,结构体需要特别定义
        /// DeviceNo1.Dev1.ComplexStruct structure = new DeviceNo1.Dev1.ComplexStruct();
         ///  structure.a = 66;
         ///structure.b = 5;
         /// structure.c = 4;
         /// bool retr = dev.adsWriteStructInt("gvl.BoardPosition", structure); 
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="complexStruct"></param>
        /// <returns></returns>
       public bool adsWriteStructInt(String strVName, ComplexStruct complexStruct)
       {
           bool ret = false;
           for (int i = 0; i < 2; i++)
           {
               try
               {
                   int hander;
                   hander = adsClient.CreateVariableHandle(strVName);
                   adsClient.WriteAny(hander, complexStruct);
                   ret = true;
                   adsClient.DeleteVariableHandle(hander);
                   if (DEBUG_LOG)
                   {
                       string strWriteString;
                       DateTime dt = DateTime.Now;
                       string retc = complexStruct.a + "," + complexStruct.b+ "," + complexStruct.c;
                       strWriteString = "\t adsWriteReal" + strVName.ToString() + " = " + retc.ToString();
                       Log.WriteLog(strWriteString);
                   }
                   break;
               }
               catch (Exception e)
               {
                   //contiue;
                   Thread.Sleep(1000);
               }
           }
           return ret;
       }
       [StructLayout(LayoutKind.Sequential, Pack = 1)]
       public class ComplexStruct
       {
           //PLCint对应C# short
           public short a;//区域
           public short b;//腔室
           public short c;//层数
           specifies how .NET should marshal the array
           SizeConst specifies the number of elements the array has.
           //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
           //public int[] dintArr = new int[4];
           //[MarshalAs(UnmanagedType.I1)]
           //public bool boolVal;
           //public byte byteVal;
           specifies how .NET should marshal the string
           SizeConst specifies the number of characters the string has.
           '(inclusive the terminating null ). 
           //[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]

            //注意事项:

           //string类型如果没有限定大小,默认是80个字符,在C#这里需要加一个字符为结束符也就是限定为81个字符

           //public string stringVal = "";
       }

 

ADS与C#通信