OPC客户端编程汇编

合集下载

手把手教您用VB编一个OPC客户端程序33页PPT

手把手教您用VB编一个OPC客户端程序33页PPT
手把手教您用VB编一个OPC客户端程

21、没有人陪你走一辈子,所以你要 适应孤 独,没 有人会 帮你一 辈子, 所以你 要奋斗 一生。 22、当眼泪流尽的时候,留下的应该 是坚强 。 23、要改变命运,首先改变自己。
24、勇气很有理由被当作人类德性之 首,因 为这种 德性保 证了所 有其余 的德性 。--温 斯顿. 丘吉尔 。 25、梯子的梯阶从来不是用来搁脚的 ,它只 是让人 们的脚 放上一 段时间 ,以便 让别一 只脚能不会再掉进坑里。——黑格尔 32、希望的灯一旦熄灭,生活刹那间变成了一片黑暗。——普列姆昌德 33、希望是人生的乳母。——科策布 34、形成天才的决定因素应该是勤奋。——郭沫若 35、学到很多东西的诀窍,就是一下子不要学很多。——洛克

delphi用Automation接口编写OPC客户端

delphi用Automation接口编写OPC客户端

delphi 用Automation接口编写OPC客户端一,首先是OPCAutomation 的安装1)使用regsvr32 注册 OPCDAAuto.dll2)在 Delphi 的project菜单中,选导入类型库 OPC Automation 2.0。

二编写程序声明 OPC 的类与接口FOPCServer:TOPCServer;FOPCGroup :TOPCGroup;FOPCb :OPCBrowser;FOPCItems :OPCItems; // interfaceFOPCItem :OPCItem; // interface// 获取OPC Server 列表function TForm1.OPCServerList(): Boolean;var OPCServerList,OPCServerName:OleVariant;j,i:integer;beginResult := false;tryFOPCServer := TOPCServer.Create(Self);OPCServerList:=FOPCServer.GetOPCServers;i:=VarArrayHighBound(OPCServerList,1);for j:=1 to i dobeginOPCServerName:=VarArrayGet(OPCServerList,j);lboxServerName.Items.Add(OPCServerName);end;exceptResult := False;end;end;// 连接OPC Serverfunction TForm1.OPCServerConnect(sServerID:string): Boolean; beginResult := true;tryFOPCServer.Connect1(sServerID);exceptResult := False;end;end;// 断开与OPC 服务器的连接procedure TForm1.OPCServerDisconnect;beginif Assigned(FOPCServer) thenbeginif Assigned(FOPCGroup) thenbeginFOPCServer.OPCGroups.RemoveAll;FOPCGroup.Free;FOPCGroup := nil;end;FOPCItems := nil;FOPCItem := nil;FOPCServer.Disconnect;FOPCServer.Free;FOPCServer := nil;end;end;// 创建连接OPC Groupfunction TForm1.OPCGroupConnect(AGroupName: OleVariant): Boolean; beginResult := True;tryFOPCGroup := TOPCGroup.Create(Self);FOPCGroup.ConnectTo(FOPCServer.OPCGroups.Add(AGroupName));FOPCGroup.UpdateRate :=1000;FOPCGroup.IsActive := True;FOPCGroup.IsSubscribed := True; // 事件支持exceptResult := False;end;end;procedure TForm1.BrowseItem(curNode:TTreeNode);var i: Integer;sItemName:WideString;beginwith FOPCb dobeginFilter:='*';DataType:=0;AccessRights:=0;ShowBranches;for i:=1 to Count dobeginsItemName:=Item(i);TvItemView.Items.AddChild(curNode,sItemName);end;// TvItemView.Selected.Expand(true);end;end;procedure TForm1.ADDBrowserItem;vari,iOrg:integer;sItemName:WideString;beginFOPCb:=FOPCServer.CreateBrowser;iOrg:=FOPCb.Get_Organization;if iOrg=2 then //平坦式结构beginwith FOPCb dobeginFilter:='*';DataType:=0;AccessRights:=0;ShowLeafs(true);for i:=1 to Count dobeginsItemName:=Item(i);TvItemView.Items.AddChild(SerVerNameNode,sItemName);end;end;endelse begin //树状结构BrowseItem(SerVerNameNode);end;end;procedure TForm1.SetBrowsePosition(sPosition:string);begintryFOPCb.MoveToRoot;caption:=sPosition;FOPCb.MoveDown(sPosition);except;end;end;procedure ItemViewClick(Sender: TObject);var i: Integer;sItemName:WideString;beginListBox1.Clear;SetBrowsePosition(TvItemView.Selected.Text);with FOPCb dobeginFilter:='*';DataType:=0;AccessRights:=0;ShowLeafs(true);for i:=1 to Count dobeginsItemName:=Item(i);ListBox1.Items.Add (sItemName);end;end;end;procedure ItemViewExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean);beginif not TvItemView.Selected.HasChildren thenbeginSetBrowsePosition(TvItemView.Selected.Text);BrowseItem(TvItemView.Selected);end;end;//添加一个项procedure TForm1.OPCItemAdd(sItemName:string);beginFOPCItems := FOPCGroup.OPCItems;FOPCItems.DefaultRequestedDataType:=0;FOPCItems.DefaultIsActive :=true;FOPCItem:=FOPCItems.AddItem(sItemName,ItemIndex);end;//读取指定项function TForm1.ReadData(ItemName:string):OleVariant;varValue, Quality, TimeStamp: OleVariant;beginFOPCitem :=FOPCItems.Item(ItemName);if not Assigned(FOPCItem) then Exit;FOPCItem.Read(OPCDevice, Value, Quality, TimeStamp);ReadData :=Value;end;。

OPC客户端编程汇编

OPC客户端编程汇编

OPC编程汇编OPC客户端的自动化实现OPC是建立在COM,DCOM的基础商的,因此绝大多数语言都可以很好的进行开发。

在Net中开发客户端有以下几种方式:(1)使用OPCNetAPI,需要用到OPCNetAPI.dll,.dll(2)使用自动化接口,需要用到OPCDAAuto.dll(3)使用自定义接口,需要用到多个Wrapper:OpcRcw.Ae.dll,OpcRcw.Batch.dll,n.dll,OpcRcw.Da.dll,OpcRcw.Dx.dll,OpcRcw.Hda.dll,OpcRcw.Sec.dll以上开发方式所需的动态链接库可以从OPC基金会(/)的网站上下载,一些下载项目可能需要注册,或成为基金会的成员。

不同的方式有各自的有缺点,请参见…本文使用自动化接口,语言进行开发,开发项目是无线射频(RFID)卡方面的应用,典型的如公交车,或公司考勤使用的刷卡机。

需要注意的是自动化接口存在一个“不是问题”的问题,数组下标是以1开始的,而不是传统计算机开发上的以0开始。

不知道设计者头脑是怎么想(有人知道吗?);这可能会给一些语言的开发造成问题(有人碰到吗,没有你就是幸运的)需求:OPCDAAuto.dll或该Dll的Interop(一):客户端开发流程OPC客户端的开发主要遵循下图所示的开发流程,下面就从以下几个开发步骤进行说明(二):枚举OPC服务器列表枚举服务器主要是通过OPCServer接口的GetOPCServers方法来实现的,该方法会返回OPC服务器数组(以1为下界,上面已有说明),以下是代码段Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loa dTryGlobalOPCServer = New OPCAutomation.OPCServerClass()Dim ServerList As Object= GlobalOPCServer.GetOPCServersFor index As Short= LBound(ServerList) To UBound(ServerList) '加入控件列表中,注意这里使用LBound和UBoundcbbServerList.Items.Add(ServerList(index))NextIf cbbServerList.Items.Count > 0 ThencbbServerList.SelectedIndex = 0End IfResetControlStatus() '设置控件状态GlobalOPCServer = NothingCatch Ex As ExceptionMessageBox.Show("List OPC servers failed: "+ Ex.Message, "OPCSample", MessageBoxButtons.OK) End TryEnd Sub(三):连接OPC服务器自动化接口中连接到服务器是使用connect方法Public Overridable Sub Connect(ByVal ProgID As String, Optional ByVal Node As Object = Nothing)ProgID指服务器的ProgID,Node代表网络节点,如果是本机则放空即可。

OPC实验指导书

OPC实验指导书

实验名称OPC客户端的编程一、实验目的:通过实际操作进一步了解OPC的各种概念,掌握OPC客户端的编写方法。

并对微软的DCOM 有一定的了解,要求通过合适的DCOM配置,使客户端能够读取网络上服务器中的数据。

二、实验内容:1)利用VB语言编写出一个简单的OPC客户端程序,要求这个客户端能够读取服务器中的数据,并显示出来。

2)配置DCOM,使客户端能够能过DCOM读取另一台服务器上的数据。

三、实验步骤:(1)建立一个Visual Basic工程1)启动Visual Basic,新建一个Visual Basic工程。

选择[Standard EXE]作为新建工程的类型。

图3-1 Visual Basic 工程的建立2)设置OPC包装DLL因为在新建的Visual Basic工程OPC包装DLL还没有被注册,必须用下述方法对OPC包装DLL 进行注册。

设置方法:1.从Visual Basic菜单里选择[Project]-[References]。

2.在[Available References]表示中,选择对应OPC包装DLL的文件名。

这里我们选择[OPCAutomation 2.0]。

图3-2 引用的设置(2)建立一个OPC对象在Visual Basic里,是以对象的单位对OPC服务器进行访问。

OPC自动化接口是由以下四种对象所定义。

OPC服务器OPC组(OPC组集合)OPC标签(OPC标签集合)OPC浏览器这里只说明OPC服务器,OPC组以及OPC标签对象的使用方法。

具体的来说,先连接一个特定的OPC服务器,然后建立OPC组,最后添加OPC标签。

1)变量声明参考图3-3所示的示范代码,先对OPC对象变量进行声明。

变量的数据类型应该指定为对象型。

这些对象变量最好在窗体代码的(General)部分声明。

因为在(General)部分声明的变量,可以在窗体的任何方法的代码内引用。

图3-3 OPC对象变量的声明有关定义OPC对象的声明及其说明列于表3-1表3-1 OPC对象变量的声明2)连接OPC服务器和建立OPC组下面说明如何连接OPC服务器和建立OPC组。

