OPC客户端的自动化_第1页
OPC客户端的自动化_第2页
OPC客户端的自动化_第3页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、OPC客户端的自动化实现OPC是建立在,D的基础商的,因此绝大多数语言都可以很好的进行开发。在Net中开发客户端有以下几种方式:(1)使用 OPetAPI,需要用到 OPetAPI.dll, OPetAPL.dll(2)使用自动化接口,需要用到OPCDAAuto.dll(3)使用自定义接口,需要用到多个Wrapper: OpcRcw.Ae.dll, OpcRcw. Batch.dll, , 以上开发方式所需的动态库可以从OPC基金会(./)的上 下载,一些下载项目可能需要注册,或成为基金会的成员。不同的方式有各自的有缺点,请参见本文便用自动化接口,VB.Net

2、语言进行开发,开发项目是无线射频(RFID)卡方面的应用,典型的如公交车,或公司考勤便用的刷卡机。需要注意的是自动化 接口存在一个"不是问题”的问题,数组下标是以1开始的,而不是传统计算机开 发上的以0开始。不知道设计者头脑是怎么想(有人知道吗?);这可能会给一些 语言的开发造成问题(有人碰到吗,没有你就是幸运的)需求:OPCDAAuto.dll 或该 D11 的 Interop(一):客户端开发流程OPC客户端的开发主要遵循下图所示的开发流程,下面就从以下几个开 发步骤进行说明(二):枚举OPC服务器列表枚举服务器主要是通过OPCServer接口的GetOPCServers方法来实

3、现的,该方法会返回OPC服务器数组(以1为下界,上面已有说明),以下是 代码段'枚举OPC服务器列表PrivateSub Forml_Load(ByVai sender As System.Object, ByVai e As System.EventArgs) HandlcsMyBase.LoadTryGlobalOPCSener = New OPCAutomation.OPCScrvcrClass()Dim ServcrList AsObject = GlobalOPCServer.GetOPCServersFor index AsShort = LBound(ServerList

