信息与通信手把手教您用VB编一个OPC客户端程序课件_第1页
信息与通信手把手教您用VB编一个OPC客户端程序课件_第2页
信息与通信手把手教您用VB编一个OPC客户端程序课件_第3页
信息与通信手把手教您用VB编一个OPC客户端程序课件_第4页
信息与通信手把手教您用VB编一个OPC客户端程序课件_第5页
已阅读5页,还剩26页未读 继续免费阅读

下载本文档

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

文档简介

UsingVisualBasicAs

AnOPCClientJohnWeberPresident&FounderSoftwareToolbox,Inc.jweber@

website:YourOPCServerCopyrightSoftwareToolbox,1999,2000,2001AllRightsReservedWorldwide.SoftwareToolboxisaregisteredtrademarkofSoftwareToolbox,Inc.PresentationUpdated3/2001UsingVisualBasicAs

AnOPC1AgendaOPC-ReviewoftheBasicsOPC-TerminologyOPC&VB101-AutomationWrapper&ObjectModelBuildingYourVBClient-Readdata-7easystepswithcodefromstarttofinishHousekeepingHandlesHandlesEverywhere-howtheserverandclientcorrelatethedataeachismanaginginyourprogramWritingDataFutureideastoconsiderNewdevelopmentssinceoriginalpresentationin10/99ResourcesforfuturelearningAgendaOPC-ReviewoftheBasi2OPC-ReviewoftheBasicsOPCisbasedontheMicrosoftComponentObjectModel(COM)OPCstandsforOLEforProcessControlOPCismanagedbytheindependentOPCFoundation()Thereareover200membercompaniessupportingtheOPCspecificationOPCdefinesastandardmethodforconnectingautomationapplicationsoftwareOPC-ReviewoftheBasicsOPC3OPCandVB101-TerminologyOPCServer-apieceofsoftwaresupportingtheOPCspecification-anOPCDataAccessServerisadriverthathandlesconnectivitytoPLCsorotherautomationhardwareOPCItem-AsingletagordatapointmanagedbytheOPCserver-i.e.onedatapointinaPLCOPCGroup-auserdefinedgroupingofOPCitems.CreatedbytheOPCclientasawayoforganizingdataitemsaroundlogicalprocessareasorequipment.Collection-agroupingofobjectsofthesamedatatype-forexample,eachOPCserverhasanOPCitemscollectioncontainingonesoftwareobjectforeachOPCitem.

OPCandVB101-TerminologyOP4OPCandVB101VisualBasicsupportsCOMCOMimplementationsfromVisualBasicusewhatiscalledan“Automation”interfaceTheOPCFoundationsuppliesthesourcecodetoan“AutomationWrapper”DLL-mostOPCvendorsprovideacompiledversionAutomationWrapperconnectsVBtoOPCOPCandVB101VisualBasicsup5OPCandVB101AutomationWrapperDLLletsVBaccessOPCServersandtheirunderlyingGroupsandItemsOPCServerObjectOPCGroupsCollectionOPCGroupObjectsOPCItemsCollectionOPCItemsObjectsOPCBrowseObjectObjectmodelfortheAutomationWrapper-thewrapperletstheVBuserconnecttoanOPCserverusingstandardOpertyandObject.methodsyntaxesOPCandVB101AutomationWrapp6OPCandVB101OPCServerObjectOPCGroupsCollectionOPCGroupObjectsOPCItemsCollectionOPCItemsObjectsOPCBrowseObjectOPCServerObjectOPCGroupsCollectionOPCGroupObjectsOPCItemsCollectionOPCItemsObjectsYourVBProgramwiththeAutomationWrapperobjectincludedinitYourOPCServerandit’sobjectmodelCOM/DCOMTheAutomationWrapperconnectstotheOPCserver

andcreatesthegroupsand

itemsintheserverandgives

youreferencestotheminyour

VBprograminanObject

modelthatmirrorsthatofthe