opcvba源代码

opcvba源代码

Option ExplicitOption Base 1Const servername = "OPCServer.WinCC"Dim WithEvents MyOPCServer As OPCServerDim WithEvents MyOPCGroup As OPCGroupDim MyOPCGroupColl As OPCGroupsDim MyOPCItemColl As OPCItemsDim MyOPCItems As OPCItemsDim MyOPCItem As OPCItemDim clienthandles(6) As LongDim ServerHandles() As LongDim Values(1) As VariantDim Errors() As LongDim ItemIDs(6) As StringDim GroupName As StringDim NodeName As StringDim itemv(6) As VariantDim ii As Integer'华丽的分割线——————————————————'Sub StartClient()'目的:链接至OPC_server,创建组和添加条目'——————————————————————————————————————华丽的分割线Sub StartClient()' On Error Goto ErrorHandler'---------------可以自由选择ClientHandle和GroupNameFor ii = 1 To 6clienthandles(ii) = iiNext iiGroupName = "MyGroup"'-------------从单元"A1"得到ItemIDNodeName = Range("C2").ValueItemIDs(1) = Range("c3").ValueItemIDs(2) = Range("c4").ValueItemIDs(3) = Range("c5").ValueItemIDs(4) = Range("c6").ValueItemIDs(5) = Range("c7").ValueItemIDs(6) = Range("c8").Value'----------------------------------得到一个OPC服务器的实例Set MyOPCServer = New OPCServerMyOPCServer.Connect servername, NodeNameSet MyOPCGroupColl = MyOPCServer.OPCGroups'-----------------为添加组设置缺省的激活状态MyOPCGroupColl.DefaultGroupIsActive = True'-----------------------添加组至收集Set MyOPCGroup = MyOPCGroupColl.Add(GroupName)Set MyOPCItemColl = MyOPCGroup.OPCItems'-----------------------添加一个条目、返回serverhandlesMyOPCItemColl.AddItems 6, ItemIDs(), clienthandles(), ServerHandles(), Errors'--------------------------用于接收不同的信息组MyOPCGroup.IsSubscribed = TrueExit SubErrorHadnler:MsgBox "Error:" & Err.Description, vbCritical, "Error"End Sub'华丽的分割线-----------------------------------------------------------------------'Sub StopClient()'目的:从服务器释放对象并且断开连接'-----------------------------------------------------------------------------------Sub stopclient()'----------------------释放组合服务器对象MyOPCGroupColl.RemoveAll'----------------------与服务器断开连接并且清楚MyOPCServer.DisconnectSet MyOPCItemColl = NothingSet MyOPCGroup = NothingSet MyOPCGroupColl = NothingSet MyOPCServer = NothingEnd Sub'华丽的分割线-----------------------------------------------------------------------'Sub MyOPCGroup_DataChange()'目的:组中的数值、质量或时间标志改变时,该事件激活'华丽的分割线-----------------------------------------------------------------------'-------------------------如果OPC-DA Automation 2.1被安装,使用:Private Sub myopcgroup_datachange(ByVal transactionID As Long, ByVal numitems As Long, clienthandles() As Long, itemvalues() As Variant, qualities() As Long, timestamps() As Date)'设置数据表单元值为数值读For ii = 1 To numitemsitemv(clienthandles(ii)) = itemvalues(ii)Next iiRange("d3").Value = CStr(itemv(1))Range("d4").Value = CStr(itemv(2))Range("d5").Value = CStr(itemv(3))Range("d6").Value = CStr(itemv(4))Range("d7").Value = CStr(itemv(5))End Sub。

用VB编写OPC

用VB编写OPC

winccopc:用VB编写OPC客户端访问WINCC-vb教程疯狂代码 / ĵ:http://VisualBasic/Article15470.html用VB编写OPC客户端访问WINCCOPC是个工业标准它是由些世界上著名自动化系统和硬件、软件Software公司和Microsoft(微软)紧密合作而建立〔O代表OLE(对象链接和嵌入)P (process过程)C (control控制)OLE已从面向对象重新定义为基于对象并更名为Active X〕WinCC是西门子公司在自动化领域采用最先进技术和微软公司在共同开发居于世界领先地位工控软件SoftwareWinCC即WINDOWS CONTROL CENTER(视窗控制中心)WinCC是个功能强大全面开放监控系统既可以用来完成小规模简单过程监控应用也可以用来完成复杂应用在任何情况下WinCC都可以生成漂亮而便捷人机对话接口使操作员能够清晰地管理和优化生产过程它集成OPC(OLE for process control)服务器使得过程数据可由其它应用(OPC客户机)访问WinCC在安装时提供了OPC客户端Control控件: Siemens OPC DAAutomation 2.0( SOPCDAAuto.dll),这个Control控件就是我们在VB中要用到Control控件我们也可以使用通用OPC客户端Control控件: OPC Automation 2.0.在WINCC帮助中有Siemens OPC DAAutomation 2.0使用简略帮助但说得不很详细我在使用中碰到不少问题现并写出来和大家共享、OPC连接 先在“引用”将近 Siemens OPC DAAutomation 2.0加入然后开始定义全局变量在本中我使用了两个OPC组进行OPC访问所以定义了全局变量我们要首先定义OPC服务类型和计算机结点名定义OPC组和OPC标签组并定义OPC标签和值数注意值定要设为Variant´OPC处理:只对WINCCConst ServerName = \"OPCServer.WinCC\" ‘OPC类型Const NodeName = \"GUK\" ‘结点名即计算机名‘Dim NodeName As StringDim WithEvents MyOPCServer As OPCServer ‘OPC服务Dim MyOPCGroupColl As OPCGroups ‘Dim WithEvents MyOPCGroupOut As OPCGroup ‘OPC组本用两个组进行OPC连接Dim WithEvents MyOPCGroupIn As OPCGroupDim MyOPCItemCollIn As OPCItems ‘OPC标签组Dim MyOPCItemCollOut As OPCItemsDim ServerHandlesIn As Long ‘句柄Dim ServerHandlesOut As LongDim ErrorsIn As Long ‘句柄Dim ErrorsOut As LongDim WatchDataReadItem(100) As String ´记录OPC标签Dim WatchDataReadValue(100) As Variant ´存放OPC值Dim WatchDataWriteItem(100) As String ´记录OPC标签Dim WatchDataWriteValue(100) As Variant ´存放OPC值在定义所有变量后我们就要进行OPC连接了要进行OPC连接的前,先要配置要访问OPC标签名我们WatchDataReadItem、WatchDataWriteItem中加入相应标签名注意:这两个必须由1开始不能由0开始配置好标签后就要进行OPC连接了如下面子:1、 ClientHandles1先配置名柄索引这将在读取OPC标签值时可要用到2、 生成OPC对象3、 进行OPC标签连接至此:OPC连接就成功了我们可以对OPC进行读和写操作了´--------------------------------------------------------------------- ´ Sub StartClient´ 目:连接至OPC_server创建组和添加条目´--------------------------------------------------------------------- Private Sub StartClientDim ItemNum As IntegerDim TarnscationID As LongDim CanceID As LongDim ClientHandles1(100) As LongDim ii As IntegerOn Error GoTo HANDLEeRRORFor ii = 0 To 100ClientHandles1(ii) = ii 先配置名柄索引这将在读取OPC标签值时可要用到 Next iiTarnscationID = 1‘ NodeName = xProfile.GetValue(\"SYSTEM\", \"NodeName\")‘生成OPC对象Set MyOPCServer = New OPCServerMyOPCServer.Connect ServerName, NodeNameSet MyOPCGroupColl = MyOPCServer.OPCGroupsMyOPCGroupColl.DefaultGroupIsActive = TrueSet MyOPCGroupIn = MyOPCGroupColl.Add(\"MYGROUPIN\")Set MyOPCGroupOut = MyOPCGroupColl.Add(\"MYGROUPOUT\") Set MyOPCItemCollIn = MyOPCGroupIn.OPCItemsSet MyOPCItemCollOut = MyOPCGroupOut.OPCItems‘进行OPC标签连接If WriteItemIdex > 0 ThenMyOPCItemCollOut.AddItems WriteItemIdex, WatchDataWriteItem, ClientHandles1, ServerHandlesOut, ErrorsOut ´化OCP连接MyOPCGroupOut.IsSubscribed = TrueEnd IfIf ReadItemIdex > 0 ThenMyOPCItemCollIn.AddItems ReadItemIdex, WatchDataReadItem, ClientHandles1, ServerHandlesIn, ErrorsIn ´化OCP连接MyOPCGroupIn.IsSubscribed = TrueEnd IfExit SubHANDLEeRROR:needOPCRestart = TruexLog1.log \"OPCl连接发生\"End Sub2、OPC标签读写对OPC标签读可以通过MyOPCGroupIn组和MyOPCGroupOutDataChange事件来读取该事件有多个参数:其中NumItems是指标签改变值个数ClientHandles是改变值标签索引ItemValues为改变值数据具体意思是ClientHandles(1)值是其对应标签索引其所指OPC标签值在ItemValues(1)中般来说刚连接上时该事件会把全部所要求访问OPC标签值全部读取过来(顺序不要通过ClientHandles索引)此后只有数据发生变化时才会触发该事件也只会传输发生了变化数据没有变化数据不会出现在本事件ItemValues中Private Sub MyOPCGroupOut_DataChange(ByVal TransactionID As Long, ByVal NumItems As Long, ClientHandles As Long, ItemValues As Variant, Qualities As Long, TimeStamps As Date)´产生要通知下级数据变化根椐不再Control控件有区别处理For ii = 1 To NumItemsWatchDataWriteValue(ClientHandles(ii) - 1) = ItemValues(ii) ´对改变值读入本Next iiEnd Sub对OPC写可以有同步和异步的分对于大量数据传输异步是更佳选择但对少量数据传输同步表现得更好要进行数据传输先要将值数据进行赋值注意:值数据要由0开始也就是说值和标签数据不是、对应值要比标签前位这点在WINCC介绍说明中没有但在我实际使用中直要这样不然数据就产生错位看下面这是个拔号完毕后返回数据进行OPC传递包含解包过程Private Sub showSuccess(msg As String)Dim location As StringDim nowTime As StringDim logStr As StringDim Value As StringDim ii, temp As IntegerDim isPack As BooleanDim sHead, sDelimited, sTail As Stringlocation = xProfile.GetValue(WatchPo(nowRunID), \"LOCATION\")nowTime = NowlogStr = \"拔\" & location & \"取数成功\" & msgxLog1.log logStrlogStr = \" \" & msgxLog2.log logStr ´记录数据´数据上传´如果有包结构,则显示包结构,isPack = xProfile.GetValue(WatchPo(nowRunID), \"ISRECHEAD\")If WatchPoRBegin(nowRunID) < 0 Then Exit SubIf isPack ThensHead = xProfile.GetValue(WatchPo(nowRunID), \"RECHEAD\")sDelimited = xProfile.GetValue(WatchPo(nowRunID), \"RECDELIMITER\") sTail = xProfile.GetValue(WatchPo(nowRunID), \"RECEND\")Value = Split(msg, sDelimited)For ii = 0 To UBound(Value) - 1temp = WatchPoRBegin(nowRunID) + iiIf temp > WatchPoREnd(nowRunID) Then Exit ForWatchDataReadValue(temp - 1) = Value(ii + 1) ´VALUE要从0开始比ITEM少1,所以减 有包头,占去位,向后延Next iiElseWatchDataReadValue(WatchPoREnd(nowRunID) - 1) = msgEnd IfMyOPCGroupIn.SyncWrite ReadItemIdex, ServerHandlesIn, WatchDataReadValue, ErrorsIn ´数据上传 ´记录上次成功执行时间xProfile.SetValue WatchPo(nowRunID), \"LASTTIME\", nowTimeEnd Sub3、OPC连接断开OPC客户端连接后要占用服务器资源所以如果不需要使用OPC时必须进行OPC连接断开断开相当简单释放资源即可如下Sub StopClient_disibledevent=>´----------- 释放组和服务器对象MyOPCGroupColl.RemoveAll´----------- 和服务器断开连接并且清除 MyOPCServer.DisconnectSet MyOPCItemCollIn = NothingSet MyOPCItemCollOut = NothingSet MyOPCGroupIn = NothingSet MyOPCGroupOut = NothingSet MyOPCGroupColl = NothingSet MyOPCServer = NothingEnd Sub但在实际使用中发现频繁连接和断开将使服务器资源被大量消耗最终让服务器出错所以尽量减少无谓OPC连接和断开结语: OPC使用是作为个DCOM在使用所以OPC客户端可以网络上任计算机运行但你必须配置DCOM访问权限如果你不想费神把服务器和客户端都用相同用户名和密码登录就成了如果想配置DCOM请参看DCOM配置参考资料:WinCC在线帮助作者介绍:顾恺高级员湖南大学毕业曾从事过LINUX内核研究从事过企业信息化平台开发当前从事SCADA开发主要将各种区别类型远程设备通过同手段进行数据采集并集成到企业信息化平台中去喜欢将工作中些积累形成文字2009-2-12 4:19:20疯狂代码 /。

