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 Try
End 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)的默认通信区域编号,如1024
OPCGroups.DefaultGroupUpdateRate:组(Group)的默认刷新率,该属性也比较重要
OPCGroups.DefaultGroupTimeBias:组(Group)的默认时间偏差
(四) :添加组(Group)和项 (Item)
添加组和项需要用到Groups.Add和Items.AddItem方法,以下是原型:
Function Add(Optional ByVal Name As Object = Nothing) As OPCAutomation.OPCGroup
Function 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 As System.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 As Integer)
Group的异步写事件
Sub AsyncWrite(ByVal NumItems As Integer, ByRef ServerHandles As System.Array, ByRef Values As System.Array, ByRef Errors As System.Array, ByVal TransactionID As 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 As System.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, ByRef Qualities 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 If
End 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 If
End 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 If
End Sub
(七) :相关链接
非常好的一个OPC技术网站http://www.opcconnect.com/
OPC基金会网址http://www.opcfoundation.org/
国内的一个比较好的OPC网站http://www.opc-china.com/Index.html
(八):全部源码
Imports System.Runtime.InteropServices2
Public Class Form13

4
Dim GlobalOPCServer As OPCAutomation.OPCServerClass5
Dim WithEvents ConnectedOPCServer As OPCAutomation.OPCServerClass6
Dim WithEvents ConnectedGroup As OPCAutomation.OPCGroupClass7

8
Dim GlobalOPCItems(4) As OPCAutomation.OPCItem9
Dim GlobalOPCBlockItems(64) As OPCAutomation.OPCItem10

11

12
'枚举OPC服务器列表13
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load14
Try15
GlobalOPCServer = New OPCAutomation.OPCServerClass()16
Dim ServerList As Object = GlobalOPCServer.GetOPCServers17
For index As Short = LBound(ServerList) To UBound(ServerList) '加入控件列表中,注意这里使用LBound和UBound18
cbbServerList.Items.Add(ServerList(index))19
Next20
If cbbServerList.Items.Count > 0 Then21
cbbServerList.SelectedIndex = 022
End If23
ResetControlStatus() '设置控件状态24
GlobalOPCServer = Nothing25
Catch Ex As Exception26
MessageBox.Show("List OPC servers failed: " + Ex.Message, "OPCSample", MessageBoxButtons.OK)27
End Try28
End Sub29

30
'连接到指定的OPC服务器31
Private Sub btnConnectServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnectServer.Click32
If cbbServerList.Text <> "" Then33
ConnectedOPCServer = New OPCAutomation.OPCServerClass()34
Try35
ConnectedOPCServer.Connect(cbbServerList.Text)36
'设置组集合的默认属性37
ConnectedOPCServer.OPCGroups.DefaultGroupIsActive = True38
ConnectedOPCServer.OPCGroups.DefaultGroupDeadband = 039
'添加组40
ConnectedGroup = ConnectedOPCServer.OPCGroups.Add()41
ConnectedGroup.UpdateRate = 3 * 1000 '刷新虑,用于下面的DataChange事件42
ConnectedGroup.IsSubscribed = True '使用订阅功能43
'添加项44
GlobalOPCItems(0) = ConnectedGroup.OPCItems.AddItem("Reader_Device.OpenCard", 0)45
GlobalOPCItems(1) = ConnectedGroup.OPCItems.AddItem("Reader_Device.CloseCard", 1)46
GlobalOPCItems(2) = ConnectedGroup.OPCItems.AddItem("Reader_Device.CardNO", 2)47
RefreshServerStatus() '刷新服务器状态48
Catch ex As Exception49
ConnectedOPCServer = Nothing50
MessageBox.Show("OPC server connect failed : " + ex.Message, "OPCSample", MessageBoxButtons.OK)51
End Try52
ResetControlStatus()53
End If54
End Sub55

56
'服务器断开事件通知57
Private Sub OnServerShutDown(ByVal Reason As String) Handles ConnectedOPCServer.ServerShutDown58
btnDisconnectServer_Click(Nothing, New EventArgs())59
End Sub60

61
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.DataChange62
For i As Integer = 1 To NumItems63
If Qualities(i) = OPCAutomation.OPCQuality.OPCQualityGood Then64
Select Case ClientHandles(i)65
Case 266
txtCardNo.Text = CStr(ItemValues(i))67
Case 200 '测试7张卡片68
txtValueBlock0.Text = CStr(ItemValues(i))69
Case 20170
txtValueBlock1.Text = CStr(ItemValues(i))71
Case 20272
txtValueBlock2.Text = CStr(ItemValues(i))73
Case 20374
txtValueBlock3.Text = CStr(ItemValues(i))75
Case 20476
txtValueBlock4.Text = CStr(ItemValues(i))77
Case 20578
txtValueBlock5.Text = CStr(ItemValues(i))79
Case 20680
txtValueBlock6.Text = CStr(ItemValues(i))81
Case 20782
txtValueBlock7.Text = CStr(ItemValues(i))83
Case Else84

85
End Select86

87
End If88
Next89
End Sub90

91

92
'断开到指定OPC服务器的连接93
Private Sub btnDisconnectServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnectServer.Click94
If Not (ConnectedOPCServer Is Nothing) Then95
Try96
ConnectedOPCServer.Disconnect()97
Catch ex As Exception98
MessageBox.Show("OPC server disconnect failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK)99
Finally100
ConnectedOPCServer = Nothing101
ResetControlStatus()102
End Try103
End If104
End Sub105

106
'开卡,并返回卡号107
Private Sub btnOpenCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)108
If ConnectedGroup IsNot Nothing Then109
Try110
'准备参数数组111
Dim ServerHandles(1) As Integer112
Dim ServerValues(1) As Object113
Dim ServerErrors As System.Array114
ServerHandles(1) = GlobalOPCItems(0).ServerHandle115
ServerValues(1) = 1116
'写入值,用于执行OpenCard的操作117
ConnectedGroup.SyncWrite(1, ServerHandles, ServerValues, ServerErrors)118
If ServerErrors(1) <> 0 Then119
MsgBox("OpenCardError: " & ServerErrors(1))120
End If121

122
ServerHandles(1) = GlobalOPCItems(2).ServerHandle123
Dim ServerResult As System.Array124
'读取卡号125
ConnectedGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDevice, 1, ServerHandles, ServerResult, ServerErrors)126
If ServerErrors(1) <> 0 Then127
MsgBox("ReadCardNoError: " & ServerErrors(1))128
Else129
txtCardNo.Text = ServerResult(1)130
End If131
Catch ex As Exception132
MessageBox.Show("OPC server Open Card failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK)133
End Try134
ResetControlStatus()135
End If136
End Sub137

138
'读取卡片指定的块号的值139
Private Sub btnReadCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)140
If Not (ConnectedGroup Is Nothing) Then141
Try142
'获取块号143
Dim BlockNo As Short = CByte(ReadBlockNo.Text)144
'如果要获取数据的块所对应的项还没有创建,就创建它145
If GlobalOPCBlockItems(BlockNo) Is Nothing Then146
GlobalOPCBlockItems(BlockNo) = ConnectedGroup.OPCItems.AddItem("Reader_Device.Block" & CStr(BlockNo), 200 + BlockNo)147
End If148
'准备参数数组149
Dim ServerResults As System.Array150
Dim ServerErrors As System.Array151
Dim ServerHandles(1) As Integer152
ServerHandles(1) = GlobalOPCBlockItems(BlockNo).ServerHandle153
'读取值154
ConnectedGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDevice, 1, ServerHandles, ServerResults, ServerErrors)155
If ServerErrors(1) <> 0 Then156
MsgBox("Read Card Failed:" & ServerErrors(1))157
Else158
txtReadBlockNo.Text = ServerResults(1)159
End If160
Catch ex As Exception161
MessageBox.Show("OPC server Read Card failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK)162
End Try163
End If164
End Sub165

166
'写卡片指定块的值167
Private Sub btnWriteCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)168
If Not (ConnectedGroup Is Nothing) Then169
Try170
'获取块号171
Dim BlockNo As Short = CByte(WriteBlockNo.Text)172
'如果要写入数据的块所对应的项还没有创建,就创建它173
If GlobalOPCBlockItems(BlockNo) Is Nothing Then174
GlobalOPCBlockItems(BlockNo) = ConnectedGroup.OPCItems.AddItem("Reader_Device.Block" & CStr(BlockNo), 200 + BlockNo)175
End If176
'准备参数数组177
Dim ServerValues(1) As Object178
Dim ServerErrors As Array179
Dim ServerHandles(1) As Integer180
ServerHandles(1) = GlobalOPCBlockItems(BlockNo).ServerHandle181
ServerValues(1) = txtWriteBlockNo.Text182
'写入值183
ConnectedGroup.SyncWrite(1, ServerHandles, ServerValues, ServerErrors)184
If ServerErrors(1) <> 0 Then185
MsgBox("Write Card Failed:" & ServerErrors(1))186
Else187
MsgBox("Write Card Succeed")188
End If189
Catch ex As Exception190
MessageBox.Show("OPC server Write Card failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK)191
End Try192
End If193
End Sub194

195
'重设控件状态196
Private Sub ResetControlStatus()197
If ConnectedOPCServer Is Nothing Then198
btnConnectServer.Enabled = True199
btnDisconnectServer.Enabled = False200
btnReadCard.Enabled = False201
btnWriteCard.Enabled = False202
btnOpenCard.Enabled = False203
btnCloseCard.Enabled = False204
ReadBlockNo.Value = 0205
WriteBlockNo.Value = 0206
txtReadBlockNo.Text = ""207
txtWriteBlockNo.Text = "00000000000000000000000000000000"208
txtCardNo.Text = ""209

210
txtSrvStartTime.Text = ""211
txtSrvCurrTime.Text = ""212
txtSrvGroupCount.Text = ""213
txtSrvGroupDeadBand.Text = ""214
txtSrvGroupDefActive.Text = ""215
txtSrvGroupLocalID.Text = ""216
txtSrvGroupTimeBias.Text = ""217
txtSrvRequestRate.Text = ""218
Else219
btnConnectServer.Enabled = False220
btnDisconnectServer.Enabled = True221
If txtCardNo.Text = "" Then222
btnReadCard.Enabled = False223
btnWriteCard.Enabled = False224
btnOpenCard.Enabled = True225
btnCloseCard.Enabled = False226
Else227
btnReadCard.Enabled = True228
btnWriteCard.Enabled = True229
btnOpenCard.Enabled = True230
btnCloseCard.Enabled = True231
End If232
End If233
End Sub234

235
'刷新服务器状态属性信息236
Private Sub RefreshServerStatus()237
If ConnectedOPCServer IsNot Nothing Then238
txtSrvStartTime.Text = ConnectedOPCServer.StartTime.ToString()239
txtSrvCurrTime.Text = ConnectedOPCServer.CurrentTime.ToString()240
With ConnectedOPCServer.OPCGroups241
txtSrvGroupCount.Text = CStr(.Count)242
txtSrvGroupDeadBand.Text = CStr(.DefaultGroupDeadband)243
If .DefaultGroupIsActive Then244
txtSrvGroupDefActive.Text = "True"245
Else246
txtSrvGroupDefActive.Text = "False"247
End If248
txtSrvGroupLocalID.Text = CStr(.DefaultGroupLocaleID)249
txtSrvGroupTimeBias.Text = CStr(.DefaultGroupTimeBias)250
txtSrvRequestRate.Text = CStr(.DefaultGroupUpdateRate)251
End With252
End If253
End Sub254

255
'关闭卡片256
Private Sub btnCloseCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)257
If ConnectedGroup IsNot Nothing Then258
Try259
Dim ServerHandles(1) As Integer260
Dim ServerValues(1) As Object261
Dim ServerErrors As System.Array262
ServerHandles(1) = GlobalOPCItems(1).ServerHandle263
ServerValues(1) = 1264
ConnectedGroup.SyncWrite(1, ServerHandles, ServerValues, ServerErrors)265
If ServerErrors(1) <> 0 Then266
MsgBox("Close Card Error: " & ServerErrors(1))267
End If268
Catch ex As Exception269
MessageBox.Show("OPC server Close Card failed: " + ex.Message, "OPCSample", MessageBoxButtons.OK)270
End Try271
End If272
End Sub273
End Class274



浙公网安备 33010602011771号