serverOPCandVB101OPCServerObjec7OPC&VB-MakingTheConnectionsConnecttothe

OPCServerAddGroup(s)AddItem(s)

toGroup(s)Activate

Groups&ItemsDataChange

EventsFireDe-Activate

Groups&ItemsRemoveItem(s)

fromGroup(s)RemoveGroup(s)Disconnectfrom

theOPCServerUserProgramHandlesData-

Log,Display,Graph,etcOptional-yourprogramcanadd/removeitemsandgroupsandactivate/deactiveitemsatruntimebasedonuserdefinedconditionsOPC&VB-MakingTheConnecti8ToolsYou’llNeedToBuildYourApplicationIfyouwanttobuildanOPCclientinVBandtestit,you’llneedthefollowingtools:VisualBasic5or6runningonWindows95,98,orNTanyVBeditionwilldothejobAnOPCServerTheOPCAutomationWrapperYoucangetthelasttwoitemsincludingasampletestOPCserverat(seelastslideforexactlink).ThereisnochargefortheAutomationWrapperandsampleOPCdemonstrationserversarefreealso.ToolsYou’llNeedToBuildYou9BuildingYourVBClient-Step1InstalltheOPCAutomationWrapperDLLonyourPCStartanewVBprojectInVB,clickonProject-->ReferencesontheVBmenubarTheOPCAutomationWrapperappearsonthedialogas“OPCAutomation2.0”-selectitasshownhere.

BuildingYourVBClient-Step10BuildingYourVBClient-Step2FirstyouneedtodeclaresomevariablesintheVBcodewindowintheGeneralDeclarationsareaasshownhereOptionExplicitOptionBase1‘Makesallarraysstartwithanindexof1DimWithEventsAnOPCServerAsOPCServerDimWithEventsConnectedOPCServerAsOPCServerDimConnectedServerGroupAsOPCGroupsDimWithEventsConnectedGroupAsOPCGroupDimOPCItemCollectionAsOPCItemsDimItemCountAsLongDimOPCItemIDs(10)AsStringDimItemServerHandles()AsLongDimItemServerErrors()AsLongDimClientHandles(10)AsLongTheselinescreateobjectsyouwillusetomanageyourOPCserverconnectionandagroup-youcouldaddmorethanonegroupifyouwantedtoTheselinescreateobjectsyouwillusetomanageyourOPCItems-wearesettingupoursampletoread10items-yousetupasmanyasyouneedBuildingYourVBClient-Step11BuildingYourVBClient-Step3IfyouwantyourVBprojecttoconnecttoyourserveratstartup,usethenameofyourserver(askyourservervendor)andenterthefollowingcodeintheFormLoadsubroutineforyourproject-ourservernameis“KepServer”DimConnectedServerNameAsString'CreateanewOPCServerobjectSetConnectedOPCServer=NewOPCServer'LoadtheselectedservernametostarttheinterfaceConnectedServerName=“Developer-EnterYourOPCServerNameHereinquotes”'Attempttoconnectwiththeserver(Localonlyinthisexample)ConnectedOPCServer.Connect(ConnectedServerName)BuildingYourVBClient-Step12BuildingYourVBClient-Step4Next,you’llgoaheadandaddagrouprightafteryougetyourconnectiontotheOPCserver.EnterthiscoderightafteryourcodeforconnectingtotheserverintheFormLoadsubroutineofyourproject'PreparetoaddagrouptothecurrentOPCServer'GetthegroupinterfacefromtheserverobjectSetConnectedServerGroup=ConnectedOPCServer.OPCGroups'SetthedesireactivestateforthegroupConnectedServerGroup.DefaultGroupIsActive=True'Setthedesiredpercentdeadband-enteranintegerfrom0to100forthedeadbandConnectedServerGroup.DefaultGroupDeadband=0'Addthegroupandsetitsupdaterate-enterwhatevergroupnameyouwantinplaceof“DataGroup1”SetConnectedGroup=ConnectedServerGroup.Add(“DataGroup1”)'Settheupdaterateforthegroup-enteranlongintegervaluerepresentingthemillisecondgroupupdaterateConnectedGroup.UpdateRate=500‘Thefollowinglineiscrucial--withoutityouwon’tbesubscribedtotheserverandDataChangeeventswillnotfire!