用VB编写OPC客户端

用VB编写OPC客户端
Copyright Software Toolbox, 1999,2000,2001 All Rights Reserved Worldwide. Software Toolbox is a registered trademark of Software Toolbox, Inc.
OPC
Agenda
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 start 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 learning
The Automation Wrapper connects to the OPC server and creates the groups and items in the server and gives you references to them in your VB program in an Object model that mirrors that of the server

OPC客户程序_VB同步

OPC客户程序_VB同步

End Sub
Private Function GetQualityText(Quality) As String
Select Case Quality
Case 0: GetQualityText = "BAD"
Case 64: GetQualityText = "UNCERTAIN"
OutText = "添加组"
Set GroupObj = ServerObj.OPCGroups.Add("Group")
OutText = "Adding an Item to the group"
Set ItemObj = GroupObj.OPCItems.AddItem("XXXITEM", 1)'XXXITEM为添加的ITEM名称
Command_Write.Enabled = True
Command_Exit.Enabled = True
OutText = "连接OPC服务器"
Set ServerObj = New OPCServer
ServerObj.Connect ("XXXSERVER")'XXXSERVER为某OPC服务器名称
End Sub
Private Sub Command_Write_Click()'同步写
Dim OutText As String
Dim Serverhandles(1) As Long
Dim MyValues(1) As Variant
Dim MyErrors() As Long

VB+OPC代码

VB+OPC代码

OPC的VB例子Option ExplicitOption Base 1Private QOpcServer As OPCServerPrivate QGroups As OPCGroupsPrivate WithEvents QGroup As OPCGroupPrivate QItems As OPCItemsPrivate QItemServerHandles() As LongPrivate Sub Form_Load()On Error GoTo ErrorHandler'建立与OPC服务器的连接Set QOpcServer = New OPCServerCall QOpcServer.Connect("S7200.OPCServer") 'S7200.OPCServer是固定的OPC名称'建立一个数据群组Set QGroups = QOpcServer.OPCGroups ' Get OPCGroups Collection Object from QOPCSe rver' Set Default Properties for Group Collection' These Properties are used to set the Properies for new GroupsQGroups.DefaultGroupIsActive = 500 ' Set Default Group Update Rate to 500 msQGroups.DefaultGroupIsActive = False ' Set Default Group Active State to InactiveSet QGroup = QGroups.Add("QGroup1") ' Add a new Group to the Group Collection' Set Group PropertiesQGroup.IsSubscribed = True ' Enable CallbacksQGroup.UpdateRate = 100 '这个群组的刷新速度是100ms'往群组里添加要传送的地址单元Dim i As LongDim ErrorFlag As BooleanDim ItemObj As OPCItemDim ItemIDs(2) As StringDim ItemClientHandles(2) As LongDim Errors() As Long ' Array for returned Item related errorsErrorFlag = FalseSet QItems = QGroup.OPCItems ' Get OPCItems Collection Object from QOPCServer' Initialize the [IN] parameters for the Add Items call' ItemIDs -> ItemIDs of the Items to add' ItemClientHandles -> Client defined handles for the Items. The Server sends these handles in the CallbacksItemIDs(1) = "2,q1.0,bool" ' Read ItemId 1 from Text BoxItemIDs(2) = "2,VW10,Word" ' Read ItemId 2 from Text BoxItemClientHandles(1) = 1ItemClientHandles(2) = 2' [OUT] parameters are' ItemServerHandles -> Server defined handles for the Items. The client must use these handle s for all Read/Write calls' Errors -> Item related errors' Add Items to the GroupCall QItems.AddItems(2, ItemIDs, ItemClientHandles, QItemServerHandles, Errors)' Check Item ErrorsFor i = 1 To 2If Not Errors(i) = 0 ThenMsgBox "Item " + Str$(i) + " FAILED. Error Code = " + Str$(Errors(i)), vbCriticalErrorFlag = TrueEnd IfNext' Continue only if all Items SUCCEEDEDIf ErrorFlag ThenDim RemoveErrors() As LongDim RemoveHandles(1) As Long' Remove Succeede ItemsFor i = 1 To 2If Errors(i) = 0 ThenRemoveHandles(1) = QItemServerHandles(i)Call QItems.Remove(1, RemoveHandles, RemoveErrors)End IfNextEnd IfIf Not QGroup Is Nothing ThenQGroup.IsActive = TrueEnd IfExit SubErrorHandler:MsgBox Err.Description + Chr(13) + "联接到OPC服务器", vbCritical, "Error"End SubPrivate Sub cmdWriteSync_Click()'On Error GoTo ErrorHandlerDim i As LongDim Values(2) As VariantDim Errors() As Long ' Array for returned Item related errors' Initialize the [IN] parameters for the SyncWrite call' Values -> Values to writeValues(1) = txtWriteVal1.Text ' Read Value 1 from Text BoxValues(2) = txtWriteVal2.Text ' Read Value 2 from Text Box' ItemServerHandles -> Server defined handles from the AddItems call' Write Values SyncronousCall QGroup.SyncWrite(2, QItemServerHandles, Values, Errors)' Check Item ErrorsFor i = 1 To 2If Not Errors(i) = 0 Then MsgBox "Item " + Str$(i) + " FAILED. Error Code = " + Str$(Error s(i)), vbCriticalNextExit SubErrorHandler:MsgBox Err.Description + Chr(13) + "Writing Items Syncronous", vbCritical, "ERROR"End Sub' Callback from OnDataChangePrivate Sub QGroup_DataChange(ByVal TransactionID As Long, ByVal NumItems As Long, Client Handles() As Long, ItemValues() As Variant, Qualities() As Long, TimeStamps() As Date)'On Error GoTo ErrorHandlerDim i As Long' Check ParametersFor i = 1 To NumItemsIf ClientHandles(i) > 0 And ClientHandles(i) < 3 Then' Values -> Values from read complete' Qualities -> Qualities of the valuesIf Qualities(i) = 192 ThentxtChangeVal.Item(ClientHandles(i) - 1).Text = ItemValues(i) ' Write Value to Text Box End IfElseMsgBox "DataChange Item " + Str$(i) + " has invalid Client Handle ", vbCriticalEnd IfNextExit SubErrorHandler:MsgBox Err.Description + Chr(13) + "OnDataChange", vbCritical, "ERRORCha"End SubPrivate Sub cmdExit_Click()Unload MeEnd Sub' Unload Form EventPrivate Sub Form_Unload(Cancel As Integer)Dim i As LongDim Errors() As Long ' Array for returned Item related errors' Remove Items from the GroupCall QItems.Remove(2, QItemServerHandles, Errors)' Check Item ErrorsFor i = 1 To 2If Not Errors(i) = 0 Then MsgBox "Item " + Str$(i) + " FAILED. Error Code = " + Str$(Errors(i)), vbCriticalNextErase QItemServerHandles ' Erase Item Server Handle ArrayQGroups.RemoveAll ' Removes all GroupsSet QGroup = Nothing ' Delete OPCGroup ObjectSet QGroups = Nothing ' Delete OPCGroups Collection ObjectQOpcServer.Disconnect ' Disconnect from OPC ServerSet QOpcServer = Nothing ' Delete OPCServer ObjectEnd Sub。

