1. 程式人生 > >用C#開發基於自動化接口的OPC客戶端

用C#開發基於自動化接口的OPC客戶端

pub alt span conn 自定義 ted mov errors 寫代碼

OPC全稱是Object Linking and Embedding(OLE) for Process Control,它的出現為基於Windows的應用程序和現場過程控制應用建立了橋梁。OPC作為一整套接口、屬性和方法的協議標準集,與具體的開發語言沒有關系。

1OPC客戶端接口方式

開發OPC客戶端程序,其訪問接口方式有多種,根據官方提供的資料大約有如下幾種方式:

  • 使用OPCNetAPI,需要用到OPCNetAPI.dll,OPCNetAPI.Com.dll
  • 使用自動化接口,需要用到OPCDAAuto.dll
  • 使用自定義接口,需要用到多個Wrapper:OpcRcw.Ae.dll,OpcRcw.Batch.dll,OpcRcw.Comn.dll,OpcRcw.Da.dll,OpcRcw.Dx.dll,OpcRcw.Hda.dll,OpcRcw.Sec.dll

對於像C++這樣的語言來開發OPC客戶端時,一般需要使用自定義接口的方式。而如果采用VB和C#這樣的語言來開發OPC客戶端時,一般就采用自動化接口。要使用OPC自動化接口,首先要引用OPCDAAuto.dll文件,並在開發環境中做好相關的引用配置。

2、自動化接口簡介

自動化接口是OPC基金會組織為了方便並統一OPC客戶端開發而發布的一個接口、屬性和方法的協議集。其訪問服務器的流程如下:

技術分享

自動化接口中共定義了6類對象:OPCServer對象、OPCBrowser對象、OPCGroups對象、OPCGroup對象、OPCItems對象、OPCItem對象。接下來簡要描述一下這些對象的主要功能。

1)、OPCServer對象

由客戶端創建的OPCServer自動化對象。然後客戶端通過其方法實現連接到OPC數據訪問自定義接口。OPCServer對象現在可以用來獲取關於OPC服務器的一般信息,並創建和操作OPCGroup對象的集合。

主要的屬性:

StartTime

CurrentTime

LastUpdateTime

MajorVersion

MinorVersion

BuildNumber

VendorInfo

ServerState

LocaleID

Bandwidth

OPCGroups

PublicGroupNames

ServerName

ServerNode

ClientName

主要的方法:

GetOPCServers

Connect

Disconnect

CreateBrowser

GetErrorString

QueryAvailableLocaleIDs

QueryAvailableProperties

GetItemProperties

LookupItemIDs

2)、OPCBrowser對象

OPCBrowser對象是在服務器中存在的分支或項目名稱的集合。其是可選的。如果服務器不支持,將不會創建這個對象。

主要的屬性:

Organization

Filter

DataType

AccessRights

CurrentPosition

Count

主要的方法:

Item

ShowBranches

ShowLeafs

MoveUp

MoveToRoot

MoveDown

MoveTo

GetItemID

GetAccessPaths

3)、OPCGroups對象

OPCGroups是OPCGroup對象的集合,以及創建、刪除和管理它們的方法。

該對象還具有OPCGroup默認屬性。當添加OPCGroups時,DefaultGroupXXXX屬性設置其初始狀態。可以更改默認值,以添加具有不同初始狀態的opc組。更改默認值並不會影響已經創建的組。添加OPCGroup後,它的屬性可以被修改。這減少了調用Add方法所需的參數數量。

主要的屬性:

Parent

DefaultGroupIsActive

DefaultGroupUpdateRate

DefaultGroupDeadband

DefaultGroupLocaleID

DefaultGroupTimeBias

Count

主要的方法:

Item

Add

GetOPCGroup

Remove

RemoveAll

ConnectPublicGroup

RemovePublicGroup

4)、OPCGroup對象

OPC組為客戶組織數據提供了一種方式。例如,組可能表示特定操作符顯示或報告中的項。數據可以讀寫。基於異常的連接也可以在客戶端和組中的項之間創建,可以根據需要啟用和禁用。OPC客戶機可以配置OPC服務器應該向OPC客戶機提供數據更改的速率。

主要的屬性:

Parent

Name

IsPublic

IsActive

IsSubscribed

ClientHandle

ServerHandle

LocaleID

TimeBias

DeadBand

UpdateRate

OPCItems

主要的方法:

SyncRead

SyncWrite

AsyncRead

AsyncWrite

AsyncRefresh

AsyncCancel

5)、OPCItems對象

這個對象還具有OPCItem默認的屬性。當添加OPCItem時,DefaultXXXX屬性設置其初始狀態。可以更改默認值,以添加具有不同初始狀態的OPCItems。當然,一旦添加了OPCItem,它的屬性可以被修改。這減少了調用Add方法所需的參數數量。

主要的屬性:

Parent

DefaultRequestedDataType

DefaultAccessPath

DefaultIsActive

Count

主要的方法:

Item

GetOPCItem

AddItem

AddItems

Remove

Validate

SetActive

SetClientHandles

SetDataTypes

6)、OPCItem對象

OPC項表示與服務器中的數據源的連接。與每個項目相關聯的是一個值,質量和時間戳。值以變量的形式出現,質量類似於Fieldbus指定的值。

