OPC客户端编程汇编(44页).doc
-OPC客户端编程汇编-第 44 页OPC编程汇编 OPC客户端的自动化实现OPC是建立在COM,DCOM的基础商的,因此绝大多数语言都可以很好的进行开发。在Net中开发客户端有以下几种方式:(1) 使用OPCNetAPI,需要用到OPCNetAPI.dll,OPCNetAPI.Com.dll(2) 使用自动化接口,需要用到OPCDAAuto.dll(3) 使用自定义接口,需要用到多个Wrapper:OpcRcw.Ae.dll,OpcRcw.Batch.dll,OpcRcw.Comn.dll,OpcRcw.Da.dll,OpcRcw.Dx.dll,OpcRcw.Hda.dll,OpcRcw.Sec.dll以上开发方式所需的动态链接库可以从OPC基金会(http:/www.opcfoundation.org/)的网站上下载,一些下载项目可能需要注册,或成为基金会的成员。不同的方式有各自的有缺点,请参见本文使用自动化接口,VB.Net语言进行开发,开发项目是无线射频(RFID)卡方面的应用,典型的如公交车,或公司考勤使用的刷卡机。需要注意的是自动化接口存在一个“不是问题”的问题,数组下标是以1开始的,而不是传统计算机开发上的以0开始。不知道设计者头脑是怎么想(有人知道吗?);这可能会给一些语言的开发造成问题(有人碰到吗,没有你就是幸运的)需求:OPCDAAuto.dll或该Dll的Interop(一) :客户端开发流程OPC客户端的开发主要遵循下图所示的开发流程,下面就从以下几个开发步骤进行说明 (二) :枚举OPC服务器列表枚举服务器主要是通过OPCServer接口的GetOPCServers方法来实现的,该方法会返回OPC服务器数组(以1为下界,上面已有说明),以下是代码段 '枚举OPC服务器列表 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Try GlobalOPCServer = New OPCAutomation.OPCServerClass() Dim ServerList As Object = GlobalOPCServer.GetOPCServers For index As Short = LBound(ServerList) To UBound(ServerList) '加入控件列表中,注意这里使用LBound和UBound cbbServerList.Items.Add(ServerList(index) Next If cbbServerList.Items.Count > 0 Then cbbServerList.SelectedIndex = 0 End If ResetControlStatus() '设置控件状态 GlobalOPCServer = Nothing Catch Ex As Exception MessageBox.Show("List OPC servers failed: " + Ex.Message, "OPCSample", MessageBoxButtons.OK) End TryEnd Sub(三) :连接OPC服务器自动化接口中连接到服务器是使用connect方法Public Overridable Sub Connect(ByVal ProgID As String, Optional ByVal Node As Object = Nothing)ProgID指服务器的ProgID,Node代表网络节点,如果是本机则放空即可。连接到服务器后,以下属性需要特别注意:OPCServer.StartTime:服务器的启动时间OPCServer.CurrentTime:服务器的当前时间,各个客户端可以通过这个属性值完成一些同步的操作OPCGroups.DefaultGroupIsActive:以后添加的Group是否默认激活OPCGroups.DefaultGroupDeadBand:Group的默认死区,变化量超过死区后将会触发DataChange事件,合理的设置该值可以提高程序性能OPCGroups.Count:下属组(Group)的数量OPCGroups.DefaultGroupLocalID:组(Group)的默认通信区域编号,如1024OPCGroups.DefaultGroupUpdateRate:组(Group)的默认刷新率,该属性也比较重要OPCGroups.DefaultGroupTimeBias:组(Group)的默认时间偏差(四) :添加组(Group)和项 (Item)添加组和项需要用到Groups.Add和Items.AddItem方法,以下是原型:Function Add(Optional ByVal Name As Object = Nothing) As OPCAutomation.OPCGroupFunction AddItem(ByVal ItemID As String, ByVal ClientHandle As Integer) As OPCAutomation.OPCItem 组也有两个重要的属性 Group.UpdateRate:刷新率,该属性通Groups的UpdateRate意义一样,如果这个值有设置,则以这个值为准 Group. IsSubscribed:是否使用订阅功能 以下是代码段 '连接到指定的OPC服务器 Private Sub btnConnectServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnectServer.Click If cbbServerList.Text <> "" Then ConnectedOPCServer = New OPCAutomation.OPCServerClass() Try ConnectedOPCServer.Connect(cbbServerList.Text) '设置组集合的默认属性 ConnectedOPCServer.OPCGroups.DefaultGroupIsActive = True ConnectedOPCServer.OPCGroups.DefaultGroupDeadband = 0 '添加组 ConnectedGroup = ConnectedOPCServer.OPCGroups.Add() ConnectedGroup.UpdateRate = 3 * 1000 '刷新虑,用于下面的DataChange事件 ConnectedGroup.IsSubscribed = True '使用订阅功能 '添加项 GlobalOPCItems(0) = ConnectedGroup.OPCItems.AddItem("Reader_Device.OpenCard", 0) GlobalOPCItems(1) = ConnectedGroup.OPCItems.AddItem("Reader_Device.CloseCard", 1) GlobalOPCItems(2) = ConnectedGroup.OPCItems.AddItem("Reader_Device.CardNO", 2) RefreshServerStatus() '刷新服务器状态 Catch ex As Exception ConnectedOPCServer = Nothing MessageBox.Show("OPC server connect failed : " + ex.Message, "OPCSample", MessageBoxButtons.OK) End Try ResetControlStatus() End If End Sub(五) :读写操作与事件控制读写操作包括同步和异步两种操作方式,以下是这几个方法的原型:Group的同步读事件Sub SyncRead(ByVal Source As Short, ByVal NumItems As Integer, ByRef ServerHandles As System.Array, ByRef Values As System.Array, ByRef Errors AsSystem.Array, Optional ByRef Qualities As Object = Nothing, Optional ByRef TimeStamps As Object = Nothing)Group的同步写事件Sub SyncWrite(ByVal NumItems As Integer, ByRef ServerHandles As System.Array, ByRef Values As System.Array, ByRef Errors As System.Array)Group的异步读事件Sub AsyncRead(ByVal NumItems As Integer, ByRef ServerHandles As System.Array, ByRef Errors As System.Array, ByVal TransactionID As Integer, ByRef CancelID AsInteger)Group的异步写事件Sub AsyncWrite(ByVal NumItems As Integer, ByRef ServerHandles As System.Array, ByRef Values As System.Array, ByRef Errors As System.Array, ByVal TransactionIDAs Integer, ByRef CancelID As Integer)如果使用异步的读写操作,那么还需要实现Group中的ReadComplete和WriteComplete两个事件Public Event AsyncReadComplete(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles As System.Array, ByRef ItemValues AsSystem.Array, ByRef Qualities As System.Array, ByRef TimeStamps As System.Array, ByRef Errors As System.Array)Public Event AsyncWriteComplete(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles As System.Array, ByRef Errors As System.Array)其他相关的重要事件包括:Group数据变化时的通知事件Public Event DataChange(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles As System.Array, ByRef ItemValues As System.Array, ByRefQualities As System.Array, ByRef TimeStamps As System.Array)Group的异步取消事件Public Event AsyncCancelComplete(ByVal CancelID As Integer)Server(服务器)关闭通知事件Public Event ServerShutDown(ByVal Reason As String)以下是这些实现的代码段 '读取卡片指定的块号的值 Private Sub btnReadCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) If Not (ConnectedGroup Is Nothing) Then Try '获取块号 Dim BlockNo As Short = CByte(ReadBlockNo.Text) '如果要获取数据的块所对应的项还没有创建,就创建它 If GlobalOPCBlockItems(BlockNo) Is Nothing Then GlobalOPCBlockItems(BlockNo) = ConnectedGroup.OPCItems.AddItem("Reader_Device.Block" & CStr(BlockNo), 200 + BlockNo) End If '准备参数数组 Dim ServerResults As System.Array Dim ServerErrors As System.Array Dim ServerHandles(1) As Integer ServerHandles(1) = GlobalOPCBlockItems(BlockNo).ServerHandle '读取值 ConnectedGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDevice, 1, ServerHandles, ServerResults, ServerErrors) If ServerErrors(1) <> 0 Then MsgBox("Read Card Failed:" & ServerErrors(1) Else txtReadBlockNo.Text = ServerResults(1) End If Catch ex As Exception MessageBox.Show("OPC server Read Card failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK) End Try End IfEnd Sub '写卡片指定块的值 Private Sub btnWriteCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) If Not (ConnectedGroup Is Nothing) Then Try '获取块号 Dim BlockNo As Short = CByte(WriteBlockNo.Text) '如果要写入数据的块所对应的项还没有创建,就创建它 If GlobalOPCBlockItems(BlockNo) Is Nothing Then GlobalOPCBlockItems(BlockNo) = ConnectedGroup.OPCItems.AddItem("Reader_Device.Block" & CStr(BlockNo), 200 + BlockNo) End If '准备参数数组 Dim ServerValues(1) As Object Dim ServerErrors As Array Dim ServerHandles(1) As Integer ServerHandles(1) = GlobalOPCBlockItems(BlockNo).ServerHandle ServerValues(1) = txtWriteBlockNo.Text '写入值 ConnectedGroup.SyncWrite(1, ServerHandles, ServerValues, ServerErrors) If ServerErrors(1) <> 0 Then MsgBox("Write Card Failed:" & ServerErrors(1) Else MsgBox("Write Card Succeed") End If Catch ex As Exception MessageBox.Show("OPC server Write Card failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK) End Try End IfEnd Sub(六) :断开服务器断开服务器只要使用OPCServer的Disconnect方法几个,以下是代码段: '断开到指定OPC服务器的连接 Private Sub btnDisconnectServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnectServer.Click If Not (ConnectedOPCServer Is Nothing) Then Try ConnectedOPCServer.Disconnect() Catch ex As Exception MessageBox.Show("OPC server disconnect failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK) Finally ConnectedOPCServer = Nothing ResetControlStatus() End Try End IfEnd Sub(七) :相关链接非常好的一个OPC技术网站OPC基金会网址http:/www.opcfoundation.org/国内的一个比较好的OPC网站http:/www.opc-(八):全部源码Imports System.Runtime.InteropServices Public Class Form1 Dim GlobalOPCServer As OPCAutomation.OPCServerClass Dim WithEvents ConnectedOPCServer As OPCAutomation.OPCServerClass Dim WithEvents ConnectedGroup As OPCAutomation.OPCGroupClass Dim GlobalOPCItems(4) As OPCAutomation.OPCItem Dim GlobalOPCBlockItems(64) As OPCAutomation.OPCItem '枚举OPC服务器列表 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Try GlobalOPCServer = New OPCAutomation.OPCServerClass() Dim ServerList As Object = GlobalOPCServer.GetOPCServers For index As Short = LBound(ServerList) To UBound(ServerList) '加入控件列表中,注意这里使用LBound和UBound cbbServerList.Items.Add(ServerList(index) Next If cbbServerList.Items.Count > 0 Then cbbServerList.SelectedIndex = 0 End If ResetControlStatus() '设置控件状态 GlobalOPCServer = Nothing Catch Ex As Exception MessageBox.Show("List OPC servers failed: " + Ex.Message, "OPCSample", MessageBoxButtons.OK) End Try End Sub '连接到指定的OPC服务器 Private Sub btnConnectServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnectServer.Click If cbbServerList.Text <> "" Then ConnectedOPCServer = New OPCAutomation.OPCServerClass() Try ConnectedOPCServer.Connect(cbbServerList.Text) '设置组集合的默认属性 ConnectedOPCServer.OPCGroups.DefaultGroupIsActive = True ConnectedOPCServer.OPCGroups.DefaultGroupDeadband = 0 '添加组 ConnectedGroup = ConnectedOPCServer.OPCGroups.Add() ConnectedGroup.UpdateRate = 3 * 1000 '刷新虑,用于下面的DataChange事件 ConnectedGroup.IsSubscribed = True '使用订阅功能 '添加项 GlobalOPCItems(0) = ConnectedGroup.OPCItems.AddItem("Reader_Device.OpenCard", 0) GlobalOPCItems(1) = ConnectedGroup.OPCItems.AddItem("Reader_Device.CloseCard", 1) GlobalOPCItems(2) = ConnectedGroup.OPCItems.AddItem("Reader_Device.CardNO", 2) RefreshServerStatus() '刷新服务器状态 Catch ex As Exception ConnectedOPCServer = Nothing MessageBox.Show("OPC server connect failed : " + ex.Message, "OPCSample", MessageBoxButtons.OK) End Try ResetControlStatus() End If End Sub '服务器断开事件通知 Private Sub OnServerShutDown(ByVal Reason As String) Handles ConnectedOPCServer.ServerShutDown btnDisconnectServer_Click(Nothing, New EventArgs() End Sub Private Sub OnGroupDataChange(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles As System.Array, ByRef ItemValues As System.Array, ByRef Qualities As System.Array, ByRef TimeStamps As System.Array) Handles ConnectedGroup.DataChange For i As Integer = 1 To NumItems If Qualities(i) = OPCAutomation.OPCQuality.OPCQualityGood Then Select Case ClientHandles(i) Case 2 txtCardNo.Text = CStr(ItemValues(i) Case 200 '测试7张卡片 txtValueBlock0.Text = CStr(ItemValues(i) Case 201 txtValueBlock1.Text = CStr(ItemValues(i) Case 202 txtValueBlock2.Text = CStr(ItemValues(i) Case 203 txtValueBlock3.Text = CStr(ItemValues(i) Case 204 txtValueBlock4.Text = CStr(ItemValues(i) Case 205 txtValueBlock5.Text = CStr(ItemValues(i) Case 206 txtValueBlock6.Text = CStr(ItemValues(i) Case 207 txtValueBlock7.Text = CStr(ItemValues(i) Case Else End Select End If Next End Sub '断开到指定OPC服务器的连接 Private Sub btnDisconnectServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnectServer.Click If Not (ConnectedOPCServer Is Nothing) Then Try ConnectedOPCServer.Disconnect() Catch ex As Exception MessageBox.Show("OPC server disconnect failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK) Finally ConnectedOPCServer = Nothing ResetControlStatus() End Try End If End Sub '开卡,并返回卡号 Private Sub btnOpenCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) If ConnectedGroup IsNot Nothing Then Try '准备参数数组 Dim ServerHandles(1) As Integer Dim ServerValues(1) As Object Dim ServerErrors As System.Array ServerHandles(1) = GlobalOPCItems(0).ServerHandle ServerValues(1) = 1 '写入值,用于执行OpenCard的操作 ConnectedGroup.SyncWrite(1, ServerHandles, ServerValues, ServerErrors) If ServerErrors(1) <> 0 Then MsgBox("OpenCardError: " & ServerErrors(1) End If