ll的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
(八):全部源码
1

Imports
System.Runtime.InteropServices
2

Public Class Form1Class
Form1
3
4

Dim GlobalOPCServer As
OPCAutomation.OPCServerClass
5

Dim WithEvents
ConnectedOPCServer As OPCAutomation.OPCServerClass
6

Dim WithEvents
ConnectedGroup As OPCAutomation.OPCGroupClass
7
8

Dim GlobalOPCItems(4) As
OPCAutomation.OPCItem
9

Dim
GlobalOPCBlockItems(64) As OPCAutomation.OPCItem
10

11

12

'枚举OPC服务器列表
13

Private Sub
Form1_Load()Sub Form1_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
14

Try
15
GlobalOPCServer = New OPCAutomation.OPCServerClass()
16

Dim ServerList As Object
= GlobalOPCServer.GetOPCServers
17

For index As Short =
LBound(ServerList) To UBound(ServerList)
'加入控件列表中,注意这里使用LBound和UBound
18
cbbServerList.Items.Add(ServerList(index))
19

Next
20

If
cbbServerList.Items.Count > 0 Then
21
cbbServerList.SelectedIndex =
0
22

End If
23
ResetControlStatus() '设置控件状态
24
GlobalOPCServer = Nothing
25

Catch Ex As
Exception
26
MessageBox.Show('List OPC servers failed: ' + Ex.Message,
'OPCSample', MessageBoxButtons.OK)
27

End Try
28

End Sub
29

30

'连接到指定的OPC服务器
31

Private Sub
btnConnectServer_Click()Sub btnConnectServer_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnectServer.Click
32

If cbbServerList.Text
<> '' Then
33
ConnectedOPCServer = New OPCAutomation.OPCServerClass()
34

Try
35
ConnectedOPCServer.Connect(cbbServerList.Text)
36

'设置组集合的默认属性
37
ConnectedOPCServer.OPCGroups.DefaultGroupIsActive = True
38
ConnectedOPCServer.OPCGroups.DefaultGroupDeadband = 0
39

'添加组
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
Exception
49
ConnectedOPCServer = Nothing
50
MessageBox.Show('OPC server connect
failed : ' + ex.Message, 'OPCSample', MessageBoxButtons.OK)
51

End Try
52
ResetControlStatus()
53

End If
54

End Sub
55

56

'服务器断开事件通知
57

Private Sub
OnServerShutDown()Sub OnServerShutDown(ByVal Reason As String)
Handles ConnectedOPCServer.ServerShutDown
58
btnDisconnectServer_Click(Nothing,
New EventArgs())
59

End Sub
60

61

Private Sub
OnGroupDataChange()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
62

For i As Integer = 1 To
NumItems
63

If Qualities(i) =
OPCAutomation.OPCQuality.OPCQualityGood Then
64

Select Case
ClientHandles(i)
65

Case 2
66
txtCardNo.Text =
CStr(ItemValues(i))
67

Case 200 '测试7张卡片
68
txtValueBlock0.Text =
CStr(ItemValues(i))
69

Case 201
70
txtValueBlock1.Text =
CStr(ItemValues(i))
71

Case 202
72
txtValueBlock2.Text =
CStr(ItemValues(i))
73

Case 203
74
txtValueBlock3.Text =
CStr(ItemValues(i))
75

Case 204
76
txtValueBlock4.Text =
CStr(ItemValues(i))
77

Case 205
78
txtValueBlock5.Text =
CStr(ItemValues(i))
79

Case 206
80
txtValueBlock6.Text =
CStr(ItemValues(i))
81

Case 207
82
txtValueBlock7.Text =
CStr(ItemValues(i))
83

Case Else
84

85

End Select
86

87

End If
88

Next
89

End Sub
90

91

92

'断开到指定OPC服务器的连接
93

Private Sub
btnDisconnectServer_Click()Sub btnDisconnectServer_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles
btnDisconnectServer.Click
94

If Not
(ConnectedOPCServer Is Nothing) Then
95

Try
96
ConnectedOPCServer.Disconnect()
97

Catch ex As
Exception
98
MessageBox.Show('OPC server
disconnect failed: ' + ex.Message, 'OPCSample',
MessageBoxButtons.OK)
99

Finally
100
ConnectedOPCServer = Nothing
101
ResetControlStatus()
102

End Try
103

End If
104

End Sub
105

106

'开卡,并返回卡号
107

Private Sub
btnOpenCard_Click()Sub btnOpenCard_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
108

If ConnectedGroup IsNot
Nothing Then
109

Try
110

'准备参数数组
111

Dim ServerHandles(1) As
Integer
112

Dim ServerValues(1) As
Object
113

Dim ServerErrors As
System.Array
114
ServerHandles(1) =
GlobalOPCItems(0).ServerHandle
115
ServerValues(1) = 1
116

'写入值,用于执行OpenCard的操作
117
ConnectedGroup.SyncWrite(1,
ServerHandles, ServerValues, ServerErrors)
118

If ServerErrors(1)
<> 0 Then
119

MsgBox('OpenCardError: '
& ServerErrors(1))
120

End If
121

122
ServerHandles(1) =
GlobalOPCItems(2).ServerHandle
123

Dim ServerResult As
System.Array
124

'读取卡号
125
ConnectedGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDevice, 1,
ServerHandles, ServerResult, ServerErrors)
126