ConnectedGroup.IsSubscribed=TrueBuildingYourVBClient-Step13BuildingYourVBClient-Step5Nextyou’llgoaheadandaddsomeitems.ThiscodefollowsrightafterthegroupaddcodeintheFormLoadsubroutineFortheitemnames,entervaliditemnamesforyourOPCserver.RefertoyourOPCserver’sdocumentationforvaliditemnamingconventions.WearegoingtobereadingsomedatafromaGEPLCheresowewillusetheirmemoryconventions.TheOPCserverweareusingusesthesyntax“itemname@updaterate”ItemCount=4DimiAsIntegerFori=0To3

‘Thislinebuildsastringlike“GE9030.R1@10”-avaliditemnamefortheOPCserverweareusingOPCItemIDs(i+1)=“GE9030.R”&(I+1)&“@10”ClientHandles(i+1)=I ‘SetsareferencepointernumberforthispointOPCItemActiveState(i).Value=1 ‘TellstheserverwewantthisitemtobeactiveNextI

SetOPCItemCollection=ConnectedGroup.OPCItems ‘GetsanitemscollectionfromthecurrentGroupOPCItemCollection.DefaultIsActive=True ‘Setstheitemscollectiontoactive‘Thislineaddstheitemswe’vechosentotheitemscollectionandinturntothegroupintheOPCServerOPCItemCollection.AddItemsItemCount,OPCItemIDs,ClientHandles,ItemServerHandles,ItemServerErrorsBuildingYourVBClient-Step14BuildingYourVBClient-Step6Now,assumingyouhaveallvaliditemnamesandyourOPCserverisreadytogo,allyouneedtodoisaddcodetoreacttotheDataChangeeventsthatyourOPCserverwillfirebacktotheAutomationDLL,whichinturnwillfireaneventinVBforyouInyourprogram,youcreatedanobjectvariablecalled“ConnectedGroup”instep2--thisobjectwillfireaneventcalled“DataChange”foranytimeoneoftheitemsinyourgrouphasnewdataforyouTheDataChangeeventtellsyouhowmanyitemschanged,givesyoubacktheclienthandlessoyouknowwhichoneschanged,andthedata,quality,andtimestampinformationBuildingYourVBClient-Step15BuildingYourVBClient-Step6Goaheadandbuildtheobjectsonyourformtodisplayyourdata.Forourform,webuiltonewith3arraysoftextboxes--oneeachforthedata,quality,andtimestampinformation.WenamedthemtxtData,txtQuality,txtTimeStamprespectively.BuildingYourVBClient-Step16BuildingYourVBClient-Step6DimiAsIntegerFori=1ToNumItemstxtData(ClientHandles(i)).Text=ItemValues(i)IfQualities(i)And&HC0ThentxtQuality(ClientHandles(i)).Text="QualityGood"ElsetxtQuality(ClientHandles(i)).Text="QualityBad"EndIftxtTimeStamp(ClientHandles(i)).Text=TimeStamps(i)NextiNowintheVBCodewindow,usethecomboboxesatthetoptogototheConnectedGroupobject’sDataChangeeventsubroutine--enterthiscodetoupdateyourtextboxes.Notethiscodeassumesyouhavenamedyourtextboxesaswehaveinourexampleandbuiltanarrayoftextboxesaswehaveinourform.Ifyounamedyourtextboxesdifferently,thenyouwillneedtoadjustthiscodeaccordingly.ThevariablesItemValues,Qualities,ClientHandles,andTimeStampsareallvariablespassedtoyoubytheAutomationWrapperDLLandyourConnectedGroupobjectwhentheDataChangeeventfiresTheQualitiesdataarraycancontainavarietyofveryhardwarespecificdataaboutwhycommunicationsfailed-avalueofHexC0isreturnedwheneverythingisOKTimestampsarereturnedinGMTorUniversalTimeBuildingYourVBClient-Step17BuildingYourVBClient-Step7Nowifyouhavenotdoneso,saveyourprojectandforminVBRunyourproject.IfyouhavespecifiedavalidOPCserverandItemnamesandyourOPCserverisrunningandready,thenwhenyourunyourproject,itshouldimmediatelystartupdatingthetextboxesonyourformBuildingYourVBClient-Step18Ifthingsaren’tworking...Ifyoudonothavecommunications,checkthefollowingDoyouhavetheOPCservernamespecifiedcorrectlyintheformloadroutine?CheckwithyourOPCservervendorfortherightnametouseAreyouusingvaliditemnamingsyntaxesforyourpariticularOPCserver?DoyouhavethecablingandhardwaresetuprightbetweenyourOPCserverandyourhardware?Ifthingsaren’tworking...19HousekeepingThisprogramwasaverybasicone--inrealityyouneedtoaddatleastonemoresectionofcodeinordertomakesureyoucleanupyourconnectionstotheOPCserverbeforeyouexityourprogram.OtherwisetheOPCserverwillstillthinkyouareconnectedandholdopenmemorytoserviceyouthatitcouldotherwiserelease.EnterthecodeonthefollowingslideintheClick()eventonthe“DisconnectandExit”commandbuttonyouputonyourformThiscodemakessureyouremovetheitem,itemscollection,group,andgroupscollectionsfromtheserverthendisconnectfromtheserveruponexit.Goodmemorymanagementdictatesthatyou“undo”everythingthatyou“do”HousekeepingThisprogramwasa20Housekeeping-Exit&CleanupCode'==========FirstRemoveAllofOurItems============='ItemCount=1'ProvideanarraytocontaintheItemServerHandlesoftheitem'weintendtoremoveDimRemoveItemServerHandles(10)AsLongDimRemoveItemServerErrors()AsLong'GettheServershandleforthedesireditems.Theserverhandles'werereturnedinadditemsubroutine.Inthiscaseweneedtoget'onlythehandlesforitemthatarevalid.DimiAsIntegerFori=1To3'Wehave3datapointswearereading'InthisexampleiftheItemServerHandleisnonzeroitisvalidIfItemServerHandles(i)<>0ThenRemoveItemServerHandles(ItemCount)=ItemServerHandles(i)ItemCount=ItemCount+1EndIfNexti'Itemcountis1greaterthanitneedstobeatthispointItemCount=ItemCount-1'InvoketheRemoveItemoperation.Rememberthiscallwill'waituntilcompletionOPCItemCollection.RemoveItemCount,RemoveItemServerHandles,RemoveItemServerErrors'CleartheItemServerHandlesandturnoffthecontrolsforinteracting'withtheOPCitemsontheform.Fori=0To2ItemServerHandles(i+1)=0'MarkthehandleasemptyNextiSetOPCItemCollection=Nothing