主要的屬性:

Parent

ClientHandle

ServerHandle

AccessPath

AccessRights

ItemID

IsActive

RequestedDataType

Value

Quality

TimeStamp

CanonicalDataType

EUType

EUInfo

主要的方法:

Read

Write

3、客戶端的開發

接下來我們基於C#開發OPC客戶端。上面說明了自動化接口具體情況,我們需要進一步針對自己的具體應用編寫代碼。

首先,封裝一斜對象、用於存取相關的屬性,如:OPC服務器信息(OPCServerInfo)、OPC數據項(OPCDataItem)、組屬性(GroupProperty)等。對於組屬性我們還需要賦予默認值。代碼如下:

public class OPCServerInfo

    {

        public DateTime StartTime { get; set; }

        public string ServerVersion { get; set; }

    }

 

    public class OPCDataItem

    {

        public object ItemName { get; set; }

        public object ItemValue { get; set; }

        public object Quality { get; set; }

        public object TimeStamp { get; set; }

    }

 

    public class GroupProperty

    {

        public bool DefaultGroupIsActive { get; set; }

        public float DefaultGroupDeadband { get; set; }

        public int UpdateRate { get; set; }

        public bool IsActive { get; set; }

        public bool IsSubscribed { get; set; }

 

        public GroupProperty()

        {

            DefaultGroupIsActive = true;

            DefaultGroupDeadband = 0;

            UpdateRate = 250;

            IsActive = true;

            IsSubscribed = true;

        }

    }

接下來,為了使用方便我們封裝了一個ClientHelper類用於實現相關的操作,應為在一個客戶端應用中,該對象是唯一的我們為了使用方便將其聲明為靜態類,以便於使用。具體代碼如下:

    public class ClientHelper

    {

        /// <summary>

        /// 獲取可以使用的OPC服務器

        /// </summary>

        /// <param name="hostName">獲取OPC服務器的主機名稱</param>

        /// <returns>返回OPC服務器列表</returns>

        public static List<string> GetOPCServerName(string hostName)

        {

            try

            {

                OPCServer OpcServer = new OPCServer();

                object opcServers = OpcServer.GetOPCServers(hostName);

                List<string> serverList = new List<string>();

                foreach (string opcServer in (Array)opcServers)

                {

                    serverList.Add(opcServer);

                }

                return serverList;

            }

            catch(Exception ex)

            {

                throw ex;

            }

        }

 

        /// <summary>

        /// 連接到指定的OPC服務器

        /// </summary>

        /// <param name="serverName">服務器名稱</param>

        /// <param name="serverIP">服務器IP</param>

        /// <returns>返回的OPC服務器</returns>

        public static OPCServer ConnectToServer(string serverName, string serverIP)

        {

            OPCServer opcServer = new OPCServer();

            try

            {

                opcServer.Connect(serverName, serverIP);

                if (opcServer.ServerState != (int)OPCServerState.OPCRunning)

                {

                    opcServer.Disconnect();

                    return null;

                }

            }

            catch

            {

                opcServer.Disconnect();

                return null;

            }

            return opcServer;

        }

 

        /// <summary>

        /// 獲取OPC服務器的相關信息

        /// </summary>

        /// <param name="opcServer">OPC服務器對象</param>

        /// <returns>OPC服務器信息</returns>

        public static OPCServerInfo GetServerInfo(OPCServer opcServer)

        {

            OPCServerInfo serverInfo = new OPCServerInfo();

            serverInfo.StartTime=opcServer.StartTime;

            serverInfo.ServerVersion = opcServer.MajorVersion.ToString() + "." + opcServer.MinorVersion.ToString() + "." + opcServer.BuildNumber.ToString();

            return serverInfo;

        }

 

        /// <summary>

        /// 展開OPC服務器的節點

        /// </summary>

        /// <param name="opcServer">OPC服務器</param>

        /// <returns>返回展開後的節點數據</returns>

        public static OPCBrowser RecurBrowse(OPCServer opcServer)

        {

            OPCBrowser opcBrowser = opcServer.CreateBrowser();

            //展開分支

            opcBrowser.ShowBranches();

            //展開葉子

            opcBrowser.ShowLeafs(true);

            return opcBrowser;

        }

 

        public static OPCGroup CreateGroup(OPCServer opcServer, OPCItems opcItems, string opcGroupName, GroupProperty groupProperty)

        {

            try

            {

                OPCGroup opcGroup = opcServer.OPCGroups.Add(opcGroupName);

 

                opcServer.OPCGroups.DefaultGroupIsActive = groupProperty.DefaultGroupIsActive;

                opcServer.OPCGroups.DefaultGroupDeadband = groupProperty.DefaultGroupDeadband;

                opcGroup.UpdateRate = groupProperty.UpdateRate;

                opcGroup.IsActive = groupProperty.IsActive;

                opcGroup.IsSubscribed = groupProperty.IsSubscribed;

 

                //opcGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OpcGroupDataChange);

                //opcGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete);

                //opcItems = opcGroup.OPCItems;

                return opcGroup;

            }

            catch (Exception err)

            {

                throw err;

            }

        }

    }

最後就是使用前述的封裝。

用C#開發基於自動化接口的OPC客戶端