If ServerErrors(1)
<> 0 Then
127

MsgBox('ReadCardNoError:
' & ServerErrors(1))
128

Else
129
txtCardNo.Text = ServerResult(1)
130

End If
131

Catch ex As
Exception
132
MessageBox.Show('OPC server Open
Card failed: ' + ex.Message, 'OPCSample',
MessageBoxButtons.OK)
133

End Try
134
ResetControlStatus()
135

End If
136

End Sub
137

138

'读取卡片指定的块号的值
139

Private Sub
btnReadCard_Click()Sub btnReadCard_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
140

If Not (ConnectedGroup
Is Nothing) Then
141

Try
142

'获取块号
143

Dim BlockNo As Short =
CByte(ReadBlockNo.Text)
144

'如果要获取数据的块所对应的项还没有创建,就创建它
145

If
GlobalOPCBlockItems(BlockNo) Is Nothing Then
146
GlobalOPCBlockItems(BlockNo) =
ConnectedGroup.OPCItems.AddItem('Reader_Device.Block' &
CStr(BlockNo), 200 + BlockNo)
147

End If
148

'准备参数数组
149

Dim ServerResults As
System.Array
150

Dim ServerErrors As
System.Array
151

Dim ServerHandles(1) As
Integer
152
ServerHandles(1) =
GlobalOPCBlockItems(BlockNo).ServerHandle
153

'读取值
154
ConnectedGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDevice, 1,
ServerHandles, ServerResults, ServerErrors)
155

If ServerErrors(1)
<> 0 Then
156