'=======Nowremovethegroup==========='RemovethegroupfromtheserverConnectedServerGroup.Remove(Groupname)'ReleasethegroupinterfaceandallowtheservertocleanuptheresourcesusedSetConnectedServerGroup=NothingSetConnectedGroup=Nothing

'=======NowDisconnectfromtheOPCServer===========ConnectedOPCServer.Disconnect'ReleasetheoldinstanceoftheOPCServerobjectandallowtheresources'tobefreedSetConnectedOPCServer=Nothing

'======Nowexittheprogram=============EndHousekeeping-Exit&Cleanup21HandlesHandlesEverywhereIntheprecedingprogram,youprobablysawthatweusedtheClientHandlesandItemServerHandlesvariablesalot.Justwhatarethese“handles”Ahandleisanidentifierassignedinsoftwaretopointtoamemorylocationordatapoint.WhenyouconnecttoanOPCServerandcreateitems,theOPCServerassignsahandleforeachitem-alargenumber.Likewise,whenyourOPCclientconnectstotheserver,itneedstohaveahandletouniquelyidentifyeachitem.Handlesasnumbersaremucheasierforcodetodealwithquicklyandefficientlybehindthescenesthanlongnames.RefertoStep5--whenyouaddeditems,yousetyourhandlesfortheclientsideinthearrayvariableClientHandles()Whenyouinvokedthe.AddItemsmethod,youpassedtheserveryourlistofClientHandles()--theOPCserverreturnsalistofthecorrespondinghandlesitassignsinthearrayvariableItemServerHandles()YouusetheItemServerHandles()totelltheserverwhichitemyouareinterestedinforfuturesynchronousreadandwriteoperationsonasingleitem.HandlesHandlesEverywhereInt22HandlesHandlesEverywhereThefollowingpictureshouldhelpyouunderstandwhathandleslooklikeinsidetheprogram.Thenumbersusedhereareactualnumbersthatwereassignedinrunningtheprogramcreatedbythistutorial.YourItemServerHandleswillbedifferentaseachserveroneachPCassignshandlesdifferentlytoassureuniqueness.ArrayIndexClientHandles()ItemServerHandles()1234012338145856381459683814608038146192AssignedbytheOPCServerandpassedbacktoyourprogrambytheAutomationWrapperDLLwhentheAddItemsmethodcompletesandreturnsAssignedbyyourprogramandpassedtotheOPCServerwhenyoucallthe.AddItemsmethod.ShouldbenumbersthatareusefultoyouinyourcodeinworkingwithandmanipulatingthedataHandlesHandlesEverywhereThe23WritingaValue-Step1Ofcoursenowthatyouarereadingdata,youwanttowritesomedata.Addatextboxesandanarrayofcommandbuttonstoyourformasshownbelow.NameyourtextboxetxtValueToWriteandthecommandbuttonarraycmdWriteValue.Forsimplicity,wewillsticktojustwritingitemsthatyoualreadysubscribedtowhenweloadedtheform.WritingaValue-Step1Ofcou24WritingaValue-Step2Whenyouclickonthewritecommandbuttons,theeventhandlerinVBhandsyouanindexfrom0to3whichmatchesuptotheitemsthatweaddedwhentheformloaded.ThefollowingcodeperformsanOPCSynchronousWritetothechosenitem-placethiscodeinthecmdWriteClickeventinyourVBprogram'Writeonly1itemthistimeItemCount=1'Createsomelocalscopevariablestoholdthevaluetobesent.'Thesearrayscouldjustaseasilycontainalloftheitemwehaveadded.DimSyncItemValues(1)AsVariantDimSyncItemServerHandles(1)AsLongDimSyncItemServerErrors()AsLong

'GettheServershandleforthedesireditem.Theserverhandles'werereturnedwhenweloadedtheform.WeusetheindexofthecommandbuttonclickedtotelluswhichitemtochangeSyncItemServerHandles(1)=ItemServerHandles(Index+1)

'LoadthevaluetobewrittenfromourtextboxSyncItemValues(1)=Val(txtValueToWrite.Text)

'InvoketheSyncWriteoperation.RememberthiscallwillwaituntilcompletionConnectedGroup.SyncWriteItemCount,SyncItemServerHandles,SyncItemValues,SyncItemServerErrorsWritingaValue-Step2Wheny25WritingaValue-Step3Runyourprogram.AssumingofcoursethatyourPLCordevicewillletyouwritethepointsyouarereading,youshouldnowbeabletoenteravalueinthetextboxandwriteadatapointandseeitchangeinthedisplaywhereyouwerereadingdata.WordsofwisdomonwritingYoucan’twritetoanitemthatyouhaven’taddedtotheitemscollection.Youdon’thavetobereadinganiteminordertowriteit--butitmustbealreadyaddedtothecurrentgroupbyyourclient

温馨提示

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

评论

0/150

提交评论