ADS与C#通信

       TwinCAT.Ads.rar-C#文档类资源-CSDN下载 这个是ADS3.1 DLL的下载地址

    1.PLC与C#类型对应表

2.ADS读写方法

public class adsHelp
    {   /*
         * 1.ads对于结构体的读写可直接用strVName=结构体.属性名
         * 也可以用提供的object方法直接对整个结构体进行读写
         * 2.ads对于数组的读写可直接用strVName=array[i]  
         * 3.注意double类型PLC的lreal
         */
        private TcAdsClient adsClient = null;
        private String strIP = "10.168.3.66:5.75.86.128.1.1:851";
        #region 连接,断开连接,检查连接状态
        /// <summary>
        /// 连接
        /// 该ip是TwinCat上的IP
        /// </summary>
        /// <param name="IPAddr"></param>
        /// <returns></returns>
        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)
            {
                return 0;
            }

            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)
                {
                    return -1;
                }
                else
                {
                    DisconnectDev();
                    Log.WriteLog("<ConnectDev> " + " AdsState: " + si.AdsState.ToString() + " DeviceState: " + si.DeviceState.ToString());
                    return 0;
                }

            }
            catch (Exception err)
            {
                Log.WriteLog("<ConnectDev> " + err.Message.ToString());
                DisconnectDev();
                return 0;
            }
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        public void DisconnectDev()
        {
            try
            {
                if (adsClient != null)
                {
                    adsClient.Disconnect();
                    adsClient.Dispose();
                }
                adsClient = null;
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 检查连接状态 
        /// 返回true是连接正常 false连接失败
        /// </summary>
        /// <returns></returns>
        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
                    {

                        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;
        }
        /// <summary>
        /// 判断与目标主机是否连接,网络是否正常
        /// true未正常,false失败
        /// </summary>
        /// <param name="ips"></param>
        /// <returns></returns>
        public bool PingOC(String ips)
        {
            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;
        }
        #endregion
        #region ads读写数据基方法 string int double bool object arr struct
        /// <summary>
        /// 读字符串
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <param name="nLength">字符串长度要大于等于读出来的字符串长度</param>
        /// <returns></returns>
        public String ReadString(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 ex)
            {
                Log.WriteLog(Log.LogLevel.EXCEPTION, ex.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
            }

            Log.WriteLog(Log.LogLevel.INFO, "ReadString " + strVName + " " + strRet, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);

            adsClient.DeleteVariableHandle(hander);
            return strRet;
        }
        /// <summary>
        ///  写字符串
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <param name="strBuffer">字符串值</param>
        /// <param name="nLength">字符串长度(需要大于等于strBuffer长度)</param>
        /// <returns></returns>
        public bool WriteString(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)
            {
                Log.WriteLog(Log.LogLevel.EXCEPTION, err.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                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值
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <returns></returns>
        public int ReadInt(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)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    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 WriteInt(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, "WriteInt " + strVName + " " + nValue + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    ret = false;
                }
            }
            return ret;
        }
        /// <summary>
        /// 读布尔值
        /// </summary>
        /// <param name="strVName"></param>
        /// <returns></returns>
        public bool ReadBool(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);
                    Log.WriteLog(Log.LogLevel.INFO, "ReadBool " + strVName + " " + ret.ToString(), MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);

                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    //Thread.Sleep(1000);
                }
            }
            return ret;
        }
        /// <summary>
        /// 写布尔值
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="bValue"></param>
        /// <returns></returns>
        public bool WriteBool(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);
                    string strWriteString;
                    strWriteString = "\t WriteBool" + strVName.ToString() + " = " + bValue.ToString();
                    Log.WriteLog(strWriteString);
                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    //Thread.Sleep(1000);
                }
            }
            return ret;
        }


        /// <summary>
        /// 读double值 
        /// </summary>
        /// <param name="strVName"></param>
        /// <returns></returns>
        public double ReadDouble(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);
                    string strWriteString;
                    strWriteString = "\t ReadDouble " + strVName.ToString() + " = " + ret.ToString();
                    Log.WriteLog(strWriteString);
                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    //Thread.Sleep(1000);
                }
            }
            return ret;
        }
        /// <summary>
        /// 写double值
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="dValue"></param>
        /// <returns></returns>
        public bool WriteDouble(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);
                    string strWriteString;
                    strWriteString = "\t WriteDouble" + strVName.ToString() + " = " + dValue.ToString();
                    Log.WriteLog(strWriteString);
                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.INFO, "WriteDouble " + strVName + " " + e.Message, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    //Thread.Sleep(1000);
                }
            }
            return ret;
        }
        /// <summary>
        /// 读object类型
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object ReadObject(String strVName, Type type)
        {
            //return 1;
            object ret = null;
            bool bRead = false;
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    hander = adsClient.CreateVariableHandle(strVName);
                    ret = adsClient.ReadAny(hander, type);
                    adsClient.DeleteVariableHandle(hander);
                    bRead = true;
                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    bRead = false;
                    //Thread.Sleep(1000);
                }
            }
            Log.WriteLog(Log.LogLevel.INFO, "ReadObject " + strVName + " " + ret.ToString() + " " + bRead, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
            return ret;
        }
        /// <summary>
        /// 写object
        /// </summary>
        /// <param name="strVName"></param>
        /// <param name="nValue"></param>
        /// <returns></returns>
        public bool WriteObject(String strVName, object nValue)
        {
            //return true;
            bool ret = false;

            for (int i = 0; i < 2; i++)
            {
                try
                {
                    int hander;
                    object sValue = nValue;
                    hander = adsClient.CreateVariableHandle(strVName);
                    adsClient.WriteAny(hander, sValue);
                    ret = true;
                    adsClient.DeleteVariableHandle(hander);
                    Log.WriteLog(Log.LogLevel.INFO, "WriteObject " + strVName + " " + nValue.ToString() + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    break;
                }
                catch (Exception e)
                {
                    Log.WriteLog(Log.LogLevel.EXCEPTION, e.Message.ToString() + "  ,变量名是" + strVName, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
                    ret = false;
                }
            }
            return ret;
        }
        /// <summary>
        /// 读数组
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <param name="length">数组长度</param>
        /// <returns></returns>
        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);
                    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;
        }
        /// <summary>
        /// 写数组
        /// </summary>
        /// <param name="strVName">变量名</param>
        /// <param name="arr">数组的值</param>
        /// <returns></returns>
        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);
                    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.XXX");
        /// </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);
                    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);
                    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;//层数
        }
        #endregion

        #region 测试
        public int getXXData()
        {
            //1.连接ADS
            ConnectDev("adsip");
            //2.检查连接
            if (!CheckConnected())
            {
                //Connect error !
                return 0;
            }
            //3.读取变量值
            return ReadInt("gvl.XXData");
        }
        #endregion
    }

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@榴莲酥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值