MsgBox('Read Card
Failed:' & ServerErrors(1))
157

Else
158
txtReadBlockNo.Text = ServerResults(1)
159

End If
160

Catch ex As
Exception
161
MessageBox.Show('OPC server Read
Card failed: ' + ex.Message, 'OPCSample',
MessageBoxButtons.OK)
162

End Try
163

End If
164

End Sub
165

166

'写卡片指定块的值
167

Private Sub
btnWriteCard_Click()Sub btnWriteCard_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
168

If Not (ConnectedGroup
Is Nothing) Then
169

Try
170

'获取块号
171

Dim BlockNo As Short =
CByte(WriteBlockNo.Text)
172

'如果要写入数据的块所对应的项还没有创建,就创建它
173

If
GlobalOPCBlockItems(BlockNo) Is Nothing Then
174
GlobalOPCBlockItems(BlockNo) =
ConnectedGroup.OPCItems.AddItem('Reader_Device.Block' &
CStr(BlockNo), 200 + BlockNo)
175

End If
176

'准备参数数组
177

Dim ServerValues(1) As
Object
178

Dim ServerErrors As
Array
179

Dim ServerHandles(1) As
Integer
180
ServerHandles(1) =
GlobalOPCBlockItems(BlockNo).ServerHandle
181
ServerValues(1) =
txtWriteBlockNo.Text
182

'写入值
183
ConnectedGroup.SyncWrite(1,
ServerHandles, ServerValues, ServerErrors)
184

If ServerErrors(1)
<> 0 Then
185

MsgBox('Write Card
Failed:' & ServerErrors(1))
186

Else
187

MsgBox('Write Card
Succeed')
188

End If
189

Catch ex As
Exception
190
MessageBox.Show('OPC server Write
Card failed: ' + ex.Message, 'OPCSample',
MessageBoxButtons.OK)
191

End Try
192

End If
193

End Sub
194

195

'重设控件状态
196

Private Sub
ResetControlStatus()Sub ResetControlStatus()
197

If ConnectedOPCServer Is
Nothing Then
198
btnConnectServer.Enabled = True
199
btnDisconnectServer.Enabled = False
200
btnReadCard.Enabled = False
201
btnWriteCard.Enabled = False
202
btnOpenCard.Enabled = False
203
btnCloseCard.Enabled = False
204
ReadBlockNo.Value = 0
205
WriteBlockNo.Value = 0
206
txtReadBlockNo.Text = ''
207
txtWriteBlockNo.Text =
'000000000000000000000000
00000000'
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

Else
219
btnConnectServer.Enabled = False
220
btnDisconnectServer.Enabled = True
221

If txtCardNo.Text = ''
Then
222
btnReadCard.Enabled = False
223
btnWriteCard.Enabled = False
224
btnOpenCard.Enabled = True
225
btnCloseCard.Enabled = False
226

Else
227
btnReadCard.Enabled = True
228
btnWriteCard.Enabled = True
229
btnOpenCard.Enabled = True
230
btnCloseCard.Enabled = True
231

End If
232

End If
233

End Sub
234

235

'刷新服务器状态属性信息
236

Private Sub
RefreshServerStatus()Sub RefreshServerStatus()
237

If ConnectedOPCServer
IsNot Nothing Then
238
txtSrvStartTime.Text =
ConnectedOPCServer.StartTime.ToString()
239
txtSrvCurrTime.Text =
ConnectedOPCServer.CurrentTime.ToString()
240

With
ConnectedOPCServer.OPCGroups
241
txtSrvGroupCount.Text =
CStr(.Count)
242
txtSrvGroupDeadBand.Text =
CStr(.DefaultGroupDeadband)
243

If .DefaultGroupIsActive
Then
244
txtSrvGroupDefActive.Text = 'True'
245

Else
246
txtSrvGroupDefActive.Text = 'False'
247

End If
248
txtSrvGroupLocalID.Text =
CStr(.DefaultGroupLocaleID)
249
txtSrvGroupTimeBias.Text =
CStr(.DefaultGroupTimeBias)
250
txtSrvRequestRate.Text =
CStr(.DefaultGroupUpdateRate)
251

End With
252

End If
253

End Sub
254

255

'关闭卡片
256

Private Sub
btnCloseCard_Click()Sub btnCloseCard_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
257

If ConnectedGroup IsNot
Nothing Then
258

Try
259

Dim ServerHandles(1) As
Integer
260

Dim ServerValues(1) As
Object
261

Dim ServerErrors As
System.Array
262
ServerHandles(1) =
GlobalOPCItems(1).ServerHandle
263
ServerValues(1) = 1
264
ConnectedGroup.SyncWrite(1,
ServerHandles, ServerValues, ServerErrors)
265

If ServerErrors(1)
<> 0 Then
266

MsgBox('Close Card
Error: ' & ServerErrors(1))
267

End If
268

Catch ex As
Exception
269
MessageBox.Show('OPC server Close
Card failed: ' + ex.Message, 'OPCSample',
MessageBoxButtons.OK)
270

End Try
271

End If
272

End Sub
273

End Class
274
