1,首先第一步,要连接OPC ,创建好 OPC对象。
/// <summary> /// 连接OPC /// </summary>
private string OPCIP=127.0.0.1; private string OPCName=PCAuto.OPCServer;
public void Connect() { if (string.IsNullOrEmpty(OPCIP)) { throw new ArgumentNullException("UaServer"); } if (string.IsNullOrEmpty(OPCName)) { throw new ArgumentNullException("UaServer"); } if (CreateServer()) { try { opcServer.Connect(OPCName, OPCIP); } catch (Exception ex) { MessageBox.Show("连接到OPC服务器失败!" + ex.Message); } } m_IsConnected = true; } /// <summary> /// 创建OPC服务 /// </summary> /// <returns></returns> public bool CreateServer() { try { opcServer = new OPCServer(); } catch (Exception ex) { MessageBox.Show("创建OPC服务出现异常:" + ex.Message); return false; } return true; }
2.窗体加载方法,我这里时winform 开发的程序。在窗体load事件加载 opc测点。使用 tree 控件。
/// <summary> /// 测点扫描加载监测点树 /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private TreeView treeView_opcItem; private void ScanItem_Load(object sender, EventArgs e) { try { OpcDaClient opcDaClient = new OpcDaClient(); TreeNode node = new TreeNode(); OPCBrowser opcBrowser = opcDaClient.RecurBrowse(); opcDaClient.ShowInTreeView(opcBrowser, node); treeView_opcItem.Nodes.Add(node); TreeNodeCollection nodes = treeView_opcItem.Nodes; GetChildNode(nodes); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
3.用到的子方法
/// <summary> /// 创建opc节点浏览对象 /// </summary> /// <returns></returns> public OPCBrowser RecurBrowse() { try { return opcServer.CreateBrowser(); } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } }
/// <summary> /// 展示OPC点号列表 /// </summary> /// <param name="opcBrowser"></param> /// <param name="node"></param> public void ShowInTreeView(OPCBrowser opcBrowser, TreeNode node) { TreeNode treeNode = null; opcBrowser.ShowBranches(); int count = opcBrowser.Count; List<string> list = null; if (opcBrowser.Count > 0) { list = new List<string>(); foreach (string item in opcBrowser) { list.Add(item); } foreach (string item2 in list) { treeNode = new TreeNode(item2); treeNode.Tag = opcBrowser.GetItemID(item2); node.Nodes.Add(treeNode); opcBrowser.MoveDown(item2); ShowInTreeView(opcBrowser, treeNode); opcBrowser.MoveUp(); } } opcBrowser.ShowLeafs(Type.Missing); int count2 = opcBrowser.Count; foreach (string item3 in opcBrowser) { treeNode = new TreeNode(opcBrowser.GetItemID(item3)); treeNode.Tag = opcBrowser.GetItemID(item3); node.Nodes.Add(treeNode); } }
4.获取当前节点下的子节点
private void GetChildNode(TreeNodeCollection nodes) { string empty = string.Empty; foreach (TreeNode node in nodes) { empty = node.Text; if (node.Nodes.Count == 0) { itemNameList.Add(node.Text); } GetChildNode(node.Nodes); } }
5.效果展示