您的位置:首页 > 运维架构

利用WTOPCSvr DLL 开发OPC服务器指南(英文原版),空的时候再翻译了...很实用

2013-10-23 16:57 741 查看

WTOPCSvr DLL User’s Guide

The WinTECHSoftware Rapid Development DLL for OPC Servers, (WTOPCSvr), provides an easy touse API for integrating custom data with OPC. All the details of COM and OPC are handled by the DLL, which allows anapplication to present data points to OPC at a high-level,
without having to beconcerned with the actual implementation of the underlying interfaces. The DLL may be easily integrated withexisting applications, or new ones. Allrequired OPC Interfaces are supported for both OPC 1.0 and OPC 2.0 Data AccessStandards
as well as the Browse Interface.

WTOPCSvrbasically operates as a data librarian. The controlling application creates Process Tags by passing a name andvalue to the DLL. The DLL records thedata point and makes it available to any OPC Client application by name. The controlling application
may change thevalue of the data at any time, and all attached clients would be automaticallynotified. Callback notification isprovided for any Process Tag that is modified by an OPC Client connection. (The application has control over which tagsare OPC_WRITEABLE.)

WTOPCSvr nowsupports dynamic creation of OPC Tags. Acallback function is supplied which returns control to the application if aclient requests a tag that has not been previously defined. The application may in turn create the tagusing the requested path
and name combination or ignore the request.

Creating a CustomOPC Server using WTOPCSvr.DLL

Installing the OPC Proxy DLL’s