4、) To UBound(ServcrList),加入控件列表中,注意这 里便用LBound和UBoundcbbSenrList.Items.Add(ServerList(indcx)NextIf cbbScrverList. Items. Count > 0 ThencbbSenerList.Selectcdlndex = 0EndlfResetControlStatusO '设更控件状态GlobalOPCSener = NotliingCatch Ex As ExceptionMessagcBox.ShowCList OPC servers failed: ” + Ex.Mes

5、sage, "OPCSaniple*,McssagcBoxButtons.OK)EndTryEndSub(三) :连接OPC服务器自动化接口中连接到服务器是使用connect方法Public Overridablc Sub Connect(ByVal ProgID As String, Optional ByVai NodeAs Object = Notliing)ProgID指服务器的ProgID, Node代表网络节点,如果是本机则放空即可。连接到服务器后,以下属性需要特别注意:OPCScncr.StartTiinc:服务器的启动时间OPCServer.CurrentTime:服

6、务器的当前时间,各个客户端可以通过这个属性值完成一些同步的操作OPCGroups.DcfaultGroupIsActive:以后添加的 Group 是否默认激活OPCGroups.DcfaultGroupDeadBand: Group的默认死区,变化量超过死区后将矣触发DataChangr 事件,合理的设旻该值可以提高程序性能OPCGroups.Count:下属俎(Group)的数量OPCGroups.DefaultGroupLocallD:俎(Group)的默认通信区域编号,如 1024 OPCGroups.DcfaultGroupUpdateRate:俎(Group)的默认刷新率,该属性也

7、比较重要 OPCGroups.DcfaultGroupTinieBias:俎(Group)的默认时间偏差(四) :添加组(Group)和项(Item)添加组和顼需要用到Groups.Add和Items.Addltem方法,以下是原型:Function Add(Optional By Vai Name As Object = Nothing) As OPCAutomation OPCGroupFunction AddItem(ByVal ItcnilD As String, ByVai ClientHandlc As Integer) As OPCAutomation OPCIt em组也有两个

8、重要的属性Group.UpdateRate:刷新率,该属性通 Groups 的 UpdateRate 意义一样,如果这个值有设置,则以这个值为准Group. IsSubscribed:是否使用订阅功能以下是代码段'连接利指定的OPC服务器PrivateSub btnConnectScrver_Click(ByVal sender As System.Object, By Vai e As Syste m.EvcntArgs) Handles btnConnectSender.ClickIf cbbScrvcrList.Text <> n,ThenConncctcdOPCSe

9、rver = New OPCAutomation.OPCSencrClass()TryConnectcdOPCServer.Connect(cbbScnerList.Text)'设旻俎隼合的默认属性ConnectcdOPCServer.OPCGroups.DcfaultGroupIsActive = TrueConncctcdOPCServer.OPCGroups.DcfaiiltGroupDcadband = 0'添加俎ConncctcdGroup = ConncetedOPCScrvrcr.OPCGroups.Add()ConnectcdGroup.UpdatcRate =

10、 3 * 1000 刪新虑,用于下面的 DataChangc事件ConncctcdGroup.IsSubscribcd = TruuY吏用订阅功能GlobalOPCItcms(O) = ce-OpenCard", 0)GlobalOPCItcms( 1) = ConncctcdGroup.OPCItcms.AddItem(nReader_Dcvi ce.CloseCardH, 1)GlobalOPCItcms(2) = ConncctcdGroup.OPCItems.AddItem(HReader_Dcvi ce.CardNO 2)RefreshServerStatiisQ 新服务器

11、状态Catch ex As ExceptionConncctedOPCServer = NothingMcssagcBox.Show('OPC server connect failed + ex.Message, ”OPC Sample", McssageBoxButtons.OK)EndTryResetControlStatus()EndlfEndSub(五) :读写操作与事件控制读写操作包括同步和异步两种操作方式,以下是这几个方法的原型:Group的同步读事件Sub SyncReadlByVal Source As Short, ByVai Numltcms As In

12、teger, ByRef Serv erHandlcs As System Array, ByRef Values As System ArrRy, ByRef Errors As System- Array, Optional ByRef Qualities As Object = Notliing, Optional ByRef TimeStanips A s Object = Notliing)Group的同步写事件Sub SyncWrite(ByVal Numitems As Integer, ByRef ScnerHandlcs As System Ar ray, ByRef Val

13、ues As System.Array, ByRef Errors As System.Array)Group的异步读事件Sub AsyncReadfByVal Numitems As Integer, ByRef ScnerHandlcs As System A rray, ByRef Errors As System.Array, ByVai TransactionlD As Integer, ByRef Canccll D As Integer)Group的异步写事件Sub AsyncWrite(ByVal Numitems As Integer, ByRef ServerHandles

14、 As System.A rray, ByRef Values As System.Array, ByRef Errors As System Array, ByVai Transacti onlD As Integer, ByRef CancclID As Integer)如果使用异步的读写操作,那么还需要实现Group中的Readplcte和Writepletc两个事件 Public Event AsyncReadplete(ByVal TransactionlD As Integer, ByVai Nuniltems As Integer, ByRef ClicntHandlcs As

15、System.Array, ByRef ItemValues As System.Arr 翌,ByRef Qualities As System Array, ByRef TinicStamps As System Array, ByRef Er rors As System.Array)Public Event AsyncWriteplete(ByVal TransactionlD As Integer ByVai Numltcms As Integer, ByRef ClicntHandlcs As System.Array, ByRef Errors As System.Array) 其

16、他相关的重要事件包括:Group敖据变化时的通知事件Public Event DataChange(ByVal TransactionlD As Integer, ByVai Nmnltcms As Integer, ByRef ClicntHandlcs As System.Array, ByRef ItemValues As System.Array, ByRef Qualities As System.Array, ByRef TiincStamps As System.Array)Group的异步取消事件Public Event AsyncCancelplete(ByVal Cancc

17、lID As Integer)Server (服务器)关闭通知事件Public Event ServerShutDown(ByVal Reason As String)以下是这些实现的代码段'读取卡片指定的块号的值PrivateSub btnRgdCard_Click(ByVal sender As System.Object, ByVai e As System.Ev entArgs)IfNot (ConnectedGroup IsNotliing) ThenTry'获取块号Dim BlockNo AsShort = CByte(ReadBlockNo.Tcxt)'如

