[信息与通信]手把手教您用VB编一个OPC客户端程序

上传人:仙*** 文档编号:43947267 上传时间:2021-12-05 格式:PPT 页数:31 大小:209KB
收藏 版权申诉 举报 下载
[信息与通信]手把手教您用VB编一个OPC客户端程序_第1页
第1页 / 共31页
[信息与通信]手把手教您用VB编一个OPC客户端程序_第2页
第2页 / 共31页
[信息与通信]手把手教您用VB编一个OPC客户端程序_第3页
第3页 / 共31页
资源描述:

《[信息与通信]手把手教您用VB编一个OPC客户端程序》由会员分享,可在线阅读,更多相关《[信息与通信]手把手教您用VB编一个OPC客户端程序(31页珍藏版)》请在装配图网上搜索。

1、Using Visual Basic As An OPC ClientJohn WeberPresident & FounderSoftware Toolbox, Iwebsite: http:/Your OPC ServerCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.Presentation Updated 3/2001Copyright Software

2、 Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCAgenda OPC - Review of the Basics OPC - Terminology OPC & VB 101 - Automation Wrapper & Object Model Building Your VB Client - Read data - 7 easy steps with code from star

3、t to finish Housekeeping Handles Handles Everywhere - how the server and client correlate the data each is managing in your program Writing Data Future ideas to consider New developments since original presentation in 10/99 Resources for future learningCopyright Software Toolbox, 1999,2000,2001 All

4、Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCOPC - Review of the Basics OPC is based on the Microsoft Component Object Model (COM) OPC stands for OLE for Process Control OPC is managed by the independent OPC Foundation (www.opcfoundation.org) Th

5、ere are over 200 member companies supporting the OPC specification OPC defines a standard method for connecting automation application softwareCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCOPC and VB

6、 101 - Terminology OPC Server - a piece of software supporting the OPC specification - an OPC Data Access Server is a driver that handles connectivity to PLCs or other automation hardware OPC Item - A single tag or data point managed by the OPC server - i.e. one data point in a PLC OPC Group - a use

7、r defined grouping of OPC items. Created by the OPC client as a way of organizing data items around logical process areas or equipment. Collection - a grouping of objects of the same data type - for example, each OPC server has an OPC items collection containing one software object for each OPC item

8、. Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCOPC and VB 101 Visual Basic supports COM COM implementations from Visual Basic use what is called an “Automation” interface The OPC Foundation supplies

9、 the source code to an “Automation Wrapper” DLL - most OPC vendors provide a compiled version Automation Wrapper connects VB to OPCCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCOPC and VB 101 Automat

10、ion Wrapper DLL lets VB access OPC Servers and their underlying Groups and ItemsOPC Server ObjectOPC Groups CollectionOPC Group ObjectsOPC Items CollectionOPC Items ObjectsOPC Browse ObjectObject model for the Automation Wrapper - the wrapper lets the VB user connect to an OPC server using standard

11、Object.property and Object.method syntaxesCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCOPC and VB 101OPC Server ObjectOPC Groups CollectionOPC Group ObjectsOPC Items CollectionOPC Items ObjectsOPC B

12、rowse ObjectOPC Server ObjectOPC Groups CollectionOPC Group ObjectsOPC Items CollectionOPC Items ObjectsYour VB Program with the Automation Wrapper object included in itYour OPC Server and its object modelCOM/DCOMThe Automation Wrapper connects to the OPC server and creates the groups and items in t

13、he server and givesyou references to them in yourVB program in an Objectmodel that mirrors that of theserverCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCOPC & VB - Making The ConnectionsConnect to t

14、he OPC ServerAdd Group(s)Add Item(s) to Group(s)Activate Groups & ItemsData Change Events FireDe-Activate Groups & ItemsRemove Item(s) from Group(s)Remove Group(s)Disconnect from the OPC ServerUser Program Handles Data - Log, Display, Graph, etcOptional - your program can add/remove items and groups

15、 and activate/deactive items at runtime based on user defined conditionsCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCTools Youll Need To Build Your Application If you want to build an OPC client in

