文章目录
前言
C#通过KEPServer对PLC进行:读取
一、在通过OPCAutomation我们先了解下这个类下的三个对象
在通过OPCAutomation我们先了解下这个类下的三个对象
1.OPCServer:创建OPC的连接
2.OPCBrowser:创建OPC浏览对象
3.OPCGroups:OPC通信组对象
4.OPCItem:单个代操作(读取的对象)
二、使用步骤
1.1.获取当前程序下的所有IP地址/计算机名,将得到的对象存入控件
this.cmbServerNode.Items.Clear();// 清空下拉框
IPHostEntry IPHost = Dns.GetHostEntry(Environment.MachineName); // 获取本机IP地址
if (IPHost.AddressList.Length > 0)// 判断是否获取到IP地址
{
int count = IPHost.AddressList.Length;
for (int i = 0; i < count; i++)
{
string HostName = Dns.GetHostEntry(IPHost.AddressList[i].ToString()).HostName;
if (!this.cmbServerNode.Items.Contains(HostName))
{
this.cmbServerNode.Items.Add(HostName);
}
}
}
else
{
return;
}
2.根据选择的IP地址/计算机名得到OPC服务名称列表,并加载进控件
this.cmbServerName.Items.Clear();// 清空下拉框
KepServer = new OPCServer();// 创建服务器对象
object serverList = KepServer.GetOPCServers(this.cmbServerNode.Text.Trim());
foreach(string item in (Array)serverList)
{
this.cmbServerName.Items.Add(item);
}
3.连接OPC服务器,其中KepBrowser记录的就是服务器内所有的标签变量,接下来就是创建组并激活,开启订阅功能,并且绑定读的操作(也可以绑定值改变的事件,根据自己需要进行选择)
try
{
// 连接OPC服务器
KepServer