18、果要获取数据的块所对应的项还没有创逮,就创逮它If GlobalOPCBlockItcms(Blocl<No) IsNothingThcnemf 'Rcader.Devicc.Block" & CStr(BlockNo), 200 + BlockNo)Endlf'准备参数数俎Dim ServcrResults As Systcm.ArrajDim ServerErrors As System.An注yDim ServerHandles(l) AslntegcrServerHandles(l) = GlobalOPCBlocldtcms(BlockNo).

19、SenerHandle'读取值ConncctcdGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDevice,1, ServcrHandles, Server Results, ServerErrors)If ServrcrErrors(l) <> 0 ThenMsgBox(nRcad Card Failed:" & ScrvrerErrors(l)ElsetxtReadBlocl<N o. Text = ScrvcrResults(l)EndlfCatch ex As ExceptionMessagcBo

20、x.ShowCOPC server Read Card failed: n + ex.Message, ”OPCSainple'*, McssagcBoxButtons.OK)EndTryEndlfEndSub'写卡片指定块的值PrivateSub btnVriteCard_Click(ByVal sender As Systcm.Objcct, ByVai e As System.E ventArgs)IfNot (ConnectedGroup IsNotliing) ThenTry'获取块号Dini BlockNo AsShort = CBytc(WriteBloc

21、kNo.Text)'如果要写入数据的块所对应的项还没有创建,就创建它If GlobalOPCBlockItems(Blocl<No) IsNothingTlicnemf 'Reader.Devicc.Block" & CStr(BlockNo), 200 + BlockNo)Endlf'准备参数数俎Dini ServerValues(l) AsObjectDim ServerErrors As ArrayDim S rrverHandles (1) AslntegcrServerHandles(l) = GlobalOPCBlocldtcms(B