16、VB and test it, youll need the following tools: Visual Basic 5 or 6 running on Windows 95, 98, or NT any VB edition will do the job An OPC Server The OPC Automation Wrapper You can get the last two items including a sample test OPC server at (see last slide for exact link). There is no charge for th

17、e Automation Wrapper and sample OPC demonstration servers are free also. Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 1 Install the OPC Automation Wrapper DLL on your

18、PC Start a new VB project In VB, click on Project - References on the VB menu bar The OPC Automation Wrapper appears on the dialog as “OPC Automation 2.0” - select it as shown here. Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark o

19、f Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 2 First you need to declare some variables in the VB code window in the General Declarations area as shown hereOption ExplicitOption Base 1 Makes all arrays start with an index of 1Dim WithEvents AnOPCServer As OPCServerDim WithEvents Conne

20、ctedOPCServer As OPCServerDim ConnectedServerGroup As OPCGroupsDim WithEvents ConnectedGroup As OPCGroupDim OPCItemCollection As OPCItemsDim ItemCount As LongDim OPCItemIDs(10) As StringDim ItemServerHandles() As LongDim ItemServerErrors() As LongDim ClientHandles(10) As LongThese lines create objec

21、ts you will use to manage your OPC server connection and a group - you could add more than one group if you wanted to These lines create objects you will use to manage your OPC Items - we are setting up our sample to read 10 items - you setup as many as you needCopyright Software Toolbox, 1999,2000,

22、2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 3 If you want your VB project to connect to your server at startup, use the name of your server (ask your server vendor) and enter the following code in the For

23、m Load subroutine for your project - our server name is “KepServer”Dim ConnectedServerName As StringCreate a new OPC Server objectSet ConnectedOPCServer = New OPCServerLoad the selected server name to start the interfaceConnectedServerName = “Developer - Enter Your OPC Server Name Here in quotes”Att

24、empt to connect with the server (Local only in this example)ConnectedOPCServer.Connect (ConnectedServerName)Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 4Next, youll g

25、o ahead and add a group right after you get your connection to the OPC server. Enter this code right after your code for connecting to the server in the Form Load subroutine of your projectPrepare to add a group to the current OPC Server Get the group interface from the server objectSet ConnectedSer

26、verGroup = ConnectedOPCServer.OPCGroups Set the desire active state for the groupConnectedServerGroup.DefaultGroupIsActive = TrueSet the desired percent deadband - enter an integer from 0 to 100 for the deadbandConnectedServerGroup.DefaultGroupDeadband = 0 Add the group and set its update rate - ent

27、er whatever group name you want in place of “DataGroup1”Set ConnectedGroup = ConnectedServerGroup.Add(“DataGroup1”) Set the update rate for the group - enter an long integer value representing the millisecond group update rateConnectedGroup.UpdateRate = 500 The following line is crucial - without it

28、 you wont be subscribed to the server and DataChange events will not fire! ConnectedGroup.IsSubscribed = True Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 5Next youll

29、go ahead and add some items. This code follows right after the group add code in the Form Load subroutineFor the item names, enter valid item names for your OPC server. Refer to your OPC servers documentation for valid item naming conventions. We are going to be reading some data from a GE PLC here

30、so we will use their memory conventions. The OPC server we are using uses the syntax “itemnameupdaterate” ItemCount = 4Dim i As IntegerFor i = 0 To 3 This line builds a string like “GE9030.R110” - a valid item name for the OPC server we are using OPCItemIDs(i + 1) = “GE9030.R” & (I + 1) & “10” Clien

31、tHandles(i + 1) = I Sets a reference pointer number for this point OPCItemActiveState(i).Value = 1 Tells the server we want this item to be activeNext ISet OPCItemCollection = ConnectedGroup.OPCItems Gets an items collection from the current GroupOPCItemCollection.DefaultIsActive = TrueSets the item

32、s collection to activeThis line adds the items weve chosen to the items collection and in turn to the group in the OPC ServerOPCItemCollection.AddItems ItemCount, OPCItemIDs, ClientHandles, ItemServerHandles, ItemServerErrorsCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. S

