版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 美容院员工合同
- 2026航空生活方式课件
- 2026未来健康趋势课件
- 业务透明合规管理责任保证承诺书8篇
- 生态农产品生产保证承诺书(4篇)
- 跨境电商极速达承诺函(3篇)
- 确定合作开发智能客服系统函8篇范文
- 食堂阿姨工作制度及流程
- 餐饮业朝九晚九工作制度
- 高中学校晨午检工作制度
- 南通市医疗机构主要运行指标定期公布工作实施方案
- 四川三江招商集团有限公司2026年3月公开招聘工作人员考试参考试题及答案解析
- 【励志教育】主题班会:《张雪机车夺冠》从山村少年到世界冠军的缔造者【课件】
- 2026重庆酉阳自治县城区学校选聘教职工91人笔试模拟试题及答案解析
- 2026湖北松滋金松投资控股集团有限公司招聘28人笔试备考试题及答案解析
- 2026江苏无锡惠高新运产业招商发展有限公司招聘6人笔试备考题库及答案解析
- T∕CEA 3030-2026 乘运质量等级 第2部分:自动扶梯和 自动人行道
- 医院清明假期安全课件
- 2026年国海证券行测笔试题库
- 湖北省武汉市2026高三下学期3月调研考试化学试题 含答案
- (新教材)2026年部编人教版三年级下册语文 语文园地三 课件
评论
0/150
提交评论