22、lockNo).SenerHandleServerValucs(l) = txtWriteBlockNo.Text'写入值ConnectcdGroup.SyncWrite( 1, ServerHandlcs, ScrrcrValues, ServcrErr ors)If ServcrErrors(l) <> 0 ThenMsgBox( AVrite Card Failed& ScnerErrors(l)ElseMsgBox('Write Card Succeed* )EndlfCatch ex As ExceptionMcssagcBox.Show('

23、;OPC server Write Card failed: " + ex.Message, "OPCSainple", MessagcBoxButtons.OK)EndTryEndlfEndSub(六) :断开服务器断开服务器只要使用OPCServer的Disconnect方法几个,以下是代码段:'断开到指定OPC服务器的连接PrivateSub btnDisconnectServer_Click(ByVal sender As System.Object, ByVai c As Sy stcm.EventArgs) Handles btnDisconn

24、ectSener.ClickIfNot (ConnectedOPCServer IsNothing) ThenTryConnectedOPCServer.DisconnectOCatch ex As ExceptionMessageBox.Show('OPC server disconnect failed: + cx.Message, nOPCSainple", MessagcBoxButtons.OK)FinallyConnectedOPCServer = NothingResetControlStatus()EndTryEndlfEndSub(七):相关非常好的一个OP

25、C技术.opcconnect./OPC 基金会网址/国内的一个比较好的 OPC.opc-china./Index.html(A):全部源码Imports Public Class FormlDim GlobalOPCSender As OPCAutomation.OPCServcrClassDim WithEvents ConncctedOPCSrrvcr As O PCAutomation. OPC Server ClassDim WithEvents ConnectedGroup As OPCAutomation.OPCGroupClassDiin Glo

26、balOPCItcms(4) As OPCAutomation.OPCItemDim GlobalOPCBlocl<Itcms(64) As OPCAutomation.OPCItem妆举OPC服务器列表Private Sub Form l.LoadtBy Vai sender As System.Object, ByVai e As Sy stem. EventAr gs) Ha ndles MyBase.LoadTryGlobalOPCScrvcr = New O PC Automation. OPC S erverClass ()Dim SenerList As Object =

27、GlobalOPCServer.GetOPCSentersFor index As Short = LBound(ScrvcrList) To UBound(SenerList) 入控件列表中,注意这 里使用LBound和UBoundcbbSenerList.Items.Add(ServerList(indcx)NextIf ebb Sender List. Items. Count > 0 ThencbbSerxer List. Select cdlndex = 0End IfResetControlStatusO '设旻控件状态GlobalOPCScrver = Notlii

28、ngCatch Ex As ExceptionMcssagcBox.Show('List OPC servers failed: ” + Ex.Message, 'OPCSample1, MessagcBo xButtons.OK)End TryEnd Sub'连接到指定的OPC服务器Private Sub btnConnectSener_Click(ByVal sender As Systcm.Object, ByVai e As System.Ev entArgs) Handles btnConnectServer.ClickIf cbbServerList.Tcx

29、t <> ,H, ThenConnectedOPCSender = New OPCAutomation.OPCServerClassQTryConncctcdOPCServer.Connect(cbbScrverList.Text)'设置俎隼合的默认属性ConnectcdOPCServer.OPCGroups.DefaultGroupIsActive = TrueConncctcdOPCServer.OPCGroups.DefaultGroupDcadband = 0'添加俎ConncctcdGroup.UpdatcRate = 3 * 1000 刪新虑,用于下面的

30、 DataChange 事件ConncctedGroup.IsSubscribed = True 使用订阅功能'添加项GlobalOPCItems(O) = ConnectedGroup.OPCItems.AddltemCRcaderDevdce.OpenCard”, 0)GlobalOPCItcms(l) = ConnectedGroup.OPCItems.AddItem(uReader_Device.CloscCard 1)GlobalOPCItcms(2) = ConnectedGroup.OPCItems.AddItem("Reader_Dcvice.CardNORe

31、freshServerStatusO 新服务器状态Catch ex As ExceptionConncctcdOPCServer = NothingMessagcBox.ShowfOPC server connect failed : ” + cx.Message, "OPCSample", Mess ageBoxButtons OK)End TryResetControlStatus()End IfEnd Sub'月艮务器断开事件通知Private Sub OnServerShutDown(BjVal Reason As String) Handles Connc

32、ctcdOPCServer.Se rverShutDownbtnDisconnectServer_Click(Nothing, New EventArgsO)End SubPrivate Sub OnGroupDataChange(ByVal TransactionlD As Integer, ByVai Nuniltems As Inte ger, ByRef ClicntHandlcs As System.Army, ByRef ItemValues As System.Array, ByRcf Qualitie s As System.Array, ByRef TiiiieStaiiip

33、s As System.Array) Handles ConnectedGroup.DataChanFor i As Integer = 1 To NumitemsIf Qualities(i) = OPCAutomation.OPCQuality.OPCQualityGood ThenSelect Case ClientHandles(i)Case 2txt CardNo.Text = CStr(ItemValues(i)Case 200 '测试7X卡片txt ValueBlockO .Text = CStr(IteniValues(i)Case 201txt Valu eBlock

34、 1 .Text = CStr(ItemValues(i)Case 202txtValueBlock2 .Text = CStr(IteniValues(i)Case 203txtValueBlocko .Text = CStr(ItemValucs(i)Case 204txtValueBlock4 .Text = CStr(ItemValues(i)Case 205txtValueBlock5 .Text = CStr(ItemValues(i)Case 206txtValueBlock6.Tcxt = C Str (It cmValucs (i)Case 207txt ValueBlock

35、7 .Text = CStr(ItemValues(i)Case ElseEnd SelectEnd IfNextEnd Sub'断开到指定OPC服务器的连接Private Sub btnDisconnectScrvcr_Click(ByVal sender As System.Object, ByVai c As System.EventArgs) Handles btnDisconncctScrvcr. ClickIf Not (ConnectedOPCServer Is Nothing) ThenTryConncctcdOPCServer.Disconnect!)Catch ex

36、 As ExceptionMessageBox.ShowC'OPC server disconnect failed: M + ex.Message, "OPCSample0, MessagcBoxButtons OK)FinallyConncctcdOPCServer = NothingResetControlStatus()End TryEnd IfEnd Sub'开卡,并返回卡号Private Sub btnOpenCard_Click(ByVal sender As System.Object, By Vai e As System. EventA rgs)I

37、f ConnectedGroup IsNot Notliing ThenTry'准备参数数俎Dim ServerHandles(l) As IntegerDim ServerValues(l) As ObjectDini ServerErrors As System.ArrayServerHandles(l) = GlobalOPCItems(O). ServerHandleServerValucs(l) = 1'写入值,用于执行OpenCard的操作ConncctcdGroup.SyncWritcf 1, ScrverHandles, ServerValucs, Server

38、Errors)If ServerErrors( 1) <> 0 ThenMsgBoxC'OpcnCardError: M & ServerErrors(l)End IfServerHandles(l) = GlobalOPCItems(2). ServerHandleDim ServerRcsult As System.Array'读取卡号ConncctcdGroup.SyncRead(OPCAutomation.OPCDataSource.OPCDcvice, 1, ServerHandles, Server Result, ServerErrors)If

39、 ServerErrors( 1) <> 0 ThenMsgBoxf' ReadCardNoError: ” & ServerErrors! 1)ElseEnd IfCatch ex As ExceptionMessageBox.ShowC'OPC server Open Card failed: ” + ex.Message, * OPCSample,» Me ssagcBoxButtons OK)End TryResetControlStatus()End IfEnd Sub'读取卡片指定的块号的值Private Sub btnRead

40、Card_Click(ByVal sender As System.Object, ByVai e As System.EventA rgs)If Not (ConnectedGroup Is Nothing) ThenTry'获取块号Dini BlockNo As Short = CByte(ReadBlockNo.Text)'如果要获取数据的块所对应的项还没有创建,就创建它If GlobalOPCBlockltems(BlockNo) Is Notliing ThenGlobalOPCBlockltems(BlockNo) = ConnectedGroup.OPCItcms

41、.AddltemC'Readcr.Device.BlockM & CStr(BloclcNo), 200 + BlockNo)End If'准备参数数俎Dim ServerRcsults As Systcm.ArrayDim ServerErrors As System.ArrayDim ServerHandles(l) As IntegerServerHandles(l) = GlobalOPCBlocl<Items(BlockNo).ServerHandle'读取值rice, 1, ServerHandles, Server Results, Serv

42、erErrors)If ServerErrors(l) <> 0 ThenMsgBoxfRead Card Failed:* & ServerErrors(l)ElsetxtReadBlocl<N o. Text = SenerRcsults(l)End IfCatch ex As ExceptionMcssageBox.ShowC'OPC server Read Card failed: " + ex.Mcssage, "OPCSamplu”,Me ssageBoxButtons. OK)End TryEnd IfEnd Sub'

43、写卡片指定块的值Private Sub btnWriteCard_Click(ByVal sender As System.Object, ByVai e As System.EventA rgs)II Not (ConnectedGroup Is Nothing) ThenTry'获取块号Dini Blocl<No As Short = CByte(WriteBlocl<No.Text)'如果要写入敖据的块所对应的项还没有创建,就创建它If GlobalOPCBlockltems(BlockNo) Is Notliing ThenGlobalOPCBlocklte

44、ms(BloclcNo) = ConnectedGroup.OPCItems.AddltemC Reader.Device.Block0 & CStr(BloclcNo), 200 + BloclcNo)End If'准备参数数俎Dim ServerValues(l) As ObjectDim ServerErrors As ArrayDini ServerHandles(l) As IntegerServerHandles(l) = GlobalOPCBlocl<Items(Blocl<No).ServerHandleServerValucs(l) = txt W

45、rit eBloclcN o. Text'写入值Connect cdGroup. Sync Writ e( 1, ScrvcrHandles, ServerValues, ServerErrors)If ServerErrors(l) <> 0 ThenMsgBoxC'Writc Card Failed:" & ServerErrors(1)ElseMsgBox(HWritc Card Succeed*)End IfCatch ex As ExceptionMessagcBox.ShowC OPC server Write Card failed:

46、 ” + ex.Message, * OPCSample, Me ssagcBoxButtons OK)End TryEnd IfEnd Sub重设控件状态Private Sub RcsctControlStatusOII ConnectcdOPC Sender Is Nothing ThenbtnConnectScrver. Enabled = TruebtnDisconnectServer. Enabled = FalsebtnReadCard.Enabled = False btnWriteCard. Enabled = False bt nOp enC ard. Enabled = F

47、alse btnCloseCard.Enabled = False ReadBloclcNo. Value = 0 WriteBlockNo.Value = 0 txtRcadBlockNo.Text = ” txtWriteBloclcNo.Text = ”0000“ txtCardNo.Text ="txtSrvStartTime.Text = ,M,txtSrvCurrTinie.Text = ,Htxt SrvGroupCount. T ext = ”txt SrvrGroupD eadBand. T ext ="txtSrvrGroupDefActive.T ext = ,M,txt SrrGroupLocalID. T ext ="txt SrvrGroupTimcBias. T ext = ”txt

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论