33、oftware Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 6 Now, assuming you have all valid item names and your OPC server is ready to go, all you need to do is add code to react to the DataChange events that your OPC server will fire back to the Automat

34、ion DLL, which in turn will fire an event in VB for you In your program, you created an object variable called “ConnectedGroup” in step 2 - this object will fire an event called “DataChange” for anytime one of the items in your group has new data for you The DataChange event tells you how many items

35、 changed, gives you back the client handles so you know which ones changed, and the data, quality, and timestamp informationCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Ste

36、p 6 Go ahead and build the objects on your form to display your data. For our form, we built one with 3 arrays of text boxes - one each for the data, quality, and timestamp information. We named them txtData, txtQuality, txtTimeStamp respectively. Copyright Software Toolbox, 1999,2000,2001 All Right

37、s Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 6 Dim i As Integer For i = 1 To NumItems txtData(ClientHandles(i).Text = ItemValues(i) If Qualities(i) And &HC0 Then txtQuality(ClientHandles(i).Text = Quality Good Else txtQ

38、uality(ClientHandles(i).Text = Quality Bad End If txtTimeStamp(ClientHandles(i).Text = TimeStamps(i) Next i Now in the VB Code window, use the combo boxes at the top to go to the ConnectedGroup objects DataChange event subroutine - enter this code to update your text boxes. Note this code assumes yo

39、u have named your text boxes as we have in our example and built an array of text boxes as we have in our form. If you named your text boxes differently, then you will need to adjust this code accordingly. The variables ItemValues, Qualities, ClientHandles, and TimeStamps are all variables passed to

40、 you by the Automation Wrapper DLL and your Connected Group object when the DataChange event firesThe Qualities data array can contain a variety of very hardware specific data about why communications failed - a value of Hex C0 is returned when everything is OKTimestamps are returned in GMT or Unive

41、rsal TimeCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCBuilding Your VB Client - Step 7 Now if you have not done so, save your project and form in VB Run your project. If you have specified a valid O

42、PC server and Item names and your OPC server is running and ready, then when you run your project, it should immediately start updating the text boxes on your formCopyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox,

43、 Inc.VBOPCIf things arent working . . . If you do not have communications, check the following Do you have the OPC server name specified correctly in the form load routine ? Check with your OPC server vendor for the right name to use Are you using valid item naming syntaxes for your pariticular OPC

44、server? Do you have the cabling and hardware setup right between your OPC server and your hardware?Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCHousekeepingThis program was a very basic one - in rea

45、lity you need to add at least one more section of code in order to make sure you clean up your connections to the OPC server before you exit your program. Otherwise the OPC server will still think you are connected and hold open memory to service you that it could otherwise release. Enter the code o

46、n the following slide in the Click ( ) event on the “Disconnect and Exit” command button you put on your formThis code makes sure you remove the item, items collection, group, and groups collections from the server then disconnect from the server upon exit. Good memory management dictates that you “

47、undo”everything that you “do”Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCHousekeeping - Exit & Cleanup Code= First Remove All of Our Items = ItemCount = 1 Provide an array to contain the ItemServer

48、Handles of the item we intend to remove Dim RemoveItemServerHandles(10) As Long Dim RemoveItemServerErrors() As Long Get the Servers handle for the desired items. The server handles were returned in add item subroutine. In this case we need to get only the handles for item that are valid. Dim i As I

49、nteger For i = 1 To 3 We have 3 data points we are reading In this example if the ItemServerHandle is non zero it is valid If ItemServerHandles(i) 0 Then RemoveItemServerHandles(ItemCount) = ItemServerHandles(i) ItemCount = ItemCount + 1 End If Next i Item count is 1 greater than it needs to be at t

50、his point ItemCount = ItemCount - 1 Invoke the Remove Item operation. Remember this call will wait until completion OPCItemCollection.Remove ItemCount, RemoveItemServerHandles, RemoveItemServerErrors Clear the ItemServerHandles and turn off the controls for interacting with the OPC items on the form

51、. For i = 0 To 2 ItemServerHandles(i + 1) = 0 Mark the handle as empty Next i Set OPCItemCollection = Nothing = Now remove the group = Remove the group from the server ConnectedServerGroup.Remove (Groupname) Release the group interface and allow the server to cleanup the resources used Set Connected

52、ServerGroup = Nothing Set ConnectedGroup = Nothing = Now Disconnect from the OPC Server = ConnectedOPCServer.Disconnect Release the old instance of the OPC Server object and allow the resources to be freed Set ConnectedOPCServer = Nothing = Now exit the program = EndCopyright Software Toolbox, 1999,

53、2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCHandles Handles EverywhereIn the preceding program, you probably saw that we used the ClientHandles and ItemServerHandles variables a lot. Just what are these “handles”A handle is an ide

54、ntifier assigned in software to point to a memory location or data point. When you connect to an OPC Server and create items, the OPC Server assigns a handle for each item - a large number.Likewise, when your OPC client connects to the server, it needs to have a handle to uniquely identify each item

55、.Handles as numbers are much easier for code to deal with quickly and efficiently behind the scenes than long names.Refer to Step 5 - when you added items, you set your handles for the client side in the array variable ClientHandles ( )When you invoked the .AddItems method, you passed the server you

56、r list of ClientHandles( ) - the OPC server returns a list of the corresponding handles it assigns in the array variable ItemServerHandles( )You use the ItemServerHandles() to tell the server which item you are interested in for future synchronous read and write operations on a single item. Copyrigh

57、t Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCHandles Handles EverywhereThe following picture should help you understand what handles look like inside the program. The numbers used here are actual numbers th

58、at were assigned in running the program created by this tutorial. Your ItemServerHandles will be different as each server on each PC assigns handles differently to assure uniqueness. Array IndexClientHandles( ) ItemServerHandles( ) 1234012338145856381459683814608038146192Assigned by the OPC Server a

59、nd passed back to your program by the Automation Wrapper DLL when the AddItems method completes and returnsAssigned by your program and passed to the OPC Server when you call the .AddItems method. Should be numbers that are useful to you in your code in working with and manipulating the dataCopyrigh

60、t Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCWriting a Value - Step 1Of course now that you are reading data, you want to write some data. Add a text boxes and an array of command buttons to your form as sh

61、own below. Name your text boxe txtValueToWrite and the command button array cmdWriteValue. For simplicity, we will stick to just writing items that you already subscribed to when we loaded the form.Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a regist

62、ered trademark of Software Toolbox, Inc.VBOPCWriting a Value - Step 2When you click on the write command buttons, the event handler in VB hands you an index from 0 to 3 which matches up to the items that we added when the form loaded. The following code performs an OPC Synchronous Write to the chose

63、n item - place this code in the cmdWriteClick event in your VB program Write only 1 item this time ItemCount = 1 Create some local scope variables to hold the value to be sent. These arrays could just as easily contain all of the item we have added. Dim SyncItemValues(1) As Variant Dim SyncItemServe

64、rHandles(1) As Long Dim SyncItemServerErrors() As Long Get the Servers handle for the desired item. The server handles were returned when we loaded the form. We use the index of the command button clicked to tell us which item to change SyncItemServerHandles(1) = ItemServerHandles(Index + 1) Load th

65、e value to be written from our text box SyncItemValues(1) = Val(txtValueToWrite.Text) Invoke the SyncWrite operation. Remember this call will wait until completion ConnectedGroup.SyncWrite ItemCount, SyncItemServerHandles, SyncItemValues, SyncItemServerErrorsCopyright Software Toolbox, 1999,2000,200

66、1 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.VBOPCWriting a Value - Step 3 Run your program. Assuming of course that your PLC or device will let you write the points you are reading, you should now be able to enter a value in the text box and write a data point and see it change in the display where you were reading data. Words of wisdom on writing You cant write to an item that you havent added to the items collection. You dont have to be

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

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!