版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2027年陕西省道德与法治中考考前一周加分卷(含答案)
- 稳扎稳打 2026-2027学年第一学期八年级语文部编版第四单元单元测试卷(含答案)
- 快速提分 2026-2027学年第一学期九年级英语人教版第二阶段阶段检测卷(含答案)
- 快速提分 2026-2027学年第一学期初一语文部编版第二单元单元归类复习卷(含答案)
- 超越自我 2026-2027学年第一学期初一道德与法治部编版上学期期末测试卷(含答案)
- 精准押题 2027年中考湖南省英语中考人教版考前冲刺押题卷(含答案)
- 靶向训练 2027年中考山东省语文九年级考前提分模拟卷(含答案)
- 幽门螺杆菌双联方案共识2026
- 四川事业编财会岗 2026 易错题试卷
- 2026 事业编计算机岗面试真题汇编 含答案
- 2026年高邮市消防系统事业单位公开招聘工作人员3人笔试备考题库及答案解析
- 2026年高校辅导员经典面试题(含答案)
- 《勤洗生活衣物》教学设计-2026-2027学年滇教版初中劳动技术七年级上册
- 2026年度湖北省部分工程高、中级职称水平能力测试(轻工)复习题及答案
- 2026八年级劳动国家质量监测考试卷含答案
- AQ3035-2010危险化学品重大危险源安全监控技术规范关键条款解读
- T∕CHCIA 013-2023 液体香氛规范
- 2025版《广东省护理病历书写管理规范(试行)》
- 银行对公营销培训课件
- 冬季安全生产综合注意事项(防冻、防滑、防火、防爆、防中毒)课件
- 中小学教学质量考核奖励办法(2026年修订)
评论
0/150
提交评论