读这篇文章的朋友请提前了解下什么是opc, opc技术的产生在这里我不再多缀述了
本篇文章主要讲解一下c#调用Interop.OPCAutomation.dll实现OPC Client的注意事项,已通过正规项的检验,在这里给大家分享一下核心经验, 此文代码版权所有,仅供参考学习,不得转载或用于商业用途,如果引起
商业利益纠纷后果自负
这里我的OPC Client从OPC Server端读到的数据是一个分层级的Tree状数据结构,所以Connect上服务后通过OPCBrowser对象来遍历整个Tree, 一般网上提供的例子大多无法动态的读到所有的OPCGroup,而且无法分辨多
层级的Branch或是Leaf,经过我对数据多次调试终于找到一种通用的解决方案,基上可以适用多种OPCServer的
数据结构,包括Kepware公司的OPCServer, OPCServer Simulator等等的一些测试。你也可以用Kassl-dOPC-Explorer工具验证你的OPCClient读到的数据结构是否一样,经过验证我的OPCClient和此工具的结果是吻合的,
OPCBrowser通过递归调用将数据的各个节点加载到TreeView控件中,Leaf认为是OPCItem, Leaf的上一级为OPCGroup.Leaf不在TreeView的TreeNode中显示.具体实现请看以下代码
private OPCServer kepServer;
private OPCBrowser opcBrowser;
private Dictionary<string, OPCGroup> groupMap = new Dictionary<string, OPCGroup>();
private Dictionary<int, OPCItem> itemMap = new Dictionary<int, OPCItem>();
//此方法通过OPCBrowser将数据结节加载到TreeView中.
private bool LoadDataToTree(TreeNode node, string nodeName)
{
TreeNode childNode = null;
OPCGroup group = null;
try
{
this.opcBrowser.ShowBranches();
int count = this.opcBrowser.Count;
if (count == 0)
{
this.opcBrowser.ShowLeafs(true);
group = this.kepServer.OPCGroups.Add(nodeName);
group.UpdateRate = 1000;
group.IsSubscribed = true;
group.IsActive = true;
node.Tag = group;
this.groupMap.Add(nodeName, group);