350
Wonderware I/O Server Toolkit User’s Guide Revision L October 2001 Wonderware Corporation

Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

  • Upload
    others

  • View
    27

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Wonderware I/O Server Toolkit

User’s GuideRevision LOctober 2001

Wonderware Corporation

Page 2: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

All rights reserved. No part of this documentation shall be reproduced, stored in a retrievalsystem, or transmitted by any means, electronic, mechanical, photocopying, recording, orotherwise, without the prior written permission of the Wonderware Corporation. No copyrightor patent liability is assumed with respect to the use of the information contained herein.Although every precaution has been taken in the preparation of this documentation, thepublisher and author assume no responsibility for errors or omissions. Neither is any liabilityassumed for damages resulting from the use of the information contained herein.

The information in this documentation is subject to change without notice and does not representa commitment on the part of Wonderware Corporation. The software described in thisdocumentation is furnished under a license or nondisclosure agreement. This software may beused or copied only in accordance with the terms of these agreements.

I/O Server Toolkit

2001 Wonderware Corporation. All Rights Reserved.

100 Technology DriveIrvine, CA 92618U.S.A.(949) 727-3200http://www.wonderware.com

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have beenappropriately capitalized. Wonderware Corporation cannot attest to the accuracy of thisinformation. Use of a term in this book should not be regarded as affecting the validity of anytrademark or service mark.

Wonderware, InTouch, and FactorySuite Web Server are registered trademarks of WonderwareCorporation.

Wonderware FactorySuite, InTouch, WindowMaker, WindowViewer, SQL Access Manager,Recipe Manager, SPC Pro, DBDump, DBLoad, HDMerge, HistData, Wonderware Logger,InControl, InTrack, InBatch, IndustrialSQL, FactoryOffice, Scout, SuiteLink, and NetDDE aretrademarks of Wonderware Corporation.

Page 3: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

i

ContentsDocumentation Conventions ...................................................................................................... ix

Terms Used in this Document .........................................................................................ixLimitation Summary .........................................................................................................x

CHAPTER 1 Introduction to the I/O Server Toolkit ............................................................1-1What’s New? .................................................................................................................1-2Installation .....................................................................................................................1-3Communication Protocols .............................................................................................1-3What is DDE?................................................................................................................1-5

DDE Protocol .........................................................................................................1-6Dynamic Data Exchange Management Library .............................................................1-7What is SuiteLink? ........................................................................................................1-8

SuiteLink Protocol..................................................................................................1-8Server Application Requirements ..................................................................................1-9Toolkit Content Overview ...........................................................................................1-10Requirements for Developing on Windows 98, Windows NT and Windows 2000.....1-11

CHAPTER 2 Getting Started with the I/O Server Toolkit ...................................................2-1Installation Process........................................................................................................2-2If You Have a Prior Installation of the I/O Server Toolkit ............................................2-2General Instructions.......................................................................................................2-2File Description .............................................................................................................2-3

Include Files ...........................................................................................................2-3Utility Files.............................................................................................................2-3Sample Servers .......................................................................................................2-4Help Files ...............................................................................................................2-4Online Book ...........................................................................................................2-4

Compiling a Server ........................................................................................................2-5Linking a Server ............................................................................................................2-5Running a Server ...........................................................................................................2-6

CHAPTER 3 Overview of an I/O Server ...............................................................................3-1Data Flow ......................................................................................................................3-2Value/Time/Quality .......................................................................................................3-2DDE and SuiteLink Conversations................................................................................3-3Logical Devices and Points ...........................................................................................3-4Logical Devices/Topics .................................................................................................3-5Items/Points ...................................................................................................................3-6Advises, Requests, and Pokes........................................................................................3-7Toolkit Database............................................................................................................3-8

Page 4: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

ii Table of Contents

CHAPTER 4 Designing an I/O Server ................................................................................. 4-1Configuring a I/O Server............................................................................................... 4-2Executing the Protocol .................................................................................................. 4-3Communication with the Device ................................................................................... 4-4

CHAPTER 5 SuiteLink.......................................................................................................... 5-1SuiteLink Overview ...................................................................................................... 5-2Components (Files) Associated with SuiteLink ............................................................ 5-3Starting Up a Server...................................................................................................... 5-3Automatic Throttling of the Data Rate.......................................................................... 5-4SuiteLink Debug Flags.................................................................................................. 5-5Deactivating SuiteLink for a Particular Server ............................................................. 5-6Preventing a Server from Running if SuiteLink Is Unavailable .................................... 5-7Preventing a Server from Reflecting SuiteLink Pokes .................................................. 5-8

CHAPTER 6 Time Marks ...................................................................................................... 6-1Reading Time Marks..................................................................................................... 6-2Understanding Time Marks........................................................................................... 6-4

CHAPTER 7 Data Quality Flags........................................................................................... 7-1Quality Flags ................................................................................................................. 7-2Quality Flag Settings..................................................................................................... 7-4Updating Quality Flags ................................................................................................. 7-5

CHAPTER 8 Statistics Functions........................................................................................ 8-1Overview....................................................................................................................... 8-2Statistics from a Client Perspective............................................................................... 8-2Toolkit Standard Statistics ............................................................................................ 8-6

CHAPTER 9 I/O Server Toolkit Function Summary........................................................... 9-1Protocol Initialization & Setup Functions ..................................................................... 9-2Logical Device Management Functions ........................................................................ 9-3Point/Item Management Functions................................................................................ 9-5Toolkit Database Interface for Protocol Functions ....................................................... 9-8Timer Functions ............................................................................................................ 9-8String PTVALUE Manipulation Functions................................................................... 9-9Memory Management Functions................................................................................. 9-12Memory Access Permission Functions - Windows Only ............................................ 9-12Common Dialog Functions ......................................................................................... 9-13Selection Boxes - Optional ......................................................................................... 9-16Miscellaneous Functions............................................................................................. 9-17Windows NT Porting Functions.................................................................................. 9-19Macros for Portability ................................................................................................. 9-22Additional Information................................................................................................ 9-24

Page 5: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Table of Contents iii

CHAPTER 10 API Function References ............................................................................10-1AdjustWindowSizeFromWinIni ...........................................................................10-2CheckConfigFileCmdLine....................................................................................10-3CloseComm..........................................................................................................10-4DbDevGetName ...................................................................................................10-5DbGetGMTasFiletime..........................................................................................10-6DbGetName..........................................................................................................10-7DbGetPointType...................................................................................................10-8DbGetPtQuality ....................................................................................................10-9DbGetPtTime .....................................................................................................10-10DbGetValueForComm........................................................................................10-11DbNewQForAllPoints ........................................................................................10-12DbNewQFromDevice.........................................................................................10-13DbNewTopicList ................................................................................................10-14DbNewTQFromDevice ......................................................................................10-15DbNewValueFromDevice ..................................................................................10-16DbNewVQFromDevice ......................................................................................10-17DbNewVTQFromDevice....................................................................................10-18DbRegisterDemandScan.....................................................................................10-19DbRegisterScanState ..........................................................................................10-20DbSetHProt ........................................................................................................10-21DbSetPointType .................................................................................................10-22DbValueWriteConfirm.......................................................................................10-23debug ..................................................................................................................10-24EnableCommNotification...................................................................................10-25FlushComm ........................................................................................................10-26GetAppName......................................................................................................10-27GetCommError ...................................................................................................10-28GetCommEventMask .........................................................................................10-29GetIOServerLicense ...........................................................................................10-30GetServerNameExtension ..................................................................................10-31GetString ............................................................................................................10-32GetTextExtent ....................................................................................................10-33NTSrvr_BuildCommDCB..................................................................................10-34NTSrvr_GetCommState .....................................................................................10-35NTSrvr_SetCommState ......................................................................................10-36NTSrvr_SetDCB_Dtr .........................................................................................10-37NTSrvr_SetDCB_Rts .........................................................................................10-38OpenComm ........................................................................................................10-39PfnSendEmSelectAll ..........................................................................................10-40PfnSendEmSelectRange .....................................................................................10-41ProtActivatePoint ...............................................................................................10-42ProtAllocateLogicalDevice ................................................................................10-43ProtClose ............................................................................................................10-44ProtCreatePoint ..................................................................................................10-45ProtDeactivatePoint............................................................................................10-46ProtDefWindowProc ..........................................................................................10-47ProtDeletePoint ..................................................................................................10-48ProtExecute ........................................................................................................10-49ProtFreeLogicalDevice.......................................................................................10-50ProtGetDriverName............................................................................................10-51ProtGetValidDataTimeout..................................................................................10-52ProtInit................................................................................................................10-53ProtNewValueForDevice ...................................................................................10-54ProtTimerEvent ..................................................................................................10-55ReadComm.........................................................................................................10-56

Page 6: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

iv Table of Contents

RelinquishPermission - Windows Only ............................................................. 10-57RequestPermission - Windows Only.................................................................. 10-58SelBoxAddEntry................................................................................................ 10-59SelBoxSetupStart ............................................................................................... 10-60SelBoxUserSelect .............................................................................................. 10-61SelBoxUserSelection ......................................................................................... 10-62SelListFree......................................................................................................... 10-63SelListGetSelection............................................................................................ 10-64SelListNumSelections........................................................................................ 10-65SetCommEventMask ......................................................................................... 10-66SetSplashScreenParams ..................................................................................... 10-67StatAddValue..................................................................................................... 10-68StatDecrementValue .......................................................................................... 10-69StatGetValue...................................................................................................... 10-70StatIncrementValue............................................................................................ 10-71StatRegisterCounter ........................................................................................... 10-72StatRegisterRate................................................................................................. 10-73StatSetCountersInterval ..................................................................................... 10-75StatSetRateInterval ............................................................................................ 10-76StatSetValue ...................................................................................................... 10-77StatSubtractValue .............................................................................................. 10-78StatUnregisterCounter........................................................................................ 10-79StatUnregisterRate ............................................................................................. 10-80StatZeroValue .................................................................................................... 10-81StrValSetNString ............................................................................................... 10-82StrValSetString .................................................................................................. 10-83StrValStringFree ................................................................................................ 10-84StrValStringLock ............................................................................................... 10-85StrValStringUnlock............................................................................................ 10-86SysTimerSetupProtTimer .................................................................................. 10-87SysTimerSetupRequestTimer ............................................................................ 10-88UdAddFileTimeOffset ....................................................................................... 10-89UdAddTimeMSec.............................................................................................. 10-90UDDbGetName ................................................................................................. 10-91UdDeltaFileTime ............................................................................................... 10-92UdDeltaTimeMSec ............................................................................................ 10-93UdInit................................................................................................................. 10-94UdReadAnyMore............................................................................................... 10-95UdReadVersion.................................................................................................. 10-96UdTerminate ...................................................................................................... 10-97UdWriteAnyMore.............................................................................................. 10-98UdWriteVersion................................................................................................. 10-99WriteComm ..................................................................................................... 10-100WriteWindowSizeToWinIni ............................................................................ 10-101WWAnnounceStartup ...................................................................................... 10-102WWCenterDialog ............................................................................................ 10-103WWConfigureComPort ................................................................................... 10-104WWConfigureServer ....................................................................................... 10-106WWConfirm .................................................................................................... 10-107WWDisplayAboutBox..................................................................................... 10-108WWDisplayAboutBoxEx ................................................................................ 10-109WWDisplayConfigNotAllow........................................................................... 10-110WWDisplayErrorCreating ............................................................................... 10-111WWDisplayErrorReading................................................................................ 10-112WWDisplayErrorWriting................................................................................. 10-113WWDisplayKeyNotEnab................................................................................. 10-114

Page 7: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Table of Contents v

WWDisplayKeyNotInst....................................................................................10-115WWDisplayOutofMemory ...............................................................................10-116WWFormCpModeString ..................................................................................10-117WWGetDialogHandle ......................................................................................10-118WWGetDriverNameExtension.........................................................................10-119WWGetExeFilePath .........................................................................................10-120WWGetOsPlatform ..........................................................................................10-121wwHeap_AllocPtr ............................................................................................10-122wwHeap_FreePtr ..............................................................................................10-123wwHeap_Init ....................................................................................................10-124wwHeap_ReAllocPtr ........................................................................................10-125wwHeap_Release .............................................................................................10-126WWInitComPortComboBox ............................................................................10-127WWReadAnyMore...........................................................................................10-128WWReadVersion .............................................................................................10-129WWSelect ........................................................................................................10-130WWSetAffinityToFirstCPU .............................................................................10-131WWTranslateCDlgToWinBaud .......................................................................10-132WWTranslateCDlgToWinData ........................................................................10-133WWTranslateCDlgToWinParity ......................................................................10-134WWTranslateCDlgToWinStop ........................................................................10-135WWTranslateWinBaudToCDlg .......................................................................10-136WWTranslateWinDataToCDlg ........................................................................10-137WWTranslateWinParityToCDlg ......................................................................10-138WWTranslateWinStopToCDlg ........................................................................10-139WWVerifyComDlgRev ....................................................................................10-140WWWriteAnyMore..........................................................................................10-141WWWriteVersion.............................................................................................10-142

CHAPTER 11 The Chain Manager .....................................................................................11-1Background .................................................................................................................11-2Chain Data Structures ..................................................................................................11-4Setting Up a Chain and Linking Items.........................................................................11-5Searching For Items in a Chain....................................................................................11-6Removing Items From a Chain ....................................................................................11-8User-Supplied Chain Item Functions...........................................................................11-9Extensible Array Data Structures...............................................................................11-10Allocating, Extending, and Deleting an Extensible Array .........................................11-11Examples of Usage ....................................................................................................11-12Handling Linked Lists ...............................................................................................11-14

Page 8: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

vi Table of Contents

CHAPTER 12 I/O Server Toolkit Data Structures............................................................. 12-1Data Structure Definitions

PTVALUE ........................................................................................................... 12-2WW_AB_INFO................................................................................................... 12-3WW_CONFIRM.................................................................................................. 12-4WW_CP_DLG_LABELS.................................................................................... 12-5WW_CP_PARAMS........................................................................................... 12-10WW_SELECT ................................................................................................... 12-12WW_SERV_PARAMS ..................................................................................... 12-14

CHAPTER 13 Common Dialogs ........................................................................................ 13-1Main Menu.................................................................................................................. 13-2Com Port Settings ....................................................................................................... 13-3Topic Definition.......................................................................................................... 13-8Server Settings .......................................................................................................... 13-10Configuration Files ................................................................................................... 13-12Convenience Functions ............................................................................................. 13-13

CHAPTER 14 Adding the Toolkit to an Existing Windows Application......................... 14-1

CHAPTER 15 Running as an NT Service.......................................................................... 15-1Overview of Services .................................................................................................. 15-2Configuration Dialog .................................................................................................. 15-3Driver Name................................................................................................................ 15-6Service Dependencies ................................................................................................. 15-7

CHAPTER 16 Porting to Windows NT .............................................................................. 16-1Primary Goals ............................................................................................................. 16-2Server Porting Instructions.......................................................................................... 16-2Miscellaneous Debugging Hints ............................................................................... 16-10

CHAPTER 17 Porting an Existing Server to FS2000 ....................................................... 17-1Overview..................................................................................................................... 17-2Driver Name................................................................................................................ 17-3CommonUI Splash Screen and Start-up Message ....................................................... 17-4CommonUI About Box ............................................................................................... 17-6Value, Time, Quality................................................................................................... 17-7

Page 9: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Table of Contents vii

CHAPTER 18 I/O Server Code Samples............................................................................18-1Overview .....................................................................................................................18-2UDSAMPLE Architectural Overview .........................................................................18-3Adapting the UDSAMPLE Server...............................................................................18-4

Customizing the Start-Up Splash Screen and About Box.....................................18-5Modifying the User Interface – UDSAMPLE.RC and UDCONFIG.C .......................18-6Storing and Retrieving Configuration Files .................................................................18-7Setting Up Data Points – UDCONFIG.C ....................................................................18-8Executing the Configuration – UDLDCFG.C............................................................18-10

LogicalAddrCmp( ) ............................................................................................18-10Building Messages..............................................................................................18-10UdprotAddPoll( ) ...............................................................................................18-10UdprotPrepareWriteMsg( ) ................................................................................18-10Building Messages – UDBLDMSG.C................................................................18-10

Executing the Protocol – UDPROTCL.C..................................................................18-11UdprotDoProtocol( ) ..........................................................................................18-11UdprotGetResponse( ) ........................................................................................18-11ProcessValidResponse( ) ....................................................................................18-11UdprotExtractReadData( ), UdprotExtractDbItem( ) .........................................18-11UdprotHandleRspError( )...................................................................................18-11

Data Structures ..........................................................................................................18-12PORT Data Structure..........................................................................................18-12UDMSG Data Structure (Message) ....................................................................18-12STAT Data Structure (i.e. Station, Node, or Topic)...........................................18-12SYMENT Data Structure (Symbol Table) .........................................................18-12

Compiling the Sample Code ......................................................................................18-13Debug and Support Functions ...................................................................................18-14Simulated PLC...........................................................................................................18-15

CHAPTER 19 Debugging and Testing...............................................................................19-1Basic Programming Rules for Windows and Windows NT.........................................19-2General Debugging Topics ..........................................................................................19-2

Debug Messages...................................................................................................19-2DDE Message Traffic Monitoring Using WIN.INI..............................................19-3DDE Message Traffic Monitoring Using DDESpy ..............................................19-3Assertion Errors....................................................................................................19-4

Windows and Windows NT Debugging Tools ............................................................19-5Microsoft Visual C/C++ Debugger ......................................................................19-5Microsoft WINDBG Debugger ............................................................................19-5NuMega Bounds Checker.....................................................................................19-5NuMega Soft Ice ..................................................................................................19-5Rational/Pure/Atria Quantify Performance Monitor.............................................19-5

Testing.........................................................................................................................19-6WWClient Usage..................................................................................................19-6Scripts for WWClient ...........................................................................................19-8Microsoft Excel Usage .........................................................................................19-9

Index................................................................................................................................................i

Page 10: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

viii Table of Contents

Page 11: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

ix

Documentation Conventions

The following conventions are used throughout this manual to define syntax:

Convention Description

Bold Text Denotes a Wonderware I/O Server Toolkit function name,for example, Wizard_New

Bold & Underlined Denotes a Wonderware I/O Server Toolkit function namethat must be written and included in the I/O server tomanage logical devices, for example,ProtAllocateLogicalDevice

Italic text Denotes a parameter value, for example, wCommand

CAPITALS Indicates return type (or most return types) also filenamesand paths

Courier 9Shaded Box Code Examples and Syntax spacing samples

Terms Used in this DocumentTerm Definition

Developer Proficient Windows C Programmer; person developing thecode

Windows NT� 32-bit platform

Page 12: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

x Conventions

Limitation SummaryAs the owner of the I/O Server Toolkit you can:

• Develop multiple servers

• Receive four hours of telephone support within one year from date of purchase

• Purchase additional support beyond four hours

• The I/O Server Toolkit license does not allow:

1. License transfer without the express written consent of Wonderware

2. Release/resale of I/O Server Toolkit source code or libraries

3. Support for other than the registered user

Page 13: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-1

C H A P T E R 1

Introduction to theI/O Server Toolkit

The I/O Server Toolkit provides a high level application program interface (API) thatdoes not require detailed handling or understanding of low level details of theclient/server communication protocol (DDE or SuiteLink). The Toolkit has beenoptimized for performance in real-time data acquisition applications.

The I/O Server Toolkit is based on a library that includes high level functions that takecare of the more difficult complications associated with the development of a well-behaved, high performance I/O Server (herein referred to as the server).

The I/O Server Toolkit was originally developed for internal use in developing otherWonderware products. It has been used to develop dozens of Wonderware I/O Serverswith a worldwide installed base of thousands of sites. These servers are generally in 24-hour use in demanding factory automation and process control applications.

The Toolkit minimizes the learning curve associated with Dynamic Data Exchange(DDE) and SuiteLink implementation by utilizing the man-years of development andtesting that have gone into Wonderware InTouch and I/O Server products. TheToolkit provides library functions that support multiple clients, thousands of data items,DDE and SuiteLink protocol error detection, recovery and support for severalcommonly used but unpublished high performance private data formats, such asWonderware InTouch FastDDE and Microsoft Excel table format.

Contents! What’s New?! Installation! Communication Protocols! What is DDE?! DDE Protocol! Dynamic Data Exchange Management Library! What is SuiteLink?! Server Application Requirements! Toolkit Content Overview! Requirements for Developing on Windows 98 Second Edition or Windows NT

Page 14: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-2 Chapter 1

What’s New?With FactorySuite 2000, several important new features have been added to theWonderware I/O Server Toolkit:

!!!! SMP (symmetrical multiprocessing machine support)The I/O Server will run on a SMP (symmetrical multiprocessing). With the newlyadded API from the library (WWSetAffinityToFirstCPU), the I/O Server can belocked to the first CPU on the SMP machine.

Page 15: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Introduction to the I/O Server Toolkit 1-3

InstallationRefer to the accompanying instruction pamphlet for installation procedures.

Note We strongly recommend before you begin installation procedures that your takethe time to familiarize yourself with Chapter 2, "Getting Started with the I/O ServerToolkit." This chapter covers in detail how the Toolkit environment will be set up onyour system.

Communication ProtocolsDynamic Data Exchange (DDE) is a communication protocol developed by Microsoftto allow applications in the Windows environment to send/receive data and instructionsto/from each other. It implements a client-server relationship between two concurrentlyrunning applications. The server application provides the data and accepts requestsfrom any other application interested in its data. Requesting applications are calledclients. Some applications such as InTouch and Microsoft Excel can simultaneously beboth a client and a server.

FastDDE provides a means of packing many proprietary Wonderware DDE messagesinto a single Microsoft DDE message. This packing improves efficiency andperformance by reducing the total number of DDE transactions required between aclient and a server. Although Wonderware's FastDDE has extended the usefulness ofDDE for our industry, this extension is being pushed to its performance constraints indistributed environments.

NetDDE extends the standard Windows DDE functionality to include communicationover local area networks and through serial ports. Network extensions are available toallow DDE links between applications running on different computers connected vianetworks or modems. For example, NetDDE supports DDE between applicationsrunning on IBM compatible computers connected via LAN or modem and DDE-awareapplications running on non-PC based platforms under operating environments such asVMS and UNIX .

SuiteLink uses a TCP/IP based protocol and is designed specifically to meet industrialneeds such as data integrity, high-throughput, and easier diagnostics. This protocolstandard is only supported on Microsoft WindowsNT 4.0 and Windows 2000 or higher.

Page 16: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-4 Chapter 1

SuiteLink is not a replacement for DDE, FastDDE, or NetDDE. The protocol usedbetween a client and a server depends on your network connections and configurations.SuiteLink was designed to be the industrial data network distribution standard andprovides the following features:

Value Time Quality (VTQ) places a time stamp and quality indicator on all datavalues delivered to VTQ-aware clients.

Extensive diagnostics of the data throughput, server loading, computer resourceconsumption, and network transport are made accessible through the MicrosoftWindows NT and Windows 2000 operating system Performance Monitor. Thisfeature is critical for the scheme and maintenance of distributed industrial networks.

Consistent high data volumes can be maintained between applications regardless ifthe applications are on a single node or distributed over a large node count.

The network transport protocol is TCP/IP using Microsoft’s standard WinSockinterface.

Page 17: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Introduction to the I/O Server Toolkit 1-5

What is DDE?Dynamic Data Exchange (DDE) is a method of communication that allows concurrentlyrunning programs to exchange data with each other. It implements a client-serverrelationship between the applications. A server application accepts requests from anyclient application interested in the data. Clients can both read and write data maintainedby the server.

DDE is often used to gather and distribute "live" data such as production measurementsfrom a factory floor, scientific instrument readings or stock price quotations. Clients canuse DDE for one-time data transfers or for ongoing exchanges in which updates will besent as soon as new information is available. DDE's data writing mechanism can beused to issue data. For example, in a factory automation system, DDE can allow clientsapplications to control temperature set points in ovens.

A DDE interface has become a standard feature of Windows applications that canbenefit from data links to other applications. Examples of DDE compliant applicationsinclude Microsoft Excel, Lotus 123 for Windows and Wonderware InTouch.

Network extensions are available to allow DDE links between applications running ondifferent computers connected via networks or modems. For example, WonderwareNetDDE supports DDE between applications running on IBM PCs connected via LANor modem as well as DDE capable applications running on non-PC based platforms suchas VAX or UNIX minicomputers.

The Windows environment has a message based architecture as its foundation.Messages are used for passing keyboard and mouse movement information to Windowsapplication programs. Each message needs only two parameters for passing data. DDEis based on the same message transport mechanism. As a result, these messageparameters must refer indirectly to other pieces of data (objects) if more than a fewwords of information are passed between applications. These secondary objects arelocated in globally shared memory.

Page 18: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-6 Chapter 1

DDE ProtocolThe DDE protocol specification is the precise interface that applications mustimplement to support DDE. The specification includes standardized formats formessages to be interchanged between DDE compliant applications. It is possible toignore all or part of the DDE protocol if you are writing a set of applications that willcommunicate in a closed environment. However, in order to reliably communicate withother standard, off-the-shelf applications it is necessary to implement an interface thatsupports the DDE protocol documented by Microsoft.

The DDE protocol is nominally documented in the Microsoft Windows SoftwareDevelopment Kit (SDK). This documentation however is deceptively simple. It isparticularly light in coverage related to performance optimization and error recovery.Sources such as back issues of the Microsoft Systems Journal and the Microsoft SupportKnowledge Database CD ROM may provide the documentation required in order toimplement a "well-behaved" DDE application.

"Ill-behaved" DDE applications can hang or crash the Windows environment. Earlyeditions of certain very popular Windows applications suffered anomalies in their DDEimplementation that are recognized and tolerated by "well-behaved" DDE applications.

To implement a reliable, high performance DDE protocol there are a multitude ofpotential error conditions that must be properly addressed. Still further, complicationsarise when optimal performance is desired and when partially compliant third partyDDE applications must be tolerated.

Page 19: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Introduction to the I/O Server Toolkit 1-7

Dynamic Data Exchange Management LibraryBased on the recognition of DDE compliance problems associated with certainapplications released by major software publishers, Microsoft released the DynamicData Exchange Management Library (DDEML) with the Microsoft Windows 3.1 SDK.

The DDEML is a dynamic link library (DLL) that applications running with theMicrosoft Windows operating system can use to share data. The DDEML provides anapplication programming interface (API) that simplifies the task of adding DDEcapability to a Windows application. The API hides interaction with Windowsmessages and provides new mechanisms for managing global shared memory objects.

The 3.1 SDK Programmer's Reference Manual states that "DDEML ensurescompatibility among DDE applications by forcing them to implement the DDE protocolin a consistent manner." Concurrent with the release of DDEML, documentation of theDDE protocol was dropped from the SDK Programmer's Reference Manual.

In keeping with the Windows 3.1 philosophy, the principal purpose for promoting use ofDDEML, as opposed to a direct implementation of the DDE protocol, would seem to bethat it more strongly enforces parameter checking on system calls made by applications.

DDEML makes it more difficult to implement an ill-behaved DDE application it doesnot make it easier to implement a well-behaved application. For example: callingGlobalAddAtom() (a function commonly used in a direct implementation of the DDEprotocol) takes only one parameter; DdeCreateStringHandle(), its replacement underthe DDEML, requires three parameters. The revised interface appears to be engineeredto allow Windows to perform stronger type checking.

The implementation of a well-behaved, high performance DDE application using theDDEML will still require reference to the DDE protocol specification. The DDEMLstill uses the DDE protocol "under the covers." A thorough understanding of theunderlying protocol is necessary to implement reliable error handling and recovery andto engineer an efficient internal program structure.

DDEML does not simplify the problem of multiple clients using potentially differentdata formats. For example, Excel uses Excel Table Format, and InTouch uses InTouchproprietary format. The Toolkit allows you to keep data in its natural form: discrete,integer, real or string. DDEML does not implicitly support these.

Page 20: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-8 Chapter 1

What is SuiteLink?SuiteLink is a proprietary communication protocol created by Wonderware that can beused as an addition to DDE or as an alternative to DDE. Where DDE providescommunication between Windows programs via global memory buffers and Windowsmessages, SuiteLink uses TCP/IP sessions and Windows Sockets. As withWonderware’s FastDDE format, SuiteLink supports high-performance data transferbetween applications by sending multiple commands and data items in each block ofinformation that gets sent.

Since it uses TCP/IP, SuiteLink can handle data transfer within a single computer nodeor between nodes across a network.

So far as an I/O Server is concerned, the type of communication channel between clientand server is transparent. That is, the server-specific code does not know – and does notneed to know – whether a client is connected via DDE or via SuiteLink.

SuiteLink ProtocolThe SuiteLink protocol was created by Wonderware, specifically to support dataacquisition for such programs as I/O Servers. While the details of the implementationare proprietary, an overview of the protocol is provided in the chapter titled “SuiteLink.”

Page 21: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Introduction to the I/O Server Toolkit 1-9

Server Application RequirementsThe I/O Server Development Toolkit is used to either write an I/O Server applicationor add server capability to an existing Windows application. Here are a fewrequirements:

1. The application must run in a time slice manner. Periodically, the server will becalled to allow it to run its protocol and provide fresh data to the Toolkit database.The time slice is configurable by the server, but it still must give up control to allowother Windows applications to run on the same PC.

2. The application program must be written in Microsoft C or C++, to interface withthe Toolkit program library.

3. The Toolkit database will handle the following data types:

Discrete (0 or 1)Integers (signed 32-bit integer)Reals (single precision floating point, IEEE 32-bit)Strings (series of 8-bit characters terminated with a null)

Within the above constraints, a large variety of applications can easily be adapted totransfer data as a I/O Server. Here are a few examples:

Gathering and sending data to a device that can be connected to the serialcommunication port of the PC.

Interface to a plug in board that has a memory-mapped interface.

A stand-alone application that can accept data and/or supply data. For example, aspecialized calculation program that takes input data values and does involvedcomputations or time-based integrations.

Page 22: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-10 Chapter 1

Toolkit Content OverviewThe Toolkit allows the software developer to concentrate on the problem at hand,transferring data to and from an external communication device or special datageneration application. It also allows the application program to deal with data in itsnative form: discrete, integer, real or string types. Source code (in the C language) fortwo example servers is included.

The examples include source code for the maintenance of extensible, heap allocated datastructures for tracking data items that are on advise or "hot linked." The implementationof these data structures alone could take hundreds of hours.

The examples can also be expected to speed the learning process for programmers wholack prior Windows programming experience.

The I/O Server Development Toolkit consists of four essential parts:

1. This document describes the Toolkit's library routines and gives helpful hints forgenerating a I/O Server application from scratch or adapting an existing one.

2. An object-code library that supports the I/O Server functions and memorymanagement. These are described later in this document.

3. Two server code examples are included to demonstrate the Toolkit. They provide astarting point for developers as well as showing useful data structures and routinesfor most device drivers.

4. Technical support for the I/O Server Toolkit provided by Wonderware's technicalsupport staff.

Page 23: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Introduction to the I/O Server Toolkit 1-11

Requirements for Developing on Windows 98, WindowsNT and Windows 2000

The FactorySuite 2000 I/O Server Toolkit supports development of I/O Servers only onplatforms that support Win32 – Windows NT, Windows 2000 or Windows 98 SecondEdition. It does not support operation using the Win32S subset that is available forWindows 3.1.

Also, it should be noted that Windows NT /2000 and Windows 98 have differentimplementations of Win32. Consequently, there may be some functional differenceswhen the same program is run on these operating systems. In particular, SuiteLink isfunctional only for an I/O Server running on Windows NT and Windows 2000.

The following requirements are necessary to successfully develop a FactorySuite 2000Windows I/O Server application:

1. IBM PC or compatible that is set up to run Microsoft Windows 98 Second Edition,Windows NT 4.0, Windows 2000 or later.

2. Microsoft Visual C/C++ Compiler, version 6.0 sp3 or later. A mastery of the C language is essential for developing a Windows serverapplication that uses the Toolkit.While a familiarity with Microsoft Windows software development is not requiredto use this Toolkit, it is highly recommended.

The following are recommended "extras" to your development system. Their relativelylow cost is greatly offset by the time you'll save in debugging alone.

Microsoft MASM 5.0 or later. MASM is the Microsoft assembler necessary formodifying assembly language that Wonderware has provided, as well as fordeveloping assembly language based routines.

Microsoft Word, an excellent documentation tool, can be used to generate thedocumentation files required for the "Help" compiler. It can be referenced in thesubtitled section called "Adding Help to the I/O Server" in the I/O Server ToolkitFunctions chapter.

The book, Programming Windows by Charles Petzold. (Microsoft Press, ISBN 1-55615-264-7)

Page 24: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

1-12 Chapter 1

Page 25: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

2-1

C H A P T E R 2

Getting Started with theI/O Server Toolkit

The Toolkit installation procedures are described in the installation pamphlet includedwith the I/O Server Toolkit. This chapter describes the basics for getting startedquickly.

Contents! Installation Process! File Description! Compiling a Server! Linking a Server! Running a Server

Page 26: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

2-2 Chapter 2

Installation ProcessThe instruction pamphlet describes the required procedure to install the Toolkitsoftware. It is important to know that if an earlier version of the Toolkit is installed onyour computer and the new version is installed the main directory should be renamed.

If You Have a Prior Installation of the I/O Server ToolkitRename the old directory to another name using Windows Explorer. This will preventobsolete files from being accidentally referenced in your new installation.

General InstructionsClick Start/Run. Enter the following in the text field of the Run dialog box:

{x:\path}\setup

where:{x:\path} is the drive:\path

This is where the I/O Server Toolkit distribution media is located.

InstallShield will direct the installation process and the installation process will createthe following main directories:

drive:\path\ioserverdrive:\path\ioservertoolkitdrive:\path\uninst

where:{drive:\path} is user defined

Example:C:\Ww\IoserverC:\Ww\IoservertoolkitC:\Ww\Uninst

Page 27: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Getting Started with the I/O Server Toolkit 2-3

File DescriptionThe following sections summarize some of the key files installed on your hard disk.

Include Files\Ww\Ioservertoolkit\Inc\Tkitstrt.rciThis file is a resource include file containing the startup dialog WWStartup for theToolkit. The project resource file (.RC) must include this file.

\Ww\Ioservertoolkit\Inc\*.hThere are various include files contained in the includes directory that must be includedin the source code to define function prototypes and structures for the Toolkit. See thesample servers for examples.

Utility Files\Program Files\FactorySuite\Common\wwclient.exeThe WWClient utility replaces the DDEAPP utility that was originally developed byMicrosoft. WWClient has been specifically written by Wonderware to exercise thebasic DDE and SuiteLink client functions to test the server. It is a 32-bit application,which can run on Windows NT/2000 or Windows 98 Second Edition. For details, referto the "Debugging and Testing" chapter.

\Program Files\FactorySuite\Common\TESTPROT.exeThe TestProt server has been specifically written by Wonderware to exercise the basicDDE and SuiteLink server functions. It is a 32-bit application which can run onWindows NT/2000 or Windows 98 Second Edition, and can be used to verify thatWWClient can actually access an I/O Server on your system configuration. For details,refer to the “Debugging and Testing” chapter.

\Program Files\FactorySuite\Common\wwlogvwr.exeThe Wonderware logger, wwlogvwr.exe, will display and save to disk debuggingmessages from the server and the Toolkit. A version has been supplied that is native toeach supported platform.

\Ww\Ioservertoolkit\Lib\W32\I386\Toolkit7.libThe I/O Server Toolkit library.

Note: Recent versions (Build 060 or later) of the Toolkit library contain debuginformation resulting in a larger file size. To build a debug version of a server, use theadded debug information. Building a release version of a server will remove the debuginformation.

Page 28: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

2-4 Chapter 2

\Ww\Ioservertoolkit\Inc\Protlib.strThis file contains the string resources used by Toolkit7.lib. These strings should onlybe modified for language conversion. Do not delete or change the order of any stringswithin the Toolkit. The project resource file (.RC) must include this file.

Ww\Ioserver\UdsampleThis subdirectory contains source files for the board and serial sample servers.

Sample ServersThe toolkit provides a sample server, UDSAMPLE. The sample server is created usingcommon source files and specific files for either the board or serial version.

\Ww\Ioserver\Udsample\CommonThis main sample directory contains the common source files from which a completeserver can be developed, once the specific files for a serial or board server are copiedfrom one of the two corresponding subdirectories.

\Ww\Ioserver\Udsample\UdboardThis directory contains three files UDSAMPLE.C, UDSAMPLE.H, and UDSAMPLE.ICOwhich can be copied to the main sample directory to build a board server, whichdemonstrates the typical use of a memory mapped interface device in Windows.

\Ww\Ioserver\Udsample\UdserialThis directory contains three files UDSAMPLE.C, UDSAMPLE.H, and UDSAMPLE.ICOwhich can be copied to the main sample directory to build a serial server, which demonstrates the typical use of a serial communications (COM port) interface device in Windows.

Help FilesTwo Help files have been provided with the I/O Server Toolkit.

\Ww\Ioservertoolkit\IOSrv_Toolkit.hlpThis is the Help file containing the API information for the Toolkit. This file will be auseful resource when developing a new server. Execute this Help file from Explorer.Creating a Help file icon in Program Manager may be helpful.

\Ww\Ioserver\Udsample\Udsample.hlpThis Help file is a template for the UDSAMPLE sample server. Copy it to the directorycontaining the UDSAMPLE.EXE file to run the sample.

Online BookAlso provided is an online book for the I/O Server Toolkit.

\WW\Ioservertoolkit\IOSrv_Toolkit.pdfThe document in this directory is in an Abode Acrobat .PDF file format.

Page 29: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Getting Started with the I/O Server Toolkit 2-5

Compiling a ServerThe sample server includes project definition files for Visual C/C++ for WindowsNT/2000 or Windows 98 Second Edition. environments. Refer to these examples todetermine the proper options for compiling. The server sample is ready for compilingand linking. The Microsoft Visual C/C++ environment use for doing the builds. Forspecific compiling instructions using Microsoft Visual C/C++, Version 6.0 sp3 or later, referto the instructions in the chapter on the I/O Server Code Examples.

The following (brief) compiler switches are recommended:Windows 32: /GX /YX /MD /W4/ "WIN32"

Warning The definition of the preprocessor symbol "WIN32" is necessary. If you donot define this symbol , any conditional code based on "#ifdef WIN32" will not becompiled correctly.

The include files for the I/O Server Toolkit are in the \WW\IOSERVERTOOLKIT\INCsubdirectory. Make sure that your compiler is able to find these includes by properlyconfiguring your INCLUDE environment variable or dialog settings in Microsoft VisualC/C++.

The Microsoft compilers provide some necessary include files in the \SYS sub-directory. Make sure that your compiler is able to find these includes. For example,\MSVC\INCLUDE\SYS or \INCLUDE\SYS needs to be defined in your INCLUDEenvironment variable or settings.

Linking a ServerYou will need to link your server against the proper TOOLKIT7.LIB static library. TheFactorySuite 2000 Toolkit is located in the directory.

\WW\IOSERVERTOOLKIT\LIB\W32\I386\TOOLKITS7.LIBWindows NT/2000 or Windows 98Intel I/O Server Toolkit Object Library

If doing command line builds, make sure your LIB environment variable references theproper directory above for your environment. If using Visual C/C++, reference theproper library in your project definition.

Page 30: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

2-6 Chapter 2

Running a ServerIf your I/O Server uses the Wonderware Common Dialog DLL, you must make surethat the appropriate DLL can be found by the operating system. This can be achievedby placing the DLL in a directory that is referenced by your PATH environment variableor by placing the DLL in the directory with your server executable.

The DLLs provided with the toolkit are:COMMONUI.DLLDDECLIKT.DLLWWCOMMON.DLLWWDLG32A.DLLWWDEBUG.DLLWWCLINTF.DLLWWPERF.DLLWWPERFM.DLLHOOKAGNT.DLLHOOKNDDE.DLLSLS_PERF.DLLSUITELINK_PERF.DLLWWSLSFIX.DLLWWSL.DLL

Note: Supply the proper selection of these DLLs to your target system or customeralong with the server executable. These DLLs are part of Factory Suite 2000 CommonComponents. To install the FactorySuite 2000 Common Component files:Run SETUP.EXE in the \FS2kCOMM\IOServer\Common\Win32\ sub-directory on theinstallation CD.

Page 31: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

3-1

C H A P T E R 3

Overview of an I/O Server

DDE (Dynamic Data Exchange) is a protocol defined by Microsoft. SuiteLink is aproprietary protocol defined by Wonderware. Both these protocols allow independentlydeveloped Windows application programs to exchange data and commands.

Contents! Data Flow! Value/Time/Quality! DDE and SuiteLink Conversations! Logical Devices and Points! Logical Devices/Topics! Items/Points! Advises, Requests, and Pokes! Toolkit Database

Page 32: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

3-2 Chapter 3

Data FlowThe flow of data through an I/O Server can be diagrammed as follows:

All connections are bi-directional, i.e. data can go in either direction.

The Toolkit maintains a database of all the topics and points that are active in the I/OServer, and keeps track of the current data for each point within a topic. It also keepstrack of connections to multiple clients, and handles fan-in and fan-out via the Toolkitdatabase. The server-specific code (i.e. the code you write) does not need to know howmany clients are connected, or whether they are communicating by DDE or SuiteLink.Instead, the server code can focus on communicating to the PLC by whatever device-specific protocol has been established by the manufacturer, and handling updates to andfrom the Toolkit database as if it were the only client.

Value/Time/QualityThe current information stored in the Toolkit database for each data point consists ofthree things:

- Value: The value of a data point represents the contents of some item within thePLC – a memory cell, a register, a bit flag, a string, etc.

Examples: 5, 3.27, 1, “This is a string”

- Time: The date/time stamp (also sometimes called the time mark) for a data pointrepresents the time at which the information about that data point was last updated.

Examples: 03/27/1997 10:23:58.010

- Quality: The quality for a data point represents the validity or trustworthiness ofthe value for that point. If there are no problems, quality for the point is set togood. If there are errors or the data is out of range, the quality is set to bad.Specific quality flag settings are used to indicate particular problems with the data.

Examples: Good, Clamped High, Communications Failed

Page 33: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Overview of an I/O Server 3-3

DDE and SuiteLink ConversationsTwo Windows applications wishing to exchange data must establish a conversation.This is accomplished by the client program opening a connection to the serverapplication.

A client opens a connection by specifying two things: the application name of theserver executable, and the topic name of interest. The application name depends uponthe server program. For example, if you are using the Modicon MODBUS I/O Server,the application name would be “MODBUS”. If using Microsoft Excel, it would be“Excel”. For the Wonderware InTouch runtime program, WindowViewer, it would be“View”.

Topic names are application-dependent. For Excel, the topic is a spreadsheet name,e.g., TOTAL.XLS, etc. For an I/O Server, the topics are names defined when the serveris configured, with each name representing a logical device to which the server isconnected, e.g., PLCFast, PLCSlow, etc. The topic in WindowViewer is always theword “TAGNAME” when accessing data elements in the InTouch runtime database.(The data is exchanged via item or point names.)

Depending on the configuration and the communication mechanism, a client may needto specify additional information to open a conversation:

- For a DDE conversation within a single computer (i.e. a single node configuration),the application name and topic name are sufficient.

- For a DDE conversation between two computers over a network (i.e. a multiplenode configuration), the client must also specify the node name for the computeron which the server is running. For example, if the server is running on a remotecomputer named “FSTest”, the node name “FSTest” must be specified. Also, youmust have NetDDE running on both computers.

- For a SuiteLink conversation, the client must also specify the node name for thecomputer on which the server is running – on a remote computer (multiple nodeconfiguration). Also, you must have the SuiteLink service running (for themultiple node configuration, it must be running on both computers).

Note FastDDE is a proprietary protocol defined by Wonderware that uses DDE totransfer information between the client and server. This protocol uses DDE for thetransport mechanism, but speeds up the transfer of data by using larger blocks ofinformation in each transfer operation. Each block contains many operations for readingand writing individual values, for acknowledging commands, and for flagging thesuccess or failure of those commands. SuiteLink also uses a block-oriented protocol,but uses TCP/IP and Windows Sockets as the transport mechanism.

Page 34: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

3-4 Chapter 3

Logical Devices and PointsAccessing information within an I/O Server requires an understanding of the InTouchconcept of logical devices (also called topics) and points. The data that will beinterfaced with the I/O Server must be treated as one or more logical devices connectedto the server. Points within the logical devices can be read and written.

Generally, an I/O Server is connected to one or more I/O channels (i.e. serial ports,adapter cards, network connections, etc.), and each I/O channel is connected to one ormore PLC devices. A logical device refers to a particular PLC – or even to a portion ofa PLC – that is connected to the I/O Server. A user who is configuring an I/O Serverwill usually take into account such considerations as the following:

- Which I/O channel do I use to talk to the PLC? (e.g. COM1 or COM2, etc.)

- How do I address a particular PLC?In a networked or multi-drop system, it may be necessary to provide an address orrecognition code that identifies a particular device.

- What variation of the protocol do I use to access a particular PLC?A single I/O Server may be connected to several different models from the samemanufacturer, each with its own version of the manufacturer’s protocol. If theserver supports multiple protocols, it will be necessary to select which one to use.

- How often do I access the logical device?

Some devices may be limited in how often they can be accessed (e.g. remotedevices connected by a radio modem that requires warm-up and cool-down).

The user may also wish to define several logical devices for a single PLC in orderto poll groups of points at different intervals – e.g. read some points once persecond and other points once per minute.

For example, let's consider the Modicon MODBUS I/O Server. A logical device forMODBUS would define the communications port and slave ID, while points within alogical device would be either coils or registers. The points will become data valuesthat are transferred via DDE or SuiteLink to other applications. These may be Boolean(0 or 1), integer (signed 32-bit number), real (single precision floating point, 32-bit), orcharacter strings (series of 8-bit characters terminated with a null, 0).

Page 35: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Overview of an I/O Server 3-5

Logical Devices/TopicsFor an I/O Server, there is only one application name, while the topic names have a one-to-one correspondence with logical devices. The notation convention for representingan application and topic is:

Application|Topic

Examples:

Excel|[Book1.XLS]Sheet1View|TagnameModbus|ReactorPLCFast

A logical device (topic) becomes active whenever at least one conversation has beenestablished between the server's logical device and the outside world's applications(clients). The Toolkit library routines call the server code when a client has initiated aconversation to a topic for the first time.

When the last conversation to a topic has terminated, the logical device will bedeactivated. This allows the server code to do start up and shut down of a device orcommunication port, as required. The Toolkit simplifies DDE and SuiteLinkconversation protocol by hiding conversations to multiple clients from the server. Theserver will only see a simple logical device activate or deactivate sequence no matterhow many clients are requesting data.

Page 36: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

3-6 Chapter 3

Items/PointsWithin a DDE or SuiteLink conversation (application|topic) the individual pieces of datathat are passed between applications are known as items or points. For example, an itemin a conversation with Excel would be the identification of the cell in a spreadsheet thatcontains the data value, e.g., R1C1 (row 1 column 1). For a conversation withWindowViewer, an item would be a tagname defined in the database, e.g., ReactorLvl.For a conversation with a Modicon MODBUS I/O Server, an item would be a register orcoil number, e.g., 40001. Therefore, when developing the I/O Server, be sure to selectthe point naming convention that makes sense for your application. The DDE addressconvention for representing an application, topic and item is:

Application|Topic!Item

Examples:

Excel|[Book1.XLS]Sheet1!R1C1View|Tagname!ReactorLvlModbus|ReactorPLCFast!40001

Points will be set active or inactive depending on usage by clients. Within the I/OServer task, a point is considered active if any DDE or SuiteLink conversations arereferencing the item associated with the data point. If only an Excel spreadsheet isreferencing an item in the server, that point is considered active. If the spreadsheet isclosed, that point would become inactive. The same principle applies toWindowViewer.

Assume a point is not trended or alarmed, the point becomes active in the server whenthe point is displayed on the screen. When the point is no longer displayed on thescreen, the point is inactive (assuming that this was the only conversation accessing thepoint).

The Toolkit library routines will call the server code whenever the active status of apoint changes. This allows the server to adjust its polling (data gathering) sequence asrequired.

Page 37: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Overview of an I/O Server 3-7

Advises, Requests and PokesA client can get continuous updates for a point by doing an Advise operation. If a pointis not already “on advise,” the Toolkit calls the functions ProtCreatePoint( ) andProtActivatePoint( ) to activate the point. These functions, which must beimplemented by the server programmer, perform whatever operations are necessary toestablish periodic polling of the PLC to obtain the current value for the data point.When new data is obtained, the server-specific code must interpret the message from thePLC, extract the new value for the point, and pass the new point information to theToolkit via a call to ProtNewVTQFromDevice( ). The Toolkit will then pass the dataon to the client(s). Note that such updates to the client(s) are done by exception – thatis, new information for a point is sent to the client(s) only if it is different from theprevious information. (See the section below regarding the Toolkit database.)

A client can also do a Request operation to get the current value of a point, even if theclient does not have that point “on advise.” This invokes a one-time data transfer of thepoint information, instead of providing a continuous update. Note, however, that theinformation transferred comes from the Toolkit’s database. A Request does notgenerate on-demand polling of the PLC. If the Toolkit’s database does not have acurrent value for the point, it will wait until normal polling provides a value – up to thetime limit specified by the parameter ValidDataTimeout. If the point is not currentlybeing polled, the Toolkit will put it on “temporary advise” for this client to initiatepolling of the PLC for a value.

A client can change the value of a point by doing a Poke operation, which is handled bya DDE Poke or SuiteLink Write. The Toolkit passes the new value onto the server-specific code via the function ProtNewValueForDevice( ). This function, which mustbe implemented by the server programmer, takes the new value and performs whateveroperations are necessary to send that value to the PLC. When a client pokes a newvalue, that value is “reflected” to the other clients, i.e. all other clients with that point“on advise” or “on request” are notified of the new value directly from the Toolkit – i.e.before it is even sent out to the PLC. Poke reflection is built into how the Toolkithandles DDE Pokes; however, it is optional for SuiteLink Writes. See the chapter onSuiteLink and SuiteLink Debug Flags for more information.

Page 38: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

3-8 Chapter 3

Toolkit DatabaseThe I/O Server Toolkit maintains a database of the logical devices (topics) and pointsthat are being accessed in an I/O Server. It also keeps track of client connections toeach Topic!Point on a per-client basis. This means that the Toolkit knows the currentinformation for each point and it knows which clients have been provided with thatinformation.

Note Multiple DDE and/or SuiteLink conversations accessing the same points(topic!items) can be established to the I/O Server at the same time. For example,WindowViewer and an Excel spreadsheet and a dozen other applications may bereferencing the same logical device and item/point at the same time. The Toolkit librarysoftware will automatically handle these situations for the server. The server code needonly be concerned with whether or not the point is active.

When a point is active, the server code should be supplying fresh data from the PLC tothe Toolkit. The Toolkit will store the value/time/quality information in its database andsend updates to all concerned clients. The server code only needs to gather the activedata and pass it on. The Toolkit will handle the rest.

Note, however, that new updates for points “on advise” are passed on to the clients byexception, i.e. only when the point value or quality changes. No update is passed on ifonly the time changes. This reporting mechanism was chosen to reduce bandwidth inthe DDE and SuiteLink channels for points that are polled frequently but do not changemuch. The exception mechanism has been in place for all previous versions of theWonderware I/O Server Toolkit.

The Toolkit makes calls to ProtAllocateLogicalDevice( ) only when the first clientconnects to that logical device. If any clients remain connected to the logical device, theToolkit keeps the logical device open. Only when the last client disconnects from aparticular logical device does the Toolkit call ProtFreeLogicalDevice( ).

The same is true for the point functions. The Toolkit calls ProtCreatePoint( ) onlywhen the first client connects to a point. And only when the last client disconnects froma point it calls ProtDeletePoint( ). The Toolkit will call ProtActivatePoint( ) andProtDeactivatePoint( ) multiple times as clients ( like an InTouch app with switchingwindows ) activate and deactivate items. Some deactivation calls will be ‘folded’ due toefficient logic built into the Toolkit.

Note Recommended IOServer Implementation:

Only react to the first activation of an item. Ignore all subsequent activation for the item.

When the server recieves a deactivation call, only react to the first deactivation for theitem. Since the item is now deactivated subsequent deactivation calls can be ignored.

The Toolkit database uses the case-insensitive string comparison function stricmp( ) todetermine whether the name of a logical device or point is the same as one it already hasin its database. When implementing a server, take special care to ensure that if theToolkit treats two names as the same or different, your server-specific code treats themthe same way. For example, if the point names “V10R” and “V10.” both refer to a realvalue at PLC address V10, keep in mind that the Toolkit will treat these as two differentpoints, even if they are functionally the same. Your implementation of functions such asLogicalAddrCmp( ) [logical address compare for points] should take this into account.

Page 39: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Overview of an I/O Server 3-9

The Toolkit database is organized as a hierarchy of points within a logical device. If apoint is referenced on two different topics, that means it has two different entries in thedatabase – one for each logical device. This is important, because if the topics are beingpolled at different rates, the information for the two entries may differ.

For example, suppose an integer point is incrementing once per second. If one topic ispolled at 500-millisecond intervals and the other is polled at 5-second intervals, theirvalues may not match except at the 5-second marks. A client doing a Request at 2.5second intervals would see the difference. Of course, this depends upon how the server-specific code is implemented – it would be possible to update both points at the 500-millisecond interval. However, if a user has set up two different scan rates for the samepoint, it might be for a specific reason. When developing a server, take care not to putso much “finesse” into the code that it yields results that are counter-intuitive.

Page 40: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

3-10 Chapter 3

Page 41: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

4-1

C H A P T E R 4

Designing an I/O Server

Designing an I/O Server with the I/O Server Toolkit can logically be divided into threeareas.

For a "working" model of an I/O Server, see the sample server that is supplied on theToolkit CD. From the sample code, you can construct either a board server or a serialserver.

Contents! Configuring an I/O Server! Executing the Protocol! Communication with the Device

Page 42: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

4-2 Chapter 4

Configuring an I/O ServerAn I/O Server can only respond to requests for data from a DDE or SuiteLink client.Those requests for data are handled by the Server Toolkit portion of the I/O Server. Thetopic (or logical device) specifies where the data is located. However, the server needsmore information than just the logical device name to supply the data. The server mayneed to know the device identification, device model, or network configuration.Additionally, other parameters may be needed in order to acquire the data, such as thecommunication port being used, the baud rate, parity, etc. If the I/O Server is gettingdata from a board device, it may need to know the memory address of the board. Whenconfiguring the I/O Server, specify how frequently the device is polled for data and howlong to wait for a timeout to occur.

The configuration is performed by the user through the use of menu items in the server'sprogram window. Typically, there are menu items for communications parameters orboard definition, topic parameters, and timing parameters for the server. The entiredefinition of a logical device (topic) may include many hardware and timing parameters.For example, the Modicon MODBUS I/O Server Topic Definition includes thefollowing information:

COM Port (COM1, COM2, etc.)Slave ID (Modicon slave number)Poll Frequency (Frequency each point is polled)Coil Read Size (Number of coils read in each message)Register Read Size (Number of registers read in each message)

We recommend that you provide the user with the ability to name and fully define eachtopic supported by the server. For example, with the Modicon MODBUS I/O Server,the user could, arbitrarily, create a file such as the following:

COM1 9600,8,1,nPLCFast COM1,1,1000,512,64PLCSlow COM1,1,5000,512,64

The server could read this file at start up, allowing the user to use meaningful names toaccess each logical device. This configuration file could just as easily be created by theserver using disk writes and selection boxes to interface to the user. The method used isentirely up to the user. There is no requirement for the server to support multiple topics(logical devices) or a configuration file. If the server is being developed to interface to asimple device containing relatively few points, only one topic needs to be defined.

The two sample programs, UDSERIAL and UDBOARD are good examples of how toimplement a configure menu option.

In order to interface to the Toolkit, the topic naming and item naming conventions mustbe defined. The topic name is generally a text string that contains a meaningful name.It is highly recommended that the item names match the convention used in the logicaldevice and provide enough information to determine the data type, address and possiblyprecision of the point. The points that are to be supported should be decided during thedesign stage.

Page 43: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Designing an I/O Server 4-3

Executing the ProtocolThe protocol is executed when the I/O Server receives a timer event from the Toolkit.The exact data items that are needed have been set up by previous calls from theToolkit. As the designer of the server, you must design the item names such that each isa unique address within the device from which you are requesting data.

Each topic may have a set of active item names. This set of items results in a messagebeing created and sent to the device. This message is sent and data received when theserver gets a timer event from the Toolkit. Since communications protocols are asvaried as the devices themselves, there is not "one way" to accomplish this. TheUDSERIAL example is a skeleton for a serial communication driver. The UDBOARDexample is a skeleton for a board based I/O Server.

Page 44: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

4-4 Chapter 4

Communication with the DeviceThe Toolkit supplies two samples of I/O Servers, based on two different models ofcommunications:

1. The SERIAL sample is based on a device that is accessed through thecommunications port of the PC.

2. The BOARD sample is based on a device that is accessed through a special board inthe PC (Windows Only). A device driver would also be necessary for Windows NTand Windows 2000.

These samples are actually template programs for working I/O Servers. They are thestarting point for all Wonderware servers and have most of the required infrastructurebuilt in to develop a working server. The portions of code that must be written by thedeveloper are noted by comments within the source.

After determining which type of server to be developed, refer to that specific server inthe sample servers section. Most developers choose to modify the few necessaryroutines in the sample programs rather than starting from scratch.

Page 45: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

5-1

C H A P T E R 5

SuiteLink

This section describes how the I/O Server Toolkit uses the Wonderware SuiteLinkcommunication protocol to transfer data between the I/O Server and clients.

Contents! SuiteLink Overview! Components (Files) Associated with SuiteLink! Starting Up a Server! Automatic Throttling of the Data Rate! SuiteLink Debug Flags! Deactivating SuiteLink for a Particular Server! Preventing a Server from Running if SuiteLink Is Unavailable! Preventing a Server from Reflecting SuiteLink Pokes

Page 46: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

5-2 Chapter 5

SuiteLink OverviewWith the advent of FactorySuite 2000, the Wonderware I/O Server Toolkit nowprovides SuiteLink, a proprietary communication protocol that can be used as inaddition to DDE or as an alternative to DDE. Generally speaking, the SuiteLinkprotocol works much like the Wonderware FastDDE protocol:

- The sender allocates a block of memory and fills it with a sequence of itemsdetailing events and data. Events/commands include the following:

- “Registering” a point (assigning a handle or ID number) - “Advising” a point for continuous update - “Requesting” the current value of a point - Writing a value to a point - Providing new polled data for a point - “Unadvising” a point - “Unregistering” a point - Acknowledging a command, indicating success or failure

- The SuiteLink transport moves the contents of this block from the sender to thereceiver.

- The receiver then interprets the block of events, performs the indicated operations,and creates a response block of ACKs, Nacks, data, etc.

- The SuiteLink transport moves the contents of the response block to the originalsender.

The main difference is that SuiteLink uses TCP/IP sessions as a transport instead ofDynamic Data Exchange (DDE). Where an I/O Server is concerned, the type ofcommunication channel between client and server is transparent. That is, the server-specific code does not know – and does not need to know to know – whether a client isconnected via DDE or via SuiteLink.

The following are some of the features SuiteLink offers over DDE:

- Performance optimizations for networked installations with large fan-in and fan-outnetwork node count requirements.

- Reduced interaction between connections when an outage or delay occurs on one ofthe connections.

- Better diagnostic and monitoring capability. - Transport of value, time, quality (VTQ) information. - Use of standard TCP/IP session based transport at fixed port address (5413) to

enable deployment over WAN intranet, RAS dial-up, or Internet if desired.

The following factors may make the continued deployment of DDE/NetDDE preferablein some installations:

- When client and server are on the same PC, DDE may offer reduced data reportinglatency under conditions of low data item counts combined with high (> once persecond) data change rates.

- When client and server are on different PCs, but on the same subnet, and NetBUI isconfigured as the NetDDE transport, NetDDE may offer reduced data reportinglatency under conditions of low data item counts combined with high (> once persecond) data change rates.

A server built with the I/O Server Toolkit will automatically support both SuiteLink andDDE/NetDDE connections. Both varieties of connections can be used simultaneously.

Page 47: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

SuiteLink 5-3

Components (Files) Associated with SuiteLinkA server supporting the SuiteLink protocol relies upon the following components:

- WWSL.DLL, the SuiteLink API library - WWSLS.EXE, the underlying SuiteLink transport library - WWPERF.DLL and WWPERFM.DLL, extensions to the Windows NT/ 2000

Performance Monitor that to allow it to track SuiteLink operation. (in addition, theperformance monitor will automatically create WWSL_PERF.DLL andWWSLS_PERF.DLL DLLs the first time that a SuiteLink enabled server is run.)

- SLSSVC.EXE, the SuiteLink service

In addition, the WinSock TCP/IP DLL that ships with Windows NT/ 2000 is required.

The SuiteLink NT service (SLSSVC.EXE) must be installed and started on the serverPC to allow SuiteLink client applications to connect to the server, even if the client andserver are on the same PC.

Starting Up a ServerWhen the I/O Server starts, the Toolkit attempts to load the SuiteLink API library(WWSL.DLL on Windows NT / 2000), unless SuiteLink is disabled via a Registryentry, see the “SuiteLink Debug Flags” section below. If the DLL can be successfullyloaded, the Toolkit attempts to initialize the SuiteLink API. If both these steps aresuccessful, the server will be ready to communicate with clients via SuiteLink.Otherwise, the Toolkit sends messages to Wonderware Logger indicating that the DLLcould not be loaded, or that it could not be initialized.

Even if SuiteLink cannot be started, an I/O Server can still run with communication toclients only by way of DDE. If you wish to prevent a server from running if SuiteLinkis unavailable, this can be set up with a Registry entry. See the section “SuiteLinkDebug Flags” below.

Page 48: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

5-4 Chapter 5

Automatic Throttling of the Data RateSuiteLink is capable of transporting data at high throughput rates – rates high enoughthat some programs (particularly those that perform a lot of graphics) may not be able tokeep up. For SuiteLink, the Toolkit automatically adjusts the data rate by tracking thesize and number of communication blocks are waiting to be accepted by the receiver. Ifthe amount of waiting data exceeds an upper threshold (the “high water mark”), datatransport to the client is “held off,” and no more polling updates are sent until thewaiting data falls below a lower threshold (the “low water mark”).

This works a little differently from the DDE protocol – where new data is not sent untilthe previous data has been acknowledged – but it has the same overall effect of keepingthe throughput at a level that the client can accommodate. DDE incurs round trip packetdelays even under condition where throttling is not required – SuiteLink does not.

Since each client application may have a different capacity at which it can digest dataupdates, the adjustment of the data throughput is done on a client-by-client basis. Oneclient may throttle back its data rate without reducing the update rate provided to otherclients.

It should be noted that while the Toolkit is waiting for a client to reach its “low watermark,” the polling process can still continue (and should still continue) making updatesto the Toolkit database. While communication to a client is being “held off,” if a changeoccurs to a point, the Toolkit sets an internal flag for that point/client connectionindicating that an update needs to be sent to the client. When the “low water mark” isreached, the most current value in the database will be sent to the client, for each pointthat has a change flagged. Thus, if the point changes several times while the client isbeing “held off,” only the most recent value will be sent. This matches the functionalityof “data folding” in DDE.

Page 49: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

SuiteLink 5-5

SuiteLink Debug FlagsSuiteLink has several Registry flags that can be set for operational or debug purposes.Each such flag applies only to the specific I/O Server for which it is entered, under theRegistry key HKEY_LOCAL_MACHINE\SOFTWARE\Wonderware\<server_name>

The list of flags is as follows:

EnableSuiteLink ( default = 0x1 )A value of 0 disables SuiteLink for the server.

RunWithoutSuiteLinkDLL ( default = 0x1 )A value of 0 prevents the server from running if the SuiteLink DLL cannot beloaded.

SuiteLinkReflectPokes ( default = 0x1 )A value of 0 prevents the server from “reflecting” pokes received via SuiteLink toother clients. See the section “Preventing a Server from Reflecting SuiteLinkPokes” later in this chapter. [Pokes received from clients via DDE will still bereflected, however.]

SuiteLinkFlushReadOnDemand ( default = 0x1 )Normally, a buffer full of read data is “flushed” to the transport process when it isfull or when the SuiteLink protocol demands an immediate flush. A value of 0causes the flush of a partial buffer to occur only on a Protocol Timer Tick event.

SuiteLinkFlushWriteOnDemand ( default = 0x1 )Normally, a buffer full of write responses is “flushed” to the transport process whenit is full or when the SuiteLink protocol demands an immediate flush. A value of 0causes the flush of a partial buffer to occur only on a Protocol Timer Tick event.

DebugSuiteLinkEvents ( default = 0x0 )A value of 1 causes the Toolkit to issue messages to Wonderware Logger fortracing the processing of SuiteLink events.

DebugSuiteLinkCalls ( default = 0x0 )A value of 1 causes the Toolkit to issue messages to Wonderware Logger fortracing SuiteLink API calls.

More details on some of these flags are provided on the following pages.

Page 50: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

5-6 Chapter 5

Deactivating SuiteLink for a Particular ServerSuiteLink can be deactivated for a particular I/O Server via an entry in the Registry. Forexample, to deactivate SuiteLink for the server TESTPROT, use the Registry Editor toaccess or create the following Registry key:

HKEY_LOCAL_MACHINESOFTWARE

WonderwareTESTPROT_IOServer

and for the key TESTPROT_IOServer, edit or create the valueEnableSuiteLink: REG_DWORD: 0

A value of 0 disables SuiteLink, while a value of 1 enables SuiteLink. If SuiteLink isdisabled, the server will not try to load the SuiteLink DLL.

Page 51: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

SuiteLink 5-7

Preventing a Server from Running if SuiteLink isUnavailable

Normally, an I/O Server will still be able to run if SuiteLink cannot be started up. Inthat circumstance, it will only be able to communicate with clients via DDE (bothregular DDE and FastDDE). However, in some environments you may wish to preventthe server from starting if the SuiteLink DLL cannot be loaded. This can be done via anentry in the Registry.

For example, to prevent the server TESTPROT from running without WWSL.DLL, usethe Registry Editor to access or create the following Registry key:

HKEY_LOCAL_MACHINESOFTWARE

WonderwareTESTPROT_IOServer

and for the key TESTPROT_IOServer, edit or create the valueRunWithoutSuiteLinkDLL: REG_DWORD: 0

A value of 0 requires the SuiteLink DLL to be available, while a value of 1 enables theserver to run without SuiteLink. If the SuiteLink DLL cannot be loaded andRunWithoutSuiteLinkDLL is disabled, the Toolkit will display a Message Boxindicating the problem and will not start the server.

Page 52: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

5-8 Chapter 5

Preventing a Server from Reflecting SuiteLink PokesNormally, when a client “pokes” data for a point to an I/O Server (via a DDE POKE ora SuiteLink Write), the Toolkit updates its database, sends the new value out to allclients connected to that point (via a REQUEST or an ADVISE), and then sends thevalue to the server-specific code via ProtNewDataForDevice( ) for transfer to the PLC.This process of sending the new data to all connected clients is called “reflecting” thepoked data, and is an inherent operation of how the Toolkit handles the DDE protocol.However, with SuiteLink, you can suppress the “reflecting” of poked data for aparticular server, via an entry in the Registry.

For example, to prevent the server TESTPROT from reflecting SuiteLink pokes, use theRegistry Editor to access or create the following Registry key:

HKEY_LOCAL_MACHINESOFTWARE

WonderwareTESTPROT_IOServer

and for the key TESTPROT_IOServer, edit or create the valueSuiteLinkReflectPokes: REG_DWORD: 0

A value of 0 prevents the Toolkit from reflecting pokes received from clients viaSuiteLink. Even clients that are connected via DDE will not receive updates, if the pointis poked via SuiteLink. (However, pokes received via DDE will still be reflected, to allclients whether they are connected with DDE or with SuiteLink.) This means thatclients will only see the new data when it is obtained from the PLC via the normalpolling process. This helps confirm that the data has actually been written to the PLC –but only if the point is being polled in the first place.

Page 53: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

6-1

C H A P T E R 6

Time Marks

This section describes the handling of time marks used by the Wonderware I/O ServerToolkit.

Contents! Reading Time Marks! Understanding Time Marks

Page 54: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

6-2 Chapter 6

Reading Time MarksThe I/O Server Toolkit keeps value, time, and quality for each point in the Toolkit’sinternal database, organized by the Topic!Point hierarchy. Whenever a data point isupdated (whether for value, quality, or both), the time of the update is stored in theToolkit database on a topic-by-topic, point-by-point basis.

To support the transfer of Value/Time/Quality (VTQ) information, the Toolkit APIprovides several function calls, in particular the following:

DbNewVTQFromDevice( ) updates value, time, and qualityDbNewTQFromDevice( ) updates time and quality only (value unchanged)

In addition, there are calls in which the time mark is not passed explicitly, but a currentdefault time mark is used:

DbNewValueFromDevice( ) updates value (quality assumed good)DbNewQFromDevice( ) updates quality only (value unchanged)

Most PLCs do not have a date/time clock that is accessible to the I/O Server. For thosewhich do, you have the option of using that date/time clock as your time mark. In thiscase, you should convert the time from the PLC’s format to a FILETIME value (seebelow). Otherwise, you should use a Toolkit API call to read the computer’s time.

Reading the time is accomplished by a call to DbGetGMTasFiletime( ), which internallymakes calls to the Win32 API routines GetSystemTime( ) andSystemTimeToFileTime( ). The FILETIME structure is a 64-bit value that encodes thenumber of 100 nanosecond intervals since January 1, 1601. (Which means the timemark is good for about 30,000 years -- no Year 2000 problem, here!) However, theseare rather expensive calls to make, as regards performance, so getting the time markshould be done only as much as is actually needed.

The Toolkit provides a default time mark only if one is needed. The way it does this isas follows. Just before it calls the server-specific function ProtTimerEvent( ), theToolkit clears an internal flag, indicating that no default time mark is available. Thenlater, if some server-specific code calls a function [such as DbNewValueFromDevice( )or DbNewQFromDevice( )] that needs a default time mark, the flag is checked and, if itis FALSE, the current time is read and saved as the default time mark for use on latercalls during the same timer event, and the flag is set TRUE. This way, if a single loopmakes 1000 calls to DbNewValueFromDevice( ), we don't wind up making 1000 calls toget the default current time (which won't differ by much, under such circumstances, butthe calls will cause a performance hit).

If you are explicitly obtaining the time via a call to DbGetGMTasFiletime( ), you shouldtake into account what these calls will do to server performance. If you're updating10,000 points per second, their time marks aren't going to be very different from oneanother; so you probably don't need 10,000 calls to DbGetGMTasFiletime( ). Youshould limit calls to this function in a way that maximizes performance whilemaintaining a reasonable update rate for the time mark. Reasonable places to get thetime mark include the following:

- Once per entry to ProtTimerEvent( ), and then only if you need it - Once per response message (which would normally encode data for many points)

Of course, depending on the device being served and the application to which it is put, itmay make sense to get time marks more or less often than once per timer event or onceper message. This is largely a judgment call, balancing performance against therequirements of the server, or of the application.

Page 55: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Time Marks 6-3

The following excerpt from the routine UdprotExtractDbItem( ) in UDPROTCL.C ofthe sample server code illustrates one way of getting the time mark only as often asneeded: /* scan through range of symbols covered by this message */ done = FALSE; while ((!done) && (lpSymEnt != (SYMPTR) NULL)) { /* check whether symbol is active and polled by this message */ if (compValue.SymHandle != 0) { /* match found, get parameters from symbol table entry */ myAddr = lpSymEnt->msAddr1; count = lpSymEnt->msCount; numBytes = (WORD) lpSymEnt->msNumBytes;

/* check whether already have date/time stamp */ if (!bHaveDateTimeStamp) { /* set up date/time stamp */#ifdef WIN32 DbGetGMTasFiletime( &ptTime );#else ptTime.dwLowDateTime = 0; ptTime.dwHighDateTime = 0;#endif /* indicate date/time stamp ready */ bHaveDateTimeStamp = TRUE; }

Page 56: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

6-4 Chapter 6

Understanding Time MarksIt is important to understand what time marks mean, i.e. what time they represent andwhen the information is transferred from server to client or vice versa.

When a client sends data to an I/O Server (via a DDE Poke or a SuiteLink Write), theToolkit reads the current time mark and stores it with the new value in the Toolkitdatabase. (Note: the quality received from the client is assumed to be good.) The newvalue, time, and quality are then “reflected” to all other clients that are connected to thatpoint (via an ADVISE or a REQUEST for data). The Toolkit then calls the functionProtNewValueForDevice( ) and passes the value to the server-specific code for transferto the PLC.

When the I/O Server obtains a new value from the PLC, it passes the value, time, andquality to the Toolkit via a call to a function such as DbNewVTQFromDevice( ). TheToolkit stores the new value, time, and quality. It then compares the new value to theold value that was in the database and the new quality to the old quality that was in thedatabase. If the values and/or qualities are different, the new VTQ is reported to allSuiteLink clients. If the values are different, the new value is reported to all DDEclients (i.e. DDE clients don't care about quality). No comparison is made regarding thetime marks. However, since the new time mark does get stored in the Toolkit database,any client connected to that point (via an ADVISE or a REQUEST) will get the mostrecent time mark with the VTQ if it is sent.

In short, a given client will get updated only when the value or quality changes (i.e.reporting by exception). Thus, if you have a point in the PLC that is unchanging, butis being polled repeatedly, a client with that point on ADVISE will probably not havethe most current time stamp – i.e. it will have the time stamp corresponding to the lastupdate the client received. However, the time stamp in the Toolkit's database does getupdated every time the server passes a new value or quality to the Toolkit.

By way of illustration, suppose you have a PLC that is counting an integer, 1..2..3..4..,with the count increasing once per second. And suppose you set the server so that itpolls the PLC at a sample rate of once per 400 milliseconds. Then the polled readingswill be

Time (msec) Value0 1

400 1800 1

1200 21600 22000 32400 32800 33200 43600 4

A client with this point on ADVISE will see the updates when the value actually changes

0 11200 22000 33200 4

Page 57: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Time Marks 6-5

But if a client were to REQUEST the data at, say, 1700 msec into the process, he wouldget

1600 2representing the timestamp of the most recent polled reading.

This last example brings up another important issue: how the Toolkit fulfills a dataREQUEST. This is actually a multi-stage process that may or may not generate a newpolling message or time stamp for the point:

1. When a client issues a REQUEST for a data point, the Toolkit looks to seewhether the point is already being polled (i.e. because it is on ADVISE foranother client).

2. If the point is being polled, the Toolkit checks whether it already has data forthat point in its database.

a. If so, the Toolkit sends the value, time, and quality from the database.

b. If not, the Toolkit waits for normal polling to update the point, and thensends the value, time, and quality to the client.

3. If the point is not being polled, the Toolkit calls ProtActivatePoint( ) to set uppolling for the point, waits for the point to be updated, and then sends thevalue, time, and quality to the client. It then calls ProtDeactivatePoint( ) tostop polling.

Note that steps 2b and 3 amount to putting the point on “temporary advise” for theclient. The Toolkit waits up to the time limit indicated by the WIN.INI settingValidDataTimeout. If no data has arrived by then, the Toolkit sends a NAK, indicatingthat the REQUEST could not be fulfilled. But it should be noted that if the Toolkitdatabase already contains a value for the indicated point, the reported time stamp willrepresent the last time the point was updated, not the time the client issued theREQUEST.

Finally, it is also important to understand that the Toolkit database is organized as aTopic!Point hierarchy – that is, points within a topic. This means that if a point is beingaccessed via two different topics, there will be a separate entry for each point. Thatmeans two time marks! It is possible for a server to cross-reference points on differenttopics, and make sure that if a point is updated on one topic it is updated on all topics.However, most servers do not do this – and it may not even be desirable. Even whenmultiple topics actually refer to points in the same memory space of the same PLC, thedifferent topics may have been created expressly to provide different “scan” rates forparticular points.

Page 58: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

6-6 Chapter 6

Page 59: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

7-1

C H A P T E R 7

Data Quality Flags

This section describes the data quality flags used by the Wonderware I/O ServerToolkit.

Contents! Quality Flags! Quality Flag Settings! Updating Quality Flags

Page 60: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

7-2 Chapter 7

Quality FlagsWonderware I/O Servers can report six (6) mutually exclusive states of quality of databeing sent back to their clients. They are as follows:

1. Good2. Clamped High3. Clamped Low4. Cannot Convert5. Cannot Access Point6. Communications Failed

The conditions under which each of these quality states will be reported are as follows:

1. Gooda. The Communications link has been verified.b. The PLC understood our Poll request and returned a valid response packet.c. If a write occurred, there were no errors during the write process.d. There were no conversion problems with the data contained in the

response packet.EXAMPLE: The value 0x0000A is returned due to a poll of a register containing

10 (decimal).

2. Clamped Higha. The Communications link has been verified.b. The PLC understood our Poll request and returned a valid response packet.c. The register was read or written without error.d. It was necessary to clamp its intended value to a limit because the value

was larger than the maximum allowed.e. In the case of a string, it is truncated.

EXAMPLE: A floating-point value is clamped to FLT_MAX.

3. Clamped Lowa. The Communications link has been verified.b. The PLC understood our Poll request and returned a valid response packet.c. The register was read or written without error.d. It was necessary to clamp its intended value to a limit because the value

was smaller than the minimum allowed.EXAMPLE: A floating-point value is clamped to FLT_MIN.

Page 61: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Data Quality Flags 7-3

4. Cannot Converta. The Communications link has been verified.b. The PLC understood our Poll request and returned a valid response

packet.c. The data from the PLC could not be converted into the desired format.d. The server may return a constant (e.g. zero) in place of the data, or return

quality information alone.e. The data is not usable.f. It is not known whether the value is too large or too small.g. The data returned from the PLC is of the incorrect data type.h. A Floating Point number is returned, but is not a value (i.e. Not A

Number).EXAMPLE: The value of 0x000A is returned from a BCD register in a PLC.

5. Cannot Access Pointa. The Communications link has been verified.b. The PLC understood our Poll request and returned a valid response packet.c. The PLC reported that it could not access the requested point.d. Possibilities for lack of accessibility include, but are not limited to:

1. Item does not exist in PLC memory.2. Item is not currently available (locked in some way due to resource

contention).3. Item is not of the correct format / data type.4. A write attempt was made, but item is read-only.

a. In most cases, a group of items will be affected when one item isinvalid. This is due to the block-polling scheme used by theservers. For example, if one item in a block of 10 is invalid, thenentire block is marked invalid by the PLC. The server will reportinvalid quality for all items in the block.

b. The data is unusable.EXAMPLE: Attempting to read R40001; but R40001 is not defined in the PLC’s

memory map.

6. Communications Faileda. Data communications are down.b. The Topic is in slow poll mode (or equivalent).c. There have been no link validating messages.d. Lack of resources in the server, e.g. a TSR (or driver) cannot allocate

memory.e. Lack of resources in the communications link.f. The communications link is off-line.g. All communications channels are in use.h. The network is unable to route the message to the PLC.

EXAMPLE: Attempting to read data from a PLC which has been powered off.

Page 62: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

7-4 Chapter 7

Quality Flag SettingsThe data quality settings and their relation to the quality flags used by OLE for ProcessControl (OPC) are defined in the file WWSQUAL.H, as follows:// Wonderware Server Data Quality Flags//// Hex OPC OPC// Value Quality Bits Quality Bytes// Quality// MSByte LSByte | SubStatus// XXXXXXXX QQSSSSLL | | Limits#define WW_SQ_GOOD 0x00C0 00000000 11000000 Q=3 S=0 L=0#define WW_SQ_CLAMPHI 0x0056 00000000 01010110 Q=1 S=5 L=2#define WW_SQ_CLAMPLO 0x0055 00000000 01010101 Q=1 S=5 L=1#define WW_SQ_NOCONVERT 0x0040 00000000 01000000 Q=1 S=0 L=0#define WW_SQ_NOACCESS 0x0004 00000000 00000100 Q=0 S=1 L=0#define WW_SQ_NOCOMM 0x0018 00000000 00011000 Q=0 S=6 L=0

It should be noted that when a client sends updated information to a server (via a DDEPOKE or a SuiteLink Write), the data quality is assumed WW_SQ_GOOD, and this isthe quality setting that is stored in the Toolkit database. The other flag settings, for“bad” quality, are set by the server-specific code and passed to the Toolkit via the APIcalls. These quality settings are then sent on to the client(s) as part of the VTQ data.

Page 63: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Data Quality Flags 7-5

Updating Quality FlagsThere are typically four places where you should update the quality flags for a point:

1. In UdprotPrepareWriteMsg( ) if there is any problem with poked data. When aclient “pokes” a value to the server, ProtNewValueForDevice( ) passes the value tothe server-specific code. This, in turn, calls a routine such asUdprotPrepareWriteMsg( ), which creates the byte sequence that will be sent to thedevice. If a string is too long, or a value is out of range, the server-specific codeshould force the value to a legal setting, set a quality of WW_SQ_CLAMPLO orWW_SQ_CLAMPHI, and report the information back to the Toolkit withDbNewVQFromDevice( ). Also, if the point is inaccessible or read-only, it may beappropriate to set the quality to WW_SQ_NOACCESS and callDbNewVQFromDevice( ).

2. In UdprotExtractDbItem( ) when the response from a device is interpreted as pointdata and reported to the Toolkit via DbNewVTQFromDevice( ). When a responsecarries valid data for the point, the quality should normally be set toWW_SQ_GOOD. However, if a string is too long, or a value is out of range, or adata conversion yields an invalid result, the quality should be set toWW_SQ_CLAMPLO, WW_SQ_CLAMPHI, or WW_SQ_NOCONVERT as isappropriate. Also, some PLCs return status information along with the data. Thisstatus information should be mapped to the corresponding WW_SQ_XX qualitysetting.

3. In ProcessValidResponse( ) and other locations where an error response is received,a bad quality should be reported for each point on a message that has a responsepending. If a polling (read) message elicits an error response, a quality ofWW_SQ_NOACCESS should be reported for each point that is being activelypolled by that message. The following excerpts from UDPROTCL.C of the sampleserver illustrate this:

/**************************************************************//** Process validated response back from the device **/

voidWINAPIProcessValidResponse(LPPORT lpPort){ LPUDMSG lpMsg; LPSTAT lpTopic; BYTE FAR *rsp;

/* get pointer to current message, if any */ lpMsg = lpPort->mbCurMsg; if (lpMsg == (LPUDMSG) NULL) { /* no current message, just return */ return; }

Page 64: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

7-6 Chapter 7

/* check whether message has changed */ if (lpMsg->mmChanged) { /* If was changed after it was written -- ignore the response */ return; }

/* get pointer to corresponding station */ lpTopic = lpMsg->mmTopic; if (lpTopic == (LPSTAT) NULL) { /* unable to access station structure, just return */ return; }

/* reset station retry limits */ lpTopic->statRetries = TOPIC_CONSEC_FAILURE_LIMIT; lpTopic->statPortRetries = TOPIC_NORMAL_RETRIES;

/*********************************************************\ How messages are handled may depend on the protocol. The following example handles reads and writes and also processes error responses from the device. \*********************************************************/

/* check type of message received */ rsp = (BYTE FAR *) lpPort->mbRspBuffer; switch (*rsp) { case 0x00: /* error message */ /* indicate error */ UdprotSetMsgQuality (lpTopic, lpMsg, WW_SQ_NOACCESS); if (ShowingErrors) { debug ("Error message received."); showReceivedData (lpPort); } break; default: /* check type of message */ if (lpMsg->mmRead) { /* was a "read" -- extract data from response and report it */ UdprotExtractReadData(lpPort, lpTopic, lpMsg); } break; } /* switch */

/* check type of message */ if (!lpMsg->mmRead) { /* was a "write" -- delete the write message */ UdprotDeleteCurWriteMsg(lpPort); } /* check station status, ensure we're out of slow poll mode */ UdprotSetTopicStatus (lpPort, lpTopic, FALSE);} /* ProcessValidResponse */

Page 65: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Data Quality Flags 7-7

/***********************************************************//* set indicated quality for all symbols on a read message */

staticvoidWINAPIUdprotSetMsgQuality (LPSTAT lpTopic, LPUDMSG lpMsg, PTQUALITY ptQuality ){ LPEXTARRAY lpSymbol_table; SYMPTR lpSymEnt; unsigned long firstSymIdx, lastSymIdx; BOOL done; CHAINSCANNER symbol_scanner; ACTIVE_CHECK compValue;

/* check whether pointers are valid */ if ((lpMsg == (LPUDMSG) NULL) || (lpTopic == (LPSTAT) NULL)) /* no message or no station, just return */ return;

/* only set quality if this is a READ message with active points */ if ((!lpMsg->mmRead) || (lpMsg->mmActiveCt == 0)) return;

/* get pointer to symbol table */ lpSymbol_table = &lpTopic->statSymTab; if (lpSymbol_table == (LPEXTARRAY) NULL) { /* cannot access symbol table structure, just return */ return; }

/* set up comparison value */ compValue.lpMsg = lpMsg; /* pointer to this message */ compValue.finalHandle = lpMsg->mmLastSym; /* last symbol in message */ compValue.SymHandle = 0; /* no symbol found yet */

/* get handles for first and last symbols in this message */ firstSymIdx = lpMsg->mmFirstSym; lastSymIdx = lpMsg->mmLastSym; /* get pointer to first symbol entry referenced by the message */ lpSymEnt = (SYMPTR) NULL; if (firstSymIdx >= SYM_OFFSET) { /* valid symbol handle, get pointer to symbol entry */ lpSymEnt = (SYMPTR) GetExtArrayMemberPtr (lpSymbol_table, firstSymIdx - SYM_OFFSET);

Page 66: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

7-8 Chapter 7

/* get first active symbol referenced by this message */ /* Note: if found, compValue.SymHandle will be non-zero */ if (lpSymEnt != (SYMPTR) NULL) lpSymEnt = (SYMPTR) FindItemStartingAt ( (LPCHAINLINK) lpSymEnt, &lpTopic->statSymUsed, SCAN_FROM_HEAD, IsActiveOnMessage, &compValue, &symbol_scanner); }

/* scan through range of symbols covered by this message */ done = FALSE; while ((!done) && (lpSymEnt != (SYMPTR) NULL)) { /* check whether symbol is active and polled by this message */ if (compValue.SymHandle != 0) { /* match found, report new quality on indicated point */ DbNewQFromDevice(lpMsg->mmIdLogDev, lpSymEnt->msDbHnd, ptQuality); } /* check whether to continue scanning */ if (lpSymEnt->msIndex + SYM_OFFSET == lastSymIdx) { /* last symbol handle for message, exit */ done = TRUE; } else { /* get pointer to next active symbol on message, if any */ lpSymEnt = (SYMPTR) FindNextItem (&symbol_scanner); } }} /* UdprotSetMsgQuality */

Page 67: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Data Quality Flags 7-9

4. In UdprotSetTopicStatus( ) when the communication with the PLC fails, bad qualityof WW_SQ_NOCOMM should be flagged on all points on all messages for thattopic. This would be at the point where the server goes into slow poll mode,attempting to re-establish communications with the PLC. The following excerptsfrom UDPROTCL.C of the sample server illustrate this:

/***********************************************************//** set STATUS item in station structure return TRUE if status is changed **/

staticBOOLWINAPIUdprotSetTopicStatus (LPPORT lpPort, LPSTAT lpTopic, unsignedbFailed){ BOOL changed;

/* initialize return value */ changed = FALSE;

/* no change if pointer is NULL */ if (lpTopic != (LPSTAT) NULL) { /* check current station status */ if (lpTopic->statFailed != bFailed) { /* different from old status, update it */ changed = TRUE; lpTopic->statFailed = bFailed; /* check whether station is active */ if (lpTopic->statStatusActive) { /* active, indicate that station STATUS is due */ lpTopic->statStatusDue = TRUE; } /* check whether new status is OK or failed */ if (bFailed) { /* have logger indicate entering slow poll mode */ debug ("Entering slow poll mode" " on topic \"%Fs\" on port %Fs.", lpTopic->statTopicName, lpPort->mbPortName); /* report new STATUS value if necessary */ UdprotCheckAndUpdateStatus (lpTopic); /* set "no communication" quality flags for all points polled on topic */ UdprotSetTopicQuality (lpTopic, WW_SQ_NOCOMM); } else { /* have logger indicate leaving slow poll mode */ debug ("Leaving slow poll mode" " on topic \"%Fs\" on port %Fs.", lpTopic->statTopicName, lpPort->mbPortName); } }

/* check whether station is failed */ if (bFailed) { /* set up slow poll mode */ UdprotSetSlowPollMode (lpPort, lpTopic); } } /* indicate whether station status changed */ return (changed);} /* UdprotSetTopicStatus */

/********************************************************//* set indicated quality for all items on a topic */

staticvoid

Page 68: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

7-10 Chapter 7

WINAPIUdprotSetTopicQuality( LPSTAT lpTopic, PTQUALITY ptQuality ){ LPUDMSG lpMsg; CHAINSCANNER message_scanner;

/* check whether pointer is valid */ if (lpTopic == (LPSTAT) NULL) /* no station, just return */ return;

/* set indicated quality on every read message for this station */ lpMsg = (LPUDMSG) FindFirstItem (&lpTopic->statReadMsgList, SCAN_FROM_HEAD, NULL, NULL, &message_scanner); while (lpMsg != (LPUDMSG) NULL) { /* set indicated quality on message */ UdprotSetMsgQuality (lpTopic, lpMsg, ptQuality); /* advance to next message on this station */ lpMsg = (LPUDMSG) FindNextItem (&message_scanner); }} /* UdprotSetTopicQuality */

Page 69: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

8-1

C H A P T E R 8

Statistics Functions

This section describes the Statistics API functions provided by the Wonderware I/OServer Toolkit.

Contents! Overview! Statistics from a Client Perspective! Toolkit Standard Statistics

Page 70: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

8-2 Chapter 8

OverviewWith the advent of FactorySuite 2000, the Wonderware I/O Server Toolkit providesextensions to the Toolkit API which allow I/O Servers to easily provide statisticalmeasurements including counters and rates to I/O Clients. This API allows the serverdeveloper to register a statistic with a particular item name with the Toolkit. TheToolkit manages point validation and sends values to any interested clients. Forstatistics which indicate counters, the server protocol code simply manipulates thecounter’s value with the supplied function calls. For statistics which indicate rates, theserver-specific code modifies the input counter and allows the Toolkit to calculate therate of change. In addition to this capability for registering server-specific statistics, theToolkit automatically provides its own internal statistics related to I/O Server activityand function call activity for performance and diagnostic purposes.

Statistics from a Client PerspectiveSince the primary purpose of statistics is to provide users a convenient and easy way togather performance and diagnostic information about their I/O Servers, it is appropriateto first discuss statistics from a user or client program perspective.

There are two basic types of statistics available to an interested I/O Client: countersand rates.

Statistical Counters

A statistical counter is used to represent an accumulated quantity (i.e. “a count”) orstate information. Most often, a counter will be used to indicate the number ofoperations or events that have occurred. For example, a counter would be useful forrepresenting the number of transactions or the number of errors that have happenedsince the server was started. Alternatively, a counter can be used to represent adiscrete state or a text string. So, for example, a counter could be used to indicate a1/0 (good/bad) condition, a string listing all topics currently available on the server,or a string containing the description of the last error that occurred (e.g. “Theconnection has timed out”).

The statistical API in the Toolkit makes it very easy to register and accumulatecounters and have them automatically broadcast to any interested clients. Astatistical counter can be any one of the four Toolkit datatypes: PTT_INTEGER,PTT_REAL, PTT_STRING, or PTT_DISCRETE. Functions for setting the value,adding/subtracting, or incrementing/decrementing counters are provided.

Page 71: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Statistics Functions 8-3

Statistical RatesA statistical rate is used to represent the current rate at which a particular operationor event is occurring. For example, a rate would be useful for representing thenumber of read operations per second on a particular communications port.

The statistical API in the Toolkit makes it very easy to register and calculate ratesand have them automatically broadcast to any interested clients. The server coderegisters the rate item with the Toolkit, assigning it a name, topic, update interval,and time units. Then, the server code simply needs to update the counter whichfeeds into the rate calculation when appropriate. The Toolkit takes care ofcalculating the rate of change of the counter in the specified time units and updatesclients that are interested in the rate item. The counter value which is the inputvalue to the rate calculation can optionally be associated with a previouslyregistered statistical counter. This allows a server to provide both an accumulatorand a rate of change for a particular measurement to clients without having toupdate two different counters.

Statistics CategoriesStatistics should be segregated into different categories or groups depending on thetype of object they are measuring. A group of statistics for a communications port,for example, should be separated from statistics related to DDE or SuiteLink traffic.To facilitate this categorization, several new standard logical devices, or I/O Servertopics, have been defined as part of the FS2000 Toolkit. The purpose of each ofthese standard topics is to hold a logically related group of statistical information.These standard topics will be created by the Toolkit at server startup and deleted atserver shutdown. They require no user configuration. Statistical items can beassigned to these new standard topics or to any user-defined topic in an I/O Server.This assignment of a statistic to a particular device or topic is the responsibility ofthe server developer and is controlled at statistic registration time via the API.

The new system standard topics are summarized in the following table.

Topic Name Description Symbol

SYSTEM I/O Server System Topic STDDEV_SYSTEM$SERVER contains general server wide statistics STDDEV_SERVER

$PORT contains statistics related tocommunication ports/boards STDDEV_PORT

$DEVICE contains statistics related to physicaldevices such as PLCs. STDDEV_DEVICE

$DDE contains statistics related to DDE andSuiteLink communications. STDDEV_DDE

$TKITIF contains statistics related to Toolkit APIfunction calls. STDDEV_TKITIF

In general, an I/O Server you create will only register statistics for the “$SERVER”,“$PORT”, and “$DEVICE” standard topics and for the user-defined topics known to theserver. The generation of statistics for the “SYSTEM”, “$DDE”, and “$TKITIF”should be left to the I/O Server Toolkit.

Page 72: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

8-4 Chapter 8

Reset of CountersI/O Clients have the ability to reset entire groups of statistical counter items. Thestatistical counters can be reset on a per-topic or per-server basis, depending on theitem name and topic used in the DDE Poke or SuiteLink Write operation. The resetoperation is controlled exclusively by the Toolkit and does not require anyprogramming by the server developer or any special notification. Only counterswhich are integer or floating point accumulators are affected by a reset.

Topic Item Name Action when poked

SYSTEM ResetAllStats Resets all counter statistics on all topics inthe I/O Server.

* ResetStats Resets all counter statistics on the indicatedtopic.

Manipulation of Counter Update IntervalThe interval at which a counter is updated to any interested clients is set by thetopic’s counter interval. This interval defaults to 10 seconds but can bemanipulated in several ways. First, the default value for all topics can be changedby adding an entry under the server section in the WIN.INI file in the Windowsdirectory. The entry name is StatCountersInterval, and the units are inmilliseconds.

The counter interval can also be controlled on an individual topic basis in two ways.First, the programmer can control it with the StatSetCountersInterval() functioncall. This function can be called anytime after a topic is created. Second, an I/OClient can control the counter update interval on a topic by manipulating the“CounterInterval” item name for the topic with a DDE Poke or SuiteLink Write.This mechanism requires no programming by the server developer.

Manipulation of Rate IntervalsThe interval at which a particular statistical rate item is calculated is set to an initialdefault value by the server developer at the time the statistic is registered via theAPI. A general guideline is that the statistical rate item should be calculated at aninterval greater than or equal to the topic update interval. It is important toremember that a server which has many rate statistics being calculated frequentlymay have some performance impact on the rest of the system. The server developermay want to provide some way to disable rate calculations if performance may be aconcern. This might be accomplished by a configuration dialog which sets a flag inthe server configuration file, the WIN.INI file, or the system Registry.

It may be desirable at times to allow a user, or I/O Client, to manipulate the intervalat which a particular rate operation is performed. This capability is providedautomatically by the I/O Server Toolkit. Once a rate item has been registered withthe Toolkit, the rate interval for that item can be changed at any time by an I/OClient. The item name to be used for reading and writing the rate interval willalways be the name of the rate item itself followed by the following string:“$INTERVAL”. So, for example, a rate item of “SENDSRATE” could have itscalculation interval manipulated by a DDE Poke or SuiteLink Write operation to theitem “SENDSRATE$INTERVAL”. This I/O Server Item is always an integer withmillisecond units. Again, this dynamic rate interval manipulation is controlledexclusively by the Toolkit and does not require any programming by the serverdeveloper.

Page 73: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Statistics Functions 8-5

Statistics NamesThe names assigned to statistical items may be controlled either by the I/O ServerToolkit or by the server developer. Certain pre-defined statistics, such as thoserelated to DDE, SuiteLink, and Toolkit interface calls, will always exist in everyserver since the Toolkit defines and maintains them. (See the Toolkit StandardStatistics section below.) The naming of protocol-specific statistics will be theresponsiblity of the server developer.

Statistical items are read-only, with the exception of special items for reset ofcounters and manipulation of counter and rate update intervals.

Page 74: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

8-6 Chapter 8

Toolkit Standard StatisticsThe following table defines the standard statistical items which are providedautomatically by the Toolkit:

Topic Item Description

SYSTEM CounterInterval Interval in milliseconds at which counters on topicwill update (integer).

SYSTEM Formats Tab separated list of DDE Formats supported byserver (string).

SYSTEM LastResetTime Last time statistics in topic were reset (string).

SYSTEM TopicItemList Tab separated list of all I/O items available on topic(string).

SYSTEM SysItems Tab separated list of all I/O items available onsystem topic (string).

SYSTEM Topics Tab separated list of all I/O Topics, or logicaldevices, available in the server (string).

SYSTEM ResetAll Resets all counters on all topics.SYSTEM ResetStats Resets all counters on topic (discrete).

SYSTEM WatchDog Watchdog timer which increments every intervalindicated by CounterInterval (integer).

$SERVER CounterInterval Interval in milliseconds at which counters on topicwill update (integer).

$SERVER LastResetTime Last time statistics in topic were reset (string).$SERVER ResetStats Used to reset all counters on topic (discrete).

$SERVER ServerBusyRate Indicates fraction of CPU time during which serveris busy (real).

$SERVER ServerStartTime Time server was started (string).

$SERVER TopicItemList Tab separated list of all I/O items available on topic(string).

$SERVER WatchDog Watchdog timer which increments every intervalindicated by CounterInterval (integer).

Page 75: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Statistics Functions 8-7

Topic Item Description

$TKITIF ActivatePoint$TKITIF ActivatePointFailures$TKITIF AllocateLogicalDevice$TKITIF AllocateLogicalDeviceFailures$TKITIF CounterInterval$TKITIF CreatePoint$TKITIF CreatePointFailures$TKITIF DeactivatePoint$TKITIF DeactivatePointFailures$TKITIF DeallocateLogicalDevice$TKITIF DeallocateLogicalDeviceFailures$TKITIF DeletePoint$TKITIF DeletePointFailures$TKITIF LastResetTime$TKITIF NewValueForDevice$TKITIF NewValueForDeviceFailures$TKITIF NewValueForDeviceRate$TKITIF NewValueForDeviceRate$Interval$TKITIF NewValueFromDevice$TKITIF NewValueFromDeviceFailures$TKITIF NewValueFromDeviceRate$TKITIF NewValueFromDeviceRate$Interval$TKITIF ResetStats$TKITIF TopicItemList$TKITIF WatchDog

$DDE CounterInterval$DDE DDEAcksReceived$DDE DDEAcksSent$DDE DDEAdviseFailures$DDE DDEAdvises$DDE DDEAdvises$DDE DDEBusyReceived$DDE DDEDataBytesReceived$DDE DDEDataBytesReceivedRate$DDE DDEDataBytesReceivedRate$Interval$DDE DDEDataBytesSent$DDE DDEDataBytesSentRate$DDE DDEDataBytesSentRate$Interval$DDE DDEExecuteFailures$DDE DDEExecutes$DDE DDEInitiateFailures

Page 76: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

8-8 Chapter 8

Topic Item Description

$DDE DDEInitiates$DDE DDENaksReceived$DDE DDENaksSent$DDE DDEPokeFailures$DDE DDEPokes$DDE DDEPokesRate$DDE DDEPokesRate$Interval$DDE DDERequestFailures$DDE DDERequests$DDE DDETerminateFailures$DDE DDETerminates$DDE DDEUnadviseFailures$DDE DDEUnadvises$DDE LastResetTime$DDE ResetStats$DDE TopicItemList$DDE WatchDog

* CounterInterval* LastResetTime* ResetStats

* TopicItemList Tab-separated listof statistical items.

* WatchDog

* Indicates all other topics.

Page 77: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-1

C H A P T E R 9

I/O Server ToolkitFunction Summary

This chapter summarizes Server Toolkit Application Programming Interface (API)functions. The following briefly describes the categories of the I/O Server Toolkitfunctions and their primary purpose.

The discussions and illustrations on the following pages describe how the Toolkithandles client/server activities, such as initiating connections, advising points, pokingvalues, etc. While the discussion is based on DDE, please note that the correspondingactivities also take place when SuiteLink is used.

Note Wonderware I/O Server Toolkit functions that are underlined and bold, e.g.,ProtInit(), must be developed. Wonderware I/O Server Toolkit functions that areprovided by the Toolkit will be bolded but not underlined, e.g.,DbNewValueFromDevice(). For more information, see the "API Function Reference"chapter for complete function descriptions.

Contents! Protocol Initialization & Setup Functions! Logical Device Management Functions! Point/Item Management Functions! Toolkit Database Interface for Protocol Functions! Timer Functions! String PTVALUE Manipulation Functions! Memory Management Functions! Memory Access Permission Functions - Windows Only! Common Dialog Functions! Selection Boxes - Optional! Miscellaneous Functions! Windows NT Porting Functions! Macros for Portability! Additional Information

Page 78: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-2 Chapter 9

Protocol Initialization & Setup FunctionsThis section describes the functions (indicated by the underlined names) that must bewritten and included in the I/O Server 's initialization. These functions are called by theToolkit.

Function Description

ProtClose() Called immediately prior to the server closing. Performsany necessary clean-up such as freeing memory, closingcommunications ports, etc.

ProtDefWindowProc() Allows the server application window to be customized.

ProtGetDriverName() Provides the Toolkit with the name of the I/O Server.

ProtGetValidDataTimeout() Returns the length of time the Toolkit is to wait for databefore issuing a timeout to the DDE client requestinginformation.

ProtTimerEvent() Called at the frequency specified in the call toSysTimerSetupProtTimer().

Allows the server to execute and perform tasks necessaryto obtain the requested data.

ProtInit() Allows the server to perform required initialization suchas:• Obtaining defaults from WIN.INI (if applicable)• Reading the configuration file (if any)• Calls SysTimerSetupProtTimer()• Calls SysTimerSetupRequestTimer()

Page 79: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-3

Logical Device Management FunctionsThe following functions are used by the Toolkit to allocate and deallocate logicaldevices.

Function Description

ProtAllocateLogicalDevice() Called when a client initiates a DDE conversation to theserver.

Returns a handle that the Toolkit will use in all futurecalls to routines dealing with that logical devicehLogDev. The handle is an unsigned long which ismeaningful to the server. It is used in all subsequentcalls to identify the logical device instead of using thename. This way, the name (which is a string) need onlybe decoded once, when ProtAllocateLogicalDevice() iscalled.

Must validate the topic name (i.e., logical device name).

Must save the idLogDev for use in other Toolkitroutines.

Note If NULL is returned, the Initiate will not be Acked,i.e., the conversation will not be established.

ProtExecute() Called when the client sends an Execute DDE messageto a conversation on the server.

This function should execute the string supplied by theclient and return success or failure based on thecommand supplied.

ProtFreeLogicalDevice() Called when the last client has sent a terminate to theserver for this topic.

All memory associated with this logical device must befreed.

Page 80: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-4 Chapter 9

Examples of Logical Device ManagementThe following examples summarize what happens regarding logical device managementon a typical conversation initiation and termination.

What is called on InitiateDDE User Toolkit The Server

---- WM_DDE_INITIATE --->| |--- ProtAllocateLogicalDevice ()---> | [if first use of device] |<-- return handle to logical device --- |<--- WM_DDE_ACK ---------| [if return is non-NULL or device | already exists]

What is called on a TerminateDDE User Toolkit The Server

---- WM_DDE_TERMINATE --->| |--- ProtFreeLogicalDevice () |---> [if last use of device] |<-----------------------------<--- WM_DDE_TERMINATE ----|

Page 81: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-5

Point/Item Management FunctionsPoint management includes defining points (setting up data structures), starting andstopping polling, sending and receiving data values and shutting down. Each item willhave two handles (unique identifiers). One is given to the server by the Toolkit hDb,and used when the server calls the Toolkit concerning an item. The other is provided bythe server hProt and given to the Toolkit. It will be used when the Toolkit calls theserver concerning a point. When a valid point is being created, you must save the hDbdatabase handle parameter. It will be the handle (unique identifier) used by the Toolkitdatabase to find this item. The return hProt for a valid item is a non-zero handle that isunique to this point in this topic. The choice of these hProt handles is completely up toyou and should make your later point processing more simple, e.g., use the index ormemory handle pointing to an element in a chain of created points. Regarding pointmanagement, the following set of functions must be supplied to the Toolkit.

Function Description

ProtActivatePoint() Called when the Toolkit wants the server to startreporting changing point values by callingDbNewValueFromDevice().

At this point the server should start "polling" the pointfrom the appropriate logical device. Calls to send datato the Toolkit via DbNewValueFromDevice() shouldonly be done between the ProtActivatePoint() and theProtDeactivatePoint() calls.

ProtCreatePoint() Validates the point name and returns the type of pointthe name represents (discrete, integer, etc.)

Must remember the hDb passed in since this is requiredfor all calls to the Toolkit databaseDbNewValueFromDevice().

Must return hProt which represents a handle that isimportant to you. All subsequent calls that the Toolkitmakes to you regarding this point will pass hLogDev,returned from ProtAllocateLogicalDevice() and hProt,returned from ProtCreatePoint().

This function should return NULL if the point is invalidor not accessible for this device. If this routine returnsNULL, the DDE message that caused the call toProtCreatePoint() will return a NAACO. (Do not callDbNewValueFromDevice() until theProtActivatePoint() has been called.)

Page 82: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-6 Chapter 9

Function Description

ProtDeactivatePoint() Called when the Toolkit wants to stop reporting pointvalue changes. At this point, the server should stoppolling for this point.

ProtNewValueForDevice() Called when the Toolkit wants to write a new value tothe device. The ptValue parameter is a union that isused to pass point values to and from the Toolkit andsupports a discrete, integer, real or string.

ProtDeletePoint() Called when the Toolkit determines that no more clientsare interested in this point. The server should delete orrelease any memory structures associated with the point.If a write is still outstanding, the server should stillperform the write.

What is called on a RequestA Request is a one-time data transfer.

DDE User Toolkit The Server---- WM_DDE_REQUEST --->| |--- ProtCreatePoint () ---> | [if not created] |<-- return hProt and point type ---- |<--- NACK --------------| [if ProtCreatePoint() returns NULL] | |--- ProtActivatePoint () ---> | [if not activated] |<----------------------------------- | | ...polling begins (if necessary)... | |<-- DbNewValueFromDevice () --------- |-----------------------------------><--- WM_DDE_DATA -------| |--- ProtDeactivatePoint () ---> | [if last activation] |<-----------------------------------

Page 83: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-7

What is called on an Advise/UnadviseAn Advise asks for a notification of changes. An Unadvise asks for a discontinuation ofthe notifications.

DDE User Toolkit The Server--- WM_DDE_ADVISE ---> | |--- ProtCreatePoint () ---> | [if not created] |<--- return hProt and point type ---- |<--- NACK ---------------| [if ProtCreatePoint() returns NULL] | |--- ProtActivatePoint () ---> | [if not activated] |<------------------------------------ | |... polling begins (if necessary) ... | |<--- DbNewValueFromDevice () --------- |------------------------------------><--- WM_DDE_DATA --------| | |<--- DbNewValueFromDevice () --------- |------------------------------------> |<--- WM_DDE_DATA --------| [if data changes] | |<--- DbNewValueFromDevice() --------- |------------------------------------> |<--- WM_DDE_DATA --------| [if data changes] | |---- WM_DDE_UNADVISE --->| |--- ProtDeactivatePoint () ---> | [if last activation] |<------------------------------------

What is called on a PokeA Poke is a one-time write of a point value.

DDE User Toolkit The Server---- WM_DDE_POKE ------->| |--- ProtCreatePoint () ---> | [if point doesn't exist] |<-- return hProt and point type ---- |<--- NACK ---------------| [if ProtCreatePoint() returns NULL] | |--- ProtNewValueForDevice () ---> |<----------------------------------- |<--- WM_DDE_ACK ---------| | | ... send write to device ... |

A ptValue is a union that is used to pass point values to and from the Toolkit. TheptValue supports discrete, integer, real and string. Strings are handled in a special way -via the functions that are provided for you in TOOLKIT7.LIB. Refer to the APIFunction Reference chapter for more details on the above routines.

Page 84: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-8 Chapter 9

Toolkit Database Interface for Protocol FunctionsThis section describes the functions that are provided in TOOLKIT7.LIB to allow theserver to update the Toolkit database.

Function Description

DbNewVTQFromDevice() Is called every time a point value is retrieved from thedevice. The Toolkit will determine whether or not thevalue has changed since the last time it was read. This iscritical for compatibility with later versions of theToolkit.

DbNewTQFromDevice() Is called when communication problems with the PLCoccur. Errors or a lost connection means every point onthe effected message or topic should be marked ashaving bad quality.

DbSetHProt() Allows the server to change the hProt value for a point(item identifies from your code to the Toolkit database).

Timer FunctionsThis section describes the timer functions that must be called to set up the Toolkit timers atrates appropriate for the protocol being used.

Function Description

SysTimerSetupProtTimer() Sets up a timer that goes off every dwMsec millisecondsand calls ProtTimerEvent().

This timer should be set to a value that is reasonable forthe protocol data supply rate. Intervals that arearbitrarily too short will result in needless systemoverhead.

SysTimerSetupRequestTimer() Sets up a timer that goes off every dwMsec millisecondsand checks for valid data timeout errors within theToolkit database.

This timer should be set to a value that is reasonable forthe protocol data timeout. The interval should be areasonable factor of the ValidDataTimeout parameterreturned in the ProtGetValidDataTimeout() calls.Intervals that are arbitrarily too short will result inneedless system overhead.

Page 85: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-9

String PTVALUE Manipulation FunctionsThe PTVALUE union is used to pass point values between the various functionsdescribed in other sections of this document (for example, ProtNewValueForDevice() ).

The following describes the functions that must be used to manipulate the hString fieldof this structure.

Function Description

StrValSetNString() Initializes a ptValue string and does not require a NULL-terminated string.

StrValSetString() Initializes a ptValue string.

StrValStringFree() Frees the associated string memory.

StrValStringLock() Locks a string in memory to allow access to it.

StrValStringUnlock() Unlocks the memory associated with a string.

Example Code #1 - Sending Data to the Toolkit Database/* Send a string item to the database. Replace our local string first. */ptValue.hString = NULL;ptValue = StrValSetString(ptValue,lpszValNew);DbNewValueFromDevice( idDev, hDbItem, ptValue ); /* The Toolkit will free the ptValue memory for me. This ptValue is now untouchable, forget it. */

Example Code #2 - Accepting Data from the Toolkit forthe DeviceProtNewValueForDevice( hLogDev, hProt, ptValue ) ... switch (info[i].ptype) case PTT_STRING: lpszValNew = StrValStringLock( ptValue ); ... /* use string */ ... StrValStringUnlock( ptValue ); break; ...

Page 86: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-10 Chapter 9

Caveats with StrVal Strings

Caveat #1 - Modifying PTVALUE withoutStrValSetString()Caution must be taken when using strings in ptValue.

The following code is a BAD example:

BOOLFAR PASCALChangeValue( ptValue, lpszNewVal )PTVALUE ptValue;LPSTR lpszNewVal;{ LPSTR lpszVal; BOOL rtn; rtn = FALSE; if( ptValue.hString != NULL ) { lpszVal = StrValStringLock( ptValue ); if( lpszVal ) { /* UNSAFE - the memory allocated for ptValue may not be enough for lpszNewVal! */ lstrcpy( lpszVal, lpszNewVal ); StrValStringUnlock( ptValue ); rtn = TRUE; } } return( rtn );}

The moral of the above example is to always use StrValSetString() to change the valueof a string. This will correctly size the memory needed to store the string (by freeing thememory associated with the old string and allocating new memory for the new string).

Page 87: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-11

Caveat #2 - Modifying PTVALUEs from DatabaseWhen the database calls ProtNewValueForDevice(), consider the ptValue to be read-only. The hString in the ptValue passed to ProtNewValueForDevice() is stored in theToolkit database. If you cause this memory to be freed, the database may malfunction.Thus, only call StrValStringLock() and StrValStringUnlock() on the ptValue receivedfrom ProtNewValueForDevice()! Never call StrValSetString() orStrValStringFree() with this ptValue!

An example of correct usage of a string in ProtNewValueForDevice() is as follows:BOOLFAR PASCALProtNewValueForDevice( hLogDev, hProt, ptValue )HLOGDEV hLogDev;HPROT hProt;PTVALUE ptValue;{char buffer[200];BOOL rtn; rtn = FALSE; /* This device handles only string point values. */ if( hLogDev = 1 && hProt = 1 && ptValue.hString != NULL ) { /* Lock the read-only input string. */ lpszVal = StrValStringLock( ptValue ); if( lpszVal ) { lstrcpy( (LPSTR)buffer, lpszVal ); StrValStringUnlock( ptValue ); /* Now we can process the input string in the local buffer*/ rtn = TRUE; } } return( rtn );}

Page 88: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-12 Chapter 9

Memory Management FunctionsWonderware has developed a heap manager that is similar to GlobalAlloc(),GlobalLock(), GlobalUnlock(), GlobalFree(), and GlobalReAlloc(). This heap managerallows the developer to allocate many different sized memory blocks while minimizingthe number of actual global memory handles (selectors) consumed. The correspondingcalls are wwHeap_Init(), wwHeap_AllocPtr(), wwHeap_ReAllocPtr(),wwHeap_FreePtr() and wwHeap_Release(). All of these functions are described indetail in the "API Function Reference" chapter.

For compatibility reasons, Wonderware has extended the heap manager to run onWindows NT/ 2000. A new common API has been developed which supports heapmanagement on both Windows 98 and Windows NT / 2000. This new heap API willwork on either platform. If you have an existing I/O Server developed using the oldheap API functions, you will need to convert these function calls to the new API prior tobuilding your server. Refer to the "Getting Started with the I/O Server Toolkit" chapterfor details.

Function Description

wwHeap_AllocPtr() Allocate the specified amount of memory using the heapspecified by hHeap.

wwHeap_FreePtr() Free the allocated memory specified by lpPtr.

wwHeap_Init() Create and initialize a heap.

wwHeap_ReAllocPtr() Re-allocate the specified amount of memory used in theheap specified by lpPtr.

wwHeap_Release() Free a heap created with wwHeap_Init().

Memory Access Permission Functions - Windows OnlyFor specialized applications that require access to fixed real mode addresses in memory,there are two routines to support this addressing in Windows protected-mode:RequestPermission() and RelinquishPermission().

Function Description

RelinquishPermission() Will release the selector that was allocated to thismemory address range, identified by hPermission.

RequestPermission() Access memory at a fixed Real Mode location.

Page 89: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-13

Common Dialog FunctionsVersion 5.0 of the I/O Server Toolkit provides a new Dynamic Link Library (DLL) calledWWCOMDLG.DLL. This DLL provides a set of functions that are available to the I/OServer developer for the purpose of providing a standard look and feel for dialogs,message boxes, and graphical controls that are common to all servers. All serial servers,for example, need to provide some way of configuring communications ports. TheWonderware Common Dialog DLL provides the WWConfigureComPort() function forthis purpose.

Although not required, the Wonderware Common Dialog functions are recommended forall I/O Servers. They provide a standard graphical user interface for server configurationand message boxes. The UDBOARD and UDSERIAL sample servers included with theToolkit have been upgraded to include usage of the Wonderware Common Dialogfunctions.

Function Description

WWCenterDialog() Places the specified dialog at the center of the screen.

WWConfigureComPort() Displays and manages the communications port settingsconfiguration dialog. It should only be used by serialservers. This dialog allows configuration ofcommunications parameters for one or more serialcommunications ports. These settings are written to theWW_CP_DLG_LABELS structure for use by theserver.

WWConfigureServer() Displays and manages the server parameterconfiguration dialog. This dialog allows configurationof several parameters related to overall operation of theI/O Server. These settings are written out as profileinformation to the WIN.INI file by this dialog functionand only take effect upon restarting of the server.

WWConfirm() Displays and manages the confirmation dialog whichindicates the directory or file where server settings are tobe saved. It should only be called when theconfiguration file does not currently exist.

WWDisplayAboutBox() Displays and manages the dialog displaying copyrightand version information. It is generally intended for useby Wonderware servers since it displays theWonderware copyright information. However, it doesprovide facilities for easily displaying version and dateinformation and is available for use by other servers.

WWDisplayConfigNotAllow() Displays a message box indicating that configuration ofthe server is not allowed while the server is in use.

WWDisplayErrorCreating() Displays a message box indicating that an error wasencountered while creating the specified file.

WWDisplayErrorReading() Displays a message box indicating that an error wasencountered while reading the specified file.

WWDisplayErrorWriting() Displays a message box indicating that an error wasencountered while writing the specified file.

Page 90: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-14 Chapter 9

Function Description

WWDisplayKeyNotEnab() Displays a message box indicating that the installedsecurity key does not enable operation of this I/O Server.

WWDisplayKeyNotInst() Displays a message box indicating that the requiredsecurity key is not installed on the system.

WWDisplayOutofMemory() Displays a message box indicating that an error wasencountered while allocating memory for the specifiedobject.

WWFormCpModeString() Creates a null-terminated string containing devicecontrol information.

WWGetDialogHandle() Returns a window handle to the top-most dialog in thecurrent application.

WWInitComPortComboBox()Creates a communications port selection box for displayon a dialog. Most commonly, it will be used in a topicconfiguration dialog for selection of the communicationsport for serial communications.

WWSelect() Displays a dialog containing a list box which willcontain a list of strings specified by the server. The userwill be provided options for adding, modifying, ordeleting entries from this list. This function is mostcommonly used to display a list of topics or boards forconfiguration.

WWTranslateCDlgToWinBaud()Translates the WWCOMDLG constant for baud rate tothe Windows equivalent.

WWTranslateCDlgToWinData()Translates the WWCOMDLG constant for number ofdata bits to the Windows equivalent.

WWTranslateCDlgToWinParity()Translates the WWCOMDLG constant for parity to theWindows equivalent.

WWTranslateCDlgToWinStop()Translates the WWCOMDLG constant for number ofstop bits to the Windows equivalent.

WWTranslateWinBaudToCDlg()Translates the Windows constant for baud rate to theWWCOMDLG equivalent.

WWTranslateWinDataToCDlg()Translates the Windows constant for number of data bits(7 or 8) to the WWCOMDLG equivalent.

Page 91: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-15

Function Description

WWTranslateWinParityToCDlg()Translates the Windows constant for parity to theWWCOMDLG equivalent.

WWTranslateWinStopToCDlg()Translates the Windows constant for number of stop bitsto the WWCOMDLG equivalent.

WWVerifyComDlgRev() Verifies that the version of WWCOMDLG.DLLinstalled on the system is at least as new as the specifiedversion. It also returns the major and minor versionnumbers of the installed WWCOMDLG.DLL to theserver. This function is intended for compatibilitychecking.

Page 92: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-16 Chapter 9

Selection Boxes - OptionalThe following list of functions provide selection box capability, as used in InTouch. Ingeneral, these functions are no longer necessary or recommended since the WWSelect()function provides similar functionality.

Function Description

SelBoxAddEntry() Add a string entry to a selection box set of choices to bedisplayed when the SelBoxUserSelect() call is done.

SelBoxSetupStart() Does the basic setup for a selection box.

SelBoxUserSelect() Actually displays the selection box and processes all thebuttons.

SelBoxUserSelection() Call this routine after SelBoxUserSelect() if you wish toget a list of what the user selected.

SelListFree() Frees the memory associated with the selection list.

SelListGetSelection() Gets the indicator value for a selection at the specifiednumber.

SelListNumSelections() Returns how many entries are in the specified hSelList.

Page 93: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-17

Miscellaneous FunctionsThis section describes the miscellaneous functions that can be used.

Function Description

AdjustWindowSizeFromWinIni()Adjusts the size of the server window to the last savedsize.

CheckConfigFileCmdLine() Checks the command line for optional configuration filepath. By default, most of the I/O Servers save theirconfiguration file path in the Windows WIN.INI file. Ifthe user defines the file path on the command line(default), or an alternate file is used, the server, withproper coding, can read the configuration file other thanthe one specified in the WIN.INI file.

debug() Sends a debug message to WWLOGGER.EXE whichcan log it to disk, monochrome adapter, AUX port, etc.

The #include "debug.h" is a required include file.

GetAppName() Returns the application name for the server. Thisapplication name is stored in the Toolkit and initially setby a call to ProtGetDriverName() during server startup.

GetString() Retrieves a string from the resource file.

UdInit() Is intended for use by a Windows application thatalready exists and needs to be extended to include theDDE capability provided by the Toolkit. It is used toinitialize the I/O Server Toolkit and should only be usedby a Windows application which supplies its ownWinMain() function. UdInit() should be called early inthe activation of such applications. Most I/O Servers donot have to call this function since they allow the Toolkitto supply the WinMain() function. The parameter list isidentical to the parameter list for the WindowsWinMain() function.

UdReadAnyMore() Reads a bAnyMore flag from the configuration file. Thisflag is used within the configuration file to indicatewhether more records of a certain type exist. Such a flagis usually necessary when the number of records isunknown.

UdReadVersion() Reads the version number from the server configurationfile. It also verifies that the magic number stored in thefile matches the specified magic number.

Page 94: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-18 Chapter 9

Function DescriptionUdTerminate() Is intended for use by Windows applications that already

exist and need to be extended to include the DDEcapability provided by the toolkit. It is used to close theI/O Server Toolkit, but it should only be used by aWindows application which supplies its own WinMain()function and calls the UdInit() function to initialize thetoolkit. UdTerminate() should be called at applicationshutdown time. Most I/O Servers do not have to call thisfunction since they allow the toolkit to supply theWinMain() function.

UdWriteAnyMore() Writes a bAnyMore flag to the configuration file. Thisflag is used within the configuration file to indicatewhether more records of a certain type exist.

UdWriteVersion() Writes the version number, magic number, date, andtime to the server configuration file.

WriteWindowSizeToWinIni()Saves the size of the server window to the last adjustedsize.

Page 95: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-19

Windows NT Porting FunctionsVersion 5.0 of the I/O Server Toolkit includes an Windows NT version that providessupport for the Windows NT/2000 operating system. Since there are a large number ofI/O Servers which currently only operate on the Windows operating system, a significantamount of porting work will be required to provide native Windows NT support forthese servers. To minimize this porting effort and, at the same time, to simplify softwaremaintenance, Wonderware has developed a set of porting functions and macros that canbe utilized for Windows NT. These tools will significantly reduce the amount of timerequired to port a Windows server to the Windows NT environment.

Although not required, the Wonderware NT porting functions and macros arerecommended for all I/O Servers. They provide a common interface that allow the samefunction call to be used on both Windows and Windows NT. The UDBOARD andUDSERIAL sample servers included with the Toolkit have been upgraded to includeusage of Wonderware NT porting functions and macros.

There are three specific areas for Windows NT porting, they are:• Windows Function Emulators• Windows and Windows NT Compatibility Functions• Macros for Portability

Page 96: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-20 Chapter 9

Windows Function EmulatorsThe following set of functions provide Windows NT emulation of Windows functions.They are only available in the Windows NT I/O Server Toolkit since the Windows APIalready incorporates them.

Function Description

CloseComm() Closes a serial communications port.

FlushComm() Flushes all characters from the transmission or receivingqueue of the specified communications device.

GetCommError() Retrieves the most recent error value and current statusfor the specified device. It also clears the error.

GetCommEventMask() Retrieves and then clears the event word for thespecified communications device.

GetTextExtent() Provides emulation of the Windows GetTextExtent()function for the Windows NT platform.

OpenComm() Opens a serial communications port for communications.

ReadComm() Reads up to a specified number of bytes from the givencommunications device.

SetCommEventMask() Does nothing on Windows NT. It is provided forcommon code convenience only.

WriteComm() Writes the specified bytes to the specifiedcommunications device.

Page 97: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-21

Windows/Windows NT Compatibility FunctionsThese functions are available in both the Windows and Windows NT I/O Server Toolkitand provide a compatible function to allow common code on both platforms.

Function Description

EnableCommNotification() Simulates the Windows EnableCommNotification()function for Windows versions older than Windows 3.1and for Windows NT. It performs no operation on theseplatforms and is provided for common code convenienceonly. On Windows versions prior to 3.0, it enables ordisables WM_COMMNOTIFY message posting to thegiven window.

NTSrvr_BuildCommDCB() Translates a device-definition string into appropriateserial device control block codes.

The return value from this function is compatible withthe Windows version of the BuildCommDCB()function.

NTSrvr_GetCommState() Retrieves the device control block for the specifieddevice. The return value from this function is compatiblewith the Windows version of the GetCommState()function.

NTSrvr_SetCommState() Sets a communications device to the state specified by adevice control block. The return value from this functionis compatible with the Windows version of theBuildCommDCB() function.

NTSrvr_SetDCB_Dtr() Modifies the DTR (data-terminal-ready) flow-controlsetting in the device control block.

NTSrvr_SetDCB_Rts() Modifies the RTS (request-to-send) flow-control settingin the device control block.

PfnSendEmSelectAll() Selects all the text in the identified edit control. It willalso scroll the caret into view if the bScrollCaret flag isTRUE.

PfnSendEmSelectRange() Selects a range of text in the identified edit control. Itwill also scroll the caret into view if the bScrollCaretflag is TRUE.

Page 98: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-22 Chapter 9

Macros for PortabilityThe following macros have been provided in the NTCONV.H header file to assist indeveloping common code servers for Windows and Windows NT. These macros shouldbe self-explanatory by looking at their definitions .

Windows NT-only MACROS#define huge#define LocalInit(a, b, c) (1)#define LockData(a)

#define lstrchr strchr#define lstrncpy strncpy#define lstrcpyn strncpy

#define MoveTo(A,B,C) MoveToEx(A, B, C, NULL)

Windows and Windows NT MACROS#ifdef WIN32#define FARWNDPROC WNDPROC#else#define FARWNDPROC FARPROC#endif

#ifdef WIN32#define SM_MINUS_ONE (HWND) 0xFFFFFFFF#else#define SM_MINUS_ONE 0xFFFF#endif

#ifdef WIN32

#define OPENRead(A) _open(A, _O_RDONLY | _O_BINARY)#define OPENCreate(A) _open(A, _O_BINARY | _O_RDWR |_O_TRUNC | _O_CREAT,

_S_IREAD | _S_IWRITE);#define LWRITE _write#define LREAD _read#define LSEEK _lseek#define LCLOSE _close#else#define OPENRead(A) open(A, O_RDONLY | O_BINARY)#define OPENCreate(A) open(A, O_RDWR | O_BINARY |O_TRUNC | O_CREAT, S_IREAD |

S_IWRITE);#define LWRITE _lwrite#define LREAD _lread#define LSEEK _llseek#define LCLOSE close#endif

Page 99: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-23

Windows-only MACROS#define InSendMessage() (FALSE)#define FreeDDElParam(a, b)#define PackDDElParam(a, b, c) (MAKELONG((b), (c)))#define UnpackDDElParam(a, b, c, d) ((*(c) = LOWORD(b)) | (*(d) =HIWORD(b)) | 1)

#if (WINVER < 0x030a)typedef unsigned int UINT ;typedef UINT WPARAM ;typedef long LPARAM ;#endif

Page 100: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-24 Chapter 9

Additional Information

Required External DataThe following data items are required by the I/O Server Toolkit:

extern HWND hWndParentextern HANDLE hInst

These data variables must be declared in the server for the Toolkit to function

properly.About the .DEF FileA .DEF file for the main executable is not needed for Win32 servers.

About the .RC FileThe .RC (resource) file must contain the following items for the Toolkit to workproperly:

• Stringtable with PROTLIB.STR• #include "tkitstrt.rci"

Note If the #include "tkitstrt.rci" is not in the resource file, the I/O Server will notstart.

Adding Help to the I/O ServerWindows will use the program WINHELP.EXE to display the on-line help *.hlp filesprovided with any application. The TOOLKIT7.LIB provides a standard mechanism forproviding Help for the I/O Servers. We recommend that you use Microsoft Word togenerate the basic documentation file that will be used by the help compiler forWindows (provided with the SDK) to generate the server .HLP file.

Note Refer to the Microsoft Professional Tools User's Guides for detailed information.

Page 101: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Function Summary 9-25

The serial and board sample server programs both show the basic use of a Help menuitem. If you start with an existing server and need to add the Help capability, followthese general steps:

1. Add the following include statement to the .RC file and .C file that doesinitialization and message processing.

#include "srvrhelp.h"

2. Add the following help menu items to the .RC file:POPUP "&Help"

BEGINMENUITEM "&Contents", MENU_HELP_INDEXMENUITEM "&How to Use Help", MENU_HELP_ON_HELPMENUITEM SEPARATORMENUITEM "&About", MENU_HELP_ABOUTEND

3. In one of the .C files add the following variable declaration statement, which will bepicked up by the Toolkit functions:

BOOL bDoHelp = TRUE;

4. Add "About" message processing for the WM_COMMAND /MENU_HELP_ABOUT. Refer to the "Serial" sample server UDMAIN.C to seesample About processing.

5. N ow you must generate the server .HLP file, where server is the same name usedfor the I/O Server's .EXE file and application name. For example,UDSAMPLE.HLP for the server UDSAMPLE.EXE.

6. Be sure to copy the .HLP file to the installation floppy and/or into a directory in thePATH.

Note There are several third-party help development software packages on the marketthat can be used to simplify the creation of the help file once the documentation file hasbeen created. For example, "RoboHelp" by Blue Sky Software in La Jolla, California.

Page 102: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

9-26 Chapter 9

Page 103: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-1

C H A P T E R 1 0

API Function References

This chapter is a complete reference section for the I/O Server Toolkit ApplicationProgramming Interface (API) functions. They are presented in alphabetic order. Thepurpose, syntax, parameters and possible return values for all functions are included.Functions that appear both bolded and underlined must be written and included in theI/O Server. These functions are called by the Toolkit.

Page 104: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-2 Chapter 10

AdjustWindowSizeFromWinIniVOID WINAPI

AdjustWindowSizeFromWinIni (HWND hWnd)

This function adjusts the size and position of the server window to the last saved size.

Parameter Description

hWnd Window to size.

Page 105: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-3

CheckConfigFileCmdLineVOID WINAPI

CheckConfigFileCmdLine( LPSTR lpszCmdLine,LPSTR lpszCfgPath,int nMaxString)

This function will check the command line for a string prefaced by "/D:". Be sure toadd CMDLNPTH.H to the list of included files and add this reference:

extern char szCmdLine[ ];

Parameter Description

lpszCmdLine Far string pointer to the szCmdLine.lpszCfgPath Far string pointer to the string containing the final

configuration path that may be used for reading the file.nMaxString Maximum length of the szCfgPath.Return Value None.Comments The syntax supporting this command line file path

definition is: SERVER EXENAME /D:{FILEPATH}For example: MODBUS /D:C:\MBTEST

Note Before ProtInit() is called, the Toolkit initializes the string variable, szCmdLine,to contain the command line that invoked the driver. The variable szCmdLine should bethe first argument to CheckConfigFileCmdLine().

Examplechar szCfgPath[ PATH_STRING_SIZE ];VOID FAR PASCAL GetConfigFilePath( VOID ){ char driverName[ 20 ]; extern char szCmdLine[]; ProtGetDriverName( driverName, sizeof(driverName) ); /* Get the ConfigurationFilePath from the WIN.INI file or set it to default to the current directory. */ GetProfileString( driverName, "ConfigurationFile", "", szCfgPath, PATH_STRING_SIZE );

/* If the command line specified a config file path, let it override the path stored in WIN.INI. */ CheckConfigFileCmdLine( szCmdLine, szCfgPath, PATH_STRING_SIZE); if( strlen( szCfgPath ) == 0 ) { getcwd( szCfgPath, PATH_STRING_SIZE ); if (Verbose ){ debug( "Config path is CWD %s", szCfgPath ); } } if ( szCfgPath[strlen(szCfgPath)-1] != '\\' ) { strcat( szCfgPath, "\\" ); }}

Page 106: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-4 Chapter 10

CloseCommint

CloseComm( int idComDev)

This function closes a serial communications port.

Parameter Description

idComDev The id of the device to close. The OpenComm()function returns this value.

Return Value The return value is zero if the function is successful.Otherwise, it is less than zero.

Comments Windows NT/2000 only. Emulates Windows function.

Page 107: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-5

DbDevGetNamevoid WINAPI

DbDevGetName ( IDLDEV idLogDev, LPSTR lpszTopicName)

Get name corresponding to indicated logical device (i.e. topic).

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

lpszTopicName Far pointer to the string buffer where the name will be returned.

Page 108: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-6 Chapter 10

DbGetGMTasFiletimeBOOL WINAPI

DbGetGMTasFiletime( FILETIME *pFileTime )

Get Greenwich Mean Time as a Win32 FILETIME structure.

FILETIME is a 64-bit value defined in Win32 as the number of 100 nanosecondintervals since January 1, 1601. It is organized as two DWORDS, dwLowDateTime anddwHighDateTime.

Parameter Description

pFileTime Far pointer to a FILETIME structure in which to storethe date/time stamp.

Return Value TRUE if the date/time stamp was obtained successfully.

Page 109: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-7

DbGetNamevoid WINAPI

DbGetName( IDLDEV idLogDev,HDB hDb,LPSTR lpszName)

Get name of database item for indicated logical device.

Note: This is the same as the following function:

VOID WINAPI UDDbGetName ( IDLDEV idLogDev, HDB hDb, LPSTR lpszName)

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

lpszName Far pointer to the string buffer where the name will bereturned.

Page 110: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-8 Chapter 10

DbGetPointTypePTTYPE WINAPI

DbGetPointType ( IDLDEV idLogDev, HDB hDb)

Get point type of indicated point from database.

Returns 0 (PTT_UNKNOWN) if database pointer invalid.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

Return Value The type index should be one of the following,according to the data type for the point:PTT_DISCRETE, PTT_INTEGER, PTT_REAL,PTT_STRING. If the database pointer hDb is invalid, avalue of 0 (PTT_UNKNOWN) is returned.

Page 111: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-9

DbGetPtQualityPTQUALITY WINAPI

DbGetPtQuality ( IDLDEV idLogDev, HDB hDb)

Get quality flags for indicated point.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

Return Value The quality flags indicate whether the Toolkit databaseentry for the point contains good data or some problemexists. See the chapter on Quality Flags for informationon the specific flag settings.

Page 112: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-10 Chapter 10

DbGetPtTimePTTIME WINAPI

DbGetPtTime( IDLDEV idLogDev, HDB hDb )

Get date/time stamp for indicated point

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

Return Value The date/time stamp is stored as a Win32 FILETIMEstructure, which is a 64-bit value indicating the numberof 100 nanosecond intervals elapsed since January 1,1601. The date/time stamp indicates when the pointinformation was last updated in the Toolkit database.

Page 113: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-11

DbGetValueForCommPTVALUE WINAPI

DbGetValueForComm( IDLDEV idLogDev, HDB hDb)

Retrieve value for indicated point/logical device from the database.

Generally, this is used internally by the Toolkit to get the data value that is to be sent toa particular client.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

Return Value A union of type PTVALUE, the value corresponding tothe indicated data point. Note that for points of typePTT_STRING, the value contains a pointer to a memorybuffer where the string is actually stored.

Page 114: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-12 Chapter 10

DbNewQForAllPointsBOOL WINAPI

DbNewQForAllPoints( IDLDEV idLogDev, PTQUALITY ptQuality)

This function is generally used when a problem occurs communicating to the PLC.Then the quality flags and time stamps for all affected points should be set to indicatethe problem, without changing the value of the points. This function sets the quality onall points in the Topic. The Toolkit supplies a default date/time stamp. See the chapteron Time Marks for more information on the default time.

Note: You may instead prefer to scan through the list(s) of points yourself and callDbNewTQFromDevice() for specific points, depending on the specific needs of yourserver and whether different quality settings are needed for different points.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

ptQuality The quality flags, indicating whether the point wasaccessed properly and whether the data had anyproblems.

Return Value TRUE means the parameters were acceptable and thetime and quality have been moved into the database.

Comments If the quality of a point changes in the Toolkit database,the value, time, and quality will be passed on to anyclients who have advised the item. (DDE clients areupdated only when the value changes.) When a clientrequests an item, the current database VTQ will be sent(once the item's value has been set).

Page 115: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-13

DbNewQFromDeviceBOOL WINAPI

DbNewQFromDevice( IDLDEV idLogDev, HDB hDb,

PTQUALITY ptQuality)

This function is generally used when a problem occurs communicating to the PLC.Then the quality flags and time stamps for all affected points should be set to indicatethe problem, without changing the value of the points.

Functionally, this is similar to DbNewTQFromDevice(), except that the Toolkitsupplies a default date/time stamp. See the chapter on Time Marks for more informationon the default time.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

ptQuality The quality flags, indicating whether the point wasaccessed properly and whether the data had anyproblems.

Return Value TRUE means the parameters were acceptable and thetime and quality have been moved into the database.

Comments If the quality of the point changes in the Toolkitdatabase, the value, time, and quality will be passed onto any clients who have advised the item. (DDE clientsare updated only when the value changes.) When aclient requests an item, the current database VTQ will besent (once the item's value has been set).

Page 116: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-14 Chapter 10

DbNewTopicListBOOL WINAPI

DbNewTopicList( LPSTR lpszTopicList)

Sets the value for the statistic “Topics” item on the SYSTEM topic. The “Topics” itemis a tab-separated list of topics available in the I/O Server. The server will normally callthis function once at startup, and subsequently only when the configured list of topicsavailable in the server changes.

Parameter Description

lpszTopicList Points to a null-terminated character string containing atab-separated list of topics available in the server’sprotocol engine. If lpszTopicList is a NULL pointer orpoints to an empty string, the list of protocol-specifictopics is considered to be empty.

Return Value TRUE if the topic list has been set successfully.

Comments This function call is optional. Note that at a minimum,the “Topics” item will always contain the standard I/OServer developer topics: SYSTEM, $DDE, $PORT,$DEVICE, $SERVER, and $TKITIF. The Toolkitappends this list of topics to the server-specified list oftopics.

Page 117: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-15

DbNewTQFromDeviceBOOL WINAPI

DbNewTQFromDevice( IDLDEV idLogDev, HDB hDb, LPPTTIME lpPtTime, PTQUALITY ptQuality)

This function is generally used when a problem occurs communicating to the PLC.Then the quality flags and time stamps for all affected points should be set to indicatethe problem, without changing the value of the points.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

lpPtTime Far pointer to a FILETIME structure that indicates whenthe point information was updated. This can be obtainedvia a call to DbGetGMTasFiletime().

ptQuality The quality flags, indicating whether the point wasaccessed properly and whether the data had anyproblems.

Return Value TRUE means the parameters were acceptable and thetime and quality have been moved into the database.

Comments If the quality of the point changes in the Toolkitdatabase, the value, time, and quality will be passed onto any clients who have advised the item. (DDE clientsare updated only when the value changes.) When aclient requests an item, the current database VTQ will besent (once the item's value has been set).

Page 118: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-16 Chapter 10

DbNewValueFromDeviceBOOL WINAPI

DbNewValueFromDevice( IDLDEV idLogDev,HDB hDb,PTVALUE value)

Note: With the advent of FactorySuite 2000, this function is outmoded. However, itremains available for backwards compatibility. Internally, the Toolkit provides a defaultdate/time stamp and a default quality of good, then calls DbNewVTQFromDevice().See the chapters on Time Marks and Quality Flags for more information on the defaulttime and quality settings.

When you receive a new point value from the device, you can tell the Toolkit's databasethrough a call to DbNewValueFromDevice().

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

value A union of type PTVALUE. The user must know thetype of data associated with this point (set by the serverin *lpPtType during the ProtCreatePoint() call). Basedon the point type, use the appropriate field in thisstructure (it contains fields for discrete, integer, and real,as well as a handle to memory containing a string).

Return Value TRUE means the parameters were acceptable and thevalue has been moved into the database.

Comments This function is supplied for backward compatibilitywith previous versions of the Toolkit. You should callDbNewVTQFromDevice() instead.See the commentson DbNewVTQFromDevice() for further informationabout how the Toolkit updates clients that have points onadvise or that make requests.

Page 119: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-17

DbNewVQFromDeviceBOOL WINAPI

DbNewVQFromDevice( IDLDEV idLogDev, HDB hDb, PTVALUE ptValue, PTQUALITY ptQuality)

Functionally, this is similar to DbNewVTQFromDevice(), except that the Toolkitsupplies a default date/time stamp. See the chapter on Time Marks for more informationon the default time.

When you receive a new point value from the device, you can tell the Toolkit's databasethrough a call to DbNewVQFromDevice().

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

ptValue A union of type PTVALUE. The user must know thetype of data associated with this point (set by the serverin *lpPtType during the ProtCreatePoint() call). Basedon the point type, use the appropriate field in thisstructure (it contains fields for discrete, integer, and real,as well as a handle to memory containing a string).

ptQuality The quality flags, indicating whether the point wasaccessed properly and whether the data had anyproblems.

Return Value TRUE means the parameters were acceptable and thevalue, time, and quality have been moved into thedatabase.

Comments To ensure compatibility with future Toolkit releases, thisfunction must be called for every poll. The Toolkitkeeps track in its database of the value of the data, thetimestamp, and the quality, and identifies when any ofthese changes. If the value or quality changes, the value,time, and quality will be passed on to any clients whohave advised the item. (DDE clients are updated onlywhen the value changes.) When a client requests anitem, the current database VTQ will be sent (once theitem's value has been set by a call to this function).

Page 120: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-18 Chapter 10

DbNewVTQFromDeviceDbNewVTQFromDevice( IDLDEV idLogDev,

HDB hDb,PTVALUE value,

LPPTTIME lpPtTime,PTQUALITY ptQuality)

When you receive a new value for a point, tell the Toolkit’s database throughDbNewVTQFromDevice(). You should provide a date/time stamp and appropriatequality flags according to when the update occurred and how valid the data is.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

value A union of type PTVALUE. The user must know thetype of data associated with this point (set by the serverin *lpPtType during the ProtCreatePoint() call). Basedon the point type, use the appropriate field in thisstructure (it contains fields for discrete, integer, and real,as well as a handle to memory containing a string).

lpPtTime Far pointer to a FILETIME structure that indicates whenthe point information was updated.

ptQuality The quality flags, indicating whether the point wasaccessed properly and whether the data had anyproblems.

Return Value TRUE means the parameters were acceptable and thevalue, time, and quality have been moved into thedatabase.

Comments To ensure compatibility with future Toolkit releases, thisfunction must be called for every poll. The Toolkitkeeps track in its database of the value of the data, thetimestamp, and the quality, and identifies when any ofthese changes. If the value or quality changes, the value,time, and quality will be passed on to any clients whohave advised the item. (DDE clients are updated onlywhen the value changes.) When a client requests anitem, the current database VTQ will be sent (once theitem's value has been set by a call to this function).

Page 121: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-19

DbRegisterDemandScanvoid WINAPI

DbRegisterDemandScan( DemandScanFncCallback lpfn)

Register a callback function for demand scan control.

The server-specific code calls this routine during initialization to provide the address ofa function that is implemented in the server-specific code, which will be called if a clientwrites to the special statistical flag DemandScan to force an immediate scan of allpoints on the corresponding topic. The default value for the function pointer is NULL,meaning that no support is provided for the demand scan functionality.

The parameter type is defined as follows:

typedef BOOL (CALLBACK *DemandScanFncCallback) (HLOGDEV);

Parameter Description

lpfn Pointer to a function with a prototype of form

BOOL CALLBACK DemandScan(HLOGDEV);

which is implemented in the server-specific code.

Return Value None.

Comments When a client writes (pokes) a value of 1 to the specialstatistical flag DemandScan on a topic, the Toolkitchecks whether a demand scan callback function hasbeen registered.If not, no action is performed, and theToolkit sends a NACK to the client indicating thatdemand scan was not set up. If a demand scan callbackfunction has been registered, theToolkit calls theindicated function, passing the server-specific handlehLogDev for the topic.It is the responsibility of theprogrammer to implement the demand scan callbackfunction so that it forces an immediate scan of all pointson the indicated topic – even if those points are alreadyscheduled to be polled on a periodic basis. The functionshould return TRUE if the setup for demand scan issuccessful (in which the Toolkit will send an ACK to theclient), FALSE otherwise (in which case the Toolkit willsend a NACK). If a client pokes a value other than 1,the Toolkit will perform no action and will return anACK to the client.

Page 122: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-20 Chapter 10

DbRegisterScanStatevoid WINAPI

DbRegisterScanState( OnOffScanFncCallback lpfn )

Register a callback function for on/off scan control.

The server-specific code calls this routine during initialization to provide the address ofa function that is implemented in the server-specific code, which will be called if a clientwrites to the special statistical flag OnScan to put a topic on-scan or take it off-scan.The default value for the function pointer is NULL, meaning that no support is providedfor the on/off scan functionality.

The parameter type is defined as follows:

typedef BOOL (CALLBACK *OnOffScanFncCallback) (HLOGDEV, INTG);

Parameter Description

lpfn Pointer to a function with a prototype of form

BOOL CALLBACK OnOffScan(HLOGDEV, INTG);

which is implemented in the server-specific code.

Return Value None.

Comments When a client writes (pokes) to the special statistical flagOnScan on a topic, the Toolkit checks whether an on/offscan callback function has been registered. If not, noaction is performed, and the Toolkit sends a NACK tothe client indicating that on/off scan was not set up. Ifan on/off scan callback function has been registered, theToolkit calls the indicated function, passing the server-specific handle hLogDev for the topic and a modeselection nMode. It is the responsibility of theprogrammer to implement the on/off scan callbackfunction so that puts the topic on-scan or off-scanaccording to the value of nMode. Generally, if nMode isnon-zero, the topic should be on-scan, i.e. all activepoints on the topic are being polled. If nMode is zero,the topic should be off-scan, i.e. none of the points onthe topic should be polled. The function should returnTRUE if the setup for on/off scan is successful (in whichthe Toolkit will send an ACK to the client), FALSEotherwise (in which case the Toolkit will send a NACK).

Page 123: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-21

DbSetHProtBOOL WINAPI

DbSetHProt( IDLDEV idLogDev,HDB hDb,HPROT hProtOld,HPROT hProtNew)

This function allows the server to change the hProt value for a point (item identifierfrom your code to the Toolkit database). Generally, this is most useful if you arechanging how your server is keeping track of the memory structures for one or morepoints (e.g. reducing the size of a symbol table or re-ordering its members).

Parameter Description

idLogDev Topic (logical device) identifier that was supplied as aparameter in the ProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint

() call.

hProtOld Handle identifying the point which was the return fromthe ProtCreatePoint() or the previous DbSetHProt()call.

hProtNew The new handle (a non-zero number chosen by you andunique to this item) that identifies this point/item in anyfuture ProtNewValueForDevice() ,ProtActivatePoint(), and ProtDeactivatePoint() calls.

Return Value TRUE means the hProt value for this item has beenchanged.

Comments The hProt value is used during calls to the server toidentify the point quickly (e.g.,ProtNewValueForDevice() or ProtActivatePoint() ).This may be useful when managing the data structuresused to keep track of points in the server (e.g., hProtNewcan be the index entries into a new symbol table).

Page 124: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-22 Chapter 10

DbSetPointTypeBOOL WINAPI

DbSetPointType( IDLDEV idLogDev, HDB hDb, PTTYPE ptType )

Deferred setting of point type for indicated point on indicated logical device.

Returns TRUE if successful.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

ptType One of the standard data types: PTT_DISCRETE,PTT_INTEGER, PTT_REAL, PTT_STRING.

Return Value TRUE if the data type for the point was successfullyupdated.

Page 125: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-23

DbValueWriteConfirmBOOL WINAPI

DbValueWriteConfirm( IDLDEV idLogDev, HDB hDb, BOOL bSuccess, BYTE bReason )

When a client writes a value to the device (via a DDE POKE or a SuiteLink Write), thevalue is passed to the server-specific code via ProtNewValueForDevice(). The server-specific code then performs whatever actions are necessary to write that data to the PLC.However, depending upon the communication protocol, this update may be immediate,or there may be a considerable delay before the new data actually reaches the PLC. (Forsome devices, e.g. those involving radio modems, this delay may be as long as severalminutes!) Sometimes, the only way to verify that the data actually arrived is tosubsequently poll the PLC for the point – or to poll other points that are affected by awrite-only point. More commonly, the operation used to write the value causes the PLCto respond with some indicator of whether the new data was accepted or rejected; and ifrejected, the response usually includes a reason code indicating why it was rejected.When such an accept/reject response is received, you can use DbValueWriteConfirm()to tell the Toolkit whether the point was written successfully.

Note: This API call is at present non-functional. It is reserved for future expansion.

Parameter Description

idLogDev Topic (logical device) identifier that was supplied as aparameter in the ProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

bSuccess TRUE if the point was successfully written, FALSEotherwise.

bReason The reason code, in case the write failed. This can be ageneric code, or can be specific to the PLC protocol.

Return Value TRUE means the notification to the Toolkit wassuccessful, i.e. that the parameters were valid.

Comments This API call is presently non-functional. It is reservedfor future expansion.

Page 126: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-24 Chapter 10

debugVOID far cdecl

debug( LPSTR lpszFmt,... args)

This function sends a debug message to WWLOGGER.EXE which can log it to disk,monochrome adapter, AUX port, etc.

Parameter Description

lpszFmt Format text string, see printf in C-Library.

args Any set of arguments applicable to printf.

Return Value None.

Comments The interface in the code is very straightforward. Simplyinclude debug.h and use debug() with parametersidentical to the C-Library printf(). Notice theWWLOGGER.EXE options; the debug messages to besaved on disk, displayed in the Wonderware Loggerwindow, and/or sent to the AUX port.

Since it is recommended that the Wonderware Loggeralways be running, you should not leave extraneousdebug messages in the server. You should also makesure that frequently occurring debug messages can beturned off via a switch in the WIN.INI file.

Warning Note The ProtGetDriverName() function may not contain any calls todebug() because debug() calls ProtGetDriverName() and an infinite loop will result.

The debug() function is often useful to have some debugging messages whiledeveloping the server. In the sample application, an interface to the WonderwareLogger WWLOGGER.EXE is provided. This interface allows you to optionally logeach debug message to disk and also send each message to either:

1. A window on the screen.

2. The AUX port (COM1 by default, or the monochrome display if OX.SYS isinstalled).

3. A printer connected directly to the PC.

Wonderware Logger can be used during development to help debug the server.Hardware or software problems should be logged for operator examination. Be advisedthat extraneous logger messages frustrate users and should be eliminated when theproduct is finished. It is useful to enable debug messages via a switch in the serversection of the WIN.INI in order to support customers at a later time.

Page 127: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-25

EnableCommNotificationBOOL WINAPI

EnableCommNotification( int idComDev,HWND hwnd,int cbWriteNotify,int cbOutQueue)

This function simulates the Windows EnableCommNotification() function for Windowsversions older than Windows 3.1 and for Windows NT/2000. It performs no operationon these platforms and is provided for common code convenience only. On Windowsversions prior to 3.0, it enables or disables WM_COMMNOTIFY message posting tothe given window.

Parameter Description

idComDev The id of the communications device. TheOpenComm() function returns this value.

hwnd Identifies the window whose WM_COMMNOTIFYmessage posting will be enabled or disabled.

cbWriteNotify Indicates the number of bytes the COM driver must writeto the application’s input queue before sending anotification message.

cbOutQueue Indicates the minimum number of bytes in the outputqueue. When the number of bytes falls below thisnumber, the COM driver sends that application anotification message.

Return Value The return value is non-zero if the function is successful.Otherwise, it is zero.

Comments None.

Page 128: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-26 Chapter 10

FlushCommint WINAPI

FlushComm( int idComDev,int fnQueue)

This function flushes all characters from the transmission or receiving queue of thespecified communications device.

Parameter Description

idComDev The id of the communications device to be flushed. TheOpenComm() function returns this value.

fnQueue Specifies the queue to be flushed. If this parameter iszero, the transmission queue is flushed. If the parameteris 1, the receiving queue is flushed.

Return Value The return value is zero if the function is successful.Any other value indicates an error.

Comments When flushing the transmission queue, beware that thisfunction will clear all characters in it. Thus, thisfunction can conceivably terminate a previous writeoperation before all submitted characters have been sentfrom the UART. This may lead to unpredictablebehaviors in your server since the receiving device willnot receive the entire message intended. Windows NT/2000 only. Emulates Windows function.

Page 129: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-27

GetAppNamePSTR WINAPI

GetAppName( VOID)

This function returns the application name for the server. This application name isstored in the Toolkit and initially set by a call to ProtGetDriverName() during serverstartup.

Parameter Description

Return Value Pointer to a character string containing the applicationname for the server.

Comments None.

Page 130: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-28 Chapter 10

GetCommErrorint WINAPI

GetCommError( int idComDev,COMSTAT * lpStat)

This function retrieves the most recent error value and current status for the specifieddevice. It also clears the error.

Parameter Description

idComDev The id of the communications device to be examined.The OpenComm() function returns this value.

lpStat Points to the COMSTAT structure that is to receive thedevice status. If this parameter is NULL, this functionreturns only the error values. See the appropriateMicrosoft documentation for a description of thisstructure.

Return Value The return value is a 32-bit value containing a maskindicating the type of error. See discussion of theClearCommError() function in the appropriate MicrosoftWindows NT/2000 documentation for more information.

Comments This function clears the error condition. WindowsNT/2000only. Emulates Windows function.

Page 131: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-29

GetCommEventMaskUINT WINAPI

GetCommEventMask( int idComDev,int fnEvtClear)

This function retrieves and then clears the event word for the specified communicationsdevice.

Parameter Description

idComDev The id of the communications device to be examined.The OpenComm() function returns this value.

fnEvtClear This parameter is ignored on Windows NT/2000.

Return Value The return value specifies the current 32-bit event maskvalue for the specified communications device if thefunction is successful. Each bit in the event maskspecifies whether a given event has occurred; a bit is set(to 1) if the event has occurred.

Comments Windows NT/2000 only. Emulates Windows function.

Page 132: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-30 Chapter 10

GetIOServerLicenseBOOL WINAPI

GetIOServerLicense( void FAR *lpKeyInfo, BOOL bExitOnFail)

This function should be called in ProtInit() to check whether the user has a license thatwill allow the server to run. If a license is unavailable, this function presents aMessageBox that gives the user the options of trying again, running the server in timeddemo mode, or exiting the program. If the function returns FALSE, the server shouldreturn FALSE from ProtInit(), indicating the server could not run.

Note If you are developing products for Wonderware, this function will be of interest.Note that a special version of the Toolkit is necessary to access the Wonderware LicenseManager. Contact Wonderware for more information.

Parameter Description

lpKeyInfo A pointer to a buffer into which feature enablement flagswill be placed. If this parameter is NULL, no specificfeature flags will be returned.

bExitOnFail If TRUE, the function will exit the program if it isunable to obtain a license. If FALSE, it will return, andthe return value will indicate whether the server shouldrun.

Return Value TRUE if the server has permission to run. This includesthe case where no license is available, but user hasselected running in the timed demo mode. If FALSE,The server should return from ProtInit() with a returnvalue of FALSE, indicating the server cannot run.

Comments For the timed demo mode, the Toolkit keeps track ofhow long it has been since the server started up. Whenthe time limit is reached, the Toolkit automatically issuesa message to the Wonderware Logger and shuts downthe server.

The following code would be placed in ProtInit(). If a valid license could not beobtained, and the timed DEMO mode was not selected, the server should exit.

Example/* check whether this product has a license to run */if (!GetIOServerLicense (NULL, FALSE)) return FALSE;}

Page 133: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-31

GetServerNameExtensionvoid WINAPI

GetServerNameExtension( void)

Set-up name extension for use in storing and retrieving Registry settings

Parameter Description

Return Value None.

Comments A call to GetServerNameExtension() should appear inProtGetDriverName(). This ensures that the functionis called early in the program, at the same time as theToolkit first gets the server’s “short” name, so that thecorrect full name is generated for the I/O Server.

ExampleBOOL WINAPI ProtGetDriverName(LPSTR lpszName, int nMaxLength){ /** WARNING: No calls to debug()... debug() calls ProtGetDriverName(), therefore ProtGetDriverName() cannot call debug(). **/ lstrcpy(lpszName, GetString(STRUSER + 76) /* "UDSAMPLE" */ );#ifdef WIN32 GetServerNameExtension();#endif return (TRUE);} /* ProtGetDriverName */

Page 134: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-32 Chapter 10

GetStringPSTR WINAPI

GetString( int nString)

This function will return a string from the resource file.

Parameter Description

nString The offset into the STRINGTABLE.

Return Value Pointer to the string.

Comments This function is used to reduce the amount of memorythat the server consumes and to allow the creation of aforeign language version of the server. The resource filecan be edited later to change text or languages, thiscapability is also know as localization. GetString()accomplishes this by using Windows' string resources tomove string constants from the resource file to the datasegment. A sample follows:

MessageBox( GetFocus(),

GetString(STRUSER+1) /* "Hello There" */,GetString(STRUSER+2) /* "Application" */,MB_OK );

STRUSER is defined in udgetstr.h and all strings thatyou use can go in udprot.str. The following is anexample of the string file that would correspond to theabove: STRUSER+1, "Hello There"

STRUSER+2, "Application"

GetString() loads the string named as its argument in atemporary buffer and returns a pointer to the temporarybuffer. This is much easier than the standard methodused in Windows applications, which is to load the stringinto a buffer and then use it.

Each string that is not put in the resource file consumesmemory byte-for-byte in the application's data segment(DS). By using resource strings, code size can beslightly increased. Code segments can be swapped - datasegments cannot!

GetString() also uses 20 string buffers circularly, soonly the most recent 20 strings are valid at any instant.

Note hInst must be initialized before making the first call to GetString(). Each string inthe STRINGTABLE is limited to 200 bytes, including the NULL.

Page 135: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-33

GetTextExtentDWORD

GetTextExtent( HDC hdc,LPCSTR lpString,int cbString)

This function provides emulation of the Windows GetTextExtent() function for theWindows NT/2000 platform.

Parameter Description

hdc Identifies the device context.

lpString Points to a string of text. The string does not need to bezero-terminated.

cbString Specifies number of characters in the string.

Return Value The low-order word of the return value contains thestring width, in logical units, if the function is successful;the high-order word contains the string height.

Comments Windows NT/2000 only. Emulates Windows function.

Page 136: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-34 Chapter 10

NTSrvr_BuildCommDCBint WINAPI

NTSrvr_BuildCommDCB( LPSTR lpszDef,DCB FAR *lpdcb)

This function translates a device-definition string into appropriate serial device controlblock codes.

The return value from this function is compatible with the Windows version of theBuildCommDCB() function.

Parameter Description

lpszDef Points to a null-terminated string that specifies device-control information. The string must have the same formas the parameters used in the MS-DOS or Windows NTmode command.

lpdcb Points to a DCB structure that will receive the translatedstring. The structure defines the control settings for theserial-communications device.

Return Value The return value is zero if the function is successful.Otherwise, it is -1.

Comments This function only fills the lpdcb buffer. To apply thesettings to a port, the server should use theNTSrvr_SetCommState() function.

Page 137: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-35

NTSrvr_GetCommStateint WINAPI

NTSrvr_GetCommState( int idComDev,DCB FAR *lpdcb)

This function retrieves the device control block for the specified device. The returnvalue from this function is compatible with the Windows version of the GetCommState()function.

Parameter Description

idComDev The id of the communications device to be examined.The OpenComm() function returns this value.

lpdcb Points to a DCB structure that is to receive the currentdevice control block. The DCB structure defines thecontrol settings for the device.

Return Value The return value is zero if the function is successful.Otherwise, it is less than zero.

Comments None.

Page 138: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-36 Chapter 10

NTSrvr_SetCommStateint WINAPI

NTSrvr_SetCommState( int idComDev,DCB FAR *lpdcb)

This function sets a communications device to the state specified by a device controlblock. The return value from this function is compatible with the Windows version ofthe BuildCommDCB() function.

Parameter Description

idComDev The id of the communications device to be set. TheOpenComm() function returns this value.

lpdcb Points to a DCB structure that contains the desiredcommunications settings for the device.

Return Value The return value is zero if the function is successful.Otherwise, it is less than zero.

Comments This function reinitializes all hardware and controls asdefined by the DCB structure. It does not emptytransmission or receiving queues.

Page 139: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-37

NTSrvr_SetDCB_Dtrint WINAPI

NTSrvr_SetDCB_Dtr( DCB FAR *lpdcb,int iMask)

This function modifies the DTR (data-terminal-ready) flow-control setting in the devicecontrol block.

Parameter Description

lpdcb Points to a DCB structure which is to be modified usingthe specified iMask setting.

iMask Specifies the DTR flow control setting. Must be one ofthe following:

NTSrvr_DTR_DISABLE, NTSrvr_DTR_ENABLE,NTSrvr_DTR_HANDSHAKE.

Return Value The return value is zero if the function is successful.Otherwise, it is less than zero.

Comments NTSrvr_DTR_DISABLE disables the DTR line whenthe device is opened and leaves it disabled.

NTSrvr_DTR_ENABLE enables the DTR line when thedevice is opened and leaves it enabled.

NTSrvr_DTR_HANDSHAKE enables DTRhandshaking.

Include header file: NTSRVR.H for bit mask definitions.

Page 140: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-38 Chapter 10

NTSrvr_SetDCB_Rtsint WINAPI

NTSrvr_SetDCB_Rts( DCB FAR *lpdcb,int iMask)

This function modifies the RTS (request-to-send) flow-control setting in the devicecontrol block.

Parameter Description

lpdcb Points to a DCB structure which is to be modified usingthe specified iMask setting.

iMask Specifies the RTS flow control setting. Must be one ofthe following:

NTSrvr_RTS_DISABLE,

NTSrvr_RTS_ENABLE, NTSrvr_RTS_HANDSHAKE.

Return Value The return value is zero if the function is successful.Otherwise, it is less than zero.

Comments NTSrvr_RTS_DISABLE disables the RTS line when thedevice is opened and leaves it disabled.

NTSrvr_RTS_ENABLE enables the RTS line when thedevice is opened and leaves it enabled.

NTSrvr_RTS_HANDSHAKE enables RTShandshaking.

Include header file: NTSRVR.H for bit mask definitions.

Page 141: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-39

OpenCommint WINAPI

OpenComm( LPCSTR lpszDevControl,UINT cbInQueue,UINT cbOutQueue)

This function opens a serial communications port for communications.

Parameter Description

lpszDevControl Points to a null-terminated string that specifies thedevice name in the form COMn, where n is the devicenumber.

cbInQueue Specifies the size, in bytes, of the receiving queue.

cbOutQueue Specifies the size, in bytes, of the transmission queue.

Return Value The return value identifies the open device if thefunction is successful. Otherwise, it is less than zero.

Comments The return value is actually a file handle when positive.Windows NT/2000 only. Emulates Windows function.

Page 142: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-40 Chapter 10

PfnSendEmSelectAllvoid WINAPI

PfnSendEmSelectAll( HWND hDlg,int idControl,BOOL bScrollCaret)

This function selects all the text in the identified edit control. It will also scroll the caretinto view if the bScrollCaret flag is TRUE.

Parameter Description

hDlg Handle of dialog box window.

idControl Identifier of control to be selected.

bScrollCaret Scroll caret flag. TRUE indicates scroll caret into view.

Return Value None.

Comments This function calls SendMessage() internally.

Page 143: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-41

PfnSendEmSelectRangevoid WINAPI

PfnSendEmSelectRange( HWND hDlg,int idControl,int nStart,int nEnd,BOOL bScrollCaret)

This function selects a range of text in the identified edit control. It will also scroll thecaret into view if the bScrollCaret flag is TRUE.

Parameter Description

hDlg Handle of dialog box window.

idControl Identifier of control to be selected.

nStart Starting text position.

nEnd Ending text position.

bScrollCaret Scroll caret flag. TRUE indicates scroll caret into view.

Return Value None.

Comments This function calls SendMessage() internally.

Page 144: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-42 Chapter 10

ProtActivatePointBOOL WINAPI

ProtActivatePoint( HLOGDEV hLogDev,HPROT hProt)

This function activates the specified point for reading (i.e., start supplying the Toolkitdatabase with fresh data for this point). The hProt is the handle you returned during theProtCreatePoint() call. As soon as you have valid data from the device, callDbNewVTQFromDevice().

Parameter Description

hLogDev Handle identifying the logical device which was returnedfrom the ProtAllocateLogicalDevice() call.

hProt Handle identifying the point which was the return fromthe ProtCreatePoint() call.

Return Value TRUE means a valid point has been activated.

Comments A point will be activated when a client has requesteddata or has asked to be advised of data changes. Theserver is then responsible for providing fresh data forthis point to the Toolkit.

Page 145: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-43

ProtAllocateLogicalDeviceHLOGDEV WINAPI

ProtAllocateLogicalDevice( LPSTR lpszTopicName,IDLDEV idLogDev)

This function is called when a DDE conversation has been initiated to the topic name(i.e., logical device name) lpszTopicName. You must first validate the topic name. If thename is valid, return a non-NULL value. If the name is invalid, return NULL.

Parameter Description

lpszTopicName Far pointer to string that came from the client initiating anew topic conversation.

idLogDev This is the Toolkit's handle to this logical device. Thisparameter must be saved for subsequent calls toDbNewVTQFromDevice() to identify the source device(topic).

Return Value Handle (a non-zero number chosen which is unique tothis topic) that identifies this logical device (topic) infuture calls to ProtCreatePoint(), etc. NULL means nodevice was allocated and the topic conversation isrejected (i.e., the conversation is not established).

Comments Usually a topic name is associated with a single I/Odevice. Be sure to save idLogDev (the Toolkit's handlefor this topic) for subsequent calls toDbNewVTQFromDevice(). Return NULL only if thetopic name is illegal or you are out of memory - not ifcommunication with the logical device fails.

After one DDE client establishes a conversation to theserver with a specific topic name, subsequentconversations to the same topic will NOT cause a call toProtAllocateLogicalDevice(), i.e., this function willonly be called when the first conversation to a topic isestablished.

Note The name is a character string that may contain spaces and have mixed case (e.g.,topic-Name). It is suggested that the lstrcmpi() function be used to compare the fullstring and ignore the case. Do not call Windows MessageBox() during this function.

Page 146: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-44 Chapter 10

ProtCloseVOID WINAPI

ProtClose( void)

This function is called when the server is shut down.

Parameter Description

Return Value None.

Comments At this point, it is intended for the server to free alllogical devices, free any allocated memory, close serialports, etc. ProtClose () is only called immediately priorto the server closing.

Page 147: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-45

ProtCreatePointHPROT WINAPI

ProtCreatePoint( HLOGDEV hLogDev,HDB hDb,LPSTR lpszName,LPPTTYP lpPtType)

This function is called when a conversation references an item (named *lpszName).You must validate the name and determine point type (discrete, integer, real or string).Return NULL if the point name is illegal or out of memory, etc. Otherwise, store thepoint type in *lpPtType. Remember the hDb for this point, and return a handle (a non-zero number chosen by you which is unique to this item) that subsequently will be usedto identify the point.

Parameter Description

hLogDev Handle identifying the logical device (generated by theserver code and returned from the call toProtAllocateLogicalDevice() ). This ties the point/itemto a particular logical device (topic).

hDb Handle from the Toolkit which is unique to this item andmust be used in future calls toDbNewVTQFromDevice().

lpszName Far pointer to a string which contains the item name as itcame from the client.

lpPtType Return the point type by storing one of the following in*lpPtType:

Value Meaning

PTT_DISCRETE (0 or 1)PTT_INTEGER (Signed 32-bit integer)PTT_REAL (IEEE 32-bit floating point,

single precision)PTT_STRING (Text string terminated by a

NULL character)

Return Value Handle (a non-zero number chosen by you and unique tothis item) that identifies this point/item in any futureProtNewValueForDevice() , ProtActivatePoint() andProtDeactivatePoint() calls.

Comments The name is a character string that may contain spacesand have mixed cases (e.g., "This Is An Item Name").The lstrcmpi() function should be used to compare thefull string and ignore the case. The HPROT valuereturned can be any non-zero number. Therefore,choose one that is useful to your protocol (e.g., an indexinto a symbol table). Based upon the item name, thedata type must be set in *lpPtType. Save the hDb forthis item. It must be used later when callingDbNewVTQFromDevice().

Page 148: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-46 Chapter 10

ProtDeactivatePointBOOL WINAPI

ProtDeactivatePoint( HLOGDEV hLogDev,HPROT hProt)

This function deactivates (i.e., stops supplying data for) the specified point. No DDEconversations are interested in the value of this point. Do not delete the symbol for thepoint though - ProtDeletePoint() will be called if the symbol should actually be deletedfrom your internal symbol tables.

Parameter Description

hLogDev Handle identifying the logical device which was thereturn value from the ProtAllocateLogicalDevice() call.

hProt Handle identifying the point which was the return fromthe ProtCreatePoint() call.

Return Value TRUE means the point is deactivated but still valid.

FALSE means error, invalid logical unit, symbol table,point, etc. Return value is not used at this time, butshould be observed for future compatibility.

Comments When this function is called, stop polling the device forthis point and stop sending data for this point to theToolkit database. The point still has valid identifiers donot delete it completely. This function should undoanything that was done as a result of a previousProtActivatePoint() call. For example, it may need todelete a poll message that was created inProtActivatePoint().

If a point is only poked (a one-time write to the point),the point will be created with ProtCreatePoint(),changed with ProtNewValueForDevice(). If a point isadvised (a request for notification whenever the pointchanges), the point will be created withProtCreatePoint(), activated with ProtActivatePoint()(in response to the advise) and changed withProtNewValueForDevice() (in response to pokes).Eventually the point will be deactivated withProtDeactivatePoint() (in response to an unadvise).ProtActivatePoint() and ProtDeactivatePoint() can becalled many times between the ProtCreatePoint() andProtDeletePoint() calls.

Page 149: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-47

ProtDefWindowProcLRESULT CALLBACK

ProtDefWindowProc( HWND hWnd,VINT message,WPARAM wParam,LPARAM lParam)

This function is called by the Toolkit to handle window messages directed to thisapplication.

Parameter Description

Return Value If no processing was done, use the following code return(hWnd, message, wParam, lParam);. If processing wasdone, the return is message-specific. Consult theWindows SDK manuals.

Comments This function is only of interest if you wish to do somespecialized Windows programming. If not, leave thecode in ProtDefWindowProc () the same as deliveredin the sample application. Otherwise, the I/O Server willnot work.

Note When doing Windows programming, any message can be processed inProtDefWindowProc(). If adding your own user interface for the server, menu itemscan be added to ProtMenu in the .RC file and WM_COMMAND messages can beintercepted in ProtDefWindowProc(), etc. Examples of this are shown in the sampleservers.

Page 150: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-48 Chapter 10

ProtDeletePointBOOL WINAPI

ProtDeletePoint( HLOGDEV hLogDev,HPROT hProt)

This function will delete the specified point. No DDE conversations are interested inthis point's value. However, if a write is outstanding - still perform the write.

Parameter Description

hLogDev Handle identifying the logical device which was thereturn from the ProtAllocateLogicalDevice() call.

hProt Handle identifying the point which was the return fromthe ProtCreatePoint() call.

Return Value TRUE means point has been deleted.

FALSE means error, invalid logical unit, symbol table,point, etc. Return value is not used at this time, butshould be observed for future compatibility.

Comments After this call, the hProt value will no longer be used (itcan then be reused by the server if so desired).

Page 151: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-49

ProtExecuteBOOL WINAPI

ProtExecute( HLOGDEV hLogDev,LPSTR lpszName)

This function is called when the client sends an Execute DDE message to a conversationon this server. The purpose is to communicate control commands to the I/O Server.This function is optional since the Toolkit supplies a default ProtExecute()

Parameter Description

hLogDev Handle which identifies this logical device (topic) asreturned by ProtAllocateLogicalDevice() call.

lpszName Far pointer to the command string.

Return Value TRUE means the command was executed. FALSEmeans the server had a problem with the command.

Comments This function should execute the string supplied by theclient and return success or failure based on thecommand supplied.

Note Please use the execute format defined in the Microsoft Windows SDKdocumentation.

Example[opcodestring] {[opcodestring]} ...

where opcodestring is

opcode { ( parameter {, parameter } ... ) }

For example:

[connect][download(query1,results.txt)][disconnect]

Page 152: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-50 Chapter 10

ProtFreeLogicalDeviceBOOL WINAPI

ProtFreeLogicalDevice( HLOGDEV hLogDev)

This function is called when there are no remaining DDE conversations on this logicaldevice identified by hLogDev. Delete all information associated with it.

Parameter Description

hLogDev Handle which identified this logical device (topic) asreturned by the ProtAllocateLogicalDevice() callearlier.

Return Value TRUE means valid hLogDev device was freed.

Comments Each individual point may not be deactivated or deletedwhen you receive this message. Be prepared to deletethe logical device and ALL associated information (e.g.,point data structures, messages, symbol table, etc.). Thisfunction will only be called when the last conversationto a topic is terminated.

Page 153: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-51

ProtGetDriverNameBOOL WINAPI

ProtGetDriverName( LPSTR lpszName,int nMaxLength)

This function will supply the driver name to the Toolkit to be used during the initiationof DDE conversations.

Parameter Description

lpszName Far pointer to the server name stored as a null terminatedcharacter string no longer than nMaxLength.

nMaxLength Maximum size for the server name string including theNULL terminator character.

Return Value TRUE means the name stored.

Comments Place the name of the server in lpszName. nMaxLengthwill be 9 (8 chars & NULL), since the server name mustbe convertible to a .EXE filename. Unless you havesome reason not to, this name should be the same as the.EXE name.

Note The ProtGetDriverName() function cannot contain any calls to debug() becausedebug() calls ProtGetDriverName() and an infinite loop will result.

Page 154: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-52 Chapter 10

ProtGetValidDataTimeoutDWORD WINAPI

ProtGetValidDataTimeout( void)

This function supplies the timeout value (in milliseconds) for the Toolkit when it iswaiting for first time data supplied by the protocol.

Parameter Description

Return Value Return (in milliseconds) how long the Toolkit shouldwait for the protocol to supply data for the first time.

Comments When a WM_DDE_REQUEST from a client comes infor a point, and the server has not received any valuesfor that point; the Toolkit will wait some amount of timefor the server to set a new value viaDbNewVTQFromDevice(). If it takes longer than thatamount of time to get a value from the device, theToolkit will Nack the item WM_DDE_REQUEST fromthe client.

Note NetDDE Considerations The value returned for the valid data timeout must be 1msec if the server is supplying data through NetDDE. This is a special case where theToolkit Nacks requests if there isn't valid data immediately available. Generally, thistimeout value is supplied in the configuration process of the server. The user must beinformed to set this for NetDDE.

Page 155: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-53

ProtInitBOOL WINAPI

ProtInit( void)

This function is called to perform any necessary initialization. It is the first functioncalled within the server.

Parameter Description

Return Value TRUE means that the server is initialized and ready tostart DDE conversations (i.e., all basic requirements forthis server have been met). FALSE means the servercannot continue and will cause it to exit.

Comments This function can perform any overall initializationneeded by the server, read configuration files, obtaininformation from the WIN.INI file (through calls toGetProfileInt() and GetProfileString() ), etc.Specifically, this function should callSysTimerSetupProtTimer(),SysTimerSetupRequestTimer(), andAdjustWindowSizeFromWinIni().

Page 156: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-54 Chapter 10

ProtNewValueForDeviceBOOL WINAPI

ProtNewValueForDevice( HLOGDEV hLogDev,HPROT hProt,PTVALUE value)

ProtNewValueForDevice() will be called whenever a new value for the point isreceived from DDE.

Parameter Description

hLogDev Handle identifying the logical device which was thereturn from the ProtAllocateLogicalDevice() call.

hProt Handle identifying the point which was the return fromthe ProtCreatePoint() call.

value The user must know the type of data associated with thispoint (set by the server in *lpPtType during theProtCreatePoint() call). Based on the point type, usethe appropriate field in this structure (it contains fieldsfor discrete, integer, and real, as well as a handle tomemory containing a string).

Return Value TRUE means the point is still valid and it is allowed tosend data to this point. FALSE indicates the pointcannot be written.

Comments The server should respond as soon as possible - i.e.,schedule a message to write the new value to the deviceand return immediately (if applicable).

Page 157: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-55

ProtTimerEventVOID WINAPI

ProtTimerEvent( DWORD dwTime)

This function will be called at the interval set by the last call toSysTimerSetupProtTimer().

Parameter Description

dwTime Time in milliseconds that have passed since the last callto this function.

Return Value None.

Comments Through this function's periodic execution, you can drivethe device protocol and supply data to the Toolkitdatabase. This is accomplished by making a call toDbNewVTQFromDevice() with each of the data itemsavailable in this time cycle. The dwTime is provided tothe protocol in case it is needed for timing relatedactivities.

Note Due to the nature of Windows and loading of the PC with other applications, thisfunction may not be called on at a precisely regular interval.

Page 158: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-56 Chapter 10

ReadCommint WINAPI

ReadComm( int idComDev,void *lpvBuf,int cbRead)

This function reads up to a specified number of bytes from the given communicationsdevice.

Parameter Description

idComDev The id of the communications device to be read. TheOpenComm() function returns this value.

lpvBuf Points to the buffer for the read bytes.

cbRead Specifies the maximum number of bytes to be read.

Return Value The return value is the number of bytes read ifsuccessful. Otherwise, it is less than zero and itsabsolute value is the number of bytes read.

Comments Windows only. Emulates Windows function. When anerror occurs, the cause of the error can be determined byusing the GetCommError() function to retrieve theerror value and status. Since errors can occur when nobytes are present, if the return value is zero theGetCommError() function should be called to ensurethat no error occurred. The return value is less than thenumber of bytes specified by cbRead if the number ofbytes in the receiving queue is less than cbRead.

Page 159: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-57

RelinquishPermission - Windows OnlyVOID WINAPI

RelinquishPermission( HANDLE hPermission)

RelinquishPermission() will release the selector that was allocated to this memoryaddress range, identified by hPermission.

Parameter Description

hPermission The permission handle that was set when permission isgranted by RequestPermission().

Return Value None.

Comments None.

Page 160: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-58 Chapter 10

RequestPermission - Windows OnlyBOOL WINAPI

RequestPermission( WORD wSegment,WORD wOffset,DWORD dwLength,LPSTR FAR *lplpProt,LPHANDLE lphPermission)

RequestPermission() is used to access memory at a fixed real mode location.

Parameter Description

wSegment Real-mode address segment.wOffset Real-mode address offset.dwLength Length of the area for permission.lplpProt Far pointer to the protected-mode far pointer. The

Protected-mode pointer is stored after the permissionprocess is completed. It may then be used to access thespecial fixed memory block.

lphPermission Far pointer to a permission handle that is set whenpermission is granted. This handle must be saved andused when calling RelinquishPermission().

Return Value TRUE means permission was granted. FALSE meansthere was a problem and no permission granted.

Comments Many plug-in I/O boards use memory mapped I/O totransfer data and commands which will then be relayedto an external device (e.g., the MODBUS Plus or AB1784-KT boards). In order to access non-standardmemory from Windows while in protected-mode,permission must be granted and a far pointer set up. Thepermission handle must be saved and used later to callRelinquishPermission(). A FALSE return indicates anerror condition in the request. After permission isgranted, that portion of memory may be freely accessedusing the lpProt pointer. When the protocol is shutdown, all requested blocks of memory must berelinquished by the user.

ExampleLPSTR lpProt;

HANDLE hPermission;

if( RequestPermission( 0x0000, 0x40, (DWORD)0x0008,

&lpProt, &hPermission) ) {

/* lpProt can be used to access 0:40 through 0:47. */

RelinquishPermission( hPermission );

}

Page 161: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-59

SelBoxAddEntryBOOL WINAPI

SelBoxAddEntry( LPSTR string,LONG value,WORD wFlags)

This function adds a string entry to a selection box set of choices to be displayed whenthe SelBoxUserSelect() call is done.

Parameter Description

string Far pointer to the string to be added to the selection boxentries.

value If this entry is picked by the user, this value will bereturned as an indicator.

wFlags Control flags allowed:

SBENTRY_DISABLED

SBENTRY_SELECTED

Return Value FALSE means there was an out of memory error addingthe entry.

Comments None.

Page 162: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-60 Chapter 10

SelBoxSetupStartVOID WINAPI

SelBoxSetupStart( HWND hWnd,PSTR title,PSTR noEntryMsg,int numCols,LONG lFlags)

SelBoxSetupStart() does the basic setup for a selection box.

Parameter Description

hWnd In most cases use the extern hWndParent.

title Pointer to the text to be displayed in the caption.

noEntryMsg Pointer to the text to be displayed in the window whenthere are no entries.

numCols Number of columns to be used. 0 will allow the Toolkitto pick the optimum based on the text lengths.

lFlags Control flags can be one of the following:

SBSTYLE_RADIO_BUTTONS(default is check-box style)

SBSTYLE_RETURN_ON_SELECTION(default is wait for OK)

SBSTYLE_SORT_ENTRIES(default is put in order of SelBoxAddEntry() calls)

SBSTYLE_ENTRIES_PRESORTED(put in order but knows that they are sorted)

Return Value None.

Comments None.

Page 163: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-61

SelBoxUserSelectLONG WINAPI

SelBoxUserSelect( HANDLE hInst,LONG lButtons,int vPosition,int nFixed)

This function actually displays the selection box and processes all the buttons.

Parameter Description

hInst Always use the extern hInst for this application.

lButtons Specifies which of the following buttons should beenabled (i.e., visible):

SB_BUTTON_NEW

SB_BUTTON_MODIFY

SB_BUTTON_DELETE

SB_BUTTON_CANCEL

SB_BUTTON_OK

vPosition Sets the vertical screen position of the box.

nFixed Set to 0 to allow free-format lengths. By setting nFixedto non-zero, the sizes for the entries are fixed at thelength specified by nFixed.

Return Value One of the buttons was picked by the user:

SB_BUTTON_OK

SB_BUTTON_CANCEL

SB_BUTTON_NEW

SB_BUTTON_MODIFY

SB_BUTTON_DELETE

Comments When this function returns, the selection box is nolonger on the screen. The user selections can now beprocessed based on which button was selected, see theSelBoxUserSelection() function below.

Page 164: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-62 Chapter 10

SelBoxUserSelectionHANDLE WINAPI

SelBoxUserSelection( void)

This function is called after SelBoxUserSelect() if you wish to get a list of what the userselected.

Parameter Description

Return Value The return is the handle of a selection list hSelList thatrepresents what the user selected during the last call toSelBoxUserSelect().

Comments SelBoxUserSelection() is called afterSelBoxUserSelect() to see what the user selected. Usethe following functions to access this list:SelListNumSelections(), SelListGetSelection(), andSelListFree(). (Refer to the sample server code forexamples of the selection box usage).

Page 165: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-63

SelListFreeVOID WINAPI

SelListFree( HANDLE hSelList)

This function will free the memory associated with the selection list.

Parameter Description

hSelList The selection list handle obtained by callingSelBoxUserSelection().

Return Value None.

Comments None.

Page 166: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-64 Chapter 10

SelListGetSelectionLONG WINAPI

SelListGetSelection( HANDLE hSelList,int nSelection)

This function gets the indicator value for a selection at the specified number.

Parameter Description

hSelList The selection list handle obtained by callingSelBoxUserSelection().

nSelection The selection to be examined, the entries start at entry 0and increase to SelListNumSelections( hSelList) -1.

Return Value The value set for this entry as an indicator by theSelBoxAddEntry() call.

Comments None.

Page 167: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-65

SelListNumSelectionsint WINAPI

SelListNumSelections( HANDLE hSelList)

This function returns how many entries are in the specified hSelList.

Parameter Description

hSelList The selection list handle obtained by callingSelBoxUserSelection().

Return Value Count of selected entries during the SelBoxUserSelect()call.

Comments None.

Page 168: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-66 Chapter 10

SetCommEventMaskUINT FAR *WINAPI

SetCommEventMask( int nCid,UINT fnEvt)

The SetCommEventMask() function does no operation on Windows NT/2000. It isprovided for common code convenience only.

Parameter Description

nCid This parameter is ignored on Windows NT/2000.

fnEvt This parameter is ignored on Windows NT/2000.

Return Value NULL pointer.

Comments Windows NT/2000 only but provides no operation.Emulates Windows function.

Page 169: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-67

SetSplashScreenParamsvoid WINAPI

SetSplashScreenParams( BOOL bSuppressSplashScreen, int nSplashSelect, UINT iProductID, LPSTR lpszPrivateString)

A call to this function should be placed in ProtInit() to enable or disable the splashscreen at start-up, and determine how it will be displayed.

Parameter Description

bSuppressSplashScreen If TRUE, suppresses the splash screen entirely. Thismay be appropriate if your program displays a splashscreen itself elsewhere. If FALSE, the selected splashscreen will be displayed for a few seconds and will thenbe erased.

nSplashSelect If zero, displays the original Wonderware splash screenusing the dialog resource WWStartup. This is providedfor backward compatibility. If non-zero, displays theCommon User Interface splash screen.

iProductID Identifies the type of product. For a Win32 server, thisvalue should be COMMON_IOSERVER32ID. For theCommon UI splash screen, this is used to select thebitmap file that will be displayed in the splash screen.For the WWStartup splash screen, it has no function.

lpszPrivateString Pointer to a string that can be displayed in the CommonUI splash screen as additional information about theprogram. For the WWStartup splash screen, it has nofunction.

Return Value None.

Comments The default is for the Toolkit to display the CommonUser Interface splash screen at start-up. Since theserver-specific code in ProtInit() is called before theToolkit displays the splash screen, this is theprogrammer’s opportunity to control or alter thisbehavior. If you are using the CommonUI splash screen,you might prefer instead to call the functionWWAnnounceStartup(), which displays theCommonUI splash screen and also issues a start-upmessage that appears in the Wonderware Logger.

Page 170: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-68 Chapter 10

StatAddValuevoid WINAPI

StatAddValue( HSTAT hStat, PTVALUE value )

Add indicated value to indicated statistics item; for strings and discretes, no change.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

value A union of type PTVALUE. The user must know thetype of data associated with this statistical point. Basedon the point type, use the appropriate field in thisstructure (it contains fields for discrete, integer, and real,as well as a handle to memory containing a string).

Return Value None.

Comments This routine assumes that the statistics item and the valuein value are of the same data type – i.e. both are integersor both are reals. No conversion is made. Mixing datatypes will yield unpredictable results. This functionshould not be called if the statistic has been unregistered.

Page 171: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-69

StatDecrementValuevoid WINAPI

StatDecrementValue( HSTAT hStat )

Decrement value for indicated statistics item by 1; for strings and discretes, no change.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

Return Value None.

Comments This routine checks the type of data encoded in thestatistics item. If it is a numerical data type, the value isdecremented by 1 (by 1.0 in the case of reals). Thisfunction should not be called if the statistic has beenunregistered.

Page 172: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-70 Chapter 10

StatGetValuePTVALUE WINAPI

StatGetValue( HSTAT hStat )

Retrieve the current value for indicated statistics item.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

Return Value A union of type PTVALUE, the value corresponding tothe indicated statistics point. Note that for points of typePTT_STRING, the value contains a pointer to a memorybuffer where the string is actually stored.

Comments For a rate statistic, the value returned is always thecurrent calculated rate value, and will always beaccessed from ptValue.real. For a counter statistic, theunion member containing the value is determined by theptType passed to StatRegisterCounter(). If thestatistics handle hStat is invalid, a value ofPTVALUE.intg==0 is returned.

Page 173: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-71

StatIncrementValuevoid WINAPI

StatIncrementValue(HSTAT hStat )

Increment value for indicated statistics item by 1; for strings and discretes, no change.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

Return Value None.

Comments This routine checks the type of data encoded in thestatistics item. If it is a numerical data type, the value isincremented by 1 (by 1.0 in the case of reals). Thisfunction should not be called if the statistic has beenunregistered.

Page 174: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-72 Chapter 10

StatRegisterCounterHSTAT WINAPI

StatRegisterCounter( IDLDEV idLogDev, IDSTDDEV idStdDev, LPSTR lpszName, PTTYPE ptType )

Register a statistical counter with the indicated name and point type. The statistic can beassociated either with a logical device (topic) defined in the protocol or with a standardstatistics device (standard topic) – such as $PORT, $DEVICE, or $SERVER. Once theitem is registered, the Toolkit will automatically handle validating the point name whena client attempts to access it, and passing updated values to interested clients. Theserver-specific code is responsible for updating the value indicated by HSTAT via callsto StatIncrementValue(), StatAddValue(), etc.

Parameter Description

idLogDev Identifier of the logical device (topic) to which thisstatistic is to be assigned. This is the handle supplied bythe Toolkit as a parameter in theProtAllocateLogicalDevice() call. If idLogDev is zero,the statistic will be assigned to one of the standarddevices (topics) maintained internally by the Toolkit,identified by the second parameter idStdDev.

idStdDev Identifier of the standard device (topic) to which thisstatistic is to be assigned. This parameter is used only ifidLogDev is zero, and must be one of the following:STDDEV_PORT, STDDEV_DEVICE, orSTDDEV_SERVER.

lpszName Far pointer to a string which contains the name of thestatistics item.

ptType Identifies the point type for the item. Typically this isPTT_INTEGER, but can be any of the other point typesalso: PTT_DISCRETE, PTT_REAL, PTT_STRING.

Return Value Handle of statistical item, a non-zero number assignedby the Toolkit and unique to this item that identifies thisstatistical point/item in any future calls to the statisticalfunctions. Returns NULL handle if unsuccessful. If theindicated statistic is already registered, the handle of thatstatistic will be returned.

Comments The statistic will automatically be initialized with a valueof zero (or for strings, to a NULL pointer, indicating “nostring assigned”). Also, the statistic will be reset to zeroif an I/O client pokes any value to “ResetAll” on theSYSTEM topic or to “ResetStats” on the topic to whichthis counter belongs. If the statistic becomes invalid,you should call the function StatUnregisterCounter()to unregister the statistic point.

Page 175: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-73

StatRegisterRateHSTAT WINAPI

StatRegisterRate( IDLDEV idLogDev, IDSTDDEV idStdDev, LPSTR lpszName, DWORD interval, BYTE units, PTTYPE ctrType, HSTAT hStatCtr )

Register a statistical rate with the indicated name. The statistic can be associated eitherwith a logical device (topic) defined in the protocol or with a standard statistics device(standard topic) – such as $PORT, $DEVICE, or $SERVER. Once the item isregistered, the Toolkit will automatically handle validating the point name when a clientattempts to access it, and passing updated values to interested clients.

The input value to the rate calculation is a counter value, which can either be anotherstatistical item counter or a counter value maintained internally within the rate itemitself. The output of the rate calculation will always be of point type PTT_REAL.

Parameter Description

idLogDev Identifier of the logical device (topic) to which thisstatistic is to be assigned. This is the handle supplied bythe Toolkit as a parameter in theProtAllocateLogicalDevice() call. If idLogDev is zero,the statistic will be assigned to one of the standarddevices (topics) maintained internally by the Toolkit,identified by the second parameter idStdDev.

idStdDev Identifier of the standard device (topic) to which thisstatistic is to be assigned. This parameter is used only ifidLogDev is zero, and must be one of the following:STDDEV_PORT, STDDEV_DEVICE,STDDEV_SERVER.

lpszName Far pointer to a string which contains the name of thestatistics item.

interval Unsigned 32-bit integer indicating the interval betweenrate calculations, in milliseconds – i.e. how often the ratevalue will be updated. Clients can modify this value byaccessing the point with the name specified by lpszNameconcatenated with “$INTERVAL”.

units Identify the units for the divisor in the rate calculation:

Value Meaning

STATS_TIME_MSEC milliseconds

STATS_TIME_SEC seconds

STATS_TIME_MIN minutes

STATS_TIME_HR hours

STATS_TIME_DAY days

Example: If the rate indicates changes per second, thisshould be STATS_TIME_SEC.

Page 176: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-74 Chapter 10

ctrType Identify the point type for the input counter item for therate calculation. Must be PTT_INTEGER orPTT_REAL. Note that this parameter is ignored if theparameter hStatCtr is non-zero.

hStatCtr Handle of the associated statistics counter item for thisrate calculation. If hStatCtr is zero, this indicates that noinput counter is used and the counter will instead bemaintained internally within the rate item itself. In thiscase, the internal counter must be manipulated via thefunctions which manipulate statistics values[StatAddValue(), StatIncrementValue(), etc]. IfhStatCtr is non-zero, then the rate calculation will beperformed using the counter value maintained separatelyby the handle returned from StatRegisterCounter().

Return Value Handle of statistical rate item, a non-zero numberassigned by the Toolkit and unique to this item thatidentifies this statistical point/item in any future calls tothe statistical functions. Returns NULL handle ifunsuccessful. If the indicated statistic is alreadyregistered, the handle of that statistic will be returned.

Comments Providing both an interval and units allows completeflexibility in the rate calculation frequency and units.For example, you can get a per-hour rate (units =TIME_HR) calculated once per minute (interval =60000). This function call will automatically create twoI/O items – one for the rate itself and one for the rateitem interval, which can be accessed by clients via therate item name concatenated with the string“$INTERVAL” (e.g. HOURLY_RATE$INTERVAL).If the statistic becomes invalid, you should call thefunction StatUnregisterRate() to unregister the statisticpoint.

Page 177: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-75

StatSetCountersIntervalBOOL WINAPI

StatSetCountersInterval( IDLDEV idLogDev, IDSTDDEV idStdDev, DWORD interval )

Set a new update (i.e. reporting) interval for the counters on the indicated logical device(topic) or standard statistics device (standard topic – such as $PORT, $DEVICE, or$SERVER). This defines the time interval at which all registered statistical counters onthe device will be updated to any interested clients. If this function is not called, thevalue specified by the WIN.INI setting “StatCountersInterval” (with a default interval of10000 msec) is used. Note that the counter interval for a given logical device can alsobe manipulated by a client via the “CounterInterval” item name on the topic.

Parameter Description

idLogDev Identifier of the logical device (topic) to which thisstatistic is to be assigned. This is the handle supplied bythe Toolkit as a parameter in theProtAllocateLogicalDevice() call. If idLogDev is zero,the statistic will be assigned to one of the standarddevices (topics) maintained internally by the Toolkit,identified by the second parameter idStdDev.

idStdDev Identifier of the standard device (topic) to which thisstatistic is to be assigned. This parameter is used only ifidLogDev is zero, and must be one of the following:STDDEV_PORT, STDDEV_DEVICE,STDDEV_SERVER.

interval Unsigned 32-bit integer indicating the interval betweenupdates, in milliseconds.

Return Value TRUE if successful.

Comments This function only affects statistical counters registeredwith StatRegisterCounter(). This setting is not used tocontrol the interval at which the actual counter valuechanges in the statistical sub-system – it is used only tocontrol the rate at which updates to external clients areperformed.

Page 178: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-76 Chapter 10

StatSetRateIntervalBOOL WINAPI

StatSetRateInterval( HSTAT hStat, DWORD interval )

Set new update interval for indicated rate item.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to StatRegisterRate().

interval Unsigned 32-bit integer indicating the interval betweenrate calculations, in milliseconds.

Return Value TRUE if successful.

Comment This is equivalent to accessing the rate interval createdwhen StatRegisterRate() was called. Note that clientscan access this interval via the rate item nameconcatenated with the string “$INTERVAL” (e.g.HOURLY_RATE$INTERVAL).

Page 179: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-77

StatSetValuevoid WINAPI

StatSetValue( HSTAT hStat, PTVALUE ptValue)

Set new value for indicated statistics item; this is used for counters and to calculaterates.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

ptValue A union of type PTVALUE. The user must know thetype of data associated with this statistical point. Basedon the point type, use the appropriate field in thisstructure (it contains fields for discrete, integer, and real,as well as a handle to memory containing a string).

Return Value None.

Comment This function should not be called if the statistic hasbeen unregistered.

Page 180: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-78 Chapter 10

StatSubtractValuevoid WINAPI

StatSubtractValue( HSTAT hStat, PTVALUE ptValue )

Subtract indicated value from indicated statistics item; for strings and discretes, nochange.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

ptValue A union of type PTVALUE. The user must know thetype of data associated with this statistical point. Basedon the point type, use the appropriate field in thisstructure (it contains fields for discrete, integer, and real,as well as a handle to memory containing a string).

Return Value None.

Comments This routine assumes that the statistics item and the valuein value are of the same data type – i.e. both are integersor both are reals. No conversion is made. Mixing datatypes will yield unpredictable results. This functionshould not be called if the statistic has been unregistered.

Page 181: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-79

StatUnregisterCounterBOOL WINAPI

StatUnregisterCounter( IDLDEV idLogDev, IDSTDDEV idStdDev,

HSTAT hStat )

Unregister the indicated counter on the indicated logical device. If the counter handlehStat is NULL, unregister ALL counter statistics on this topic. The server-specific codeshould call this function if the statistic counter is no longer valid. After unregistration,this item will no longer be automatically validated or updated to any interested clients.However, any clients which currently have the point on advise will retain the lastupdated item for the value.

Parameter Description

idLogDev Identifier of the logical device (topic) to which thisstatistic is to be assigned. This is the handle supplied bythe Toolkit as a parameter in theProtAllocateLogicalDevice() call. If idLogDev is zero,the statistic will be assigned to one of the standarddevices (topics) maintained internally by the Toolkit,identified by the second parameter idStdDev.

idStdDev Identifier of the standard device (topic) to which thisstatistic is to be assigned. This parameter is used only ifidLogDev is zero, and must be one of the following:STDDEV_PORT, STDDEV_DEVICE,STDDEV_SERVER.

hStat Handle from the Toolkit that identifies a particularstatistics counter item, assigned by a call toStatRegisterCounter(). If NULL, unregister all counterstatistics in this topic.

Return Value TRUE if successful. FALSE indicates that eitheridLogDev, idStdDev, or hStat was unknown to theToolkit.

Comment This function should be called when the statistic counterbecomes invalid. However, it need not be called as partof a ProtFreeLogicalDevice() function call for theindicated idLogDev. In this case, the Toolkit calls thisfunction implicitly.

Page 182: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-80 Chapter 10

StatUnregisterRateBOOL WINAPI

StatUnregisterRate( IDLDEV idLogDev, IDSTDDEV idStdDev, HSTAT hStat )

Unregister the indicated rate on the indicated logical device. If the rate handle hStat isNULL, unregister ALL rate statistics on this topic. The server-specific code should callthis function if the statistic rate is no longer valid. After unregistration, this item will nolonger be automatically validated or updated to any interested clients. However, anyclients which currently have the point on advise will retain the last updated item for thevalue.

Parameter Description

idLogDev Identifier of the logical device (topic) to which thisstatistic is to be assigned. This is the handle supplied bythe Toolkit as a parameter in theProtAllocateLogicalDevice() call. If idLogDev is zero,the statistic will be assigned to one of the standarddevices (topics) maintained internally by the Toolkit,identified by the second parameter idStdDev.

idStdDev Identifier of the standard device (topic) to which thisstatistic is to be assigned. This parameter is used only ifidLogDev is zero, and must be one of the following:STDDEV_PORT, STDDEV_DEVICE,STDDEV_SERVER.

hStat Handle from the Toolkit that identifies a particularstatistics rate item, assigned by a call toStatRegisterRate(). If NULL, unregister all ratestatistics for this topic.

Return Value TRUE if successful. FALSE indicates that eitheridLogDev, idStdDev, or hStat was unknown to theToolkit.

Comment This function should be called when the statistic ratebecomes invalid. However, it need not be called as partof a ProtFreeLogicalDevice() function call for theindicated idLogDev. In this case, the Toolkit calls thisfunction implicitly.

Page 183: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-81

StatZeroValuevoid WINAPI

StatZeroValue( HSTAT hStat )

Set zero value for indicated statistics item; for strings, clear string buffer pointer.

Parameter Description

hStat Handle from the Toolkit that identifies a particularstatistics item, assigned by a call to eitherStatRegisterCounter() or StatRegisterRate().

Return Value None.

Comments This routine checks the data type of the indicatedstatistics point. Numerical and Boolean items are set tozero. For strings, the buffer pointer is cleared, indicatingno string is assigned. This function should not be calledif the statistic has been unregistered.

Page 184: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-82 Chapter 10

StrValSetNStringPTVALUE WINAPI

StrValSetNString( PTVALUE ptValueOld,LPSTR lpszValue,int nMax)

StrValSetNString() is used to initialize or change the value of a ptValue string whilelimiting the length of the input.

Parameter Description

ptValueOld If this is the initial call, set hString to NULL before thiscall. If you are changing an existing string, this is theptValue used previously that may be removed oroverwritten.

lpszValue Far pointer to the new string (null terminated or to amaximum of nMax) which will be moved into the systemmemory for use by the Toolkit database.

nMax The maximum number of characters read from thelpszValue string.

Return Value New ptValue to be saved.

Comments This function is functionally identical toStrValSetString() except that a limit can be put on thestring size. This function will move characters until aNULL is reached or the maximum limit (then a NULL isstored).

Example/* only sets the value to "This " */ptValue = StrValSetNString( ptValue, "This is a new value", 5 );

Page 185: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-83

StrValSetStringPTVALUE WINAPI

StrValSetString( PTVALUE ptValueOld,LPSTR lpszValue)

StrValSetString() is used to initialize or change the value of a ptValue string.

Parameter Description

ptValueOld If this is the initial call, set hString to NULL before thiscall. If you are changing an existing string, this is theptValue used previously that may be removed oroverwritten.

lpszValue Far pointer to the new string (null terminated) which willbe moved into the system memory for use by the Toolkitdatabase.

Return Value New ptValue to be saved.

Comments Be aware that calls to StrValSetString() (as well asStrValSetNString() ) cause heap memory to beallocated. Only set the hString to NULL prior to thefirst call, or memory will be lost. When you are donewith the ptValue, call StrValStringFree().

Example/* We have never used the ptValue before so null it. */ptValue.hString = NULL;/* Now store strings ready to be sent to the Toolkit Database */ptValue = StrValSetString( ptValue, "This is the new value" );ptValue = StrValSetString( ptValue, "This is a newer value & size" );

Note Version 5.0 and later of the I/O Server Toolkit allocate string memory from theheap rather than using system global memory resources.

Page 186: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-84 Chapter 10

StrValStringFreePTVALUE WINAPI

StrValStringFree( PTVALUE ptValue)

StrValStringFree() will free the memory used for a ptValue string.

Parameter Description

ptValue This is the ptValue supplied by the StrValSetString()call.

Return Value This is the new ptValue to be saved for future stringfunction calls.

Comments Free strings only when the server has been using theminternally. If the ptValue came from or is going to theToolkit database, do not free it. To save or manipulatethe string, copy the string to an internal string element.

Page 187: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-85

StrValStringLockLPSTR WINAPI

StrValStringLock( PTVALUE ptValue)

This function will lock a string in memory and return a far pointer to the beginning ofthe string memory.

Parameter Description

ptValue This is the ptValue supplied by the StrValSetString()call.

Return Value Far pointer to the string (null terminated) which ispointed to by the ptValue memory handle. A NULLreturn means the string memory could not be locked.

Comments Be sure to unlock any locked memory at the earliestpossible opportunity. When memory is locked, it cannotbe moved by Windows memory management. The lesslocked memory, the better.

Note Be sure to execute the same number of locks and unlocks on any piece of memory.If, for any reason, the memory is locked more than once, it must be unlocked more thanonce.

Example (function using lock/unlock)BOOLFAR PASCALCompareString( ptValue )PTVALUE ptValue; /* String from database or device */{LPSTR lpszVal;BOOL rtn; rtn = FALSE; if( ptValue.hString != NULL ) { lpszVal = StrValStringLock( ptValue ); if( lpszVal ) { if( lstrcmpi( lpszVal, "Value" ) == 0 ) { rtn = TRUE;} StrValStringUnlock( ptValue ); } } return( rtn );}

Page 188: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-86 Chapter 10

StrValStringUnlockVOID WINAPI

StrValStringUnlock( PTVALUE ptValue)

This function will unlock a string in memory previously locked by StrValStringLock().

Parameter Description

ptValue This is the ptValue supplied by the StrValSetString()call.

Return Value None.

Comments StrValStringLock() and StrValStringUnlock() areused to lock/unlock the value of a ptValue string. Referto the StrValStringLock() code example.

Note Be sure to execute the same number of locks and unlocks on any piece ofmemory. If, for any reason, the memory is locked more than once, it must be unlockedmore than once.

Page 189: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-87

SysTimerSetupProtTimerBOOL WINAPI

SysTimerSetupProtTimer( DWORD dwMsec)

This function sets up a timer that goes off every dwMsec milliseconds and callsProtTimerEvent ().

Parameter Description

dwMsec Interval timer range from 1 to 32767 milliseconds.

Return Value TRUE means that the interval requested was acceptable.FALSE means that it was out of range and should bechanged.

Comments This timer should be set to a value that is reasonable forthe protocol data supply rate. Intervals that arearbitrarily too short will result in needless systemoverhead.

Page 190: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-88 Chapter 10

SysTimerSetupRequestTimerBOOL WINAPI

SysTimerSetupRequestTimer(DWORD dwMsec)

This function sets up a timer that goes off every dwMsec milliseconds and checks forvalid data timeout errors within the Toolkit database.

Parameter Description

dwMsec Interval timer range from 1 to 32000 milliseconds.

Return Value TRUE means that the interval requested was acceptable.FALSE means that it was out of range and should bechanged.

Note This timer should be set to a value that is reasonable for the protocol data timeout.The interval should be a reasonable factor of the ValidDataTimeout parameter return inthe ProtGetValidDataTimeout() calls. Intervals that are arbitrarily too short will resultin needless system overhead.

Page 191: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-89

UdAddFileTimeOffsetvoid WINAPI

UdAddFileTimeOffset( FILETIME *ft1, long lDelta, FILETIME *ft2 )

Add indicated time difference (in 100 nsec / 8192) to source time mark.

Return result in destination time mark.

Note: FILETIME is a 64-bit value defined in Win32 as the number of 100 nanosecondintervals since January 1, 1601. It is organized as two DWORDS, dwLowDateTime anddwHighDateTime.

Parameter Description

ft1 Pointer to a FILETIME structure for a date/time stampwhich serves as the source time mark, i.e. the date/timeto which the indicated interval will be added.

lDelta Interval to be added to source date/time, in units of 100nanoseconds / 8192, i.e. 1.220703125 milliseconds.

ft2 Pointer to a FILETIME structure for a date/time stampwhich serves as the destination time mark, i.e. theresulting date/time stamp after the interval lDelta hasbeen added to the source date/time stamp.

Return Value None.

Comments The use of the 100 nsec / 8192 is provided forconvenience and rapid calculations, as it is close to a 1msec interval, but requires only a simple shift operationto calculate, instead of division or multiplication of a 64-bit number. You may prefer to use the functionUdAddTimeMsec() instead

Page 192: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-90 Chapter 10

UdAddTimeMSecvoid WINAPI

UdAddTimeMSec( FILETIME *ft1, long lDelta, FILETIME *ft2 )

Add indicated time difference (in msec) to source time mark.

Return result in destination time mark.

Note: FILETIME is a 64-bit value defined in Win32 as the number of 100 nanosecondintervals since January 1, 1601. It is organized as two DWORDS, dwLowDateTime anddwHighDateTime.

Parameter Description

ft1 Pointer to a FILETIME structure for a date/time stampwhich serves as the source time mark, i.e. the date/timeto which the indicated interval will be added.

lDelta Interval to be added to source date/time, in units of 1millisecond.

ft2 Pointer to a FILETIME structure for a date/time stampwhich serves as the destination time mark, i.e. theresulting date/time stamp after the interval lDelta hasbeen added to the source date/time stamp.

Return Value None.

Comments The use of 1 millisecond intervals is convenient, butconversions to and from units of 100 nanosecondsrequire division or multiplication of 64-bit numbers. Iflarge numbers of high-speed calculations are required,you may prefer to use calls to the functionUdAddFileTimeOffset() instead.

Page 193: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-91

UDDbGetNameVOID WINAPI

UDDbGetName( IDLDEV idLogDev, HDB hDb,

LPSTR lpszName)

Get name of database item for indicated logical device.

Note: this is the same as the following function:

VOID WINAPI DbGetName ( IDLDEV idLogDev, HDB hDb, LPSTR lpszName);

Parameter Description

idLogDev Topic (logical device) identifier that was supplied by theToolkit as a parameter in theProtAllocateLogicalDevice() call.

hDb Handle from the Toolkit that is unique to this item andwas supplied as a parameter in the ProtCreatePoint()call.

lpszName Far pointer to the string buffer where the name will bereturned.

Page 194: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-92 Chapter 10

UdDeltaFileTimelong WINAPI

UdDeltaFileTime( FILETIME *ft1, FILETIME *ft2 )

Calculate signed difference between 2 FILETIMEs in 100 nsec / 8192

delta = (ft1 - ft2) / 8192

Note: FILETIME is a 64-bit value defined in Win32 as the number of 100 nanosecondintervals since January 1, 1601. It is organized as two DWORDS, dwLowDateTime anddwHighDateTime.

Parameter Description

ft1 Pointer to a FILETIME structure for a date/time stampwhich serves as the ending time mark, i.e. the date/timestamp at which some event or interval finished.

ft2 Pointer to a FILETIME structure for a date/time stampwhich serves as the starting time mark, i.e. the date/timestamp at which some event or interval started.

Return Value Interval between the two date/time stamps, in units of100 nanoseconds / 8192, i.e. 1.220703125 milliseconds.Value is returned as a signed LONG integer.

Comments The use of the 100 nsec / 8192 is provided forconvenience and rapid calculations, as it is close to a 1msec interval, but requires only a simple shift operationto calculate, instead of division or multiplication of a 64-bit number. You may prefer to use the functionUdDeltaTimeMsec() instead

Page 195: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-93

UdDeltaTimeMSeclong WINAPI

UdDeltaTimeMSec( FILETIME *ft1, FILETIME *ft2 )

Calculate signed difference between 2 FILETIMEs in msec

( delta = (ft1 - ft2)/10000 )

Return difference as a signed LONG integer.

Note: FILETIME is a 64-bit value defined in Win32 as the number of 100 nanosecondintervals since January 1, 1601. It is organized as two DWORDS, dwLowDateTime anddwHighDateTime.

Parameter Description

ft1 Pointer to a FILETIME structure for a date/time stampwhich serves as the ending time mark, i.e. the date/timestamp at which some event or interval finished.

ft2 Pointer to a FILETIME structure for a date/time stampwhich serves as the starting time mark, i.e. the date/timestamp at which some event or interval started.

Return Value Interval between the two date/time stamps, in units of 1millisecond. Value is returned as a signed LONGinteger.

Comments The use of 1 millisecond intervals is convenient, butconversions to and from units of 100 nanosecondsrequire division or multiplication of 64-bit numbers. Iflarge numbers of high-speed calculations are required,you may prefer to use calls to the functionUdDeltaFileTime() instead.

Page 196: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-94 Chapter 10

UdInitBOOL WINAPI

UdInit( HANDLE hInstance,HANDLE hPrevInstance,LPSTR lpszCmdLine,int nCmdShow)

This function is intended for use by a Windows application that already exists and needsto be extended to include the DDE capability provided by the Toolkit. It is used toinitialize the I/O Server Toolkit and should only be used by a Windows applicationwhich supplies its own WinMain() function. UdInit() should be called early in theactivation of such applications. Most I/O Servers do not have to call this function sincethey allow the Toolkit to supply the WinMain() function. The parameter list is identicalto the parameter list for the Windows WinMain() function.

Parameter Description

hInstance Handle of the current instance of the application.

hPrevInstance Handle of the previous instance of the application.

lpszCmdLine Pointer to a string containing the command line for theapplication.

nCmdShow Specifies how the window is to be shown.

Return Value TRUE indicates the Toolkit initialized successfully.

FALSE indicates an initialization failure and that theapplication should terminate.

Comments This function should only be called by an applicationwhich must supply its own WinMain() function ratherthan using the one supplied in the Toolkit.

Page 197: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-95

UdReadAnyMoreBOOL WINAPI

UdReadAnyMore( HFILE hCfgFile,short FAR *pbAnyMore)

This function reads a bAnyMore flag from the configuration file. This flag is usedwithin the configuration file to indicate whether more records of a certain type exist.Such a flag is usually necessary when the number of records is unknown.

Parameter DescriptionhCfgFile File handle of the configuration file.

pbAnyMore Pointer to the boolean value to be set with the value readout of the configuration file.

Return Value TRUE if the read operation succeeded. FALSEotherwise.

Comments None.

Page 198: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-96 Chapter 10

UdReadVersionBOOL WINAPI

UdReadVersion( long lMagic,long FAR *lVersion,HFILE hCfgFile)

This function reads the version number from the server configuration file. It alsoverifies that the magic number stored in the file matches the specified magic number.

Parameter DescriptionlMagic Magic number to be checked against the magic number

in the configuration file.

lVersion Points to a longword variable to receive theconfiguration file’s version number.

hCfgFile File handle of the configuration file.

Return Value TRUE if the magic number matches. FALSE otherwise.

Comments Configuration file must be previously opened.

Page 199: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-97

UdTerminatevoid WINAPI

UdTerminate( HINSTANCE hInstance)

This function is intended for use by Windows applications that already exist and need tobe extended to include the DDE capability provided by the Toolkit. It is used to closethe I/O Server Toolkit, but it should only be used by a Windows application whichsupplies its own WinMain() function and calls the UdInit() function to initialize theToolkit. UdTerminate() should be called at application shutdown time. Most I/OServers do not have to call this function since they allow the Toolkit to supply theWinMain() function.

Parameter DescriptionhInstance Handle of the current instance of the application.

Return Value None.

Comments This function should only be called by an applicationwhich must supply its own WinMain() function ratherthan using the one supplied in the Toolkit.

Page 200: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-98 Chapter 10

UdWriteAnyMoreBOOL WINAPI

UdWriteAnyMore( HFILE hCfgFile,short bAnyMore)

This function writes a bAnyMore flag to the configuration file. This flag is used withinthe configuration file to indicate whether more records of a certain type exist.

Parameter DescriptionhCfgFile File handle of the configuration file.

bAnyMore Boolean value to be written to the configuration file.

Return Value TRUE if the write operation succeeded. FALSEotherwise.

Comments Configure file must be previously opened.

Page 201: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-99

UdWriteVersionBOOL WINAPI

UdWriteVersion( long lMagic,long lVersion,HFILE hCfgFile,char FAR *szDate,char FAR *szTime)

This function writes the version number, magic number, date, and time to the serverconfiguration file.

Parameter DescriptionlMagic Magic number to be written to the configuration file.

lVersion Version number to be written to the configuration file.

hCfgFile File handle of the configuration file.

szDate Points to a date string to be written.

szTime Points to a time string to be written.

Return Value TRUE if the write operation succeeds. FALSEotherwise.

Comments Configuration file must be previously opened.

Page 202: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-100 Chapter 10

WriteCommint WINAPI

WriteComm( int idComDev,void *lpvBuf,

int cbWrite)

This function writes the specified bytes to the specified communications device.

Parameter DescriptionidComDev The id of the communications device to be written to.

The OpenComm() function returns this value.

lpvBuf Points to the buffer that contains the bytes to be written.

cbWrite Specifies the number of bytes to be written.

Return Value The return value specifies the number of bytes written, ifsuccessful. The return value is less than zero if an erroroccurs, making the absolute value of the return value thenumber of bytes written.

Comments When an error occurs, the cause of the error can bedetermined by using the GetCommError() function toretrieve the error value and status.Windows NT/2000only. Emulates Windows function.

Page 203: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-101

WriteWindowSizeToWinIniVOID WINAPI

WriteWindowSizeToWinIni( HWND hWnd)

This function saves the size of the server window to the last adjusted size.

Parameter DescriptionhWnd Handle of window whose size is to be saved.

Return Value None.

Comments None.

Page 204: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-102 Chapter 10

WWAnnounceStartupvoid WINAPI

WWAnnounceStartup( UINT iProductID, LPSTR lpszSplashString

Set up to display Common User Interface splash screen and log start-up message, usingindicated product ID and private strings.

Parameter Description

iProductID Identifies the type of product. For a Win32 server, thisvalue should be COMMON_IOSERVER32ID. For theCommon UI splash screen, this is used to select thebitmap file that will be displayed in the splash screen.

lpszSplashString Pointer to a string that can be displayed in the splashscreen as additional information about the program.

Return Value None.

Comments The default is for the Toolkit to display the CommonUser Interface splash screen at start-up. Since theserver-specific code in ProtInit() is called before theToolkit displays the splash screen, this is theprogrammer’s opportunity to control or alter thisbehavior. If do not wish to use the CommonUI splashscreen, you should call SetSplashScreenParams() toselect the WWStartup dialog resource or to suppress thesplash screen altogether. In this case, you should alsocall debug() to display your own startup message in theWonderware Logger.

Note If you are developing products for Wonderware, this function and itscorresponding definitions will be of interest..

The following code would appear in ProtInit().

Example/* set up string with server name and version number */strcpy (szServerIDstring, GetString (STRUSER+142)); /* "Sample I/O Server" */L = strlen (szServerIDstring);sprintf (&szServerIDstring[L], GetString (STRUSER+145), /* "- Version %s" */ SERVER_VERSION);/* set up to display common start-up message and splash screen */WWAnnounceStartup (COMMON_IOSERVER32ID, (LPSTR) szServerIDstring);

Page 205: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-103

WWCenterDialogVOID WINAPI

WWCenterDialog( HWND hDlg)

This function places the specified dialog at the center of the screen.

Parameter DescriptionhDlg Window handle for the dialog to be centered.

Return Value None.

Comments None.

Page 206: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-104 Chapter 10

WWConfigureComPortBOOL WINAPI

WWConfigureComPort( LPWW_CP_DLG_LABELS lpDlgLabels)

This function displays and manages the communications port settings configurationdialog. It should only be used by serial servers. This dialog allows configuration ofcommunications parameters for one or more serial communications ports. Thesesettings are written to the WW_CP_DLG_LABELS structure for use by the server.

Parameter DescriptionlpDlgLabels Points to a WW_CP_DLG_LABELS structure that

contains initial and final dialog values and dialog controlinformation.

Return Value The return value is TRUE if the dialog box display issuccessful. Otherwise, it is FALSE.

Comments The WW_CP_DLG_LABELS structure must beproperly initialized prior to calling this function. For acomplete description of how to implement, refer to "I/OServer Toolkit Data Structures" section.

Structure typedef struct tagWW_CP_DLG_LABELS {

HWND hwndOwner;char far *szDriverName;LPWW_CP_PARAMS lpDefaultCpParams;LPWW_CP_PARAMS lpCpParams;int iNumPorts;BOOL bAllowBaud110;BOOL bAllowBaud300;BOOL bAllowBaud600;BOOL bAllowBaud1200;BOOL bAllowBaud2400;BOOL bAllowBaud4800;BOOL bAllowBaud9600;BOOL bAllowBaud14400;BOOL bAllowBaud19200;BOOL bAllowBaud38400;BOOL bAllowBaud56000; /* not used */BOOL bAllowBaud57600; /* not used */BOOL bAllowBaud115200; /* not used */BOOL bAllowBaud128000; /* not used */BOOL bAllowDatabits7;BOOL bAllowDatabits8;BOOL bAllowStopbits1;BOOL bAllowStopbits2;BOOL bAllowParityEven;BOOL bAllowParityOdd;BOOL bAllowParityNone;BOOL bAllowParityMark;BOOL bAllowParitySpace;char far *szCustom1BoxLabel;char far *szCustom1Radio1Label;char far *szCustom1Radio2Label;struct tagWW_CP_DLG_LABELS FAR

*lpRadio2DlgLabels;char far *szCustom2BoxLabel;char far *szCustom2Radio1Label;

Page 207: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-105

char far *szCustom2Radio2Label;char far *szCustom3BoxLabel;char far *szCustom3Radio1Label;char far *szCustom3Radio2Label;char far *szCheck1Label;char far *szCheck2Label;char far *szCustomEditLabel;UINT uCustomEditBase;UINT uCustomEditLowLimit;UINT uCustomEditHighLimit;FARPROC lpfnConfigureSave;int iInternalUseOnly;char reserved[16];

} WW_CP_DLG_LABELS, FAR*LPWW_CP_DLG_LABELS;

A variable with the type of WW_CP_PARAMS structure is a member ofWW_CP_DLG_LABELS and can be written and read directly from the serverconfiguration file. It is properly aligned for all platforms and has the following form:

typedef struct tagWW_CP_PARAMS {

unsigned long uBaud;unsigned long uDataBits;unsigned long uStopBits;unsigned long Parity;unsigned long uReplyTimeout;unsigned long uCustomEdit;short bCustom1Radio;short bCustom2Radio;short bCustom3Radio;short bCheck1;short bCheck2;char reserved[30]; /* pad to 64 bytes */

} WW_CP_PARAMS, FAR *LPWW_CP_PARAMS;

For a full description of this structure, refer to the "I/O Server Toolkit Data Structures"chapter.

Page 208: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-106 Chapter 10

WWConfigureServerBOOL WINAPI

WWConfigureServer( LPWW_SERV_PARAMS lpServerParams)

This function displays and manages the server parameter configuration dialog. Thisdialog allows configuration of several parameters related to overall operation of the I/OServer. These settings are written out as profile information to the WIN.INI file by thisdialog function and only take effect upon restarting of the server.

Parameter DescriptionlpServerParams Points to a WW_SERV_PARAMS structure that

contains initial and final dialog values and dialog controlinformation.

Return Value The return value is TRUE if the dialog box display issuccessful. Otherwise, it is FALSE.

Comments The WW_SERV_PARAMS structure must be properlyinitialized prior to calling this function. For a completedescription of how to implement, refer to "I/O ServerToolkit Data Structures" for details.

Structure typedef struct tagWW_SERV_PARAMS {

HWND hwndOwner;char far *szCfgPath;int iSizeOfszCfgPath;char far *szDriverName;BOOL bIndefWriteRetrySupported;BOOL bIndefWriteRetry;BYTE bPreventChanges;BYTE bNotService;BYTE bCFGfileUnused;BYTE nNTServiceSetting;char far *szCaption;char reserved[8];

} WW_SERV_PARAMS, FAR*LPWW_SERV_PARAMS;

The value returned in nNTServiceSetting is an OR of the following bits:

#define WW_NTSERVICE_IS_SERVICE (0x01) /* set to run as NT service */#define WW_NTSERVICE_CHANGED (0x02) /* setting was changed */#define WW_NTSERVICE_ERROR (0x04) /* unable to establish new

service settings */

Page 209: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-107

WWConfirmBOOL WINAPI

WWConfirm( LPWW_CONFIRM lpConfirm)

This function displays and manages the confirmation dialog which indicates thedirectory or file where server settings are to be saved. It should only be called when theconfiguration file does not currently exist.

Parameter DescriptionlpConfirm Points to a WW_CONFIRM structure that contains

initial and final dialog values and dialog controlinformation.

Return Value The return value is TRUE if the dialog box display issuccessful. Otherwise, it is FALSE.

Comments The WW_CONFIRM structure must be properlyinitialized prior to calling this function. For a completedescription of this structure refer to the "I/O ServerToolkit Data Structures" chapter.

Structure typedef struct tagWW_CONFIRM {

HWND hwndOwner;* Identifies Window that owns the dialog box */char far *szCfgPath;/* points to a buffer that holds pathname */int iSizeOfszCfgPath;char far *szDriverName;char reserved[16];

} WW_CONFIRM, FAR *LPWW_CONFIRM;

Page 210: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-108 Chapter 10

WWDisplayAboutBoxBOOL WINAPI

WWDisplayAboutBox( LPWW_AB_INFO lpAbout)

This function displays and manages the dialog displaying copyright and versioninformation. It is generally intended for use by Wonderware servers since it displays theWonderware copyright information. However, it does provide facilities for easilydisplaying version and date information and is available for use by other servers.

Parameter DescriptionlpAbout Points to a WW_AB_INFO structure that contains

dialog control information.

Return Value The return value is TRUE if the dialog box display issuccessful. Otherwise, it is FALSE.

Comments The WW_AB_INFO structure must be properlyinitialized prior to calling this function. For a completedescription on this structure, refer to the I/O ServerToolkit Data Structures chapter.

Structure typedef struct tagWW_AB_INFO {

HWND hwndOwner;char far *szDriverName;char far *szId;char far *szVersion;char far *szCopyright;HICON hIcon;char far *szComment;char reserved[12];

} WW_AB_INFO, FAR *LPWW_AB_INFO;

Page 211: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-109

WWDisplayAboutBoxExBOOL WINAPI

WWDisplayAboutBoxEx( LPWW_AB_INFO lpAbout,

UINT iProductID,

LPSTR szPrivateStr)

Display Common User Interface about box, using indicated product ID and privatestring, or Wonderware Common Dialog about box, as is appropriate.

Note If you are developing products for Wonderware, this function will be of interest.This function serves primarily to provide source code compatibility between FS2000and pre-FS2000 servers.

Parameter DescriptionlpAbout Points to a WW_AB_INFO structure that contains

dialog control information.

iProductID Identifies the type of product. For a Win32 server, thisvalue should be COMMON_IOSERVER32ID. For theCommon UI splash screen, this is used to select thebitmap file that will be displayed in the splash screen.

szPrivateStr Pointer to a string that can be displayed in the AboutBox as additional information about the program.

Return Value The return value is TRUE if the dialog box display issuccessful. Otherwise, it is FALSE.

Comments The WW_AB_INFO structure must be properlyinitialized prior to calling this function. For a completedescription on this structure, refer to the I/O ServerToolkit Data Structures chapter.

Structure typedef struct tagWW_AB_INFO {

HWND hwndOwner;char far *szDriverName;char far *szId;char far *szVersion;char far *szCopyright;HICON hIcon;char far *szComment;char reserved[12];

} WW_AB_INFO, FAR *LPWW_AB_INFO;

Page 212: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-110 Chapter 10

WWDisplayConfigNotAllowVOID WINAPI

WWDisplayConfigNotAllow(LPSTR szAppName)

This function displays a message box indicating that configuration of the server is notallowed while the server is in use.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

Return Value None.

Comments None.

Page 213: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-111

WWDisplayErrorCreatingVOID WINAPI

WWDisplayErrorCreating( LPSTR szAppName,

LPSTR szFileName)This function displays a message box indicating that an error was encountered whilecreating the specified file.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

szFileName Pointer to a character string containing the file name forwhich the create operation failed.

Return Value None.

Comments None.

Page 214: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-112 Chapter 10

WWDisplayErrorReadingVOID WINAPI

WWDisplayErrorReading( LPSTR szAppName,LPSTR szFileName)

This function displays a message box indicating that an error was encountered whilereading the specified file.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

szFileName Pointer to a character string containing the file name forwhich the read operation failed.

Return Value None.

Comments None.

Page 215: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-113

WWDisplayErrorWritingVOID WINAPI

WWDisplayErrorWriting( LPSTR szAppName,LPSTR szFileName)

This function displays a message box indicating that an error was encountered whilewriting the specified file.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

szFileName Pointer to a character string containing the file name forwhich the write operation failed.

Return Value None.

Comments None.

Page 216: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-114 Chapter 10

WWDisplayKeyNotEnabint WINAPI

WWDisplayKeyNotEnab( LPSTR szAppName)

This function displays a message box indicating that the installed security key does notenable operation of this I/O Server.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

Return Value Returns the MessageBox() return code.

Comments This function is not used by servers which do not utilizea hardware security key.

Page 217: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-115

WWDisplayKeyNotInstint WINAPI

WWDisplayKeyNotInst( LPSTR szAppName)

This function displays a message box indicating that the required security key is notinstalled on the system.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

Return Value Returns the MessageBox() return code.

Comments This function is not used by servers which do not utilizea hardware security key.

Page 218: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-116 Chapter 10

WWDisplayOutofMemoryVOID WINAPI

WWDisplayOutofMemory( LPSTR szAppName,LPSTR szObjectName)

This function displays a message box indicating that an error was encountered whileallocating memory for the specified object.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

szObjectName Pointer to a character string containing the description ofthe object for which the memory allocating failed.

Return Value None.

Comments None.

Page 219: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-117

WWFormCpModeStringVOID WINAPI

WWFormCpModeString( LPWW_CP_PARAMS lpComPortParams,int index,char FAR *szMode)

This function creates a null-terminated string containing device control information.

Parameter DescriptionlpComPortParams Points to a WW_CP_PARAMS structure defining

communications port parameters. This structure is readdirectly from the configuration file and returned by theWWConfigureComPort() function.

index Communications port index (e.g. 1 for COM1).

*szMode Points to the string to receive the resulting device controlinformation string.

Return Value None.

Comments This string will have the same format as the MS-DOSmode command.

Page 220: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-118 Chapter 10

WWGetDialogHandleHWND WINAPI

WWGetDialogHandle( void)

This function returns a window handle to the top-most dialog in the current application.

Parameter DescriptionReturn Value Window handle of the top-most dialog in the current

application.

Comments None.

Page 221: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-119

WWGetDriverNameExtensionBOOL WINAPIWWGetDriverNameExtension( LPSTR lpszNameExt, int nLen )Get name extension for use in storing and retrieving Registry settings.

This function is implemented in the Wonderware Common Dialog DLL and is called byGetServerNameExtension(). Locating the source of the extension string in a singleplace helps ensure consistency between the server-specific code and the CommonDialogs. The string is “_IOServer” and is appended to the “short” server name toproduce the full name of the server, which is used for accessing the Registry and theService Control Manager.

Parameter DescriptionlpszNameExt Points to a string buffer to which the extension string can

be copied.

nLen Length of the buffer at lpszNameExt.

Return Value True if successful.

Comments The string returned is “_IOServer” and is obtained fromthe Wonderware Common Dialogs to ensure that it isconsistent.

Page 222: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-120 Chapter 10

WWGetExeFilePathchar *

WWGetExeFilePath( char *szCfgPathStr, int maxlen)

Get path to directory where executable is located.

Replacement for _getcwd (temp_szCfgPath, PATH_STRING_SIZE);

Use this function to get the path to the server EXE file, instead of using getcwd() or_getcwd(). The reason for this is that on a Windows NT/2000 platform, the CWD(current working directory) may in fact be the directory of another program that isstarting up your server. [You can even encounter this problem when developing withMicrosoft Visual C++, if your project directory and your executable directory aredifferent.] WWGetExeFilePath() will get the correct path to the server executable,regardless of how the server is invoked.

Parameter DescriptionszCfgPathStr Points to a string buffer into which the path string can be

stored.

maxlen Length of the buffer at szCfgPathStr.

Return Value Pointer to the path string. Returns NULL ifunsuccessful.

Comments The maximum length of a path string is defined inMicrosoft Visual C++ by the constant _MAX_PATH.

Page 223: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-121

WWGetOsPlatformDWORD

WWGetOsPlatform( void );

Get platform, operating system info, summarize in global variable dwWWOsPlatform.

If dwWWOsPlatform is zero, perform operating system calls to determine the platform;otherwise, just return the present value.

This routine is called by the I/O Server Toolkit early in its start-up sequence. You canget the value from the global variable

extern DWORD dwWWOsPlatform;

or you can force a re-read of the operating system by forcing the value to zero andcalling the function:

dwWWOsPlatform = 0; WWGetOsPlatform( );

The platform information is returned as a combination of bits, defined as follows:

#define WW_OSPLATFORM_W16 (0x00000001) /* Win 16 */

#define WW_OSPLATFORM_W32 (0x00000002) /* Win 32 */#define WW_OSPLATFORM_WIN31 (0x00000100) /* Windows 3.1x */#define WW_OSPLATFORM_WIN95 (0x00000200) /* Windows 95 */#define WW_OSPLATFORM_NT (0x00000400) /* Windows NT */#define WW_OSPLATFORM_WOW (0x00010000) /* WOW (Win16 on NT) */#define WW_OSPLATFORM_INTEL (0x01000000) /* Intel processor */#define WW_OSPLATFORM_ALPHA (0x02000000) /* DEC Alpha processor */#define WW_OSPLATFORM_MIPS (0x04000000) /* MIPS processor */#define WW_OSPLATFORM_PPC (0x08000000) /* Power PC processor */#define WW_OSPLATFORM_UNKNOWN (0x80000000) /* unable to read info */

Example/* determine platform */WWGetOsPlatform();if ((dwWWOsPlatform & (WW_OSPLATFORM_W32 | WW_OSPLATFORM_NT)) == (WW_OSPLATFORM_W32 | WW_OSPLATFORM_NT)){ /* Win32 on Windows NT */ debug ("Running on Windows NT");}else{ /* not Windows NT -- assume running on Windows 95 */ debug ("Running on Windows 95 or earlier");}

Page 224: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-122 Chapter 10

wwHeap_AllocPtrLPVOID WINAPI

wwHeap_AllocPtr( HHEAP hHeap,WORD wGmemFlags,DWORD dwSize)

wwHeap_AllocPtr() is used to allocate the specified amount of memory using the heapspecified by hHeap.

Parameter Description

hHeap The heap handle supplied by wwHeap_Init().

wGmemFlags Control flags for the allocated memory:

GMEM_ZEROINIT

GMEM_MOVEABLE

dwSize Number of bytes needed in this piece of memory.

Return Value A far pointer to the memory allocated. A NULL isreturned if the memory could not be allocated.

Comments When Windows memory is low or large blocks cannotbe allocated, a return of NULL may result. Theapplication must handle this situation gracefully. Forexample, displaying a Message Box warning theoperator about low memory; then rejecting the currentoperation.

Note Message Boxes indicating low memory must be SYSTEM modal or they won'tappear in low memory conditions. See WWDisplayOutofMemory() function.

Page 225: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-123

wwHeap_FreePtrVOID WINAPI

wwHeap_FreePtr( HHEAP hHeap,LPVOID lpPtr)

wwHeap_FreePtr() is used to free the allocated memory specified by lpPtr.

Parameter Description

hHeap The heap handle supplied by wwHeap_Init().

lpPtr Long pointer to the allocated memory.

Return Value None.

Comments None.

Page 226: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-124 Chapter 10

wwHeap_InitHHEAP WINAPI

wwHeap_Init( void)

wwHeap_Init() is used to create and initialize a heap.

Parameter Description

Return Value The handle for this heap. NULL means there was anerror and no memory heap was allocated.

Comments This call must be done prior to anywwHeap_AllocPtr(), wwHeap_FreePtr(), andwwHeap_ReAllocPtr().

Page 227: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-125

wwHeap_ReAllocPtrLPVOID WINAPI

wwHeap_ReAllocPtr( HHEAP hHeap,LPVOID lpPtr,WORD wGmemFlags,DWORD dwSize)

wwHeap_ReAllocPtr() is used to re-allocate the specified amount of memory used inthe heap specified by lpPtr.

Parameter Description

hHeap The heap handle supplied by wwHeap_Init().

lpPtr Long pointer to the allocated memory.

wGmemFlags Control flags for the allocated memory:

GMEM_ZEROINIT

GMEM_MOVEABLE

dwSize Number of bytes needed in this piece of memory.

Return Value A long pointer to the memory allocated. A NULL isreturned if the memory could not be allocated.

Comments When Windows memory is low or large blocks cannotbe allocated, a return of NULL may result. Theapplication must handle this situation gracefully. Forexample, displaying a message box to warn the operatorabout low memory; then rejecting the current operation.

Note Message boxes indicating low memory must be SYSTEM modal or they won'tappear in low memory conditions. See WWDisplayOutofMemory() function.

Page 228: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-126 Chapter 10

wwHeap_ReleaseBOOL WINAPI

wwHeap_Release( HHEAP hHeap)

This function is used to release a heap which was created with wwHeap_Init().

Parameter Description

hHeap The heap handle supplied by wwHeap_Init().

Return Value TRUE indicates success. FALSE indicates failure.

Comments None.

Page 229: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-127

WWInitComPortComboBoxVOID WINAPI

WWInitComPortComboBox(HWND hDlg,int iNumPorts,int idControl)

This function creates a communications port selection box for display on a dialog. Mostcommonly, it will be used in a topic configuration dialog for selection of thecommunications port for serial communications.

Parameter DescriptionhDlg Window handle of the dialog to contain the combo box.

iNumPorts Number of communications ports to be listed.

idControl Control identifier of the selection box.

Return Value None.

Comments None.

Page 230: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-128 Chapter 10

WWReadAnyMoreNote: the following functions have been retired, and no longer work:

WWReadVersion(), WWWriteVersion(),WWReadAnyMore(), WWWriteAnyMore()

Either replace them with their corresponding UdXXX functions

UdReadVersion(), UdWriteVersion(),UdReadAnyMore(), UdWriteAnyMore()

or create user-defined functions to accomplish the same result.

Page 231: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-129

WWReadVersionNote: the following functions have been retired, and no longer work:

WWReadVersion(), WWWriteVersion(),WWReadAnyMore(), WWWriteAnyMore()

Either replace them with their corresponding UdXXX functions

UdReadVersion(), UdWriteVersion(),UdReadAnyMore(), UdWriteAnyMore()

or create user-defined functions to accomplish the same result.

Page 232: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-130 Chapter 10

WWSelectBOOL WINAPI

WWSelect( LPWW_SELECT lpSelectParams)

This function displays a dialog containing a list box which will contain a list of stringsspecified by the server. The user will be provided options for adding, modifying, ordeleting entries from this list. This function is most commonly used to display a list oftopics or boards for configuration.

Parameter DescriptionlpSelectParams Points to a WW_SELECT structure that contains

information necessary for displaying the selection list.

Return Value The return value is TRUE if the dialog box display issuccessful. Otherwise, it is FALSE.

Comments The WW_SELECT structure contains several pointersto callback functions which must be supplied by theserver developer. For a complete description of how toimplement, refer to "I/O Server Toolkit Data Structure"chapter.

Structure typedef struct tagWW_SELECT {

HWND hwndOwner;char far *szTitle;char far *szGroupBoxLabel;GETLISTHEADPROC lpfnGetListHead;GETNEXTNODEPROC lpfnGetNextNode;GETNODENAMEPROC lpfnGetNodeName;ADDNODEPROC lpfnAddNode;CONFIGNODEPROC lpfnConfigNode;DELETENODEPROC lpfnDeleteNode;BOOL bAddDeleteModifyEnabled;unsigned char bDoNotConfirmDeletes;char reserved[15];

} WW_SELECT, FAR *LPWW_SELECT;

Page 233: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-131

WWSetAffinityToFirstCPUvoid WINAPI

WWSetAffinityToFirstCPU( void)

This function locks the I/O Server execution to the first CPU on a SMP (symmetricalmultiprocessor) machine only.

Parameter DescriptionReturn Value None.

Comments None.

Page 234: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-132 Chapter 10

WWTranslateCDlgToWinBaudUINT WINAPI

WWTranslateCDlgToWinBaud(UINT uCDlgBaud)

This function translates the WWCOMDLG constant for baud rate to the Windowsequivalent.

Parameter DescriptionuCDlgBaud Specifies WWCOMDLG constant representing the baud

rate for the characters sent and received.

Return Value The return value is the Windows constant correspondingto the baud rate specified.

Comments None.

Page 235: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-133

WWTranslateCDlgToWinDataUINT WINAPI

WWTranslateCDlgToWinData(UINT uCDlgData)

This function translates the WWCOMDLG constant for number of data bits to theWindows equivalent.

Parameter DescriptionuCDlgData WWCOMDLG constant representing number of bits in

the characters sent and received.

Return Value The return value is the Windows constant correspondingto the number of data bits specified.

Comments None.

Page 236: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-134 Chapter 10

WWTranslateCDlgToWinParityUINT WINAPI

WWTranslateCDlgToWinParity(UINT uCDlgParity)

This function translates the WWCOMDLG constant for parity to the equivalentWindows.

Parameter DescriptionuCDlgParity Specifies WWCOMDLG constant representing the

parity for the characters sent and received.

Return Value The return value is the Windows constant correspondingto the parity specified.

Comments None.

Page 237: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-135

WWTranslateCDlgToWinStopUINT WINAPI

WWTranslateCDlgToWinStop(UINT uCDlgStop)

This function translates the WWCOMDLG constant for number of stop bits to theWindows equivalent.

Parameter DescriptionuCDlgStop WWCOMDLG constant representing number of stop

bits.

Return Value The return value is the Windows constant correspondingto the number of stop bits specified.

Comments None.

Page 238: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-136 Chapter 10

WWTranslateWinBaudToCDlgUINT WINAPI

WWTranslateWinBaudToCDlg(UINT uBaud)

This function translates the Windows constant for baud rate to the WWCOMDLGequivalent.

Parameter DescriptionuBaud Specifies baud rate for the characters sent and received.

Must be one of CS_BAUD_110, CS_BAUD_300,CS_BAUD_600, CS_BAUD_1200, CS_BAUD_2400,CS_BAUD_4800, CS_BAUD_9600,CS_BAUD_14400, CS_BAUD_19200,CS_BAUD_38400.

Return Value The return value is the WWCOMDLG constantcorresponding to the baud rate specified.

Comments None.

Page 239: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-137

WWTranslateWinDataToCDlgUINT WINAPI

WWTranslateWinDataToCDlg(UINT uWinData)

This function translates the Windows constant for number of data bits (7 or 8) to theWWCOMDLG equivalent.

Parameter DescriptionuWinData Specifies number of bits in the characters sent and

received. Can be 7 or 8.

Return Value The return value is the WWCOMDLG constantcorresponding to the number of data bits specified.

Comments None.

Page 240: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-138 Chapter 10

WWTranslateWinParityToCDlgUINT WINAPI

WWTranslateWinParityToCDlg(UINT uParity)

This function translates the Windows constant for parity to the WWCOMDLGequivalent.

Parameter DescriptionuParity Specifies parity for the characters sent and received.

Must be one of CS_PARITY_EVEN,CS_PARITY_ODD, CS_PARITY_NONE,CS_PARITY_MARK, CS_PARITY_SPACE.

Return Value The return value is the WWCOMDLG constantcorresponding to the parity specified.

Comments None.

Page 241: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-139

WWTranslateWinStopToCDlgUINT WINAPI

WWTranslateWinStopToCDlg(UINT uStopBits)

This function translates the Windows constant for number of stop bits to theWWCOMDLG equivalent.

Parameter DescriptionuStopBits Specifies number of stop bits in the characters sent and

received. Must be ONESTOPBIT or TWOSTOPBITS.

Return Value The return value is the WWCOMDLG constantcorresponding to the number of stop bits specified.

Comments None.

Page 242: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-140 Chapter 10

WWVerifyComDlgRevBOOL WINAPI

WWVerifyComDlgRev( LPSTR szAppName,int iRequiredRev,int FAR *piMajorRev,int FAR *piMinorRev)

This function verifies that the version of WWCOMDLG.DLL installed on the system isat least as new as the specified version. It also returns the major and minor versionnumbers of the installed WWCOMDLG.DLL to the server. This function is intendedfor compatibility checking.

Parameter DescriptionszAppName Pointer to a character string containing the server’s

application name.

iRequiredRev Minimum required major version number forWWCOMDLG.DLL.

piMajorRev Pointer to an integer to receive the major version numberof WWCOMDLG.DLL.

piMinorRev Pointer to an integer to receive the minor version numberof WWCOMDLG.DLL.

Return Value TRUE if the installed WWCOMDLG.DLL is compatiblewith the server. FALSE otherwise.

Comments The server typically will call this function duringinitialization in ProtInit() to verify that the installedWWCOMDLG.DLL is compatible with the server. Thisfunction will display a message box if the DLL isincompatible. It is the server’s responsibility to exit ifthe return value is FALSE.

Page 243: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

API Function References 10-141

WWWriteAnyMoreNote: the following functions have been retired, and no longer work:

WWReadVersion(), WWWriteVersion(),WWReadAnyMore(), WWWriteAnyMore()

Either replace them with their corresponding UdXXX functions

UdReadVersion(), UdWriteVersion(),UdReadAnyMore(), UdWriteAnyMore()

or create user-defined functions to accomplish the same result.

Page 244: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

10-142 Chapter 10

WWWriteVersionNote: the following functions have been retired, and no longer work:

WWReadVersion(), WWWriteVersion(),WWReadAnyMore(), WWWriteAnyMore()

Either replace them with their corresponding UdXXX functions

UdReadVersion(), UdWriteVersion(),UdReadAnyMore(), UdWriteAnyMore()

or create user-defined functions to accomplish the same result.

Page 245: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-1

C H A P T E R 1 1

The Chain Manager

This section describes the specifications and usage of the Chain Manager library, asoftware tool for handling linked lists of any type of data – including mixed types.

Contents! Background! Chain Data Structures! Setting Up a Chain and Linking Items! Searching For Items in a Chain! Removing Items From a Chain! User-Supplied Chain Item Funchtions! Extensible Array Data Structures! Allocating, Extending, and Deleting an Extensible Array! Examples of Usage! Handling Linked Lists

Page 246: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-2 Chapter 11

BackgroundThe Chain Manager Library contains a set of software tools for handling linked lists andextensible arrays. In many ways, it is like the container class library of C++ or Java.However, it has been implemented in C and can be used with ordinary C or with C++and does not require templates. Among the key capabilities provided by the ChainManager are the following:

- Implementation of doubly-linked lists, with routines for adding items at the head ofthe list, the tail of the list, or in the middle with or without sorting. No C++templates are needed, and lists may contain mixed data types.

- Pointers from one item to the next may be either C-type far pointers or unsignedlong offsets from a base pointer.

- FindFirst ( ) and FindNext ( ) routines that accept pointers to user routines. Thesepermit easy searches of a list for items satisfying any criteria that the user wishes toimplement.

- DeleteList ( ) and DeleteFromList ( ) routines that accept pointers to user routines.These permit easy implementation of clean-up processes (much like destructmethods in C++).

- Implementation of extensible arrays. Allocation and extension routines acceptpointers to user routines that perform the actual memory management, permittingallocation on the stack, heap, or anywhere else the user requires.

In many parts of an I/O Server, there are collections of structures that can beimplemented as linked lists. Among the most common are the following:

- Lists of Boards, COM Ports, or other configured I/O channels - Lists of Topics - Lists of Messages - Symbol Tables

The process of writing servers can be greatly simplified if one can offload themanagement of linked lists (which are here called CHAINs) to a set of standard, pre-tested routines.

Typically, there are two basic kinds of data that might be linked into chains:

- Data whose location in memory remains fixedExamples: Topic configurations, Board or COM Port definitions, pendingmessages

- Data whose location might changeExample: Symbol Tables

The example I/O Server UDSAMPLE includes sample code which allocates a symboltable as an array and links the elements together in two separate lists (with forward andbackward pointers): symbol entries in use and unused symbol entries. The symboltable is extended by reallocating the array to a larger size. This means that the actuallocation of the array elements in RAM may be different after the extension of the array.The Chain Manager APIs take care of that by giving you a choice as to whether theCHAIN uses pointers or offsets from a base pointer. The distinction is made by leavinga base pointer NULL or setting it to the current base location. All the API calls forhandling the CHAIN are identical in both cases. The nice thing about this is that itenables one to manage symbol tables VERY simply using the same set of linked listroutines for inserting, finding, unchaining, deleting, etc.

The Chain Manager also includes a set of APIs for handling extensible arrays.Essentially, all you have to do is declare an extensible array structure, and provide theroutines for allocating, reallocating, and freeing the memory associated with the array.This allows the programmer to specify whether to allocate from the stack, the heap, etc.

Page 247: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-3

Chain Data StructuresGenerally, a linked list can handle structures that have a CHAINLINK as the first part oftheir structure:

typedef struct tagCHAINLINK FAR *LPCHAINLINK; /* pointer to chainlink */

typedef union tagCHAINLINKPTR /* chainlink member, pointer or offset */ {LPCHAINLINK ptr; unsigned long offs; } CHAINLINKPTR;

typedef struct tagCHAINLINK /* chainlink structure */ {CHAINLINKPTR next_item;

CHAINLINKPTR prev_item; } CHAINLINK;

Then the general item can have any size or structure the programmer requires, so long asthe first structure element is a CHAINLINK:

typedef struct tagITEM {chain_link

CHAINLINK; .... } ITEM;

Note that a list may contain items of different types and sizes. In such a mixed list, it isup to the programmer to determine how to identify the type and/or size of any givenitem. Items may be created on the stack, the heap, etc.

A list of items should be identified by a CHAIN manager structure

typedef struct tagCHAIN /* chain manager structure */ {CHAINLINKPTR first_item; CHAINLINKPTR last_item; unsigned long item_count; char FAR *base; } CHAIN;

typedef CHAIN FAR *LPCHAIN; /* pointer to chain */

If the element base is NULL, the chain uses pointers for addressing. That is, theforward and backward pointers in a CHAINLINK are pointers, and so are the pointers tofirst_item and last_item. If the element base is set to a non-NULL location, the chainuses offsets for addressing.

Page 248: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-4 Chapter 11

Setting Up a Chain and Linking Items/*******************************************************************//** Initialize a chain Clear all pointers, counts to create an empty chain Returns TRUE if successful **/BOOL InitializeChain (LPCHAIN chain);

/*******************************************************************//** Set the base pointer for a based chain Returns TRUE if successful **/BOOL SetChainBase (LPCHAIN chain, VOID FAR *new_base);

/*******************************************************************//** Insert an item at the head of a chain Returns TRUE if successful **/BOOL InsertItemAtHead (LPCHAIN chain, LPCHAINLINK new_item);

/*******************************************************************//** Append an item at the tail of a chain Returns TRUE if successful **/BOOL AppendItemAtTail (LPCHAIN chain, LPCHAINLINK new_item);

/*******************************************************************//** Insert an item before a specific point in a chain Returns TRUE if successful **/BOOL InsertItemBefore (LPCHAIN chain, LPCHAINLINK new_item, LPCHAINLINK item);

/*******************************************************************//** Insert an item after a specific point in a chain Returns TRUE if successful **/BOOL InsertItemAfter (LPCHAIN chain, LPCHAINLINK new_item, LPCHAINLINK item);

/*******************************************************************//** Insert an item in the middle of a chain using a comparison routine to keep the chain sorted Returns TRUE if successful **/BOOL InsertItemInMiddle (LPCHAIN chain, LPCHAINLINK new_item, LPCOMPARISONROUTINE compare_routine, BOOL fwd);

Note The definition of LPCOMPARISONROUTINE is provided below, in the sectionon User-Supplied Functions.

Page 249: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-5

Searching For Items in a ChainGenerally, the programmer will search through a CHAIN in order to find a particularitem or an item with certain desired properties, do something with that item, and thenpossibly search for and process other such items in the chain. To facilitate this process,the Chain Manager provides several APIs for setting up a CHAINSCANNER whichhandles the search. In a sense, this is much like setting up an iterator in C++ or Java;but in practice it is more like using the C function FindFirstFile( ) with a FIND_DATAstructure, and continuing with the function FindNextFile( ).

The CHAINSCANNER structure is defined as follows:

typedef struct tagCHAINSCANNER /* chain scanner structure */

{LPCHAIN chain; /* chain being searched */ CHAINLINKPTR item; /* last item found, if any */ BOOL forward; /* TRUE if scanning forward */ void FAR *found_routine; /* returns TRUE if item found */ void FAR *comparison_value; /* structure to use for evaluating criteria */ } CHAINSCANNER;

typedef CHAINSCANNER FAR *LPCHAINSCANNER;

/* pointer to chain scanner */

Note The definition of the found_routine is described below, in the section on User-Supplied Functions.

/*******************************************************************//** Check whether item is in indicated chain Returns TRUE if item is in chain **/BOOL IsInChain (LPCHAIN chain, LPCHAINLINK item);

/*******************************************************************//** Find first item in chain that satisfies criteria of found routine If found_routine is NULL, this routine uses AlwaysFound as a default. Search can proceed from head of chain (forward) or from tail (backward) Returns pointer if successful **/LPCHAINLINK FindFirstItem (LPCHAIN chain, BOOL forward, LPFOUNDROUTINE found_routine, void FAR *comparisonValue, LPCHAINSCANNER scanner);

/*******************************************************************//** Find first item in chain that satisfies criteria of found routine, beginning with indicated item. This allows a search to begin in the middle of a chain, as needed, starting with a particular item. If found_routine is NULL, this routine uses AlwaysFound as a default. Search can proceed from head of chain (forward) or from tail (backward) If start_item is NULL, starts with the head or tail of the chain. Returns pointer if successful **/LPCHAINLINK FindItemStartingAt (LPCHAINLINK start_item, LPCHAIN chain, BOOL forward, LPFOUNDROUTINE found_routine, void FAR *comparisonValue, LPCHAINSCANNER scanner);

Page 250: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-6 Chapter 11

/*******************************************************************//** Find first item in chain that satisfies criteria of found routine, beginning with item that follows indicated item. This allows a search to begin in the middle of a chain, as needed, starting just after a particular item. If found_routine is NULL, this routine uses AlwaysFound as a default. Search can proceed from head of chain (forward) or from tail (backward) If start_item is NULL, starts with the head or tail of the chain. Returns pointer if successful **/LPCHAINLINK FindItemFollowing (LPCHAINLINK start_item, LPCHAIN chain, BOOL forward, LPFOUNDROUTINE found_routine, void FAR *comparisonValue, LPCHAINSCANNER scanner);

/*******************************************************************//** Find next item in chain that satisfies criteria Returns pointer if successful **/LPCHAINLINK FindNextItem (LPCHAINSCANNER scanner);

/*******************************************************************//** Get next item that scanner would examine. Note that this does not check whether the item satisfies the criteria. Also, it does not advance the scan pointer. **/LPCHAINLINK GetScannerNextItem (LPCHAINSCANNER scanner);

Page 251: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-7

Removing Items From a Chain/*******************************************************************//** Remove item from chain Returns pointer if successful **/BOOL UnchainItem (LPCHAIN chain, LPCHAINLINK item);

/*******************************************************************//** Perform indicated delete operation on item and remove it from chain If delete operation is unsuccessful, item is NOT removed from chain Returns TRUE if successful **/BOOL DeleteItem (LPCHAIN chain, LPCHAINLINK item, DELETEROUTINE delete_routine);

/*******************************************************************//** Perform indicated delete operation on all items in chain and remove them from the chain If delete operation is unsuccessful on any item, operation stops and the pointer to the item is returned. If all items are deleted successfully, NULL is returned **/LPCHAINLINK DeleteChain (LPCHAIN chain, DELETEROUTINE delete_routine);

Note The definition of the delete_routine is described below, in the section on User-Supplied Functions.

Page 252: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-8 Chapter 11

User-Supplied Chain Item FunctionsFor the search, comparison, and delete operations, the user must provide a routine toperform the appropriate action. The following definitions are used:

typedef BOOL FAR FOUNDROUTINE (LPCHAINLINK item, void FAR *comparisonValue); /** result = TRUE if item satisfies criterion **/

typedef FOUNDROUTINE FAR *LPFOUNDROUTINE;

The pointers to item and to comparisonValue are of types LPCHAINLINK and voidFAR *, respectively, so that they can match any structures the programmer defines.Inside the function, the programmer is responsible for casting item to a pointer to theappropriate structure type and for defining the structure of the comparisonValue –which can be anything from a simple basic type to something more complicated. Theprogrammer is also responsible for defining what portions of the structures need to becompared and how to determine whether a match has been found.

typedef int FAR COMPARISONROUTINE (LPCHAINLINK item, LPCHAINLINK new_item); /** result = -1 if item < new_item = 0 if item = new_item = +1 if item > new_item **/

typedef COMPARISONROUTINE FAR *LPCOMPARISONROUTINE;

The pointers to item and new_item are of type LPCHAINLINK so they can match anystructures the programmer defines. As with the FOUNDROUTINE, the programmer isresponsible for casting item and new_item to the appropriate type(s) and for defininghow the comparison will be performed.

typedef BOOL FAR DELETEROUTINE (LPCHAINLINK item); /** result = TRUE if routine successful **/

typedef DELETEROUTINE FAR *LPDELETEROUTINE;

The pointer to item is of type LPCHAINLINK so that it can match any structure theprogrammer defines. Inside the comparison function, the programmer is responsible forcasting item to the appropriate structure type, for performing the clean-up, and fordetermining whether the clean-up was successful.

Also provided are two defaults, in case the user just wants to pass NULL for the pointerto the found routine or to the delete routine:

/** default found routine -- always returns TRUE **/BOOL FAR AlwaysFound (LPCHAINLINK item, void FAR *comparisonValue);

/** default delete routine -- does nothing, always returns TRUE **/BOOL FAR AlwaysDeleted (LPCHAINLINK item);

Page 253: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-9

Extensible Array Data StructuresAn extensible array structure identifies where the start of the array is located, how it is tobe allocated, and how it is to be extended.

typedef struct tagEXTARRAY {void FAR *first_member; /* location of first member */ unsigned long member_count; /* number of members in array */ unsigned long member_size; /* number of bytes per member */ unsigned long init_count; /* number of members to allocate first time */ unsigned long extension_count; /* number of members to add when

extending */ void FAR *alloc_routine; /* pointer to allocation routine */ void FAR *extend_routine; /* pointer to extension routine */ void FAR *delete_routine; /* pointer to delete routine */ } EXTARRAY;typedef EXTARRAY FAR *LPEXTARRAY;

typedef LPVOID FAR ALLOCARRAYROUTINE (LPEXTARRAY array);typedef ALLOCARRAYROUTINE FAR *LPALLOCARRAYROUTINE;

typedef LPVOID FAR EXTENDARRAYROUTINE (LPEXTARRAY array);typedef EXTENDARRAYROUTINE FAR *LPEXTENDARRAYROUTINE;

typedef BOOL FAR DELETEARRAYROUTINE (LPEXTARRAY array); /** result = TRUE if routine successful **/typedef DELETEARRAYROUTINE FAR *LPDELETEARRAYROUTINE;

Page 254: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-10 Chapter 11

Allocating, Extending, and Deleting an Extensible Array/*******************************************************************//** Initialize an extensible array: Set pointers to functions to allocate, extend, and delete array, Clear all pointers, counts to create an empty array Returns TRUE if successful **/BOOL InitializeExtArray (LPEXTARRAY array, unsigned long initCount, unsigned long memberSize, unsigned long extCount, LPALLOCARRAYROUTINE allocRoutine, LPEXTENDARRAYROUTINE extendRoutine, LPDELETEARRAYROUTINE deleteRoutine);

/*******************************************************************//** Allocate an extensible array: Set all pointers, counts, and attempt to allocate memory Returns pointer to first array member if successful **/LPVOID AllocExtArray (LPEXTARRAY array);

/*******************************************************************//** Extend an extensible array Update all pointers, counts, and attempt to allocate memory Returns TRUE if successful **/LPVOID ExtendExtArray (LPEXTARRAY array);

Note: If ExtendExtArray ( ) is called before AllocExtArray ( ) has been called, thesoftware performs AllocExtArray ( ) instead, ensuring that the array is allocated, ifpossible.

/*******************************************************************//** Delete an extensible array Returns TRUE if successful **/BOOL DeleteExtArray (LPEXTARRAY array);

/*******************************************************************//** Get pointer to indicated member of extensible array Returns pointer if valid, NULL if invalid or out of range **/void FAR *GetExtArrayMemberPtr (LPEXTARRAY array, unsigned long index);

Note: The programmer is responsible for supplying routines to allocate, extend, anddelete the array. Examples are provided below for doing this on the heap.

Page 255: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-11

Examples of Usage

Memory Management for Extensible Arrays/***********************************************************//** Allocate an extensible array on the heap, Returns pointer to first member if successful **/

LPHVOID FAR AllocateHeapArray (LPEXTARRAY array){ unsigned long newSize; LPHVOID firstPtr;

/* initialize return value */ firstPtr = NULL;

if (array != NULL) { /* attempt to allocate initial array */ if ((array->member_size > 0) && (array->init_count > 0)) { newSize = array->init_count * array->member_size; firstPtr = wwHeap_AllocPtr (hHeap, GMEM_MOVEABLE | GMEM_ZEROINIT, newSize); } }

#ifdef TRACE_HEAP_ARRAY if (firstPtr) debug ("AllocateHeapArray successful" endln); else debug ("AllocateHeapArray failed" endln);#endif /* return pointer, if successful */ return (firstPtr);} /* AllocateHeapArray */

/***********************************************************//** Extend an extensible array on the heap, Returns new pointer to first member if successful **/

LPHVOID FAR ExtendHeapArray (LPEXTARRAY array){ unsigned long newCount; unsigned long newSize; LPHVOID newFirst;

/* initialize return value */ newFirst = NULL;

if (array != NULL) { /* if array is extensible, attempt to reallocate */ if ((array->first_member != NULL) && (array->member_size > 0) && (array->extension_count > 0))

Page 256: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-12 Chapter 11

{ newCount = array->member_count + array->extension_count; newSize = newCount * array->member_size; newFirst = wwHeap_ReAllocPtr (hHeap, array->first_member, GMEM_MOVEABLE | GMEM_ZEROINIT, newSize); } } /* return pointer, if successful */ return (newFirst);} /* ExtendHeapArray */

/***********************************************************//** Delete an extensible array on the heap, Returns TRUE if successful **/

BOOL FAR DeleteHeapArray (LPEXTARRAY array){ BOOL status;

/* initialize return value */ status = FALSE;

if (array != NULL) { if (array->first_member != NULL) { /* free the memory used for the array */ wwHeap_FreePtr (hHeap, array->first_member); status = TRUE; } } /* indicate success or failure */ return (status);} /* DeleteHeapArray */

Page 257: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-13

Handling Linked ListsThe examples below use a generic item of the following form:

typedef struct tagITEM {CHAINLINK chain_link; int address; char name[20+1]; int contents; int flags; } ITEM;

/***********************************************************//** Allocate a new ITEM with indicated properties, Return pointer to item if successful, NULL otherwise **/ITEM FAR *AllocItem (int new_addr, char *new_name, int new_contents, int new_flags){ ITEM FAR *lpItem;

/* attempt to allocate new item on heap */ lpItem = wwHeap_AllocPtr (hHeap, GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof(ITEM)); if (lpItem) { /* item successfully created, initialize it */ lpItem->address = new_addr; lstrcpy (lpItem->name, new_name); lpItem->contents = new_contents; lpItem->flags = new_flags; } /* return pointer to item or NULL */ return (lpItem);} /* AllocItem */

/***********************************************************//** Destroy indicated ITEM, Return TRUE if successful **/BOOL FAR DeleteItem (LPCHAINLINK lpItem){ /* free item from heap */ wwHeap_FreePtr (hHeap, lpItem); /* indicate successful */ return (TRUE);} /* DeleteItem */

Page 258: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-14 Chapter 11

/***********************************************************//** Check whether item has indicated name, Return TRUE if match found **/BOOL FAR StringFound (LPCHAINLINK lpChain_link, void FAR *lpComparisonValue){ BOOL status; char FAR *lpSt; ITEM FAR *lpItem;

/* initialize return status */ status = FALSE; /* cast parameters as appropriate structures */ lpItem = (ITEM FAR *) lpChain_link; lpSt = (char FAR *) lpComparisonValue; /* check whether match was found, return indicator */ if (lstrcmpi (lpItem->name, lpSt) >= 0) status = TRUE; /* indicate whether match was found */ return (status);} /* StringFound */

/***********************************************************//** Compare indicated item1 to item2, Return –1 if <, 0 if =, +1 if > */ if item1 < item2 **/int FAR StringCompare (LPCHAINLINK lpChain_link1, LPCHAINLINK lpChain_link2){ int retval; ITEM FAR *lpItem1, FAR *lpItem2;

/* cast parameters as appropriate structures */ lpItem1 = (ITEM FAR *) lpChain_link1; lpItem2 = (ITEM FAR *) lpChain_link2; /* compare items, set return value */ retval = lstrcmpi (lpItem1->name, lpItem2->name); if (retval > 0) retval = 1; if (retval < 0) retval = -1; return (retval);} /* StringCompare */

Page 259: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

The Chain Manager 11-15

/* Examples of chain operations */

CHAIN people;ITEM FAR *lpItem;CHAINSCANNER item_scanner;char search_name[21];

/* initialize the list of people */InitializeChain (&people);

/* allocate several entries and add to list; note that the list ends up sorted, but we’re not explictly sorting, here */lpItem = AllocItem (3579, "Fred", 7, 0xF3);AppendItemAtTail (&people, lpItem);lpItem = AllocItem (2468, "Jane", 2, 0x0B);AppendItemAtTail (&people, lpItem);lpItem = AllocItem (2473, "Jane", 4, 0x37);AppendItemAtTail (&people, lpItem);lpItem = AllocItem (1234, "Joe", 5, 0x00);AppendItemAtTail (&people, lpItem);

/* find all items with indicated name */strcpy (search_name, "Jane");lpItem = FindFirstItem (&people, SCAN_FROM_HEAD, StringFound, (LPSTR) search_name, &item_scanner);while (lpItem) { /* display item and address */ debug ("Item found with name %Fs has address %d", (LPSTR) lpItem->name, (int) lpItem->address); /* find next item, if any */ lpItem = FindNextItem (&item_scanner);}

/* create new item and insert in sorted list */lpItem = AllocItem (9742, "George", 3, 0x77);InsertItemInMiddle (&people, lpItem, StringCompare, SCAN_FROM_HEAD);

/* delete certain items from list, one by one */lpItem = FindFirstItem (&people, SCAN_FROM_HEAD, NULL, NULL, &item_scanner);while (lpItem) { if (lpItem->flags >= 0x50) { UnchainItem (&people, (LPCHAINLINK) lpItem); wwHeap_FreePtr (hHeap, lpItem); } /* find next item, if any */ lpItem = FindNextItem (&item_scanner);}

/* delete all items in list */lpItem = DeleteChain (&people, DeleteItem);

Page 260: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

11-16 Chapter 11

Page 261: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-1

C H A P T E R 1 2

I/O Server Toolkit DataStructures

The I/O Server Toolkit contains several structures associated with the API functions.These structures are defined in alphabetic order in this chapter.

Contents! Data Structure Definitions

Page 262: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-2 Chapter 12

Data Structure Definitions

PTVALUE#include "protypes.h"

typedef union {

DISC disc;INTG intg;REAL real;WHMEM hString;

} PTVALUE;

The PTVALUE union contains a value to be passed between the I/O Server Toolkit andthe server. The element of the union which contains the value is determined by thepoint’s type.

Element Descriptiondisc Byte containing value for a discrete point.

intg Long-word containing value for an integer point.

real Float containing value for a real point.

hString Memory handle for string value.

Comments Do not manipulate the hString value directly. Use thestring manipulation functions StrValSetString(),StrValSetNString(), StrValStringLock(),StrValStringUnlock(), and StrValStringFree().

Page 263: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-3

WW_AB_INFO#include "wwcomdlg.h"

typedef struct tagWW_AB_INFO {HWND hwndOwner;char far *szDriverName;char far *szId;char far *szVersion;char far *szCopyright;HICON hIcon;char *szComment;char reserved[12];

} WW_AB_INFO, FAR *LPWW_AB_INFO;

The WW_AB_INFO structure is used to configure the Wonderware About box dialoginvoked by a call to WWDisplayAboutBox() or WWDisplayAboutBoxEx().

Element DescriptionhwndOwner Handle of window which owns the dialog box.

szDriverName Pointer to a string containing the server name.

szId Pointer to a string describing the purpose of the server.For example, "GE Fanuc Series 90 Protocol".

szVersion Pointer to a string containing the version number for theserver. For example, "5.1".

szCopyright Pointer to a string containing the year for the copyrightinformation. For example, "1995".

hIcon Handle of server icon to be displayed within the dialogbox.

szComment Pointer to a string containing a comment to be displayedin the dialog box.

reserved[12] Reserved buffer space. Currently unused, but should beinitialized to 0 by caller.

Comments None.

Page 264: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-4 Chapter 12

WW_CONFIRM#include "wwcomdlg.h"

typedef struct tagWW_CONFIRM {HWND hwndOwner;char far *szCfgPath;int iSizeOfszCfgPath;char far *szDriverName;char reserved[16];

} WW_CONFIRM, FAR *LPWW_CONFIRM;

The WW_CONFIRM structure is used to configure the Save Configuration dialoginvoked by a call to WWConfirm(). This dialog is used to confirm the location forsaving server configuration information.

Element DescriptionhwndOwner Handle of window which owns the dialog box.

szCfgPath Points to a string which contains the path where theconfiguration file is to be saved. Changes typed by theuser will be placed in this buffer when WWConfirm()returns.

iSizeofszCfgPath Maximum allowed length for configuration file pathname.

szDriverName Pointer to string containing server name.

reserved[16] Reserved buffer space. Currently unused, but should beinitialized to 0 by caller.

Comments None.

Page 265: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-5

WW_CP_DLG_LABELS#include "wwcomdlg.h"

typedef struct tagWW_CP_DLG_LABELS {HWND hwndOwner;char far *szDriverName;LPWW_CP_PARAMS lpDefaultCpParams;WW_CP_PARAMS lpCpParams;int iNumPorts;BOOL bAllowBaud110;BOOL bAllowBaud300;BOOL bAllowBaud600;BOOL bAllowBaud1200;BOOL bAllowBaud2400;BOOL bAllowBaud4800;BOOL bAllowBaud9600;BOOL bAllowBaud14400;BOOL bAllowBaud19200;BOOL bAllowBaud38400;BOOL bAllowBaud56000; /* not used at this time */BOOL bAllowBaud57600; /* not used at this time */BOOL bAllowBaud115200; /* not used at this time */BOOL bAllowBaud128000; /* not used at this time */BOOL bAllowDatabits7;BOOL bAllowDatabits8;BOOL bAllowStopbits1;BOOL bAllowStopbits2;BOOL bAllowParityEven;BOOL bAllowParityOdd;BOOL bAllowParityNone;BOOL bAllowParityMark;BOOL bAllowParitySpace;char far *szCustom1BoxLabel;char far *szCustom1Radio1Label;char far *szCustom1Radio2Label;struct tagWW_CP_DLG_LABELS FAR *lpRadio2DlgLabels;char far *szCustom2BoxLabel;char far *szCustom2Radio1Label;char far *szCustom2Radio2Label;char far *szCustom3BoxLabel;char far *szCustom3Radio1Label;char far *szCustom3Radio2Label;char far *szCheck1Label;char far *szCheck2Label;char far *szCustomEditLabel;UINT uCustomEditBase;UINT uCustomEditLowLimit;UINT uCustomEditHighLimit;FARPROC lpfnConfigureSave;int iInternalUseOnly;char reserved[16];

} WW_CP_DLG_LABELS, FAR *LPWW_CP_DLG_LABELS;

Page 266: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-6 Chapter 12

The WW_CP_DLG_LABELS structure is used with the WWConfigureComPort()function to control the serial port configuration dialog. This structure containsnumerous boolean flags used to enable or disable various radio buttons or entire groupboxes. The convention for group boxes and labeled controls is that if the label field isNULL, the group box and its contents are hidden from view.

Element DescriptionhwndOwner Handle of window which owns the dialog box.

szDriverName Pointer to string containing server name.

lpDefaultCpParams Pointer to a WW_CP_PARAMS structure whichcontains the default port parameter settings. Thesesettings will be applied to the current selection when the"Defaults" button is selected. This structure should beinitialized by the caller.

lpCpParams Pointer to array of WW_CP_PARAMS structures. Thisarray contains the initial and final settings for allcommunications ports. There is one entry for eachcommunications port in the system.

iNumPorts Integer value indicating total number of entries in thelpCpParams array.

bAllowBaud110 Boolean value indicating whether the radio button for110 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud300 Boolean value indicating whether the radio button for300 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud600 Boolean value indicating whether the radio button for600 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud1200 Boolean value indicating whether the radio button for1200 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud2400 Boolean value indicating whether the radio button for2400 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud4800 Boolean value indicating whether the radio button for4800 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud9600 Boolean value indicating whether the radio button for9600 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud14400 Boolean value indicating whether the radio button for14400 baud should be enabled. A value of TRUE willenable the button.

Page 267: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-7

Element DescriptionbAllowBaud19200 Boolean value indicating whether the radio button for

19200 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud38400 Boolean value indicating whether the radio button for38400 baud should be enabled. A value of TRUE willenable the button.

bAllowBaud56000 Not supported at this time.

bAllowBaud57600 Not supported at this time.

bAllowBaud115200 Not supported at this time.

bAllowBaud128000 Not supported at this time.

bAllowDatabits7 Boolean value indicating whether the radio button for 7data bits should be enabled. A value of TRUE willenable the button.

bAllowDatabits8 Boolean value indicating whether the radio button for 8data bits should be enabled. A value of TRUE willenable the button.

bAllowStopbits1 Boolean value indicating whether the radio button for 1stop bit should be enabled. A value of TRUE willenable the button.

bAllowStopbits2 Boolean value indicating whether the radio button for 2stop bits should be enabled. A value of TRUE willenable the button.

bAllowParityEven Boolean value indicating whether the radio button foreven parity should be enabled. A value of TRUE willenable the button.

bAllowParityOdd Boolean value indicating whether the radio button forodd parity should be enabled. A value of TRUE willenable the button.

bAllowParityNone Boolean value indicating whether the radio button for noparity should be enabled. A value of TRUE will enablethe button.

bAllowParityMark Boolean value indicating whether the radio button formark parity should be enabled. A value of TRUE willenable the button.

bAllowParitySpace Boolean value indicating whether the radio button forspace parity should be enabled. A value of TRUE willenable the button.

szCustom1BoxLabel Pointer to character string for the first custom group boxlabel. If NULL, no first custom group box will bedisplayed.

szCustom1Radio1Label Pointer to character string for first radio button in firstcustom group box. Only used if szCustom1BoxLabel isnot NULL.

Page 268: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-8 Chapter 12

Element DescriptionszCustom1Radio2Label Pointer to character string for second radio button in first

custom group box. Only used if szCustom1BoxLabel isnot NULL.

lpRadio2DlgLabels Currently unused.

szCustom2BoxLabel Pointer to character string for the second custom groupbox label. If NULL, no second custom group box willbe displayed.

szCustom2Radio1Label Pointer to character string for first radio button in secondcustom group box. Only used if szCustom2BoxLabel isnot NULL.

szCustom2Radio2Label Pointer to character string for second radio button insecond custom group box. Only used ifszCustom2BoxLabel is not NULL.

szCustom3BoxLabel Pointer to character string for the third custom group boxlabel. If NULL, no third custom group box will bedisplayed.

szCustom3Radio1Label Pointer to character string for first radio button in thirdcustom group box. Only used if szCustom3BoxLabel isnot NULL.

szCustom3Radio2Label Pointer to character string for second radio button inthird custom group box. Only used ifszCustom3BoxLabel is not NULL.

szCheck1Label Pointer to character string for the first custom check boxlabel. If NULL, no first custom check box will bedisplayed.

szCheck2Label Pointer to character string for the second custom checkbox label. If NULL, no second custom check box willbe displayed.

szCustomEditLabel Pointer to character string containing the label for thecustom edit control. If NULL, custom edit control willbe displayed.

uCustomEditBase Indicates radix of the number system for custom editcontrol. For example, 10 for decimal, 16 for hex, etc.

uCustomEditLowLimit Indicates lowest allowed number to be entered forcustom edit control.

uCustomEditHighLimit Indicates highest allowed number to be entered forcustom edit control.

lpfnConfigureSave Points to a function which will be called when the portsettings are to be saved. This function will be calledwhen the "Save" button is selected or when the portsettings have been modified and the user selects a newport. No arguments are passed to this function. Thisfunction is expected to write all configurationinformation contained in the lpCpParams array.

Page 269: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-9

Element DescriptioniInternalUseOnly Reserved for internal use. Do not use.

reserved[16] Reserved buffer space. Currently unused, but should beinitialized to 0 by caller.

Comments None.

Page 270: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-10 Chapter 12

WW_CP_PARAMS#include "wwcomdlg.h"

typedef struct tagWW_CP_PARAMS {

unsigned long uBaud;unsigned long uDataBits;unsigned long uStopBits;unsigned long uParity;unsigned long uReplyTimeout;unsigned long uCustomEdit;short bCustom1Radio;short bCustom2Radio;short bCustom3Radio;short bCheck1;short bCheck2;char reserved[30]; /* pad to 64 bytes */

} WW_CP_PARAMS, FAR *LPWW_CP_PARAMS;

The WW_CP_PARAMS structure contains the configuration settings for a serialcommunications port.

Element DescriptionuBaud Contains the WWCOMDLG constant indicating the

baud rate setting.

uDataBits Contains the WWCOMDLG constant indicating thenumber of data bits setting.

uStopBits Contains the WWCOMDLG constant indicating thenumber of stop bits setting.

uParity Contains the WWCOMDLG constant indicating theparity setting.

uReplyTimeout Contains the reply timeout in seconds.

uCustomEdit Contains the setting for the custom edit control.

bCustom1Radio Boolean flag indicating which radio button in the firstcustom group box is selected. A value of TRUEindicates that the first radio button is selected. A valueof FALSE indicates that the second radio button isselected.

bCustom2Radio Boolean flag indicating which radio button in the secondcustom group box is selected. A value of TRUEindicates that the first radio button is selected. A valueof FALSE indicates that the second radio button isselected.

Page 271: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-11

Element DescriptionbCustom3Radio Boolean flag indicating which radio button in the third

custom group box is selected. A value of TRUEindicates that the first radio button is selected. A valueof FALSE indicates that the second radio button isselected.

bCheck1 Boolean flag indicating whether the first customcheckbox is selected. A value of TRUE indicates that itis selected.

bCheck2 Boolean flag indicating whether the second customcheckbox is selected. A value of TRUE indicates that itis selected.

reserved[30] Reserved buffer space. Currently unused, but should beinitialized to 0 by caller.

Comments None.

Page 272: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-12 Chapter 12

WW_SELECT#include "wwcomdlg.h"

typedef struct tagWW_SELECT {HWND hwndOwner;char far *szTitle;char far *szGroupBoxLabel;GETLISTHEADPROC lpfnGetListHead;GETNEXTNODEPROC lpfnGetNextNode;GETNODENAMEPROC lpfnGetNodeName;ADDNODEPROC lpfnAddNode;CONFIGNODEPROC lpfnConfigNode;DELETENODEPROC lpfnDeleteNode;BOOL bAddDeleteModifyEnabled;unsigned char bDoNotConfirmDeletes;char reserved[15];

} WW_SELECT, FAR *LPWW_SELECT;

The WW_SELECT structure is used with the WWSelect() function to populate andmanipulate a list box of items. This list box is typically used for presenting a list of I/Otopics. Some servers also use this listbox for presenting a list of interface boards forperusal. The dialog box associated with the list contains buttons for adding, modifying,and deleting entries, as well as the standard listbox traversal operations (arrow keys,etc.)

Element DescriptionhwndOwner Handle of window which owns the dialog box.

szTitle Pointer to a string to be placed in the title bar of thedialog.

szGroupBoxLabel Pointer to a string to be used to label the list box.

lpfnGetListHead Pointer to a function which will be called to obtain apointer to the head entry of the list.

lpfnGetNextNode Pointer to a function which will be called to obtain thesuccessor to a given list entry.

lpfnGetNodeName Pointer to a function which will be called to obtain thename of a given list entry.

lpfnAddNode Pointer to a function which will be called to add a newentry to the list. This function is called in response tothe "New..." button and will most likely put up anapplication dialog box for collecting informationregarding the new item.

Page 273: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-13

Element DescriptionlpfnConfigNode Pointer to a function which will be called to modify an

existing entry in the list. This function is called inresponse to the "Modify..." button and will most likelyput up an application dialog box for collectinginformation regarding the item.

lpfnDeleteNode Pointer to a function which will be called to delete anexisting entry in the list. This function is called inresponse to the "Delete" button. It is up to theapplication to determine if the delete operation isallowed. For example, you would not want to delete anadapter card which is in use by any topic.

bAddDeleteModifyEnabled Boolean value indicating whether the Add and Deletedialog buttons will be enabled. If TRUE, these buttonswill be enabled. This parameter will be passed as aparameter to the lpfnConfigNode callback function.

bDoNotConfirmDeletes Boolean value indicating whether a delete confirmationdialog should be automatically displayed. If this value isFALSE, the delete confirmation dialog will be displayed.

reserved[15] Reserved buffer space. Currently unused, but should beinitialized to 0 by caller.

Comments None.

Page 274: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-14 Chapter 12

WW_SERV_PARAMS#include "wwcomdlg.h"

typedef struct tagWW_SERV_PARAMS {HWND hwndOwner;char far *szCfgPath;int iSizeOfszCfgPath;char far *szDriverName;BOOL bIndefWriteRetrySupported;BOOL bIndefWriteRetry;BYTE bPreventChanges;BYTE bNotService;BYTE bCFGfileUnused;BYTE nNTServiceSetting;char far *szCaption;char reserved[8];

} WW_SERV_PARAMS, FAR *LPWW_SERV_PARAMS;

The WW_SERV_PARAMS structure is used with the WWConfigureServer() functionto initialize and manipulate the "Server Settings" dialog. This dialog is used to view andset server settings such as configuration file path and protocol timer tick.

Element DescriptionhwndOwner Handle of window which owns the dialog box.

szCfgPath Pointer to string containing the configuration file pathname.

iSizeOfszCfgPath Maximum allowed length for configuration file pathname.

szDriverName Pointer to string containing server name.

bIndefWriteRetrySupported Boolean value indicating whether the server supportsindefinite retries of failed writes. If TRUE, this optionwill be provided to the user.

bIndefWriteRetry Boolean value indicating whether the server should retryfailed writes indefinitely. Only applies if thebIndefWriteRetrySupported flag is TRUE.

bPreventChanges Boolean value indicating whether modifications shouldbe disallowed. If TRUE, the OK button will be disabled,making the dialog read-only.

bNotService Boolean value indicating whether server can beconfigured as an NT service. If TRUE, checking the“Run automatically as NT service” checkbox willgenerate an error message.

bCFGfileUnused Boolean value indicating whether a configuration file isused. If TRUE, the “Configuration File Directory” editbox will be disabled.

nNTServiceSetting Integer value, combining several flags. This value isreturned as a result from WWConfigureServer() toindicate whether changes have been made for runningthe server as an NT service and with what success.

szCaption Pointer to a string that is used as the title caption for thedialog. If NULL, the default caption is used.

Page 275: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Toolkit Data Structures 12-15

reserved[8] Reserved buffer space. Currently unused, but should beinitialized to 0 by caller.

Comments None.

The value returned in nNTServiceSetting is an OR of the following bits:#define WW_NTSERVICE_IS_SERVICE (0x01) /* set to run as NT service */#define WW_NTSERVICE_CHANGED (0x02) /* setting was changed */#define WW_NTSERVICE_ERROR (0x04) /* unable to establish new

service settings */

Page 276: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

12-16 Chapter 12

Page 277: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-1

C H A P T E R 1 3

Common Dialogs

This chapter describes usage of WWDLG32A, a Windows 98/NT/2000 Dynamic LinkLibrary (DLL), which provides a common look and feel throughout the I/O Server family.

Contents! Main Menu! Com Port Settings! Topic Definition! Server Settings! Configuration Files! Convenience Functions

Page 278: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-2 Chapter 13

Main Menu

Serial ServersSerial servers should use the following standardized main menus.

Board-based ServersBoard-based servers are nearly identical, with the exception of the wording on theinterface settings menu item:

Page 279: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Common Dialog 13-3

Com Port Settings

Serial port configuration is stored in a WW_CP_PARAMS structure. The Wonderwareservers read and write this structure directly to a configuration file. In addition, theconfiguration dialog used by WWConfigureComPort() uses this structure tocommunicate settings with the caller.

typedef struct tagWW_CP_PARAMS { unsigned long uBaud; unsigned long uDataBits; unsigned long uStopBits; unsigned long uParity; unsigned long uReplyTimeout; unsigned long uCustomEdit; short bCustom1Radio; short bCustom2Radio; short bCustom3Radio; short bCheck1; short bCheck2; char reserved[30]; /* pad to 64 bytes */} WW_CP_PARAMS, FAR *LPWW_CP_PARAMS;

Page 280: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-4 Chapter 13

The values stored in the fields are generally dialog control IDs. Translation functions areprovided to map Windows constants like CBR_9600, etc., to the proper values. Thefollowing translators are for mapping the Windows constants for word size, stop bits,parity, and baud rate to the WW_CP_PARAMS equivalents:

UINT WINAPI WWTranslateWinDataToCDlg(UINT);

UINT WINAPI WWTranslateWinStopToCDlg(UINT);

UINT WINAPI WWTranslateWinParityToCDlg(UINT);

UINT WINAPI WWTranslateWinBaudToCDlg(UINT);

The following translators are for mapping the WW_CP_PARAMS constants for wordsize, stop bits, parity, and baud rate:UINT WINAPI WWTranslateCDlgToWinData(UINT);UINT WINAPI WWTranslateCDlgToWinStop(UINT);UINT WINAPI WWTranslateCDlgToWinParity(UINT);

UINT WINAPI WWTranslateCDlgToWinBaud(UINT);

The custom fields are for parameters which are peculiar to the particular type of serialserver. MODBUS, for instance, uses these fields to indicate whether the communicationport is connected to an ASCII- or an RTU- speaking host.

The appearance of the serial port configuration dialog is controlled by theWW_CP_DLG_LABELS structure. This structure contains numerous boolean flags usedto enable or disable certain radio buttons, e.g. bAllowParityMark, or entire group boxes,e.g. szCustom1BoxLabel. The convention for group boxes and labeled controls is that ifthe label field is NULL, the group box and its contents are hidden from view.

Page 281: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Common Dialog 13-5

The following illustration shows the locations of the custom group boxes. Some fieldswithin the group boxes are mutually exclusive, and are therefore obscured in the picture.

The initial settings for all ports are passed in the lpCpParams[] array in theWW_CP_DLG_LABELS structure. This array of WW_CP_PARMS structures has oneentry for each communication port in the system. There should be one entry in thelpCpParams array for each entry in the "Com Port" list box. The size of the lpCpParamsarray is indicated in the iNumPorts field. Changes to port configuration are placed in theappropriate lpCpParams entry for the port selected by the list box.

The "Defaults" button copies the settings from the default port parameters structurelpDefaultCpParams. This structure should be initialized appropriately.

Pressing the "Save" button invokes the lpfnConfigureSave callback function. Likewise, ifthe port settings have been modified and the user selects a new port in the "Com Port" listbox, the lpfnConfigureSave callback is invoked after confirmation from the user. There areno arguments to lpfnConfigureSave. The save function is expected to write allconfiguration information in the lpCpParams array.

Page 282: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-6 Chapter 13

The CustomEdit control is intended for entering a numeric value. The uCustomEditBasefield determines the radix for the value (e.g. uCustomEditBase of 16 will allow hexnumbers to be entered). The uCustomEditLowLimit and uCustomEditHighLimit are usedby WWConfigureComPort to validate the entry. Values below the LowLimit or abovethe HighLimit will be rejected (with a message box.)

The WW_CP_DLG_LABELS structure is shown below in its entirety.typedef struct tagWW_CP_DLG_LABELS { char far *szC HWND hwndOwner; char far *szDriverName; LPWW_CP_PARAMS lpDefaultCpParams; LPWW_CP_PARAMS lpCpParams; int iNumPorts; BOOL bAllowBaud110; BOOL bAllowBaud300; BOOL bAllowBaud600; BOOL bAllowBaud1200; BOOL bAllowBaud2400; BOOL bAllowBaud4800; BOOL bAllowBaud9600; BOOL bAllowBaud14400; BOOL bAllowBaud19200; BOOL bAllowBaud38400; BOOL bAllowBaud56000; /* not used at this time */ BOOL bAllowBaud57600; /* not used at this time */ BOOL bAllowBaud115200; /* not used at this time */ BOOL bAllowBaud128000; /* not used at this time */ BOOL bAllowDatabits7; BOOL bAllowDatabits8; BOOL bAllowStopbits1; BOOL bAllowStopbits2; BOOL bAllowParityEven; BOOL bAllowParityOdd; BOOL bAllowParityNone; BOOL bAllowParityMark; BOOL bAllowParitySpace; char far szCustom1BoxLabel; char far *szCustom1Radio1Label; char far *szCustom1Radio2Label; struct tagWW_CP_DLG_LABELS FAR *lpRadio2DlgLabels;/* Not used at this time */ char far *szCustom2BoxLabel; char far *szCustom2Radio1Label; char far *szCustom2Radio2Label; char far *szCustom3BoxLabel; char far *szCustom3Radio1Label; char far *szCustom3Radio2Label; char far *szCheck1Label; char far *szCheck2Label; char far *szCustomEditLabel; UINT uCustomEditBase; UINT uCustomEditLowLimit; UINT uCustomEditHighLimit; FARPROC lpfnConfigureSave; int iInternalUseOnly; char reserved[16];} WW_CP_DLG_LABELS, FAR *LPWW_CP_DLG_LABELS;

Page 283: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Common Dialog 13-7

The "iInternalUseOnly" and "reserved" fields are for Wonderware use only. Before using,always initialize these fields to zero (a memset(...,0,sizeof WW_CP_DLG_LABELS)works nicely) to ensure compatibility with future versions of the WWDLG32A.

void WINAPI WWFormCpModeString(LPWW_CP_PARAMS, int, char FAR *);

Given a port parameter array, and a port number (1-based, i.e., 1 is COM1 ), return astring suitable for use in a Windows OpenCom call (e.g. "COM1:9600,8,N,1").

void WINAPI WWInitComPortComboBox(HWND, int iNumPorts, int

idControl);

Given the control ID of a combo box (typically CI_TEXT_COMM_PORT for thestandard Communication Port Settings dialog) and the number of ports addressable for theplatform (typically 9 for Windows 3.1 and 32 for Windows NT), load the combo boxwith the names of the ports (e.g. COM1, COM2...COM32).

BOOL WINAPI WWConfigureComPort(LPWW_CP_DLG_LABELS);

Given the dialog labels structure, display and run the "Communication Port Settings"dialog.

Page 284: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-8 Chapter 13

Topic Definition

The WW_SELECT data structure and WWSelect are used for populating andmanipulating a listbox of items. This listbox is typically used for presenting a list ofconfigured topics. Some servers also use this listbox for presenting a list of interfaceboards for perusal. The dialog box associated with the list contains buttons for adding,modifying, and deleting entries, as well as the standard listbox traversal operations (arrowkeys, etc.)

The structure WW_SELECT contains the parameters for the WWSelect listbox. Thefields of WW_SELECT are defined as follows:

HWND hwndOwner;

This is the window handle of the caller.

char far *szTitle;

This is the title string to place in the title bar of the selection dialog ("Topic Definition" inthe above dialog.)

char far *szGroupBoxLabel;

This is the label to place above the list box ("Topics" in the above dialog.)typedef void far *(CALLBACK *GETLISTHEADPROC)(void);

GETLISTHEADPROC lpfnGetListHead;

This entry point is called to obtain a pointer to the list head. WWSelect does not interpretthe pointers representing listbox entries, other than passing them back to the manipulatorfunctions represented here.typedef void far *(CALLBACK *GETNEXTNODEPROC)(void far *);

GETNEXTNODEPROC lpfnGetNextNode;

Get the successor to a given list node.typedef char far *(CALLBACK *GETNODENAMEPROC)(void far *);

GETNODENAMEPROC lpfnGetNodeName;

Get the name of a given node, (i.e. the Key field) for use in the listbox.typedef void (CALLBACK *ADDNODEPROC)(HWND);

ADDNODEPROC lpfnAddNode;

Page 285: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Common Dialog 13-9

Add a new node to the list. This routine is called in response to the "New..." button, andwill most likely need to put up an application specific dialog box for collectinginformation regarding the new item. Note that there are no list element parameters to theAddNode function -- it is up to the application to find the proper position in the list for thenew element.

BOOL bAddDeleteModifyEnabled;

If this value is TRUE, then the Delete and Modify dialog buttons will be enabled.Otherwise, the Delete and Modify dialog buttons will be disabled and the lpfnConfigNodeand lpfnDeleteNode callbacks will never be invoked. Note that the Delete and Modifybuttons are also disabled when the listbox is empty.

unsigned char bDoNotConfirmDeletes;

If this value is FALSE, then prior to calling the lpfnDeleteNode, the followingconfirmation dialog will be posted when the Delete button is pressed:

If the value is TRUE, the confirmation dialog will not appear. If the confirmation dialog isenabled, and the user selects the "No" button, the lpfnDeleteNode function will not becalled. It is sometimes desirable to perform specialized feasibility checking beforepresenting the confirmation dialog. In this case, enable the bDoNotConfirmDeletes flag,then perform any feasibility checking in the lpfnDeleteNode function before presentingyour own confirmation dialog. (See the lpfnDeleteNode example, below.)typedef void (CALLBACK *CONFIGNODEPROC)(HWND, void far *, BOOL);

CONFIGNODEPROC lpfnConfigNode;

Configure the given list entry. In general, this will put up the same dialog as for the"New..." button, and will initialize the dialog with the values from the given entry. It isreasonable for the user to be allowed to change the name of the entry, thereby creating anew entry. This is equivalent to a "New..." operation.typedef void (CALLBACK *DELETENODEPROC)(HWND, void far *);

DELETENODEPROC lpfnDeleteNode;

Delete the given entry. Called in response to the "Delete" button. It is up to theapplication to determine if the operation is possible or desirable. For example, theMBPLUS server uses the WWSelect listbox for listing SA85 adapter cards. ThelpfnDeleteNode callback in this case checks to see if the given adapter card is in use byany topics. If so, the user is notified and the card is not deleted.

char reserved[15];

Expansion space is reserved in the WW_SELECT structure. Always initialize thisreserved space to 0 to ensure compatibility with future versions of WWDLG32A.

BOOL WINAPI WWSelect(LPWW_SELECT);

Invoke the WWSelect() function with the completed WW_SELECT structure to displayand process the selection listbox.

Page 286: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-10 Chapter 13

Server Settings

The "I/O Server Settings" dialog is one of the simplest dialogs in the WWDLG32A. Inresponse to the "Server Settings..." menu item, the server should initialize aWW_SERV_PARAMS structure with the HWND of the main window, a buffercontaining the initial configuration path name (a backslash terminated directory name), thesize of the buffer, the name of the driver, and a flag indicating whether the server cansupport the "Server as a service" capability.

The server keeps the configuration path name as a Windows "ProfileString" entry. In theabsence of a profile string (e.g. the first time the server is run) the current workingdirectory is provided as the initial value for this string. The values for "Protocol TimerTick" and "NetDDE being used" and "Start automatically…" are automatically maintainedas the "ProfileInt" entries "ProtocolTimer", "ValidDataTimeout". The "ProtocolTimer"value is suitable for use in the call to the Toolkit routine SysTimerSetupProtTimer. The"NetDDE being used" flag sets the "ValidDataTimeout" profile entry (an integral value) toa value which is suitable for use in the ProtGetValidDataTimeout Toolkit callback. Thesetting for whether the server is an NT service is stored in the registry inHKEY_LOCAL_MACHINE\SOFTWARE\WONDERWARE\<server registryname>\NTSERVICE and inHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<server registryname>.

Page 287: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Common Dialog 13-11

To ensure compatibility with future versions of WWDLG32A, always initialize thereserved area to zero.

typedef struct tagWW_SERV_PARAMS { HWND hwndOwner; /* Identifies Window that owns thedialog box */ char far *szCfgPath; /* points to a buffer that holdspathname */ int iSizeOfszCfgPath; char far *szDriverName; BOOL bIndefWriteRetrySupported; BOOL bIndefWriteRetry; BYTE bPreventChanges; BYTE bNotService; BYTE bCFGfileUnused; BYTE nNTServiceSetting; char far *szCaption; char reserved[8];} WW_SERV_PARAMS, FAR *LPWW_SERV_PARAMS;

BOOL WINAPI WWConfigureServer(LPWW_SERV_PARAMS);

WWConfigureServer puts up the "Server Settings" dialog box, initialized with the valuesfrom the given LPWW_SERV_PARAMS structure and the above mentioned WIN.INIprofile settings. This function returns TRUE if the OK button was pressed, otherwise itreturns FALSE.

The returned value in nNTServiceSetting can be examined to determine whether the serverhas been configured as a Windows NT service, whether that configuration has changed,and whether there was any problem updating the system.

Page 288: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-12 Chapter 13

Configuration Files

The "Save Configuration" dialog is a convenience dialog. The server should put up thisdialog when a "Save" operation is underway, and the configuration file does not exist inthe named directory. This is the last chance for the user to avoid putting a configurationfile in the wrong directory.

The WW_CONFIRM structure is used to configure the Save Configuration dialog. TheszCfgPath field should be initialized with the path where the configuration file is to besaved. Changes typed by the user will be placed in this buffer when WWConfirm returns.If the "Make this the default configuration file" box is checked, the path in the edit box iswritten to the "ConfigurationFile" WIN.INI profile string. The "Make this the defaultconfiguration file" box will be disabled if the contents of the edit field matches the currentdefault configuration file directory.

The path name is validated before being written to the configuration file. Only valid,existing directory names are accepted.typedef struct tagWW_CONFIRM { HWND hwndOwner; /* Identifies Window that owns thedialog box */ char far *szCfgPath; /* points to a buffer that holdspathname */ int iSizeOfszCfgPath; char far *szDriverName; char reserved[16];} WW_CONFIRM, FAR *LPWW_CONFIRM;

HWND WINAPI WWGetDialogHandle(void);

Since WWConfirm is generally called from within a dialog procedure, it is notappropriate for the HWND in WW_CONFIRM to be the main window. Instead, useWWGetDialogHandle to return the window handle for the currently active dialog for usein the hwndOwner field.

BOOL WINAPI WWConfirm(LPWW_CONFIRM);

WWConfirm puts up the "Save Configuration" dialog box.

Page 289: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Common Dialog 13-13

Convenience FunctionsMany Wonderware servers use configuration files with sentinel codes embedded whichindicate if more configuration information follows. These functions encapsulate this logic.UdWriteAnyMore writes the sentinel indicating if more information will be written to thefile. UdReadAnyMore reads this sentinel value. Both functions return TRUE unlessthere was an I/O error, in which case they return FALSE.

void WINAPI WWCenterDialog(HWND hDlg);

Centers the given dialog within the screen dimensions.void WINAPI WWDisplayErrorReading(LPSTR szAppName, LPSTRszFileName);void WINAPI WWDisplayErrorWriting(LPSTR szAppName, LPSTRszFileName);void WINAPI WWDisplayErrorCreating(LPSTR szAppName, LPSTRszFileName);

Display a message box containing a message indicating one of three types of file I/O error.void WINAPI WWDisplayOutofMemory(LPSTR szAppName, LPSTRszObjectName);

Display a "Hard System Modal Message Box" indicating an inability to allocate memoryfor the given object.

int WINAPI WWDisplayKeyNotEnab(LPSTR szAppName);

int WINAPI WWDisplayKeyNotInst(LPSTR szAppName);

Display a message box indicating problems validating security information with the copyprotection device. WWDisplayKeyNotEnab complains that the key does not containaccess bits for the current server. WWDisplayKeyNotInst complains that the key is notresponding.

Page 290: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

13-14 Chapter 13

void WINAPI WWDisplayConfigNotAllow(LPSTR szAppName);

Display a message indicating that online configuration is not allowed. Servers display thismessage box if the "Com Port Settings..." or "Topic Definition..." menu items are selectedwhen any topics are open.

Page 291: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

14-1

C H A P T E R 1 4

Adding the Toolkit to anExisting Windows Application

The Toolkit can be used to add DDE (Dynamic Data Exchange) or SuiteLink capabilityto an existing Windows application. In order to accomplish this, there are several thingsthat need to be done:

•••• Must link with the Toolkit library, it is named TOOLKIT7.LIB.

•••• Must call UdInit() early in your application to initialize the Toolkit.

•••• Must call UdTerminate() at application shutdown time to close the Toolkit.

•••• Application must not register classes containing the application name returned byProtGetDriverName() or the string "WddeWnd".

•••• Application must define external data hWndParent and hInst. These variables areinitialized by UdInit().

extern HWND hWndParentextern HANDLE hInst

•••• Application must not use global variable hWndParent.

• File UDMAIN.C or file containing equivalent functionality must be added to theapplication and linked in.

• Unknown messages must be passed to ProtDefWindowProc(), notDefWindowProc ().

• User must define the boolean variable bLinkedToExistingEXE and initialize it toTRUE before calling UdInit().

extern BOOL bLinkedToExistingEXE = TRUE;

•••• Application’s resource (.RC) file must contain STRINGTABLE for protlib.str.

• Application’s resource (.RC) file must include tkitstrt.rci.

To add HELP to your application you must do your own calls to WINHELP. TheToolkit cannot do this for you.

Page 292: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

14-2 Chapter 14

Page 293: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

15-1

C H A P T E R 1 5

Running as an NT Service

This section describes how to set up an I/O Server to run as a Windows NT service.

Contents! Overview of Services! Configuration Dialog! Driver Name! Service Dependencies

Page 294: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

15-2 Chapter 15

Overview of ServicesOn Windows 98, an I/O Server runs as an application. Typically, this is also how aserver runs on a Windows NT/2000 platform. However, it is also possible to configurea server to run on Windows NT/2000 as a service.

From a functional standpoint, the main difference between a service and an applicationis this: on Windows NT/2000, someone has to be logged on to the computer for anapplication to run. That is, the computer boots up, Windows is started up, and anyapplications can then be started. Applications can even be started automatically, e.g. byplacing icons for them in the STARTUP folder. This can be set up to happencompletely automatically from a cold start on Windows 98. However, on Windows NT/2000, the programs in the STARTUP folder are not activated until a user logs on. Thiscan be a problem if someone is trying to set up a completely automatic start-up, as mightbe desirable for handling recovery from a power-loss.

Windows NT/ 2000 services run under a “system account” that starts up during the boot-up process for Windows NT/ 2000. Many functions are provided by programs runningas services “in the background,” such as TCP/IP. Also, since some services aredependent upon having other services up and running before they can start, WindowsNT/2000 provides several ways of controlling the order in which services are started up.

Once services are in place and running, a computer running Windows NT/2000 cancontinue running these services, even if no user ever logs onto the machine. Also, ifsomeone does log on, performs some operations, and logs off, programs running asservices continue to function after the user logs off from the system.

Before a service can be started, it must be installed via the Service Control Manager.Once it is installed, the start-up for the service can be configured in one of three ways:automatic, manual, or disabled. An I/O Server should be configured to startautomatically, since the intention of making an I/O Server run as a service is to have itstart as part of the boot-up process for Windows NT/ 2000.

More details about Windows NT/2000 and services can be found in Microsoft’smanuals and help files.

Page 295: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Running as an NT Service 15-3

Configuration DialogThe simplest way to set up an I/O Server as a Windows NT service is to use theWonderware Common Dialog for Server Configuration. This dialog contains acheckbox that enables or disables running the server as an NT service:

When the user clicks this checkbox and then clicks OK, the Common Dialog DLL doestwo things:

1. It attempts to set a flag in the Registry indicating to the server that it should run asan NT service. This flag is in the key HKEY_LOCAL_MACHINE\SOFTWARE\Wonderware\<server extended name> and is named NTService: REG_DWORD.For example, for the server TESTPROT, the entry would be

HKEY_LOCAL_MACHINESOFTWARE

WonderwareTESTPROT_IOServer

With value NTService: REG_DWORD: 1.

2. It attempts to get the Service Control Manager (SCM) to install the server as aservice, mark it for automatic start-up, and to set up a standard set of dependencieson other services. These settings can be found in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<server extended name>. For example, forthe server TESTPROT, the entry would be

HKEY_LOCAL_MACHINESYSTEM

CurrentControlSetServices

TESTPROT_IOServer

Various Registry values get set, including ImagePath (the path to the executable),Start (set to 0x2, i.e. automatic), and DependOnService (set to a list of servicesupon which the server depends – see below).

If the attempt to establish these settings is successful, the server is ready to run as aservice. To ensure proper operation, you should shut the server down and reboot thecomputer.

Page 296: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

15-4 Chapter 15

Typically, a server calls the Server Configuration dialog in a very generic way:/***********************************************************//* set general I/O server settings */

VOIDWINAPIServerSettings (HWND hWnd){ WW_SERV_PARAMS ServParams; char driverName [20]; char temp_szCfgPath [PATH_STRING_SIZE];

/* get name of driver application */ ProtGetDriverName (driverName, sizeof (driverName));

/* try reading the configuration path from WIN.INI */ temp_szCfgPath [0] = 0; GetProfileString(driverName, NAME_PATH, DEFAULT_PATH, temp_szCfgPath, PATH_STRING_SIZE); if (strlen (temp_szCfgPath) == 0) { /* no config path defined, use default path to EXE */ WWGetExeFilePath(temp_szCfgPath, PATH_STRING_SIZE); }

/* ensure pathname ends with a backslash */ if (temp_szCfgPath[strlen (temp_szCfgPath) - 1] != '\\') { strcat (temp_szCfgPath, "\\"); }

/* set up I/O server settings via common dialog */ memset (&ServParams, 0, sizeof ServParams); ServParams.hwndOwner = hWnd; ServParams.szCfgPath = (LPSTR) temp_szCfgPath; ServParams.iSizeOfszCfgPath = PATH_STRING_SIZE; ServParams.szDriverName = GetAppName(); ServParams.bIndefWriteRetrySupported = FALSE; if (iAllocatedDevices) { /* protocol running, don't reconfigure now */ WWDisplayConfigNotAllow (GetAppName ()); ServParams.bPreventChanges = 1; } else { /* nothing allocated, go ahead and configure */ ServParams.bPreventChanges = 0; } /* configure, or allow user to look at configuration */ WWConfigureServer((LPWW_SERV_PARAMS) &ServParams);} /* ServerSettings */

To disallow the user from checking the “run as a service” checkbox, before you callWWConfigureServer(), insert the following statements:/* disallow setting as an NTservice */ServParams.bNotService = TRUE;

This does not disable the checkbox; but the server will display an error message if theuser attempts to check it and clicks OK.

Page 297: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Running as an NT Service 15-5

After WWConfigureServer() returns, you can check whether the server was configuredas an NTservice, whether that setting was changed, and whether there was any problemupdating the Registry:if ((ServParams.nNTServiceSetting & WW_NTSERVICE_IS_SERVICE) != 0) { /* server is configured as an NT service */}if ((ServParams.nNTServiceSetting & WW_NTSERVICE_CHANGED) != 0) { /* setting was changed by the user */}if ((ServParams.nNTServiceSetting & WW_NTSERVICE_ERROR) != 0) { /* something went wrong updating the Registry */}

You can use these in various combinations to determine whether to change Registryentries for additional drivers, etc. according to whether the server is being set up as aservice or as an application. See the section below on Dependencies.

If the user un-checks the checkbox, the Common Dialog DLL does not uninstall theserver. Instead, it tells the Service Control Manager to disable start-up of the service.This is necessary because the I/O Server may be running as a service when the ServerConfiguration Dialog is accessed, and additional activities may be necessary beforeshutting down the server. To ensure proper operation, after reconfiguration you shouldshut down the system and reboot the computer.

Page 298: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

15-6 Chapter 15

Driver NameIt is important to note that the Wonderware Common Dialogs use the extended servername when accessing the Registry and the Service Control Manager. That is, theextension “_IOServer” is appended to the “short” server name to produce the extendedserver name. For example, TESTPROT becomes TESTPROT_IOServer.

The function GetServerNameExtension( ) sets up the extended server name so theserver-specific code can access it. To ensure that the name of your server is handledconsistently, you should be sure to insert a call to this function inside the routineProtGetDriverName( ), which is the routine used by the I/O Server Toolkit to obtain the“short” name of your server:/***********************************************************//** Copy name of driver to string at indicated location **/

BOOLWINAPIProtGetDriverName(LPSTR lpszName, int nMaxLength){ /** WARNING: No calls to debug()... debug() calls ProtGetDriverName(), therefore ProtGetDriverName() cannot call debug(). **/ lstrcpy(lpszName, GetString(STRUSER + 76) /* "UDSAMPLE" */ );#ifdef WIN32 GetServerNameExtension();#endif return (TRUE);} /* ProtGetDriverName */

This extension was found to be necessary where some I/O Servers had the same name asthird-party drivers (such as MODBUS.exe vs. MODBUS.sys), and attempting toconfigure both as NT services caused name clashes in the Registry and Service ControlManager.

Actually, GetServerNameExtension( ) is a function in the Toolkit that obtains theextension string from WWDLG32A.DLL (the Wonderware Common Dialog DLL). Notall products that use the I/O Server Toolkit need an extended name, which is why thiscall is performed explicitly. If GetServerNameExtension( ) is never called, theapplication name and Registry key would merely be the short name (e.g.“TESTPROT”). This is fine for most applications; but it is important to remember thatthe “Run as NT Service” checkbox in WWDLG32A.DLL assumes the name with theextension.If you don't call the function GetServerNameExtension( ), you must thenprovide your own set-up dialog and routines for making the application an NTservice.

Page 299: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Running as an NT Service 15-7

Service DependenciesSome programs depend upon the presence of other programs to run properly. Forexample, if you are using a word processor and want to print a document, you must havea printer driver loaded. It may or may not be possible to start the driver after theprogram is already running, depending on the nature of the dependency.

If an I/O Server is to run as a Windows NTservice and it depends upon other services torun, it may be necessary to start the other services first before the server will functionproperly. When the “Run as a service” checkbox is checked in the Server Settingsdialog, WWDLG32A.DLL sets up the following default set of dependencies, in thisorder:

DependOnService: REG_MULTI_SZ: WWLOGSVC WWNETDDE SLSSVC

These services are as follows:WWLOGSVC

The Wonderware Logger Service. This passes messages from debug( ) calls tothe Wonderware Logger.

WWNETDDEThe Wonderware NetDDE Helper Service. This service is necessary for DDEconversations to continue even with no one logged on a the computer.

SLSSVCThe Wonderware SuiteLink Service. This service passes messages betweenapplications using the SuiteLink protocol.

When the computer is booted up, Windows NT/2000 inspects the Registry forinformation regarding the order in which various drivers and services are to be startedup. Services and drivers can actually be put into specific groups to be loaded in specificorders. Services with no specific group are loaded last. Within a group, if a servicedepends upon other services, NT/2000 checks first to see whether other services arerunning and, if not, attempts to start them. Any problems are identified by messages inthe Windows NT/2000 Event Log, which can be accessed via the Windows NT/2000EventViewer.

Your server may have additional services upon which it depends, particularly if itrequires a device-specific driver or service to run properly. In this case, you shouldmake your own calls to access the Registry or the Service Control Manager to establishthese additional dependencies. If you use the Wonderware Common ServerConfiguration Dialog, you can check the returned information inServParams.nNTServiceSetting to check whether operation as a service hassuccessfully been changed, enabled, or disabled and determine whether to make youradditional Registry changes accordingly.

Page 300: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

15-8 Chapter 15

Page 301: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

16-1

C H A P T E R 1 6

Porting to Windows NT

This chapter will be useful for two different audiences. The first and primary audienceis the developer who wants to port an existing 16-bit Windows server to the WindowsNT environment. If you fall in this category, you will find that this chapter provides auseful recipe for accomplishing this port. The goal is to make this port asstraightforward as possible by giving you a concise set of step-by-step instructions.

The secondary audience for this chapter is the developer who wants to develop a newserver that will operate in both 16-bit Windows and 32-bit Windows. If you fall in thiscategory, the step-by-step instructions for porting an existing server to Windows NT willprovide you with some useful ideas for accomplishing this task.

Contents! Primary Goals! Server Porting Instructions! Miscellaneous Debugging Hints

Page 302: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

16-2 Chapter 16

Primary GoalsKeep the following goals in mind when porting a server from 16-bit Windows to the 32-bit Windows NT environment:

1. The source code for the server should maintain as much common code as possiblebetween the two operating systems. In cases where common code is not possible,condition compiles using "#ifdef WIN32" macros will be used.

2. If there is a server configuration file which is used to store topic, device andcommunications configurations, it should have the same file structure on bothplatforms. This allows the same configuration file to be used seamlessly regardlessof platform.

3. The server should maintain a common graphical user interface between the twoplatforms. A user should not have to learn how to use your server again uponmoving to a new operating system. A side benefit of this goal is that any user-leveldocumentation you provide for your server will not have to be customized forWindows NT.

Server Porting InstructionsThe server porting process is sequential and categorized into several phases.Generally,the earlier phases are more mechanical and simple in nature.As you progress through thephases, you will find they require more time and thought.If you have any questionsabout the meaning of any of these phases, please refer to the UDSERIAL or UDBOARDsample servers included with this Toolkit. These servers provide useful illustrations ofthe instructions described below.

Warning Backup your source code to another location prior to beginning this work.Keep in mind the following abbreviations: Win16 refers to 16-bit Windows; Win32refers to 32-bit Windows.

Page 303: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting to Windows NT 16-3

Phase I - General, Quick Edits of "C", "H" FilesGoal: Do simple, mass edits typical of all servers. Use the sample server as a referenceguide.

1. For each C file, move "#include <windows.h>" to the top of the list of includes.Insure that the windows.h is enclosed by the brackets and not double quotes.

2. Replace each "FAR PASCAL" in function definitions and prototypes with theportable "WINAPI".

3. For each C file, delete the large collection of "#define NOxxxxx" macros at or nearthe top if they exist. They are no longer needed for versions of the Windows SDKgreater than 3.0.

4. For each C file, add "#include "ntconv.h"" to the list of includes. This header filecontains porting macros which simplify the porting process. Refer to the WindowsNT Porting Functions and Macros for a list of the porting macros.

5. Replace the obsolete "assert.h" include with "wwassert.h".

6. Delete the obsolete "tools.h" include, which is no longer needed.

7. Check if you need "lmem.h" and "listrcmp.h"; They are OK but very old. listrcmpis simply lstrcmpi.

8. Replace the obsolete "lmemclr.h" include with "lmem.h" if you are using the"lmemclear()" function call.

Page 304: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

16-4 Chapter 16

Phase II - More EditsGoal: Do edits typical of all servers which require more time and thought. Use thesample server as a reference guide. Refer to the "I/O Server Toolkit Functions" sectionfor details on Windows NT Porting Functions and Macros.

1. Change all definitions and prototypes for Windows procedures, dialog procedures,and callbacks to use the new parameter declarations.

From: HWND, unsigned, WORD, LONGTo: HWND, UINT, WPARAM, LPARAM

2. Search for all occurrences of WM_COMMAND. For each occurrence, make surethat "LOWORD(wParam)" is used to get the control identifier rather than just"wParam".

3. Search for all occurrences of EM_SETSEL. The message packing for this functionvaries between Windows and Windows NT. Use the new portable functions listedbelow instead of sending an EM_SETSEL message directly.

#include "portfncs.h"PfnSendEmSelectAll( HWND hDlg, int idControl, BOOL bScrollCaret);PfnSendEmSelectRange( HWND hDlg, int idControl, int nStart, intnEnd, BOOL bScrollCaret );

For more information on these functions, see the "API Function Reference" chapter.

4. If you use the Windows ChangeMenu() function, with the 4th parameter set to "-1", change it to "0xffff". If you have time, consider converting to the newer menufunctions AppendMenu(), DeleteMenu(), InsertMenu(), ModifyMenu(), andRemoveMenu().

5. Search for all SendMessage function calls. If the first parameter is 0xffff, this isnot portable, since it would need to be 0xffffffff on Windows NT. Replace the0xffff with SM_MINUS_ONE (macro in NTCONV.H).

6. Search for references to ConfigurePort(). This function name conflicts with anative Windows NT function. Change the function name to ConfigPort() orsomething similar.

7. In all ".C", ".RC", and ".H" files, search for "BAUD_" references and change to"WW_BAUD_" references. This will prevent conflicts with native Windows NTdefinitions in WINBASE.H.

8. In all ".C", ".RC", and ".H" files, search for "PARITY_" references and change to"WW_PARITY_" references. This will prevent conflicts with native Windows NTdefinitions in WINBASE.H.

9. If you have not already, convert to the new version of the Wonderware Heap API asdescribed in the "Getting Started with the I/O Server Toolkit" section. Briefly, youwill need to change all Wonderware HeapXxXxxx style function calls towwHeap_XxXxxx. Add the HHEAP (heap handle) as the new first parameter tothe wwHeap_ReAlloc and wwHeap_FreePtr function calls.

10. Change each "Assert(FALSE);" to "ASSERT_ERROR;".

11. If the Windows function GetTextExtent() is used, change it to the portableGetTextExtentPoint() function.

12. If the Windows function MoveTo() is used, change it to the portable MoveToEx().

Page 305: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting to Windows NT 16-5

Phase III - Porting Tool (optional step)Goal: Locate any pending porting problems at this time.

At this time, you are well on the way to taking care of most of the basic porting issuesassociated with moving a server to Windows NT. Some more difficult areas related tofile I/O and communications remain.

The Microsoft Win32 SDK includes a utility called "PortTool" which you can use tolocate any potential porting problems which still remain. This is a good time to use thistool on each of your ".C" files. For the most part, it will point out potential difficultieswhich you have already solved. However, it also may catch some items which wouldotherwise slip through the cracks and cause more mysterious problems later.

Phase IV - CompilingGoal: Compile each file in the server on Win32 with no warnings/errors.

You are not yet finished making modifications, but this is a good time to compile yoursource code and let the compiler catch any obvious problems which exist. Anyproblems related to communications functions and file I/O can be ignored at this time.

1. Compile under Windows NT. You should expect some warnings and errors at thistime.

Some tips on resolving compiler problems:NULLs need to be cast to the appropriate type.

There may be errors with communications items such as fRtsDisable, fRtsflow,fDtrDisable, fDtrflow. For now, simply comment out the code. It will be fixed in thenext phase.

There may be errors with communications items such as CE_CTSTO, CE_DSRTO,CE_RLSDTO. For now, simply put the code under a "#ifndef WIN32" conditional.

Numerical constants such as -1,-2, -3, etc. when used in logical expressions can haveproblems. Make sure you cast them appropriately.

Page 306: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

16-6 Chapter 16

Phase V - Communications

(Windows COMM Driver Serial Servers Only)Goal: Add common source communications function calls. Use the sample serversource for UDSERIAL as a reference guide. Refer to the "I/O Server ToolkitFunctions" section for details on Windows NT Porting Functions and Macros.

Note If you are developing a board-based server on Windows NT, a kernel devicedriver must also be developed or purchased which interfaces directly with the board ofinterest. Your server then must be modified to communicate with the device driver inorder to send and receive messages. It can no longer access the board directly as waspossible under Windows. Documentation of device drivers and device driver interfacingis beyond the scope of these instructions. Please refer to the Microsoft Device DriversKit (DDK) for instructions and information.

1. To all ".C" files which call communications functions, add include of"NTSRVR.H". This file provides prototypes for functions which emulate thecommunications functions found in Windows. Typical files which containcommunications functions will be xxLDCFG.C, xxFREE.C, and xxPROTCL.C.

2. Change BuildCommDCB() to the compatible functionNTSrvr_BuildCommDCB().

3. Change SetCommState() to NTSrvr_SetCommState() and add the new firstparameter.

4. Change GetCommState() to NTSrvr_GetCommState(). TheNTSrvr_GetCommState() call should be located after the OpenComm() andbefore the NTSrvr_buildCommDCB(). The DCB needs to be initialized, and theWindows NT version does not initialize all members of the DCB structure. This isthe easiest way to accomplish this initialization and it works on both platforms.

5. Group the setting of the DCB's fRtsflow and fRtsDisable members together andreplace with a call to function NTSrvr_SetDCB_Rts with the parameter of:NTSrvr_RTS_DISABLE if the "fRtsDisable" was set.NTSrvr_RTS_ENABLE if the "fRtsDisable" was NOT set

and "fRtsflow was NOT set.NTSrvr_RTS_HANDSHAKE if the "fRtsflow" was set.

6. Group the setting of the DCB's fDtrflow and fDtrDisable together and replace witha call to function NTSrvr_SetDCB_Dtr() with the parameter of:NTSrvr_DTR_DISABLE if the "fDtrDisable" was set.NTSrvr_DTR_ENABLE if the "fDtrDisable" was NOT set

and "fDtrflow" was NOT set.NTSrvr_DTR_HANDSHAKE if the "fDtrflow" was set.

Page 307: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting to Windows NT 16-7

Phase VI - Compile AgainGoal: Compile each file in the server on Win32.

At this time, all your communications functions should be in place and ready forcompilation. Compile again on both platforms and resolve any warnings or errors.

Phase VII - File I/OGoal: Replace Win16 file I/O with common source file I/O macros. Use the sampleserver as a reference guide. Refer to the "I/O Server Toolkit Functions" section fordetails on Windows NT Porting Functions and Macros.

Your server probably has some file I/O calls such as open(), close(), _lread(), _lwrite(),etc. These function calls should be modified to use the portable macros provided inNTCONV.H and listed in the "I/O Server Toolkit Functions" section. Follow theseinstructions:

1. Change each read-only open() to "OPENRead(filename)".

2. Change each file-create open() to "OPENCreate(filename)".

3. Change each "read()", "_read()", or "_lread()" to simply "LREAD()".

4. Change the variations of "write" to "LWRITE".

5. Change the variations of "lseek" to "LSEEK".

6. Change the variations of "close" to "LCLOSE".

Phase VIII - Compile Again (see above)Goal: Compile on both platforms with no warnings or errors.

At this time, all your file I/O functions should be in place and ready for compilation.Compile again on both platforms and resolve any warnings or errors.

Phase IX - Symbol Table Entry SizeIn your xxMAIN.C file, there is a check of the symbol table entry size. This check is nolonger required under Windows NT, so conditionalize this check of"sizeof(SYMENT)" under a "#ifndef WIN32". See the UDMAIN.C in the UDSERIALsample server for an example.

Page 308: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

16-8 Chapter 16

Phase X - Compile Again (see above)

Phase XI - Config File CompatibilityGoal: Server configuration file (xxxxxx.CFG) is identical on both platforms. Thisallows users to move it between platforms with no compatibility issues. Use the sampleserver as a reference guide.

A major goal is that the configuration (.CFG) file created and used by the server can bemoved between the Windows NT and Win16 platforms seamlessly. This requires thatextra work be done in the server to retain this compatibility. This is because thestructures (specifically the "topic" structure variant) that are used to directly read andwrite the configuration file may be packed differently between Win16 and WindowsNT. This is because Windows NT forces structure members to be aligned on theirnatural boundaries (e.g. WORD on word boundary, DWORD on double word boundary,etc.). The approach that should be used is to define an extra intermediate (or scratch)structure for each (port and topic) which is used exclusively for the read/writeoperations. All members of these structures are arrays of type "char" to force bytealignment as on Win16. For example, in the UDSERIAL sample server’sUDCONFIG.C you will find the following structure definition:/** This structure is the one used to read in the config file into* a structure that has members whose alignment/packing will be* identical to the file's. (This is an NT issue). This means* words are on even boundaries, and longwords are on longword* (multiple of 4) boundaries. To make this easiest and most* straightforward, each structure member is of type char, and* will be an array if necessary to match the actual member size* in number of bytes. Then, memcpy’s will be done out of this* structure and into the real one.*/

typedef struct tagTOPIC_file {char tp_next[4];char tp_comPort[2];char tp_name[ 33 ];char tp_topicAddress;char tp_coilReadSize[2];char tp_regReadSize[2];char tp_updateInterval[4];

} TOPIC_CFG_FILE;

Page 309: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting to Windows NT 16-9

Then, immediately after the read or immediately before the write, the data is movedfrom or to this temporary structure into the actual usable structure already in place in thecode.

Note You'll need to do this in xxCONFIG.C and xxCONVERT.C (if any). ThexxCONVERT.C will only exist if the configuration file format has changed during therelease lifetime of the server.

Note The maximum number of serial ports allowed on Windows 16 was previously 4.You have the option of increasing this number to 9 on Windows and to 32 on WindowsNT. This will require a change to the configuration file also. See the sample servers foran example of how to add the additional communications ports to the configuration file.

Note The WW_CP_PARAMS communications port structure can be read and writtendirectly to the configuration file. It is properly aligned for all platforms.

Phase XII - Compile Again (see above)

Phase XIII - Common Dialogs (optional)Goal: Give server standard look and feel. Use sample server for examples.

You may choose to use the new Common Dialog API. This will require substantialchanges. Refer to the "Common Dialogs" section. You may want to postpone thisphase until you are done testing below.

Phase XIV - Final Compile and LinkGoal: Compile and Link server on Windows NT / 2000 or Windows 98 Second Edition.

At this time, all source code modifications which are necessary to build and executeyour server on Windows NT / 2000 should be complete. You should now compile andlink your server and prepare for testing and debugging.

Phase XV - Test the ServerGoal: No bugs.

Test on Intel processor first on Windows NT if possible, then Windows 98 SecondEdition.

Note that on Windows 98 Second Edition , the SuiteLink protocol may not be availableand the server cannot run as a Windows NT service.

Page 310: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

16-10 Chapter 16

Miscellaneous Debugging HintsCheck "union" type structures for any "int" types. Make sure that you did not want a"short". "short" and "int" are the same size (2 bytes) on Windows 16, but not WindowsNT. If a WORD and an "int" are overlaid, you may need to initialize the "int"; you alsomay need to sign extend, etc. If you have an array overlaid with another array, becareful.

When building messages or extracting data from messages, be careful with data pointers.If you use a BYTE pointer to process the data, all is OK! But if you use WORD,DWORD, or structure pointers to process the data, it MUST be aligned. To get it to beso, you'll have to use memcpys to workaround the problems. Test thoroughly! (i.e. allmessage types).

When converting data, casting a WORD to an "int" will work on Win16; but on Win32you need to be careful. If you have 2 bytes of data from the device and the data hasbeen saved in a WORD variable, casting it to an "int" will NOT sign extend (first cast asa "short"). Test thoroughly!

Page 311: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

17-1

C H A P T E R 1 7

Porting an ExistingServer to FS2000

This section describes the software changes necessary to upgrade an existing I/O Server,developed with a previous Wonderware Toolkit, to FS2000.

Contents! Overview! Driver Name! CommonUI Splash Screen and Start-up Message! CommonUI About Box! Value, Time, Quality

Page 312: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

17-2 Chapter 17

OverviewIf you have an existing I/O Server written with a previous version of the WonderwareDDE Server Toolkit, porting your code to Factory Suite 2000 should be fairly easy –particularly if your server has been written as a Win32 program for Windows NT.Most of the changes in the Toolkit involve enhancements that are transparent to theprogrammer. However, you will want to make changes to four basic areas of your code:

- handling the driver name - handling the start-up Splash Screen and Start-up Message - handling the About Box - handling updates to Value/Time/Quality (VTQ)

Page 313: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting an Existing Server to FS2000 17-3

Driver NameThe routine ProtGetDriverName( ) is the routine used by the I/O Server Toolkit toobtain the “short” name of your program. You should insert a call to the functionGetServerNameExtension( ) inside this function:/***********************************************************//** Copy name of driver to string at indicated location **/

BOOLWINAPIProtGetDriverName(LPSTR lpszName, int nMaxLength){ /** WARNING: No calls to debug()... debug() calls ProtGetDriverName(), therefore ProtGetDriverName() cannot call debug(). **/ lstrcpy(lpszName, GetString(STRUSER + 76) /* "UDSAMPLE" */ );#ifdef WIN32 GetServerNameExtension();#endif return (TRUE);} /* ProtGetDriverName */

For I/O Servers, the extension is “_IOServer” and this string gets internally stored in theToolkit. The extension gets appended to the basic name of the server to produce the fullname used in Registry keys, the NT service name (if the server is configured as aservice), etc. For example, the TESTPROT server uses the full name“TESTPROT_IOServer”. This extension was found to be necessary where some I/OServers had the same name as third-party drivers (such as Modbus.exe vs. Modbus.sys),and attempting to configure both as NT services caused name clashes in the Registry andService Control Manager.

Actually, GetServerNameExtension( ) is a function in the Toolkit that obtains a stringfrom WWDLG32A.DLL (the Wonderware Common Dialogs).Not all products that usethe I/O Server Toolkit need an extended name, which is why this call is performedexplicitly. If GetServerNameExtension( ) is never called, the application name andRegistry key would merely be the short name (e.g. “TESTPROT”). This is fine for mostapplications; but it is important to remember that the “Run as NT Service” checkbox inWWDLG32A.DLL assumes the name WITH the extension. If you don't call thefunction GetServerNameExtension( ), you must then provide your own set-up dialog androutines for making the application an NT service.

Page 314: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

17-4 Chapter 17

CommonUI Splash Screen and Start-up MessageWhen an I/O Server starts up, it displays a splash screen – a small window that identifiesthe program that is starting up. Mostly, the purpose of the splash screen for anyprogram is to give the user something to look at while the program starts up – whichmight take several seconds.

Previous versions of the Wonderware I/O Server Toolkit displayed a dialog with theresource name WWStartup, which could be generic or which could be tailored by theprogrammer as needed.This option is still available, but with the advent of FactorySuite2000, the default behavior is to display the Common User Interface splash screen. TheCommonUI routines use one of a set of Wonderware bitmaps for the correspondingproduct type, examine a particular set of resources for the product name and versionnumber, and interrogate the Wonderware License Manager for license features andexpiration dates. The information so obtained is then displayed in the splash screen andin a start-up message. The problem is, this is very Wonderware-centric. If you'redeveloping a Wonderware product, this start-up display has been made quite easy, usinga call to WWAnnounceStartup( ). Otherwise, you might want to display your ownsplash screen, or no splash screen at all.

To tailor the handling of the start-up splash screen, in ProtInit( ) callvoid WINAPI SetSplashScreenParams (BOOL bSuppressSplashScreen,

int nSplashSelect, UINT iProductID,LPSTR lpszPrivateString);

with the appropriate parameters: bSuppressSplashScreen

If TRUE, suppresses the Splash Screen entirely. This may be appropriate if yourprogram displays a splash screen itself elsewhere.If FALSE, the selected splash screen will be displayed for a few seconds and willthen be erased.

nSplashSelectIf 0, displays the original Wonderware splash screen using the dialog resourceWWStartup. This is provided for backward compatibility.If non-zero, displays the Common User Interface splash screen.

iProductID and lpszPrivateStringThese are used as a product selection and special string for the Common UserInterface splash screen.

Page 315: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting an Existing Server to FS2000 17-5

The routine SetSplashScreenParams( ) can be used to select between the CommonUIsplash screen, the “old-style” splash screen, or suppressing the splash screen. Thefollowing code, taken from UDMAIN.C of the sample server, should appear near thestart of the routine ProtInit( ):

[Note: szServerIDstring is defined as a global variable as follows:#ifdef WIN32 char szServerIDstring[100];#endif

]

#ifdef WIN32 /* set up string with server name and version number */ strcpy (szServerIDstring, GetString(STRUSER+142)); /* "Sample I/O Server" */ L = strlen (szServerIDstring); sprintf (&szServerIDstring[L], GetString(STRUSER+145), /* "- Version %s" */ SERVER_VERSION);#endif

#if (defined(USING_WW_COMMONUI) && defined(WIN32)) /* set up to display common start-up message and splash screen */ WWAnnounceStartup(COMMON_IOSERVER32ID, (LPSTR) szServerIDstring);#else /* Log our own startup message and version number */ strcpy (tmpBuf, GetString(STRUSER+144)); /* "Startup" */ L = strlen (tmpBuf); sprintf (&tmpBuf[L], GetString(STRUSER+145), /* "- Version %s" */ SERVER_VERSION); debug (tmpBuf); /* set up to display start-up splash screen with resource name WWStartup */ #ifdef WIN32 /* select WWStartup splash screen instead of Common UI splash screen */ SetSplashScreenParams (FALSE, 0, COMMON_IOSERVER32ID, (LPSTR) szServerIDstring); /* ensure common user interface has instance handle for application */ Common_SetAppInstance (hInst); #endif#endif

Page 316: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

17-6 Chapter 17

CommonUI About BoxAs with the splash screen, the CommonUI routines support the display of a standardWonderware FS2000 About Box, which includes information from a standard set ofresources and from the Wonderware License Manager. Again, this is very Wonderware-centric. You have a choice of several ways you can display an About Box. All three ofthese are illustrated by code in the sample server UDSAMPLE.

Display the CommonUI About BoxYou will have to provide resource version information and a resource icon namedABOUTICON. Normally, this would be the same as the main icon for your I/O Server. Common_SetAppInstance(hInst);Common_ShowAboutBox (COMMON_IOSERVER32ID, szServerIDstring);

Display the Wonderware Common Dialog About BoxThis can be somewhat tailored by putting information into the comment string. WW_AB_INFO AboutBoxInfo;HICON hIcon;

memset (&AboutBoxInfo, 0, sizeof(AboutBoxInfo));hIcon = LoadIcon(hInst, "Udprot");

AboutBoxInfo.hwndOwner = hWnd;AboutBoxInfo.szDriverName = GetAppName();AboutBoxInfo.szId = GetString(STRUSER + 142); /* "Sample I/O Server" */AboutBoxInfo.szVersion = GetString(STRUSER + 0);AboutBoxInfo.szCopyright = GetString(STRUSER + 143); /* "1997" */AboutBoxInfo.hIcon = hIcon;AboutBoxInfo.szComment = GetString(STRUSER + 149); /* "This is a sample server" */

WWDisplayAboutBox((LPWW_AB_INFO) &AboutBoxInfo);DestroyIcon (hIcon);

Display an About Box of your own design.You will have to provide a routine UdPrivateAbout( ) to handle the dialog.

FARPROC lpprocAbout;

lpprocAbout = MakeProcInstance((FARPROC) UdPrivateAbout, hInst);DialogBox(hInst, GetString(STRUSER + 75) /* "ABOUT_BOX" */ , hWnd, lpprocAbout);#ifndef WIN32 FreeProcInstance(lpprocAbout);#endif

Page 317: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Porting an Existing Server to FS2000 17-7

Value, Time, QualityOne of the main functional differences between the FactorySuite 2000 I/O ServerToolkit and previous versions of the Toolkit is the addition of Time and Quality stampsto the data. The I/O Server can now pass to the client information about when a pointwas last updated and whether the data is completely trustworthy or has some problemsassociated with it.

To support the transfer of Value/Time/Quality (VTQ) information, the call toDbNewValueFromDevice( ) has been replaced with several other calls:

DbNewVTQFromDevice( ) updates value, time, and qualityDbNewTQFromDevice( ) updates time and quality only (value unchanged)DbNewQFromDevice( ) updates quality only (a current default time mark is used)

The function DbNewValueFromDevice( ) is still available, but what happens internallyis that it makes a call to DbNewVTQFromDevice( ) using default values for time andquality. Quality is assumed good (WWQ_GOOD). The Toolkit provides a default timemark only if one is needed. You can either choose to leave intact all your calls toDbNewValueFromDevice( ), or you can add code to explicitly get a time mark and passit to the Toolkit via one of the other functions.

Most PLCs do not have a date/time clock that is accessible to the I/O Server. For thosewhich do, you have the option of using that date/time clock as your time mark. In thiscase, you should convert the time from the PLC’s format to a FILETIME value (see thechapter on Time Marks). Otherwise, you should use the Toolkit API functionDbGetGMTasFiletime( ) to read the computer’s time.

If you are explicitly obtaining the time via a call to DbGetGMTasFiletime( ), you shouldtake into account what these calls will do to server performance. If you're updating10,000 points per second, their time marks aren't going to be very different from oneanother; so you probably don't need 10,000 calls to DbGetGMTasFiletime( ). Youshould limit calls to this function in a way that maximizes performance whilemaintaining a reasonable update rate for the time mark. Reasonable places to get thetime mark include the following:

- Once per entry to ProtTimerEvent( ), and then only if you need it - Once per response message (which would normally encode data for many points)

See the chapter on Time Marks for more information on optimizing how often you callDbGetGMTasFiletime( ).

Page 318: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

17-8 Chapter 17

There are four places where you should update the quality flags for a point:

1. In UdprotPrepareWriteMsg( ) if there is any problem with poked data. When aclient “pokes” a value to the server, ProtNewValueForDevice( ) passes the value tothe server-specific code. This, in turn, calls a routine such asUdprotPrepareWriteMsg( ), which creates the byte sequence that will be sent to thedevice. If a string is too long, or a value is out of range, the server-specific codeshould force the value to a legal setting, set a quality of WW_SQ_CLAMPLO orWW_SQ_CLAMPHI, and report the information back to the Toolkit withDbNewVQFromDevice( ). Also, if the point is inaccessible or read-only, it may beappropriate to set the quality to WW_SQ_NOACCESS and callDbNewVQFromDevice( ).

2. In UdprotExtractDbItem( ) when the response from a device is interpreted as pointdata and reported to the Toolkit via DbNewVTQFromDevice( ). When a responsecarries valid data for the point, the quality should normally be set toWW_SQ_GOOD. However, if a string is too long, or a value is out of range, or adata conversion yields an invalid result, the quality should be set toWW_SQ_CLAMPLO, WW_SQ_CLAMPHI, or WW_SQ_NOCONVERT as isappropriate. Also, some PLCs return status information along with the data. Thisstatus information should be mapped to the corresponding WW_SQ_XX qualitysetting.

3. In ProcessValidResponse( ) and other locations where an error response is received,a bad quality should be reported for each point on a message that has a responsepending. If a polling (read) message elicits an error response, a quality ofWW_SQ_NOACCESS should be reported for each point that is being activelypolled by that message.

4. In UdprotSetTopicStatus( ) when the communication with the PLC fails, bad qualityof WW_SQ_NOCOMM should be flagged on all points on all messages for thattopic. This would be at the point where the server goes into slow poll mode,attempting to re-establish communications with the PLC.

See the chapter on Quality Flags for more information and specific examples of settingthe quality flags.

Page 319: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-1

C H A P T E R 1 8

I/O Server Code Samples

Example source code for an I/O Server is included on the installation media. It willautomatically be copied to your hard disk when you install the Toolkit. The sample codeillustrates the concepts of the Toolkit, demonstrates basic problems that must be addressedfor all I/O Servers (e.g., dialog boxes, file I/O for configuration), and gives you a startingpoint for developing code from scratch. The code includes a simple simulated PLC, so youcan run the executable and see these concepts in action. Also, the sample server can be builtin two ways – as a serial server and as a board server – to illustrate the similarities anddifferences between these two types of interfaces.

Contents! Overview! UDSAMPLE Architectural Overview! Adapting the UDSAMPLE Server! Modifying the User Interface – UDSAMPLE.RC and UDCONFIG.C! Storing and Retrieving Configuration Files! Setting Up Data Points – UDCONFIG.C! Executing the Configuration – UDLDCFG.C! Executing the Protocol – UDPROTCL.C! Data Structures! Compiling the Sample Code! Debug and Support Functions! Simulated PLC

Page 320: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-2 Chapter 18

OverviewWonderware Corporation has developed all of its I/O Servers using this Toolkit. The samplecode included in the Toolkit is the basis for many of the production I/O Servers. We highlyrecommend experimenting with the sample server to learn more about the Toolkit's libraryfunctions. These sample programs will be in the following sub-directories:

\WW\IOSERVER\UDSAMPLE The sample code contained in this directory is a skeletonfor a complete I/O Server. To build it as a functional EXE, you must copy three files fromone of the subdirectories: either UDSERIAL or UDBOARD.

\WW\ IOSERVER\UDSAMPLE\UDBOARD This subdirectory contains three files:UDSAMPLE..C, UDSAMPLE.H, and UDSAMPLE.ICO. To build the sample server as aboard server, type the following:

CD \WW\IOSERVER\UDSAMPLE\UDBOARDCOPY UDSAMPLE.* ..\COMMON

to copy the three files to the UDSAMPLE\COMMON directory with the appropriate names.This example illustrates communicating to a PLC via a memory-mapped interface deviceplug-in board (adapter card). The server program can directly access areas of memory thatare mapped to a device I/O board's specific protocol.

\WW\ IOSERVER\UDSAMPLE\UDSERIAL This subdirectory contains three files:UDSAMPLE..C, UDSAMPLE.H, and UDSAMPLE.ICO. To build the sample server as aserial server, type the following:

CD \WW\IOSERVER\UDSAMPLE\UDSERIALCOPY UDSAMPLE.* ..\COMMON

to copy the three files to the UDSAMPLE \COMMON directory with the appropriate names.The example illustrates communicating to a PLC via a serial interface (COM port).

The UDSAMPLE example server has symbol processing functions to handle many thousandsof active data points. It shows you how to set up lists of polling messages, how to optimizepolling messages, and much more. This example code is the basis for many of theWonderware I/O Servers. UDSAMPLE contains everything that you need to write an actualI/O Server. It includes the user interface code, dialog boxes and the code necessary tointeract with them, configuration file management, and the necessary data structures. It canbe compiled for Win32 programming models. It contains functions to assist in debugging. Italso contains device and protocol-specific code for a simple, simulated PLC, to illustrate howto construct polling messages and how to interpret the reply messages. This code and thecomments should provide an excellent starting point for the development of a server for yourspecific needs.

Page 321: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-3

UDSAMPLE Architectural OverviewThere are essentially three parts of UDSAMPLE: one part establishes the configuration ofthe I/O Server, a second part collects and validates information requests, and the third partactually does the communication.

UDSAMPLE establishes its configuration settings via dialogs with the user. This is used toset up the I/O channels (COM ports or boards) and the available topics. The configurationsettings are stored in a file which gets loaded from the disk when the server is started up.

The I/O Server receives its information via DDE or SuiteLink requests. The Toolkit callsfunctions in UDSAMPLE to set up and validate the topics and item names requested. Oncethe topic and item names have been validated, messages are created to read information fromthe PLC. UDSAMPLE is based on a master/slave communication model, where the serversends a message to the device and receives a response back.

The I/O Server builds two kinds of messages: Read Messages for all the active points andWrite Messages for writing data back to the PLC.

Read Messages are built from the information in the symbol table and stay around. One readmessage may read data for several points. Read messages repeatedly get sent to the PLC foras long as the points are active. If points go inactive, the corresponding read messages maybe modified or deleted, depending on what points remain active.

Write Messages are built on demand (when a DDE POKE or SuiteLink WRITE is received)and placed on the top of the message queue so they are sent on the next execution of theprotocol. Generally one write message is generated for every point that is written, although itmay be possible to optimize writes and send values for several points in a single message.Write messages are deleted after they have been successfully received and processed by thePLC.

The heart of the driver is in the UdprotDoProtocol( ) function. This function executes theprotocol. It examines the state of the server and executes the appropriate action. (Forexample, if the I/O Server is in the idle state, it sends the next message to the device. If it isin the awaiting response state, it looks for information from the device and processes thatinformation.) The server contains necessary logic to handle error conditions.

Page 322: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-4 Chapter 18

Adapting the UDSAMPLE ServerThere are several things that should be determined before you start coding a server:

I/O Channel: Does the server communicate over a serial port, a plug-in board (adaptercard), an Ethernet connection? What configuration information is necessary to identifywhich particular I/O channel is being used? What settings need to be specified, e.g.transmission rates, parity, data encoding, etc.?

Protocol Structure: If the protocol supports multiple message types, decide whichmessages you will need to run the protocol. This should determine if there is any additionalinformation required at configuration time.

Topic Description: The topic configuration generally contains all of the information neededto address a particular device. It contains a topic name, PLC address, update interval, andany other information generally required to build and send a message (except for theparticular point to address).

Item Naming Convention: Item names should match the convention used in the PLC andprovide you with enough information to determine the data type, address and possiblyprecision of the point. You should decide which points you are going to support. Thesample contains one built-in item name: STATUS. This item name is a discrete variable thatis TRUE when communication to the device is active and FALSE when communication isinactive.

Page 323: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-5

Customizing the Start-Up Splash Screen and AboutBoxWhen an I/O Server starts up, it normally displays a Splash Screen for a few seconds. This isa window that identifies the I/O Server and the Toolkit, and any other information that seemsappropriate. When the I/O Server is running and its window is visible, the user can selectHelp|About to display the About Box, an informational window that identifies the product,version number, company, etc.

UDSAMPLE has two macros that function as compile-time flags that can be used to selectwhat kind of Splash Screen and About Box to use:

#define USING_WW_COMMONUI

This selects the Wonderware FactorySuite 2000 Splash Screen and About Box, whichare normally displayed by a Wonderware FS2000 production I/O Server. Informationfor the program ID and version are provided in the version marker code section of the*.RC file. If this macro is not defined, UDSAMPLE will display a Splash Screendefined by the dialog resource named WWStartup. You can then use the dialog definedin TKITSTRT.RCI or define your own Splash Screen. You can also suppress thedisplay of the splash screen entirely [see the section on the functionSetSplashScreenParams( )].

#define USING_WW_ABOUT

This selects the Wonderware Common Dialog About Box (but only if the macroUSING_WW_COMMONUI is not defined). See the section on the WonderwareCommon Dialogs for more information on customizing the information displayed. If thismacro is not defined, the About Box defined by the dialog resource ABOUT_BOX isdisplayed. You can customize this resource as needed.

UDSAMPLE also has a macro named USING_WW_LICENSE. If this macro is defined, theserver calls the function GetIOServerLicense( ) to check whether the server has a license torun. This call requires a special version of the Wonderware Toolkit that provides access tothe Wonderware License Manager. Contact Wonderware for further information.

Modifying the User Interface – UDSAMPLE.RC andUDCONFIG.C

The dialog boxes for generic Topic and Board configurations are contained inUDSAMPLE.RC. The corresponding dialog handlers are functions contained inUDCONFIG.C. These can be modified as needed for your protocol. (For example, you mayneed to differentiate PLC devices.) It is also a good idea to change the name UDSAMPLE toreflect the name of your PLC.

For configuring the serial ports (COM ports), the sample server uses the WonderwareCommon Dialogs. See the chapter on the common dialogs for more information on using theoptional edit fields, check boxes, and radio buttons.

Page 324: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-6 Chapter 18

Storing and Retrieving Configuration FilesOnce configuration information has been entered via the user interface, it needs to be storedfor retrieval next time the server is started up. The sample server handles this by storing theI/O channel configurations and Topic configurations in a disk file named UDSAMPLE.CFG.Two basic techniques are illustrated:

Configuration using binary structures – UDCFGBIN.C:The data structures for COM ports, boards, and topics are simply written to a disk file assequences of bytes, and are read back the same way. While this provides the simplesttechnique for configuration storage and retrieval, there are some shortcomings:

- If the structures are changed in any way, the format of the data file also changes. Forbackward compatibility, it is necessary to provide extra code to read old formats andconvert to the new data structures.

- On different platforms, alignment issues may actually insert extra bytes betweenstructure members. Care must be taken to ensure compatibility when moving betweenWin16 and Win32 systems.

- There is usually no verification that the configuration is valid, although verification canbe added.

- Configuration must be done using the user interface with a running I/O Server. Theconfiguration file can only be written or read by the I/O Server, and does not easily lenditself to independent verification or to being printed out.

Configuration using ASCII text – UDCFGTXT.C:The data structures for COM ports, boards, and topics are written to a disk file asconfiguration “commands” with named parameters. When the file is read in by the I/OServer, the server interprets the commands and parameters. Commands can be in any order(e.g. COM ports then topics, topics then COM ports, or mixed). Within a command,parameters can be in any order. Any missing parameters are given default values; anyobsolete parameters are merely ignored. A command can span several lines of text, and endswith a semicolon (‘;’). This technique requires a little more code, but confers severalimportant advantages:

- If the structures are changed, no version tracking is necessary, and backwardcompatibility is automatic. (This can be even better than C++ serialization!)

- The configuration file is platform-independent. There are no alignment issues.

- As each command and each parameter is processed, the validity of the configuration canbe verified.

- Configuration can be done without a server running, and on a completely separatemachine. Configuration files can be verified and printed.

UDSAMPLE can read its own configuration files in either binary or ASCII text. By default,it stores configuration files in binary. To store configurations as text, in the [UDSAMPLE]section of WIN.INI, simply include the following line:

WriteConfigInASCII=1This setting is read in when the server starts up, in the routine ProtInit( ).

Page 325: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-7

Setting Up Data Points – UDCONFIG.CFirst, determine the item/point naming convention. The item/point name should containenough information for the user to know its data type and address. For example, the itemname V23 indicates that this is an integer register in V-memory at address 23.

Function ValidatePoint( )The function ValidatePoint( ) needs to be written to parse and validate the item names foryour specific device. It is passed a text string of the item name, and the function must decodethis into information that is eventually placed in the symbol table. This information will beused later to build the messages. The amount of information that needs to be stored into thesymbol table depends on what information you need to build the message and extract the databack out. This structure may be modified to meet your needs. UDSAMPLE uses atemporary data structure LPPPS to store information about the item until it has been fullyvalidated. The symbol table entry is built following a return from ValidatePoint( ).

Example of ValidatePoint: Valid Item Names are Vxxx/* ValidatePoint() checks to see that a point name conforms to the convention: Vxxx The main purpose of the function is to fill in the LPPPS structure.*/BOOLWINAPIValidatePoint( LPSTR lpszPointName, LPPPS ppp)/* use the LPPPS structure to temporarily store the decoded information. UdprotAddSymbol will stuff this information into the symbol table entry when we are done. */{ PSTR pszReference; WORD Reference = 0; PTTYPE ExplicitType = NULL; BOOL PointOK = TRUE; char tc; BOOL input; BOOL Regs; if (bVerbose){ debug( "ValidatePoint: %Fs" , lpszPointName ); } ppp->ppsType = 0; ppp->ppsNumReg = 0; /* element size */ ppp->ppsSeg = 0; /* seg is a field added to the symbol table */ /* to identify the segment */ ppp->ppsAlias = 0;

Page 326: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-8 Chapter 18

lstrcpy( tmpBuf, lpszPointName ); strupr( tmpBuf ); pszReference = tmpBuf; switch( *pszReference ) { case 'V': ppp->ppsType = PTT_INTEGER; /* check register specification */ pszReference++; if( !NumericsOnly( pszReference ) ) { PointOK = FALSE; break; } Reference = atoi( pszReference ); /* range check the register address if appropriate */ if( !ValidRegisterAddress( (DWORD)Reference, Regs )){ PointOK = FALSE; break; } ppp->ppsAlias = Reference - 1; /* zero based addressing */ ppp->ppsSeg = REGISTER; break; default: PointOK = FALSE; break; } if (bVerbose) { if( PointOK ) { debug( "Valid Point: %Fs" , lpszPointName ); debug( " ppsAlias=%05u ppsSeg=%u" , ppp->ppsAlias, ppp->ppsSeg ); debug( " ppsType=%04u", ppp->ppsType ); debug( " ppsNumReg=%d ", ppp->ppsNumReg); } else { debug("Item rejected: %Fs" , lpszPointName ); } } return PointOK;} /* ValidatePoint */

staticBOOLWINAPINumericsOnly( PSTR pstr ) { if( !*pstr ) return FALSE; while( *pstr ) { if( !isdigit( *pstr++ ) ) { return FALSE; } } return TRUE;} /* NumericsOnly */

Note The above code does not match the code on the installation media, however, this codeis more useful for this example.

Page 327: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-9

Executing the Configuration – UDLDCFG.CThis section describes the functions that build the message queues. They are found inUDLDCFG.C.

LogicalAddrCmp( )The function LogicalAddrCmp( ) is the function used to sort symbol table entries. Fieldsfrom the symbol table entry, such as data type and address, are compared in this function todetermine the sort order of the symbol table. It may be necessary to add additional fields tothe comparison criteria to ensure that symbols are sorted properly. For example, the servermight support bits in registers and the bit identifier would need to be added to the sortcriteria. If the symbols are not in the correct order, the data will not be extracted properly.

Building MessagesThe message data structure contains information about which symbols are referenced in themessage and the actual message itself. UdprotAddPoll( ) contains the logic to build the readmessage, and UdprotPrepareWriteMsg( ) builds the write message. The actual message thatis sent to the device is built by either BldRead( ) or BldWrite( ).

UdprotAddPoll( )UdprotAddPoll( ) builds a read message to be placed in the message queue. Existing readmessages are examined to see if the point can be read from an existing message. If it can fitinto an existing message, the information in the LPMSG structure is updated. Otherwise, anew message is built and added to the message queue. BldRead( ) builds the actual sequenceof bytes that is sent to the PLC.

UdprotPrepareWriteMsg( )This function builds the write message. Existing write messages are examined to see if thepoint can be combined into a message that is already waiting to be sent. If it can fit into anexisting message, the information in the LPMSG structure is updated. Otherwise, a newmessage is built and added to the message queue. BldWrite( ) builds the actual sequence ofbytes that is sent to the PLC.

Building Messages – UDBLDMSG.CBldRead( ), BldWrite( ), BldCks( ): These functions need to be supplied as they are totallydevice-dependent. Write the code to build the correct message according to your protocol.This message is typically a character buffer that is passed to the I/O driver via the functionWritePortMsg( ). The message is part of the UDMSG data structure. Usually, a serial serveruses WriteComm( ) to pass the buffer to the Windows COM driver; while a board serveruses a function tailored to the particular board interface.

Page 328: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-10 Chapter 18

Executing the Protocol – UDPROTCL.CThis section describes the functions that actually do the communication. The functions arefound in UDPROTCL.C.

UdprotDoProtocol( )This is the function called for every ProtTimerEvent. It contains the case statement thatdetermines what happens at a given state. In UDSAMPLE, it is assumed that there are alimited number of states, namely IDLE, WAITRESP, and error conditions. If your devicehas more states than these, add these states and whatever action needs to be taken.

UdprotGetResponse( )This function may need to be modified to determine if you have enough of the message tocontinue processing.

ProcessValidResponse( )This function validates the response back from the device. (The response is in the lpPortdata structure, field mbRspBuffer.) It may validate the checksum, look for a particular fieldin the message, or do anything required to ensure that the entire response has been receivedcorrectly.

UdprotExtractReadData( ), UdprotExtractDbItem( )These functions extract information from the response based on information in the messagestructure and the symbol table. Modify these to suit your protocol.

UdprotHandleRspError( )This function handles problems with the communication protocol: incomplete responses,error responses, timeouts, etc.

Page 329: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-11

Data StructuresThere are several built-in data structures that the server needs to build messages, send them,and extract the responses. These data structures may be modified to suit your needs.

PORT Data StructureThis data structure contains the information necessary to control the port in processing theprotocol. It contains a handle to a linked list of nodes, as well as handles to the currentlyactive node and message. It also contains the mbRspBuffer field which is the data comingback from the PLC.

UDMSG Data Structure (Message)This is the message data structure. It contains the actual message to be sent to the device, apointer to the topic, and indices into the symbol table for the first symbol contained in themessage and the last symbol contained in the message. This information allows theinformation to be plucked out of the response.

STAT Data Structure (i.e. Station, Node, or Topic)This structure contains all of the topic information. It has a handle to the associated symboltable and a list of messages sent to a particular node.

SYMENT Data Structure (Symbol Table)This data structure contains a one-to-one correspondence with the items that are beingrequested (i.e. there should be one symbol table entry for every item requested). The symboltable should be sorted according to data type and address (at the very least). If the item is abit address, the bit offset is often stored and sorted as well.

Note For Win16, the symbol table is an array of memory type HUGE, and consequentlyneeds to be allocated with data structure sizes that are a power of 2. In Win32, HUGE doesnot exist, so the symbol table is a normal allocation.

Page 330: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-12 Chapter 18

Compiling the Sample CodeNote The I/O Server Toolkit for FactorySuite 2000 has been built with Microsoft VisualC++ version 6.0. Consequently, you must use version 6.0 sp3 or later to create Win32 I/OServers using this Toolkit. After following the instructions below, you will be able to build,execute, and debug the sample server from the IDE.

Setting up a project for the sample code with Microsoft Visual C++ 6.0:

Create the new project:- Click on File|New and select the “Projects” tab.- Select Win32 Application- For the project name, enter UDSAMPLE- For the location, enter the path to the files, e.g.,

C:\WW\IOSERVER\COMMON\UDSAMPLE- Click on Create New Workspace- Click on OK

Copy the specific files for the desired server type to the UDSAMPLE directory• For a board server, copy the files UDSAMPLE.C, UDSAMPLE.H and UDSAMPLE.ICO

from the UDBOARD directory to the C:\WW\IOSERVER\UDSAMPLE\COMMONdirectory.

• For a serial server, copy the files UDSAMPLE.C, UDSAMPLE.H and UDSAMPLE.ICOfrom the UDSERIAL directory to the C:\WW\IOSERVER\UDSAMPLE\COMMONdirectory.

Set up the files for the project - Click on Project|Add-to-Project|Files

- In the dialog, select the directory where the files are located - Hold down the control key while clicking to select multiple files - Add all the *.C files and the *.RC file - Click on OK - Click on Project|Add-to-Project|Files again - In the dialog, select the directory where TOOLKIT7.LIB is located - Click on TOOLKIT7.LIB - Click on OK

Set up the appropriate compiler and linker options - Click on Project|Settings - Select the “C/C++” tab - For “Category,” select “Code Generation” - For “Use run-time library,” select “Multithreaded DLL” - Select the “Link” tab - For “Category,” select “Input” - Under “Ignore Libraries,” enter LIBC - Click on OK

Note The MSVC library OLEAUT32.LIB must also be linked to your project, eitherexplicitly or as one of the “Object/Library modules” on the “Link” tab.

Set up the appropriate directories- Click on Tools|Options- Select the “Directories” tab- For “Show directories for” select “Include files”- Add the path to the Toolkit include files, e.g., C:\WW\IOSERVERTOOLKIT\INC. Move this path to the top of the list of directories using "Move Item Up."- Also add the path to C;\Program Files\DevStudio\VC\include\sys. Click on OK

Page 331: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-13

Debug and Support FunctionsIf you include DebugMenu=1 in the [UDSAMPLE] section of the Windows WIN.INI filethere will be several menu items that appear in the server system menu.

!!!! Dump prints the current port, topic, message, and symbol table structures to theWonderware Logger.

! ShowSend prints the messages sent to the PLC to the Wonderware Logger.! ShowReceive prints the messages received from the PLC to the Wonderware Logger.! ShowErrors prints enhanced error message information in the Wonderware Logger.! Verbose prints program execution trace information in the Wonderware Logger.! ShowEvents is primarily for tracing COM port activity for a serial server when an error

occurs. Events such as transmit buffer empty are printed in the Wonderware Logger.

Two other menu items are specific to the simulated PLC in UDSAMPLE:

! Simulator Read Paused stops the simulated PLC from responding to read messages.This can be used to explore what happens when communication with the PLC fails.

! Simulator Write Paused stops the simulated PLC from responding to write messages.This can be used to explore what happens when the server has a chance to accumulateseveral write operations before the PLC is ready to process them.

If you are working with the Integrated Development Environment for a compiler, such asMicrosoft Visual C++ 6.0 sp3 or later, you can use breakpoints, watch windows, and other tools.Note that if you do use a breakpoint to interrupt the normal operation of the program,remember that some activities – such as PLC “keep alive” handshaking – may time out.

For debugging, feel free to make liberal use of debug( ) statements sent to the WonderwareLogger. Hardware error and serious communications problems should always be sent to theWonderware Logger for operator use. Debug( ) statements to the Wonderware Loggershould be under menu control as Wonderware recommends that Wonderware Logger berunning at all times.

For more detailed information on debugging refer to the “Debugging and Testing” chapter.

Page 332: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-14 Chapter 18

Simulated PLCThe sample I/O Server UDSAMPLE contains a simulator for a simple PLC. This simulatoris not intended to reflect the operation of any actual PLC; but it does provide a way toillustrate the complete operation of the sample server. Points can be advised, requested, andpoked just as if the server were connected to a real device. The simulator can be paused toexplore what happens when communication gets lost, and resumed to explore how the serverrecovers when communication is restored.

The serial server UDSERIAL and board server UDBOARD talk to the same simulated PLC.The only difference is the communication protocol. The serial server uses hex ASCII stringsto send and receive messages, e.g.

:81000301002B4F;

with the start of the message marked with a colon (‘:’) and the end marked with a semicolon(‘;’). By contrast, the board server uses straight binary to send and receive messages, e.g.

81 00 03 01 00 2B 4F

Otherwise, the points available and the protocols are the same.

For the serial server, one simulated PLC is implemented for each of the COM ports 1..4. Forthe board server, one simulated PLC is implemented for each of the board segments 0xD000,0xD400, 0xD800, 0xDC00.

The simulation has two PLC memory segments:

NAME ADDRESS RANGE DESCRIPTION FUNCTION V 1..512 variable memory holds value steady C 1..512 counter memory increments each time read

Addressing wraps around, so V814 = V((814-1) mod 512)+1 = V302

C-memory counters are always accessed as 16-bit integers.

However, points in V-memory can be accessed in additional ways:V<number> 16-bit integer Example: V3V<number>B 16-bit BCD integer Example: V3BV<number>S 16-bit signed integer Example: V3SV<number>D 32-bit DWORD Example: V3D (V3 and V4)V<number>R 32-bit float (real number) Example: V3R (V3 and V4)V<number>:<number> Bit of word (read only) Example: V3:12 (V3 bit 12)V<number>-<number> String, blank-terminated Example: V1-5V<number>-<number>B String, blank-terminated Example: V1-5BV<number>-<number>C String, C-style Example: V1-5CV<number>-<number>P String, Pascal-style Example: V1-5P

(length byte first)

The PLC simulator in UDSAMPLE provides a way to illustrate various aspects of I/O Serverdesign with actual, running code. Topics can be configured, modified, and deleted. I/Ochannels (COM ports or boards) can be configured and modified. Messages for reading andwriting PLC point values are created, “sent,” “received,” and interpreted just as if there werea real device at the end of some kind of communication cable. In some cases, those messagesare “optimized” to improve performance.

Page 333: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

I/O Server Code Samples 18-15

The use of the simulated PLC can be enabled or disabled at compile time, according towhether the macro

#define SIMULATING

is defined or not in the module UDSAMPLE.C.This approach makes it possible to include a complete or partial simulator in the source code for a server and mask it out when the server is built for use with real I/O. As a failsafe, the firsttime the simulator is accessed, it puts the message

Simulated I/O – for test purposes only!

into the Wonderware Logger. This helps ensure that, if you forget to mask out thesimulator, the log indicates that simulated I/O is being used.

While it may not be practical to include a complete or even partial simulator for an actualPLC in your server, this technique can often be a significant aid in debugging – especially ifan actual PLC is unavailable for certain tests. See the chapter on debugging for additionalideas on testing and debugging your server.

Page 334: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

18-16 Chapter 18

Page 335: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

19-1

C H A P T E R 1 9

Debugging and Testing

This section presents a basic development and testing methodology that will assist youin completing the I/O Server quickly and efficiently.

Contents! Basic Programming Rules for Windows and Windows NT! General Debugging Topics! Windows and Windows NT Debugging Tools! Testing

Page 336: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

19-2 Chapter 19

Basic Programming Rules for Windowsand Windows NT

The Toolkit uses C-language include files that use the WINAPI parameter passingoption. We recommend following Microsoft guidelines for writing compatible code.The samples included have been written to compile Win32 models.

General Debugging Topics

Debug MessagesLiberal use of debug( ) message calls can greatly enhance your debugging arsenal.These message calls are most useful at decision points to record data and flow throughthe logic. The UDSAMPLE code described in the previous section illustrates howdebug( ) calls can be used to describe the device status returns. Until you becomefamiliar with the use of the Toolkit, we recommend that you put a debug( ) call at theentry and exit of every new routine.The following are a few suggestions for debug( )usage:

1. Remember, always use far pointers to strings and be careful to keep the byte size ofthe parameters equal to the format statement elements.

Example:

debug( "UdprotFreeMsg( %04X )", (unsigned) hmsg );debug( "UdprotFreeSymEnt( %Fp, %Fp, %d )", lpnode, lpSymTab, (int) indx );debug( "UdprotUnchainSymEnt( %Fp, %Fp, %ld )", lpnode, lpSymTab, (long) lnum );

2. The debug( ) calls can take a lot of machine time to execute, especially if they arebeing logged to disk (check the display options in Wonderware Logger). Allowfor this at first by selecting long timeouts, slow polling rates, and short messages.

When the server is completed, it is handy to leave a few protocol debug( ) calls in thecode. By using either a menu selection, a WIN.INI variable, or a Registry setting, youcan enable or disable these remaining debug( ) calls by putting the appropriate (if)statements around them. This finer level of information gathering is useful when aninstallation is first started up. When there is enough detail in the debug messages, theywill assist in isolating hardware problems, configuration errors, user problems, and thelingering "one last bug" in the software.

Page 337: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Debugging and Testing 19-3

DDE Message Traffic Monitoring Using WIN.INIThe Toolkit will handle the entire DDE protocol for the server, but in rare cases youmay need to examine the DDE message traffic in detail. The Toolkit can be switchedinto debug mode by using WIN.INI variables. The Toolkit routines will access theWIN.INI file for a server by the name selected for the application name in theProtGetDriverName( ) function.The following two WIN.INI variables can be set to 1to force the Toolkit to send DDE debugging messages to the Wonderware Logger:

[SERVERNAME]DebugDDEMessages=1PreventBlockedDDE=1

Below is a sample from the Wonderware Logger with the DebugDDEMessages debugvariable set. A simple sequence of INITIATE, REQUEST, POKE, ADVISE,UNADVISE, then TERMINATE was done from DDEAPP.EXE:90/07/24 21:48:08.301/UDSIMPLE/rcvd WM_DDE_REQUEST 4848 24E8 0001 C37D [T1]90/07/24 21:48:09.851/UDSIMPLE/sent WM_DDE_DATA 24E8 4848 154E C37D [T1]90/07/24 21:48:21.099/UDSIMPLE/rcvd WM_DDE_POKE 4848 24E8 154E C37D [T1]90/07/24 21:48:21.264/UDSIMPLE/sent WM_DDE_ACK 24E8 4848 8000 C37D [T1]90/07/24 21:48:27.646/UDSIMPLE/rcvd WM_DDE_ADVISE 4848 24E8 15FE C37D [T1]90/07/24 21:48:27.756/UDSIMPLE/sent WM_DDE_ACK 24E8 4848 8000 C37D [T1]90/07/24 21:48:27.921/UDSIMPLE/sent WM_DDE_DATA 24E8 4848 1026 C37D [T1]90/07/24 21:48:31.821/UDSIMPLE/sent WM_DDE_DATA 24E8 4848 15FE C37D [T1]90/07/24 21:48:36.874/UDSIMPLE/sent WM_DDE_DATA 24E8 4848 1636 C37D [T1]90/07/24 21:48:38.466/UDSIMPLE/rcvd WM_DDE_UNADVISE 4848 24E8 0000 C37D [T1]90/07/24 21:48:38.631/UDSIMPLE/sent WM_DDE_ACK 24E8 4848 8000 C37D [T1]90/07/24 21:48:43.289/UDSIMPLE/sent WM_DDE_TERMINATE 24E8 4848 0000 0000 []

When using WindowViewer as the client to debug the DDE traffic, set the flagPreventBlockedDDE to 1 to keep the server in the standard (slower) DDE mode.WindowViewer will normally use its own extra message blocking protocol to speed upthe DDE transfers of large numbers of data points greatly.

Note: Remember to either set these both back to 0 or delete them from the WIN.INI filewhen the server application is complete. With either one of these variables set,performance will be severely degraded.

DDE Message Traffic Monitoring Using DDESpyA Microsoft utility called DDESpy displays all the DDE messages on your computerand tags each message with a window handle that will distinguish the messages frommultiple clients. An example of the level of detail that’s displayed with each message isthe DDE data message, where the output includes the source window handle, the data,the data format and the item name.

You can get DDESpy from the Professional version of Microsoft's Visual C++ or fromCompuServe (enter GO WINSDK, file is DDESPY.ZIP). If you run DDESpy and get aGPF or the output suddenly stops updating, you may not have the latest version ofDDESpy. Make sure you get the most recent version of DDESpy from CompuServe.

Page 338: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

19-4 Chapter 19

Assertion ErrorsUnder certain illogical or fatal conditions, an Assertion Error message box will bedisplayed showing a program line number, as shown in the example below:

An application can create these errors by calling ASSERT( boolean expression ). If theboolean expression evaluates to FALSE, the message box will come up. You can usethese calls at points in your code that should never happen or to indicate an illogicalsituation.

Note: Use ASSERT_ERROR rather than using ASSERT (FALSE).

When an assertion error comes from the Toolkit library function, write down theconditions that lead up to the error and the information in the message box. You canrespond Yes to the message box and, depending on the severity of the error condition,the application may continue with no ill effects, get another assertion error, abort theapplication and produce a DrWatson listing, or hang the system. Therefore, continue atyour own risk. If you respond No to the message box, the Toolkit will produce aDrWatson listing which can be valuable in tracking the problem. Refer to the MicrosoftProfessional Tools User's Guides for detailed information.

Another useful technique in tracking assertion errors that may come from the Toolkit isto set a breakpoint at AssertLog. Then re-create the error and look at the CALL trace todetermine which routine in the server was called. Sometimes there are errors in thecalling routines parameters that are invalid and these errors do not get trapped as invaliduntil they are several layers deep within the Toolkit.

Caution Note Assertion errors should be used sparingly since they will disable theoperation of your server. They should not be used to indicate communication errors,nuisance errors, etc. Use the debug( ) function call to log these types of errors. As ageneral rule, if the server can recover gracefully from an error, do not use an assert call.

Prior to contacting Technical Support, try to recreate the error and make note of the filespecification listed in the assertion message box. In many cases, the assert informationwill be copied to the Wonderware Logger, resulting in an entry similar to the onebelow:90/10/22 16:13:25.542/UDSAMPLE/Assertion Error: "FileC:\WW\IOSERVER\UDSAMPLE\udmain.c Line 620"

Page 339: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Debugging and Testing 19-5

Windows and Windows NT Debugging Tools

Microsoft Visual C/C++ DebuggerMicrosoft Visual C++ provides an integrated debugger to debug programs. If usingVisual C++ as the development environment, choose this full-featured debugger as thedebugging tool. It is strongly recommended that when you install Microsoft Visual C++,you also perform the optional step of installing the Win32 symbol table. This willfacilitate tracing your program even when it makes calls to the operating system.

The Toolkit Library is now supplied with debugging information (symbols,programmers database, and browsing). This requires Microsoft Visual C/C++ Version6.0 sp3 or later.

Microsoft WINDBG DebuggerThe Microsoft Windows NT SDK includes a powerful symbolic debugger calledWINDBG. If using the Windows NT SDK to develop a server, this debugger is anessential tool for diagnosing and solving problems with code.

NuMega Bounds CheckerThis tool is often of great help in tracking down memory leaks, bad memory pointers,and out-of-range indexes. It does require a special effort to build your program for thisdebugging tool, but it does provide a way of trapping mismatched memoryallocations/deallocations, resources accessed but not released, and invalid indexes.

NuMega Soft IceThis tool can be useful if you find yourself debugging a server that uses drivers, such asVxD programs for Windows 98 or kernel device drivers (KDDs) for Windows NT.

Rational/Pure/Atria Quantify Performance MonitorThis tool is of most value when your server is already running, but you want to look forways to improve performance. It does require a special effort to build your program forthis evaluation tool, but it does provide a way to examine areas where programefficiency could be improved.

Page 340: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

19-6 Chapter 19

Testing

WWClient UsageThe next most useful tool for debugging the new server code is the Wonderwareprogram WWClient that is included on the Wonderware Toolkit installation disks. Thisprogram allows you to manually exercise DDE and SuiteLink functions in order to testthe server. (The program is discussed in the chapter entitled “I/O Server CodeSamples”.) This program will act as a client application. To use it, runC:\Program Files\FactorySuite\COMMON\wwclient and select the various menuoptions. The operations we will discuss are:

ConnectRegisterAdviseUnadviseRequestPokeUnregisterDisconnect

By using WWClient you can simulate all of the typical client DDE and SuiteLinkactions. Follow the sequence listed below to observe the basic operations of the newserver:

1. Select Connect to bring up the Connect dialog. Enter the name of the node to whichyou want to connect, the application name of the server, and a valid topic name forthe server. Then select whether the type of connection you want: DDE or IOT forSuiteLink. [Note: If WWClient and your server are on the same machine, the nodename can be left blank for a DDE connection, but not for a SuiteLink connection.]Finally, click on the “Connect” button. This will result in a call toProtAllocateLogicalDevice( ) and you can watch the server do its protocol setup.If the connection is successful, a status line will appear in the WWClient mainwindow. An important test of the server logic is to use an invalid topic name. Also,you can open up connections to several topics and several different servers fromthis dialog. Click on the “Done” button when you are finished.

2. Select Item to bring up the Item dialog. Select which connection you want to use,then enter a valid item name. Then click on the “Register” button. This will notresult in any calls to the server itself. However, an entry for each point registeredwill appear under the corresponding topic in the WWClient main window. You canalso register a range of points in a single command. For example, typing “V1..5”and clicking on “Register” will register points V1, V2, V3, V4, and V5. When youregister points under different connections, the points will be listed in theWWClient main window under their corresponding connections.

Page 341: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Debugging and Testing 19-7

3. With a connection selected and a valid item name or range in the “Item” edit box,click the “Advise” button. This will result in two calls to the server:ProtCreatePoint( ) and ProtActivatePoint( ). At this point, the server shouldbegin gathering data and return it by calling the ToolkitDbNewVTQFromDevice( ) routine. The new data will be displayed in theWWClient, and any of your debugging messages should be examined. Anotherimportant test is to use an invalid item name.

4. With a connection selected and a valid item name or range in the “Item” edit box,click the “Unadvise” button. Now ProtDeactivatePoint( ) will be called. Thisshould have exercised all of the basic data gathering paths.

5. With a connection selected and a valid item name or range in the “Item” edit box,click the “Request” button. If the point is not already on advise, you will see callsto ProtCreatePoint( ) and ProtActivatePoint( ), followed by updates to theToolkit via the DbNewVTQFromDevice( ), and a call to ProtDeactivatePoint( ).You will also see current value for the point appears in the WWClient mainwindow. To examine what happens with a point that is already on advise, you canuse two instances of WWClient, one of which has the point on advise, and use theother instance to request the point data. The instance of WWClient that makes therequest will show the current data value at the time of the request, but no updates tothat value will occur – even though updates are taking place in the other instance ofWWClient. See note below regarding multiple clients.

6. With a connection selected and a valid item name or range in the “Item” edit box,select the type of data you want to send (Integer, Real, Discrete, or String) and entera new value in the “Value” edit box. Then click on the “Poke” button. Now youwill see a call to ProtNewValueForDevice( ) with the new data to be written by theserver to the device.

7. With a connection selected and a valid item name or range in the “Item” edit box,click on the “Unregister” button. The listing for the point will be removed from themain WWClient window. If the point is on advise, you will also see a call toProtDeactivatePoint( ).

8. Close the Item dialog box by clicking the “Done” button. Select Disconnect toclose the connection. If there is only one connection active, it will be closed.Otherwise, the Disconnect dialog box will be displayed. You can close a particularconnection or all connections. Closing a connection will invoke a call toProtFreeLogicalDevice( ) and effectively shut down that topic in the server. Seenote below regarding multiple clients.

Page 342: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

19-8 Chapter 19

If you have multiple clients connected to the same topic, the call toProtAllocateLogicalDevice( ) only gets issued when the first client connects to thetopic. Likewise, ProtFreeLogicalDevice( ) gets called only when the last clientdisconnects from the topic. Similarly, ProtCreatePoint( ) and ProtActivatePoint( )get called only when the first client connects to the point, and ProtDeactivatePoint( )gets called only when the last client disconnects from the point.

After the basic single topic, single item paths through the server have been tested. Nowyou can move on to a more complicated test. Keep in mind that nearly all of the serverfunctions can be exercised using this simple tool. Plan your testing around the boundaryconditions of your protocol. The following are a few other basic test suggestions:

1. If you have implemented the STATUS item for the server's topics, use WWClient totest its operation while causing protocol error conditions. Most of the protocolerror handling can be tested during this phase.

2. You can use multiple copies of WWClient to exercise overlapping operations. Forexample, advise several points to check the protocol for optimizing its polling, anddo pokes to others points.

3. Clean up after topic termination (call ProtFreeLogicalDevice( ) ) can be tested.Have WWClient Advise several points and then do a Disconnect (without doing anUnadvise first).

4. Clean up after shut down (calls to ProtClose( ) ) can be tested by closing the serverwhile several points are Advised.

Scripts for WWClientWWClient can be controlled from a script, so that complex or repetitive tests can berecorded and replayed again later.;Script test.scr;Perform repeated connect, advise, and disconnect

Loop:-1Connect_iot:\\FStest05\udsample|topic1Register:v1..10Advise:v1..10Pause:1000Disconnect:\\FStest05\udsample|topic1Pause:1000LoopEnd:

Page 343: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Debugging and Testing 19-9

Microsoft Excel UsageAny cell in Excel can be set to input DDE data from the server. This can be useful fortesting and obviously for the completed application usage. To cause Excel to read DDEdata, select a cell and then enter the full address formula:

= Application|Topic!Item

For example:

=UDSAMPLE|Trans1!T1=View|Tagname!ReactorLvl=MODBUS|ReactorPLCFast!'40001'

If the item name contains special characters, Excel may try to evaluate the expression. Itis useful to put apostrophe marks (single quotes) around the item name.

In addition, Excel can be forced to do Pokes. The following two example pokes can beused:

1. Using DDEView.

DDEView can be used to poke a single cell to an item or columns of cells tomultiple items. DDEView is shipped with Wonderware's NetDDE for Windows oris available in the utilities section of Wonderware's Comprehensive Support CD.Documentation on the installation and usage of DDEView is available in AppendixC of the NetDDE for Windows User's Guide that comes with Wonderware'sNetDDE for Windows and the DDEView on-line help.

2. Using Excel 5.0 VBA macros.

An example of how to poke a single cell to an item using an Excel 5.0 VBA stylemacro:

Sub GetUDSERIAL( )Dim rangeToPokeDim channelNumber

channelNumber = Application.DDEInitiate("UDSERIAL", "topic")Set rangeToPoke = Worksheets("Sheet1").Cells(1, 1)Application.DDEPoke channelNumber, "R1", rangeToPokeApplication.DDETerminate channelNumber

End Sub

Page 344: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

19-10 Chapter 19

Page 345: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Index 1

IndexAAbout the .DEF File, 9-30About the .RC File, 9-30Active Points, 3-10Adding Help to the I/O Server, 9-30Adding SuiteLink/DDE to an Existing Windows

Application, 14-1Addressing in Windows Protected-Mode, 9-14AdjustWindowSizeFromWinIni, 9-22, 10-2, 10-53Advise, 9-7, 19-3, 19-6, 19-8ALLOCARRAYROUTINE, 11-10AllocExtArray, 11-11AlwaysDeleted, 11-9AlwaysFound, 11-6, 11-7, 11-9API Function Reference, 10-1AppendItemAtTail, 11-5, 11-16Application Name, 3-3, 3-5, 3-6Assertion Errors, 19-4AUX port, 10-24

Bbase, 11-2, 11-3, 11-4, 11-5Basic Programming Rules, 19-2Basic Setup for a Selection Box, 9-21, 10-60bCFGfileUnused, 10-106, 12-14bNotService, 10-106, 12-14Boolean Expression, 19-4Building Messages, 18-10Built in Data Structures, 18-12

CC file, 9-31Called Timer (Setup and Event) Functions, 9-9Caveats with StrVal strings, 9-12CHAIN, 7-7, 7-10, 11-3, 11-4, 11-6, 11-16Chain Manager, 11-1, 11-2, 11-3, 11-6CHAINLINK, 11-4, 11-14CHAINLINKPTR, 11-4, 11-6CHAINSCANNER, 7-7, 7-10, 11-6, 11-16CheckConfigFileCmdLine, 9-22, 10-3Client Application, 4-2CloseComm, 9-26, 10-4Coil Read Size, 4-2COM Port, 4-2Command Line Builds, 2-6Common Dialog DLL (WWDLG32A.DLL), 2-7Common Dialog Functions, 9-16Communication with the Device, 4-4Compatibility Functions, 9-27Compatibility with Later Versions of the Toolkit, 9-9Compiling a Server, 2-5Configuration File Path, 9-22Configuring an I/O Server, 4-2Control of DDEAPP from WIN.INI, 19-8Conversation, 3-6Correct Usage of a String, 9-13

DData Structures

CHAIN, 7-7, 7-10, 11-3, 11-4, 11-6, 11-16CHAINLINK, 11-4, 11-14CHAINLINKPTR, 11-4, 11-6CHAINSCANNER, 7-7, 7-10, 11-6, 11-16EXTARRAY, 11-10FILETIME, 6-2, 10-6, 10-10, 10-15, 10-18, 10-89,

10-90, 10-92, 10-93, 17-7HSTAT, 10-68, 10-69, 10-70, 10-71, 10-72, 10-73,

10-76, 10-77, 10-78, 10-79, 10-80, 10-81LPCHAIN, 11-4, 11-5, 11-6, 11-7, 11-8LPCHAINLINK, 7-8, 11-4, 11-5, 11-6, 11-7, 11-8,

11-9, 11-14, 11-15, 11-16LPCHAINSCANNER, 11-6, 11-7LPEXTARRAY, 7-7, 11-10, 11-11, 11-12, 11-13PORT, 8-3, 10-14, 10-72, 10-73, 10-75, 10-79, 10-

80, 18-12PTQUALITY, 7-7, 7-10, 10-9, 10-12, 10-13, 10-15,

10-17, 10-18PTTIME, 10-10PTVALUE, 9-12, 9-13, 10-11, 10-16, 10-17, 10-18,

10-54, 10-68, 10-70, 10-77, 10-78, 10-82, 10-83, 10-84, 10-85, 10-86, 12-2

STAT, 18-12SYMENT, 16-8, 18-12WW_AB_INFO, 10-108, 10-109, 12-3, 17-6WW_CONFIRM, 10-106, 10-107, 12-4, 12-14, 15-

4WW_CP_DLG_LABELS, 9-16, 10-104, 10-105,

12-5, 12-6WW_CP_PARAMS, 10-105, 10-117, 12-5, 12-6,

12-10, 16-10WW_SELECT, 10-130, 12-12WW_SERV_PARAMS, 12-14

Data Variables, 9-30Database Handle Parameter, 9-5DbDevGetName, 10-5DbGetGMTasFiletime, 6-2, 6-3, 10-6, 10-15, 17-7DbGetName, 10-7, 10-91DbGetPointType, 10-8DbGetPtQuality, 10-9DbGetPtTime, 10-10DbGetValueForComm, 10-11DbNewQForAllPoints, 10-12DbNewQFromDevice, 6-2, 7-8, 10-13, 17-7DbNewTQFromDevice, 6-2, 9-9, 10-12, 10-13, 10-15,

17-7DbNewValueFromDevice, 9-1, 10-16, 19-7DbNewVQFromDevice, 7-5, 10-17, 17-8DbNewVTQFromDevice, 6-2, 6-4, 7-5, 9-9, 10-16, 10-

17, 10-18, 10-42, 10-45, 10-52, 10-55, 17-7, 17-8,19-7

DbRegisterDemandScan, 10-19DbRegisterScanState, 10-20DbSetHProt, 9-9, 10-21DbSetPointType, 10-22DbValueWriteConfirm, 10-23DDE Conversation, 10-43DDE Server Toolkit Data Structures, 12-1DDEAPP.EXE, 19-3, 19-6

Page 346: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Index2

debug, 9-22, 10-24, 19-2Debug and Support Functions, 18-14Debug Messages, 19-2DebugDDEMessages, 19-3Debugging and Testing, 5-1, 6-1, 7-1, 8-1, 11-1, 15-1,

17-1, 19-1Debugging the DDE Message Traffic, 19-3DEF file, 9-30DELETEARRAYROUTINE, 11-10DeleteChain, 11-8, 11-16DeleteExtArray, 11-11DeleteItem, 11-8, 11-14, 11-16DELETEROUTINE, 11-8, 11-9Deleting an Extensible Array, 11-11DemandScanFncCallback, 10-19Designing the UDSERIAL Server, 18-4Discrete (Boolean) Data Type, 3-4Discrete Data Type, 9-5, 9-6, 9-7dwWWOsPlatform, 10-121Dynamic Data Exchange, 3-1

EEnableCommNotification, 9-27, 10-25Examples of Logical Device Management, 9-4Excel Usage, 19-9Executing the Configuration, 18-10Executing the Protocol, 4-3, 18-11EXTARRAY, 11-10EXTENDARRAYROUTINE, 11-10ExtractReadData/ExtractDbItem, 18-11

FFastDDE, 3-3, 5-2, 5-7File Description, 2-3

Include Files, 2-3Sample Servers, 2-4Utility Files, 2-3

FILETIME, 6-2, 10-6, 10-10, 10-15, 10-18, 10-89, 10-90, 10-92, 10-93, 17-7

FindFirstItem, 7-10, 11-6, 11-16FindItemFollowing, 11-7FindItemStartingAt, 7-8, 11-6FindNextItem, 7-8, 7-10, 11-7, 11-16FlushComm, 9-26, 10-26FOUNDROUTINE, 11-9Freeing Memory, 9-2, 9-14Freeing the Memory Associated with the Selection List,

9-21, 10-63Freeing the Memory used for a ptValue String, 10-84Functions

AdjustWindowSizeFromWinIni, 9-22, 10-2AllocExtArray, 11-11AlwaysDeleted, 11-9AlwaysFound, 11-6, 11-7, 11-9AppendItemAtTail, 11-5, 11-16CheckConfigFileCmdLine, 9-22, 10-3CloseComm, 9-26, 10-4DbDevGetName, 10-5DbGetGMTasFiletime, 6-2, 6-3, 10-6, 10-15, 17-7DbGetName, 10-7, 10-91

DbGetPointType, 10-8DbGetPtQuality, 10-9DbGetPtTime, 10-10DbGetValueForComm, 10-11DbNewQForAllPoints, 10-12DbNewQFromDevice, 6-2, 7-8, 10-13, 17-7DbNewTQFromDevice, 6-2, 9-9, 10-12, 10-13, 10-

15, 17-7DbNewValueFromDevice, 9-5, 10-16, 19-7DbNewVQFromDevice, 7-5, 10-17, 17-8DbNewVTQFromDevice, 6-2, 6-4, 7-5, 9-9, 10-16,

10-17, 10-18, 17-7, 17-8, 19-7DbRegisterDemandScan, 10-19DbRegisterScanState, 10-20DbSetHProt, 9-9, 10-21DbSetPointType, 10-22DbValueWriteConfirm, 10-23debug, 10-24, 19-2DeleteChain, 11-8, 11-16DeleteExtArray, 11-11DeleteItem, 11-8, 11-14, 11-16EnableCommNotification, 9-27, 10-25ExtendExtArray, 11-11FindFirstItem, 7-10, 11-6, 11-16FindItemFollowing, 11-7FindItemStartingAt, 7-8, 11-6FindNextItem, 7-8, 7-10, 11-7, 11-16FlushComm, 9-26, 10-26GetAppName, 10-27GetCommError, 9-26, 10-28GetCommEventMask, 9-26, 10-29GetExtArrayMemberPtr, 7-7, 11-11GetIOServerLicense, 10-30, 18-5GetScannerNextItem, 11-7GetServerNameExtension, 10-31, 10-119, 15-6, 17-

3GetString, 10-32GetTextExtent, 10-33InitializeChain, 11-5, 11-16InitializeExtArray, 11-11InsertItemAfter, 11-5InsertItemAtHead, 11-5InsertItemBefore, 11-5InsertItemInMiddle, 11-5, 11-16IsInChain, 11-6NTSrvr_BuildCommDCB, 9-27, 10-34NTSrvr_GetCommState, 9-27, 10-35NTSrvr_SetCommState, 9-27, 10-36NTSrvr_SetDCB_Dtr, 9-27, 10-37NTSrvr_SetDCB_Rts, 9-27, 10-38OpenComm, 9-26, 10-39PfnSendEmSelectAll, 9-27, 10-40PfnSendEmSelectRange, 9-27, 10-41ProtActivatePoint, 9-5, 10-21, 10-42, 19-7ProtAllocateLogicalDevice, 9-3, 10-43, 19-6ProtClose, 9-2, 10-44, 19-8ProtCreatePoint, 9-5, 10-45, 19-7ProtDeactivatePoint, 9-6, 10-46, 19-7ProtDefWindowProc, 9-2, 10-47ProtDeletePoint, 10-48ProtDefWindowProc, 14-1ProtExecute, 9-3, 10-49ProtFreeLogicalDevice, 9-3, 10-50, 19-7, 19-8

Page 347: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Index 3

ProtGetDriverName, 9-2, 9-22, 10-3, 10-24, 10-27,10-31, 10-51, 14-1, 15-4, 15-6, 17-3, 19-3

ProtGetValidDataTimeout, 9-2, 9-10, 10-52ProtInit, 9-2, 10-53ProtNewValueForDevice, 9-6, 9-11, 9-13, 10-21,

10-54, 19-7ProtTimerEvent, 9-2, 9-9, 10-55ReadComm, 9-26, 10-56RelinquishPermission, 9-14, 10-57RequestPermission, 9-14, 10-58SelBoxAddEntry, 9-21, 10-59SelBoxSetupStart, 9-21, 10-60SelBoxUserSelect, 9-21t, 10-61SelBoxUserSelection, 9-21, 10-62SelListFree, 9-21, 10-63SelListGetSelection, 9-21, 10-64SelListNumSelections, 9-21, 10-65SetChainBase, 11-5SetCommEventMask, 9-26, 10-66SetSplashScreenParams, 10-67, 10-102, 17-4, 17-5,

18-5StatAddValue, 10-68, 10-72, 10-74StatDecrementValue, 10-69StatGetValue, 10-70StatIncrementValue, 10-71, 10-72, 10-74StatRegisterCounter, 10-68, 10-69, 10-70, 10-71,

10-72, 10-74, 10-75, 10-77, 10-78, 10-79, 10-81

StatRegisterRate, 10-68, 10-69, 10-70, 10-71, 10-73, 10-76, 10-77, 10-78, 10-80, 10-81

StatSetCountersInterval, 8-4, 10-75StatSetRateInterval, 10-76StatSetValue, 10-77StatSubtractValue, 10-78StatUnregisterCounter, 10-72, 10-79StatUnregisterRate, 10-74, 10-80StatZeroValue, 10-81StrValSetNString, 9-11, 10-82StrValSetString, 9-11, 9-12, 9-13, 10-83StrValStringFree, 9-11, 10-84StrValStringLock, 9-11, 9-13, 10-85StrValStringUnlock, 9-11, 9-13, 10-86SysTimerSetupProtTimer, 9-2, 10-87SysTimerSetupRequestTimer, 10-88UdAddFileTimeOffset, 10-89, 10-90UdAddTimeMSec, 10-90UDDbGetName, 10-7, 10-91UdDeltaFileTime, 10-92, 10-93UdDeltaTimeMSec, 10-93UdInit, 10-94UdReadAnyMore, 9-22, 10-95, 10-128, 10-129, 10-

140, 10-141UdReadVersion, 9-22, 10-96, 10-128, 10-129, 10-

140, 10-141UdTerminate, 10-97UdWriteAnyMore, 9-24, 10-98, 10-128, 10-129,

10-140, 10-141UdWriteVersion, 9-24, 10-99, 10-128, 10-129, 10-

140, 10-141UnchainItem, 11-8, 11-16WriteComm, 9-26, 10-100WriteWindowSizetoWinIni, 9-24WriteWindowSizetoWinIni, 10-101

WWAnnounceStartup, 10-67, 10-102, 17-4, 17-5WWCenterDialog, 9-16, 10-103WWConfigureComPort, 9-16, 10-104WWConfigureServer, 9-16, 10-106WWConfirm, 9-16, 10-107WWDisplayAboutBox, 9-16, 10-108WWDisplayAboutBoxEx, 10-109, 12-3WWDisplayConfigNotAllow, 9-16, 10-110WWDisplayErrorCreating, 9-17, 10-111WWDisplayErrorReading, 9-17, 10-112WWDisplayErrorWriting, 9-17, 10-113WWDisplayKeyNotEnab, 9-18, 10-114WWDisplayKeyNotInst, 9-18, 10-115WWDisplayOutofMemory, 9-18, 10-116WWFormCpModeString, 9-18, 10-117WWGetDialogHandle, 9-18, 10-118WWGetDriverNameExtension, 10-119WWGetExeFilePath, 10-120, 15-4WWGetOsPlatform, 10-121wwHeap_AllocPtr, 10-122wwHeap_AllocPtr, 9-14wwHeap_FreePtr, 10-123wwHeap_FreePtr, 9-14wwHeap_Init, 10-124wwHeap_Init, 9-14wwHeap_ReAllocPtr, 10-125wwHeap_ReAllocPtr, 9-14wwHeap_Release, 9-14, 10-126WWInitComPortComboBox, 9-18, 10-127WWSelect, 9-18, 10-130WWTranslateCDlgToWinBaud, 9-18, 10-131WWTranslateCDlgToWinData, 9-18, 10-132WWTranslateCDlgToWinParity, 9-18, 10-133WWTranslateCDlgToWinStop, 9-19, 10-134WWTranslateWinBaudToCDlg, 9-19, 10-135WWTranslateWinDataToCDlg, 9-19, 10-136WWTranslateWinParityToCDlg, 9-20, 10-137WWTranslateWinStopToCDlg, 9-20, 10-138WWVerifyComDlgRev, 9-20, 10-139

GGetAppName, 9-22, 10-27GetCommError, 9-26, 10-28GetCommEventMask, 9-26, 10-29GetExtArrayMemberPtr, 7-7, 11-11GetIOServerLicense, 10-30, 18-5GetProfileInt, 10-53GetProfileString, 10-53GetScannerNextItem, 11-7GetServerNameExtension, 10-31, 10-119, 15-6, 17-3GetString, 9-22, 10-32GetTextExtent, 10-33Getting Started with the I/O Server Toolkit, 2-1GlobalAlloc, 9-14GlobalFree, 9-14GlobalLock, 9-14GlobalReAlloc, 9-14GlobalUnlock, 9-14

Page 348: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Index4

HHeap Manager, 9-14Help Development Software Packages, 9-31Help Files, 9-31Help Menu Items

MENU_HELP_ABOUT, 9-31MENU_HELP_INDEX, 9-31MENU_HELP_ON_HELP, 9-31SEPARATOR, 9-31

HSTAT, 10-68, 10-69, 10-70, 10-71, 10-72, 10-73, 10-76, 10-77, 10-78, 10-79, 10-80, 10-81

hString Field, 9-11

II/O Conversation, 3-2, 3-3, 3-5, 9-3I/O Server Code Samples, 18-1I/O Server Toolkit Application Programming Interface,

10-1I/O Server's Initialization, 9-2Implementing a Configure Menu Option, 4-2InitializeChain, 11-5, 11-16InitializeExtArray, 11-11Initializing a Heap, 9-14, 10-124Initializing a ptValue String, 9-11Initializing or Changing the Value of a ptValue string,

10-83INITIATE, 19-3, 19-6InsertItemAfter, 11-5InsertItemAtHead, 11-5InsertItemBefore, 11-5InsertItemInMiddle, 11-5, 11-16Installation Procedures

With a prior installation of the I/O Server Toolkit,2-2

Integer Data Type, 3-4, 9-5, 9-6, 9-8IsInChain, 11-6Item Name, 3-6, 4-3Item/Point, 3-3, 3-6, 4-2

LLimiting the String Size, 10-82Linked List, 11-14Linking a Server, 2-6Locking a String in Memory, 9-11, 10-85Logging Hardware/Software Problems, 10-24Logical Device, 3-3, 3-5, 4-2, 9-3LogicalAddrCmp, 18-10LPALLOCARRAYROUTINE, 11-10, 11-11LPCHAIN, 11-4, 11-5, 11-6, 11-7, 11-8LPCHAINLINK, 7-8, 11-4, 11-5, 11-6, 11-7, 11-8, 11-9,

11-14, 11-15, 11-16LPCHAINSCANNER, 11-6, 11-7LPDELETEARRAYROUTINE, 11-10, 11-11LPDELETEROUTINE, 11-9LPEXTARRAY, 7-7, 11-10, 11-11, 11-12, 11-13LPEXTENDARRAYROUTINE, 11-10, 11-11LPFOUNDROUTINE, 11-6, 11-7, 11-9lstrcmpi, 10-43, 10-45

MMacros for Portablility, 9-28Managing Points, 9-5Memory, 9-11Memory Access Permission Functions, 9-14Memory Address Range, 9-15Memory Management Functions, 9-14Memory Mapped I/O, 10-58Miscellaneous Functions, 9-22Modifying the User Interface - UDSERIAL.RC, 18-6Multiple I/O Conversations, 3-8

NnNTServiceSetting, 10-106, 12-14, 12-15, 15-5, 15-7Non-Standard Memory, 10-58Notation Convention for Application and Topic, 3-5, 3-6Notes on the UDSAMPLE, 18-2NTSrvr_BuildCommDCB, 9-27, 10-34NTSrvr_GetCommState, 9-27, 10-35NTSrvr_SetCommState, 9-27, 10-36NTSrvr_SetDCB_Dtr, 9-27, 10-37NTSrvr_SetDCB_Rts, 9-27, 10-38

OObtaining a File Path from the Command Line, 9-22OnOffScanFncCallback, 10-20OpenComm, 9-26, 10-39OX.SYS, 10-24

PPfnSendEmSelectAll, 9-27, 10-40PfnSendEmSelectRange, 9-27, 10-41Point/Item Management, 9-5Poke, 9-7, 19-3, 19-7Poll Frequency, 4-2PORT Data Structure, 18-12Porting to Windows NT, 16-1PreventBlockedDDE, 19-3ProcessValidResponse, 18-11ProtActivatePoint, 9-5, 10-42, 10-46, 19-7ProtAllocateLogicalDevice, 9-3, 9-5, 10-43, 10-48, 19-6ProtClose, 9-2, 10-44ProtCreatePoint, 9-5, 10-21, 10-23, 10-42, 10-45, 10-46,

10-48, 19-7ProtDeactivatePoint, 9-6, 10-46, 19-7ProtDefWindowProc, 9-2, 10-47, 14-1ProtDeletePoint, 10-48ProtExecute, 9-3, 10-49ProtFreeLogicalDevice, 9-3, 10-50, 19-7, 19-8ProtGetDriverName, 9-2, 9-22, 10-3, 10-24, 10-27, 10-

31, 10-51, 14-1, 15-4, 15-6, 17-3, 19-3ProtGetValidDataTimeout, 9-2, 9-10, 10-52, 10-88ProtInit, 9-1, 9-2, 10-3, 10-53ProtNewValueForDevice, 9-6, 9-11, 9-13, 10-46, 10-54,

19-7Protocol Initialization & Setup, 9-2ProtTimerEvent, 9-2, 9-9, 10-55, 18-11

Page 349: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Index 5

PTQUALITY, 7-7, 7-10, 10-9, 10-12, 10-13, 10-15, 10-17, 10-18

PTTIME, 10-10ptValue, 9-11, 12-2

QQuality, 3-2, 6-2, 7-1, 7-2, 7-4, 7-5, 10-9, 10-16, 17-2,

17-7, 17-8

RRC file, 9-30, 9-31ReadComm, 9-26, 10-56Real Data Type, 3-4, 9-5, 9-6, 9-8Real Mode, 9-14Register Read size, 4-2RelinquishPermission, 9-14, 10-57, 10-58Reporting Changing Point Values, 9-5REQUEST, 19-3RequestPermission, 9-14, 10-58Resource File, 10-32Retrieving a Point Value from the Device, 9-9Returning a String from the Resource File, 10-32Running a Server, 2-7

SSample I/O Servers

Board, 9-31Board Sample, 4-4Serial, 9-31

SampleI/O ServersSerial Sample, 4-4

SAMPLES, 18-2SelBoxAddEntry, 9-21, 10-59, 10-64SelBoxSetupStart, 9-21, 10-60SelBoxUserSelect, 9-21, 10-59, 10-61SelBoxUserSelect, 10-62SelBoxUserSelection, 9-21, 10-61, 10-62Selection Box, 9-21SelListFree, 9-21, 10-32, 10-62, 10-63SelListGetSelection, 9-21, 10-62, 10-64SelListNumSelections, 9-21, 10-62, 10-64, 10-65Server Application, 3-3, 4-2, 9-3Server Porting Instructions, 16-2Server.HLP file, 9-31SetChainBase, 11-5SetCommEventMask, 9-26, 10-66SetSplashScreenParams, 10-67, 10-102, 17-4, 17-5, 18-5Setting the Vertical Screen Position of the Box, 10-61Slave ID, 4-2STAT Data Structure (or Node or Topic), 18-12StatAddValue, 10-68, 10-72, 10-74StatDecrementValue, 10-69StatGetValue, 10-70StatIncrementValue, 10-71, 10-72, 10-74StatRegisterCounter, 10-68, 10-69, 10-70, 10-71, 10-72,

10-74, 10-75, 10-77, 10-78, 10-79, 10-81StatRegisterRate, 10-68, 10-69, 10-70, 10-71, 10-73, 10-

76, 10-77, 10-78, 10-80, 10-81StatSetCountersInterval, 8-4, 10-75

StatSetRateInterval, 10-76StatSetValue, 10-77StatSubtractValue, 10-78StatUnregisterCounter, 10-72, 10-79StatUnregisterRate, 10-74, 10-80StatZeroValue, 10-81Stop Reporting Point Value Changes, 9-6stricmp, 3-8String Buffers, 10-32String Data Type, 3-4, 9-5, 9-6, 9-8String PtValue Manipulation Functions, 9-9, 9-11STRINGTABLE, 9-30STRUSER, 10-32StrValSetNString, 9-11, 10-82StrValSetString, 9-11, 9-12, 9-13, 10-83StrValStringFree, 9-11, 10-83, 10-84StrValStringLock, 9-11, 9-13, 10-85, 10-86StrValStringUnlock, 9-11, 9-13, 10-86SuiteLink, 2-3, 3-1, 3-2, 3-3, 3-4, 3-5, 3-6, 3-7, 3-8, 4-2,

5-1, 5-2, 5-3, 5-4, 5-5, 5-6, 5-7, 5-8, 6-4, 7-4, 8-3,8-4, 8-5, 9-1, 10-23, 14-1, 15-7, 18-3, 19-6

Symbol Table, 11-2, 16-8, 18-12SYMENT Data Structure (Symbol Table), 18-12System Topic, 8-3SysTimerSetupProtTimer, 9-2, 9-9, 10-53, 10-55, 10-87SysTimerSetupRequestTimer, 9-2, 9-9, 10-53, 10-88szCaption, 10-106, 12-14szComment, 10-108, 12-3, 17-6

TTERMINATE, 3-5, 19-3, 19-6, 19-7, 19-8Time Mark, 6-2, 6-4, 10-12, 10-13, 10-16, 10-17, 17-7Timeout, 4-2Timer Event from the Toolkit, 4-3Toolkit database, 3-2, 3-7, 3-8, 3-9, 5-4, 6-2, 6-4, 6-5, 7-

4, 9-5, 9-9, 9-10, 9-13, 10-9, 10-10, 10-12, 10-13,10-15, 10-21, 10-42, 10-46, 10-55, 10-82, 10-83,10-84, 10-88

Toolkit Database Interface for Protocol Functions, 9-9Toolkit Functions, 9-1Toolkit Library Routines, 3-6TOOLKIT7.LIB, 9-7, 9-9, 9-30, 14-1Topic Name, 3-3, 3-5, 3-6, 4-2, 4-3

UUdAddFileTimeOffset, 10-89, 10-90UdAddTimeMSec, 10-90UDBLDMSG.C, 18-10UDBOARD, 4-3UDCONFIG.C - Function ValidatePoint, 18-8UDDbGetName, 10-7, 10-91UdDeltaFileTime, 10-92, 10-93UdDeltaTimeMSec, 10-93UdInit, 9-22, 10-94, 14-1UDMAIN.C, 9-31UDMSG Data Structure (Message), 18-12UdprotAddPoll, 18-10UdProtDoProtocol, 18-11UdprotGetResponse, 18-11UdprotPrepareWriteMsg, 18-10

Page 350: Wonderware I/O Server Toolkit User's Guide Connectivity/DA...Bold Text Denotes a Wonderware I/O Server Toolkit function name, for example, Wizard_New Bold & Underlined Denotes a Wonderware

Index6

UdReadAnyMore, 9-22, 10-95, 10-128, 10-129, 10-140,10-141

UdReadVersion, 9-22, 10-96, 10-128, 10-129, 10-140,10-141

UDSAMPLE, 18-2UDSERIAL, 4-2UDSERIAL Architectural Overview, 18-3UdTerminate, 9-24, 10-97, 14-1UdWriteAnyMore, 9-24, 10-98, 10-128, 10-129, 10-140,

10-141UdWriteVersion, 9-24, 10-99, 10-128, 10-129, 10-140,

10-141Unadvise, 9-7, 19-3, 19-8UnchainItem, 11-8, 11-16Unlocking a String in Memory, 10-86

VValidatePoint

Example, 18-8ValidDataTimeout, 9-10, 10-88VTQ, 5-2, 6-2, 6-4, 10-12, 10-13, 10-15, 10-17, 10-18,

17-2, 17-7

WWhat is called on a Poke?, 9-7What is called on a Request?, 9-6What is called on a TERMINATE?, 9-4What is called on an Advise/Unadvise?, 9-7What is called on INITIATE?, 9-4What is DDE?,1-4What is SuiteLink?, 5-1WIN.INI, 9-22, 10-24, 19-8Windows Function Emulators, 9-26Windows NT Only Macros, 9-28Windows NT Porting Functions, 9-25Windows' String Resources, 10-32WindowViewer, 3-3, 3-6WINHELP, 9-30WinMain, 9-22, 9-24, 10-94, 10-97WM_COMMAND / MENU_HELP_ABOUT, 9-31WM_COMMAND Messages, 10-47WM_DDE_REQUEST, 10-52Wonderware InTouch, 3-3, 9-21Wonderware Logger Sample, 19-3WriteComm, 9-26, 10-100WriteWindowSizetoWinIni, 9-24, 10-101Writing a New Value to the Device, 9-6WW_AB_INFO, 12-3WW_CONFIRM, 12-4WW_CP_DLG_LABELS, 12-5WW_CP_PARAMS, 12-10WW_SELECT, 12-12WW_SERV_PARAMS, 12-14WWAnnounceStartup, 10-67, 10-102, 17-4, 17-5WWCenterDialog, 9-16, 10-103WWConfigureComPort, 9-16, 10-104WWConfigureServer, 9-16, 10-106WWConfirm, 9-16, 10-107WWDisplayAboutBox, 9-16, 10-108WWDisplayAboutBoxEx, 10-109, 12-3

WWDisplayConfigNotAllow, 9-16, 10-110WWDisplayErrorCreating, 9-17, 10-111WWDisplayErrorReading, 9-17, 10-112WWDisplayErrorWriting, 9-17, 10-113WWDisplayKeyNotEnab, 9-18, 10-114WWDisplayKeyNotInst, 9-18, 10-115WWDisplayOutofMemory, 9-18, 10-116, 10-122, 10-

125WWFormCpModeString, 9-18, 10-117WWGetDialogHandle, 9-18, 10-118WWGetDriverNameExtension, 10-119WWGetExeFilePath, 10-120, 15-4WWGetOsPlatform, 10-121wwHeap_AllocPtr, 9-14, 10-122wwHeap_FreePtr, 9-14, 10-123wwHeap_Init, 9-14, 10-124wwHeap_ReAllocPtr, 9-14, 10-125wwHeap_Release, 9-14, 10-126wwHeapAllocPtr, 10-124wwHeapFreePtr, 10-124wwHeapReAllocPtr, 10-124WWInitComPortComboBox, 9-18, 10-127WWLOGGER.EXE, 10-24WWSelect, 9-18, 10-130WWTranslateCDlgToWinBaud, 9-18, 10-131WWTranslateCDlgToWinData, 9-18, 10-132WWTranslateCDlgToWinParity, 9-18, 10-133WWTranslateCDlgToWinStop, 9-19, 10-134WWTranslateWinBaudToCDlg, 9-19, 10-135WWTranslateWinDataToCDlg, 9-19, 10-136WWTranslateWinParityToCDlg, 9-20, 10-137WWTranslateWinStopToCDlg, 9-20, 10-138WWVerifyComDlgRev, 9-20, 10-139