OPC客户端搭建

OPC客户端搭建
}
}
在异步读取函数完成之后调用本函数,输出数据读取结果。
5)断开与服务器连接
断开服务器得先清除所有组对象及其下的数据项对象。
public void disconnectSvr()//与断开服务器
{
try
{
OPCSvr.OPCGroups.RemoveAll();
OPCSvr.Disconnect();
{
Console.WriteLine("异步读取数据结果如下:");
for (int i = 1; i <= NumItems; i++)
{
Console.WriteLine("ID:{0}Vaule:{1}Quality:{2} Timestamp:{3}",OPCIt[i-1].ItemID,Convert.ToString(ItemValues.GetValue(i)), Convert.ToString(Qualities.GetValue(i)), Convert.ToString(TimeStamps.GetValue(i)));
}
B.异步读取
public void AsRead(string itemid)//异步读取
{
{
OPCIt[0] = OPCIts.AddItem(itemid, 0);
int[] temp = new int[] { 0, OPCIt[0].ServerHandle };
Array serverHandles = (Array)temp;
OPCIt[0] = OPCIts.AddItem(itemid, 0);
OPCIt[0].Read(1, out ItemValues, out Qualities, out TimeStamps);

关于OPCClient编写

关于OPCClient编写

关于OPCClient编写关于OPC Client 编写hapican 895 5热门 2014-02-23 20:14昨天又有人问我 OPC Client 编写,实际是他们不了解OPC 客户端的工作原理,要想写客户端程序,必须知道OPC对象,OPC逻辑对象模型包括3类对象:OPC server对象、OPC group对象、OPC item对象,每类对象都包括一系列接口。

OPC Server对象主要功能为:1、创建和管理OPC Group对象;2、管理服务器内部的状态信息;OPC Group对象主要功能为:1、管理OPC Group对象的内部状态信息;2、创建和管理Items对象。

3、OPC服务器内部的实时数据存取服务(同步与异步方式)。

OPC组中有以下几个主要属性:Name :组的名字;Active:组的激活状态标志;Update Rate OPC:服务器向客户程序提交数据变化的刷新速率;Percent Dead band:数据死区,即能引起数据变化的最小数值百分比。

OPC ITEM 是非COM对象,在OPC标准中用来描述实时数据,是客户端不可见的对象。

代表了与服务器中的数据的连接,它并不是数据源,而仅仅是与数据源的连接。

每个项都有以下主要属性:Active项的激活状态、Value项的数值、类型为VARIANT、Quality 项的品质,代表数值的可信度,类型为SHORT、TimeStamp时间戳,代表数据的存取时间。

你不管用什么开发语言只要了解上面几个对象,就会写程序了下面举个VC的例子HRESULT r1;CLSID clsid;LONG TimeBias = 0;FLOAT PercentDeadband = 0.0;DWORD RevisedUpdateRate;LPWSTR ErrorStr;char str[100];CString szErrorText;m_pItemResult = NULL;客户端程序必须对DCOM进行初始化设置,以保证OPC服务器端回调函数不会被堵塞。

VB编写OPC客户端程序

VB编写OPC客户端程序

如何用VB编写OPC客户端程序一、引言在工业自动化领域,计算机早已成为必不可少的工具,计算机技术的不断发展,大大加速了工业自动化技术的进步,而各种各样的工业控制应用软件正是具体实现这一进程的最重要的工具。

以往,应用软件开发商要为每一种硬件开发驱动程序,由于硬件的种类繁多,特征各异,软件开发商的负担异常繁重,尤其是如果硬件特征发生了变化,整个应用软件相应的驱动程序也要相应地修改,这对软件开发商,对整个工程都是很不利的。

而且由于驱动程序的不统一,不同应用程序访问同一硬件设备时常常发生冲突。

OPC(OLE for Process Control)技术标准正是在这种情况下产生的。

OPC 基于微软的OLE、COM和DCOM技术,而且它本身就是一种特殊的COM ,也正因为有微软的参与,以及以已经成熟的技术为基础,它比一般的工业标准制定的效率更高,它从开始制定到第一个可运行的规范开始运行,只用了不到一年的时间。

二、OPC原理及应用OPC技术为工业自动化软件面向对象的开发提供了统一的标准。

它大大减轻了软件开发商的负担,软件开发商不必再为每一硬件单独编写驱动程序,只要硬件的特征符合统一的OPC接口程序标准,或者硬件生产商提供OPC服务器,如图一所示,不同的应用软件开发商都可以采用OPC标准设计工控软件,以标准规定的统一接口通过OPC服务器存取现场数据。

这样,当现场设备发生变化或系统中加入新设备时,OPC服务器的提供商需要重新实现服务器接口,以适应硬件的变化,但由于服务器所提供的接口的一致性,工控软件不作更改即可继续使用,只是某些情况下可能需要重新组态(如添加新的PLC站点等),这样,软件开发商可以节省大量的时间致力于工控软件的性能方面的提高,不必再考虑硬件变化带来的影响,大大减小了软件维护的工作量。

这正如OPC规范里所说,OPC将应用软件和硬件设备划清了界限。

2.1 OPC基本结构OPC服务器有两类接口:定制接口(Custom Interface)、自动化接口(Automation Interface),定制接口比较低级,它提供更多的功能,效率也比后者高,可以用C++语言调用此类接口,自动化接口主要用于VB、DELPHI等开发工具。

(完整word版)OPCclient在VC环境下编程

(完整word版)OPCclient在VC环境下编程

OPC client 在VC环境下编程一.连接使用到变量的说明类型说明HRESULT 函数返回值,用来检测函数返回值(如:初始化COM库,查找CLSID,创建OPC服务等),提供函数执行情况CLSID 全球唯一标示符,用来确定OPC服务的标识,从注册表查找获得LPWSTR LPSTR和LPWSTR是Win32和VC++所使用的一种字符串数据类型.LPSTR被定义成是一个指向以NULL(‘\0')结尾的8位ANSI字符数组指针,而LPWSTR是一个指向以NULL结尾的16位双字节字符数组指针OPC接口说明IOPCServer *m_IOPCServer;IOPCServer 接口及成员函数主要用于对组对象进行创建,删除,枚举和获取当前状态等操作.是OPC 服务器对象的主要接口.接口及成员IOPCItemMgt *m_IOPCItemMgt;IOPCItemMgt 接口及成员函数用于OPC 客户程序添加、删除和组对象中组员等控制操作。

IOPCSyncIO *m_IOPCSyncIO;IOPCSyncIO 用于同步数据访问。

OPCITEMDEF m_Items[1];OPCITEMDEF 数组,包含着项的存取路径, 定义和被请求的数据类OPCITEMRESULT *m_ItemResult;OPCITEMRESULT 数组,服务器用来告诉客户关于项的附加的信息(项句柄和规范的数据类型)OPCHANDLE m_GrpSrvHandle;OPC服务的句柄,在多个函数中都会用到使用到的函数说明CoInitialize(NULL); 初始化COM库CoInitialize是Windows提供的API函数,用来告诉Windows以单线程的方式创建com对象.应用程序调用com库函数(除CoGetMalloc和内存分配函数)之前必须初始化com库。

返回值S_OK : 该线程中COM库初始化成功S_FALSE 该线程中COM库已经被初始化CoInit ialize () 标明以单线程方式创建。

C#编写OPC客户端读取OPC服务器的数据(最高效简洁版)

C#编写OPC客户端读取OPC服务器的数据(最高效简洁版)

C#编写OPC客户端读取OPC服务器的数据(最⾼效简洁版) List<string> ItemIds= new List<string>(){"S7-1200.0-166.BOOL","S7-1200.0-166.BYTE","S7-1200.0-166.INT","S7-1200.0-166.WORD","S7-1200.0-166.REAL",};//把需要订阅的项添加到group中。

for (int i = 0; i < ItemIds.Count; i++){OPCItem myItem = group.OPCItems.AddItem(ItemIds[i], i);}Console.ReadKey();}private static void Group_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps){//此处注意i是从1开始,因为getvalue没有0.下⾯输出分别为数据的ClientHandles(就是上⽂AddItem⽅法的第⼆个参数。

),Itemvalue 就是值,Qualities为质量,timestamps为时间。

for (int i = 1; i < NumItems+1; i++){Console.WriteLine(ClientHandles.GetValue(i).ToString() + "--" + ItemValues.GetValue(i).ToString() + "--" +Qualities.GetValue(i).ToString() + "--" + TimeStamps.GetValue(i).ToString());}}}}最终结果输出如下:这就是⼀个OPC客户端,我想应该是最简单的了。

(C#)OPC客户端源码

(C#)OPC客户端源码

(C#)OPC客户端源码Code///摘要///程式使用C#.NET 2005 编写///引用类库OPCDAAuto.dll///OPCServer采用KEPWare///在windows xp sp2、sp3、windows 2003上测试通过///完成于:2008年12月31日///测试于:2009年01月05日//////作者:潇洒草///Email:zhkai868@///QQ:44649029//////如分发,请保留此摘要。

///鄙视那些拿代码当宝贝的人,鄙视那些你不拿源码换就不稀罕你的人,鄙视那些自私的人。

///别人看到你的代码,你能死啊?对你有多大威胁啊?强烈鄙视~~~///如果你是这样的人,赶紧关了。

偶不欢迎。

using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using ;using System.Collections;using OPCAutomation;namespace OPC测试通过{public partial class MainFrom : Form{public MainFrom(){InitializeComponent();}#region 私有变量/// <summary>/// OPCServer Object/// </summary>OPCServer KepServer;/// <summary>/// OPCGroups Object/// </summary>OPCGroups KepGroups;/// <summary>/// OPCGroup Object/// </summary>OPCGroup KepGroup;/// <summary>/// OPCItems Object/// </summary>OPCItems KepItems;/// <summary>/// OPCItem Object/// </summary>OPCItem KepItem;/// <summary>/// 主机IP/// </summary>string strHostIP = "";/// <summary>/// 主机名称/// </summary>string strHostName = "";/// <summary>/// 连接状态/// </summary>bool opc_connected = false;/// <summary>/// 客户端句柄/// </summary>int itmHandleClient = 0;/// <summary>/// 服务端句柄/// </summary>int itmHandleServer = 0;#endregion#region 方法/// <summary>/// 枚举本地OPC服务器/// </summary>/// </summary>private void GetLocalServer(){//获取本地计算机IP,计算机名称IPHostEntry IPHost = Dns.Resolve(Environment.MachineName);if (IPHost.AddressList.Length > 0){strHostIP = IPHost.AddressList[0].ToString();}else{return;}//通过IP来获取计算机名称,可用在局域网内IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP);strHostName=ipHostEntry.HostName.ToString();//获取本地计算机上的OPCServerNametry{KepServer = new OPCServer();object serverList = KepServer.GetOPCServers(strHostName);foreach (string turn in (Array)serverList){cmbServerName.Items.Add(turn);}cmbServerName.SelectedIndex = 0;btnConnServer.Enabled = true;}catch(Exception err){MessageBox.Show("枚举本地OPC服务器出错:"+err.Message,"提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);}}/// <summary>/// 创建组/// </summary>private bool CreateGroup(){try{KepGroups = KepServer.OPCGroups;KepGroup = KepGroups.Add("OPCDOTNETGROUP");SetGroupProperty();KepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);KepGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete); KepItems = KepGroup.OPCItems;}catch (Exception err){MessageBox.Show("创建组出现错误:"+err.Message,"提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);return false;}return true;}/// <summary>/// 设置组属性/// </summary>private void SetGroupProperty(){KepServer.OPCGroups.DefaultGroupIsActive =Convert.ToBoolean(txtGroupIsActive.Text);KepServer.OPCGroups.DefaultGroupDeadband = Convert.ToInt32(txtGroupDeadband.Text);KepGroup.UpdateRate = Convert.ToInt32(txtUpdateRate.Text);KepGroup.IsActive = Convert.ToBoolean(txtIsActive.Text);KepGroup.IsSubscribed =Convert.ToBoolean(txtIsSubscribed.Text);}/// <summary>/// 列出OPC服务器中所有节点/// </summary>/// <param name="oPCBrowser"></param>private void RecurBrowse(OPCBrowser oPCBrowser){//展开分支oPCBrowser.ShowBranches();//展开叶子oPCBrowser.ShowLeafs(true);foreach (object turn in oPCBrowser){listBox1.Items.Add(turn.ToString());}}/// <summary>/// 获取服务器信息,并显示在窗体状态栏上/// </summary>private void GetServerInfo(){{tsslServerStartTime.Text ="开始时间:"+ KepServer.StartTime.ToString()+" ";tsslversion.Text ="版本:"+ KepServer.MajorVersion.ToString() + "." + KepServer.MinorVersion.ToString()+"."+KepServer.BuildNumber.ToString();}/// <summary>/// 连接OPC服务器/// </summary>/// <param name="remoteServerIP">OPCServerIP</param>/// <param name="remoteServerName">OPCServer名称</param>private bool ConnectRemoteServer(string remoteServerIP, string remoteServerName){try{KepServer.Connect(remoteServerName, remoteServerIP);if (KepServer.ServerState == (int)OPCServerState.OPCRunning){tsslServerState.Text = "已连接到-" + KepServer.ServerName + " ";}else{//这里你可以根据返回的状态来自定义显示信息,请查看自动化接口API文档tsslServerState.Text = "状态:" + KepServer.ServerState.ToString() + " ";}}catch (Exception err){MessageBox.Show("连接远程服务器出现错误:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);return false;}return true;}#endregion#region 事件/// <summary>/// 写入TAG值时执行的事件/// </summary>/// <param name="TransactionID"></param>/// <param name="NumItems"></param>/// <param name="ClientHandles"></param>/// <param name="Errors"></param>void KepGroup_AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors){lblState.Text = "";for (int i = 1; i <= NumItems; i++){lblState.Text += "Tran:" + TransactionID.ToString() + " CH:" + ClientHandles.GetValue(i).ToString() + " Error:" + Errors.GetValue(i).ToString();}}/// <summary>/// 每当项数据有变化时执行的事件/// </summary>/// <param name="TransactionID">处理ID</param>/// <param name="NumItems">项个数</param>/// <param name="ClientHandles">项客户端句柄</param>/// <param name="ItemValues">TAG值</param>/// <param name="Qualities">品质</param>/// <param name="TimeStamps">时间戳</param>void KepGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps) {//为了测试,所以加了控制台的输出,来查看事物ID号//Console.WriteLine("********"+TransactionID.ToString()+"*********");for (int i = 1; i <= NumItems; i++){this.txtTagValue.Text = ItemValues.GetValue(i).ToString();this.txtQualities.Text = Qualities.GetValue(i).ToString();this.txtTimeStamps.Text = TimeStamps.GetValue(i).ToString();}}/// <summary>/// 选择列表项时处理的事情/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void listBox1_SelectedIndexChanged(object sender, EventArgs e){try{if (itmHandleClient != 0){this.txtTagValue.Text = "";this.txtQualities.Text ="";this.txtTimeStamps.Text = "";Array Errors;OPCItem bItem = KepItems.GetOPCItem(itmHandleServer);//注:OPC中以1为数组的基数int[] temp = new int[2] { 0, bItem.ServerHandle };int[] temp = new int[2] { 0, bItem.ServerHandle };Array serverHandle = (Array)temp;//移除上一次选择的项KepItems.Remove(KepItems.Count, ref serverHandle, out Errors);}itmHandleClient = 1234;KepItem = KepItems.AddItem(listBox1.SelectedItem.ToString(), itmHandleClient);itmHandleServer = KepItem.ServerHandle;}catch(Exception err){//没有任何权限的项,都是OPC服务器保留的系统项,此处可不做处理。

汇编指令之OpCode快速入门

汇编指令之OpCode快速入门

汇编指令之OpCode快速入门:最近一直被一些初学者问及有关于汇编指令的长度问题,因此为此专门撰写本文,以求为不知OpCode为何物,或者正为汇编长短不一的指令而烦恼的朋友一个最为快速的指引。

其实,OpCode并不复杂,在本文中我不打算细致入微的告诉大家OpCode的原理,不会为大家带来一大堆有关于什么是定长指令、什么是变长指令的理论知识,更不会带着各位读者玩OpCode Hacking,我只会告诉你“怎么了”、“为什么”以及“如何解决”。

1、我的汇编指令怎么了?哦,天啊!怎么我今天突然发现汇编指令竟然是长短不一的!你还没发现吗?那么请过目:1E831880000CALL00430B862E917FEFFFF JMP0042817138B442404MOV EAX,DWORD PTR SS:[ESP+4]485C0TEST EAX,EAX556PUSH ESI68BF1MOV ESI,ECX我们可以看见“CALL00430B86”这条汇编指令竟然占用了5个字节,而“PUSH ESI”则只占用了1个字节,汇编指令的脾气犹如一只滑头的猴子一样让你摸不到头脑,它很明显的告诉了你“嘿!兄弟,你别想搞懂我!”你也许会感到很郁闷,但是我并不这么想,因为如果我要想自己搞一个反汇编引擎,或者是我要在我的壳里加上代码混淆功能……嗯,算了,就算是我想娱乐一下搞搞免杀吧,那么我终归是要搞懂它的,为什么?因为如果搞懂它的话,那么我就没办法做到这些!很明显我们的汇编指令继承了Intel工程师的狡猾本质,为了尽可能的减少体积,所以它们的体积被设计的不尽相同。

哇哦!很多读者此时似乎已经想明白是怎么回事了,肯定是不同的指令对应的字节数不一样,恩……这样只要我们搞到一张表就可以了!不是吗?一张可以描述每个指令所用二进制码的表格,然后我们就万事大吉了。

但是很不幸,我在初次接触OpCode时也想出了这个“超级点子”,但是很可惜我的“超级点子”与各位读者的一样,并没有为我解决任何问题,请过目:7B801000000MOV EAX,188BC3MOV EAX,EBX98BC7MOV EAX,EDI看到了吗,一样的指令,一样的目的操作数,得到的确是完全不同的机器码……2、这是为什么?嗯,我想这个问题是很明显的,源操作数如果是一个寄存器的话,那么能有几种可能呢?按照规则来讲貌似只有不超过50种可能,那么如果被操作数是一个数值呢?你想想,32位能表示多少数,将其乘以2就是最终的可能性了,这么多的可能性一定不是区区两个16位数就能表示过来的。

OPC客户端源码

OPC客户端源码

【转】(C#)OPC客户端源码转载申明申明:本文为转载,如需转载本文,请获取原文作者大尾巴狼啊的同意,谢谢合作!转自:大尾巴狼啊原文出处:前几天我就发布过这篇文章,可惜的是,发布后代码有的却看不到,后来我就删了,至今不明白什么原因- -!关于C++、VB来开发OPC客户端的资料网上有很多,但C#的至今没发现有多少。

由于近期项目的需要,就开发了OPC客户端的一个模块。

在我想来,程序员挺累的,原因我很累。

所以我想大家也很累~~~嘿嘿。

特别是刚接手OPC客户端开发的前几天,天天盯住显示器,百度、GOOGLE不停的搜索。

每天早上醒来,眼睛都瑟瑟的。

从事3年以上软件开发的朋友们,估计都会腰酸背痛吧!反正我是这样的。

不说那么多废话了,贴上源码,让需要的同行看看吧,代码的质量并不高,就当做抛砖引玉吧!1、枚举本地服务器2、获取服务器信息3、列出了服务器上Tag4、可以设置组的属性5、读\写功能6、可进行远程连接(DCOM需配置)先看图:引用类库:OPC服务器:开发工具:当前环境:源码:}else{return; }+ "."+}oString() + " Error:" + (i).ToString();}}oString();= (i).ToString();= (i).ToString();}}mail 2009-03-31 15:01 | 李默[未注册用户]#29楼回复引用能给我份源码吗2009-04-04 19:01 | 滕大鹏[未注册用户]#30楼回复引用我想要文档,能给份吗谢谢2009-04-04 19:03 | 滕大鹏[未注册用户]#31楼回复引用谢谢楼主,我的邮箱是,能给我发一份全部的资料吗2009-04-07 14:02 | TJC#32楼回复引用谢谢,传份给我,要全部资源(文档+源码),万分感谢!2009-04-08 22:02 | hxf[未注册用户]#33楼回复引用急需一份资料谢谢2009-04-11 16:34 | jhjohn[未注册用户]#34楼回复引用麻烦传份给我,要全部资源(文档+源码),万分感谢2009-04-13 08:36 | yldx#35楼回复引用您好!麻烦传分全部资源(文档+源码),谢谢2009-04-15 13:00 | xhm0924[未注册用户]#36楼回复引用谢谢,传份给我,要全部资源(文档+源码),万分感谢!急用2009-04-25 09:35 | bestyaq#37楼回复引用谢谢,传份给我,要全部资源(文档+源码),万分感谢!2009-04-26 12:13 | carson1978[未注册用户]#38楼回复引用谢谢,传份给我,要全部资源(文档+源码),万分感谢!2009-04-26 12:14 | carson1978[未注册用户]#39楼回复引用我也要一份,谢谢!2009-04-27 11:59 | 黄旭东[未注册用户]#40楼[楼主] 回复引用查看你们不会自己下载啊想的到美!还让我给你们传呢!工资也直接打我卡上算了!2009-04-28 13:17 | badnewfish#41楼回复引用谢谢楼主分享,后面的三个文档可以麻烦给发一份吗现在项目上遇到了这样的问题,希望能借鉴一下!万分感谢!2009-05-04 13:25 | 陆海成[未注册用户]#42楼回复引用可否给我发一份。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

O P C客户端编程汇编公司内部编号:(GOOD-TMMT-MMUT-UUPTY-UUYY-DTTI-OPC编程汇编OPC客户端的自动化实现OPC是建立在COM,DCOM的基础商的,因此绝大多数语言都可以很好的进行开发。

在Net中开发客户端有以下几种方式:(1)使用OPCNetAPI,需要用到,(2)使用自动化接口,需要用到(3)使用自定义接口,需要用到多个Wrapper:,,,,,,以上开发方式所需的动态链接库可以从OPC基金会的网站上下载,一些下载项目可能需要注册,或成为基金会的成员。

不同的方式有各自的有缺点,请参见…本文使用自动化接口,语言进行开发,开发项目是无线射频(RFID)卡方面的应用,典型的如公交车,或公司考勤使用的刷卡机。

需要注意的是自动化接口存在一个“不是问题”的问题,数组下标是以1开始的,而不是传统计算机开发上的以0开始。

不知道设计者头脑是怎么想();这可能会给一些语言的开发造成问题(,没有你就是幸运的)需求:或该Dll的Interop(一):客户端开发流程OPC客户端的开发主要遵循下图所示的开发流程,下面就从以下几个开发步骤进行说明?(二):枚举OPC服务器列表枚举服务器主要是通过OPCServer接口的GetOPCServers方法来实现的,该方法会返回OPC服务器数组(以1为下界,上面已有说明),以下是代码段'枚举OPC服务器列表PrivateSub Form1_Load(ByVal sender As,ByVal e AsHandlesTryGlobalOPCServer =New()Dim ServerList AsObject=For index AsShort= LBound(ServerList)To UBound(ServerList)'加入控件列表中,注意这里使用LBound和UBoundNextIfThen= 0EndIfResetControlStatus()'设置控件状态GlobalOPCServer =NothingCatch Ex As Exception("List OPC servers failed: "+ ,"OPCSample",EndTryEndSub(三):连接OPC服务器自动化接口中连接到服务器是使用connect方法Public Overridable Sub Connect(ByVal ProgID As String,OptionalByVal Node As Object= Nothing)ProgID指服务器的ProgID,Node代表网络节点,如果是本机则放空即可。

连接到服务器后,以下属性需要特别注意::服务器的启动时间:服务器的当前时间,各个客户端可以通过这个属性值完成一些同步的操作:以后添加的Group是否默认激活:Group的默认死区,变化量超过死区后将会触发DataChange事件,合理的设置该值可以提高程序性能:下属组(Group)的数量:组(Group)的默认通信区域编号,如1024:组(Group)的默认刷新率,该属性也比较重要:组(Group)的默认时间偏差(四):添加组(Group)和项(Item)添加组和项需要用到和方法,以下是原型:Function Add(Optional ByVal Name As Object= Nothing) AsFunction AddItem(ByVal ItemID As String,ByVal ClientHandle As Integer) As 组也有两个重要的属性:刷新率,该属性通Groups的UpdateRate意义一样,如果这个值有设置,则以这个值为准Group.IsSubscribed:是否使用订阅功能以下是代码段'连接到指定的OPC服务器PrivateSub btnConnectServer_Click(ByVal sender As,ByVal e AsHandlesIf <>""ThenConnectedOPCServer =New()Try'设置组集合的默认属性True'添加组= 3 * 1000'刷新虑,用于下面的DataChange事件=True'使用订阅功能'添加项"", 0)"", 1)"", 2)RefreshServerStatus()'刷新服务器状态Catch ex As ExceptionConnectedOPCServer =Nothing("OPC server connect failed : "+ ,"OPCSample",EndTryResetControlStatus()EndIfEndSub(五):读写操作与事件控制读写操作包括同步和异步两种操作方式,以下是这几个方法的原型:Group的同步读事件Sub SyncRead(ByVal Source As Short,ByVal NumItems As Integer,ByRef ServerHa ndles As,ByRef Values As,ByRef Errors,Optional ByRef Qualities As Object= Nothing,Optional ByRef TimeStamps As Object= Nothing)Group的同步写事件Sub SyncWrite(ByVal NumItems As Integer,ByRef ServerHandles As,ByRef Value s As,ByRef Errors AsGroup的异步读事件Sub AsyncRead(ByVal NumItems As Integer,ByRef ServerHandles As,ByRef Error s As,ByVal TransactionID As Integer,ByRef CancelID As Integer)Group的异步写事件Sub AsyncWrite(ByVal NumItems As Integer,ByRef ServerHandles As,ByRef Valu es As,ByRef Errors As,ByVal TransactionID As Integer,ByRef CancelID As Integ er)如果使用异步的读写操作,那么还需要实现Group中的ReadComplete和WriteComplete两个事件PublicEvent AsyncReadComplete(ByVal TransactionID As Integer,ByVal NumItems As I nteger,ByRef ClientHandles As,ByRef ItemValues,ByRef Qualities As,ByRef T imeStamps As,ByRef Errors AsPublicEvent AsyncWriteComplete(ByVal TransactionID As Integer,ByVal NumItems As Integer,ByRef ClientHandles As,ByRef Errors As其他相关的重要事件包括:Group数据变化时的通知事件PublicEvent DataChange(ByVal TransactionID As Integer,ByVal NumItems As Integer, ByRef ClientHandles As,ByRef ItemValues As,ByRef Qualities As,ByRef TimeSt amps AsGroup的异步取消事件Public Event AsyncCancelComplete(ByVal CancelID As Integer)Server(服务器)关闭通知事件Public Event ServerShutDown(ByVal Reason As String)以下是这些实现的代码段'读取卡片指定的块号的值PrivateSub btnReadCard_Click(ByVal sender As,ByVal e AsIfNot(ConnectedGroup IsNothing)ThenTry'获取块号Dim BlockNo AsShort=CByte'如果要获取数据的块所对应的项还没有创建,就创建它If GlobalOPCBlockItems(BlockNo)IsNothingThen""&CStr(BlockNo), 200 + BlockNo)EndIf'准备参数数组Dim ServerResults AsDim ServerErrors AsDim ServerHandles(1)AsIntegerServerHandles(1) = GlobalOPCBlockItems(BlockNo).ServerHandle '读取值If ServerErrors(1) <> 0ThenMsgBox("Read Card Failed:"& ServerErrors(1))Else= ServerResults(1)EndIfCatch ex As Exception("OPC server Read Card failed: "+ ,"OPCSample",EndTryEndIfEndSub'写卡片指定块的值PrivateSub btnWriteCard_Click(ByVal sender As,ByVal e AsIfNot(ConnectedGroup IsNothing)ThenTry'获取块号Dim BlockNo AsShort=CByte'如果要写入数据的块所对应的项还没有创建,就创建它If GlobalOPCBlockItems(BlockNo)IsNothingThen""&CStr(BlockNo), 200 + BlockNo)EndIf'准备参数数组Dim ServerValues(1)AsObjectDim ServerErrors As ArrayDim ServerHandles(1)AsIntegerServerHandles(1) = GlobalOPCBlockItems(BlockNo).ServerHandle ServerValues(1) ='写入值(1, ServerHandles, ServerValues, ServerErrors)If ServerErrors(1) <> 0ThenMsgBox("Write Card Failed:"& ServerErrors(1))ElseMsgBox("Write Card Succeed")EndIfCatch ex As Exception("OPC server Write Card failed: "+ ,"OPCSample",EndTryEndIfEndSub(六):断开服务器断开服务器只要使用OPCServer的Disconnect方法几个,以下是代码段:'断开到指定OPC服务器的连接PrivateSub btnDisconnectServer_Click(ByVal sender As,ByVal e AsHandles IfNot(ConnectedOPCServer IsNothing)ThenTry()Catch ex As Exception("OPC server disconnect failed: "+ ,"OPCSample",FinallyConnectedOPCServer =NothingResetControlStatus()EndTryEndIfEndSub(七):相关链接非常好的一个OPC技术网站OPC基金会网址国内的一个比较好的OPC网站(八):全部源码ImportsPublicClass Form1?Dim GlobalOPCServer As?DimWithEvents ConnectedOPCServer As?DimWithEvents ConnectedGroup As??Dim GlobalOPCItems(4)As?Dim GlobalOPCBlockItems(64)As???'枚举OPC服务器列表PrivateSub Form1_Load(ByVal sender As,ByVal e AsHandles?TryGlobalOPCServer=New()Dim ServerList AsObject=?For index AsShort=LBound(ServerList)ToUBound(ServerList)'加入控件列表中,注意这里使用LBound和UBoundNextIfThen=0EndIfResetControlStatus()'设置控件状态GlobalOPCServer=NothingCatch Ex As Exception ("ListOPCserversfailed:"+,"OPCSample",?EndTryEndSub?'连接到指定的OPC服务器PrivateSub btnConnectServer_Click(ByVal sender As,ByVal e AsHandles?If<>""ThenConnectedOPCServer=New()Try?'设置组集合的默认属性True'添加组=3*1000'刷新虑,用于下面的DataChange事件=True'使用订阅功能'添加项RefreshServerStatus()'刷新服务器状态Catch ex As ExceptionConnectedOPCServer=Nothing ("OPCserverconnectfailed:"+,"OPCSample",?EndTryResetControlStatus()EndIfEndSub?'服务器断开事件通知PrivateSub OnServerShutDown(ByVal Reason AsString)Handles?btnDisconnectServer_Click(Nothing,New EventArgs())EndSub?PrivateSub OnGroupDataChange(ByVal TransactionID AsInteger,ByVal NumItems A sInteger,ByRef ClientHandles As,ByRef ItemValues As,ByRef Qualities As,ByRef TimeStamps AsHandles?For i AsInteger=1To NumItemsIfThenSelectCase ClientHandles(i)Case2=CStr(ItemValues(i))Case200'测试7张卡片=CStr(ItemValues(i))Case201=CStr(ItemValues(i))Case202=CStr(ItemValues(i))Case203=CStr(ItemValues(i))Case204=CStr(ItemValues(i))Case205=CStr(ItemValues(i))Case206=CStr(ItemValues(i))Case207=CStr(ItemValues(i))CaseElse?EndSelect?EndIfNextEndSub??'断开到指定OPC服务器的连接PrivateSub btnDisconnectServer_Click(ByVal sender As,ByVal e AsHandles?IfNot(ConnectedOPCServer IsNothing)ThenTry()Catch ex As Exception ("OPCserverdisconnectfailed:"+,"OPCSample",?FinallyConnectedOPCServer=NothingResetControlStatus()EndTryEndIfEndSub'开卡,并返回卡号PrivateSub btnOpenCard_Click(ByVal sender As,ByVal e As?If ConnectedGroupIsNot NothingThenTry'准备参数数组Dim ServerHandles(1)AsIntegerDim ServerValues(1)AsObjectDim ServerErrors As?ServerHandles(1)=GlobalOPCItems(0).ServerHandleServerValues(1)=1'写入值,用于执行OpenCard的操作(1,ServerHandles,ServerValues,ServerErrors)If ServerErrors(1)<>0ThenMsgBox("OpenCardError:"&ServerErrors(1))EndIfServerHandles(1)=GlobalOPCItems(2).ServerHandleDim ServerResult As?'读取卡号If ServerErrors(1)<>0ThenMsgBox("ReadCardNoError:"&ServerErrors(1))Else=ServerResult(1)EndIfCatch ex As Exception ("OPCserverOpenCardfailed:"+,"OPCSample",?EndTryResetControlStatus()EndIfEndSub'读取卡片指定的块号的值PrivateSub btnReadCard_Click(ByVal sender As,ByVal e As?IfNot(ConnectedGroup IsNothing)ThenTry'获取块号Dim BlockNo AsShort=CByte'如果要获取数据的块所对应的项还没有创建,就创建它If GlobalOPCBlockItems(BlockNo)IsNothingThenCStr(BlockNo),200+BlockNo) EndIf'准备参数数组Dim ServerResults As?Dim ServerErrors As?Dim ServerHandles(1)AsIntegerServerHandles(1)=GlobalOPCBlockItems(BlockNo).ServerHandle'读取值If ServerErrors(1)<>0ThenMsgBox("ReadCardFailed:"&ServerErrors(1))Else=ServerResults(1)EndIfCatch ex As Exception ("OPCserverReadCardfailed:"+,"OPCSample",?EndTryEndIfEndSub'写卡片指定块的值PrivateSub btnWriteCard_Click(ByVal sender As,ByVal e As?IfNot(ConnectedGroup IsNothing)ThenTry'获取块号Dim BlockNo AsShort=CByte'如果要写入数据的块所对应的项还没有创建,就创建它If GlobalOPCBlockItems(BlockNo)IsNothingThenCStr(BlockNo),200+BlockNo) EndIf'准备参数数组Dim ServerValues(1)AsObjectDim ServerErrors As ArrayDim ServerHandles(1)AsIntegerServerHandles(1)=GlobalOPCBlockItems(BlockNo).ServerHandle ServerValues(1)=?'写入值(1,ServerHandles,ServerValues,ServerErrors)If ServerErrors(1)<>0ThenMsgBox("WriteCardFailed:"&ServerErrors(1))ElseMsgBox("WriteCardSucceed")EndIfCatch ex As Exception ("OPCserverWriteCardfailed:"+,"OPCSample",?EndTryEndIfEndSub'重设控件状态PrivateSub ResetControlStatus()If ConnectedOPCServer IsNothingThen=True=False=False=False=False=False=0=0=""="00000000000000000000000000000000"=""=""=""=""=""=""=""=""=""Else=False=TrueIf=""Then=False=False=True=FalseElse=True=True=True=TrueEndIfEndIfEndSub'刷新服务器状态属性信息PrivateSub RefreshServerStatus()If ConnectedOPCServerIsNot NothingThenWith?=CStr(.Count)=CStr(.DefaultGroupDeadband)If.DefaultGroupIsActive Then="True"Else="False"EndIf=CStr(.DefaultGroupLocaleID)=CStr(.DefaultGroupTimeBias)=CStr(.DefaultGroupUpdateRate)EndWithEndIfEndSub'关闭卡片PrivateSub btnCloseCard_Click(ByVal sender As,ByVal e As?If ConnectedGroupIsNot NothingThenTryDim ServerHandles(1)AsIntegerDim ServerValues(1)AsObjectDim ServerErrors As?ServerHandles(1)=GlobalOPCItems(1).ServerHandleServerValues(1)=1(1,ServerHandles,ServerValues,ServerErrors) If ServerErrors(1)<>0ThenMsgBox("CloseCardError:"&ServerErrors(1)) EndIfCatch ex As Exception ("OPCserverCloseCardfailed:"+,"OPCSample",?EndTryEndIfEndSubEndClassPrerequisites: ComboBox control named cbbServerList, Button1 and Button2 on Form1.Code BlockPublicClass Form1Dim GlobalOPCServer AsDimWithEvents ConnectedOPCServer AsDimWithEvents ConnectedGroup AsPrivateSub Form1_Load(ByVal sender As,ByVal e AsHandlesTryGlobalOPCServer =New()Dim ServerList AsObject=For index AsShort= LBound(ServerList)To UBound(ServerList)NextIfThen= 0EndIfGlobalOPCServer =NothingCatch Ex As Exception("List OPC servers failed: "+ ,"OPCSample",EndTryEndSub' Connect to OPC serverPrivateSub Button1_Click(ByVal sender As,ByVal e AsHandlesIf <>""ThenConnectedOPCServer =New()Try'Set property for Group connectionTrue'Add group= 3 * 1000=True'Add items"", 0)"", 1)"", 2)Catch ex As ExceptionConnectedOPCServer =Nothing("OPC server connect failed : "+ ,"OPCSample",EndTryEndIfEndSub' Disconnect to OPC serverPrivateSub Button2_Click(ByVal sender As,ByVal e AsHandles IfNot(ConnectedOPCServer IsNothing)ThenTry()Catch ex As Exception("OPC server disconnect failed: "+ ,"OPCSample", FinallyConnectedOPCServer =NothingEndTryEndIfEndSubEndClassHierarchyThe OPC server and the client application communicate each other through the interface of COM. The root class is OPC server object, and it accesses the group object and the item object by using this device datas of PLC (ex. 'X0' and 'D0' etc.) are constructed at the low hierarchy, and you can access the device datas as the unit of item or collection.?Register OPC automation dllWhen the OPC server is set up, DLL necessary for OPC is automatically registered. For access to OPC Server from Visual Basic, it needs to check "OPC Automation ".?Declare OPC Objects (OPC Server / OPC Group / OPC Item)For hooking events of OPC Server, add to "WithEvents" in dimension statement or event handler named "OBJECTNAME_EVENTNAME".Dim WithEvents Myserver As OPCServerDim WithEvents Mygroup As OPCGroupDim WithEvents Mygroups As OPCGroupsDim Myitem As OPCItemDim Myitems As OPCItemsDim MyBrowser As OPCBrowserIt is able to get installed OPC Server name by using OPC Server object. In this sample, it shows OPC Server name in list box and operator can select the target server.Dim Getserver As OPCServerDim Servers As VariantSet Getserver = New OPCServerServers =For i = LBound(Servers) To UBound(Servers)Servers(i)Next iSet Getserver=NothingIt is able to get device name registered in OPC Server by using OPC Server object. You can make the Group under device and OPC Serverobject is enabled to access this lower layer.?Set Myserver = New OPCServer,Set MyBrowser =Dim bname As VariantFor Each bname In MyBrowser"+" & bnameNext nameFor accessing client application to physical device data, it needs to generate OPC Group object in OPC group collection. The OPC Groupobject can configure update interval of tags. Normally, the device of accessing same cycle will register in same group. Also, you should becarefully CPU performance to create over groups because OPC Server create a thread for each group.?Dim ClientHandles(16) As LongDim OPCItemIDs(16) As StringSet Mygroups =Set Mygroup = ("Group1")= "1000"= FalseFor i = 1 To 16ClientHandles(i) = iOPCItemIDs(i) = "Device1" + ".D" + Format(i)Next iSet Myitems =16, OPCItemIDs, ClientHandles, ItemServerHandles, ItemServerErrors= TrueImplements event handler of OPC Group object for advice mode. The OPC Server read data for each cycle and if changing the value, callback to client application. The quality flag is normally '0xC0', when occurred error, it will be turn to other value.?= TruePublic Sub Mygroup_DataChange(ByVal TID As Long, _ByVal NumItems As Long, Chd() As Long, ItemValues() As Variant, _Qualities() As Long, TimeStamps() As Date)For i = 1 To NumItemsItemValues(i) + ":" + TimeStamps(i) + _":" + Qualities(i)Next iEnd SubThe OPC has two ways of data access, Synchronize and Asynchronous. In Synchronize, the client application must be wait for completing server work. But the client application can confirm server transaction is normally completed because the OPC Server returns the result on completing the communication work. This is a normally style of procedure.In Asynchronous mode, the OPC Server turns the handle to client as soon as receiving the request and proceed the transaction on background. After completing this work, calls handler of client application. Asynchronous mode cut down wait time for communication and be able to run client application.Caution: Asynchronous access is enabled under advice mode.?'Sync ReadOPCDevice, 16, ItemServerHandles, ItemValues, ItemServerErrors, ItemQualities, ItemTimeStampsFor i = 1 To 16ItemValues(i) + ":" + ItemTimeStamps(i) + ":" + ItemQuality(i)Next i'Sync WriteFor i = 1 To 16ItemVal(i) = iNext i16, ItemServerHandles, ItemVal, ItemServerErrorsFor i = 1 To 16If ItemServerErrors(i) <> 0 ThenMsgBox "Write ERROR " + Format(i)End IfNext i'Async Read(TransactionID=10, CancelID=11)16, ItemServerHandles, ItemServerErrors, 10, 11Private Sub Mygroup_AsyncReadComplete(ByVal TransactionID As Long, ByVal NumItems As Long, _ClientHandles() As Long, ItemValues() As Variant, Qualities() As Long, _TimeStamps() As Date, Errors() As Long)"AsyncRead Comp" + Chr$(9) + Time$ + Chr$(13) + Chr$(10)End Sub'Async WriteDim ItemVal(ItemCount) As VariantFor i = 1 To ItemCountItemVal(i) = iNext i16, ItemServerHandles, ItemVal, ItemServerErrors, 100, 101Private Sub Mygroup_AsyncWriteComplete(ByVal TransactionID As Long, _ ByVal NumItems As Long, ClientHandles() As Long, Errors() As Long)"AsyncWrite Comp" + Chr$(9) + Time$ + Chr$(13) + Chr$(10)End SubIn cache read operation, OPC Server doesn't access the physical device and return the last data on memory. The OPC Server read and caches the value every each will be able to access on high speed if not need newest value.OPCCache, 16, ItemServerHandles, ItemValues, ItemServerErrors, ItemQualities, ItemTimeStampsFor i = 1 To 16ItemValues(i) + ":" + ItemTimeStamps(i) + ":" + ItemQuality(i)Next iI am trying to develop an opc - da client using technology.?Have gone through the documents on opc and opc client and all,?but am still not sure how to implement it, can someone give me a direction on how to start with it59 Answers Foundcan you please provide some additional details on exactly what you're trying to do and any other relevant info that I can pass on to our support engineerthanks,-brenda (ISV Buddy Team)Hey Ksona,I was just speaking to a college of mine about DA cleints this morning. Have your checked out the Exchange atI know that Eric Murphy is an OPC genius, and he can probably you a hand, or point you in a great direction.You can also email me and I can see if one of my college's has sometime to help you out I'm curious as to what devices you are trying to accessGenius That's a wee bit over the top, let's just say I've experienceda thing or two about OPC. However, if you're fishing for a response, flattery will get you everywhere :)As the other replies pointed out, the question is a bit open ended.'using .NET technology' offers a few possibilites, depending on your develpoment language C#, , managed C++, etc.The easiest way, would be to make use of the OPC .NET wrapper supplied by the OPC Foundation. You do have to be a member to access this, however that offers other advantages such as invitations to the OPC Interoperabilty events to test your client against other vendors.If that's not an option, I have seen applications that make use of the OPC Automation dll. This was originally intended for VB apps, but some vendors have upgraded the automation interface to work with You would have to ask specifically because not all versions do.Otherwise, you are looking at writing an application that interfaces to unmanaged COM interfaces. From an programatic point of view, an OPC client would be no different from any other COM client. If you're new to OPC, this is not a trivial task...Hey Ksona,I agree with what Eric Murphy said, that your best bet is to get the libraries off of theHi Eric,Sounds like you know what you're talking about ... Can I also butter you up and find out if you know anything about using an interface in that was designed for VB6. The problem is the that Rockwell use to interface to their OPC server (RSlinx). It only accepts Arrays with lower bounds of 1 which is not possible in . (seerefs below)I only dimly understand the article on . It seems to be saying that if I was using VC++ I could write some kind of code which would make be able to use the OPC interface which was COM and written for VB6. If I was using C++ I'd be laughing.I'm not. :-)... and while the C++is interesting and gives me hope, I'm working with and I'm still trying to figure out how I can use the OPC interface designed for VB6 with . Why do I even need If OPC is astandard, can I not just use any OPC interface and hope that RSLinx (the Rockwell OPC server) answers with the right data Is there not a "General" OPC interface dllPuzzled from LeicesterAndrew SmithYou can use or c# with rslinx's COM dll.You just add the reference to to your project and use its classes.To pass an array to a OPC method, just dim the array to n+1 and fill it starting at index 1.The method will return object arrays that you will read starting at index 1.You have to cast to the specific types to get the values.Excuse me for my bad grammar.I hope this helps.I was looking for some help developing a C# OPC using the OPCAutomation wrapper when I stumbled upon your conversation. Here is a link to a sample OPC client that helped shed some light onusing .Net toThanks Everyone,Right now, i am using Advasol opc clientcomponents for my client development. It looks ok till now :)Andrew, Perrakus is correct in his discription on using the Automation dll with . Once you add the reference, you can access all the classes just like in VB6. Since doesn't seem to support the 'Option Base 1' you will have to handle the offset yourself. A little bit of background on the Automation wrappers. There actually is a "General" interface dll. It's called the Automation Wrapper, or . When the first OPC DA specifications were released, the OPC Foundation did not wishto support complied applications, so the source code for the was supplied to all OPC members. Each vendor then recompiled the codeunder their own GUID(Rockwell renamed it . In November of 2005, the OPC Foundation decided to take the responsibility of maintainingvarious applications (DA Wrapper, Compliance tests, proxy stubs etc). All the bug fixes various vendors had applied over the years was compiled and the OPC Foundation released the 'official' . Manyvendors already were supporting 'their' wrapper so continue to shipthe vendor branded version. Version of the automation wrapper hasbeen tested with on Win2000 and WinXP. You can read the details onthe Foundation website at If you are an OPC Foundation member you can download the files directly. If you are an end user, you need to getthe binaries from your OPC Vendor (I assume it's Rockwell in your case) Cheers and Good Luck. EricWhen i try add an Opc group, i get te following error message:Opc Server add group failed with exception: Unable to cast object of type '' to type ''Does anyone help mePost your code here to have a look at it, leandroAre you using a reference to COM OPC?Altough the exception is very clear.I have the same problem .I am using this sample code ( anybody have a solution for thisThe link you posted doesn't work.Post the code in this forum.Sorry , this one should workHere a sample of the code:'--- connect OPCServerOPCMyServer = New, "")OPCMyGroups = ' !!!!!!!!!!!!! << The problemhappens in this line "Group1") ' ("Group1")= Val ' UpdateRate is 1000msec= False=OPCMyItems =Martin, you've run into a problem that many have faced. It stems from the fact that the OPCGroups method doesn't work quite the way the OPC Foundation describes. It has something to do with a misdirected reference in the original C code or something like that. If you're really interested in the why's there a lot of people and sites that can explain it better. But anyway, I ended up solving it by a bit of slight of hand. In the declarations portion of my application I putthe definitions shown below. I'm not sure why it works better this way (I do a lot of trial and error programming) but it does for me:' Initialization for the OPC Class functionsDim WithEvents AnOPCGroup As OPCGroupDim AnOPCServer As OPCServerDim AnOPCItem As OPCItemThen, in its own Sub:Private Sub AnOPCSetup(ByVal Signal As String, ByVal i As Long)Set AnOPCServer = New OPCServer' Connect to the OPC Server, setup our Group,' set the group to Active and Subscribed' Required for Update on Change' Add the tagsPaul,thanks for your tried your sample code ,but it doesn't work for me. I made several programs in VB5/6 and never had a problem like am using VB2005 ,i tested your sample as following:Dim AnOPCGroup AsDim AnOPCServer AsDim AnOPCItem AsConst Opcserver_ID = ""Const OPCNode_ID = ""'local serverPublicSub AnOPCSetup(ByVal Signal AsString, ByVal i AsLong) AnOPCServer = New' Connect to the OPC Server, setup our Group,' set the group to Active and Subscribed(Opcserver_ID, OPCNode_ID)"Group1") <<< !!!!= True= True' Required for Update on Change' Add the tagsEndSubWhen i try to add a group te error appears....think i go back to VB6 again........Hi Martin,What version og the are you using ....I am using Siemens OPC DAAutomationHi Martin.MichaelHi Michael Jensen.Could you please send the .NET API to me I am studying how to connect OPC server using visual studio 2005. I am not a member of opcfoundation.Thanks.KevoHi MichaelI'm a student trying to an OPCDear Michael,i am not member of the foundation,but i would be very glad if you could send it to me am using also Visual Studio 2005.Hi Michael,Likethe other guys,I have been using OPCSiemensDAAutomation in VB6 and I've got the same problems in .Would you mind to end me the dll My e-mail address isThanks in advance.Hi Michael,That is one dificult to find.i registered but i not a member in opcfoundation.Thanks mansamples they have will help out with your interfaces.Martin Brasil,Sorry it took me so long to get back to this thread. Things got chaotic after the last time I answered. I don't know if you've gotten an answer yet but what I was trying to point out in my inept way was the "WithEvents" keyword in the OPCGroups declaration. As I said before, I'm not sure why it works with it and not without but I've had success both in VB6 and in .Net since I started using it. I believeit's because the OPC dll calls use the object handles asidentification for Groups and Items.I think it was originally Eric Murphy at Matrikon that pointed the correct for me. You should try contacting Matrikon directly. They've got a ton of very useful tools for building and troubleshooting just about anything you can think to create. On top of that they are very helpful in answering questions. They had the answer for my application problems in a matter of minutes.HiStill did not found the OPCNetApi. Is it possible to send this to meI'm getting desperate.ThanksStanleyHi Stanley!Did you solved this problemI've the same.Any helpOsvaldo。

相关文档
最新文档