当前位置:网站首页>ADS与C#通信
ADS与C#通信
2022-07-31 12:54:00 【黄昏和星空】
TwinCAT.Ads.rar-C#文档类资源-CSDN下载 这个是ADS3.1 DLL的下载地址
1.PLC与C#类型对应表
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 连接,断开连接,检查连接状态
///
/// 连接
/// 该ip是TwinCat上的IP
///
///
///
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
边栏推荐
猜你喜欢
golang八股文整理(持续搬运)
Hard disk partition, expand disk C, no reshipment system, not heavy D dish of software full tutorial.
关于MySQL主从复制的数据同步延迟问题
[CPU Design Practice] Simple Pipeline CPU Design
五种数据提交方式的优化
跨境电商小知识之跨境电商物流定义以及方式讲解
基于verilog的CRC校验(汇总)
CWE4.8 -- 2022年危害最大的25种软件安全问题
365-day challenge LeetCode1000 questions - Day 044 Maximum element in the layer and level traversal
PyQt5快速开发与实战 9.7 UI层的自动化测试
随机推荐
字符函数和字符串函数
NameNode (NN) 和SecondaryNameNode (2NN)工作机制
Build a Valentine's Day confession website (super detailed process, package teaching package)
计算机复试面试问题(计算机面试常见问题)
CWE4.8 -- 2022年危害最大的25种软件安全问题
Anaconda安装labelImg图像标注软件
全局平均池化层替代全连接层(最大池化和平均池化的区别)
golang中使用泛型
ipv4和ipv6对比(IPV4)
Google Chrome(谷歌浏览器)安装使用
Architecture Camp | Module 8
PyQt5 rapid development and actual combat 9.7 Automated testing of UI layer
Basic use of dosbox [easy to understand]
Verilog——基于FPGA的贪吃蛇游戏(VGA显示)
[RPI]树莓派监控温度及报警关机保护「建议收藏」
Flutter键盘可见性
365天挑战LeetCode1000题——Day 044 最大层内元素和 层次遍历
查看Oracle数据库的用户名和密码
ASM module in SAP Ecommerce Cloud Spartacus UI and Accelerator UI
榕树贷款GPU 硬件架构