The first stepin creating an OPC Server is to obtain and install the OPC Proxy/Stub DLL’sfrom OPCFoundation (http://www.opcfoundation.org)

Download and upzip the proxy/stub files.
Copy opccomn_ps.dll, opcproxy.dll, opcae_ps.dll, opchda_ps.dll to the SYSTEM32 Directory. *Be sure not to overwrite any newer versions*
Type REGSVR32 opccomn_ps.dll
Type REGSVR32 opcproxy.dll
Type REGSVR32 opc_aeps.dll
Type REGSVR32 opchda_ps.dll

You will also need to download andinstall the OPC Server Browser Object supplied by the OPC Foundation. The OPC Foundation also advises that youverify that your system contains the actxprxy.dll and if not, install theActiveX Redistributable Installation
Kit from Microsoft. The aprxdist.zip file containing theMicrosoft software is also available from the OPC Foundation Web-Site.

Link WTOPCSvr.lib with the Application

WTOPCSvr.lib contains the exportdefinitions for the DLL’s API. Includethis file with the project files for the custom application and includeWTOPCSvrAPI.h with those modules which will be making calls into the DLL.

Generate a new CLSID

Each OPC Serveris identified by a unique CLSID. TheGUIDGen.exe utility supplied by Microsoft may be used to generate a uniqueidentifier for the new server application. Run GUIDGen.exe, (located in the Visual C++\Bin directory). Generate a new CLSID and
copy to theclipboard to be pasted in to your server application as described below.




Registry Entries

The WTOPCSvr.DLL exports two APIfunctions that make modifications to the Windows Registry for installation ofthe custom server.

UpdateRegistry(BYTE *pCLSID_Svr, LPCSTR Name, LPCSTR Descr, LPCSTR ExePath);

UnregisterServer(BYTE *pCLSID_Svr, LPCSTR Name);

These functionstake as arguments the CLSID generated above, (as well as text strings toidentify and describe the new server). While the UpdateRegistry and UnregisterServer functions may be calledfrom the controlling application at any time, it is generally
preferred toimplement the registry functions based on command-line entries during start-upof the application. A self-registeringserver would process the \RegServer and \UnregServer command line optionssimilar to the code below, (extracted from OPCSimSvr Application):

const GUID

CLSID_OPCSimSvr= {0x99b8f471, 0xc027, 0x11d2, {0x80, 0xb8, 0x0, 0x60, 0x97, 0x58, 0x58,0xbe}};

BOOLCOPCSimSvrApp::InitInstance()

{

TCHAR szTokens[]= _T("-/ ");

CString HelpPath;

CString SvrName,SvrDescrip;

int i;

HelpPath = AfxGetApp()->m_pszHelpFilePath;

i = HelpPath.ReverseFind('\\');

HelpPath = HelpPath.Left(i+1);

HelpPath += "OPCSIMSVR.EXE";

//

// Self-Registration code

// (look for cmdline options to register &unregister server)

//

SvrName = "WinTECH.OPCServer";

SvrDescrip = "WinTECH Software OPC ServerSimulator";

CString tempCmdLine(m_lpCmdLine);

LPTSTR lpszToken =_tcstok(tempCmdLine.GetBuffer(1), szTokens);

while (lpszToken != NULL)

{

if (_tcsicmp(lpszToken,_T("UnregServer"))==0)

{

UnregisterServer ((BYTE*)&CLSID_OPCSimSvr, SvrName);

return (FALSE);

}

else if (_tcsicmp(lpszToken,_T("RegServer"))==0)

{

UpdateRegistry ((BYTE*)&CLSID_OPCSimSvr,

SvrName,

SvrDescrip,

HelpPath);

return (FALSE);

}

lpszToken = _tcstok(NULL, szTokens);

}

Initialization of WTOPCSvr.DLL


The Windows Registration functionsdescribed above may be called prior to the initialization of theWTOPCSvr.DLL. During theself-registration process, the focus is on making the necessary changes to theRegistry and then exiting the application. There is no
need at this point to go through the effort of initializingDCOM and loading up the OPC Server support. The exported function:

InitWTOPCsvr(BYTE *pCLSID_Svr, UINT ServerRate);

does just that. When this function is executed, the DLLperforms all necessary initialization of COM/DCOM and creates the OPCServerInterface object to be used for client connections. The specified ServerRate defines how fast theOPC Client data connections
are refreshed.

Creating Process Tags

Afterinitialization, the WTOPCSvr.DLL is now ready to accept data points from thecustom application. Three exportedfunctions are provided:

CreateTag (LPCSTR Name, VARIANT Value, WORD InitialQuality, BOOLIsWriteable);

UpdateTag (HANDLE TagHandle, VARIANT Value, WORD Quality);

UpdateTagByName (LPCSTR Name, VARIANT Value, WORD Quality);

SetWtOPCsvrQualifier (char Delimiter);

As each processtag is created, the DLL returns a HANDLE to identify the point for future references, (updates), from theapplication. The naming convention used by WTOPCSvr.DLL for browsingoperations, (OPC_NS_FLAT or OPC_NS_HIERARCHIAL), is a function of
how the namesare assigned by the controlling application. If segmented names are used to create the tags, (strings containing thedelimiter ‘.’,

such as “PLANTA.PROCESS1.TAG17”), WTOPCsvr.DLL will automatically configure the name space ashierarchial, otherwise a flat name space is used. If you want to use a delimiting characterother than ‘.’, you can select it using SetWtOPCsvrQualifier().

Dynamic TagCreation

If the designwarrants, WTOPCSvr.DLL may be used to provide for dynamic creation of OPC Tagsas requested by attached clients. Ratherthan create all the OPC Tags up-front, the application may choose to have theDLL issue a callback function whenever an OPC
Client requests a tag name thatis not already listed.

EnableUnknownItemNotification(UNKNOWNITEMPROC lpCallback);

If enabled, thecallback function will receive control anytime a client requests a tag that hasnot been previously defined. Therequested tag name and path may then be used as arguments to CreateTagA() todynamically create the tag before returning from the
callback and givingcontrol back to the client. If theapplication chooses to ignore the request, the client will receive aOPC_E_UNKNOWNITEMID response from the DLL.

WTOPCSvr.DLLalso supports a user callback function that indicates when the last clientreference to a tag has been removed. This may be used by the server application to delete the tag when it isno longer needed. The following exportedfunction enables this
functionality:

EnableItemRemovalNotification(ITEMREMOVEDPROC lpCallback);

The callbackwill receive the handle to the removed item, as well as the path and itemnames.

Write Callback Notification

If process tagsare created as OPC_WRITEABLE, attached client applications may change the valueof data points contained within WTOPCSvr.DLL. WTOPCSvr.DLL provides the ability for the controlling application todefine a callback routine for notification of
client writes. This would be required in most situations toallow the server application to accept the new value and perform the write tothe actual device.

EnableWriteNotification(WRITENOTIFYPROC lpCallback);

If enabled, the callback functionwill receive the HANDLE of any data point written by an attached OPC Client, aswell as the value to be written and a pointer to an error DWORD to allowfeedback to the client if the write operation fails

Clean-up Functions

The onlyremaining functions exported from WTOPCSvr.DLL provide the mechanism forgracefully closing the custom server.

intNumbrClientConnections ();

voidRequestDisconnect ();

RemoveTag(HANDLE TagHandle);

UninitWTOPCsvr();

Generally, the server logic shouldcheck to see if any OPC Clients are connected before allowing the applicationto close. OPC 2.0 clients may berequested to disconnect. Any tagscreated by the application should be removed using the defined function. The
UnintWTOPCsvr() function callsCoUnitialize and should be placed in the ExitInstance procedure of theapplication.

Performance Related Functions

Beginning withversion 4.0 of the WtOPCsvr.dll, there have been several extended API functionsadded to support more efficient updating for large item counts. The dll now supports an option to use hashingfor storage and lookup of text strings representing
item names. Significant performance gains are provided inthe areas of intensive string manipulation such as the item browsingfunctions. A second series of APIfunctions improves upon the data update cycle by updating multiple items with asingle command rather
than one at a time. The WtSvrTst2 example application that is packaged with the WtOPCsvr.dllmay be used to generate performance numbers using various tag counts andvarious combinations of these two options. Refer to the API descriptions below for detailed
information relative tothe use of these functions.




OPC Alarms & Events

The WtOPCsvr.dllprovides basic support for the Alarms & Events standard by providing levelchecking for each process tag. The dllwill automatically create an OPC A&E Server using the same CLSID as theData Access Server. As each tag iscreated, the controlling
application may specify two levels of high and lowalarm limits surrounding it’s value. Asa tag’s value is updated, either by the controlling application or by anattached client, the dll will check its value against these limits and generatethe appropriate
A&E messages if exceeded. These messages are accessible from any standard OPC A&E clientapplication. WtOPCsvr.dll also exportsfunctions that allow the controlling application to generate textual events toany interested client. Finally, ifgreater control
over A&E Server operation is desired, the application maydisable the internal limit checking and process all the A&E Interface callsfrom a client directly. A simplecallback object is provided that may be overridden by the application toprocess the individual
A&E Interfaces as required.

NT Security Additions

To accommodateOPC Server designs where it is desired to control access to certain tags basedon the identity of the connected user, WtOPCsvr.dll supports api functions thatallow a security mask to be applied for both read and write access toindividual tags.
The user may thendefine a list of user names with specific rights. When the security option is enabled,WtOPCsvr.dll will verify the access rights of the client against the severdefined user list and allow or deny access accordingly. Additionally, an extended
write callback isprovided that contains the user name of the client making a write requiest fora tag. This information may then be usedto maintain an audit trail of users who have updated a particular tag.




WTOPCSvr.DLL Exported functions



Initialization and Registry Functions

BOOL InitWTOPCsvr (BYTE *pCLSID_Svr, UINT ServerRate);

Use this function to initialize DCOM and create the OPC Server.

CLSID_Svr defines the CLSID which OPC Clients will use to connect to thisserver.

ServerRate is expressed in msecs and defines the rate at which clientconnections are updated.

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL UpdateRegistry (BYTE *pCLSID_Svr, LPCSTR Name, LPCSTR Descr, LPCSTR ExePath);

This function makes modificationsto the Windows Registry to allow other applications to find and execute theserver.

CLSID_Svr defines the CLSID which OPC Clients will use to connect to thisserver,

(this isa BYTE Pointer to the C-style GUID structure).

Name defines the Server Name

Descr may be anything to describe the server, and will usually containthe vendor name.

ExePath defines the full Windows Directory path to the executable (i.e.c:\OPC\test\mysvr.exe).

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL AddLocalServiceKeysToRegistry (LPCSTR Name);

This function makes additionalmodifications to the Windows Registry to allow the server to run as an NTService.

Name defines the Server Name

BOOL UnregisterServer (BYTE *pCLSID_Svr, LPCSTR Name);

This function removes entries fromthe Windows Registry.

CLSID_Svr defines the CLSID which OPC Clients will use to connect to thisserver.

Name defines the Server Name

The return value will be TRUEif the function succeeds, otherwiseFALSE.




TagCreation & Update Functions

HANDLE CreateTag (LPCSTRName, VARIANT Value, WORD InitialQuality, BOOL IsWriteable);

Thisfunction creates a process tag within WTOPCSvr.DLL.

Name defines the identifier that OPC Clients will use to access thetag. This name may be any string of textas required by the server. Segmentednames, (those containing the delimiter character ‘.’), are valid and will causeWTOPCSvr.DLL
to structure the OPC name space as hierarchial, for browsingoperations.

Value defines the initial data to be associated with the tag

InitialQuality defines the OPC Quality flags associated with the tag.

IsWriteable determines whether or not the tag may be written from an OPC Client

The return value will be a HANDLEto the created point or
INVALID_HANDLE_VALUE
if the tag could not be created.

BOOL SetTagProperties(HANDLE TagHandle, DWORD PropertyID, LPCSTR Description,

VARIANTValue);

Any number of OPC Item properties may be set for a defined tag withthis function. The DLL maintains a listof all defined properties and their current value for access by an OPC Client.

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL UpdateTag (HANDLETagHandle, VARIANT Value, WORD Quality);

BOOLUpdateTagWithTimeStamp (HANDLE TagHandle, VARIANT Value, WORD Quality, FILETIMEtimestamp);

Thisfunction allows the controlling application to change the value, quality flag,and timetstammp of a defined process tag. If thetimestamp is notsupplied by the application, the dll will use the current PC time setting.

TagHandle defines the point.

Value defines the new data.

Quality defines the new Quality condition

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL UpdateTagByName(LPCSTR Name, VARIANT Value, WORD Quality);

Thisfunction also allows the controlling application to change the value andquality flags of a defined process tag.

Name defines the point.

Value defines the new data.

Quality defines the new Quality condition

The return value will be TRUEif the function succeeds, otherwiseFALSE.

unsigned long SetHashing (unsigned longHashSize);

Enableshashing and sets the suggested hash table size.

BOOL StartUpdateTags();

BOOL WINAPI UpdateTagToList (HANDLE TagHandle, VARIANTValue, WORD Quality);

BOOL WINAPI EndUpdateTags();

These three functions must be used together, and provide a moreefficient means of updating multiple tags. UpdateTagToList replacesUpdateTag call, requires prior StartUpdateTags else fails and EndUpdateTagsafter all tags are updated.

BOOL SuspendTagUpdates(HANDLE TagHandle, BOOL OnOff);

This function may be used in conjunction with the Unknown Itemcallback to allow the server application to know when a particular tag is beingsubscribed to by a client. In mostcases, the server application willcontinuously update the tags as their respective
values change. The dll will then handle all client subscriptions,notifications and updates. In certainsituations, it’s desirable for the server to only update the OPC Tag databasewhenever a client is actively subscribing to an item. By suspending updates,
the dll will issue theUNKNOWNITEM callback whenever a client attempts to subscribe to the item. The server may then resume updates and waitfor the ITEMREMOVED callback to again suspend updates.

TagHandle defines the itemto be suspended.

OnOff suspends or resumesupdates. (The application should callSuspendTagUpdates (.., TRUE)

After the first UNKNOWNITEM notificationto prevent additional callbacks if another client subscribes to the same datapoint).

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL ReadTag (HANDLETagHandle, VARIANT *pValue);

BOOL ReadTagWithTimestamp(HANDLE TagHandle, VARIANT *pValue, WORD *pQuality,

FILETIME*pTimestamp);

Thisfunction allows the application to obtain the current value of a defined tagcontained within WTOPCSvr.DLL.

TagHandle defines the point.

pValue points to the buffer to receive the data.

pQuality points to a value to receive the OPC Quality indication.

pTimeStamp receives the current timestamp for the tag.

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL RemoveTag (HANDLETagHandle);

This function removes a processtag from the WTOPCSvr.DLL. If clientconnections are accessing the point when it is removed, the connection willremain valid, but no new data will be presented to the client.

TagHandle defines the point.

The return value will be TRUEif the function succeeds, otherwiseFALSE.



CallbackNotification Functions



BOOLEnableUnknownItemNotification (UNKNOWNITEMPROC lpCallback);

Thisfunction defines the callback routine that receives control from theWTOPCSvr.DLL whenever a client requests an OPC Tag that has not been previouslydefined.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORT UnknownTagProc (LPSTR Path, LPSTR Name)

Path defines the requestedpath name.

Name defines the requestedtag name.

BOOLEnableItemRemovalNotification (ITEMREMOVEDPROC lpCallback);

Thisfunction defines the callback routine that receives control from theWTOPCSvr.DLL whenever the last client reference to a defined tag is removed.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORT RemoveTagProc (HANDLE hTag, LPSTRPath, LPSTR Name)

hTag specifies the handleof the tag that has been removed.

Path defines the requestedpath name.

Name defines the requestedtag name.

BOOLEnableWriteNotification (WRITENOTIFYPROC lpCallback, BOOL ConvertToNativeType);

Thisfunction defines the callback routine which receives control from theWTOPCSvr.DLL whenever an OPC Client application writes to a defined processtag. Normally, the dll would beconfigured to convert values to the item’s native variant type, but in somecases
it may be desirable for the application itself to perform special conversionprocessing.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORTNotificationHandler (HANDLE handle,

VARIANT *pNewValue, DWORD *pDeviceError)

handle defines the handle of the process tag which was written.

pNewValue defines the value to be written. The application needs to write the new value to the actual device andcall UpdateTag to update the new value to the DLL cache.

pDeviceError allows the application to flag an error back to the client if thedata value cannoty be written.

BOOL EnableDisconnectNotification(DISCONNECTPROC lpCallback);

Thisfunction defines the callback routine which receives control from theWTOPCSvr.DLL whenever an OPC Client application disconnects.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORTDisconnectHandler (DWORD Numbr)

Numbr defines the the number of client connections remaining.

BOOL EnableEventMsgs(EVENTMSGPROC lpCallback);

Thisfunction allows the server application to receive event messages from theWtOPCsvr.dll during normal operation of the OPC Server Interfaces. Event messages are available as a debuggingtool to trace execution of the logic through the various Interface
procedures.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORT EventHandler(LPCSTR Msg)

Msg is a byte string describing the event.

BOOLEnableRateNotification (RATECHANGEPROC lpCallback);

Thisfunction defines a callback procedure that receives control whenever theminimum request update rate for an item changes. Various clients may request an item from theserver at different rates. This callbackallows the server application to optimize it’s
data acquisition logic to obtainthe data for an item at the most efficient rate.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORTRateChangeHandler (HANDLE hItem, DWORD Rate)

hItem defines the item.

Rate is the newly requested update rate.

BOOL EnableDeviceRead(DEVICEREADPROC lpCallback);

Thisfunction allows the application to supply a callback procedure to serviceDEVICE_READ requests from a client. Thecallback, if defined, will be called whenever a client requests aSyncIO::Read with dwSource set to OPC_DS_DEVICE. If the callback is not
defined, WtOPCsvr.dllwill treat OPC_DS_DEVICE as OPC_DS_CACHE

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORTDeviceReadHandler (HANDLE hItem, VARIANT *pValue,

WORD *pQuality, FILETIME *pTimestamp)

hItem defines the item.

*pValue, *pQuality, and*pTimestamp are to be supplied by the applicationto represent the current value of the defined item.




MiscellaneousFunctions

char SetWtOPCsvrQualifier (char qualifier);

This function sets the delimiting character used by the dll tosegment the node names of a hiearchial namespace. The default delimiter is the ‘.’ character.

int NumbrClientConnections();

This function returns the number of OPC Clients currently connectedto WTOPCSvr.DLL

void RequestDisconnect ();

Thisfunction requests that all OPC Clients disconnect from the server. This function does not guarantee that therequest will be honored, or that the clients will actually disconnect. The ability for an OPC Server to request aclient disconnect only applies
to those clients connected according to the OPC2.0 specification.

BOOL RefreshAllClients ();

This function may be used by the server application to initiate arefresh operation to all attached OPC Clients. Normally, client applications are refreshed based on an asynchronousclock tick within the WTOPCSvr.DLL. Thisfunction may be used to force the
server to update all client data.

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL ResetServerRate (UINTServerRate);

This function may be used by the server application to change thecurrent setting for the rate at which data is refreshed by the server.

The return value will be TRUEif the function succeeds, otherwiseFALSE.

BOOL SetVendorInfo (LPCSTRVendorInfoString);

The application may set the vendor information description that isreturned by the server in response to a client request for Server Information..

The return value will be TRUEif the function succeeds, otherwiseFALSE.

void SetServerState (OPCSERVERSTATE SvrState);

This function allows the application to set the state of the serveras accessed by a client. Useful duringdesign and commissioning to display internal diagnostics related to serveroperation.






Alarms& Events Functions

BOOL SetItemLevelAlarm(HANDLE TagHandle, int LevelID, float Limit, DWORD Severity,

BOOL Enabled);

Multiplelevels of alarms may be configured for each defined Tag. If enabled, WtOPCsvr will check the alarmlimits and notify any attached OPC Alarms & Events Client of level changesas an item is updated. LevelID refers tothe following literal definitions:

#define ID_LOLO_LIMIT 1

#define ID_LO_LIMIT 2

#define ID_HI_LIMIT 3

#define ID_HIHI_LIMIT 4

BOOL GetItemLevelAlarm (HANDLE TagHandle, intLevelID, float *pLimit, DWORD *pSeverity,

BOOL*pEnabled);

This function allows the application to retrieve the associatedalarm limits for a given Tag

BOOL UserAEMessage (LPCSTRMsg, DWORD Severity);

BOOL UserAEMessageEx(ONEVENTSTRUCT Msg);

BOOL UserAEMessageEx2(DWORD hEventSubscription, ONEVENTSTRUCT Msg, BOOL bRefresh, BOOLbLastRefresh);

Thesefunctions send a user-defined event message to all connected OPC Alarm &Event Clients.




CwtAExCallbackFunctions



The application can use theCWtAExCallback object definition described below to generate overloaded functions to change the defaultbehavior of the WtOPCsvr.dll with regardto Alarms & Events.

Basic support for Alarms& Events is supplied by the dll in the form of High & Low level alarms surrounding eachdefined OPC Item. As the data values change, these level limits are compared andevent messages generated as appropriate. The default behavior
of the WtOPCsvr.dll does not provide foracknowledgements from an OPC Client orany filtering to be applied to the event subscription.

By basing a C++ object on the CWtAExCallback object and overloadingany of the virtual functions theapplication can expand upon or replace the basic A&E functionality of the dll as required.

virtual HRESULT GetStatus(OPCEVENTSERVERSTATUS** ppEventServerStatus,

FILETIME LastUpdateTime);

Thisfunction is called by the dll based upon CIOPCEventServer::GetStatus(...).

The dll supplies the Last Update Time parameter to match therequesting subscriber. The defaultimplementation of this function returns valid parameters to the client. Only overload this function if you havespecific information to add to the status structure

virtual HRESULTQueryAvailableFilters (DWORD *pdwFilterMask);

This function is called from CIOPCEventServer::QueryAvailableFilters(...)

The default implementation of this function returns zero for theFilterMask and

S_OK, (i.e. Filters notsupported!)

virtual HRESULTQueryEventCategories (DWORD dwEventType,

DWORD *pdwCount,

DWORD **ppdwEventCategories,

LPWSTR **ppszEventCategoryDescs);

This function is called fromCIOPCEventServer::QueryEventCategories(...).

The default implementation of this function supports two categories

OPC_SIMPLE_EVENT -- OPC_MSG_CAT:System Message

OPC_CONDITION_EVENT -- OPC_LEVEL_CAT:Level

-- OPC_DISCRETE_CAT:Discrete

virtual HRESULTQueryConditionNames ( DWORD dwEventCategory,

DWORD *pdwCount,

LPWSTR **ppszConditionNames);

This function is called from CIOPCEventServer::QueryConditionNames(...)

The default implementation of this function returns the followingcondition names

OPC_MSG_CAT -- "Informational Text"

OPC_LEVEL_CAT -- "Level Alarm"

OPC_DISCRETE_CAT -- "Discrete Alarm"

virtual HRESULTQuerySubConditionNames ( LPWSTR szConditionName,

DWORD *pdwCount,

LPWSTR **ppszSubConditionNames);

This function is called fromCIOPCEventServer::QuerySubConditionNames(...)

The default implementation of this function returns foursubCondition Names for the "Level Alarm" condition:

"Lo"

"Lo Lo"

"Hi"

"Hi Hi"

virtual HRESULTQuerySourceConditions ( LPWSTR szSource,

DWORD *pdwCount,

LPWSTR **ppszConditionNames);

This function is called from CIOPCEventServer::QuerySourceConditions(...)

The default implementation of this function returns E_NOTIMPL.

virtual HRESULTQueryEventAttributes ( DWORD dwEventCategory,

DWORD *pdwCount,

DWORD **ppdwAttrIDs,

LPWSTR **ppszAttrDescs,

VARTYPE **ppvtAttrTypes);

This function is called fromCIOPCEventServer::QueryEventAttributes(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTTranslateToItemIDs ( LPWSTR szSource,

DWORD dwEventCategory,

LPWSTR szConditionName,

LPWSTR szSubconditionName,

DWORD dwCount,

DWORD *pdwAssocAttrIDs,

LPWSTR **ppszAttrItemIDs,

LPWSTR **ppszNodeNames,

CLSID **ppCLSIDs);

This function is called fromCIOPCEventServer::TranslateToItemIDs(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTGetConditionState ( LPWSTR szSource,

LPWSTR szConditionName,

DWORD dwNumEventAttrs,

DWORD *pdwAttributeIDs,

OPCCONDITIONSTATE **ppConditionState);

This function is called from CIOPCEventServer::GetConditionState(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTEnableConditionByArea ( DWORD dwNumAreas,

LPWSTR *pszAreas);

This function is called from CIOPCEventServer::EnableConditionByArea(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTEnableConditionBySource ( DWORD dwNumSources,

LPWSTR *pszSources);

This function is calledfrom CIOPCEventServer::EnableConditionBySource(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTDisableConditionByArea ( DWORD dwNumAreas,

LPWSTR *pszAreas);

This function is called from CIOPCEventServer::DisableConditionByArea(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTDisableConditionBySource ( DWORD dwNumSources,

LPWSTR *pszSources);

This function is called from CIOPCEventServer::DisableConditionBySource(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTAckCondition ( DWORD dwCount,

LPWSTR szAcknowledgerID,

LPWSTR szComment,

LPWSTR *pszSource,

LPWSTR *pszConditionName,

FILETIME *pftActiveTime,

DWORD *pdwCookie,

HRESULT **ppErrors);

This function is called from CIOPCEventServer::AckCondition(...)

The default implementation of this function returns S_FALSE

virtual HRESULTCreateAreaBrowser ( REFIID riid,

LPUNKNOWN *ppUnk);

This function is called from CIOPCEventServer::CreateAreaBrowser(...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTCreateEventSubscription (DWORD hEventSubscription,

DWORD dwBufferTime,

DWORD dwMaxSize,

OPCHANDLEhClientSubscription);

virtual HRESULTRemoveEventSubscription (DWORD hEventSubscription);

WtOPCsvr.dll will execute these funtions in the application callbackobject whenevr a client subcribes and unsubscribes to the event server. Thisallows the application to implement filters on an individual subscription basisby calling UserAEMessageEx2.

virtual HRESULTSetEventSubscriptionFilter ( DWORD hEventSubscription,

DWORD dwEventType,

DWORD dwNumCategories,

DWORD *pdwEventCategories,

DWORD dwLowSeverity,

DWORD dwHighSeverity,

DWORD dwNumAreas,

LPWSTR *pszAreaList,

DWORD dwNumSources,

LPWSTR *pszSourceList);

This function is called from CIOPCEventSubscriptionMgt::SetFilter (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTGetEventSubscriptionFilter ( DWORD hEventSubscription,

DWORD *pdwEventType,

DWORD *pdwNumCategories,

DWORD **ppdwEventCategories,

DWORD *pdwLowSeverity,

DWORD *pdwHighSeverity,

DWORD *pdwNumAreas,

LPWSTR **ppszAreaList,

DWORD *pdwNumSources,

LPWSTR **ppszSourceList);

This function is called from CIOPCEventSubscriptionMgt::GetFilter (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTSelectEventSubscriptionReturnedAttributes ( DWORD hEventSubscription,

DWORD dwEventCategory,

DWORD dwCount,

DWORD *dwAttributeIDs);

This function is called from CIOPCEventSubscriptionMgt::SelectReturnedAttributes (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTGetEventSubscriptionReturnedAttributes ( DWORD hEventSubscription,

DWORD dwEventCategory,

DWORD *pdwCount,

DWORD **ppdwAttributeIDs);

This function is called from CIOPCEventSubscriptionMgt::GetReturnedAttributes (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTRefreshEventSubscription ( DWORD hEventSubscription,

DWORD dwConnection);

This function is called from CIOPCEventSubscriptionMgt::Refresh (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTCancelEventSubscriptionRefresh ( DWORD hEventSubscription,

DWORD dwConnection);

This function is called from CIOPCEventSubscriptionMgt::CancelRefresh (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTGetEventSubscriptionState ( DWORD hEventSubscription,

BOOL *pbActive,

DWORD *pdwBufferTime,

DWORD *pdwMaxSize,

OPCHANDLE *phClientSubscription);

This function is called from CIOPCEventSubscriptionMgt::GetState (...)

The default implementation of this function returns E_NOTIMPL

virtual HRESULTSetEventSubscriptionState ( DWORD hEventSubscription,

BOOL *pbActive,

DWORD *pdwBufferTime,

DWORD *pdwMaxSize,

OPCHANDLE hClientSubscription,

DWORD *pdwRevisedBufferTime,

DWORD *pdwRevisedMaxSize);

This function is called from CIOPCEventSubscriptionMgt::SetState (...)

The default implementation of this function returns E_NOTIMPL

SecurityFunctions

BOOL EnableNTSecurity(BOOL EnableSecurity, DWORD MinImpersonationLevel);

Call this function to enable security checking for each tag. The MinImpersonationLevel is used to definethe minimum requirements for a client connection.

HRESULT DefineNTUser(LPCSTR GroupName, LPCSTR UserName, DWORD AccessLevel);

This function defines the name of a particular user and the accessrights to be assigned for access to server tags. Access rights may be any combination of thefollowing:

ACCESSLEVELNONE 0x00000000

ACCESSLEVEL1 0x00010000

ACCESSLEVEL2 0x00020000

ACCESSLEVEL3 0x00040000

ACCESSLEVEL4 0x00080000

ACCESSLEVEL5 0x00100000

ACCESSLEVEL6 0x00200000

ACCESSLEVEL7 0x00400000

ACCESSLEVEL8 0x00800000

ACCESSLEVEL9 0x01000000

ACCESSLEVEL10 0x02000000

ACCESSLEVEL11 0x04000000

ACCESSLEVEL12 0x08000000

ACCESSLEVEL13 0x10000000

ACCESSLEVEL14 0x20000000

ACCESSLEVEL15 0x40000000

ACCESSLEVEL16 0x80000000

HANDLE CreateSecureTag(LPCSTR Name, VARIANT Value, WORD InitialQuality, DWORD ReadAccessLevel, DWORDWriteAccessLevel);

When a tag is created, the access level required for both read andwrite access must be specified.

If NT Security is enabled, the WtOPCsvr.dll will compare the accesslevel required to read and/or write a tag with the access rights that have beenassigned to the user definition. If the connected user does not have the properaccess rights, the dll will deny
access and return an error to the client.

BOOLEnableWriteNotification2 (WRITENOTIFYPROC2 lpCallback, BOOLConvertToNativeType);

Thisfunction defines the callback routine that receives control from theWTOPCSvr.DLL whenever an OPC Client application writes to a defined processtag.

lpCallback points to a routine defined such as the following:

void CALLBACK EXPORTNotificationHandler (HANDLE handle,

VARIANT *pNewValue, DWORD *pDeviceError, char *pUser)

This callback is identical to the standard write notificationcallback with an extra parameter on the end that describes the name of the userrequesting the write.




WTSvrTest MFC Example





The WTSvrTestapplication was designed to demonstrate how an OPC Server may be assembledusing the WTOPCSvr dll. WTSvrTest wasbuilt using MSDEV Version 6.0. Allproject and resource files are contained in the distribution fileWtSvrTest.zip.

This simpleapplication uses the standard MFC framework, (Application/Document/View),architecture generated by the Microsoft development platform for a single-documentinterface. All custom logic to interfacewith the WTOPCsvr dll has been added to WTSvrTestView.cpp.
For demonstration purposes, menu options areincluded which Register and Unregister the server, instead of the preferredmethod of processing command line options during self-registration.

Menu options areavailable to add tags to the server and update their value. An option is also available to enable writenotification back from the WTOPCsvr dll if an attached OPC Client writes a tagor requests an undefined tag. The menuoptions closely match
the actual calls that would be made to the server dll forcreating and updating tags for an actual OPC Server application.

WTSvrTst2 MFCExample





The WTSvrTst2application was designed to demonstrate different techniques for writing an OPCServer with large tag counts. It too waswritten using MSDEV 6.0 and is designed around the standard MFC framework. The WtSvrTst2 application uses a single formview
that displays a tree control depicting the server tag list and an eventwindow that displays DCOM Interface calls processed by the server. Menu commands allow you to Register and Unregister the server and tocreate a list of tags up to 20,000 in size. The tag
list may be created using any combination of options forupdating the values, (Hashing/No-Hashing, single Updates/UpdateByList). Text messages are displayed that show thetimes involved with creation of the tag list and the update times.

译文,部分没有翻译完全...

下载opc基金会的OPC Proxy DLL然后按照说明进行安装。这些动态库是opc程序运行所必须的。
1. 将下列文件拷贝至要运行OPC服务器和OPC客户端的机器上的SYSTEM32目录下
copy opcproxy.dll C:\WINDOWS\system32
copy opccomn_ps.dll C:\WINDOWS\system32
copy opc_aeps.dll C:\WINDOWS\system32
copy opchda_ps.dll C:\WINDOWS\system32
copy aprxdist.exe C:\WINDOWS\system32
copy opcenum.exe C:\WINDOWS\system32
2. 注册这些 dll 文件
REGSVR32 opcproxy.dll
REGSVR32 opccomn_ps.dll
REGSVR32 opc_aeps.dll
REGSVR32 opchda_ps.dll
3. 如果在windows 系统(\WINDOWS \system32)目下不存在actxprxy.dll,运行aprxdist.exe
4. 安装 opcenum.exe
opcenum /regserver

二.opcserver开发
1. 新建vc工程。比如建一个控制台工程。在工程中包含如下头文件
#include "opcda.h"
#include "opc_ae.h"
#include "WTOPCsvrAPI.h"
#include "WtOPCsvrEXTapi.h"
以上头文件在例子程序中都能找到,拷贝到自己的工程下。
WTOPCsvrAPI.h是开发包动态库提供的导出函数文件。里面有每个函数的具体说明,调用的时候看一下说明。
2. 在.cpp中定义一个GUID这个guid是用来标识opcserver的唯一id可以通过操作系统的工具生成,也可以编一个。格式如下。
const GUID
CLSID_OPCSimSvr = {0x99b8f472, 0xc037, 0x11d2, {0x80, 0xb8, 0x0, 0x60, 0x97, 0x58, 0x58, 0xbe}};

3. 在工程中加入对WtOPCSvr动态库的连接。
WTOPCsvr动态库的有关文件都在之前的例子包里面能找到。
WTOPCsvr.lib WTOPCsvr.dll是对应lib和dll

4. 初始化
(1)调用UpdateRegistry()函数完成注册。下面是一个调用参考例子代码

BOOL COPCSimSvrApp::InitInstance()
{
TCHAR szTokens[] = _T("-/ ");
CString HelpPath;
CString SvrName, SvrDescrip;
int i;

HelpPath = AfxGetApp()->m_pszHelpFilePath;
i = HelpPath.ReverseFind('\\');
HelpPath = HelpPath.Left(i+1);
HelpPath += "OPCSIMSVR.EXE";
//
// Self-Registration code
// (look for cmdline options to register & unregister server)
//

SvrName = "WinTECH.OPCServer";
SvrDescrip = "WinTECH Software OPC Server Simulator";

CString tempCmdLine(m_lpCmdLine);
LPTSTR lpszToken = _tcstok(tempCmdLine.GetBuffer(1), szTokens);
while (lpszToken != NULL)
{
if (_tcsicmp(lpszToken, _T("UnregServer"))==0)
{
UnregisterServer ((BYTE *)&CLSID_OPCSimSvr, SvrName);
return (FALSE);
}
else if (_tcsicmp(lpszToken, _T("RegServer"))==0)
{
UpdateRegistry ((BYTE *)&CLSID_OPCSimSvr,
SvrName,
SvrDescrip,
HelpPath);
return (FALSE);
}
lpszToken = _tcstok(NULL, szTokens);
}

(2)调用InitWTOPCsvr完成开发包dll初始化。
以上两个步骤不可颠倒。
5. 创建item
这里的item是服务器所有的item,这些item通过opc库户端能浏览到。创建item的函数为CreateTag().
Opc有两种地址空间形式:扁平和多层结构的。
比如调用创建的点为item1、item2、item3.这类结构就是扁平的。各个点类似与文件系统中的文件。
比如调用创建的点为test.item1、test.item2、test.item3这种点名,开发包会自动形成多层的点结构。Test类似与文件系统中的文件夹,item类似与文件系统中的文件夹下的文件。扁平式和多层结构在客户端浏览点名时体现。
多层结构的点名之间默认是用“.”分隔。为了简单可以将我们的opcserver设计为扁平结构。
创建一个点时会返回一个handle用来标识这个点。我们程序需要自己建立这个handle和数据库中保存设备实时值的对应关系。这部分可以参考例子代码。
6. 建立一个定时器采集设备数据
定时从数据库中取得各个handle对应的item的值。然后比较各个item的值是否和上一次读取的值有变化,如果有变化调用UpdateTagToList放入对应的队列。开发包会自动将变化的值送到客户端。

大致流程为
(1) 从数据库中采集一遍所有点的实时值。
(2) 调用StartUpdateTags()
(3) 循环读取每个item在数据库中的数据,和上一次读取到的进行比较。如果有变化调用UpdateTagToList()
(4) 最用调用EndUpdateTags()完成所有item的更新。
7. 客户端控制
客户端写tag的值的时候,在opcserver是通过一个回调函数来响应的。
在服务器端必须调用EnableWriteNotification()来指定写值的回调函数。回调函数的格式为:
typedef VOID (CALLBACK* WRITENOTIFYPROC)(HANDLE, VARIANT*, DWORD*);
然后在回调函数内部实现从HANDLE指定的tag写到具体的控制设备对应的变量中。
8. 其它常用函数
RequestDisconnect()一般在opcserver在关闭时调用,用来通知客户端opcserver自己要关闭。
NumbrClientConnections()用来计算当前有多少个客户端连接到了opcserver
UninitWTOPCsvr()程序退出时清理
SetVendorInfo()设置厂商信息
三.opc客户端测试
下面以本机opcquickclient.exe为例说明服务器和客户端之间的应用关系。
1. 运行opcquickclient.exe
2. 点击edit->new server connection 菜单。弹出server properties对话框。从中展开opc data access server version 2.0.会浏览到本机安装的所有opcserver。选中我们自己开发的opcserver,点击确定。完成与服务器的连接
3. 点击edit->new group 用默认值添加组。
4. 点击edit->new item 弹出如下对话框。(下图是一个多层结构地址空间的例子,单层的更简单)选中左侧的某个父节点,右侧会显示出各个子tag。选中要向opcserver查询的tag,点击add leaves。然后点击ok
5. 在客户端主界面上能看到刚才要查询的tag。它会自动跟随opcserver端数据的变化而变换。
6. 右键要控制的tag,在菜单中选择同步写或者异步写(一般建议用异步,避免阻塞客户端的正常运行)。键入要写入的值。查看设备上是否动作。从而检验opcserver是否编写的正确。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