当前位置:网站首页>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
边栏推荐
猜你喜欢
365天挑战LeetCode1000题——Day 044 最大层内元素和 层次遍历
IDEA连接MySQL数据库并执行SQL查询操作
2022年最新重庆建筑安全员模拟题库及答案
alert(1) (haozi.me)靶场练习
分布式监视 Zabbix 和 Prometheus 到底怎么选?千万别用错了!
networkx绘制度分布
跨境电商小知识之跨境电商物流定义以及方式讲解
The 2nd activity of the TOGAF10 Standard Reading Club continues wonderfully, and the highlights will be reviewed!
golang八股文整理(持续搬运)
Hard disk partition, expand disk C, no reshipment system, not heavy D dish of software full tutorial.
随机推荐
Optimization of five data submission methods
centos7安装mysql5.7
FIFO深度计算学习记录(汇总)
Exploring Plain Vision Transformer Backbones for Object Detection Paper Reading Notes
Introduction to using NPM
matlab as(assert dominance)
深入浅出边缘云 | 4. 生命周期管理
ASM module in SAP Ecommerce Cloud Spartacus UI and Accelerator UI
Cognitive-exercise rehabilitation medical robot application design
sqlalchemy determines whether a field of type array has at least one consistent data with an array
PyQt5 rapid development and actual combat 10.2 compound interest calculation && 10.3 refresh blog clicks
纷享销客罗旭对话元气森林黄晓枫:零售数字化的终点不是创新,而是数据
go中select语句
函数的参数
电脑重要文件很多,如何备份比较安全?
AMBA APB学习记录(AMBA 2.0)
如何使用StarUML画类图[通俗易懂]
带有对称约束切换线性系统的结构可控性
SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块
跨境电商小知识之跨境电商物流定义以及方式讲解