100% found this document useful (2 votes)
8K views1,355 pages

CitectSCADA Cicode Reference

Schneider Electric (Australia) Pty. Ltd. Makes no representations or warranties with respect to this manual. The Example Projects are provided to you for the purpose of illustrating how the SCADA software v7. Could be used in an operational environment. Schneider Electric gives no express warranties, guarantees or conditions, including any implied warranties of merchantability, fitness for a particular purpose or noninfringement of third parties' intellectual property rights.

Uploaded by

Sebestyén Béla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
8K views1,355 pages

CitectSCADA Cicode Reference

Schneider Electric (Australia) Pty. Ltd. Makes no representations or warranties with respect to this manual. The Example Projects are provided to you for the purpose of illustrating how the SCADA software v7. Could be used in an operational environment. Schneider Electric gives no express warranties, guarantees or conditions, including any implied warranties of merchantability, fitness for a particular purpose or noninfringement of third parties' intellectual property rights.

Uploaded by

Sebestyén Béla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1355

CitectSCADAv7.

40
Cicode Reference Guide
August 2013

Legal Information
DISCLAIMER
Schneider Electric (Australia) Pty. Ltd. makes no representations or warranties with respect to this manual and, to the maximum extent permitted by law, expressly limits its liability for breach of any warranty that may be implied to the replacement of this manual with another. Further, Schneider Electric (Australia) Pty. Ltd. reserves the right to revise this publication at any time without incurring an obligation to notify any person of the revision. The Example Projects are provided to you for the purpose of illustrating how the SCADA software v7.40 could be used in an operational environment ("the Purpose").Schneider Electric grants you a royalty free, non exclusive, non transferable license to use the example projects installed with your SCADA software version v7.40 (the Example Projects) for the Purpose only. The Example Projects are provided by Schneider Electric as part of the SCADA software version v7.40 on an "as is" basis and Schneider Electric does not guarantee the reliability, serviceability or function of the Example Projects. Should you modify the Example Projects, you bear the risk of any use of such modified Example Projects. Schneider Electric gives no express warranties, guarantees or conditions and to the extent permitted under applicable laws, Schneider Electric disclaims all implied warranties, including any implied warranties of merchantability, fitness for a particular purpose or noninfringement of third parties intellectual property rights. Schneider Electric shall not be liable for any direct, indirect or consequential damages or costs of any type arising out of any action taken by you or others related to the Example Projects.

COPYRIGHT
Copyright 2013 Schneider Electric (Australia) Pty. Ltd. All rights reserved.

TRADEMARKS
Schneider Electric (Australia) Pty. Ltd. has made every effort to supply trademark information about company names, products and services mentioned in this manual. Citect, CitectHMI,PowerSCADA Expert and CitectSCADA are either registered trademarks or trademarks of Schneider Electric (Australia) Pty. Ltd.. Pelco, Spectra, Sarix, Endura, are registered trademarks of Pelco, Inc. IBM, IBM PC and IBM PC AT are registered trademarks of International Business Machines Corporation. MS-DOS, Windows, Windows NT, Microsoft, and Excel are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. DigiBoard, PC/Xi and Com/Xi are trademarks of Digi International Inc. Novell, Netware and Netware Lite are either registered trademarks or trademarks of Novell, Inc. in the United States and other countries. dBASE is a trademark of dataBased Intelligence, Inc. All other brands and products referenced in this document are acknowledged to be the trademarks or registered trademarks of their respective holders.

GENERAL INFORMATION
Some product names used in this manual are used for identification purposes only and may be trademarks of their respective companies. August 2013 edition for CitectSCADA Version v7.40. Manual Revision Version v7.40.

PLEASE NOTE
Electrical equipment should be installed, operated, serviced, and maintained only by qualified personnel. No responsibility is assumed by Schneider Electric (Australia) Pty. Ltd. for any consequences arising out of the use of this material. 2013 Schneider Electric (Australia) Pty. Ltd.. All Rights Reserved.

Validity Note
The present documentation is intended for qualified technical personnel responsible for the implementation, operation and maintenance of the products described. It contains information necessary for the proper use of the products. However, those who wish to make a more "advanced" use of our products may find it necessary to consult our nearest distributor in order to obtain additional information.

The contents of this documentation are not contractual and in no way constitute an extension to, or restriction of, the contractual warranty clauses. Contact Schneider Electric today at www.schneider-electric.com

Contents
Legal Information Contents 1 3

Introduction
Safety Information Chapter 1: Introducing Cicode
Getting Started Using Cicode Files Restricted Cicode Keywords

11
13 15
15 16 16

Using Cicode
Chapter 2: Using Cicode Commands
Setting Variables Performing Calculations Using Multiple Command Statements Using Include (Text) Files Getting Runtime Operator Input

19
21
21 22 23 23 25

Chapter 3: Using Cicode Expressions


Displaying Data Using Expressions Decision-Making Logging Expression Data Triggering Events Using Expressions

27
27 28 28 29

Chapter 4: Using Cicode Functions

31
3

Contents

Calling Functions from Commands and Expressions Triggering Functions via Runtime Operator Input Evaluating Functions Combining Functions with Other Statements Passing Data to Functions (Arguments) Using String Arguments String assignment Using the Caret Escape Sequence Character Using Multiple Arguments Using Numeric Arguments Using Variable Arguments Using Operator Input in Functions Returning Data from Functions

31 31 32 32 33 33 34 34 35 35 35 36 36

Chapter 5: Working with Commonly Used Functions


Alarm Functions Page Functions Keyboard Functions Report Functions Time/date Functions Miscellaneous Functions

37
37 38 39 39 39 39

Chapter 6: Writing Functions


Cicode Function Structure Function Uses Writing Groups of Functions Cicode Function Libraries Creating a Function Outline Pseudocode Using Comments in Cicode Using Comments for Debugging Functions Tag Reference /TagReadEx() behavior in Cicode Expressions Following Cicode Syntax Cicode Function Syntax End of line markers Function Scope Declaring the Return Data Type Declaring Functions Naming Functions Function Argument Structure Declaring Argument Data Type Naming Arguments Setting Default Values for Arguments Returning Values from Functions

41
41 42 43 43 44 44 45 46 46 47 48 50 50 51 52 53 54 56 57 58 60

Chapter 7: Using Variables


Declaring Variable Properties

63
63

Contents

Declaring the Variable Data Type QUALITY Data Type TIMESTAMP Data Type Naming Variables Setting Default Variable Values Using Variable Scope Using Database Variables

64 64 65 65 66 66 68

Chapter 8: Using Arrays


Declaring Array Properties Declaring the Array Data Type Naming Arrays Declaring the Variable Array Size Setting Default (Initial) Array Values Passing Array Elements as Function Arguments Using One-dimensional Arrays Using Two-dimensional Arrays Using Three-dimensional Arrays Using Array Elements in Loops Using the Table (Array) Functions

69
69 70 70 70 71 72 72 72 73 74 74

Chapter 9: Using Cicode Macros


IFDEF IFDEFAdvAlm IFDEFAnaAlm IFDEFDigAlm Macro Arguments

75
75 76 77 78 79

Chapter 10: Converting and Formatting Cicode Variables


Converting Variable Integers to Strings Converting Real Numbers to Strings Converting Strings to Integers Converting Strings to Real Numbers Formatting Text Strings Escape Sequences (String Formatting Commands)

81
81 82 83 83 83 85

Chapter 11: Working with Operators


Using Mathematical Operators Using Bit Operators Using Relational Operators Using Logical Operators Order of Precedence of Operators

87
87 89 90 91 92

Chapter 12: Working with Conditional Executors


Setting IF ... THEN Conditions

93
93

Contents

Using FOR ... DO Loops Using WHILE ... DO Conditional Loops Nested Loops Using the SELECT CASE statement

94 95 95 96

Chapter 13: Performing Advanced Tasks


Handling Events How Cicode is Executed Multitasking Foreground and background tasks Controlling tasks Pre-emptive multitasking

99
99 100 101 101 102 102

Chapter 14: Editing and Debugging Code


The Cicode Editor Starting the Cicode Editor Changing the default Cicode Editor Creating Cicode files Creating functions Saving files Opening Cicode files Deleting Cicode files Finding text in Cicode files Compiling Cicode files Viewing errors detected by the Cicode Compiler Cicode Editor Options Docking the Windows and Toolbars Displaying the Editor Options Properties dialog Windows and Bars Tab Toolbar options Window options Viewing Editor windows Options Properties Tab Language Formatter Properties Tab Debugging Cicode Using debug mode Debugging functions Debugging functions remotely Using breakpoints Inserting or removing breakpoints Enabling/disabling breakpoints Stepping through code

105
105 106 107 108 108 108 109 110 110 111 111 111 112 112 113 113 114 114 119 121 122 122 122 123 124 124 124 125

Chapter 15: Using Cicode Programming Standards


Variable Declaration Standards Variable Scope Standards Variable Naming Standards

127
128 128 129

Contents

Standards for Constants, Variable Tags, and Labels Formatting Simple Declarations Formatting Executable Statements Formatting Expressions Cicode Comments Formatting Functions Format Templates Function Naming Standards Modular Programming Defensive Programming Function Error handling Debug Error Trapping

130 131 132 133 134 134 136 138 140 143 144 147

Functions Reference
Chapter 16: Accumulator Functions Chapter 17: ActiveX Functions Chapter 18: Alarm and Alarm Filter Functions Chapter 19: Clipboard Functions Chapter 20: Cluster Functions Chapter 21: Color Functions Chapter 22: Communication Functions Chapter 23: DDE Functions Chapter 24: Device Functions Chapter 25: Display Functions Chapter 26: DLL Functions Chapter 26: Equipment Database Functions

149
151 159 173 281 285
285

293 299 307 321 351 441 447

Contents

Chapter 27: Error Functions Chapter 28: Event Functions Chapter 29: File Functions Chapter 30: Form Functions Chapter 31: Format Functions Chapter 32: FTP Functions Chapter 33: FuzzyTech Functions Chapter 34: Group Functions Chapter 35: I/O Device Functions Chapter 36: Keyboard Functions Chapter 37: Mail Functions Chapter 38: Math/Trigonometry Functions Chapter 39: Menu Functions Chapter 40: Miscellaneous Functions Chapter 41: Page Functions Chapter 42: Plot Functions Chapter 43: Process Analyst Functions Chapter 44: Quality Functions Chapter 45: Report Functions
8

463 475 493 513 551 561 567 573 583 595 611 617 633 649 701 747 769 777 791

Contents

Scheduler Functions

796

Chapter 46: Security Functions Chapter 46: Sequence of Events Chapter 47: Server Functions Chapter 48: SQL Functions Chapter 49: SPC Functions Chapter 50: String Functions Chapter 51: Super Genie Functions Chapter 52: Table (Array) Functions Chapter 53: Tag Functions Chapter 54: Task Functions Chapter 55: Time/Date Functions Chapter 56: Timestamp Functions Chapter 57: Trend Functions Chapter 58: Window Functions Chapter 58: XML Functions

829 855 857 873 927 943 971 1011 1015 1073 1113 1135 1151 1243 1278

Technical Reference
Chapter 59: Cicode Errors
Hardware/Cicode Errors

1297
1299
1299

Contents

Cicode and General Errors MAPI Errors

1300 1323

Chapter 60: Browse Function Field Reference


Server Browse Function Fields

1327
1338

10

Part: 1
Introduction
This section provides some introductory material for CitectSCADA:
Introducing Cicode

11

12

Safety Information

Safety Information
Hazard categories and special symbols

The following symbols and special messages may appear in this manual or on the product to warn of potential hazards or to call attention to information that clarifies or simplifies a procedure.
Symbol Description The addition of either symbol to a Danger or Warning safety label indicates that an electrical hazard exists which will result in personal injury if the instructions are not followed. This is the safety alert symbol. It is used to alert you to personal injury hazards. Obey all safety messages that follow this symbol to avoid possible injury or death.

or

DANGER indicates an imminently hazardous situation, which, if not avoided, will result in death or serious injury.

WARNING indicates a potentially hazardous situation, which, if not avoided, can result in death or serious injury.

CAUTION indicates a potentially hazardous situation which, if not avoided, can result in minor or moderate injury.

NOTICE
NOTICE used without a safety alert symbol, indicates a potentially hazardous situation which, if not avoided, can result in property or equipment damage.

Please Note

Electrical equipment should be installed, operated, serviced, and maintained only by qualified personnel. No responsibility is assumed by Schneider Electric (Australia) Pty. Ltd. for any consequences arising out of the use of this material.

13

Safety Information

Before You Begin

CitectSCADA is a Supervisory Control and Data Acquisition (SCADA) solution. It facilitates the creation of software to manage and monitor industrial systems and processes. Due to CitectSCADA's central role in controlling systems and processes, you must appropriately design, commission, and test your CitectSCADA project before implementing it in an operational setting. Observe the following:

UNINTENDED EQUIPMENT OPERATION Do not use CitectSCADA or other SCADA software as a replacement for PLC-based control programs. SCADA software is not designed for direct, high-speed system control. Failure to follow these instructions can result in death, serious injury, or equipment damage.

LOSS OF CONTROL
l

l l l l

The designer of any control scheme must consider the potential failure modes of control paths and, for certain critical control functions, provide a means to achieve a safe state during and after a path failure. Examples of critical control functions are emergency stop and overtravel stop, power outage and restart. Separate or redundant control paths must be provided for critical control functions. System control paths may include communication links. Consideration must be given to the implications of unanticipated transmission delays or failures of the link. Observe all accident prevention regulations and local safety guidelines. 1 Each implementation of a control system created using CitectSCADA must be individually and thoroughly tested for proper operation before being placed into service.

Failure to follow these instructions can result in death, serious injury, or equipment damage.

1. For additional information, refer to NEMA ICS 1.1 (latest edition) "Safety Guidelines for the Application, Installation, and Maintenance of Solid State Control", and to NEMA ICS 7.1 (latest edition) "Safety Standards for Construction and Guide for Selection, Installation and Operation of Adjustable-Speed Drive Systems" or their equivalent governing your particular location.

14

Chapter 1: Introducing Cicode


Cicode is a programming language designed for use in CitectSCADA to monitor and control plant equipment. It is a structured language similar to Visual Basic or 'C'. You need no previous programming experience to use it. Using Cicode, you can access real-time data (variables) in the CitectSCADA project, and CitectSCADA facilities: variable tags, alarms, trends, reports, and so on. You can use Cicode to interface to various facilities on the computer, such as the operating system and communication ports. Cicode supports advanced features including pre-empted multitasking, multi threads, and remote procedure calls.

Getting Started
Use the following sections as a quick start to using Cicode in your CitectSCADA projects:
l

Cicode can be stored in procedures called functions for multiple reuse and centralized maintenance. For details, see Using Cicode Files. Cicode can be typed directly into command fields in online CitectSCADA forms. For details, see Using Cicode Commands. Cicode expressions are used to display and log data for monitoring and analysis, and to trigger various elements in your system, such as alarms, events, reports, and data logging. For information on using expressions, see Using Cicode Expressions. A Cicode function is a small program, a collection of statements, variables, operators, conditional executors, and other functions. A Cicode function can perform complex tasks and give you access to CitectSCADA graphics pages, alarms, trend data, and so on. For information on using functions, see the section titled Using Cicode Functions. Cicode has many pre-defined functions that perform a variety of tasks. For details on commonly used functions, see the section titled Working with Commonly Used Functions. Where system functionality cannot be achieved with built-in functions, you can write your own functions. See Writing Functions. The Cicode Editor is the code editing tool provided with CitectSCADA for the writing, editing and debugging of your Cicode code. For details, see The Cicode Editor.

See Also Performing Advanced Tasks Using Cicode Programming Standards

15

Chapter 1: Introducing Cicode

Using Cicode Files


You write your Cicode functions in Cicode source files, stored on your hard disk. Cicode files are identified by having a *.CI extension. To minimize potential future difficulties with maintaining your Cicode files, adopt a programming standard as early as possible (see Using Cicode Programming Standards). Maintain structured Cicode files, by logically grouping your Cicode functions within the files, and by choosing helpful descriptive names. For details about modular programming methods, see Modular Programming. For details about using and debugging Cicode functions, see Formatting Functions and Debugging Cicode respectively. When you compile your CitectSCADA project, the compiler reads the functions in your Cicode source files. Your system can then use these functions in the same way as it uses built-in functions. You can use as many Cicode files as required. Cicode files reside in the same directory as your CitectSCADA project. When you back up your project, the Cicode source files in the project directory are also backed up. See Also The Cicode Editor Creating Cicode files Opening Cicode files

Restricted Cicode Keywords


The following keywords have specific function in the operation of Cicode and should not be used for function names, variable names, etc. They are reserved for use as mathematical operators, condition executors, or as part of a function definition.
and bitand bitor bitxor case cicode CiVBA do global if int is mod module nop not quality real return select string then timestamp to

16

Chapter 1: Introducing Cicode

else end for function

object or private public

var while

If you use any of these words inappropriately in your Cicode, it will not be allowed by the compiler.

17

Chapter 1: Introducing Cicode

18

Part: 2
Using Cicode
This section contains information for Users and describes the following:
Using Cicode Commands Using Cicode Expressions Using Cicode Macros Converting and Formatting Cicode Variables Working with Operators Working with Conditional Executors Performing Advanced Tasks Editing and Debugging Code Using Cicode Programming Standards

Using Cicode Functions Working with Commonly Used Functions Writing Functions Using Variables Using Arrays

19

20

Chapter 2: Using Cicode Commands


Cicode commands extend the control element of a CitectSCADA control and monitoring system. You use commands to control your CitectSCADA system and therefore the processes in your plant. Each command has a mechanism to activate it. Commands can be issued manually, through an operator typing a key sequence, or by clicking on a button (or object) on a graphics page. You can also configure commands to execute automatically:
l l l l l

When an operator logs into or out of the runtime system When a graphics page is displayed or closed When an alarm is triggered In a report When an event is triggered

To define a Cicode command, you enter a statement (or group of statements) in the command field (Input category) for an object. Each statement in a command usually performs a single task, such as setting a variable to a value, calculating a value, displaying a message on the screen, or running a report. For information on using variables, see the section titled Using Variables. If you want to evaluate a condition, like checking the state of your plant rather than perform an action or command upon your plant, use an expression instead. See the section titled Using Cicode Expressions. See Also Using Cicode Programming Standards

Setting Variables
You can set a Variable in CitectSCADA within a Command field, an Expression field, or in a Cicode Function, by using the mathematical 'equals' sign ( = ) assignment operator. The value on the right is assigned (set) to the variable on the left, as shown in the following Cicode example :
<VAR_TAG> = Val;

where:

21

Chapter 2: Using Cicode Commands

<VAR_TAG>

is the name of the variable, and Val is the value being assigned to the variable.

Examples To set a digital variable (named BIT_1) to ON (1), use the command:
BIT_1 = 1;

To set a digital variable (named BIT_1) to OFF (0), use the command:
BIT_1 = 0;

To set a digital variable (named B1_PUMP_101_M) to ON (1), use the command:


B1_PUMP_101_M = 1;

To set a digital variable (named B1_PUMP_101_M) to OFF (0), use the command:
B1_PUMP_101_M = 0;

To set an analog variable (named B1_TIC_101_SP) to a value of ten (10), use the command:
B1_TIC_101_SP = 10;

You can copy a variable to another by assigning (setting) the value of a variable to the value of another variable, for example:
B1_PUMP_101_COUNT = B1_PUMP_101_CLIMIT;

The value of B1_PUMP_101_COUNT is set to the value of B1_PUMP_101_CLIMIT only when that command is issued. Note: The value of B1_PUMP_101_CLIMIT could change immediately after, but B1_ PUMP_101_COUNT remains unchanged and storing the original value, until this command is issued again.

Performing Calculations
Mathematical calculations can be performed between variables in a Cicode statement. For example:

22

Chapter 2: Using Cicode Commands

B1_TIC_101_SP = B1_TIC_101_PV + B1_TIC_102_PV - 100;

When this command is executed, the variable B1_TIC_101_SP is set to a value that is the sum of variables B1_TIC_101_PV and B1_TIC_102_PV minus 100.

Using Multiple Command Statements


A single statement in a Cicode command usually performs a single task. When the CitectSCADA runtime system is in operation, the statement executes whenever the command is requested. For example, if the statement is linked to a keyboard command, the task is performed when an operator presses the keyboard key defined as that command. To perform several tasks at the same time, you combine statements in a command property:
B1_PUMP_101_COUNT = B1_PUMP_101_CLIMIT; BATCH_NAME = "Bread"; B1_TIC_101_SP = 10;

The example above uses three statements, separated by semi-colons ( ; ). The first statement sets the variable B1_PUMP_101_COUNT to the value of the variable B1_PUMP_ 101_CLIMIT; the second statement sets the variable BATCH_NAME to the string "Bread"; and the third statement sets the variable B1_TIC_101_SP to 10. Each statement is executed in order. Note: Separate each statement in a command with a semicolon (;). If you don't, CitectSCADA will not recognize the end of a statement, and errors will result when the project is compiled. The number of statements you can enter in a command property is limited only by the size of the field. However, for clarity, don't use too many statements; enter the statements into an Include File or write a Cicode Function. You then refer to the include file or call the function in the command property field.

Using Include (Text) Files


There is a maximum number of characters that you can type in a Command or Expression field (usually 128). If you need to include many commands (or expressions) in a property field, you can define a separate include file that contains the commands or expressions.

23

Chapter 2: Using Cicode Commands

An include file is a separate and individual ASCII text file containing only one sequence of CitectSCADA commands or expressions that would otherwise be too long or complicated to type into the Command or Expression field within CitectSCADA. The include file name is entered instead, and the whole file is activated when called. When you compile the project, the commands (or expressions) in the include file are substituted for the property field, just as if you had typed them directly into the field. Use a text editor such as Notepad to create the text file. Enter the name of the include file (either upper- or lower case) in the property, in the following format:
@<filename>

where <filename> is any valid DOS file name. Be aware that the bracket characters (< >) are part of the syntax. You can use include files with many properties (except record names), but they are commonly used for commands and expressions, for example:
l l

Key sequence: F5 ENTER Command: @<setvars.cii>

In the above example, the setvars.cii include file would contain commands to be substituted for the Command property when you compile your project, for example:
PV12 = 10; PV22 = 20; PV13 = 15; PV23 = 59; PageDisplay("Mimic");

Notes
l l

Include files can not be used for genie properties. Do notconfuse include files and includedprojects. Include files contain CitectSCADA commands and/or expressions and are used as substitutions in a CitectSCADA command or expression property field. Included projects are separate (usually smaller) CitectSCADA projects that can be included in another CitectSCADA project so that they appear together as one project. The include file name can contain a maximum of 64 characters, or 253 characters including a path, and can consist of any characters other than the semi-colon (;) or the single quote('). There is no need to include the .cii extension, but if the file is not in the project directory, you need to enter the full path to the file. If the file is not in the project directory, it will not be backed up with the Backup facility.

24

Chapter 2: Using Cicode Commands

If modifying an Include file with the Cicode Editor, when you save your changes a .ci file extension will be appended to the file name. Change this to a .cii file extension in Windows Explorer.

Getting Runtime Operator Input


You can define a keyboard command as a key sequence, to perform a specific task each time the key sequence is pressed, for example:
l l

Key sequence: F2 ENTER Command: B1_TIC_101_SP = 10;

A key sequence can include provision for the operator to enter data. In the following example, the operator can set the value of the variable B1_TIC_101_SP:

The operator sends out the command by pressing the F2 key, up to three characters, and the Enter key. The three character sequence (identified by the three hash (#) characters) is called an argument. The argument is passed into the command (as Arg1) when the command is completed (when the operator presses the Enter key). The operator might type:

The value 123 is passed to the command, and B1_TIC_101_SP is set to 123. It is recommended that you use a specific key (for example, Enter) to signal the end of a key sequence. If, for example, you use the key sequence F2 ####, the operator needs to enter 4 characters for the command to be executed - CitectSCADA waits for the fourth character. But if you use F2 #### Enter, the operator can enter between one and four characters as necessary. The command executes as soon as the Enter key is pressed. To use more than one argument in a command, separate the arguments with commas ( , ):
l l

Key sequence: F2 ###,## Enter Command: B1_TIC_101_SP = Arg1; B1_TIC_101_PV = Arg2;

To set both variables, the operator can type:

25

Chapter 2: Using Cicode Commands

The values 123 and 18 are passed to the command. B1_TIC_101_SP is set to 123 and B1_TIC_101_PV is set to 18.

26

Chapter 3: Using Cicode Expressions


Cicode expressions are the basic elements of the Cicode language. An expression can be a constant, the value of a variable tag, or the result of a complex equation. You can use expressions to display and log data for monitoring and analysis, and to trigger various elements in your system, such as alarms, events, reports, and data logging. You can enter a Cicode expression in any CitectSCADA editor form or graphic object that contains an expression property. Unlike a command, an expression does not execute a specific task - it is evaluated. The evaluation process returns a value that you can use to display information on the screen (for example, as a bar graph) or to make decisions. The following expression returns a result of 12:
l

Numeric expression: 8 + 4

In the above example, the value of the expression is a constant (12) because the elements of the expression are constants (8 and 4). See Also Displaying Data Using Expressions Logging Expression Data Triggering Events Using Expressions Using Cicode Programming Standards Using Cicode Files

Displaying Data Using Expressions


In the following example, the value of the expression is the value of the variable B1_ TIC_101_PV. As its value changes, the value of the expression also changes. You can use this expression to display a number on a graphics page.
l

Numeric expression: B1_TIC_101_PV

As the expression changes, the number also changes. Expressions can also include mathematical calculations. For example, you can add two variables together and display the combined total:
l

Numeric expression: B1_TIC_101_PV + B1_TIC_102_PV

In this case, the value of the expression is the combined total. As the value of one variable (or both variables) changes, the value of the expression changes.

27

Chapter 3: Using Cicode Expressions

See Also Using Cicode Expressions

Decision-Making
Some expressions return only one of two logical values, either TRUE(1) or FALSE(0). You can use these expressions to make decisions, and to perform one of two actions, depending on whether the return value is TRUE or FALSE. For example, you can configure a text object with appearance as follows:
l l l

On text when: B1_PUMP_102_CMD ON text: Pump Running OFF text: "Pump Stopped"

In this example, if B1_PUMP_102_CMD is a digital tag (variable), it can only exist in one of two states (0 or 1). When your system is running and the value of B1_PUMP_ 102_CMD changes to 1, the expression returns TRUE and the message "Pump Running" is displayed. When the value changes to 0, the expression returns FALSE and the message "Pump Stopped" is displayed. See Also Using Cicode Expressions

Logging Expression Data


You can log the value of an expression to a file for trending, by defining it as a trend tag:
Trend Tag Name Expression File Name B1_TIC B1_TIC_101_PV + B1_TIC_102_PV [log]:B1_TIC

When the system is running, the value of the expression B1_TIC_101_PV + B1_TIC_102_ PV is logged to the file [log]:B1_TIC. See Also Using Cicode Expressions

28

Chapter 3: Using Cicode Expressions

Triggering Events Using Expressions


Logical expressions - those that return either TRUE (1) or FALSE (0) -can be used as triggers. For example, you might need to log the expression in the above example only when an associated pump is running.
Trend Tag Name Expression File Name Trigger B1_TIC B1_TIC_101_PV + B1_TIC_102_PV [log]:B1_TIC B1_PUMP_101_CMD

In this example, the trigger is the expression B1_PUMP_101_CMD (a digital variable tag). If the pump is ON, the result of the trigger is TRUE, and the value of the expression (B1_TIC_101_PV + B1_TIC_102_PV) is logged. If the pump is OFF, the result is FALSE, and logging ceases. See Also Using Cicode Expressions

29

Chapter 3: Using Cicode Expressions

30

Chapter 4: Using Cicode Functions


A Cicode function can perform more complex tasks than a simple command or expression allows. Functions give you access to CitectSCADA graphics pages, alarms, trend data, and so on. CitectSCADA has several hundred built-in functions that display pages, acknowledge alarms, make calculations, and so on. You can also write your own functions to meet your specific needs. See Also Working with Commonly Used Functions Writing Functions

Calling Functions from Commands and Expressions


You can call a function by entering its name in any command or expression property. The syntax is as follows:
Command FunctionName ( Arg1, Arg2, ... );

where: FunctionName is the name of the function Arg1, Arg2, ... are the arguments you pass to the function

Triggering Functions via Runtime Operator Input


In the following command, the PageNext() function displays the next graphics page when the Page Down keyboard key is pressed by the Runtime operator.
Key Sequence Command Page_Down PageNext();

31

Chapter 4: Using Cicode Functions

Evaluating Functions
You can use a function in any expression. For example, the AlarmActive() function returns TRUE (1) if any alarms are active, and FALSE (0) if no alarms are active. In the following text object, either "Alarms Active" or "No Alarms Active" is displayed, depending on the return value of the expression.
ON text when ON Text OFF Text AlarmActive(0) "Alarms Active" "No Alarms Active"

Note: Functions return a value that indicates the success of the function, or provides information on an error that has occurred. In many cases (for example, when used in a command) the return value can be ignored. You need to use the parentheses () in the function name, even if the function uses no arguments. Function names are not case-sensitive: PageNext(), pagenext() and PAGENEXT() call the same function.

Combining Functions with Other Statements


In expressions and commands you can use functions alone or in combination with other functions, operators, and so on. The following example uses three statements:
Command Report("Shift"); B1_TIC_101_PV = 10; PageDisplay("Boiler 1")

Each statement is executed in order. The "Shift" report is started first, the variable B1_ TIC_101_PV is set to 10 next, and finally, the "Boiler 1" page is displayed. Functions combine with operators and conditional executors to give you specific control over your processes, for example, you can test for abnormal operating conditions and act on them.

32

Chapter 4: Using Cicode Functions

Passing Data to Functions (Arguments)


The parentheses ( ) in the function name identify the statement as a function and enclose its arguments. Arguments are the values or variables that are passed into the function when it executes. Note: Some functions (such as PageNext()) have no arguments. However you need to include the parentheses ( ) or CitectSCADA will not recognize that it is a function, and an error could result when the project is compiled.

Using String Arguments


Functions can require several arguments or, as in the following example, a single argument:
Command PageDisplay("Boiler 1");

This function displays the graphics page called "Boiler 1". Be aware that when you pass a string to a function, you need to always enclose the string in double quotes. You can use the PageDisplay() function to display any graphics page in your system - in each case, only the argument changes. For example, the following command displays the graphics page "Boiler 2":
Command PageDisplay("Boiler 2");

You can use the Report() function to run a report (for example, the "Shift" report) when the command executes:
Command Report("Shift");

The following example uses the Prompt() function to display the message "Press F1 for Help" on the screen when the command executes:
Command Prompt("Press F1 for Help");

33

Chapter 4: Using Cicode Functions

String assignment
You can also assign string variables in commands. For example, if BATCH_NAME is a variable tag defined as a string data type, you can use the following command to set the tag to the value "Bread":
BATCH_NAME = "Bread";

Note: you need to enclose a string in double quotation marks ( " ).

Using the Caret Escape Sequence Character


The caret character ( ^ ) signifies a special instruction in Cicode, called an escape sequence, primarily used in the formatting of text strings. Escape sequences include formatting instructions such as new line, form feed, carriage return, backspace, horizontal and vertical tab-spaces, single and double quote characters, the caret character, and hexadecimal numbers. Strings are commonly represented in Cicode between double quote characters ( " ) known as delimiters. If you want the string to contain a double quote character itself as part of the string, you need to precede the double quote character with the caret character ( ^" ) so that Cicode doesn't interpret the double quote in the string as the delimiter indicating the end of the string. The caret character is interpreted as a special instruction, and together with the characters immediately following it, are treated as an escape sequence instruction. See the section titled Formatting Text Strings for the list of escape sequences used in Cicode. In the following Cicode example, both of these message functions will display the following message.
Message("Info", "P29 has a ^"thermal overload^".", 0); sCurrentAlmText = "Thermal Overload"; Message("Info", "P29 has a ^""+sCurrentAlmText+"^".", 0);

34

Chapter 4: Using Cicode Functions

Using Multiple Arguments


Some functions require several arguments. You need to list arguments between the parentheses, and separate each argument with a comma ( , ) as in the following example:
Command Login("Manager", "ABC");

The order of the arguments affects the operation of any function. The Login() function logs a user into your runtime system. The first argument ( "Manager" ) indicates the name of the user, and the second argument ( "ABC" ) is the user's password. If you reverse the order of the arguments, the function would attempt to login a user called "ABC" - if a user by this name does not exist, an error message displays.

Using Numeric Arguments


You can pass numbers (integers and floating point numbers) directly to a function, for example:
Command AlarmAck(2, 35);

Using Variable Arguments


When variables (such as real-time data) are used as arguments, the value of the variable is passed, not the variable itself. The following example uses the DspStr() function to display the value of a process variable at AN25:
Command DspStr(25, "TextFont", B1_TIC_101_PV);

In this instance, the value of B1_TIC_101_PV displays. If it is a real-time variable, the number that displays depends on its value at the time. Note: If you use double quotes around variables, for example, "B1_TIC_101_PV", the text string B1_TIC_101_PV displays, rather than the value of the variable.

35

Chapter 4: Using Cicode Functions

Using Operator Input in Functions


You can pass operator input to functions at runtime. For example, you can define a System Keyboard Command to let the operator select a page:
Key Sequence Command F10 ######## Enter PageDisplay(Arg1);

When the command executes, the page name is passed to the function as Arg1. The operator can then display any page, for example:

Returning Data from Functions


Functions return data to the calling statement (a command or expression). Some functions simply return a value that indicates whether the function was successful. For example, both the PageNext() and PageDisplay() functions return 0 (zero) if the page displays successfully, otherwise they return an error number. For a large number of simple applications, you can ignore this return value. Some functions return data that you can use in an expression or command. For example, the Date() function returns the current date as a string. To display the current date on a graphics page, use the following expression in a text object display value property:
Numeric expression Date();

The following example shows an entry command event for a graphics page, using a combination of two functions. The FullName() function returns the name of the user who is currently logged in to the run-time system, passing this name to the calling function, Prompt(). When the page is opened, a welcome message displays in the prompt line.
On page entry Prompt("Hello, " + FullName())

For example, if the current user is John Citizen, the message "Hello, John Citizen" displays.

36

Chapter 5: Working with Commonly Used Functions


Cicode has many functions that perform a variety of tasks. Many of these are used for building complex CitectSCADA systems. The functions you will often use are divided into six categories:
l l l l l l

Alarm Functions Page Functions Keyboard Functions Report Functions Time/date Functions Miscellaneous Functions

See Also Functions Reference

Alarm Functions
You can use alarm functions to display alarms and their related alarm help pages, and to acknowledge, disable, and enable alarms. You can assign a privilege to each command that uses an alarm function, so that only an operator with the appropriate privilege can perform these commands. However, you should assign privileges to commands only if you have not assigned privileges to individual alarms.
l

AlarmAck: Acknowledges an alarm. The alarm where the cursor is positioned (when the command is executed) is acknowledged. You can also use this function to acknowledge multiple alarms. AlarmComment: Adds a comment to the alarm summary entry at run time. The comment is added to the alarm where the cursor is positioned when the command is executed. A keyboard argument passes the comment into the function. Verify that the length of the comment does not exceed the length of the argument, or an error results. AlarmDisable: Disables an alarm. The alarm where the cursor is positioned (when the command is executed) is disabled. You can also use this function to disable multiple alarms.

37

Chapter 5: Working with Commonly Used Functions

AlarmEnable: Enables an alarm. The alarm where the cursor is positioned (when the command is executed) is enabled. You can also use this function to enable multiple alarms. AlarmHelp: Displays an alarm help page for the alarm. Each alarm in your system can have an associated help page. The help page for the alarm at the position of the cursor (when the command is executed) is displayed.

Page Functions
With the page functions, you can display your graphics pages and the standard alarm pages. Note: The following page functions are not supported in the server process in a multiprocessor environment. Calling page functions from the server process results in a hardware alarm being raised. PageAlarm: Displays current alarms on the alarm page configured in the project. PageDisabled: Displays disabled alarms on the alarm page configured in the project. PageDisplay: Displays a new page on the screen. The Page name or number is required as an argument. (Use the PageLast() function to go back to the last page - the page that this new page replaced). PageFile: Displays a file on the file page configured in the project. PageGoto: Displays a new page on the screen. This function is similar to the PageDisplay() function, except that if PageLast() is called, it does not return to the last page. PageHardware: Displays hardware alarms on the alarm page configured in the project. PageLast: Displays the graphics page that was displayed before the current one. You can use this function to 'step back' through the last ten pages. PageNext: Displays the next graphics page (defined in the Next Page property of the Pages form). PagePrev: Displays the previous graphics page (defined in the Prev Page property of the Pages form). PageSOE: Displays a category of sequence of events (SOE) entries on the SOE page. PageSummary: Displays summary alarm information on the alarm page configured in the project. PageTrend: Displays a standard trend page.

l l l

l l

l l

38

Chapter 5: Working with Commonly Used Functions

Keyboard Functions
Keyboard functions control the processing of keyboard entries and the movement of the keyboard cursor on the graphics page.
l

KeyBs: Backspaces (removes) the last key from the key command line. Use this function with a 'Hotkey' command. It is normally used to erase keyboard characters during runtime command input. KeyDown: Moves the cursor down the page to the closest animation point number (AN). KeyLeft: Moves the cursor left (across the page) to the closest animation point number (AN). KeyRight: Moves the cursor right (across the page) to the closest animation point number (AN). KeyUp: Moves the cursor up the page to the closest animation point number (AN).

Report Functions
To run a report by operator action, use the following function:
l

Report: Runs the report on the report server.

Time/date Functions
The following functions return the current date and time:
l l

Date: Returns the current date as a string. Time: Returns the current time as a string.

Miscellaneous Functions
l l l

Beep: Beeps the speaker on the CitectSCADA computer. FullName: Returns the full name of the user who is currently logged in to the system. InfoForm: Displays the animation information form. This form displays the real-time data that is controlling the current animation. Login: Allows a user access to the CitectSCADA system. LoginForm: Displays a dialog box to allow a user to log in to the system. Logout: Logs the current user out of the CitectSCADA system.

l l l

39

Chapter 5: Working with Commonly Used Functions

l l

Name: Returns the user name of the user who is currently logged in to the system. Prompt: Displays a message on the screen. The message String is supplied as an argument to the function. Shutdown: Terminates CitectSCADA. Use this function, or the ShutdownForm() function, to shut down your system. Otherwise buffered data may be lost. ShutdownForm: Displays a dialog box to allow a user to shut down your CitectSCADA system.

40

Chapter 6: Writing Functions


CitectSCADA is supplied with over 600 built-in functions. One of these functions (or several functions in combination) can usually perform the required tasks in your system. However, where system functionality cannot be achieved with built-in functions, you can write your own functions. A Cicode function is a small program: a collection of statements, variables, operators, conditional executors, and other functions. While it is not necessary to be an experienced programmer to write simple Cicode functions, it is strongly recommended not to attempt to write large, complex functions unless you are familiar with computer programming, and have experience with Cicode. Functions are equivalent to the subroutines of BASIC and assembly language, and the subroutines and functions used in Pascal and C. Note: The Cicode Editor is designed specifically for editing and debugging Cicode functions. See Also The Cicode Editor Using Cicode Files

Cicode Function Structure


A function in Cicode can be described as a collection or list of sequential statements that CitectSCADA can perform (execute) in the logical order that they exist within the function. A Cicode function starts with the FUNCTION statement and finishes with the END statement. Every statement that lie between the FUNCTION and END statements, will be executed by the function, when called to do so. A typical Cicode function is structured like the following example:
FUNCTION FunctionName ( ) ! The exclamation point indicates that the rest of this line contains a comment. ! Further Cicode statements go here, between the function name and the END. END

41

Chapter 6: Writing Functions

The line immediately following the FUNCTION statement, contains the name of the function, which is used to identify the function to CitectSCADA. This name is referred to when the function is called upon (called) to be executed (perform the statements it contains) by some other event, action, or function in CitectSCADA. Note: Functions can contain statements that call other functions. These functions are then executed before returning to the rest of the statements within the calling function. The function name has to end with parentheses ( ), which may or may not contain one or more arguments required by the function. Arguments are explained in the section titled Function Argument Structure. Every line between the function name line and the END statement line contain the statements that will be executed when the function is called in CitectSCADA. These statements are executed one at a time in logical order from top to bottom within the function. For details about function structure, see Formatting Functions. For details about Cicode function syntax, see Following Cicode Syntax. For details about using comments in Cicode and in Cicode functions, see Using Comments in Cicode.

Function Uses
Cicode functions can have many purposes. Quite often, functions are used to store a common set of commands or statements that would otherwise require repetitious typing and messy command or expression fields. Some functions are simple, created to avoid a long command or expression. For example, the following command increments the variable tag COUNTER:
Command IF COUNTER < 100 THEN COUNTER = COUNTER + 1; ELSE COUNTER = 0; END;

This command would be easier to use (and re-use) if it was written as a function that can be called in the command:
Command IncCounter ( );

42

Chapter 6: Writing Functions

To be able to use the function like this, you need to write it in a Cicode file, and declare it with the FUNCTION keyword:
FUNCTION IncCounter ( ) IF COUNTER < 100 THEN COUNTER = COUNTER + 1; ELSE COUNTER = 0; END END

Be aware that the indented code is identical in functionality to the long command above. By placing the command code inside a function, and using the function name in the command field as in the previous example, this function need only to be typed once. It can then be called any number of times, from anywhere in CitectSCADA that requires this functionality. Because the code exists in the one location, rather than repeated wherever needed (in potentially many places), it can be easily maintained (altered if necessary).

Writing Groups of Functions


To perform complex tasks you need careful design. Large, complex functions are not only more difficult to understand and debug than simple functions, but they can also hide tasks that are common to other activities. Cicode functions allow a modular approach - complex tasks can be organized into small functions, each with a single, clear purpose. These small functions can then be called by other functions, or called directly in commands and expressions. In fact, any function can call - and be called by - any other function. For example, you might need to write a set of functions for handling alarms. To perform any action on an alarm, you first need to know which alarm. You would identify the alarm in a separate function, and call this function from the other functions.

Cicode Function Libraries


Cicode functions are stored within Cicode files. You can use a separate file for each stand-alone function, or group several functions together into a common file. For easy maintenance, store functions that perform related tasks in the same file - for example, store functions that act on alarm data in an Alarms.CI file. Note: Every Cicode file in your project directory will be included when you compile

43

Chapter 6: Writing Functions

your project.

Creating a Function Outline


First, define the purpose of the function group, and create an outline of the tasks to be performed. The following example shows an outline for a group of functions that change the threshold values of analog alarms during run time. The outline describes the workings of the function group, and is written in pseudocode (also called Program Design Language).
/* This file contains functions to allow the operator to make runtime changes to Analog Alarm thresholds. This file has 4 functions. The master function calls the other functions. ChangeAnalogAlarmThresholds ( ) This calls in turn: 1:GetVariableTag ( ) Argument: cursor position Return: name of variable tag at cursor 2:GetAlarmThresholds ( ) Argument: tag name Return: threshold value of alarm 3:DisplayAlarmThresholds ( ) Argument: threshold value of alarm Displays threshold values in prompt line Return: success or error code */

Pseudocode
The pseudocode above is a Cicode comment, enclosed between the comment markers /* and */, and is ignored by the compiler. With pseudocode, you can get the logic of the function correct in a more readable structure, before you write it in Cicode syntax, leaving the pseudocode within the finished code as comments. It is good practice to use comments as file headers at the start of each Cicode file, to describe the functions in the file - their common purpose, a broad description of how they achieve that purpose, special conditions for using them, and so on. You can also use the header to record maintenance details on the file, such as its version number and date of revision. For example:

44

Chapter 6: Writing Functions

/* ** ** ** ** ** ** ** ** ** ** */

FILE: AUTHOR: DATE: REVISION:

Recipe Download.Ci AJ Smith March 2008 1.0 for CitectSCADA v7.1

This file contains functions to allow the operator to load the recipe data from the SQL server to the PLC.

Following the file header are the functions in series:


/* ** Main function */ FUNCTION RecipeDownload ( ) ! {body of function} ! . END /* ** Function to open the SQL connection. */ FUNCTION RecipeConnectSQL ( ) ! {body of function} ! . END ! (and so on)

Using Comments in Cicode


It is good programming practice to include comments in your Cicode files. Comments allow you to quickly understand how a function works next time you (or another designer) need to modify it. The Cicode compiler recognizes the following single line, C style, and C++ style comments:
! A single line comment WHILE DevNext ( hDev ) DO Counter = Counter + 1 ; ! An in-line comment END /* A block comment is a C-style comment, and can extend over several lines. Block comments need to finish with a delimiter, but delimiters at the

45

Chapter 6: Writing Functions

start of each line are optional only. */ // A double-slash comment is a C++ style comment, for example: Variable = 42; // This is a comment

Single line ( ! ) and C++ style ( // ) comments can have a line of their own, where they refer to the block of statements either before or after it. It is good practice to set a convention for these comments. These comments can also be on the same line as a statement, to explain that statement only. Any characters after the ! or // (until the end of the line) are ignored by the compiler. Block (C style) comments begin with /* and end with */. These C style comments need no punctuation between the delimiters.

Using Comments for Debugging Functions


You can use comments to help with the debugging of your functions. You can use comments to temporarily have the compiler ignore blocks of statements by changing them to comments. C style and C++ style comments can be nested, for example.
FUNCTION IncCounter ( ) IF COUNTER < 100 THEN COUNTER = COUNTER + 1 ; /* ELSE // Comment about statement COUNTER = 0; // Another comment */ END END

The complete ELSE condition of the IF conditional executor will be ignored (and not execute) so long as the block comment markers are used in this example. Note: The inline ( // ) comments have no effect within the block ( /* and */ ) comments (as the whole section is now one big comment), and should remain unchanged, so that when you do remove the block comments, the inline comments will become effective again.

Tag Reference /TagReadEx() behavior in Cicode Expressions


The following table describes the tag reference and TagReadEx() behavior in a Cicode expression if the quality of the tag is BAD:

46

Chapter 6: Writing Functions

Tag Reference / TagReadEx syntax Tag1

Error Mode/Citect.ini settings ErrSet(0) [Code]HaltOnInvalidTagData = 0 ErrSet(0) [Code]HaltOnError = 0 ErrSet(0) [Code]HaltOnInvalidTagData = 1 ErrSet(0) [Code]HaltOnError = 1 ErrSet(1)

Cicode Expression behavior Tag ref returns a BAD quality value, Cicode expression continues, Error is set.

TagReadEx(Tag1)

Function returns a BAD quality value, Cicode expression continues, Error is set.

Tag1

Tag ref returns a BAD quality value, Cicode expression stops.

TagReadEx(Tag1)

Function returns a BAD quality value, Cicode expression stops.

Tag1

Tag ref returns a BAD quality value, Cicode expression continues, Error is set. Function returns a BAD quality value, Cicode expression continues, Error is set Tag ref returns a GOOD quality value, Cicode expression continues, No error is set. Function returns a GOOD quality value, Cicode expression continues, No error is set.

TagReadEx(Tag1)

ErrSet(1)

Tag1.V

ErrSet(0) or ErrSet (1) ErrSet(0) or ErrSet (1)

TagReadEx (Tag1.V)

See Also TagReadEx() Tag Functions

Following Cicode Syntax


Some programming languages have strict rules about how the code needs to be formatted, including the indenting and positioning of the code structure. Cicode has no indenting or positioning requirements, allowing you to design your own format - provided only that you follow the correct syntax order for each statement. However, it is a good idea to be consistent with your programming structure and layout, so that it can be easily read and understood. For details about programming standards, see the section titled Using Cicode Programming Standards, which includes sections on:
l l

Standards for constants, variable tags, and labels Standards variables: declaration, scope, and naming

47

Chapter 6: Writing Functions

l l l

Standards for functions: naming , file headers, headers Formatting of: declarations, statements, expressions, and functions Use of comments

For information on problem solving, see the sections onModular Programming, Defensive Programming, Function Error handling, or Debugging Cicode. The following is an example of a simple Cicode function:
/* This function is called from a keyboard command. The operator presses the key and enters the name of the page to be displayed. If the page cannot be displayed, an error message is displayed at the prompt AN. */ INT FUNCTION MyPageDisplay ( STRING sPage ) ! pass in the name of the page to be displayed ! declare a local integer to hold the results of the pagedisplay function INT Status; ! call the page Cicode pagedisplay function and store the result Status = PageDisplay ( sPage ) ; ! determine if the page display was successful IF Status < > 0 THEN ! error was detected ! display an error message at the prompt AN DspError ( "Cannot Display " + sPage ) ; END ! return the status to the caller RETURN Status; END

The rules for formatting statements in Cicode functions are simple, and help the compiler in interpreting your code. It is good practice to use white space to make your code more readable. In the example above, the code between the FUNCTION and END statements is indented, and the statement within the IF THEN conditional executor is further indented to make the conditions and actions clear. Develop a pattern of indentation - and stick to it. Extra blank lines in the code make it easier to read (and understand).

Cicode Function Syntax


Note: In the following function syntax example: Every placeholder shown inside arrow brackets ( <placeholder> ) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown

48

Chapter 6: Writing Functions

here only for your information.


l

Statements shown between square brackets ( [ ] ) are optional. The square brackets should not be included in the statement, and are shown here only for your information.

Cicode functions have the following syntax:


[ <Scope> ] [ <ReturnDataType> ] FUNCTION <FunctionName> ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; RETURN <ReturnValue> ; END

where:
l

<Scope> = Scope Statement: optional, PRIVATE or PUBLIC, default PUBLIC, no semicolon. See the section titled Function Scope. <ReturnDataType> = Return Data Type Statement: optional and one of INT, REAL, STRING, OR OBJECT. No default, no semicolon. If no return type is declared, the function cannot return any data. See the section titled Declaring the Return Data Type. FUNCTION = FUNCTION Statement: required, indicates the start of the function, keyword, no semicolon. See the section titled Declaring Functions. <FunctionName> = Name statement: required, up to 32 ASCII text characters, case insensitive, no spaces, no reserved words, no default, no semicolon. See the section titled Naming Functions. ( <Arguments> ) = Argument statement: surrounding brackets required even if no arguments used, if more than one argument - each need to be separated by a comma, can contain constants or variables of INT or REAL or STRING or QUALITY or TIMESTAMP data type, default can be defined in declaration, can be spread over several lines to aid readability, no semicolon. See the section titled Function Argument Structure. <Statement> = Executable Statement: required, one or more executable statements that perform some action in CitectSCADA, often used to manipulate data passed into the function as arguments, semicolon required. RETURN = RETURN Statement: optional, used to instruct Cicode to return a value to the caller of the function - usually a manipulated result using the arguments passed in to the function by the caller, need to be followed by Return Value Statement, keyword, no semicolon. <ReturnValue> = Return Value Statement; required if RETURN Statement used in function, need to be either a constant or a variable, the data type need to have been

49

Chapter 6: Writing Functions

previously declared in the function Return Data Type Statement - or does not return a value, semicolon required. See the section titled Returning Values from Functions.
l

END = END Statement: required, indicates the end of the function, keyword, no semicolon. See the section titled Declaring Functions.

End of line markers


Most statements within the function are separated by semicolons ( ; ) but some exceptions exist. The FUNCTION and END Statements (the start and end of the function) have no semicolons, nor does the Scope or Return Data Type Statements, nor any statement that ends with a reserved word. Where a statement is split over several lines (for example, within the IF THEN conditional executor), each line ends with a semicolon - unless it ends in a reserved word.

Function Scope
The optional Scope Statement of a function (if used), precedes all other statements of a function declaration in Cicode, including the FUNCTION Statement. The scope of a function can be either PRIVATE or PUBLIC, and is declared public by default. That is, if no Scope Statement is declared, the function will have public scope. Both PRIVATE and PUBLIC are Cicode keywords and as such, are reserved. A private scope function is only accessible (can be called) within the file in which it is declared. Public scope functions can be shared across Cicode files, and can be called from pages and CitectSCADA databases (for example, Alarm.dbf). Because functions are public by default, to make a function public requires no specific declaration. To make a function private however, you need to prefix the FUNCTION Statement with the word PRIVATE.
PRIVATE FUNCTION FunctionName ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; END

50

Chapter 6: Writing Functions

Declaring the Return Data Type


For information about the RETURN Statement, see the section titled Returning Values from Functions. The optional Return Data Type Statement of a function (if used), follows the optional Scope Statement (if used), and precedes the FUNCTION Statement declaration in Cicode. The return data type of a function can be only one of six possible data types: INT (32 bits), REAL (64 bits), STRING (255 bytes), OBJECT (32 bits), QUALITY or TIMESTAMP (64 bits). If no Return Data Type Statement is declared, the function will not be able to return any type of data. INT, REAL, STRING, OBJECT, QUALITY and TIMESTAMP are Cicode keywords and as such, are reserved. Note: In the following function syntax example, every placeholder shown inside arrow brackets ( <placeholder> ) should be replaced in the actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown only for your information. To declare the data type that will be returned to the calling code, prefix the FUNCTION Statement with one of the Cicode data type keywords, in the <ReturnDataType> placeholder in the following example.
<ReturnDataType> FUNCTION FunctionName ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; END

The following example returns an integer of value 5:


INT FUNCTION FunctionName ( <Arguments> ) <Statement> ; INT Status = 5; <Statement> ; RETURN Status; END

51

Chapter 6: Writing Functions

If the RETURN Statement within the function encounters a different data type to that declared in the return data type statement, the value is converted to the declared return data type. In the example below, the variable Status is declared as a real number within the function. However, Status is converted to an integer when it is returned to the caller, because the data type of the return was declared as an integer type in the return data type statement:
INT ! declare return value as integer FUNCTION FunctionName ( <Arguments> ) <Statement> ; REAL Status = 5; ! declare variable as a REAL number <Statement> ; RETURN Status; ! returned as an integer number END

If you omit the return data type, the function does not return a value.

Declaring Functions
The required FUNCTION Statement follows the optional Scope Statement (if used) and the optional Return Data Type Statement (if used), and precedes any other statements of a function declaration in Cicode. Everything between it and the END Statement, contains the function. Both FUNCTION and END are Cicode keywords and, as such, are reserved. You declare the start of a function with the FUNCTION Statement, and declare the end of a function with the END Statement:
FUNCTION <FunctionName> ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; END

The FUNCTION Statement needs to be followed by the Name Statement, then the Argument Statement, before any code statements that will be processed by the function. For information on the Name and Argument Statements, see the sections titled Naming Arguments and Function Argument Structure. The code (as represented by the <Statement> placeholders) located between the FUNCTION and END Statements, will be executed (processed by the function) when called to do so.

52

Chapter 6: Writing Functions

Functions can execute a large variety of statements, and are commonly used to process and manipulate data, including the arguments passed when the function was called, plant-floor and other CitectSCADA data, Windows data, and so on. CitectSCADA provides many built-in functions. For more information, see the section titled Working with Commonly Used Functions.

Naming Functions
The required name statement follows the FUNCTION Statement and precedes the arguments statement in a CitectSCADA function. The function name is used elsewhere in CitectSCADA to activate (call) the function to have it perform the statements it contains. Replace the <FunctionName> placeholder in the following function example with an appropriate name for your function. See the section Function Naming Standards for details.
FUNCTION <FunctionName> ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; END

You can use up to 32 ASCII text characters to name your functions. You can use any valid name except for a reserved word. The case is ignored by the CitectSCADA compiler, so you can use upper and lower case to make your names clear. For example, MixerRoomPageDisplay is easier to read than mixerroompagedisplay or MIXERROOMPAGEDISPLAY.
FUNCTION MixerRoomPageDisplay ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; END

Your functions take precedence over any other entity in CitectSCADA with the same name:
l

Variable tags. When you call a function by the same name as a variable tag, the function has precedence. The variable tag can not be referred to because the function executes each time the name is used. Built-in functions. You can give your function the same name as any built-in Cicode function. Your function takes precedence over the built-in function - the built-in function cannot be called. Because built-in Cicode functions cannot be changed, this

53

Chapter 6: Writing Functions

provides a method of 'modifying' any built-in function to suit an application. For example, you might want to display the message "Press F1 for Help" whenever you display a page. You could simply write a new function called PageDisplay ( ). The body of the function would be the statements that display the page and prompt message:
Prompt ( "Press F1 for Help" ) ;PageDisplay ( <Arguments> ) ;

Your function is invoked whenever you use the function name in CitectSCADA.

Function Argument Structure


The optional Arguments Statement follows the required FUNCTION Statement and precedes the executable statements of a function in Cicode. Note: The maximum number of arguments you can have in a function is 128. When you call a function, you can pass one or more arguments to the function, enclosed within the parentheses ( ) located after the function name statement. Replace the <Arguments> placeholder in the following function example with your Argument Statement.
FUNCTION FunctionName ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; END

For your function to perform tasks with data, it requires accessibility to the data. One way to achieve this, is to pass the data directly to the function when the function is being called. To enable this facility, Cicode utilizes arguments in its function structure. An argument in Cicode is simply a variable that exists in memory only as long as its function is processing data, so the scope of an argument is limited to be local only to the function. Arguments cannot be arrays. Arguments are variables that are processed within the body of the function only. You cannot use an argument outside of the function that declares it. As arguments are variables used solely within functions, they needs to be declared just as you would otherwise declare a variable in Cicode. See the section titled Declaring Variable Properties. An argument declaration requires a data type, a unique name, and may contain an initial value which also behaves as the default value for the argument. Notes: In the following function syntax example:

54

Chapter 6: Writing Functions

Every placeholder shown inside arrow brackets ( <placeholder> ) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information. Statements shown between square brackets ( [ ] ) are optional. The square brackets should not be included in the statement, and are shown here only for your information.

Cicode function argument statements have the following syntax:


<ArgumentDataType> <ArgumentName> [ = <InitialDefaultValue> ]

where:
l

<ArgumentDataType> = Argument Data Type Statement: required, INT or REAL or STRING. See the section titled Declaring Argument Data Type. <ArgumentName> = Argument Name Statement: required, up to 32 ASCII text characters, case insensitive, no spaces, no reserved words. See the section titled Naming Arguments. <InitialDefaultValue> = Argument Initialization Statement: optional, preceded by equals ( = ) assignment operator, a value to assign to the argument variable when first initialized, needs to be the same data type as that declared in the argument <ArgumentDataType> parameter, defaults to this value if no value passed in for this argument when the function was called. See the section titled Setting Default Values for Arguments.

The Argument Statement in a Cicode function can have only one set of surrounding parentheses ( ), even if no arguments are declared in the function. If more than one argument is used in the function, each needs to also be separated by a comma. Argument Statements can be separated over several lines to aid in their readability. When you call a function, the arguments you pass to it are used within the function to produce a resultant action or return a value. For information on passing data to functions, see the section titled Passing Data to Functions (Arguments). For information on returning results from functions, see the section titled Returning Data from Functions. Arguments are used in the function and referred to by their names. For instance, if we name a function AddTwoIntegers, and declare two integers as arguments naming them FirstInteger and SecondInteger respectively, we would end up with a sample function that looks like the following:

55

Chapter 6: Writing Functions

INT FUNCTION AddTwoIntegers ( INT FirstInteger, INT SecondInteger ) INT Solution ; Solution = FirstInteger + SecondInteger ; RETURN Solution ; END

In this example, the function would accept any two integer values as its arguments, add them together, and return them to the caller as one integer value equal to the summed total of the arguments values passed into the function. This functionality of passing values into a function as arguments, manipulating the values in some way, then being able to return the resultant value, is what makes functions potentially very powerful and time saving. The code only needs to written once in the function, and can be utilized any number of times from any number of locations in CitectSCADA. Write once, use many.

Declaring Argument Data Type


If an argument is listed in a Cicode function declaration, the Argument Data Type Statement is required, and is listed first before the required Argument Name Statement and the optional Argument Initialisation Statement. The argument data type of a function can be only one of six possible data types: INT (32 bits), REAL (32 bits), STRING (255 bytes), OBJECT (32 bits), QUALITY or TIMESTAMP (64 bits). INT, REAL, STRING, OBJECT, QUALITY and TIMESTAMP are Cicode keywords and as such, are reserved. Note: In the following function syntax example: - Every placeholder shown inside arrow brackets ( <placeholder> ) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information. - Statements shown between square brackets ( [ ] ) are optional. The square brackets should not be included in the statement, and are shown here only for your information. To declare the argument data type that will be used in the function, you need to prefix the Argument Name Statement with one of the Cicode data type keywords, in the <ArgumentDataType> placeholder in the following example.

56

Chapter 6: Writing Functions

FUNCTION FunctionName ( <ArgumentDataType> <ArgumentName> [ = <InitialDefaultValue> ] ) <Statement> ; <Statement> ; <Statement> ; END

The Argument Statement in a Cicode function needs to have only one set of surrounding parentheses ( ) brackets, even if no arguments are declared in the function. If more than one argument is used in the function, each needs to also be separated by a comma. Argument Statements can be separated over several lines to aid in their readability.

Naming Arguments
If an argument is listed in a Cicode function declaration, the Argument Name Statement is required, and is listed second, after the required Argument Data Type Statement, and before the optional Argument Initialization Statement. The argument name is used only within the function to refer to the argument value that was passed into the function when the function was called. The name of the argument variable should be used in the executable statements of the function in every place where you want the argument variable to be used by the statement. Note: In the following function syntax example: - Every placeholder shown inside arrow brackets ( <placeholder> ) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information. - Statements shown between square brackets ( [ ] ) are optional. The square brackets should not be included in the statement, and are shown here only for your information. Replace the <ArgumentName> placeholder in the following function example with an appropriate name for your Argument variable. See the section titled Function Argument Structure for details.
FUNCTION FunctionName ( <ArgumentDataType> <ArgumentName> [ = <InitialDefaultValue> ] ) <Statement> ; <Statement> ; <Statement> ;

57

Chapter 6: Writing Functions

END

You can use up to 32 ASCII text characters to name your arguments. You can use any valid name except for a reserved word. The case is ignored by the CitectSCADA compiler, so you can use upper and lower case to make your names clear. For example, iPacketQnty is easier to read than ipacketqnty or IPACKETQNTY .
FUNCTION FunctionName ( INT iPacketQnty ) <Statement> ; <Statement> ; <Statement> ; END

To refer to the argument (in the body of your function) you use the name of the argument in an executable statement:
INT FUNCTION AddTwoIntegers ( INT FirstInteger, INT SecondInteger ) INT Solution ; Solution = FirstInteger + SecondInteger ; RETURN Solution ; END

Setting Default Values for Arguments


If an argument is listed in a Cicode function declaration, the Argument Initialisation Statement is optional, and if used, is listed last in the Argument Statement after the required Argument Data Type and the Argument Name Statements. The Argument Initialization Statement needs to be preceded by an equals ( = ) assignment operator. Note: In the following function syntax example:
Every placeholder shown inside arrow brackets ( <placeholder> ) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information. Statements shown between square brackets ( [ ] ) are optional. The square brackets should not be included in the statement, and are shown here only for your information.

Replace the <InitialDefaultValue> placeholder in the following function example with an appropriate value for your Argument variable.

58

Chapter 6: Writing Functions

FUNCTION FunctionName (<ArgumentDataType> <ArgumentName> [ = <InitialDefaultValue> ]) <Statement> ; <Statement> ; <Statement> ; END

The default value for an argument needs to be of the same data type as declared for the argument in the Argument Data Type Statement. You assign a default argument variable value in the same manner that you assign a Cicode variable value, by using the equals ( = ) assignment operator. For example:
FUNCTION PlotProduct ( INT iPackets = 200 , STRING sName = "Packets" ) <Statement> ; <Statement> ; <Statement> ; END

If you assign a default value for an argument, you may omit a value for that argument when you call the function, because the function will use the default value from the declaration. To pass an empty argument to a function, omit any value for the argument in the call. For example, to call the PlotProduct function declared in the previous example, and accept the default string value of "Packets", a Cicode function call would look like:
PlotProduct(500)

Be aware that the second argument for the function was omitted from the calling code. In this instance, the default value for the second argument ( "Packets" ) would remain unchanged, and so would be used as the second argument value in this particular function call. If you do call that function and pass in a value for that argument in the call, the default value is replaced by the argument value being passed in. However, the arguments are reinitialized every time the function is called, so each subsequent call to the function will restore the default values originally declared in the function. If the function has more than one argument and none of them are explicitly declared in the function declaration, the default values for the undeclared arguments will be used. For more information on function calls, callers, and calling, see the section titled Calling Functions from Commands and Expressions. Argument Statements can be separated over several lines to aid in their readability.

59

Chapter 6: Writing Functions

Returning Values from Functions


Many of the built-in Cicode functions supplied with CitectSCADA return a data value to their calling statement. Mathematical functions return a calculated value. The Date ( ) and Time ( ) functions return the current date and time. Other functions, like PageDisplay ( ), perform an action, and return a value indicating either the success of the action or the type of error that occurred. You can also use return values in your own functions, to return data to the calling statement. The return value is assigned in the RETURN Statement: The optional RETURN Statement of a function (if used), needs to be placed in the executable Statements section of a Cicode function between the FUNCTION and END Statements. Because the RETURN Statement is used to return data values that have usually been manipulated by the function, they are usually placed last just before the END Statement.
<ReturnDataType> FUNCTION FunctionName ( <Arguments> ) <Statement> ; <Statement> ; <Statement> ; RETURN <ReturnValue> ; END

The RETURN Statement consists of the RETURN keyword followed by a value to be returned and finished with the semicolon (;) end-of-line marker. The RETURN value needs to be of the same data type as was declared in the Return Data Type Statement at the start of the function declaration. The return data type of a function can be only one of six possible data types: INT (32 bits), REAL (64 bits), STRING (255 bytes), OBJECT (32 bits), QUALITY or TIMESTAMP (64 bits). If no Return Data Type Statement is declared, the function will not be able to return any type of data. If the RETURN Statement within the function encounters a different data type to that declared in the Return Data Type Statement, the value is converted to the declared return data type. For information about the Return Data Type Statement, see the section titled Declaring the Return Data Type. FUNCTION, INT, REAL, STRING, and OBJECT are Cicode keywords and as such, are reserved. Note: In the following function syntax example every placeholder shown inside

60

Chapter 6: Writing Functions

arrow brackets ( <placeholder> ) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information. To declare the value that will be returned to the calling code, you need to replace the <ReturnValue> placeholder in the following example with an appropriate data value to match the Return Data Type as declared in the function.
<ReturnDataType> FUNCTION FunctionName ( <Arguments> ) <Statement> ; <Statement> ; RETURN <ReturnValue> ; END

The following example returns an integer of value 5:


INT FUNCTION FunctionName ( <Arguments> ) <Statement> ; INT Status = 5; <Statement> ; RETURN Status; END

The RETURN statement passes a value back to the calling procedure (either another function, command or expression). Outside of the function, the return value can be read by the calling statement. For example, it can be used by the caller as a variable (in a command), or animated (in an expression).

61

Chapter 6: Writing Functions

62

Chapter 7: Using Variables


A variable is a named location in the computer's memory where data can be stored. Cicode variables can store the basic data types (such as strings, integers, and real numbers) and each variable is specific for its particular data type. For example, if you set up a Cicode variable to store an integer value, you cannot use it for real numbers or strings. Note: Each data type uses a fixed amount of memory: integers use 4 bytes of memory, real numbers use 4 bytes, and strings use 1 byte per character. PLC INT types use only 2 bytes. The computer allocates memory to variables according to the data type and the length of time you need the variable to be stored. Real-time variables (such as PLC variables) are already permanently stored in database files on your hard disk. Any variable you use in a database field command or expression needs to be defined as a variable tag, or the compiler will report an error when the system is compiled. Note: Cicode variables can handle a wide range of CitectSCADA variable tag data types. For example, a Cicode variable of INT data type can be used to store I/O device data types: BCD, BYTE, DIGITAL, INT, LONG, LONGBCD, and UINT. See Also Using Arrays Variable Declaration Standards Variable Naming Standards Variable Scope Standards Using Cicode Files

Declaring Variable Properties


You need to declare each variable used in your functions (except for variables that are configured as variable tags). In the declaration statement, you specify the name and data type of the variable. You can also set a default value for the variable.

63

Chapter 7: Using Variables

Declaring the Variable Data Type


You can use variables of the following data types:
INT Integer (32 bits) -2,147,483,648 to 2,147,483,647 -3.4E38 to 3.4E38 ASCII (null terminated)

REAL STRING

Floating point (64 bits) Text string (128 bytes maximum, including null termination character) ActiveX control Represents the CitectSCADA quality

OBJECT QUALITY

QUAL_GOOD, QUAL_ BAD, QUAL_UNCR

TIMESTAMP

64-bit value representing the number of 100-nanosecond intervals since January 1, 1601

If you want to specify a digital data type, use the integer type. Digital types can either be TRUE(1) or FALSE(0), as can integer types. Note: Cicode may internally store floating point values as 64 bit to minimize rounding errors during floating point calculations.

QUALITY Data Type


The QUALITY data type is a new data type in Cicode which incorporates the CitectSCADA quality. The QUALITY data type and the Cicode quality labels can be used in Cicode expressions. The operators allowed for the QUALITY data type are:
l l

Assignment operator: =. Relational operators: =, <>.

The assignment operation also allows for the QUALITY data type.
Example: QUALITY q1; QUALITY q2; q1 = q2; q1 = Tag1.Field.Q;

64

Chapter 7: Using Variables

//the following expression will generate a compiler error as a tag //element can be modified only as a whole Tag1.Field.Q = q1;

A set of Cicode functions are provided which allow quality fields to be initialized, a specific quality field to be extracted, and other operations on the QUALITY data type. Conversion between the QUALITY data type and other Cicode data types is not allowed. Direct conversion from Quality to string will return an empty string.
Example: //this will generate a compiler error INT n = Tag1.Q;

TIMESTAMP Data Type


The TIMESTAMP data type is a new data type in Cicode which represents the date and time as a 64-bit value by specifying the number of 100-nanosecond intervals since January 1, 1601.This data type is always in Coordinated Universal Time (UTC). The operators allowed for the TIMESTAMP data type are:
l l

Assignment operator: =. Relational operators: =, <>, <, >, <=, >=.

Example:

TIMESTAMP t1; TIMESTAMP t2; t1 = Tag1.T; t1 = t2; IF t1 < Tag2.T THEN // insert code here END

A set of Cicode functions are provided which allow initialization, conversion and other operations on the TIMESTAMP data type. Implicit conversion between the TIMESTAMP data type and other Cicode data types is not allowed.

Naming Variables
Throughout the body of the function, the variable is referred to by its name. You can name a variable any valid name except for a reserved word, for example:
STRING REAL sStr; Result;

65

Chapter 7: Using Variables

INT OBJECT

x, y; hObject;

The first 32 characters of a variable name needs to be unique. See Also Variable Naming Standards

Setting Default Variable Values


When you declare variables, you can set them to an initial (startup) value; for example:
STRING REAL INT Str = "Test"; Result = ; x = 20, y = 50;

Using Variable Scope


Scope refers to the accessibility of a function and its values. A Cicode variable can be defined as any one of three types of scope - global, module, and local. By default, Cicode variables are module scope, unless they are declared within a function. Variables have the following format:
DataType Name [=Value];

Global variables

A global Cicode variable can be shared across all Cicode files in the system (as well as across include projects). They cannot be accessed on pages or databases (for example, Alarm.dbf). Global Cicode variables are prefixed with the keyword GLOBAL, and needs to be declared at the start of the Cicode file. For example:
GLOBAL STRING sDefaultPage = "Mimic"; INT FUNCTION MyPageDisplay(STRING sPage) INT iStatus; iStatus = PageDisplay(sPage); IF iStatus <> 0 THEN PageDisplay(sDefaultPage);

66

Chapter 7: Using Variables

END RETURN iStatus; END

The variable sDefaultPage could then be used in any function of any Cicode file in the system. Note: Use global variables sparingly if at all. If you have many such variables being used by many functions, finding bugs in your program can become time consuming. Use local variables wherever possible. Global Cicode STRING types are 256 bytes.

Module variables

A module Cicode variable is specific to the file in which it is declared. This means that it can be used by any function in that file, but not by functions in other files. By default, Cicode variables are defined as module, therefore prefixing is not required (though a prefix of MODULE could be added if desired). Module variables should be declared at the start of the file. For example:
STRING sDefaultPage = "Mimic"; INT FUNCTION MyPageDisplay(STRING sPage) INT Status; Status = PageDisplay(sPage); IF Status <> 0 THEN PageDisplay(sDefaultPage); END RETURN Status; END INT FUNCTION DefaultPageDisplay() PageDisplay(sDefaultPage); END

Note: Use module variables sparingly if at all. If you have many such variables being used by many functions, finding bugs in your program can become time-consuming. Use local variables wherever possible.

Local variables

67

Chapter 7: Using Variables

A local Cicode variable is only recognized by the function within which it is declared, and can only be used by that function. You need to declare local variables before you can use them. Any variable defined within a function (that is, after the function name) is a local variable, therefore no prefix is needed. Local variables are destroyed when the function exits. Local variables take precedence over global and module variables. If you define a local variable in a function with the same name as a global or module variable, the local variable is used; the global/module variable is unaffected by the function. This situation should be avoided, however, as it is likely to cause confusion.
Local Variables and Variable Tags

Local variables have limited functionality compared with variable tags. Limitations are:
l

Qualities of Override, OverrideMode, ControlMode and Status elements are showing Bad with extended substatus QUAL_EXT_INVALID_ARGUMENT. Writing to the elements returns error Invalid argument passed (274). Values of Override, OverrideMode, ControlMode and Status elements are showing 0. Respective timestamps and quality of Field, Valid and default elements are the same. Field, Valid and default elements can be read. Field and default elements can be written.

l l l l

See Also Variable Scope Standards

Using Database Variables


You can use any variable that you have defined in the database (with the Variable Tags form) in your functions. To use a database variable, specify the tag name:
<Tag>

where Tag is the name of the database variable. For example, to change the value of the database variable "LT131" at run time, you would use the following statement in your function:
LT131=1200; !Changes the value of LT131 to 1200

68

Chapter 8: Using Arrays


A Cicode variable array is a collection of Cicode variables of the same data type, in the form of a list or table. You name and declare an array of variables in the same way as any other Cicode variable. You can then refer to each element in the array by the same variable name, with a number (index) to indicate its position in the array. See Also Variable Declaration Standards Declaring Array Properties Declaring the Array Data Type Naming Arrays Declaring the Variable Array Size Setting Default (Initial) Array Values Passing Array Elements as Function Arguments Using One-dimensional Arrays Using Two-dimensional Arrays Using Three-dimensional Arrays Using Array Elements in Loops Using the Table (Array) Functions Using Cicode Files

Declaring Array Properties


Arrays have several properties that you need to declare to the compiler along with the array name: data type, size and dimension. You can also set default values for individual elements of the array. An array declaration has the following syntax:
DataType Name[Dim1Size,{Dim2Size},{Dim3Size}]{=Values};

See Also Using Arrays Using Cicode Files

69

Chapter 8: Using Arrays

Declaring the Array Data Type


As with any other Cicode variable, arrays can have four Data Types:
INT REAL STRING OBJECT QUALITY TIMESTAMP Integer (32 bits) Floating point (32 bits) Text string (255 bytes) ActiveX object (32 bits) CitectSCADA Quality Date and Time (64 bits)

See Also Using Arrays Using Cicode Files

Naming Arrays
Throughout the body of a Cicode function, a Cicode variable array is referred to by its name, and individual elements of an array are referred to by their index. The index of the first element of an array is 0 (that is a four element array has the indices 0,1,2, and 3). You can name a variable any valid name except for a reserved word; for example:
STRING REAL INT StrArray[5]; Result[5][2]; IntArray[4][3][2]; ! list ! 2-D table ! 3-D table

See Also Using Arrays Using Cicode Files

Declaring the Variable Array Size


You need to declare the size of the array (the number of elements the array contains), for example:

70

Chapter 8: Using Arrays

STRING

StrArray[5];

This single dimension array contains 5 elements. The compiler multiplies the number of elements in the array by the size of each element (dependent upon the Data Type), and allocates storage for the array in consecutive memory locations. You cannot declare arrays local to a function. However, they can be declared as Module (that is at the beginning of the Cicode file), or Global. When referring to the array within your function, take to care to remain within the size you set when you declared the array. The example below would cause an error:
STRING StrArray[5]; ... StrArray[10] = 100; ...

The compiler allows storage for 5 strings. By assigning a value to a 10th element, you cause a value to be stored outside the limits of the array, and you could overwrite another value stored in memory. See Also Using Arrays Using Cicode Files

Setting Default (Initial) Array Values


When you declare an array, you can (optionally) set the individual elements to an initial (or start-up) value within the original declaration statement. For instance, naming a string array "ArrayA", sizing it to hold 5 elements, and initializing the array with string values, would look like the following example:
STRING ArrayA[5]="This","is","a","String","Array";

This array structure would contain the following values:


ArrayA[0]="This" ArrayA[1]="is" ArrayA[2]="a" ArrayA[3]="String" ArrayA[4]="Array"

See Also Using Arrays

71

Chapter 8: Using Arrays

Using Cicode Files

Passing Array Elements as Function Arguments


To pass a Cicode variable array element to a Cicode function, you need to provide the element's address; for example:
/* Pass the first element of ArrayA. */ MyFunction (ArrayA[0]) /* Pass the second element of ArrayA. */ MyFunction (ArrayA[1]) /* Pass the fifth element of ArrayA. */ MyFunction (ArrayA[4])

See Also Using Arrays Using Cicode Files

Using One-dimensional Arrays


To use a one-dimensional array:
STRING ArrayA[5]="This","is","a","String","Array"; This array sets the following values: ArrayA[0]="This" ArrayA[1]="is" ArrayA[2]="a" ArrayA[3]="String" ArrayA[4]="Array"

See Also Using Arrays Using Cicode Files

Using Two-dimensional Arrays


To use a two-dimensional array:
REAL ArrayA[5][2]=1,2,3,4,5,6,7,8.3,9.04,10.178;

This array sets the following values:

72

Chapter 8: Using Arrays

ArrayA[0][0]=1 ArrayA[1][0]=3 ArrayA[2][0]=5 ArrayA[3][0]=7 ArrayA[4][0]=9.04

ArrayA[0][1]=2 ArrayA[1][1]=4 ArrayA[2][1]=6 ArrayA[3][1]=8.3 ArrayA[4][1]=10.178

See Also Using Arrays Using Cicode Files

Using Three-dimensional Arrays


To use a three-dimensional array:
INT ArrayA[4][3][2]=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 16,17,18,19,20,21,22,23,24;

This array sets the following values:


ArrayA[0][0][0]=1 ArrayA[0][1][1]=4 ArrayA[1][0][0]=7 ArrayA[1][1][1]=10 ArrayA[2][0][0]=13 ArrayA[2][1][1]=16 ArrayA[3][0][0]=19 ArrayA[3][1][1]=22 ArrayA[0][0][1]=2 ArrayA[0][2][0]=5 ArrayA[1][0][1]=8 ArrayA[1][2][0]=11 ArrayA[2][0][1]=14 ArrayA[2][2][0]=17 ArrayA[3][0][1]=20 ArrayA[3][2][0]=23 ArrayA[0][1][0]=3 ArrayA[0][2][1]=6 ArrayA[1][1][0]=9 ArrayA[1][2][1]=12 ArrayA[2][1][0]=15 ArrayA[2][2][1]=18 ArrayA[3][1][0]=21 ArrayA[3][2][1]=24

You use arrays in your functions in the same way as other variables, but arrays have special properties that, in many situations, reduce the amount of code you need to write.

73

Chapter 8: Using Arrays

See Also Using Arrays Using Cicode Files

Using Array Elements in Loops


You can set up loops that deal efficiently with arrays by incrementing the index number. The following example shows a method of initializing an array:
REAL Array[10] : FOR Counter = 0 TO 9 DO Array[Counter] = 0 END RETURN Total :

See Also Working with Conditional Executors Using Arrays Using Cicode Files

Using the Table (Array) Functions


Cicode has built-in functions for processing Cicode variable arrays:
l l l

To perform calculations (max, min, total, etc.) on array elements. To look up the index number of an array element. To shift the elements of an array left or right.

See Also Table (Array) Functions Using Arrays Using Cicode Files

74

Chapter 9: Using Cicode Macros


Cicode has the following macros:
l

IFDEF: Determines one of two possible outcomes based on the existence of a specified non-alarm tag at compile time. Use one of the macros below for alarm tags. IFDEFAdvAlm: Determines one of two possible outcomes based on the existence of a specified advanced alarm tag at compile time. IFDEFAnaAlm: Determines one of two possible outcomes based on the existence of a specified analog alarm tag at compile time. IFDEFDigAlm: Determines one of two possible outcomes based on the existence of a specified digital alarm tag at compile time.

IFDEF
The IFDEF macro allows you to define two possible outcomes based on whether or not a specified tag exists within a project at the time of compiling. The macro can be implemented anywhere a simple expression is used, including fields within relevant CitectSCADA dialogs. The macro was primarily created to avoid the "Tag not found" compile error being generated whenever a genie was missing an associated tag. By allowing a "0" or "1" to be generated within the Hidden When field of a Genie's properties, elements could simply be hidden if a required tag was missing, allowing the genie to still be pasted onto a graphics page. The macro accepts three arguments: the first specifies the tag that requires confirmation, the second defines the outcome if the tag exists, the third defines the outcome if it does not exist. In the case of a genie being pasted on a graphics page, the IFDEF function would be configured as follows in the Hidden When field of the object properties dialog:
IFDEF("Bit_1",0,1)

If the tag "Bit_1" is defined in the tag database, the value in the Hidden When field will be 0. If Bit_1 is undefined, the value will be 1. Since the object is hidden when the value is TRUE (1), the object will be hidden when Bit_1 is undefined. See Hiding Graphics Objects for details.

75

Chapter 9: Using Cicode Macros

Beyond this purpose, the IFDEF macro can be broadly used as a conditional variable. The [<value if defined>] and <value if not defined> arguments can support any variable, expression, or constant. The [<value if defined>] argument is optional; if you leave it blank it will generate the current variable. You can also use nested IFDEF macros. Note: As different types of alarms can share the same name, you have to use a variation of IFDEF to check for the existence of alarm tags. See IFDEFAnaAlm for analog alarms, IFDEFDigAlm for digital alarms, or IFDEFAdvAlm for advanced alarms.
Syntax
IFDEF(TagName,

[<value if defined>], <value if not defined>)

Return Value

If the tag specified in the first argument exists, the value defined by the second argument is returned. This could be a variable, expression, or constant, or the current tag value if the argument has been left blank. If the specified tag does not exist, the variable, expression, or constant defined by the third argument is returned.
Example
! Generate the tag value if tag "Bit_1" is defined ! Generate an empty string if "Bit_1" is not defined IFDEF("Bit_1",," ") ! Generate a zero value (0) if tag "Bit_1" is defined ! Generate a true value (1) if "Bit_1" is not defined IFDEF("Bit_1",0,1)

For more examples of how to implement the IFDEF macro, see the CitectSCADA Knowledge Base article Q3461. See Also IFDEFAnaAlm, IFDEFDigAlm, IFDEFAdvAlm, Hiding Graphics Objects, IFDEF macro

IFDEFAdvAlm
Based on the IFDEF macro, IFDEFAdvAlm allows you to define two possible outcomes based on whether or not a specified advanced alarm tag exists within a project at the time of compiling. The macro can be implemented anywhere a simple expression is used, including fields within relevant CitectSCADA dialogs. The macro accepts three arguments: the first specifies the advanced alarm tag that requires confirmation, the second defines the outcome if the alarm exists, the third defines the outcome if it does not exist.

76

Chapter 9: Using Cicode Macros

Note: As different types of alarms can share the same name, you have to use a variation of IFDEF to check for the existence of alarm tags. See IFDEFAnaAlm for analog alarms, or IFDEFDigAlm for digital alarms.
Syntax
IFDEFAdvAlm(TagName,

[<value if defined>], <value if not defined>)

Return Value

If the advanced alarm tag specified in the first argument exists, the value defined by the second argument is returned. This could be a variable, expression, or constant, or the current tag value if the argument has been left blank. If the specified alarm does not exist, the variable, expression, or constant defined by the third argument is returned.
Example
! Generate tag value if advanced alarm "AdvAlarm_1" is defined ! Generate an empty string if "AdvAlarm_1" is not defined IFDEFAdvAlm("AdvAlarm_1",,"") ! Generate a zero value (0) in Hidden When field if advanced alarm "AdvAlarm_1" is defined ! Generate a true value (1) in Hidden When field if "AdvAlarm_1" is not defined IFDEFAdvAlm("AdvAlarm_1",0,1)

For more examples of how to implement the IFDEF macro, see the CitectSCADA Knowledge Base article Q3461. See Also IFDEFAnaAlm, IFDEFDigAlm, IFDEF

IFDEFAnaAlm
Based on the IFDEF macro, IFDEFAnaAlm allows you to define two possible outcomes based on whether or not a specified analog alarm tag exists within a project at the time of compiling. The macro can be implemented anywhere a simple expression is used, including fields within relevant CitectSCADA dialogs. The macro accepts three arguments: the first specifies the analog alarm tag that requires confirmation, the second defines the outcome if the alarm exists, the third defines the outcome if it does not exist. Note: As different types of alarms can share the same name, you have to use a

77

Chapter 9: Using Cicode Macros

variation of IFDEF to check for the existence of alarm tags. See IFDEFDigAlm for digital alarms, or IFDEFAdvAlm for advanced alarms.
Syntax
IFDEFAnaAlm(TagName,

[<value if defined>], <value if not defined>)

Return Value

If the analog alarm tag specified in the first argument exists, the value defined by the second argument is returned. This could be a variable, expression, or constant, or the current tag value if the argument has been left blank. If the specified alarm does not exist, the variable, expression, or constant defined by the third argument is returned. See Also IFDEF, IFDEFDigAlm, IFDEFAdvAlm
Example
! Generate tag value if analog alarm "AnaAlarm_1" is defined ! Generate an empty string if "AnaAlarm_1" is not defined IFDEFAnaAlm("AnaAlarm_1",,"") ! Generate a zero value (0) in Hidden When field if analog alarm "AnaAlarm_1" is defined ! Generate a true value (1) in Hidden When field if "AnaAlarm_1" is not defined IFDEFAnaAlm("AnaAlarm_1",0,1)

For further examples of how to implement the IFDEF macro, see the CitectSCADA Knowledge Base article Q3461. See Also IFDEF, IFDEFDigAlm, IFDEFAdvAlm

IFDEFDigAlm
Based on the IFDEF macro, IFDEFDigAlm allows you to define two possible outcomes based on whether or not a specified digital alarm tag exists within a project at the time of compiling. The macro can be implemented anywhere a simple expression is used, including fields within relevant CitectSCADA dialogs. The macro accepts three arguments: the first specifies the digital alarm tag that requires confirmation, the second defines the outcome if the alarm exists, the third defines the outcome if it does not exist.

78

Chapter 9: Using Cicode Macros

Note: As different types of alarms can share the same name, you have to use a variation of IFDEF to check for the existence of alarm tags. See IFDEFAnaAlm for analog alarms or IFDEFAdvAlm for advanced alarms.
Syntax
IFDEFDigAlm(TagName, [<value if defined>], <value if not defined>)

Return Value

If the digital alarm tag specified in the first argument exists, the value defined by the second argument is returned. This could be a variable, expression, or constant, or the current tag value if the argument has been left blank. If the specified alarm does not exist, the variable, expression, or constant defined by the third argument is returned.
Example
! Generate tag value if digital alarm "DigAlarm_1" is defined ! Generate an empty string if "DigAlarm_1" is not defined IFDEFDigAlm("DigAlarm_1",,"") ! Generate a zero value (0) in Hidden When field if digital alarm "DigAlarm_1" is defined ! Generate a true value (1) in Hidden When field if "DigAlarm_1" is not defined IFDEFDigAlm("DigAlarm_1",0,1)

For more examples of how to implement the IFDEF macro, see the CitectSCADA Knowledge Base article Q3461. Related macros IFDEFAnaAlm, IFDEFAdvAlm, IFDEF

Macro Arguments
The Cicode macros use the following arguments.
l l l

TagName [<value if defined>] <value if not defined>

TagName

79

Chapter 9: Using Cicode Macros

The name of the tag you would like the IFDEF macro to confirm the existence of. The CitectSCADA compiler will check the current project database for a tag matching this name.
[<value if defined>]

Defines the outcome of the macro if the specified tag exists in the current project. This argument is optional, which means you can:
l l

Generate any variable, constant, or expression. Generate the current value for the specified tag by leaving the argument blank.

<value if not defined>

Defines the outcome of the macro if the specified tag does not exist in the current project. This will generate any variable, constant, or expression, including a blank string (" ") if you want nothing to be presented.

80

Chapter 10: Converting and Formatting Cicode Variables


CitectSCADA provides four functions for converting integers and real numbers into strings, and vice versa.
l l l l

IntToStr: converts an integer variable into a string RealToStr: converts a floating-point variable into a string StrToInt: converts a string into an integer variable StrToReal: converts a string into a floating-point variable

You can convert data types without using these Cicode functions, but the result of the format conversion might not be what you expect. If you want more control over the conversion process, use the appropriate Cicode functions. Note: Variables of type object cannot be converted to any other type. When variables are automatically converted, or when the return value from a function call is converted, specific rules apply. See Also Converting Variable Integers to Strings Converting Real Numbers to Strings Converting Strings to Integers Converting Strings to Real Numbers Formatting Text Strings Escape Sequences (String Formatting Commands) Using Cicode Files

Converting Variable Integers to Strings


To convert an integer variable to a string:
IntVar=5; StringVar=IntVar;

81

Chapter 10: Converting and Formatting Cicode Variables

The value of StringVar is set to "5". The format of the string is specified when the variable is defined in the database. However you can override this default format with the string format (:) operator, and use the # format specifier to set a new format. For example:
IntVar=5; StringVar=IntVar:####

The value of StringVar = " 5". (The '#' formatting characters determine the size and number of decimal places contained in the string, that is a length of 4 with no decimal places.)
See Also

Converting and Formatting Cicode Variables Using Cicode Files

Converting Real Numbers to Strings


To convert a real number variable to a string:
RealVar=5.2; StringVar=RealVar;

The value of StringVar is set to "5.2". Note: Unpredictable results may occur if you use large numbers with a large number of decimal places. The format of the string is specified when the variable is defined in the database. However you can override this default format with the string format (:) operator, and use the # format specifier to set a new format. For example:
StrTag1=RealTag1:######.###

The value of StringVar = " 5.200". (The '#' formatting characters determine the size and number of decimal places contained in the string, that is a length of 10 including a decimal point and three decimal places.)

82

Chapter 10: Converting and Formatting Cicode Variables

See Also Converting and Formatting Cicode Variables Using Cicode Files

Converting Strings to Integers


To convert a string variable to an integer:
StringVar="50.25"; IntVar=StringVar;

The value of IntVar is set to 50. If StringVar contains any characters other than numeric characters, IntVar is set to 0. See Also Converting and Formatting Cicode Variables Using Cicode Files

Converting Strings to Real Numbers


To convert a string variable to a real number:
StringVar="50.25"; RealVar=StringVar;

The value of RealVar is set to 50.25. If StringVar contains any characters other than numeric characters, RealVar is set to 0. See Also Converting and Formatting Cicode Variables Using Cicode Files

Formatting Text Strings


A string in Cicode is represented as text positioned between double quote ( " ) delimiters. For example:
"This is my text string."

A string value can be assigned to a string variable. For example:

83

Chapter 10: Converting and Formatting Cicode Variables

STRING sMyStringVariable; sMyStringVariable = "This is my text string.";

More than one string can be joined together (concatenated) using the Cicode 'plus' mathematical operator ( + ). For example:
STRING sMyStringVariable; sMyStringVariable = "This is my text string." + "This is my second text string.";

The two strings would be joined together and assigned to the string variable sMyStringVariable. However, if subsequently displayed somehow, like in the following MESSAGE example, the concatenated string would look wrong because there is no space character positioned between the string sentences.
STRING sMyStringVariable; sMyStringVariable = "This is my text string." + "This is my second text string."; MESSAGE("String Concatenation Example",sMyStringVariable,32);

To overcome this potential formatting problem, you could include an extra space as the last character in the strings, or include the space as a third string in the concatenation. For example:
sMyStringVariable = "This is my text string. " + "This is my second text string. ";

or
sMyStringVariable = "This is my text string." + " " + "This is my second text string. ";

However, these are considered poor programming practices and not recommended. Instead, you can use special string formatting commands known as escape sequences.

84

Chapter 10: Converting and Formatting Cicode Variables

If the two strings (as used in the previous example), were formatted using appropriate escape sequences positioned within the strings, and subsequently displayed somehow, like in the following MESSAGE example, the concatenated string would look different, For example:
STRING sMyStringVariable; STRING sNewLine = "^n"; sMyStringVariable = "This is my text string." + sNewLine + "This is my second text string."; MESSAGE("String Concatenation Example",sMyStringVariable,32);

Strings and string variables can also be concatenated as in the previous example. Be aware of how the newline escape sequence ( ^n ) was assigned to the string variable sNewLine, and how this value was concatenated between the other strings and assigned to the string variable sMyStringVariable for display in the MESSAGE function. See Also Converting and Formatting Cicode Variables Using Cicode Files

Escape Sequences (String Formatting Commands)


Cicode supports several escape sequences that you can use in text strings for custom formatting of the string. By using the appropriate Cicode escape sequences listed below you can format the string display to do such things as divide onto separate lines at specific positions, insert tab spaces, insert quotes, or to display Hexadecimal numbers. Cicode escape sequences are preceded by a caret ( ^ ) character. The caret character is interpreted as a special instruction, and together with the characters immediately following it, are treated as an Cicode escape sequence formatting command. The escape sequences used in Cicode are:
^b backspace

85

Chapter 10: Converting and Formatting Cicode Variables

^f ^n ^t ^v ^' ^" ^^ ^r ^0xhh

form feed new line horizontal tab vertical tab single quote double quote caret carriage return where hh is a hexadecimal number (for example, ^0x1A)

See Also Converting and Formatting Cicode Variables Using Cicode Files

86

Chapter 11: Working with Operators


With Cicode, you can use the data operators that are standard in a large number of programming languages: mathematical, bit, relational, and logical operators. See Also Using Mathematical Operators Using Bit Operators Using Relational Operators Using Logical Operators Order of Precedence of Operators

Using Mathematical Operators


Standard mathematical operators allow you to perform arithmetic calculations on numeric variables - integers and floating point numbers.
Operator + * / MOD Description Addition Subtraction Multiplication Division Modulus (Remainder)

Example

The following are examples of mathematical operators


Command ComPV12 = PV10 + PV11;

PV12 is the sum of PV10 and PV11

87

Chapter 11: Working with Operators

ment Command Comment Command Comment Command Comment Command Comment Command Comment Counter = Counter - 1;

The value of Counter is decreased by 1

PV12 = Speed * Counter;

PV12 is the product of Speed and Counter

Average = Total / ShiftHrs;

Average is Total divided by ShiftHrs

Hold = PV12 MOD PV13;

If PV12 = 10 and PV13 = 8, Hold equals 2 (the remainder when PV12 is divided by PV13) Hold = PV12 MOD PV13;

If PV12 = 10 and PV13 = 8, Hold equals 2 (the remainder when PV12 is divided by PV13)

Note: Cicode uses the standard order of precedence, that is multiplication and division are calculated before addition and subtraction. In the statement A=1+4/2, 4 is divided by 2 before it is added to 1, and the result is 3. In the statement A=(1+4)/2 , 1 is first added to 4 before the division, and the result is 2.5. You can also use the addition operator (+) to concatenate (join) two strings.
Operator + Description Concatenate

88

Chapter 11: Working with Operators

Command Comment

Message = "For info see " + "Supervisor"; Message now equals "For info see Supervisor"

For example: See Also Working with Operators Using Cicode Files

Using Bit Operators


With a bit operator, you can compare the corresponding bits in two numeric expressions. (A bit is the smallest unit of data a computer can store.)
Operator BITAND BITOR BITXOR Description AND OR Exclusive OR

For example
Command Command Command Command Tag3 = Tag1 BITAND Tag2; Tag3 = Tag1 BITAND 0xFF; Tag3 = Tag1 BITOR Tag2; Tag3 = Tag1 BITXOR Tag2;

See Also Working with Operators Using Cicode Files

89

Chapter 11: Working with Operators

Using Relational Operators


Relational operators describe the relationship between two values. The relationship is expressed as one value being larger than, the same as, or smaller than another. You can use relational operators for both numeric and string variables, however you can only test variables of the same type. A numeric variable cannot be compared with a string variable.
Operator = <> < > <= >= Description Is equal to Is not equal to Is less than Is greater than Is less than or equal to Is greater than or equal to

For example:
Command Expression Command Expression Command Expression IF Message = "Alarm Active" THEN ... PV12 <> PV10; IF (Total + Count) / Avg < 10 THEN ... Counter > 1; IF PV12 <= PV10 THEN ... Total >= Shift * Hours;

See Also Working with Operators Using Cicode Files

90

Chapter 11: Working with Operators

Using Logical Operators


With logical operators, you can test several conditions as either TRUE or FALSE.
Operator AND OR NOT Description Logical AND Logical OR Logical NOT

Examples:
Command Comment Expression Comment Expression Comment Command Comment Command Comment Result = (PV12 = 10 AND PV13 = 2);

If PV12 equals 10 and PV13 equals 2 then Result is TRUE(1)

Motor_1 AND Motor_2;

If both Motor_1 and Motor_2 are TRUE, that is Digital bits are 1 or ON, then the expression is TRUE PV12 = 1 OR PV13 > 2 OR Counter <> 0;

If either PV12 equals 1 or PV13 is greater than 2 or Counter is not equal to 0, then the expression is TRUE Result = (Motor1_Ol OR Motor2_Ol);

If either Motor1_Ol or Motor2_Ol is TRUE, that is Digital bit is 1 or ON, then Result is TRUE (1) IF NOT PV12 = 10 THEN ...

If PV12 does not equal 10 then the result is TRUE. This is functionally identical to IF PV12 <> 10 THEN . . .

91

Chapter 11: Working with Operators

Expression Comment

NOT Tag_1;

This expression is TRUE if Tag_1 = 0. This is commonly used for testing digital variables

See Also Working with Operators Using Cicode Files

Order of Precedence of Operators


The table below shows the order of precedence of operators.
Operators have a set of rules that govern the order in which operations are performed. These rules are called the order of precedence. The precedence of Cicode operators from highest to lowest is: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. () NOT *, /, MOD : +, >, <, <=, >= =, <> AND OR BITAND, BITOR, BITXOR

See Also Working with Operators Using Cicode Files

92

Chapter 12: Working with Conditional Executors


The statements that control decisions and loops in your functions are called conditional executors. Cicode uses four conditional executors: If, For, While, and select case. See Also Formatting Executable Statements Setting IF ... THEN Conditions Using FOR ... DO Loops Using WHILE ... DO Conditional Loops Using the SELECT CASE statement Using Cicode Files

Setting IF ... THEN Conditions


The IF statement executes one or more statements based on the result of an expression. You can use If in one of two formats: If Then and If Then Else.
If Expression Then Statement(s); END -orIf Expression Then Statement(s); Else Statement(s); END

When you use the If Then format, the statement(s) following are executed only if the expression is TRUE, for example:
INT Counter; IF PV12 = 10 THEN Counter = Counter + 1; END

In this example, the Counter increments only if the tag PV12 is equal to 10, otherwise the value of Counter remains unchanged. You can include several statements (including other IF statements), within an IF statement, for example:

93

Chapter 12: Working with Conditional Executors

INT Counter; IF PV12 = 10 THEN Counter = Counter + 1; IF Counter > 100 THEN Report("Shift"); END END

In this example, the report runs when the Counter increments, that is when PV12 = 10, and the value of the counter exceeds 100. You can use the If Then Else format for branching. Depending on the outcome of the expression, one of two actions are performed, for example:
INT Counter; IF PV12 = 10 THEN Report("Shift"); ELSE Counter = Counter + 1; END

In this example, the report runs if PV12 is equal to 10 (TRUE), or the counter increments if PV12 is anything but 10 (FALSE). See Also Working with Conditional Executors

Using FOR ... DO Loops


A For loop executes a statement or statements a specified number of times.
FOR Variable=Expression To Expression DO Statement(s); END

The following function uses a For loop:


STRING ArrayA[5]="This","is","a","String","Array"; INT FUNCTION DisplayArray() INT Counter; FOR Counter = 0 TO 4 DO Prompt(ArrayA[Counter]); Sleep(15); END END

94

Chapter 12: Working with Conditional Executors

This function displays the single message "This is a String Array" on the screen one word at a time pausing for 15 seconds between each word. See Also Working with Conditional Executors

Using WHILE ... DO Conditional Loops


A While loop executes a statement or statements in a loop as long as a given condition is true.
WHILE Expression DO Statement(s); END

The following code fragment uses a WHILE loop:


INT Counter; WHILE DevNext(hDev) DO Counter = Counter + 1; END /* Count the number of records in the device (hDev)*/

Be careful when using WHILE loops in your Cicode functions: WHILE loops can cause excessive loading of the CPU and therefore reduce system performance. If you use a WHILE loop to loop forever, you should call the Cicode function Sleep() so that CitectSCADA can schedule other tasks. The Sleep() function increases the performance of your CitectSCADA system if you use many WHILE loops. See Also Working with Conditional Executors

Nested Loops
You can "nest" one loop inside the other. That is, a conditional statement can be placed completely within (nested inside) a condition of another statement. See Also Working with Conditional Executors

95

Chapter 12: Working with Conditional Executors

Using the SELECT CASE statement


The select case statement executes on several groups of statements, depending on the result of an expression. SELECT CASE statements are a more efficient way of writing code that would otherwise have to be done with nested IF THEN statements.
SELECT CASE Expression CASE CaseExpression1,CaseExpression2 Statement(s); CASE CaseExpression3 TO CaseExpression4 Statement(s); CASE IS >CaseExpression5,IS<CaseExpression6 Statement(s); CASE ELSE Statement(s); END SELECT

Where CaseExpressionn is any one of the following forms:


- expression - expression TO expression

Where the TO keyword specifies an inclusive range of values. The smaller value needs to be placed before TO.
- IS <relop> expression.

Use the IS keyword with relational operators (<relop>). Relational operators that may be used are <, <=, =, <>, >, >= . If the Expression matches any CaseExpression, the statements following that CASE clause are executed up to the next CASE clause, or (for the last clause) up to the END SELECT. If the Expression matches a CaseExpression in more than one CASE clause, only the statements following the first match are executed. The CASE ELSE clause is used to indicate the statements to be executed if no match is found between the Expression and any of the CaseExpressions. When there is no CASE ELSE statement and no CaseExpressions match the Expression, execution continues at the next Cicode statement following END SELECT. You can use multiple expressions or ranges in each CASE clause. For example, the following line is valid:
CASE 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

96

Chapter 12: Working with Conditional Executors

You can also specify ranges and multiple expressions. In the following example, CASE matches strings that are exactly equal to "everything", strings that fall between "nuts" and "soup" in alphabetical order, and the current value of "TestItem":
CASE "everything","nuts" To "soup",TestItem

SELECT CASE statements can be nested. Each SELECT CASE statement needs to have a matching END SELECT statement. For example, if the four possible states of a ship are Waiting, Berthed, Loading, and Loaded, the Select Case statement could be run from a button to display a prompt detailing the ship's current state.
select case iStatus CASE 1 Prompt("Waiting"); CASE 2 Prompt("Berthed"); CASE 3 Prompt("Loading"); CASE 4 Prompt("Loaded"); CASE Else Prompt("No Status"); END SELECT

See Also Working with Conditional Executors

97

Chapter 12: Working with Conditional Executors

98

Chapter 13: Performing Advanced Tasks


This section introduces and explains event handling, CitectSCADA tasks, CitectSCADA threads, how CitectSCADA executes, and multitasking - including foreground and background tasks, controlling tasks, and pre-emptive multitasking. See Also Handling Events How CitectSCADA Executes Multitasking Foreground and background tasks Controlling tasks Pre-emptive multitasking

Handling Events
Cicode supports event handling. You can define a function that is called only when a particular event occurs. Event handling reduces the overhead that is required when event trapping is executed by using a loop. The following example illustrates the use of the OnEvent() function:
INT FUNCTION MouseCallback() INT x, y; DspGetMouse(x,y); Prompt("Mouse at "+x:####+","+y:####); RETURN 0; END OnEvent(0,MouseCallback);

The function MouseCallBack is called when the mouse is moved - there is no need to poll the mouse to check if it has moved. CitectSCADA watches for an event with the OnEvent() function. Because these functions are called each time the event occurs, you should avoid complex or time consuming statements within the function. If the function is executing when another call is made, the function can be blocked, and some valuable information may be lost. If you do wish to write complex event handling functions, you should use the queue handling functions provided with Cicode.

99

Chapter 13: Performing Advanced Tasks

See Also Performing Advanced Tasks

How Cicode is Executed


Your multi-tasking operating system gives CitectSCADA access to the CPU through threads. However, this access time is not continuous, as CitectSCADA needs to share the CPU with other applications and services. Note: Be careful when running other applications at the same time as CitectSCADA. Some applications place high demands on the CPU and reduce the execution speed of CitectSCADA. The CitectSCADA process has many operations to perform, including I/O processing, alarm processing, display management, and Cicode execution - operations that are performed continuously. And, because CitectSCADA is a real-time system, it needs to perform the necessary tasks within a minimum time - at the expense of others. For this reason, CitectSCADA is designed to be multitasking, so it can efficiently manage it's own tasks. CitectSCADA performs its tasks in a specific order in a continuous loop (cycle). CitectSCADA's internal tasks are scheduled at a higher priority than that of Cicode and have access to the CPU before the Cicode. For example, the Alarms, Trends, and I/O Server tasks all get the CPU before any of your Cicode tasks. The reports are scheduled at the same priority as your Cicode. CitectSCADA background spoolers and other idle tasks are lower priority than your Cicode. For Cicode, which consists of many tasks, CitectSCADA uses round-robin single priority scheduling. With this type of scheduling each task has the same priority. When two or more Cicode tasks exist, they each get a CPU turn in sequence. This is a simple method of CPU scheduling. Note: If a Cicode task takes longer than its designated CPU time to execute, it is preempted until the next cycle - continuing from where it left off. See Also Performing Advanced Tasks

100

Chapter 13: Performing Advanced Tasks

Multitasking
Multitasking is when you can run more than one task at the same time. Windows supports this feature at the application level. For example you can run MS-Word and MSExcel at the same time. CitectSCADA also supports multitasking internally; that is you can tell CitectSCADA to do something, and before CitectSCADA has completed that task you can tell CitectSCADA to start some other task. CitectSCADA will perform both tasks at the same time. CitectSCADA automatically creates the tasks, leaving you to call the functions. Multitasking is a feature of CitectSCADA not the operating system. Many applications cannot do this, for example if you start a macro in Excel, while that macro is running you cannot do any other operation in Excel until that macro completes. A multitasking environment is useful when designing your Cicode. It allows you to be flexible, allowing the operator to perform one action, while another is already taking place. For example, you can use Cicode to display two different input forms at the same time, while allowing the operator to continue using the screen in the background. See Also Performing Advanced Tasks

Foreground and background tasks


Cicode tasks (or threads) can be executing in either foreground or background mode. A foreground task is one that displays and controls animations on your graphics pages. Any expression (not a command) entered in a property field (that is Text, Rectangle, Button, etc.) is executed as a foreground task. Any other commands and expressions are executed in background mode. The difference between a background and foreground task is that a background task can be pre-empted. That is, if system resources are limited, the task (for example, the printing of a report) can pause to allow a higher priority task to be executed. When the task is completed (or when system resources become available) the original task resumes. Foreground tasks are the highest priority and can not be pre-empted. See Also Performing Advanced Tasks

101

Chapter 13: Performing Advanced Tasks

Controlling tasks
You can use the Task functions to control the execution of Cicode tasks, and use the CitectSCADA Kernel at runtime to monitor the tasks that are executing. Since CitectSCADA automatically creates new tasks (whenever you call a keyboard command, etc.), schedules them, and destroys them when they are finished, users rarely need to consider these activities in detail. Sometimes it is desirable to manually 'spawn' a new task. For example, suppose your Cicode is polling an I/O Device (an operation which need to be continuous), but a situation arises that requires operator input. To display a form would temporarily halt the polling. Instead you can spawn a new task to get the operator input, while the original task continues polling the device. Note: The TaskNew Cicode function is used to spawn new tasks. See Also "Using the CitectSCADA Kernel" in the CitectSCADA User Guide Performing Advanced Tasks Task Functions

Pre-emptive multitasking
Cicode supports pre-empted multitasking. If a Cicode task is running, and a higher priority task is scheduled, CitectSCADA will suspend the original task, complete the higher priority task and return to the original task. Preemption is supported between Cicode threads and other internal processes performed by CitectSCADA. You can, therefore, write Cicode that runs forever (for example, a continuous while loop) without halting other Cicode threads or CitectSCADA itself. For example:
INT FUNCTION MyLoopFunction() WHILE TRUE DO // Whatever is required in the continuous loop Sleep(1); // Optional END END

102

Chapter 13: Performing Advanced Tasks

In the above example, the function Sleep() is used to force preemption. The Sleep() function is optional, however it will reduce the load on the CPU, because the loop is suspended each second (it will not repeat at a high rate). See Also Performing Advanced Tasks

103

Chapter 13: Performing Advanced Tasks

104

Chapter 14: Editing and Debugging Code


This section describes how to edit and debug your Cicode using the Cicode Editor.

The Cicode Editor


You use the Cicode Editor to write, edit, and debug your Cicode code. The Cicode Editor behaves similarly to other code editing tools like Microsoft Dev Studio, and contains many advanced editing features such as:
l l l l

Dockable windows and toolbars. Syntax highlighting - color highlighting of syntax functions. IntelliSense AutoPrompt - function definition tooltips. IntelliSense AutoComplete - automatic inline prompting and completion of functions with their parameters. AutoCaseCorrect - automatic case correction of function keywords. AutoIndent - automatic indent alignment of code. AutoScroll - automatic mouse middle button support. Drag and Drop - copy or move of selected text. Bookmark and Breakpoint indicator bar - single click set and reset of bookmarks and breakpoints. Keyboard Shortcuts support.

l l l l l

Cicode Editor starts automatically when you double-click a Cicode file object in Citect Explorer, or click the Cicode Editor button in Citect Explorer. See the topic Starting the Cicode Editor. Cicode files are stored as text files. For more information see the Introducing Cicode and the section Using Cicode Files. Note: Be careful not to confuse a Cicode file (*.ci) with an Include file (*.cii). You could use any text editor to view or edit the Cicode files, however, the Cicode Editor provides integrated views specific to Cicode. As well as the features listed above, it includes:

105

Chapter 14: Editing and Debugging Code

l l l l l l l l

Breakpoint window Output window, Global Variable Window Stack window Thread window Compile Errors window CitectVBA Watch window Files window

To minimize potential future problems with maintaining your Cicode files, you should adopt a programming standard as early as possible, as discussed in the section Using Cicode Programming Standards. Maintain structured Cicode files, by logically grouping your Cicode functions within the files, and by choosing helpful descriptive names. Modular programming methods are discussed in the section Modular Programming. Cicode functions are introduced in the section titled Using Cicode Functions. Suggestions for debugging your Cicode is included in the section titled Debugging Cicode.

Starting the Cicode Editor


To start the Cicode Editor: 1. Click the Citect Explorer button. 2. Open the Cicode Files folder in the project list area of your project.

106

Chapter 14: Editing and Debugging Code

3. Do either of the following:


l l l

Double click a Cicode file (*.ci). Choose Tools | Cicode Editor in a CitectSCADA application. Click the Cicode Editor button.

Changing the default Cicode Editor


CitectSCADA allows you to use any text editor supported by Windows (for example, ED for Windows, Windows Notepad, or Microsoft Word), instead of the default Cicode Editor. To change the default Cicode Editor: 1. Click the Project Editor button. 2. Choose Tools | Options. 3. Enter the editor application file name in the Cicode Editor field. Note: The application name of the default Cicode Editor is ctcicode.exe located in the CitectSCADAbin folder. The application name for Notepad is notepad.exe, located in the Microsoft Windows c:\windows\ folder. The relative path to the editor application need to be included if the application is not stored in the CitectSCADAbin folder. 4. Click OK to save the changes and close the form, or Cancel to abort changes without saving.

107

Chapter 14: Editing and Debugging Code

Creating Cicode files


To create a new Cicode file: 1. Start the Cicode Editor. 2. Choose File | New, or click New. Save the Cicode file after creating it. The file is only stored on disk after you save it.

Creating functions
To create a new Cicode function: 1. Start the Cicode Editor. 2. Choose File | New, or click New. 3. Type in your new Cicode function in the blank space, or at the end of the file. Format the Cicode function correctly, following the documented syntax. 4. Save the Cicode file.

Saving files
To save a Cicode file: 1. Choose File | Save, or click Save. 2. If the file is new, you will be prompted by the Save as dialog. CitectSCADA automatically suggests a name. 3. Type in a new name in the File name field. 4. Click Save to save the file, or Cancel to abort the save. To save your Cicode file under a new name, choose Save as instead of Save. The original file will remain in your project under the original filename, until you delete it. All

108

Chapter 14: Editing and Debugging Code

source files in your project directory will be included when you compile your project.

Opening Cicode files


To open a Cicode file: 1. Start the Cicode Editor. 2. Choose File | Open, or click Open. 3. Select a file from the list. You can use the dialog controls to open other projects and directories. 4. Click the Open button to open the file, or Cancel to abort. Note: Double clicking on any Cicode file (*.ci) in the Citect Explorer will launch the Cicode Editor and open the Cicode file. However, be careful not to confuse a

109

Chapter 14: Editing and Debugging Code

Cicode file with an Include file (*.cii).

Deleting Cicode files


To delete a Cicode file: 1. Run the Cicode Editor. 2. Choose File | Open, or click the Open button. 3. Select the target file from the list. You can use the dialog controls to open other projects and directories. 4. Press the Delete key. 5. Click the Yes button to confirm delete, or No to abort. 6. Click the Cancel button to close the Open form.

Finding text in Cicode files


To find text in a Cicode file: 1. Choose Edit | Find, or click the Find button. 2. Complete the Find dialog, filling in the Find what field. 3. Click the Find Next button to begin searching, or Cancel to abort. The search is performed down the file from the cursor. Hits are highlighted.

110

Chapter 14: Editing and Debugging Code

Compiling Cicode files


To compile Cicode: 1. Run the Cicode Editor. 2. Choose File | Compile, or click the Compile button. Note: You cannot compile Cicode functions individually. When you compile CitectSCADA, it automatically compiles the entire contents of the project.

Viewing errors detected by the Cicode Compiler


To view errors detected by the Cicode compiler: Do either of the following:
l

From the Compile Errors in the File menu of the Project Editor, click Goto. This launches the Cicode Editor and opens the appropriate file at the correct line. Choose View | Compile Errors, then double-click the compile error you want to view.

Cicode Editor Options


Cicode error handling behavior is controlled through the Cicode Editor Options Properties Dialog. These allow you to set (and change) what should happen when errors occur in running Cicode, under which circumstances the debugger should be started, and how the debugger behaves when in debug mode. There are three tabbed property pages of options within the Debugger Options Properties dialog:
l l l

View Windows and ToolBars tab Options Properties tab Language Formatter Properties tab

See Also Debugging Cicode

111

Chapter 14: Editing and Debugging Code

Docking the Windows and Toolbars


The view windows and toolbars of the Cicode Editor can be docked or free floating within the editing and debugging environment. Toolbars are docked by default within the toolbar area at the top of the Cicode Editor. Windows are docked by default in the document display area at the lower portion of the Cicode Editor, beneath the toolbar area. Docked windows are those that resize themselves to fit totally within the Cicode Editor display area, by docking (attaching) themselves to an internal edge of the display area. Docked windows cannot be resized manually, and will share the display space with the Editor toolbars and other docked windows. Docked windows and toolbars share the display space side-by-side, without obscuring the view of each other. Free floating windows are those that are not docked to the editor, nor are necessarily constrained by the editor boundaries. Free floating windows can be resized manually, and are subject to layering (Z-order), in which they can be partly or wholly obscured by another window, and they could partly or wholly obscure the view of another window themselves. The window or toolbar with the current focus, is the one completely visible at the top of all other display window layers, partly or wholly obscuring any beneath it in the Z-order. Windows and toolbars can be moved about in the Cicode Editor environment by clicking and dragging the titlebar of a window, or non-button area of a button bar. Docking behaviour is by default, and can be overridden by holding down the CTRL key during the drag-and-drop to force the window or bar to be free floating. The position of the mouse during the drop action determines which side the window or toolbar docks to. Docking outlines of the window or toolbar are displayed with gray lines during the drag action to indicate the potential docked position. Debugging Cicode

Displaying the Editor Options Properties dialog


To view/hide the Editor Options properties dialog: 1. Run the Cicode Editor. 2. Choose Debug | Options, or press Ctrl + T and then select the appropriate Window from the dialog.

112

Chapter 14: Editing and Debugging Code

Note: You can also choose View | Options, and then select the appropriate Window from the dialog.

Windows and Bars Tab

The Windows and Bars tab displays the current display state of the listed Toolbars and Debug Windows within the Cicode Editor. A check mark in the checkbox next to the Window or Toolbar name enables the display of that Window or Toolbar in the Cicode Editor. A grayed-out checkbox indicates that the window is disabled (presently unable to be displayed). For example: Many of the debug windows which display the active state of project Cicode variables are disabled when a Cicode project is not running, and therefore the Cicode Editor cannot be in debug mode). Note: Right-click in the toolbar area to view a menu of available toolbars and debug windows. For a description the buttons, see The Cicode Editor.

Toolbar options
Click the button on the toolbar to display the tool bar you want; for example, click Edit to display the Edit tool bar.

113

Chapter 14: Editing and Debugging Code

Window options
The Cicode Editor has several editing and debug windows that you can use to display information about running Cicode and CitectVBA. The Cicode Editor windows available are:
l l l l l l l l

Breakpoint window Output window Global Variable window Stack window Thread window Compile Errors window CitectVBA Watch window Files window

Viewing Editor windows


You can choose to view Editor windows or hide them to give you more room on your screen. To view/hide an Editor Window: 1. Run the Cicode Editor. 2. From the View menu, select the appropriate Window, or click the toggle button you want in the View toolbar.
Breakpoint window

Displays the Breakpoint Window, which is used to list all breakpoints that are currently set within the project. Double clicking an item in the list loads the file into the editor and jumps to the breakpoint position. Right-clicking an item allows the enable/disable/removal of the list item.

The Breakpoint Window has the following fields:

114

Chapter 14: Editing and Debugging Code

l l l

File: the full name and location of the code file in which the breakpoint exists. Line: the line number (in the code file) where the breakpoint is located. Enabled: indicates if the breakpoint is enabled or not. Yes indicates it is active, No indicates it is not.

Output window

Displays the Output Window, which lists the output messages sent by CitectSCADA during debugging. It states when threads start and terminate, and if a break occurs. This window will show messages sent by the TraceMsg() function. The Output window shows entries in the order that they occur:

Note: you need to be in debug mode to view the messages.

Global Variable Window

Displays the Global Variables Window, which lists the names and values of all global variables processed to date in the running project during debugging. A global variable is added to the list when it is first assigned a value. Each time the Global variable is processed, its value will be updated in the Global Variable Window.

Note: you need to be in debug mode to view global variable values in this window.

Stack window

115

Chapter 14: Editing and Debugging Code

Displays the Call Stack window, which lists the stack values of the current thread. The stack consists of the functions called (including the arguments), any variables used in the functions, and return values. This is especially useful during debugging to trace the origin of the calling procedures. A stack is a section of memory that is used to store temporary information. For example, when you call a Cicode function, the variables used inside the function exist only as long as the function runs. To view the values of arguments and variables in a procedure, place a breakpoint within the procedure under watch. When that breakpoint is reached, the Stack Window will display the current call stack of the procedure containing the breakpoint. The values of the stack are updated as the values change.

Note: you need to be in debug mode to view this window.

Thread window

Displays the Threads History window.

The Thread Window has the following fields:


l

Name: The name of the Cicode thread. This is the name of the function called to start the thread (from the TaskNew() function for example).

If you click on the Name of the Cicode thread, you will make the selected thread the current focus of the Debugger. The Debugger will change the display to show the source of the new thread.

116

Chapter 14: Editing and Debugging Code

Note: If the thread was not started from TaskNew(), the Name shown will be Command. Hnd: The Cicode thread handle. CPU: The amount of CPU the Cicode thread is currently using, as a percentage of the total CPU usage. Cicode is efficient and this value should be quite small (0-25%). If this value is large it can indicate a problem with the Cicode program you have created. For example, values over 60% can indicate that your thread is running in 'hard' loops, and needs a Sleep() function inserted. State: The state of the Cicode thread. The states are defined as follows:
l l l l

l l

Ready: The Cicode is ready to be run. Sleep: Suspended using the Sleep() function. Run: The thread is running.

CPU_Time: The total amount of CPU time that the Cicode thread has consumed. This tracks how much CPU time the thread has used over its lifetime. Note: you need to be in debug mode to view this window.

Compile Errors window

Displays the Compile Errors window, which lists any code errors that have occurred during compile. You can double-click on the file name in the list, to open that code file in the Cicode Editor, and jump to the line of code that caused the compile error.

CitectVBA Watch window

Displays the CitectVBA Watch window. During debugging mode, you can use the CitectVBA Watch window to watch the value of any CitectVBA variables in the current scope. Click in the Variable column and type in the name of the variable under watch. As it comes into scope, its value is updated and appears in the Value column.

117

Chapter 14: Editing and Debugging Code

Note: You need to be in debug mode to view this window.

Files window

Displays the Files window containing three tabs.


l

The 'All Projects' tab displays a tree hierarchy view of all projects and their Cicode and CitectVBA files available within Citect Explorer. The 'Open Project' tab displays a tree hierarchy view of the currently selected project, and all included projects. The currently selected project will be the top entry. The 'Open Files' tab lists the names of all files currently open for editing in the Cicode Editor.

Note: Clicking any of the file names displayed in the tree will open that file in the editor and give it the focus.

118

Chapter 14: Editing and Debugging Code

Options Properties Tab

The Options properties tab has the following features: [Dynamic properties] Break on all hardware errors Stops a Cicode thread if a hardware error is detected. A Cicode error will be generated and the thread will terminate (without executing the rest of the function). [Dynamic properties] Suspend all Cicode threads while stepping All Cicode threads will be suspended while the debugger is stepping (or when the debugger reaches a breakpoint, or the user performs a manual break). If you try to run any Cicode thread at such a time (by pressing a button at runtime, and so on), the Command paused while in debug mode message will display in the runtime prompt line. This option allows better isolation of any software errors that are detected, especially those that occur when your Cicode thread interacts with other threads. Foreground Cicode cannot be suspended and will continue running when this option is set. Note: This option will help prevent all new Cicode threads from running (including keyboard and touch commands), and should not be used on a running plant. [Dynamic properties] Warning on break in foreground Cicode If a break point is 'hit' in a foreground Cicode task, the Foreground Cicode cannot break (343) error message is generated, and will be displayed on the Hardware Alarm page. Disable this option to stop the alarm message from displaying. [CitectSCADA startup options] CitectSCADA will start debugger on hardware errors

119

Chapter 14: Editing and Debugging Code

CitectSCADA will automatically start the debugger when a Cicode generated hardware error is detected. The debugger will display the Cicode source file, and mark the location of the error. Note: This option will interrupt normal runtime operation, and should only be used during testing and commissioning of systems.

UNINTENDED EQUIPMENT OPERATION Do not use the following options during normal plant or process operations:
l l

Suspend all Cicode threads while stepping. CitectSCADA will start debugger on hardware errors.

These options are only for use during system testing and commissioning. Failure to follow these instructions can result in death, serious injury, or equipment damage.

[CitectSCADA startup options] Notify debugger of errors in foreground Cicode CitectSCADA will automatically start the debugger if an error is detected in a foreground task. The debugger will display the Cicode source file, and mark the location of the error. This option is overridden by the CitectSCADA will start debugger on hardware errors option. That is, if the above option is disabled, then this option is disabled also. Note: Foreground Cicode cannot be suspended. The break point will be marked, but you will not be able to step through the function. [CitectSCADA startup options] Allow remote debugging Allows debugging of Cicode on this computer from a remote CitectSCADA computer. [CitectSCADA startup options] Remote IP Address The Windows Computer Name or TCP/IP address of the remote CitectSCADA computer. The Windows Computer Name is the same as specified in the Identification tab, under the Network section of the Windows Control Panel. You specify this name on the computer from which you are debugging. The TCP/IP address (for example, 10.5.6.7 or plant.yourdomain.com) can be determined as follows:
l

Go to the Command Prompt, type IPCONFIG, and press Enter.

[Debugger options] Save breakpoints between sessions

120

Chapter 14: Editing and Debugging Code

Save the location and states of breakpoints between running sessions of the Cicode Editor and Debugger. This means breakpoints inserted using the Cicode Editor can later be recalled when an error is detected - even though the file (and application) has been closed. [Compile options] Incremental compile Enables the incremental compilation of the project. See Also Debugging Cicode

Language Formatter Properties Tab

This dialog displays the currently selected programming language that the editor will use to format the syntax of the file being edited in the code window. If you open a Cicode file (with a .Ci extension), the current language formatter changes to Cicode. If you open a CitectVBA file (with a .bas extension), the current language formatter changes to CitectVBA. Similarly, if you open a file with neither a Cicode nor a CitectVBA extension, say a text file (with a .txt extension), the editor will not know which language type you want to use, and will not apply any formatting to the file. You can use this dialog to select which programming language the file contains, and it will format the file appropriately for display in the code window. Note: The Cicode Editor can be used to edit any ASCII text based file, including Microsoft JScript. The editor recognizes JScript files (with a .jav extension) and will change the current language formatter to JScript. CitectSCADA does not support JScript, and will not compile it into your project. However, the editor can still be used

121

Chapter 14: Editing and Debugging Code

separately to edit or create a JScript file or any other ASCII text based file. Current Displays the currently selected programming language formatter for appropriate syntax coloring of the file displayed in the code window. Selection Displays the range of possible programming languages that can be chosen as the current language for formatting and display in the code window.

Debugging Cicode
To help you locate Cicode errors, you can switch the Cicode Editor to debug mode to analyze running Cicode. You can toggle debugging on and off as required, but CitectSCADA needs to be running for the debugger to work. Note: The Cicode Editor cannot debug foreground Cicode. A break in a foreground Cicode will result in the Foreground Cicode cannot break message. See Also Cicode Editor Options | Function Error handling | Debug Error Trapping

Using debug mode


To switch to debug mode: 1. Run the Cicode Editor. 2. Choose Debug | Start Debugging, or click the Toggle Debug button. Note: If the current project is not running, CitectSCADA compiles and runs it automatically. The bug in the bottom right-hand corner is green when debugging.

Debugging functions
To debug a function: 1. Run the Cicode Editor. 2. Open the file containing the function you wish to debug. 3. Click the Toggle Debug button, or choose Debug | Start Debugging.

122

Chapter 14: Editing and Debugging Code

Note: If the current project is not running, CitectSCADA compiles and runs it automatically. The bug in the bottom right-hand corner is green when debugging. 4. Insert a breakpoint where you want to start debugging. 5. From the View menu, select any debug windows you want to use. If you are unsure, you can use them all. 6. Initiate the thread by calling the function. You can do this directly from the Cicode window in the Kernel, or by using a function, etc. 7. The function will break at the specified breakpoint. You can then use the step tools to step through and trace your function. 8. Click the Toggle Debug button to stop debugging, or choose Debug | Stop Debugging.

Debugging functions remotely


You can debug functions remotely if both computers are running identical projects and the CitectSCADA Path is the same on both machines. To remotely debug Cicode: 1. Click the Cicode Editor button on the computer that will be running CitectSCADA (the remote). 2. Choose Debug | Options. 3. Check (tick) the Allow remote debugging option. 4. Click OK. 5. Click the Run button (you can close the Cicode Editor first), or choose File | Run. 6. On the computer that will be debugging CitectSCADA, click the Cicode Editor button. 7. Choose Debug | Options. 8. Enter the Windows Computer Name or TCP/IP address of the remote CitectSCADA computer. The Windows Computer Name is specified on the Computer Name tab of the System Properties dialog (go to Control Panel and select System). The TCP/IP address (for example, 10.5.6.7 or plant.yourdomain.com) can be determined by going to the Command Prompt, typing IPCONFIG, and pressing Enter. 9. Click OK. 10. Click the debug button to start remote debugging. Note:CitectSCADA uses Named Pipes for remote debugging. To enable the Windows

123

Chapter 14: Editing and Debugging Code

Named Pipe service, you need to enable the Server service. Select Administrative Tools from Control Panel, then select Services. Locate the Server service in the list that appears, and confirm that it is running. You can start and stop a service by right-clicking on it.

Using breakpoints
There are three ways for a processing thread to halt:
l l l

Manually inserting a breakpoint. Using the DebugBreak() Cicode function. If a hardware error is detected.

To debug a function, you need to first be able to stop it at a particular point in the code. You can place a breakpoint on any line in the source code functions. Breakpoints may be inserted or removed while editing or debugging without the need for them to be saved with the file. For a detected hardware error to halt a function, you need to have either the Break on all hardware errors or Break on hardware errors in active thread option set (Debug menu Options). When the break occurs, the default Cicode Editor will be launched (if it is not open already), with the correct code file, function, and break point line displayed. To launch the debugger in this case, you need to have the CitectSCADA will start debugger on hardware errors option set.

Inserting or removing breakpoints


You can insert and remove breakpoints to halt processing. To insert/remove a breakpoint: 1. Open the Cicode Editing window. 2. Position the cursor on the line where you want the breakpoint to be placed or removed. 3. Click the Debug indicator bar. Alternatively, you can press F9 or choose Debug | Insert/Remove Breakpoint. The breakpoint appears as a large red dot at the beginning of the line.

Enabling/disabling breakpoints
You can enable or disable breakpoints you have inserted into your Cicode.

124

Chapter 14: Editing and Debugging Code

To enable/disable a breakpoint: 1. Open the Cicode Editing Window. 2. Position the cursor on the line where the breakpoint is located. 3. Press Ctrl + F9, or choose Debug | Enable/Disable Breakpoint. Note: A disabled breakpoint appears as a large dark gray (disabled) dot at the beginning of the line.

Stepping through code


Once you have halted a thread, the debugger marks the position in the code with an arrow. Now you can step through the function, line by line, and watch what happens in the debug window (see below). The following tools are provided in the Cicode Editor, to control stepping through functions.
Step Into Advances the current Cicode thread by one statement. If the statement is a user defined function, the debugger steps into it (the pointer jumps to the first line of the source code). Advances the current Cicode thread by one statement. If the statement is a user defined function, the debugger steps over it (the function is not expanded). Advances to the end of the current function and return. If there is no calling function, the thread terminates. Re-starts normal execution of the current Cicode thread. If there are no more breaks, the thread terminates normally.

Step Over

Step Out Continue

125

Chapter 14: Editing and Debugging Code

126

Chapter 15: Using Cicode Programming Standards

Implementing programming practices results in Cicode that is more robust, manageable, and predictable in execution, regardless of the author. Using programming standards entails:
l l

Adopting modular programming techniques. Helping to ensure that programs are adequately described by suitable module headers. Formatting code to improve readability.

The following topics are presented as a suggested means of achieving good programming standards:
l l l l l l l l l l l l l

Variable Declaration Standards Variable Scope Standards Variable Naming Standards Standards for Constants, Variable Tags, and Labels Formatting Simple Declarations Formatting Executable Statements Formatting Expressions Cicode Comments Formatting Functions Modular Programming Defensive Programming Function Error handling Debug Error Trapping

See Also Using Cicode Functions

127

Chapter 15: Using Cicode Programming Standards

Variable Declaration Standards


When declaring variables you should use consistent formatting. A variable declaration has up to five parts. Each part is separated by at least one tab stop:

Note: Parts contained within square brackets are optional. For example, you may omit the variable scope (it defaults to local). Parts contained within greater than ( < ) and less than ( > ) signs should be replaced with the relevant text/value. For example, you would replace <initial value> with an actual value. (You would not bracket your value with greater than and less than signs.) When declaring your variables, the parts of each should align vertically (the scope part of each should be vertically aligned, the type part of each should be aligned, etc.). Each part of the declaration is allotted a set amount of space. If one part is missing, its space should be left blank. The missing part should not affect the positioning of the next part:
Module int string int iRecipeMax; sRecipeDefault miRecipeMax=100; ="Tasty";

See Also Using Cicode Programming Standards

Variable Scope Standards


Local variable standards Local Variables should be initialized, for example:
INT STRING iFile = 0; sName = "";

128

Chapter 15: Using Cicode Programming Standards

INT

bSuccess = FALSE;

Module variable standards Module Variables should be initialized, for example:


MODULE MODULE INT STRING mhForm = -1; msPageName = "Loop";

Global variable standards Global variables should be initialized, for example:


GLOBAL GLOBAL INT STRING ghTask = -1; gsLastPage = "Menu";

Variable Naming Standards


The following naming conventions should be applied to variables:
l

Variable names should have a small case letter prefix as follows:


Type Prefix i h b r s Used for

INT (32 bits) INT (32 bits) and OBJECT (32 bits) INT (32 bits) REAL (64 bits) STRING (255 bytes)

index, loop counter handle boolean (TRUE/FALSE) real type variables string type variables

Variable names typically consist of up to three words. Each word in a variable name should start with a capital letter, for example: Module variable names should be prefixed with an "m", for example: Global variable names should be prefixed with a "g", for example:

iTrendType, rPeriod, sFileName


l

miTrendType, mrPeriod, msFileName


l

giTrendType, grPeriod, gsFileName

129

Chapter 15: Using Cicode Programming Standards

Local variable names should not be prefixed (when you declare a variable without specifying the scope, it is considered a Local variable by default):

iTrendType, rPeriod, sFileName

See Also Using Cicode Programming Standards

Standards for Constants, Variable Tags, and Labels


When coding constants, variable tags and labels in Cicode you should try to use the following standards:
l l l

Constants Variable tags Labels

Constants

In Cicode there is no equivalent of #defines of C language, or a type that will force variables to be constants (read-only variables). However, the variable naming convention makes constants easily identifiable so developers will treat those variables as read-only variables.
l l

Constants are recommended to have the prefix `c'. Constants need to be declared and initialized at the beginning of the Cicode file and under no circumstances assigned a value again.

For example:
INT ciTrendTypePeriodic = 1; INT ciTrendTypeEvent = 2; STRING csPageName = "Mimic";

Variable tags

Variable tags that have been defined in the database (with the Variable Tags form) can be used in all functions in the Cicode files. Variable tags are identifiable because they will not have a prefix (also, they are generally in uppercase letters).

Labels

130

Chapter 15: Using Cicode Programming Standards

Labels, like variable tags, can be used in all functions in the Cicode files. They can be either all upper case letters or mixed case. In order to differentiate them from the variable tags and other Cicode variables they should have an `_' (underscore) in front of them. For example:
_BILLING_EVENT, _UNIT_OFFLINE, _AfterHoursEvent

Note: There are a few labels without an underscore defined in the Labels form in the INCLUDE project. Although they do not follow the guidelines set in this document their wide usage makes changing those labels impractical. These labels are: TRUE, FALSE, BAD_HANDLE, XFreak, XOutsideCL, XAboveUCL, XBelowLCL, XOutsideWL, XUpTrend, XDownTrend, XGradualUp, XGradualDown, XErratic, XStratification, XMixture, ROutsideCL, RAboveUCL, RBelowLCL See Also Using Cicode Programming Standards

Formatting Simple Declarations


The following conventions should be observed when formatting simple Cicode declarations:
l

Only one item should be declared per declaration; there should be no comma separated list of variables. Tab stops should be used for declarations and indentation.

For example:
INT INT INT hFile,hForm; // WRONG hFile; // RIGHT hForm; // RIGHT

The reasons for this are:


l

Only the first identifier in the WRONG case is obvious and the others are often missed in a quick glance;. It is harder to add a comment or initialization to an item in the WRONG case. Types, items, and initialization within a group of declarations should be vertically aligned.

l l

For example:

131

Chapter 15: Using Cicode Programming Standards

STRING sFileName = "temp.dat"; // WRONG INT iOffset = -1; // WRONG INT iState = 3; // WRONG STRING sFileName = "temp.dat"; // RIGHT INT iOffset = -1; // RIGHT INT iState = 3; // RIGHT

See Also Using Cicode Commands Using Cicode Programming Standards

Formatting Executable Statements


The following conventions should be observed when formatting executable statements:
l

Statements are placed on new lines, indented one tab stop from the level of their surrounding block. Note: Do not place more than one statement on a single line. While this practice is permitted in other programming languages, in Cicode the subsequent statements will not be interpreted and will effectively be lost, potentially affecting your program's runtime behavior.

UNINTENDED EQUIPMENT OPERATION Do not place more than one statement per line. Failure to follow these instructions can result in death, serious injury, or equipment damage.

Although it may be argued that some statements are logically related, this is not sufficient justification. If they are logically related, place the statements on consecutive lines and separate the statements by a blank line before and after. For example:
hFile = -1; hForm = -1; // WRONG hFile = -1; // RIGHT hForm = -1; // RIGHT

IF statements can be used in one of the formats below. When indenting the IF statements, a tab stop should be used. For example: Simple IF block

132

Chapter 15: Using Cicode Programming Standards

IF <expression> THEN ... END

IF-THEN-ELSE block
IF <expression> THEN ... ELSE ... END

To simulate ELSEIF blocks, use nested statements. For example:


IF <expression> THEN ... ELSE IF <expression> THEN ... ELSE IF <expression> THEN ... ELSE ... END END END

For WHILE and FOR statements see Working with Conditional Executors.

See Also Using Cicode Commands Working with Conditional Executors Using Cicode Programming Standards

Formatting Expressions
The following conventions should be observed when formatting Cicode functions:
l

When an expression forms a complete statement, it should, like any other statement, occupy one or more lines of its own and be indented to the current level. Operators should be surrounded by spaces. For example:
i= i*10+c-'0'; // WRONG i = i * 10 + c - '0'; // RIGHT

133

Chapter 15: Using Cicode Programming Standards

When a sub-expression is enclosed in brackets, the first symbol of the sub-expression should be placed hard against the opening bracket. The closing bracket should be placed immediately after the last character for the sub-expression. For example:
a = b * ( c - d ); a = b * (c - d); // WRONG // RIGHT

The round brackets which surround the arguments of a function attract no spaces, for example:
DisplayText( "hello" ); DisplayText("hello"); // WRONG // RIGHT

Commas, whether used as operators or separators, would be placed hard against the previous symbol and followed by a space. For example:
DevSeek(hDev ,Offset); DevSeek(hDev, Offset); // WRONG // RIGHT

See Also Using Cicode Expressions Using Cicode Commands Using Cicode Programming Standards

Cicode Comments
Comments are designed to to aid understanding and maintenance of code. You should place comments in the notes of the function header so as not to clutter up the code. Small one-line comments are acceptable to explain some small part of the code which may be hard to understand in the normal header comment. See Also Using Cicode Programming Standards

Formatting Functions
Cicode functions have up to seven parts: Scope, Type, Keyword, Name, Argument(s), Statement(s), Keyword. [Scope]

134

Chapter 15: Using Cicode Programming Standards

The scope of the function. If the scope is omitted, the function will be Public by default. That is, it will be available to all Cicode files, pages, and CitectSCADA databases (for example, Alarm.dbf). To make a function Private (that is only available within the file in which it is declared), you need to prefix it with the word PRIVATE. [Type] The return type of the function. This should be on a separate line. Keyword The keyword FUNCTION. This should be on a separate line. Name The function name. Function names should follow the Function Naming Standards. This should be on a separate line. Argument(s) The argument list. The arguments are separated by commas and they can have default values. The argument list is normally on the same line as the function name but multiple line argument list is also acceptable if it improves readability. Statement(s) The statements. Each statement should be on a separate line. Keyword The keyword END which marks the end of the function. This should be on a separate line. Note: Parts contained within square brackets - [ ] - are optional. For example, the scope may be omitted and if so, it will default to Public. Parts contained within greater than & less than signs - < > - should be replaced with the relevant text/value. For example, you would replace <initial value> with an actual value. You would not bracket your value with greater than & less than signs. For example:
FUNCTION PlotInit() <statements> END INT FUNCTION PlotOpen(STRING sName, INT nMode) INT hPlot = _BAD_HANDLE; ... hPlot = .....; ...

135

Chapter 15: Using Cicode Programming Standards

RETURN hPlot; END PRIVATE STRING FUNCTION WasteInfoName(INT nType, INT nMode) STRING sName = "Sydney"; ... sName = .....; ... RETURN sName; END

See Also Writing Functions Using Cicode Functions Using Cicode Programming Standards

Format Templates
The format of a format template string
[text]{<name>[,width[,justification]]}[text]...

Rules for valid format template display 1. If the "width" value is not present then the width is set to the length of the number of characters inclusive between '{' and '}'. This means that the field value may be truncated or padded depending on the name value length. 2. If the "width" value is specified then that is the length of the field. This means that the name value length may be truncated or padded. 3. The justification is made up of a single character with the following behaviours as specified:
l

'R' or 'r' will align the field on the right hand side. If the width is longer than the name value length then the left hand side of the name value is padded with spaces. 'L' or 'l' will align the field on the left hand side. If the width is longer than the name value length then the right hand side of the name value is padded with spaces. 'Z' or 'z' will align the field on the right hand side. If the width is longer than the name value length then the left hand side of the value is padded with zeros.

136

Chapter 15: Using Cicode Programming Standards

'N' or 'n' will remove any extra padding that is used. Essentially any padding of the name value is trimmed.

4. If a justification is not specified then the name value is assumed to be left justified. 5. Any spaces appearing after the first comma onwards in the format template will be stripped out at no penalty to the user.
Malformed format template display

There are two types of malformed templates and below are examples of each and the resulting output. Internal malformation This is when there is a correct open and close bracer '{' and '}' but inside the format template there is a malformation. For example there may be a space not a comma separating the name and the width. In this case the whole field is ignored which means nothing between and including '{' and '}' is displayed. For example: Take the following string
< { LocalTimeDate , 20 , R } > TagLabel < { Tag , 20 Desc , 20 , L } > L } > DescriptionLabel < {

The output would as follows:


< 2009-07-17 11:13:17 > TagLabel < > DescriptionLabel < ValidAlarm1Desc >

Note: The "Tag" name value is not outputted as the field has no ',' between the width and justification. Bracer malformation This is when there is an open bracer '{' but no closing bracer '}'. In this case the malformation is printed as a string literal. For example: Take the following string:
< { LocalTimeDate , 20 , R } > TagLabel < { Tag , 20 , L Desc , 20 , L } > > DescriptionLabel < {

The output would be as follows:


< 2009-07-17 11:31:44 > TagLabel < { Tag , 20 , L ValidAlarm1Desc > > DescriptionLabel <

137

Chapter 15: Using Cicode Programming Standards

Note: The "Tag" name value is outputted as a literal as no closing bracer '}' is detected. Functions Reference

Function Naming Standards


Function names should contain at least the following information:
l l l

A three-to-five letter description of the function type (Trend, Plot, Win). A one or two word description of the data to be operated on (Info, ClientInfo, Mode). A one word action to be taken (Get, Set, Init, Read).

For example:
PlotInit();TrendClientOpen();TrendClientInfoRead();

See Also Naming Functions


Source file headers

Source files (the files that contain your Cicode) should have a header to provide a basic overview of the file. This header should be formatted as follows:
//** FILE: <name of file.CI> //** //** DESCRIPTION: <description of basically what is in the file> //** //** FUNCTIONS: PUBLIC //** <list of the PUBLIC functions contained //** in this file> //** //** PRIVATE //** <list of the PRIVATE functions contained //** in this file> //** //*************** MODULE CONSTANTS*********************** <module constants> //<comments (optional)> //**************** MODULE VARIABLES *********************** <module variables> //<comments (optional)> //*********************************************************

Note: Declare all module variables at the MODULE VARIABLES section at the

138

Chapter 15: Using Cicode Programming Standards

beginning of the file and initialize the module variables. For example:
//** FILE: Recipe.CI //** //** DESCRIPTION: Contains all functions for gathering recipe data. //** //** FUNCTIONS: PUBLIC //** OpenRecipeDatabase //** CloseRecipeDatabase //** ReadRecipeData //** WriteRecipeData //** GatherRecipeData //** RecipeForm //** OpenRecipeDatabase //** //** PRIVATE //** ButtonCallback //** //*************** MODULE CONSTANTS*********************** module int cmiRecipeMax =100; //Maximum number of recipes //**************** MODULE VARIABLES *********************** module int miRecipeNumber =0; //Minimum number of recipes //*********************************************************

Function headers

Functions should have a descriptive header, formatted as follows:


//** //** //** //** //** //** //** //** //** //** //** //** FUNCTION : <name of function>

DESCRIPTION : <suggests the operation, application source and multi-tasking issues> REVISION DATE BY COMMENTS <revision number> <date> <author> <comments about the change> ARGUMENTS: <argument description> < description of possible return values>

RETURNED VALUE: NOTES:

The order of functions in a file is important for efficient operation. Initialization and shutdown functions should be placed at the top of the file. Command functions should be next. Local utility functions should be at the bottom of the file. For example:

139

Chapter 15: Using Cicode Programming Standards

//** FUNCTION : OpenRecipeDatabase //** //** DESCRIPTION : Opens the specified database. //** //** REVISION DATE BY COMMENTS //** 1 28/09/97 BS Original //** 2 05/10/97 SFA Added INI checking //** //** ARGUMENTS: //** //** STRING sName Name of the recipe database. //** //** INT dwMode Mode to open the recipe database. //** 0 for read only, 1 for read/write. //** //** RETURNED VALUE: Handle if successful, otherwise -1. //** //** NOTES: INT FUNCTION OpenRecipeDatabase(STRING sName, INT dwMode) ... END

Modular Programming
One of the more effective programming practices involves partitioning large, complex programming challenges into smaller and more manageable sub-tasks and reusable functions. A similar approach should be taken when using a programming language like Cicode to complete a task. Reducing the task to smaller tasks (or functions) has the following advantages:
l

Reduced Complexity - Once the function is created and tested, the detailed operation about how it works need not be revisited. Users need only focus on the results produced by the function. Avoids Duplicate Code - Creating a generic function instead of copying similar code reduces the total amount of code in the system. It also means the function can be reused by separate code areas. This makes the code more maintainable because it is smaller in size, and only one instance needs to be modified. Hides Information - Information can be in the form of operations, data, or resources. Access to information can be controlled when functions are written that provide a limited set of actions to be performed on the information. For example, if a user wishes to log a message to a database, he or she should only send the message to a function, say LogDBaseMessage("hello world"), and the function should control the database resource. The function then becomes the single interface to the database resource. Resources that have multiple interfaces to them are harder to control. This

140

Chapter 15: Using Cicode Programming Standards

is because in a multitasking environment, the user cannot control or even know in advance the order of code execution, and hence a resource may be modified at the same time by different tasks. Information hiding can also smooth out any wrinkles in standard functions, minimizing possible misuse of resources such as semaphores, queues, devices, and files. Functions that do this are often called `wrapper' functions as they add a protective shell to existing functions.
l

Improves Performance - Optimizing code that resides in one place immediately increases the performance of code that calls this function. Scattered code will require multiple areas to be modified should any optimization be necessary. Isolates Complex Code - Code that requires complex operations such communications protocols, complex algorithms, boolean logic, or complex data manipulation is susceptible to errors. Placing this code in a separate function reduces the possibility of this code corrupting or halting other code. Improves Readability - A small function with meaningful parameter names assists readability as it is a step towards self-documenting code and reduces the need to scan multiple pages of code to establish what the operation is meant to achieve.

Modular programming has a few rules that define how functions should be structured Cohesion - and how they are related to other functions - Coupling. See Also Defensive Programming Using Cicode Programming Standards
Cohesion

A goal of modular programming is to create simple functions that perform a single task, but perform that task well. This can be described as how 'cohesive' a function is. Two factors that affect the level of cohesion are:
l l

Number of tasks the function performs. Similarity of the tasks.

The following table illustrates the different levels of cohesion:


Number of tasks Similarity Not applicable Similar Cohesion level High Example

Sin(x)

More than 1

Moderate

SinAndTan(x)

141

Chapter 15: Using Cicode Programming Standards

Number of tasks

Similarity Dissimilar Radically different

Cohesion level Low None

Example

More than 1 Many

SinAndLength(x) SinAndDateAndTimeAndSQLNext (x)

For example, the function Sin(x) will perform one task - return the trigonometric Sine value of x. This is an example of a highly cohesive function. The function SinAndTan(x) performs two tasks - calculate the trigonometric Sine and Tan of the value X. This function has lower cohesion than Sin(x) because it performs two tasks. Highly cohesive functions are more dependable, easier to modify, and easier to debug than functions that have lower levels of cohesion and are hence acceptable and encouraged. Low cohesion functions are typically complex, prone to errors, and are more costly to fix. Low cohesion functions are regarded as poor programming practice and discouraged.
Coupling

Another rule of modular programming is to reduce the number of relationships between functions. This is referred to as function coupling. Functions that have few, or no, relationships between them are loosely coupled. Loosely coupled functions provide simple, visible interfaces to the function. This makes the functions easier to use and modify. For example, the Cicode function TimeCurrent() is a loosely coupled function. To use this function, a user need only call its name, and the function will return with the desired result. The user does not need to be aware of any relationships because there are no parameters passed to the function, and it does not read from, or write to, any global data. There is very little likelihood of error with this function; it only returns a time/date variable and does not support error codes. In the unlikely event that the function did not return the time/date variable, it would be through no error of the calling function because it has no relationship to it. Functions that have many relationships between them are tightly coupled. For example, a user written function like AddCustomerRecord(hDatabase, sFirstName, sSurname, sAddress, sAge, sPhone) has a higher level of coupling than the function TimeCurrent (). Tightly coupled functions are inflexible in their use, less robust, and harder to maintain. The AddCustomerRecord() function is less robust because it could experience an error of its own accord, or if the function calling it passes bad data to it. Tightly coupled functions are harder to maintain because modifying a function with many relationships in it may result in modifications to other functions to accept the data. The different types of function relationships are listed below:

142

Chapter 15: Using Cicode Programming Standards

Passed parameters. A simple, visible form of loose coupling that is encouraged. Once the number of parameters passed to a function exceeds seven, you should consider partitioning the function into two smaller functions. These types of relationships are acceptable. Control information. Control information causes the called function to behave in a different way. For example, the function ChangeData(iMode), behaves differently depending on the value of the variable iMode that is passed into it. It may be responsible for deleting, inserting, or updating data. In addition to being a tightly coupled function, it has low cohesion because it performs multiple tasks. This function could be divided into three separate functions to perform the separate tasks. These types of relationships are moderately acceptable. Shared common data. This is often referred to as global variable data. This is an invisible form of tight coupling that, particularly in pre-emptive, multi-tasking environments, can result in an unpredictable, hard-to-maintain program. When functions write to the global variable data there is no monitoring of or restriction on who is writing to the variable. Hence the value can be indeterminate. Global variables are acceptable when they are used for read-only purposes, otherwise their use is discouraged. Similarly, module variable data in CitectSCADA should be treated the same way. The use of local function variables is encouraged to decrease function coupling.

Defensive Programming
Defensive programming is an approach to improve software and source code. It aims to improve general quality by reducing the number of software bugs. It promotes making the source code readable and understandable. It aims to make your code behave in a predictable manner despite unexpected input or user actions. You should try to:
l l l l l l

Verify that your code does not produce unexplained hardware alarms. Check that denominators in division are not zero. Check that array indexes cannot go out of range. Check that arguments from external sources are valid. Check that loop terminations are obvious and achievable. Only write code once. If you find that two sections of code look identical or almost identical it is worth spending the time to re-write or re-design it. This will generally reduce the size of the code in question by a third or more, which reduces complexity and therefore maintenance and debugging time. An effective method to achieve this is to convert the identical code to a new function.

143

Chapter 15: Using Cicode Programming Standards

l l

Do not access the module data in any function other than the member functions. Write the member functions whenever an array is defined. Do not try to pass arrays between functions, make the arrays the centre piece of the object. Cicode is a multitasking language. Several tasks (commands, expressions and tasks created by TaskNew function) can be executed concurrently. This powerful feature of Cicode should be used with care as some of the functions may be modifying module data. It is essential that the number of tasks running at any point in time be minimized. This may require the use of semaphores to help protect the module data from interference and corruption. (For the use of semaphores, refer to SemOpen, SemClose, SemSignal and SemWait functions in on-line help or the Cicode Reference manual).

UNINTENDED EQUIPMENT OPERATION Write your Cicode programs with the minimum number of concurrent instructions suitable to your application. l Use semaphores or some related means to coordinate program flow if your program will execute a high number of concurrent instructions. Failure to follow these instructions can result in death, serious injury, or equipment damage.
l

See Also Using Cicode Programming Standards Modular Programming Function Error handling

Function Error handling


Errors are handled by examining the return values of the functions. The Cicode functions can be classified as regards their return value as follows:
Functions returning Error code only Calling functions should check for

0 no error (success) > 0 error code

Handles

-1 bad handle >= 0 valid handle

144

Chapter 15: Using Cicode Programming Standards

Functions returning Random values

Calling functions should check for

the return of IsError()

The following Cicode functions can halt the current task:


DevOpen, DevHistory, DevNext, DevPrev, DevSeek, DevFind, DevFlush, DevRecNo, DevRead, DevReadLn, DevAppend, DevDelete, DevZap, DevControl , DevPrint , DevModify, ErrTrap; FileOpen, FileClose, FileReadBlock, FileWriteBlock, FileSeek, FileDelete, FileReName, FileSize, FileReadLn, FileCopy; FormNew; SQLConnect, SQLTraceOn, SQLTraceOff, SQLErrMsg.

If an error is detected in one of these functions, your Cicode task will generate a hardware error and be halted. You may stop your Cicode task from being halted by using the ErrSet() function and checking for errors using IsError(). The parameter [Code]HaltOnError allows you to stop any errors detected in these functions from halting your Cicode. If you set. . .
[code] HaltOnError=0

then your Cicode will continue to run after a hardware error is detected in these functions. For example:
l

Example of error code only


INT FUNCTION ExampleInit() INT nError = 0; nError = ExampleOpen("MyForm"); IF nError = 0 THEN ... END END INT FUNCTION ExampleOpen(STRING sName) INT nError = 0; ... IF <an error has been detected> THEN nError = 299; END RETURN nError; END

Example of handles

145

Chapter 15: Using Cicode Programming Standards

INT FUNCTION ExampleInit() INT hFile = BAD_HANDLE; ... hFile = ExampleFileOpen("MyFile.txt"); IF hFile <> BAD_HANDLE THEN ... END END FUNCTION ExampleFileOpen(STRING sName) INT hFile = BAD_HANDLE; hFile = FileOpen(sName, "r+"); IF hFile = BAD_HANDLE THEN hFile = FileOpen(sName, "r"); END RETURN hFile; END

Example of random values


INT FUNCTION ExampleInit() INT nSamples = 0; ... ErrSet(1); nSamples = ExampleSamples(); IF IsError() = 0 THEN ... END ErrSet(0); END INT FUNCTION ExampleSamples() INT nSamples = 0; INT nError = 0; ... ErrTrap(nError); RETURN nSamples; END

See Also Debugging Cicode

146

Chapter 15: Using Cicode Programming Standards

Debug Error Trapping


The functions listed below can also be used during normal project execution to trap runtime problems:
l l

DebugMsg function Assert function

DebugMsg function

internally calls the TraceMsg() function if the debug switch is on. The implementation of this function can be found in DEBUG.CI in the INCLUDE project. You can turn the debug switch on or off by doing any of the following:
DebugMsg()
l

Calling DebugMsgSet(INT bDebugMsg) on the Kernel Cicode window. (Or, this function can be called from a keyboard command or something similar.) Changing the [Code]DebugMessage parameter in the INI file.

For example:
INT FUNCTION FilePrint(STRING sDeviceName, STRING sFileName) INT hFile; INT hDev; STRING Str1; hDev = DevOpen(sDeviceName, 0); IF (hDev = -1) THEN DebugMsg("Invalid arg to FilePrint - 'DeviceName'"); RETURN 261; /* File does not exist */ END hFile = FileOpen(sFileName, "r"); IF (hFile = -1) THEN DebugMsg("Invalid arg to FilePrint - 'FileName'"); DevClose(hDev); RETURN 261; /* File does not exist */ END WHILE NOT FileEof(hFile) DO Str1 = FileReadLn(hFile); DevWriteLn(hDev, Str1); END FileClose(hFile); DevClose(hDev); RETURN 0; END

Assert function

147

Chapter 15: Using Cicode Programming Standards

reports an error if the test passed by the argument does not return the expected value. The implementation of this function can be found in DEBUG.CI in the INCLUDE project.
Assert

For example:
INT FUNCTION FileDisplayEx(STRING sFileName) INT hFile;

hFile = FileOpen(sFileName, "r"); ASSERT(hFile <> -1); ... FileClose(hFile); RETURN 0; END

See Also Debugging Cicode

148

Part: 3
Functions Reference
This section describes Cicode functions, and provides syntax and use examples. Note: In some examples, lines of code might wrap due to page size limitations. Cicode does not support code written over more than one line and has no line continuation character. Cicode uses the semicolon (;) as the end-of-line character. If you copy these examples into your project, reassemble any lines that have wrapped and place them back onto the one line in your code. Cicode includes the following function categories:
Accumulator Functions ActiveX Functions Alarm Functions Clipboard Functions Cluster Functions Color Functions Communication Functions I/O Device Functions Keyboard Functions Mail Functions Math/Trigonometry Functions Miscellaneous Functions Page Functions Plot Functions

149

DDE Functions Device Functions Display Functions DLL Functions Equipment Database Functions Error Functions Event Functions File Functions Form Functions Format Functions FTP Functions FuzzyTech Functions Group Functions

Quality Functions Report Functions Scheduler Functions Security Functions Sequence of Event Functions SPC Functions SQL Functions String Functions Super Genie Functions Table (Array) Functions Tag Functions Task Functions Time/Date Functions Trend Functions Window Functions

150

Chapter 16: Accumulator Functions


Following are functions relating to accumulators.
AccControl AccumBrowseClose AccumBrowseFirst AccumBrowseGetField Controls accumulators for example, motor run hours. Closes an accumulator browse session. Gets the oldest accumulator entry. Gets the field indicated by the cursor position in the browse session. Gets the next accumulator entry in the browse session. Returns the number of records in the current browse session. Opens an accumulator browse session. Gets the previous accumulator entry in the browse session.

AccumBrowseNext AccumBrowseNumRecords AccumBrowseOpen AccumBrowsePrev

See Also Functions Reference

AccControl
Controls accumulators, for example, motor run hours. You can reset the values of Run Time, Totalizer Inc, and No. of Starts (defined in the Accumulator database), re-read these values from the I/O device, or flush pending writes of these values to the I/O device.
Syntax

AccControl(sName, nMode [, sClusterName] ) sName:


The name of the accumulator or a mask for the names of accumulators. You can use the following wildcards:
l

* matches all following characters, for example, "Motor*" matches all accumulators starting with the word "Motor"

151

Chapter 16: Accumulator Functions

? matches any single character, for example, "Motor?10" matches "MotorA10" and "MotorB10"

This argument can be prefixed by the name of the cluster for example ClusterName.AccumulatorName.

nMode:
The mode of the control:

1 - Reset Run Time and Totalizer value 2 - Reset No. of Starts 3 - Reset Run Time, Totalizer value, and No. of Starts 4 - Flush pending writes to the I/O device 5 - Re-read Run Time, Totalizer value, and No. of Starts from the I/O device sClusterName:
Name of the cluster in which the accumulator resides. This is optional if you have one cluster or are resolving the reports server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Example
! Reset all accumulator variables for accumulator "MCC123". AccControl("MCC123", 3, "ClusterXYZ");

See Also

Accumulator Functions

AccumBrowseClose
The AccumBrowseClose function terminates an active data browse session and cleans up all resources associated with the session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AccumBrowseClose(iSession) iSession:
The handle to a browse session previously returned by a AccumBrowseOpen call.

Return Value

152

Chapter 16: Accumulator Functions

0 (zero) if the accumulator browse session exists, otherwise an error code is returned.
Related Functions

AccumBrowseFirst, AccumBrowseGetField, AccumBrowseNext, AccumBrowseNumRecords, AccumBrowseOpen, AccumBrowsePrev See Also Accumulator Functions

AccumBrowseFirst
The AccumBrowseFirst function places the data browse cursor at the first record. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AccumBrowseFirst(iSession) iSession:
The handle to a browse session previously returned by a AccumBrowseOpen call.

Return Value

0 (zero) if the accumulator browse session exists, otherwise an error code is returned.
Related Functions

AccumBrowseClose, AccumBrowseGetField, AccumBrowseNext, AccumBrowseNumRecords, AccumBrowseOpen, AccumBrowsePrev See Also Accumulator Functions

AccumBrowseGetField
The AccumBrowseGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

STRING AccumBrowseGetField(LONG Session, STRING FieldName) Session:


The handle to a browse session previously returned by a AccumBrowseOpen call.

FieldName:

153

Chapter 16: Accumulator Functions

The name of the field that references the value to be returned. Supported fields are:

AREA, CLUSTER, EQUIPMENT, NAME, PRIV, RUNNING, STARTS, TOTALISER, TRIGGER, VALUE
See Browse Function Field Reference for information about fields.

Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

AccumBrowseClose, AccumBrowseFirst, AccumBrowseNext, AccumBrowseNumRecords, AccumBrowseOpen, AccumBrowsePrev


Example
STRING fieldValue = ""; STRING fieldName = "TYPE"; INT errorCode = 0; ... fieldValue = AccumBrowseGetField(iSession, sFieldName); IF fieldValue <> "" THEN // Successful case ELSE // Function returned an error END ...

See Also Accumulator Functions

AccumBrowseNext
The AccumBrowseNext function moves the data browse cursor forward one record. If you call this function after you have reached the end of the records, error 412 is returned (Databrowse session EOF). This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AccumBrowseNext(iSession) iSession
The handle to a browse session previously returned by a AccumBrowseOpen call.

154

Chapter 16: Accumulator Functions

Return Value

0 (zero) if the accumulator browse session exists, otherwise an error code is returned.
Related Functions

AccumBrowseClose, AccumBrowseFirst, AccumBrowseGetField, AccumBrowseNumRecords, AccumBrowseOpen, AccumBrowsePrev See Also Accumulator Functions

AccumBrowseNumRecords
The AccumBrowseNumRecords function returns the number of records that match the filter criteria. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AccumBrowseNumRecords(iSession) iSession:
The handle to a browse session previously returned by a AccumBrowseOpen call.

Return Value

The number of records that have matched the filter criteria. A value of 0 denotes that no records have matched. A value of -1 denotes that the browse session is unable to provide a fixed number. This may be the case if the data being browsed changed during the browse session.
Related Functions

AccumBrowseClose, AccumBrowseFirst, AccumBrowseGetField, AccumBrowseNext, AccumBrowseOpen, AccumBrowsePrev


Example
INT numRecords = 0; ... numRecords = AccumBrowseNumRecords(iSession); IF numRecords <> 0 THEN // Have records ELSE // No records END ...

155

Chapter 16: Accumulator Functions

See Also Accumulator Functions

AccumBrowseOpen
The AccumBrowseOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT AccumBrowseOpen( STRING Filter, STRING Fields [, STRING Clusters] ) Filter:


A filter expression specifying the records to return during the browse. An empty string indicates that all records will be returned. Where a fieldname is not specified in the filter, it is assumed to be tagname. For example, the filter "AAA" is equivalent to "name=AAA". All string fields can be filtered based on regular expressions. Using operators other than = and <> will cause strings to not match the filter criteria. The following regular expressions are supported *expr, expr*, and *expr*.

Note: Use the following fields with care in filters since they return the actual value of the variable tag which they refer to. RUNNING, STARTS, TOTALISER, TRIGGER, VALUE. Fields:
Specifies via a comma delimited string the columns to be returned during the browse. An empty string indicates that the server will return all available columns. Supported fields are:

COMMENT, EQUIPMENT, TAGGENLINK.


See Browse Function Field Reference for information about fields.

Clusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that the connected clusters will be browsed.

Return Value

Returns an integer handle to the browse session. Returns -1 when an error is detected. The returned entries will be ordered alphabetically by name. After a reload of the Report Server, any new records may be added at the end.
Related Functions

156

Chapter 16: Accumulator Functions

AccumBrowseClose, AccumBrowseFirst, AccumBrowseGetField, AccumBrowseNext, AccumBrowseNumRecords, AccumBrowsePrev


Example
INT iSession; ... iSession = AccumBrowseOpen("NAME=ABC*", "NAME,AREA", "ClusterA,ClusterB"); IF iSession <> -1 THEN // Successful case ELSE // Function returned an error END ...

See Also Accumulator Functions

AccumBrowsePrev
The AccumBrowsePrev function moves the data browse cursor back one record. If you call this function after you have reached the beginning of the records, error 412 is returned (Databrowse session EOF). This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AccumBrowsePrev(iSession) iSession:
The handle to a browse session previously returned by a AccumBrowseOpen call.

Return Value

0 (zero) if the accumulator browse session exists, otherwise an error code is returned.
Related Functions

AccumBrowseClose, AccumBrowseFirst, AccumBrowseGetField, AccumBrowseNext, AccumBrowseNumRecords, AccumBrowseOpen See Also Accumulator Functions

157

Chapter 16: Accumulator Functions

158

Chapter 17: ActiveX Functions


Following are functions relating to ActiveX objects:
_ObjectCallMethod _ObjectGetProperty _ObjectSetProperty AnByName Calls a specific method for an ActiveX object. Retrieves a specific property of an ActiveX object. Sets a specific property of an ActiveX object. Retrieves the animation point number of an ActiveX object. Creates a new instance of an ActiveX object. Creates the automation component of an ActiveX object. Allows you to change the ActiveX object's event class. Establishes an association between a variable tag and an ActiveX object property. Retrieves an ActiveX object. Queries the ActiveX component to determine if its specific interface is supported. Determines if the given handle for an object is valid. Converts an object handle to a string.

CreateControlObject CreateObject ObjectAssociateEvents ObjectAssociatePropertyWithTag ObjectByName ObjectHasInterface

ObjectIsValid ObjectToStr

See Also Functions Reference

_ObjectCallMethod
Calls a specific method for an ActiveX object. (See the documentation for your ActiveX object for details on methods and properties.) Note: The parameter list passed to the control can only have Cicode variables or

159

Chapter 17: ActiveX Functions

variable tags; it cannot use values returned directly from a function because an ActiveX control may modify parameters passed to it. For example:
//Calculate a value and pass to ActiveX control _ObjectCallMethod(hControl, "DoSomething", CalcValue());

is not allowed because the return value of a function cannot be modified. The following should be used instead:
INT nMyValue; //Calculate Value nMyValue = CalcValue(); //Pass Value to ActiveX control _ObjectCallMethod(hControl, "DoSomething", nMyValue);

Syntax

_ObjectCallMethod(hObject, sMethod, vParameters) hObject:


The handle for the object (as returned by the ObjectByName() function).

sMethod:
The name of the method.

vParameters:
A variable length parameter list of method arguments. The variables will be passed however you enter them, and will then be coerced into appropriate automation types. Likewise, any values modified by the automation call will be written back - with appropriate coercion - into the passed Cicode variable.

Return Value

The return value from the method - if successful, otherwise an error code is returned.
Related Functions

ObjectByName, DspAnCreateControlObject, CreateObject, CreateControlObject


Example

See CreateControlObject. See Also ActiveX Functions

160

Chapter 17: ActiveX Functions

_ObjectGetProperty
Gets a specific property of an ActiveX object.
Syntax

_ObjectGetProperty(hObject, sProperty) hObject:


The handle for the object (as returned by the ObjectByName() function).

sProperty:
The name of the property you want to get.

Return Value

The value of the property - if successful, otherwise error code is returned.


Related Functions

ObjectByName, DspAnCreateControlObject, CreateObject, CreateControlObject


Example

See CreateControlObject See Also ActiveX Functions

_ObjectSetProperty
Sets a specific property of an ActiveX object.
Syntax

_ObjectSetProperty(hObject, sProperty, vValue) hObject:


The handle for the object (as returned by the ObjectByName() function).

sProperty:
The name of the property you want to set.

vValue:
The value to which the property will be set. This value can be of any data type. Appropriate coercion will take place when creating the equivalent automation parameter.

Return Value

0 (zero) if successful, otherwise an error code is returned.

161

Chapter 17: ActiveX Functions

Related Functions

ObjectByName, DspAnCreateControlObject, CreateObject, CreateControlObject


Example

See CreateControlObject See Also ActiveX Functions

AnByName
Retrieves the animation point number of an ActiveX object.
Syntax

AnByName(sName) sName:
The name given to the ActiveX object. This name is visible in the "Identification" tab of the ActiveX control in the Graphics Builder and is used to access the object. If the Animation number for an object is 35 and you renamed the object to fred use AnByName ("Fred"); which will return 35. If you left the name of the object as the default use AnByName("AN35"); which will return 35.

Return Value

The animation point number of the object - if successful, otherwise an error code is returned.
Related Functions

CreateControlObject See Also ActiveX Functions

CreateControlObject
Creates a new instance of an ActiveX object. An object created using this function remains in existence until the page is closed or the associated Cicode Object is deleted. This function does not require an existing animation point. When the object is created, an animation point is created internally. This animation point is freed when the object is destroyed.
Syntax

162

Chapter 17: ActiveX Functions

CreateControlObject(sClass, sName, x1, y1, x2, y2, sEventClass) sClass:


The class of the object. You can use the object's human readable name, its program ID, or its GUID. If the class does not exist, the function will return an error message. For example:
l l l

"Calendar Control 8.0" - human readable name "MSCAL.Calendar.7" - Program ID "{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID

sName:
The name for the object in the form of "AN" followed by its AN number, for example, "AN35". This name is used to access the object.

x1:
The x coordinate of the object's top left hand corner as it will appear in your CitectSCADA window.

y1:
The y coordinate of the object's top left hand corner as it will appear in your CitectSCADA window.

x2:
The x coordinate of the object's bottom right hand corner as it will appear in your CitectSCADA window.

y2:
The y coordinate of the object's bottom right hand corner as it will appear in your CitectSCADA window.

sEventClass:
The string you would like to use as the event class for the object.

Return Value

The newly created object, if successful, otherwise an error is generated.


Related Functions

DspAnCreateControlObject, CreateObject, AnByName


Example
// This function creates a single instance of the calendar control at the designated location with an object name of "CalendarEvent" and an event class of "CalendarEvent"// FUNCTION

163

Chapter 17: ActiveX Functions

CreateCalendar() OBJECT Calendar; STRING sCalendarClass; STRING sEventClass; STRING sObjectName; sCalendarClass = "MSCal.Calendar.7"; sEventClass = "CalendarEvent"; sObjectName = "MyCalendar"; Calendar = CreateControlObject(sCalendarClass, sObjectName, 16, 100, 300, 340, sEventClass); END // This function shows how to change the title font of the calendar// FUNCTION CalendarSetFont(STRING sFont) OBJECT Font; OBJECT Calendar; Calendar = ObjectByName("MyCalendar"); Font = _ObjectGetProperty(Calendar, "TitleFont"); _ObjectSetProperty(Font, "Name", sFont); END // This function shows how to change the background color of the calendar// FUNCTION CalendarSetColor(INT nRed, INT nGreen, INT nBlue) OBJECT Calendar; Calendar = ObjectByName("MyCalendar"); _ObjectSetProperty(Calendar, "BackColor", PackedRGB(nRed,nGreen,nBlue)); END // This function shows how to call the NextDay method of the calendar// FUNCTION CalendarNextDay() OBJECT Calendar; Calendar = ObjectByName("MyCalendar"); _ObjectCallMethod(Calendar, "NextDay"); END // This function shows you how to write a mouse click event handler for the calendar// FUNCTION CalendarEvent_Click(OBJECT This) INT nDay; INT nMonth; INT nYear; nDay = _ObjectGetProperty(This, "Day"); nMonth = _ObjectGetProperty(This, "Month"); nYear = _ObjectGetProperty(This, "Year"); ... Your code goes here... ... END

See Also ActiveX Functions

164

Chapter 17: ActiveX Functions

CreateObject
Creates a new instance of an ActiveX object. If you use this function to create an ActiveX object, it will have no visual component (only the automation component will be created). If you assign an object created with the CreateObject() function to a local variable, that object will remain in existence until the variable it is assigned to goes out of scope. This means that such an object will only be released when the Cicode function that created it ends. If you assign an object created with the CreateObject() function to a module or global scope variable, then that object will remain in existence until the variable either has another object assigned or is set to NullObject, provided the CreateObject() call is not made within a loop. Objects created by calls to CreateObject() within WHILE or FOR loops are only released on termination of the Cicode function in which they are created, regardless of the scope of the variable to which the object is assigned. The use of CreateObject() within a loop may therefore result in the exhaustion of system resources, and is not generally recommended unless performed as shown in the examples below.

UNINTENDED EQUIPMENT OPERATION Do not use the CreateObject() function within a loop except in strict accordance with the following instructions. Failure to follow these instructions can result in death, serious injury, or equipment damage.

Syntax

CreateObject(sClass) sClass:
The class of the object. You can use the object's human readable name, its program ID, or its GUID. If the class does not exist, the function will return an error. For example:
l l l

"Calendar Control 8.0" - human readable name "MSCAL.Calendar.7" - Program ID "{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID

Return Value

The newly created object, if successful, otherwise an error is generated.

165

Chapter 17: ActiveX Functions

Related Functions

DspAnCreateControlObject, CreateControlObject
Example

The following examples show correct techniques for calling CreateObject() within a loop.
/* In the example below, the variable objTest associated with calls to ProcessObject() will time that function ends. */ FUNCTION Forever() WHILE 1 DO ProcessObject(); Sleep(1); END END FUNCTION ProcessObject() .OBJECT objTest; objTest=CreateObject("MyObject"); - do something END /* In the example below, the variable objTest associated with calls to ProcessObject() will objTest is set to NullObject. */ FUNCTION Forever() WHILE 1 DO ProcessObject(); Sleep(1); END END FUNCTION ProcessObject() objTest=CreateObject("MyObject"); - do something objTest=NullObject; END is local. Resources be released each

is global. Resources be released when

See Also ActiveX Functions

ObjectAssociateEvents
Allows you to change the ActiveX object's event class. If you have inserted an object on a graphics page using Graphics Builder, it allows you to change the event class to something other than the default of PageName_ObjectName
Syntax

ObjectAssociateEvents(sEventClass, hSource) sClass:

166

Chapter 17: ActiveX Functions

The class of the object. You can use the object's human readable name, its program ID, or its GUID. If the class does not exist, the function will report an error.

hSource:
The source object firing the events which are to be handled by the event handler. For example:
l l l

"Calendar Control 8.0" - human readable name "MSCAL.Calendar.7" - Program ID "{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspAnCreateControlObject, CreateControlObject
Example

Inserting ActiveX objects using Cicode If you have created an ActiveX object using Cicode (for example, by calling the function CreateControlObject()), the parameter 'sEventClass' would have required you to define an event class for the object to enable event handling. If you want to change the class you used, you can call ObjectAssociateEvents(). Inserting ActiveX objects via Graphics Builder If you have inserted an ActiveX object in Graphics Builder, runtime will automatically create an event class for the object in the form PageName_ObjectName. If this is the case, you may want to change the object's event class. Using the example of an ActiveX sludge tank controller, the default event class for the object could be "PageName_AN35". This means any events handlers for the object would take the form "PageName_AN35_Click" (presuming this example relates to a click event). You may want to define this more clearly, in which case you can call the following:
// This function redefines the event class for the ActiveX sludge tank controller at AN35 to "SludgeTank". // ObjectAssociateEvents ("SludgeTank", ObjectByName("AN35")); ..

With the event class for the object now defined as "SludgeTank", the event handlers can take the form "SludgeTank_Click".

167

Chapter 17: ActiveX Functions

This would be useful if you define event handlers in relation to an object that will eventually be copied to other graphics pages, as it will reduce the need to redefine the event handlers to identify the default event class associated with each new placement of the object. See Also ActiveX Functions

ObjectAssociatePropertyWithTag
Establishes an association between an ActiveX property and a variable tag. This means that any changes made to an ActiveX object property will be mirrored in the variable tag. Generally, ActiveX objects issue "property change notifications" to CitectSCADA whenever a change occurs to a specific property value. This notification tells CitectSCADA when to read the property value. Note: An association will not succeed if property change notifications are not supported and the OnChangeEvent argument is left blank. Verify that the scaling and units of the associated tag are compatible with the ActiveX property values. However, some property changes do not trigger property change notifications. If this is the case, you need to choose an appropriate "on change" event instead - an event fired by the ActiveX object in response to a change. An "appropriate" event is one that happens to be fired whenever the property value changes. For example, the MS Calendar Control fires an AfterUpdate event whenever a day button is pressed.
Syntax

ObjectAssociatePropertyWithTag(sObject, sPropertyName, sTagName [, sOnChangeEvent] ) sObject:


The object instance that associates a property with a tag.

sPropertyName:
The name of the ActiveX property to associate with the tag.

sTagName:
The name of the CitectSCADA variable tag to associate with the property.

sOnChangeEvent:

168

Chapter 17: ActiveX Functions

The name of the "on change" event that informs CitectSCADA of a change to the ActiveX object. This is required where the ActiveX object does not automatically generate a property change notification. Choose an event that happens to be fired whenever the ActiveX object property changes, for example, the MS Calendar Control fires an AfterUpdate event whenever a day button is pressed.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspAnCreateControlObject, CreateObject, CreateControlObject See Also ActiveX Functions

ObjectByName
Retrieves an ActiveX object. This is useful when you know the object by name only (this will often be the case for objects created during configuration, rather than those created at runtime using a Cicode function).
Syntax

ObjectByName(STRING Name) Name:


The name used to access the object, as specified when creating it in Cicode. For objects created in the Graphics Builder, the object name is set in the Access (Identification) tab, and defaults to "AN" followed by its AN number, for example, "AN35". The Name argument should be enclosed in quotes "". "".

Return Value

The requested object, if successful, otherwise an error is generated.


Related Functions

DspAnCreateControlObject, CreateObject, CreateControlObject


Example

See CreateControlObject See Also ActiveX Functions

ObjectHasInterface

169

Chapter 17: ActiveX Functions

Queries the ActiveX component to determine if its specific interface is supported. (Refer to the ActiveX object's documentation for details of its interfaces.)
Syntax

ObjectHasInterface(hObject, sInterface) hObject:


The handle for the object (as returned by the ObjectByName() function).

sInterface:
The name of the interface (case sensitive).

Return Value

0 if the interface is not supported, otherwise 1.


Related Functions

ObjectByName, CreateObject, CreateControlObject


Example
hPen = _ObjectGetProperty(hControl, "Pen"); IF ObjectHasInterface(hPen, "IDigitalPen") THEN //Fill is only supported on digital pen _ObjectSetProperty(hPen, "Fill", 0) END

See Also ActiveX Functions

ObjectIsValid
Determines if the given handle for an object is a valid handle. This function is useful for programmatically checking that an object was returned for a call.
Syntax

ObjectIsValid(hObject) hObject:
The handle for the object (as returned by the ObjectByName() function).

Return Value

0 if the handle is not valid, otherwise 1.


Related Functions

170

Chapter 17: ActiveX Functions

ObjectByName, CreateObject, CreateControlObject


Example
hFont = _ObjectGetProperty(hControl, "Font"); IF ObjectIsValid(hFont) THEN _ObjectSetProperty(hFont, "Size", 22) END

See Also ActiveX Functions

ObjectToStr
Converts an object handle to a string.
Syntax

ObjectToStr(hObject) hObject:
The handle for the object (as returned by the ObjectByName() function).

Return Value

A string containing the converted object handle


Related Functions

ObjectByName, CreateObject, CreateControlObject See Also ActiveX Functions

171

Chapter 17: ActiveX Functions

172

Chapter 18: Alarm and Alarm Filter Functions


Alarm functions display alarms and their related alarm help pages, and acknowledge, disable, and enable alarms. They provide information about alarms and allow your operators to add comments to alarm records. You can also access alarms at the record level (on the alarms server) for more complex operations. Following are functions relating to alarms:
AlarmAck AlarmAckRec AlarmAckTag AlarmActive AlarmCatGetFormat Acknowledges alarms. Acknowledges alarms by record number. Acknowledges a specified alarm Determines if any alarms are active in the user's area. Returns the display format string of the specified alarm category. Clears acknowledged, inactive alarms from the active alarm list.

AlarmClear AlarmClearRec AlarmComment AlarmCount AlarmCountList AlarmDelete AlarmDisable AlarmDisableRec AlarmDsp AlarmDspClusterAdd AlarmDspClusterInUse AlarmDspClusterRemove

Clear an alarm by its record number. Allows users to add comments to alarm summary entries. Counts the available alarms for the selected filter criteria. Counts the available alarms for the selected alarm list. This function is now obsolete. Disables alarms. Disables alarms by record number. Displays alarms. Adds a cluster to a client's alarm list. Determines if a cluster is included in a client's alarm list. Removes a cluster from a client's alarm list.

173

Chapter 18: Alarm and Alarm Filter Functions

AlarmDspLast AlarmDspNext AlarmDspPrev AlarmEnable AlarmEnableRec AlarmEventQue AlarmFirstCatRec

Displays the latest, unacknowledged alarms. Displays the next page of alarms. Displays the previous page of alarms. Enables alarms. Enables alarms by record number. Opens the alarm event queue. Searches for the first occurrence of an alarm category and type. Searches for the first occurrence of an alarm priority and type. Searches for the first occurrence of an alarm tag, name, and description. Gets the delay setting for an alarm. Gets the delay setting for an alarm via the alarm record number. Gets field data from the alarm record that is displayed at the specified AN. Gets alarm field data from the alarm record number. Gets information about an alarm list displayed at an AN. Retrieves the list of key(s) used to determine the order of the alarm list. Gets the thresholds of analog alarms. Gets the thresholds of analog alarms by the alarm record number. Displays the help page for the alarm where the cursor is positioned. Searches for the next occurrence of an alarm category and type.

AlarmFirstPriRec

AlarmFirstTagRec

AlarmGetDelay AlarmGetDelayRec

AlarmGetDsp

AlarmGetFieldRec AlarmGetInfo AlarmGetOrderbyKey

AlarmGetThreshold AlarmGetThresholdRec

AlarmHelp

AlarmNextCatRec

174

Chapter 18: Alarm and Alarm Filter Functions

AlarmNextPriRec

Searches for the next occurrence of an alarm priority and type. Searches for the next occurrence of an alarm tag, name, and description. Activates a time-stamped digital or time-stamped analog alarm Searches for the first occurrence of an alarm category (or priority) and type. Searches for the next occurrence of an alarm category (or priority) and type. Clears the filter of the specified filter source. Used to reset the filter set up by the Cicode function AlarmFilterForm(). Changes the delay setting for an alarm. Changes the delay set for an alarm via the alarm record number. Changes the display parameters for the alarm list displayed at an AN. This function is now obsolete. Use the Alarm Filter Edit Functions. Changes the thresholds of analog alarms. Changes the thresholds of analog alarms by the alarm record number. This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete.

AlarmNextTagRec

AlarmNotifyVarChange

AlarmQueryFirstRec

AlarmQueryNextRec

AlarmResetQuery

AlarmSetDelay AlarmSetDelayRec

AlarmSetInfo

AlarmSetQuery

AlarmSetThreshold AlarmSetThresholdRec

AlarmSplit AlarmSumAppend AlarmSumCommit AlarmSumDelete AlarmSumFind AlarmSumFirst

175

Chapter 18: Alarm and Alarm Filter Functions

AlarmSumGet AlarmSumLast AlarmSumNext AlarmSumPrev AlarmSumSet AlarmSumSplit AlarmSumType AlmBrowseAck

This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete. This function is now obsolete. Acknowledges the alarm tag at the current cursor position in an active data browse session. This function is now obsolete. Closes an alarm tags browse session. Disables the alarm tag at the current cursor position in an active data browse session. Enables the alarm tag at the current cursor position in an active data browse session. Gets the oldest alarm tags entry. Gets the field indicated by the cursor position in the browse session. Gets the next alarm tags entry in the browse session. Returns the number of records in the current browse session. Opens an alarm tags browse session. Gets the previous alarm tags entry in the browse session. Acknowledges the alarm at the current cursor position in an active data browse session. Clears the alarm at the current cursor position in an active

AlmBrowseClear AlmBrowseClose AlmBrowseDisable

AlmBrowseEnable

AlmBrowseFirst AlmBrowseGetField

AlmBrowseNext AlmBrowseNumRecords

AlmBrowseOpen AlmBrowsePrev AlmSummaryAck

AlmSummaryClear

176

Chapter 18: Alarm and Alarm Filter Functions

data browse session. AlmSummaryClose AlmSummaryCommit AlmSummaryDelete AlmSummaryDeleteAll AlmSummaryDisable Closes an alarm summary browse session. This function is now obsolete. Deletes alarm summary entries from the browse session. Deletes all alarm summary entries from the browse session. Disables the alarm at the current cursor position in an active data browse session. Enables the alarm at the current cursor position in an active data browse session. Gets the oldest alarm summary entry. Gets the field indicated by the cursor position in the browse session. Places the data browse cursor at the latest summary record from the last cluster of the available browsing cluster list. Gets the next alarm summary entry in the browse session. Retrieves the number of records in an alarm summary browse session. Opens an alarm summary browse session. Gets the previous alarm summary entry in the browse session. This function is now obsolete.

AlmSummaryEnable

AlmSummaryFirst AlmSummaryGetField

AlmSummaryLast

AlmSummaryNext AlmSummaryNumRecords AlmSummaryOpen AlmSummaryPrev

AlmSummarySetFieldValue AlmTagsAck AlmTagsClear AlmTagsClose AlmTagsDisable

Deprecated in this version Deprecated in this version Deprecated in this version Deprecated in this version

177

Chapter 18: Alarm and Alarm Filter Functions

AlmTagsEnable AlmTagsFirst AlmTagsGetField AlmTagsNext AlmTagsNumRecords AlmTagsOpen AlmTagsPrev HwAlarmQue

Deprecated in this version Deprecated in this version Deprecated in this version Deprecated in this version Deprecated in this version Deprecated in this version Deprecated in this version Returns the handle of the hardware alarm queue.

Alarm Filter Functions

Following are the functions relating to alarm filters:


AlarmFilterEditFirst AlarmFilterClose AlarmFilterEditAppend AlarmFilterEditClose AlarmFilterEditCommit AlarmFilterEditLast AlarmFilterEditNext AlarmFilterEditOpen AlarmFilterEditPrev AlarmFilterEditSet Retrieves the first part of the filter. Removes the session from memory. Appends the provided expression to the current filter session content without any validation. Removes the session from the memory.

Validates the filter built in this session and, if valid, applies the filter to the list associated with the session. Retrieves the last part of the filter. Retrieves the next part of the filter. Creates a session for the historical list associated with the provided animation number (aN) or FilterName. Retrieves the previous part of the filter. It replaces the current filter session content by the provided expression without any validation. Available when using the Legacy Filter Form. Use to display an alarm form to specify filter criteria for an alarm list or a named filter.

AlarmFilterForm

178

Chapter 18: Alarm and Alarm Filter Functions

AlarmFilterOpen AlarmGetFilterName AlarmResetQuery

Creates a new named filter. Retrieves the name of the filter for the AN. Use when using the AlarmFilterForm(). Clears the filter of the specified filter source. Displays a generic alarm filter popup for specifying filter criteria for either an alarm list or named filter. Only available if 'Lib_controls' project is included in main project.

LibAlarmFilterForm

See Also Functions Reference

AlarmAck
Acknowledges alarms. You can acknowledge the alarm where the cursor is positioned, one or more alarm lists on the active page, a whole category of alarms, or alarms of a particular priority. This command takes the currently logged in user into account. In other words, only the alarms that the user can see are acknowledged. You would normally call this function from a keyboard command. No action is taken if the specified alarms have already been acknowledged. Note:Alarm commands on single clusters will return either 0 if successful or an error code if unsuccessful. Alarm commands across multiple clusters may also return a partial success result, whereby a command has been successful on 'at least' one cluster but unsuccessful on another cluster.
Syntax

INT AlarmAck(INT Mode, INT Value [, STRING ClusterName]) Mode:


The type of acknowledgment:

0 - Acknowledge a single alarm. l Set Value to the AN where the alarm is displayed. l If Value is set to 0, the current cursor position will be used. 1 - Acknowledge a page of alarms. An alarm page can contain more than one alarm list: l Set Value to the AN where the alarm list is displayed. l Set Value to 0 to acknowledge the (displayed) alarm list (on the active page) where the cursor is positioned.

179

Chapter 18: Alarm and Alarm Filter Functions

Set Value to -1 to acknowledge all (displayed) alarm lists on the active page.This only applies to alarm lists created using AlarmDsp (and not those created using AlarmDspLast).

2 - Acknowledge a category of alarms: l Set Value to the alarm category (0 to 16375) of the alarms to be acknowledged. Please be aware that Alarm category 0 indicates all categories; alarm category 255 indicates hardware alarms. l Set Value to the group number to acknowledge a group of categories. 3 - Acknowledge alarms of a specific priority. l Set Value to the alarm priority (0-255) of the alarms to be acknowledged. Alarm priority 0 indicates all priorities. Hardware alarms are not affected by priority. Set Value to the group handle to acknowledge a group of alarms of different priorities. Value:
Used with Mode 1 and 2 to specify which alarms to acknowledge.

sClusterName:
Used with Mode 2 or 3 to specify the name of the cluster in which the alarms being acknowledged reside. This argument is optional if the client is connected to only one cluster containing an Alarm Server or are resolving the alarm server via the current cluster context. This argument is not required where:
l

the mode is 2 and the value is 255 (hardware alarm category).

This argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code will return


Note: In some cases an error code is not returned.This function is non-blocking, and as such, any error that is detected when the alarm server processes the command will not be returned.

Related Functions

GrpOpen
Example

System Keyboard Key Sequence LeftButton

180

Chapter 18: Alarm and Alarm Filter Functions

Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment

AlarmAck(0, 0) Acknowledge the alarm where the cursor is positioned

ShiftLeftButton AlarmAck(1, -1) Acknowledge a page of alarms

AlarmAck ### Enter AlarmAck(2, Arg1, "clusterXYZ") Acknowledge alarms of a specified category in cluster XYZ

AckPri ############# Enter AlarmAck(3,Arg1, "clusterXYZ") Acknowledge alarms of a specific priority in cluster XYZ

! Acknowledge alarms of the specified group of categories. FUNCTION AckGrp(STRING CategoryGroup) INT hGrp; hGrp=GrpOpen("CatGroup",1); StrToGrp(hGrp,CategoryGroup); AlarmAck(2,hGrp, "clusterXYZ"); GrpClose(hGrp); END

See Also Alarm Functions

AlarmAckRec

181

Chapter 18: Alarm and Alarm Filter Functions

Acknowledges alarms by record number on both the Primary and Standby Alarm Servers. This function can be called from Alarm Server or Client and should not be used with a MsgRPC() call to the Alarm Server. This is a blocking function. If the function is called from a foreground task that is unable to block, an error will be returned.
Syntax

INT AlarmAckRec(LONG Record [, STRING ClusterName] ) Record:


The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec(): used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec(): used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec(): used to search for a record by alarm tag, name, and description. AlarmGetDsp(): used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmFirstCatRec, AlarmFirstTagRec, AlarmNextTagRec, AlarmGetDelayRec


Example
/* Acknowledge all unacknowledged (Type 1) alarms of the specified alarm category. */ FUNCTION AutoAccept(INT Category) INT Current; INT Next; Current=AlarmFirstCatRec(Category,1); WHILE Current<>-1 DO

182

Chapter 18: Alarm and Alarm Filter Functions

Next=AlarmNextCatRec(Current,Category,1); AlarmAckRec(Current); Current=Next; END END

See Also Alarm Functions

AlarmAckTag
Acknowledge a specified alarm.
Syntax

INT AlarmAckTag(STRING Tag, [, STRING ClusterName]) Tag:


The name of the tag to acknowledge

ClusterName:
The cluster where the tag resides

Return Value

0 (zero) if successful, otherwise an error code will return


Example

See Also Alarm Functions

AlarmActive
Determines if any alarms are active in the user's area. Call this function from the Page Strings database, to display an alarm message at a specified AN on a graphics page. You can specify the type of alarms, for example, active hardware alarms or disabled non-hardware alarms.
Syntax

AlarmActive(Type [, sClusterName] ) nType:


The type of alarms to check:

Non-hardware alarms 0 - Active alarms

183

Chapter 18: Alarm and Alarm Filter Functions

1 - Unacknowledged alarms, ON and OFF 2 - Highest priority unacknowledged alarm 3 - Disabled alarms Hardware alarms 5 - Active alarms 6 - Unacknowledged alarms, ON and OFF sClusterName:
The name of the cluster to check for active alarms. If this argument is blank or empty, the function will check the connected clusters.

Return Value
l l l

1 or 0 for Non-hardware alarms (modes 0, 1, and 3). The priority of the highest priority unacknowledged alarm (mode 2). The number of active alarms for Hardware alarms (modes 5 and 6).

Example

Strings AN Expression True Text False Text Comment 9 AlarmActive(5) "Hardware Alarms Active" "No Active Hardware Alarms" Display the alarm status at AN 9

See Also Alarm Functions

AlarmCatGetFormat
Returns the display format string of the specified alarm category.
Syntax

STRING AlarmCatGetFormat(INT Category [, INT Type] ) Category:


The alarm category.

Type:

184

Chapter 18: Alarm and Alarm Filter Functions

The type of display format string:


l l l

0 - Alarm format. Default value. 1 - Summary format. 2 - SOE format

Return Value

The display format string of the specified category. If the alarm category is not specifically defined or it has no format string specified in your project, the format string of category 0 will be returned.
Example
sFormat = AlarmCatGetFormat(0, 0); ! sFormat is assigned to the format string as defined in the Alarm Format field of the Alarm Categories form for category 0 in your project.

See Also Alarm Functions

AlarmClear
Clears an acknowledged (and off) alarm from the active alarm list. You can clear the alarm where the cursor is positioned, one or more alarm lists on the active page, a whole category of alarms, or alarms of a particular priority. If you set the [Alarm]AckHold parameter to 1, alarms that go off and have been acknowledged are not removed from the active list until this function is called.
Syntax

AlarmClear(Mode, Value [, ClusterName] ) Mode:


The type of clear:

0 - Clear a single alarm where the cursor is positioned: l Set Value to 0 (zero) - it is not used. 1 - Clear a page of alarms. AN alarm page can contain more than one alarm list: l Set Value to the AN where the alarm list is displayed. l Set Value to 0 to clear the (displayed) alarm list (on the active page) where the cursor is positioned. l Set Value to -1 to clear every (displayed) alarm list on the active page. 2 - Clear a category of alarms:

185

Chapter 18: Alarm and Alarm Filter Functions

Set Value to the alarm category (0 to 16375) of the alarms to clear. Please be aware that alarm category 0 indicates all categories; alarm category 255 indicates hardware alarms. Set Value to the group number to clear a group of categories.

3 - Clear alarms of a specific priority. l Set Value to the alarm priority (0-255) of the alarms to be cleared. Alarm priority 0 indicates all priorities. Hardware alarms are not affected by priority. Set Value to the group handle to clear a group of alarms of different priorities. Value:
Used with Mode 1 or 2 to specify which alarms to clear.

ClusterName:
Used with Mode 2 or 3 to specify the name of the cluster in which the alarms being cleared reside. This argument is optional if the client is connected to only one cluster containing an Alarm Server or you are resolving the alarm server via the current cluster context. This argument is not required where:
l

the mode is 2 and the value is 255 (hardware alarm category).

This argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

AlarmAck
Example
System Keyboard Key Sequence Command Comment System Keyboard Key Sequence ClearAll Clear AlarmClear(0, 0) Clear the alarm where the cursor is positioned

186

Chapter 18: Alarm and Alarm Filter Functions

Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment

AlarmClear(1, -1) Clear a page of alarms

AlarmClear ### Enter AlarmClear(2, Arg1, "clusterXYZ") Clear alarms of a specified category in cluster XYZ

CtrlClear AlarmClear(2, 0, "clusterXYZ") Clear categories of inactive alarms in cluster XYZ

ClearPri ########### Enter AlarmClear(3,Arg1, "clusterXYZ") Clear alarms of a specific priority in cluster XYZ

See Also Alarm Functions

AlarmClearRec
Clears an alarm by its record number on both the Primary and Standby Alarms Servers. This function can be called from Alarm Server or Client. This function should not be used with a MsgRPC() call to the Alarm Server.
Syntax

AlarmClearRec(Record [, ClusterName] ) Record:


The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.).

187

Chapter 18: Alarm and Alarm Filter Functions

AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

AlarmFirstCatRec, AlarmAck, AlarmFirstTagRec, AlarmNextTagRec, AlarmGetDelayRec, MsgRPC See Also Alarm Functions

AlarmComment
Allows an operator to add a comment to a selected alarm summary or SOE entry during runtime. You would normally call this function from a keyboard command.
Syntax

INT AlarmComment(STRING Comment[, INT An]) Comment:


The comment to add to the alarm summary entry. Currently for the Alarm summary page the maximum length of a comment is 128 characters. The maximum length for a comment on the SOE page is 244 characters. If you exceed the maximum length it will be truncated and an ellipsis appended.

AN:
An animation identifier. It is required that this animation is an alarm event.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

188

Chapter 18: Alarm and Alarm Filter Functions

AlarmDsp
Example

System Keyboard Key Sequence Command Comment Com ################## Enter

AlarmComment(Arg1) Add an alarm comment to the alarm where the cursor is positioned

See Also Alarm Functions

AlarmCount
Counts the available alarms for the selected filter criteria.
Syntax

LONG AlarmCount(INT Type [, STRING FilterCriteria [, LONG KeepAliveSeconds [, INT CachedMode]]]) Type 0 All active alarms,that is Types 1 and 2 1 All unacknowledged alarms, On and OFF 2 All acknowledged ON alarms 3 All disabled alarms 4 - All configured (non-hardware) alarms 11 - All ON alarms 12 - All OFF alarms. FilterCriteria:
A filter name OR filter text Refer to the topic Implementing alarm filters using Cicode for more information regarding filter syntax.

KeepAliveSeconds:
Optional length of time (in seconds) that the count will remain in memory.

CachedMode:

189

Chapter 18: Alarm and Alarm Filter Functions

Optional flag that causes the current cached value to be supplied even when the value is being refreshed. This makes the function non-blocking. If the property has not yet been cached, an error is set. 0 - Do not force cached read. Cicode is blocking 1 - Force cached read. Cicode is non-blocking Default value is 1 (true).

A count in memory will be accessed when its filter criteria matches a subsequent filter criteria and the counts KeepAliveSeconds period will be extended. A count will stay in the cache for 'at least' the duration specified by KeepAliveSeconds, and may stay in the cache for an unspecified period of time before being discarded. The period set for an existing count will be overridden in the event a longer duration is set using 'KeepAliveSeconds". A count that is added to the cache is not immediately available for reading, so a foreground call to AlarmCount that causes a new count to be added will return a value of -1 and an error of 345 (Data not ready).
Return Value

Returns counted alarms for the selected filter criteria. Returns -1 when an error is detected.
Example

INT INT

iRet, iErr; iCountWhile=0;

// return values // loop counter

// counts all unacknowledged alarms, ON and OFF, default non-blocking cicode

iRet = AlarmCount(1); iErr = IsError(); //check error code

// repeat the above non-blocking function INT iCountWhile=0; // loop counter WHILE (iRet = 0) AND (iErr = 0) AND (iCountWhile < 10) DO SleepMS(100); iRet = AlarmCount(1); iErr = IsError(); iCountWhile = iCountWhile + 1; END

190

Chapter 18: Alarm and Alarm Filter Functions

// counts all disabled alarms, default non-blocking cicode iRet = AlarmCount(3); iErr = IsError(); // repeat this non-blocking function as shown above (see while loop) // counts all unacknowledged alarms with category 10 non-blocking cicode iRet = AlarmCount(1,Category=10,1,1); iErr = IsError(); // repeat this non-blocking function as shown above (see while loop) // counts all unacknowledged alarms with category 10 blocking cicode iRet = AlarmCount(1,Category=10,1,0); IF iRet = -1 THEN iErr = IsError(); // get error code) END

// counts all unacknowledged tag alarms of equipA without it's children equipment // and keeps the count in memory for 3 seconds - blocking cicode // (where is equipment structure is equipA.equipB.equipC.equipD) iRet = AlarmCount(1,Equipment=equipA,3,0); IF iRet = -1 THEN iErr = IsError(); // get error code) END // counts all acknowledged ClusterA tag ON alarms of equipA and it's children equipment // and keeps the count in memory for 3 seconds - blocking cicode // (where is equipment structure is equipA.equipB.equipC.equipD) iRet = AlarmCount(2,Equipment=equipA*;cluster=ClusterA,3,0); IF iRet = -1 THEN iErr = IsError(); // get error code) END // counts all active tag alarms of equipB and it's children equipment // and keeps the count in memory for 3 seconds - non-blocking cicode // (where is equipment structure is equipA.equipB.equipC.equipD) iRet = AlarmCount(0,Equipment=equipA.equipB*,3,1); iErr = IsError() // counts all ON alarms of equipB and it's children equipment // and keeps the count in memory for 3 seconds - non-blocking cicode // (where is equipment structure is equipA.equipB.equipC.equipD) iRet = AlarmCount(11,Equipment=equipA.equipB*,3,1); iErr = IsError()

// This example shows how to count the alarms using a named filter // This example requires that the named filter "Myfilter" exists. INT nActiveAlarmType; INT nCount; INT nError;

191

Chapter 18: Alarm and Alarm Filter Functions

nCount = AlarmCount(nActiveAlarmType, "MyFilter"); IF nCount greater 0 THEN nError = IsError(); ELSE nError = 0; END

Related Functions

AlarmCountList See Also Alarm Functions

AlarmCountList
Counts the available alarms for the selected filter criteria.
Syntax

LONG AlarmCountList(INT AN) AN:


An animation identifier of an alarm list.

Return Value

Returns counted alarms for the selected filter criteria. Returns -1 when an error is detected.
Example
// counts all listed alarms on the slected alarm page INT iRet, iErr; // return values iRet = AlarmCountList(21); IF iRet = -1 THEN iErr = IsError(); // get error code) END

Related Functions

AlarmCount

192

Chapter 18: Alarm and Alarm Filter Functions

See Also Alarm Functions

AlarmDisable
Disables alarms. You can disable the alarm where the cursor is positioned, one or more alarm lists on the active page, a whole category of alarms, or alarms of a particular priority. You would normally call this function from a keyboard command. No action is taken if the alarms are already disabled. Use the AlarmEnable() function to re-enable an alarm. After you disable an alarm, it does not display on the alarm page, alarm summary page, or alarm log. If you set the [Alarm]DisplayDisable parameter to 1, logging of disabled alarms continues, but the disabled alarms are not displayed on the alarm display or alarm summary pages.
Syntax

INT AlarmDisable(INT Mode, INT Value [, STRING ClusterName] ) Mode:


The type of disable:

0 - Disable a single alarm where the cursor is positioned. l Set Value to the AN where the alarm list is displayed. l If Value is set to 0, the current cursor position will be used. 1 - Disable a page of alarms. An alarm page can contain more than one alarm list: l Set Value to the AN where the alarm list is displayed. l Set Value to 0 to disable the (displayed) alarm list (on the active page) where the cursor is positioned. l Set Value to -1 to disable all (displayed) alarm lists on the active page. This only applies to alarm lists created using AlarmDsp (and not those created using AlarmDspLast). 2 - Disable a category of alarms. l Set Value to the alarm category (0-16375) of the alarms to be disabled. Please be aware that alarm category 0 indicates all categories; alarm category 255 indicates hardware alarms. l Set Value to the group number to disable a group of categories. 3 - Disable alarms of a specific priority. l Set Value to the alarm priority (0-255) of the alarms to be disabled. Alarm priority 0 indicates all priorities. Hardware alarms are not affected by priority. Set Value to the group handle to disable a group of alarms of different priorities. Value:

193

Chapter 18: Alarm and Alarm Filter Functions

Used with Mode 1 and 2 to specify which alarms to disable.

ClusterName:
Used with Mode 2 or 3 to specify the name of the cluster where the alarms being disabled reside in. This argument is optional if the client is connected to only one cluster containing an Alarm Server or are resolving the alarm server via the current cluster context. This argument is not required where:
l

the mode is 2 and the value is 255 (hardware alarm category).

This argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

GrpOpen, AlarmEnable, AlarmDisableRec


Example

System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment AlarmDisable ### Enter AlarmDisable(2, Arg1, "clusterXYZ") Disable alarms of a specified category in cluster XYZ ShiftDisable AlarmDisable(1, -1) Disable a page of alarms Disable AlarmDisable(0, 0) Disable the alarm where the cursor is positioned

194

Chapter 18: Alarm and Alarm Filter Functions

System Keyboard Key Sequence Command Comment DisPri ############# Enter AlarmDisable(3,Arg1,"clusterXYZ") Disable alarms of a specific priority in cluster XYZ

See Also Alarm Functions

AlarmDisableRec
Disables alarms by record number on both the Primary and Standby Alarms Servers. This function can be called from Alarm Server or Client and should not be used with a MsgRPC() call to the Alarm Server. This is a blocking function. If the function is called from a foreground task that is unable to block, an error will be returned.
Syntax

INT AlarmDisableRec(LONG Record [, STRING ClusterName] ) Record:


The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.

195

Chapter 18: Alarm and Alarm Filter Functions

Related Functions

AlarmFirstTagRec, AlarmNextTagRec, AlarmDisable


Example
/* Disable/enable the specified "Pump" alarm. Flag determines whether the alarm is disabled (Flag=0) or enabled (Flag=1). */ FUNCTION DisablePumps(STRING sTag, INT Flag) INT Current; INT Next; Current=AlarmFirstTagRec(sTag,"Pump",""); WHILE Current<>-1 DO Next=AlarmNextTagRec(Current,sTag,"Pump",""); IF Flag=0 THEN AlarmDisableRec(Current); ELSE AlarmEnableRec(Current); END Current=Next; END END

See Also Alarm Functions

AlarmDsp
Displays an alarm list, starting at a specified AN and then on subsequent ANs. You specify the number of alarms to display, the type of alarms and the name of the cluster the alarms belong to, for example, active hardware alarms or disabled non-hardware alarms in cluster XYZ. Before you call this function, you need to first add animation points to the graphics page for each alarm to be displayed. If you only need to display the standard alarm page, use the PageAlarm function - it uses this AlarmDsp() function to display alarms. If you need more control over the display of alarms you can use this function, but only to display alarms on the alarm page. Use the AlarmDspLast function to display alarms on another graphics page (it uses less memory).
Syntax

INT AlarmDsp(INT AN, Count [, INT Type] [, STRING ClusterName] [, INT NoDraw] [, STRING CallbackFunc] ) AN:
The AN where the first alarm is to display.

196

Chapter 18: Alarm and Alarm Filter Functions

Note: The [Animator]MaxAn citect ini parameter sets the maximum AN which AlarmDsp will work with. Count:
The number of alarms to display.

Type:
The type of alarms to display: Non-hardware alarms

0 - All active alarms, that is Types 1 and 2 1 - All unacknowledged alarms, ON and OFF 2 - All acknowledged ON alarms 3 - All disabled alarms 4 - All configured (non-hardware) alarms, that is Types 0 to 3, plus acknowledged OFF alarms.
Hardware alarms

5 6 7 8 9

- All - All - All - All - All

active alarms, that is Types 6 and 7 unacknowledged alarms, ON and OFF acknowledged ON alarms disabled alarms configured alarms, that is Types 5 to 8

Alarm Summary

10 - All summary alarms 15 Sequence of event list


Alarm General

11 12 13 14

- All - All - All - All

ON alarms OFF alarms ON hardware alarms OFF hardware alarms

If you omit the Type, the default is 1.

ClusterName:
The cluster name to which the alarms belong. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "". If the client is connected to only one cluster containing an Alarms Server then this argument is optional, the list returned will be limited to alarms within this cluster. If the client is connected to clusters containing more than one Alarms Server then the Cluster Name needs to be specified. If a cluster name is not specified, alarms are returned for all clusters.

NoDraw:
197

Chapter 18: Alarm and Alarm Filter Functions

Makes call to Alarm Server to update the ALMCB but does not automatically perform the animation of the data when the result is returned.

CallbackFunc:
Callback function to associate with the return of the ALMCB data from the Alarm Server.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmDspNext, AlarmDspPrev, AlarmDspLast, AlarmGetInfo, PageAlarm, AlarmDspClusterAdd, AlarmDspClusterRemove, AlarmDspClusterInUse


Example

Advanced Animation Command Comment AlarmDsp(20,15,3) Display 15 disabled alarms at AN 20

See Also Alarm Functions

AlarmDspClusterAdd
Adds a cluster to a client's alarm list. Alarms in the specified cluster (that correspond to the mode set in AlarmDsp) will be added to the alarm list at the AN number.
Syntax

AlarmDspClusterAdd(nAN, sClusterName) nAN:


The AN used in the original AlarmDsp() call.

sClusterName:
The name of the cluster to be used for this alarm list. The argument is enclosed in quotation marks ("").

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

198

Chapter 18: Alarm and Alarm Filter Functions

AlarmDspClusterRemove AlarmDSPClusterInUse AlarmDsp See Also Alarm Functions

AlarmDspClusterInUse
Determines if a cluster is included in a client's alarm list.
Syntax

AlarmDspClusterInUse(nAN, sClusterName) nAN:


The AN used in the original AlarmDsp() call.

sClusterName:
The name of the cluster to query an alarm list for to determine if it's included. The argument is enclosed in quotation marks ("").

Return Value
Returns a Boolean value: True(1) if successful, otherwise False(0) is returned.

Related Functions

AlarmDspClusterAdd, AlarmDSPClusterRemove, AlarmDsp See Also Alarm Functions

AlarmDspClusterRemove
Removes a cluster from a client's alarms list. Alarms for the specified cluster will be removed from the alarms list at the AN number. If the cluster to be removed is the last cluster, the call will be unsuccessful.
Syntax

AlarmDspClusterRemove(nAN, sClusterName) nAN:


The AN used in the original AlarmDsp() call.

sClusterName:
The name of the cluster to remove from this alarm list. The argument is enclosed in quotation marks ("").

Return Value

199

Chapter 18: Alarm and Alarm Filter Functions

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmDspClusterAdd, AlarmDSPClusterInUse, AlarmDsp See Also Alarm Functions

AlarmDspLast
Displays the latest alarms, at a specified AN with the cluster name. Use this function to display the last alarms. You can specify the number of alarms to display of a specified type, for example, active hardware alarms or disabled non-hardware alarms.
Syntax

AlarmDspLast(nAN [, nCount] [, nType] [, sClusterName] [, iNoDraw] [, sCallbackFunc] ) nAN: Note: The [Animator]MaxAn citect ini parameter sets the maximum AN which AlarmDspLast will work with.
The AN where the last alarms are to be displayed.

Count:
The number of alarms to display. If you omit the Count, the default is 1.

nType:
The type of alarms to display: Non-hardware alarms

0 - All active alarms, that is Types 1 and 2 1 - All unacknowledged alarms, ON and OFF 2 - All acknowledged ON alarms 3 - All disabled alarms 4 - All configured (non-hardware) alarms, that is Types 0 to 3, plus acknowledged OFF alarms.
Hardware alarms

5 - All active alarms, that is Types 6 and 7 6 - All unacknowledged alarms, ON and OFF 7 - All acknowledged ON alarms 8 - All disabled alarms 9 - All configured alarms, that is Types 5 to 8

200

Chapter 18: Alarm and Alarm Filter Functions

Alarm Summary

10 - All summary alarms


Alarm General

11 - All ON alarms 12 - All OFF alarms 13 - All ON hardware alarms 14 - All OFF hardware alarms
If you omit the Type, the default is 1.

sClusterName:
The cluster name to which the alarms belong. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "". If a cluster name is not specified, alarms are returned for all clusters.

iNoDraw:
Makes call to Alarm Server to update the ALMCB but does not automatically perform the animation of the data when the result is returned.

sCallbackFunc:
Callback function to associate with the return of the ALMCB data from the Alarm Server.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmDsp
Example

Advanced Animation Command Comment Advanced Animation Command Comment AlarmDspLast(21,3, 'ClusterXYZ') Display the last 3 alarms at AN 21 AlarmDspLast(11, 'ClusterXYZ') Display the last alarm at AN 11

201

Chapter 18: Alarm and Alarm Filter Functions

See Also Alarm Functions

AlarmDspNext
Displays the next page of alarms. This function pages down (scrolls) the alarms displayed by the AlarmDsp() function. You would normally call this function from a keyboard command.
Syntax

INT AlarmDspNext(INT AN) AN:


The AN where the alarm list is displayed, or:

-1 - Scroll every alarm list displayed on the page. 0 - Scroll the alarm list where the cursor is positioned. Note: An alarm page can contain more than one alarm list.
Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmDsp, AlarmDspPrev
Example

System Keyboard Key Sequence Command Comment NextAlarm AlarmDspNext(20) Display the next page of alarms (from the alarm list) at AN20

See Also Alarm Functions

AlarmDspPrev

202

Chapter 18: Alarm and Alarm Filter Functions

Displays the previous page of alarms. This function pages up (scrolls) the alarms displayed by the AlarmDsp() function. You would normally call this function from a keyboard command.
Syntax

INT AlarmDspPrev(INT AN) AN:


The AN where the alarm list is displayed, or:

-1 - Scroll every alarm list displayed on the page. 0 - Scroll the alarm list where the cursor is positioned. Note: An alarm page can contain more than one alarm list.
Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmDsp, AlarmDspNext
Example

System Keyboard Key Sequence Command Comment PrevAlarm

AlarmDspPrev(20) Display the previous page of alarms (from the alarm list) at AN20

See Also Alarm Functions

AlarmEnable
Enables an alarm on the active alarm list. You can enable the alarm where the cursor is positioned, one or more alarm lists on the active page, a whole category of alarms, or alarms of a particular priority. No action is taken if the alarms are already enabled. You would normally call this function from a keyboard command.

203

Chapter 18: Alarm and Alarm Filter Functions

Syntax

INT AlarmEnable(INT Mode, INT Value [, STRING ClusterName] ) Mode:


The type of enable:

0 - Enable a single alarm where the cursor is positioned. l Set Value to the AN where the alarm list is displayed. l If value is set to 0, the current cursor position will be used. 1 - Enable a page of alarms. An alarm page can contain more than one alarm list: l Set Value to the AN where the alarm list is displayed. l Set Value to 0 to enable the (displayed) alarm list (on the active page) where the cursor is positioned. l Set Value to -1 to enable all (displayed) alarm lists on the active page.This only applies to alarm lists created using AlarmDsp (and not those created using AlarmDspLast). 2 - Enable a category of alarms. l Set Value to the alarm category (0-16375) of the alarms to be enabled. Please be aware that alarm category 0 indicates all categories; alarm category 255 indicates hardware alarms. l Set Value to the group number to enable a group of categories. 3 - Enable alarms of a specific priority. l Set Value to the alarm priority (0-255) of the alarms to be enabled. Alarm priority 0 indicates all priorities. Hardware alarms are not affected by priority. 3) Set Value to the group handle to enable a group of alarms of different priorities. Value:
Used with Mode 0, 1 and 2 to specify which alarms to enable.

ClusterName:
Used with Mode 2 or 3 to specify the name of the cluster where the alarms being enabled reside in. This argument is optional if the client is connected to only one cluster containing an Alarm Server or are resolving the alarm server via the current cluster context. This argument is not required where:
l

the mode is 2 and the value is 255 (hardware alarm category).

This argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.

204

Chapter 18: Alarm and Alarm Filter Functions

Related Functions

GrpOpen, AlarmDisable, AlarmEnableRec


Example

System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment EnPri ############# Enter AlarmEnable(3,Arg1, "clusterXYZ") Enable alarms of a specific priority in cluster XYZ AlarmEnable ### Enter AlarmEnable(2, Arg1, "clusterXYZ") Enable alarms of a specified category in cluster XYZ ShiftEnable AlarmEnable(1, -1) Enable a page of alarms Enable AlarmEnable(0, 0) Enable the alarm where the cursor is positioned

See Also Alarm Functions

AlarmEnableRec

205

Chapter 18: Alarm and Alarm Filter Functions

Enables alarms by record number on both the Primary and Standby Alarms Servers. This function can be called from Alarm Server or Client and should not be used with a MsgRPC() call to the Alarm Server. This is a blocking function. If the function is called from a foreground task that is unable to block, an error will be returned.
Syntax

INT AlarmEnableRec(LONG Record [, STRING ClusterName]) Record:


The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmFirstTagRec, AlarmNextTagRec, AlarmEnable, AlarmDisableRec


Example

See AlarmDisableRec See Also Alarm Functions

AlarmEventQue

206

Chapter 18: Alarm and Alarm Filter Functions

Opens the alarm event queue. The Alarms Server writes events into this queue as they are processed. These events include activated, reset, acknowledged, enabled and disabled alarms. To read events from this queue, use the QueRead() or QuePeek() functions. The data put into the queue is the alarm record identifier (into the Type field) and the alarm event format (into the Str field). The function puts every state change into the queue and CitectSCADA does not use this queue for anything. To use this function, you need to enable the alarm event queue with the [Alarm]EventQue parameter. This parameter will tell the Alarms Server to start placing events into the queue. The [Alarm]EventFmt parameter defines the format of the data placed into the string field. You can enable the EventQue parameter without setting the event format so that the Alarms Server does not place a formatted string into the queue. Enabling this formatting feature can increase CPU loading and reduce performance of the Alarms Server as every alarm is formatted and placed in the queue. You should reconsider using this feature if a decrease in performance is noticeable. The maximum length of each queue is controlled by the [Code]Queue parameter. You may need to adjust this parameter so as not to miss alarm events. When the queue is full, the Alarms Server will discard events.

UNINTENDED EQUIPMENT OPERATION You may need to adjust the [Code]Queue parameter so as not to miss alarm events. When the queue is full, the Alarms Server will discard events. Failure to follow these instructions can result in death, serious injury, or equipment damage.

Syntax

AlarmEventQue()
Return Value

The handle of the alarm event queue, or -1 if the queue cannot be opened.
Related Functions

QueRead, QuePeek, TagWriteEventQue


Example
hQue = AlarmEventQue() WHILE TRUE DO QueRead(hQue, nRecord, sAlarmFmt, 1);

207

Chapter 18: Alarm and Alarm Filter Functions

/* do what ever with the alarm event */ ... Sleep(0); END

See Also Alarm Functions

AlarmFilterClose
This function removes the named filter from memory.
Syntax

INT AlarmFilterClose(STRING FilterName) FilterName


Name of Filter

Return Value

0 (zero) if successful, otherwise an error code is returned.


Example
// This example shows how to open and close the named filter "Myfilter" // nothing of interest is done with the filter in this example. INT nOpenModeOld = 0; INT nOpenModeNew = 1; INT nOpenModeAny = 2; INT nCloseModeManual = 0; INT nCloseModePageChanged = 1; INT nError; nError = AlarmFilterOpen("MyFilter", nOpenModeNew, nCloseModeManual); IF nError = 0 THEN nError = AlarmFilterClose("MyFilter"); END

Related Functions

AlarmFilterOpen See Also Alarm Filter Functions

AlarmFilterEditAppend

208

Chapter 18: Alarm and Alarm Filter Functions

The AlarmFilterEditAppend function takes a session handle and a filter expression as parameters. It appends the provided expression to the current filter session content without any validation. This does not apply to all filters on the list (see AlarmFilterEditCommit).
Syntax

INT AlarmFilterEditAppend(INT hSession, STRING FilterCriteria) Session:


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

FilterCriteria:
Filter expression as a string. For example:"(Tag=A) OR (TAG=B)" Refer to the topic Implementing alarm filters using Cicode for more information regarding filter syntax.

Return Value

0 (zero) if the alarm filter session exists, otherwise an error code is returned.
Example
// This example shows how to update an edit session. // This example requires that the edit session hEdit exists. // This example shows how you would split the parts of the filter // to avoid an overflow error when handling strings. INT nError; nError = AlarmFilterEditSet(hEdit,"Tag"); nError = AlarmFilterEditAppend(hEdit,"="); nError = AlarmFilterEditAppend(hEdit,"Dig*"); nError = AlarmFilterEditCommit(hEdit); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*;

Related Functions

AlarmFilterEditSet See Also Alarm Filter Functions

AlarmFilterEditClose
The AlmFilterEditClose function removes the session from the memory. The filter is not reset and is valid until a new filter is created and applied.
Syntax

209

Chapter 18: Alarm and Alarm Filter Functions

INT AlarmFilterEditClose(INT hSession) Session


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

Return Value

0 (zero) if the alarm filter session exists, otherwise an error code is returned.
Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20; sRet = AlarmFilterEditPrev(iHndl); // Area=1; iRet = AlarmFilterEditClose(iHndl);

Related Functions

AlarmFilterEditOpen See Also Alarm Filter Functions

AlarmFilterEditCommit
The AlarmFilterEditCommit function takes a session handle as parameter. It validate the filter created in this session and, if valid, applies this filter to the list associated with the session.
Syntax

INT AlarmFilterEditCommit(INT hSession) Session:


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

Return Value

0 (zero) if the alarm filter session exists, otherwise an error code is returned.
Example
// This example requires that the edit session hEdit exists. INT nError; nError = AlarmFilterEditSet(hEdit,"tag=Dig*;Category=1;");

210

Chapter 18: Alarm and Alarm Filter Functions

nError = AlarmFilterEditCommit(hEdit);

Related Functions

AlarmFilterEditSet, AlarmFilterEditAppend See Also Alarm Filter Functions

AlarmFilterEditFirst
This function takes a session handle parameter. It gets the first part of the filter. Each part is either A filter expression delimited with ; A partial filter expression truncated at 254 character (if no ; found before)
Syntax

STRING AlarmFilterEditFirst(INT hSession) Session


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

Return Value

First part of filter or if does not exist an empty string "".


Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20; sRet = AlarmFilterEditPrev(iHndl); // Area=1; iRet = AlarmFilterEditClose(iHndl);

Related Functions

AlarmFilterEditNext, AlarmFilterEditPrev See Also Alarm Filter Functions

AlarmFilterEditLast

211

Chapter 18: Alarm and Alarm Filter Functions

This function takes a session handle parameter. It gets the last part of the filter. Each part is either A filter expression delimited with ; A partial filter expression truncated at 254 character (if no ; found before)
Syntax

STRING AlarmFilterEditLast(hSession) Session


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

Return Value

First part of filter or if does not exist an empty string "".


Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20; sRet = AlarmFilterEditPrev(iHndl); // Area=1; iRet = AlarmFilterEditClose(iHndl);

Related Functions

AlarmFilterEditPrev See Also Alarm Filter Functions

AlarmFilterEditNext
This function takes a session handle parameter. It gets the next part of the filter. Each part is either A filter expression delimited with ; A partial filter expression truncated at 254 character (if no ; found before)
Syntax

INT AlarmFilterEditNext(INT hSession) Session:


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

212

Chapter 18: Alarm and Alarm Filter Functions

Return Value

Next part of filter or if does not exist an empty string "".


Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20; sRet = AlarmFilterEditPrev(iHndl); // Area=1; iRet = AlarmFilterEditClose(iHndl);

Related Functions

AlarmFilterEditFirst, AlarmFilterEditPrev See Also Alarm Filter Functions

AlarmFilterEditOpen
The AlmFilterEditOpen function creates a session for the historical list (or lists) associated with the provided animation number (AN) or FilterName or all alarm lists displayed on the page via (-1) option. This session is initialised with the current filter applied on the lists. It returns a session handle which will be used as parameter in all other functions to reference the session or BAD_HANDLE if the parameter is not a valid animation number or if this animation number is not linked to an historical list.
Syntax

INT AlarmFilterEditOpen(STRING FilterName or INT AN or INT -1)


FilterName Name of Filter AN Animation Number, for example 21 or 11 -1 Change the display parameters of all alarm lists displayed on the page

Return Value

213

Chapter 18: Alarm and Alarm Filter Functions

Returns a session handle to the filter browse session. Returns -1 when an error is detected.
Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20; sRet = AlarmFilterEditPrev(iHndl); // Area=1; iRet = AlarmFilterEditClose(iHndl);

Related Functions

AlarmFilterEditClose See Also Alarm Filter Functions

AlarmFilterEditPrev
This function takes a session handle parameter. It gets the previous part of the filter. Each part is either A filter expression delimited with ; A partial filter expression truncated at 254 character (if no ; found before)
Syntax

STRING AlarmFilterEditPrev(INT hSession ) Session:


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

Return Value

Previous part of filter or if does not exist an empty string "".


Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20;

214

Chapter 18: Alarm and Alarm Filter Functions

sRet = AlarmFilterEditPrev(iHndl); iRet = AlarmFilterEditClose(iHndl);

// Area=1;

Related Functions

AlarmFilterEditFirst, AlarmFilterEditNext, AlarmFilterEditLast See Also Alarm Filter Functions

AlarmFilterEditSet
The AlarmFilterEditSet function takes a session handle and a filter expression as parameters. It replaces the current filter session content by the provided expression without any validation. This does not apply to all filters on the list (see AlarmFilterEditCommit).
Syntax

INT AlarmFilterEditSet(INT hSession, STRING FilterCriteria ) Session:


Session handle for the historical list previously returned by the function AlarmFilterEditOpen().

FilterCriteria:
Filter expression as a string. For example:"(Tag=A) OR (TAG=B)" Refer to the topic Implementing alarm filters using Cicode for more information regarding filter syntax.

Return Value

0 (zero) if the alarm filter session exists, otherwise an error code is returned.
Example
iHndl = AlarmFilterEditOpen(iAN); iRet = AlarmFilterEditSet(iHndl,"Tag=Dig*;Category=1;Area=1;"); iRet = AlarmFilterEditAppend(iHndl, "Priority<20"); sRet = AlarmFilterEditFirst(iHndl); // Tag=Dig*; sRet = AlarmFilterEditNext(iHndl); // Category=1; sRet = AlarmFilterEditLast(iHndl); // Priority<20; sRet = AlarmFilterEditPrev(iHndl); // Area=1; iRet = AlarmFilterEditClose(iHndl);

Related Functions

AlarmFilterEditOpen, AlarmFilterEditClose, AlarmFilterEditAppend, See Also Alarm Filter Functions

215

Chapter 18: Alarm and Alarm Filter Functions

AlarmFilterOpen
This function creates a named filter. The filter is initialised with empty content (matches all alarms).If unable to open the named filter an error code is returned.
Syntax

INT AlarmFilterOpen(STRING FilterName, INT OpenMode [, INT AutoCloseMode]) FilterName


Name of Filter

OpenMode
The values for OpenMode are:
l l l

0 - Open an existing named filter. 1- Create a new named filter. 2- Attempts to open an existing named filter. If the named filter does not exist, a new named filter is created.

AutoCloseMode Values for AutoCloseMode are bit flags. The values for the bits are: l 0 bit - Will not automatically close filter. Use AlarmFilterClose. l 1 bit - When set, the named filter will be closed when the page is changed or otherwise closed. Note: All other modes are reserved
Return Value

0 (zero) if the filter was opened or created or an error if unsuccessful.


Example
// This example shows how to open and close the named filter "Myfilter" // nothing of interest is done with the filter in this example. INT nOpenModeOld = 0; INT nOpenModeNew = 1; INT nOpenModeAny = 2; INT nCloseModeManual = 0; INT nCloseModePageChanged = 1; INT nError; nError = AlarmFilterOpen("MyFilter", nOpenModeNew, nCloseModeManual); IF nError = 0 THEN nError = AlarmFilterClose("MyFilter"); END

Related Functions

216

Chapter 18: Alarm and Alarm Filter Functions

AlarmFilterClose, AlarmSetInfo See Also Alarm Filter Functions "Understanding Named Filters" in the CitectSCADA User Guide

AlarmFirstCatRec
Searches for the first occurrence of an alarm category and type. You can search all areas, the current area only, or specify an area to limit the search. This function returns an alarm record identifier that you can use in other alarm functions, for example, to acknowledge, disable, or enable the alarm, or to get field data on that alarm. Note: Record numbers obtained from AlarmGetDsp are not valid for this function. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code.
Syntax

LONG AlarmFirstCatRec(INT Category, INT Type [, INT Area] [, STRING ClusterName] ) Category:
The alarm category or group number to match. Set Category to 0 (zero) to match all alarm categories.

Type:
The type of alarms to find: Non-hardware alarms

0 - All active alarms, that is Types 1 and 2. 1 - All unacknowledged alarms, ON and OFF. 2 - All acknowledged ON alarms. 3 - All disabled alarms. 4 - All configured alarms, that is, types 0 to 3, plus acknowledged OFF alarms. If you do not specify a type, the default is 0. If [Alarm]DisplayDisable = 1, then disabled alarms, type 3, will not be included in type 4. Area:
The area in which to search for alarms. If you do not specify an area, or if you set Area to -1, only the current area will be searched.

ClusterName:
217

Chapter 18: Alarm and Alarm Filter Functions

Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.


Related Functions

GrpOpen, AlarmNextCatRec, AlarmFirstPriRec, AlarmNextPriRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec
Example

See AlarmAckRec See Also Alarm Functions

AlarmFirstPriRec
Searches for the first occurrence of an alarm priority and type. You can search all areas, the current area only, or specify an area to limit the search. This function returns an alarm record identifier that you can use in other alarm functions, for example, to acknowledge, disable, or enable the alarm, or to get field data on that alarm. Note: Record numbers obtained from AlarmGetDsp are not valid for this function. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code. Note: This function will return a match for an Acknowledge Off alarm with [Alarm] AckHold=1 even after it has been cleared using AlarmClear or AlarmClearRec.
Syntax

LONG AlarmFirstPriRec(INT Priority, INT Type [, INT Area] [, STRING ClusterName] ) Priority:
The alarm Priority or group handle of a group of alarm priorities. Set Priority to 0 (zero) to match all alarm priorities.

Type:

218

Chapter 18: Alarm and Alarm Filter Functions

The type of alarms to find: Non-hardware alarms

0 - All active alarms, that is Types 1 and 2. 1 - All unacknowledged alarms, ON and OFF. 2 - All acknowledged ON alarms. 3 - All disabled alarms. 4 - All configured alarms, that is types 0 to 3, plus acknowledged OFF alarms. If you do not specify a type, the default is 0. Area:
The area in which to search for alarms. If you do not specify an area, or if you set Area to -1, only the current area will be searched.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found. If you do not specify an area, only alarms in the current area on the alarms server are searched.
Related Functions

GrpOpen, AlarmNextCatRec, AlarmFirstPriRec, AlarmNextPriRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec
Example
/* Acknowledge all unacknowledged (Type 1) alarms of the specified alarm priority. */ FUNCTION AutoAccept(INT iPriority) INT iCurrent; INT iNext; iCurrent=AlarmFirstPriRec(iPriority,1,-1); WHILE iCurrent <>-1 DO iNext=AlarmNextPriRec(iCurrent,iPriority,1,-1); AlarmAckRec(iCurrent); iCurrent=iNext; END END

See Also Alarm Functions

219

Chapter 18: Alarm and Alarm Filter Functions

AlarmFirstTagRec
Searches for the first occurrence of an alarm tag, name, and description. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code. Note: Record numbers obtained from AlarmGetDsp are not valid for this function. This function returns an alarm record identifier that you can use in other alarm functions, for example, to acknowledge, disable, or enable the alarm, or to get field data on that alarm. Note: This function will return a match for an Acknowledge Off alarm with [Alarm] AckHold=1 even after it has been cleared using AlarmClear or AlarmClearRec. For complex filtering operations it is more efficient to use the alarm tag browse functions AlmBrowseOpen and AlmBrowseNext.
Syntax

LONG AlarmFirstTagRec(STRING Tag, STRING Name, STRING Description [, STRING ClusterName] ) Tag:
The alarm tag to be matched. Specify an empty string (" ") to match all alarm tags.

Name:
The alarm name to be matched. Specify an empty string (" ") to match all alarm names.

Description:
The alarm description to be matched. Specify an empty string (" ") to match all alarm descriptions.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.


Related Functions

220

Chapter 18: Alarm and Alarm Filter Functions

AlarmNextTagRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec, AlmBrowseOpen , AlmBrowseNext


Example

See AlarmDisableRec See Also Alarm Functions

AlarmGetDelay
Gets the delay setting for the alarm the cursor is currently positioned over.
Syntax

LONG AlarmGetDelay(Type) nType:


The type of delay:

0 - Delay (digital alarm/advancedalarm) 1 - High high delay (analog alarm) 2 - High delay (analog alarm) 3 - Low delay (analog alarm) 4 - Low low delay (analog alarm) 5 - Deviation delay (analog alarm)
Return Value

The alarm delay if successful, otherwise -1 is returned. Use IsError() to retrieve extended error information.
Related Functions

AlarmNotifyVarChange, AlarmSetDelayRec, AlarmGetDelayRec See Also Alarm Functions

AlarmGetDelayRec
Gets the delay setting for an alarm via the alarm record number. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set.
Syntax

221

Chapter 18: Alarm and Alarm Filter Functions

LONG AlarmGetDelayRec(LONG Record, INT Type [, STRING ClusterName] ) Record:


The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

Type:
The type of delay:

0 - Delay (digital alarm/advancedalarm) 1 - High high delay (analog alarm) 2 - High delay (analog alarm) 3 - Low delay (analog alarm) 4 - Low low delay (analog alarm) 5 - Deviation delay (analog alarm) ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm delay if successful, otherwise -1 is returned. Use IsError() to retrieve extended error information.
Related Functions

AlarmNotifyVarChange, AlarmSetDelayRec, AlarmGetDelay See Also Alarm Functions

AlarmGetDsp

222

Chapter 18: Alarm and Alarm Filter Functions

Gets field data from the alarm record that is displayed at the specified AN. You can use this function for both Alarm Pages and Alarm Summaries (an Alarm Page or Alarm Summary needs to be displayed before this function can be used). You can call this function on an Alarms Server or a client to get the contents of any field in the alarm record at that AN. You can return the record number of the alarm record for use in other alarm functions, for example, to acknowledge, disable, or enable an alarm (on an Alarms Server). The AlarmGetDsp() function does not support hardware alarms.
Syntax

STRING AlarmGetDsp(INT AN, STRING Field) AN:


AN number of an ALMCB Alarm record. Equal to AN where actual ALMCB resides + Offset into the list of ALMCB records.

Field:
The name of the field from which the data is retrieved. The contents of the following fields can be retrieved when the Alarm Page is displayed: Field Area Description The area to which the alarm belongs. The user needs to have access to this area to access this alarm data. The text entered into the Comment field of the alarm properties dialog. Alarm category The name of the cluster the alarm tag applies. Operator comments attached to the Alarm Log entry (if any) Custom Filter Fields The date that the alarm changed state (mm/dd/yyyy) The date that the alarm changed state in extended format Deadband (Only Valid on Analog Alarms) Deviation Alarm trigger value (Only Valid on Analog Alarms) Alarm description Font of alarm. Format of alarm. High Alarm trigger value (Only Valid on Analog Alarms)

AlmComment Category Cluster Comment Custom1..8 Date DateExt Deadband Deviation Desc Font Format High

223

Chapter 18: Alarm and Alarm Filter Functions

Field HighHigh Help LogState Low LowLow Name Paging PagingGroup Priority Rate RecNo State State_desc

Description High High Alarm trigger value (Only Valid on Analog Alarms) Alarm help page The last state that the alarm passed through Low Alarm trigger value (Only Valid on Analog Alarms) Low Low Alarm trigger value (Only Valid on Analog Alarms) Alarm name Alarm paged flag Paging group for alarm The alarm priority Rate of change trigger value (Only Valid on Analog Alarms) The alarm record number The current state of the alarm The configured description (for example, healthy or stopped) of a particular state Alarm tag The time that the alarm changed state (hh:mm:ss) The type of alarm or condition The current value of the alarm variable

Tag Time Type Value

The contents of the any of the above fields (except for State) and the following fields can be retrieved when the Alarm Summary is displayed:
Field UserName Description The name of the user (User Name) who was logged on and performed some action on the alarm (for example, acknowledging the alarm or disabling the alarm, etc.). Be aware that when the alarm is first activated, the user name is set to "system" (because the operator did not trip the alarm). The full name of the user (Full Name) who was logged on and performed some action on the alarm (for example, acknowledging the alarm or disabling the alarm, etc.). Be aware that when the alarm is first activated, the full name is set to "system" (because the operator did not trip the alarm). The date when alarm was activated The date (in extended format) when the alarm was activated (dd/mm/yyyy)

FullName

OnDate OnDateExt

224

Chapter 18: Alarm and Alarm Filter Functions

Field OffDate OffDateExt

Description The date when the alarm returned to its normal state The date (in extended format) when the alarm returned to its normal state (dd/mm/yyyy) The time when the alarm was activated The time when the alarm returned to its normal state The time difference between OnDate/OnTime and OffDate/OffTime, in seconds Adds milliseconds to the time the alarm was activated. Adds milliseconds to the time the alarm returned to its normal state. The time when the alarm was acknowledged The date when the alarm was acknowledged The date (in extended format) when the alarm was acknowledged (dd/mm/yyyy) Describes the state of the alarm when it occurred A description of the alarm summary A description of the alarm summary, in the native language Native language comments the operator adds to an Alarm Summary entry during runtime. String that uniquely identifies SOE records within the cluster. On the Alarm Summary table, this field references the associated SOE record.

OnTime OffTime DeltaTime

OnMilli OffMilli AckTime AckDate AckDateExt

SumState SumDesc Native_SumDesc Native_Comment

RecordId

Return Value

The alarm field data (as a string) or empty string "".


Related Functions

AlarmDsp
Example
! Display the tag and category for the alarm at the specified AN. FUNCTION AlarmData(INT AN) STRING Category; STRING Tag; Category=AlarmGetDsp(AN,"Category"); Tag=AlarmGetDsp(AN,"Tag"); Prompt("Alarm "+Tag+" is Category "+Category); END

225

Chapter 18: Alarm and Alarm Filter Functions

See Also Alarm Functions

AlarmGetFieldRec
Gets the contents of the specified field in the specified alarm record. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code.
Syntax

STRING AlarmGetFieldRec(LONG Record, STRING Field [, INT Ver [, STRING ClusterName]]) Record:
The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description.

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

Field:
The name of the field from which the data is retrieved. Field Category Desc Help Name Tag Time Comment Date Description Alarm category Alarm description Alarm help page Alarm name Alarm tag The time that the alarm changed state (hh:mm:ss) Operator comments attached to the Alarm Log entry (if any) The date that the alarm changed state (dd/mm/yyyy)

226

Chapter 18: Alarm and Alarm Filter Functions

Field DateExt Type State Value High HighHigh Low LowLow Rate Deviation Deadband LogState AlmComment

Description The date that the alarm changed state in extended format The type of alarm or condition The current state of the alarm The current value of the alarm variable High Alarm trigger value (Only Valid on Analog Alarms) High High Alarm trigger value (Only Valid on Analog Alarms) Low Alarm trigger value (Only Valid on Analog Alarms) Low Low Alarm trigger value (Only Valid on Analog Alarms) Rate of change trigger value (Only Valid on Analog Alarms) Deviation Alarm trigger value (Only Valid on Analog Alarms) Deadband (Only Valid on Analog Alarms) The last state that the alarm passed through The text entered into the Comment field of the alarm properties dialog. Custom Filter Fields The configured description (for example, healthy or stopped) of a particular state The name of the user (User Name) who was logged on and performed some action on the alarm (for example, acknowledging the alarm or disabling the alarm, etc.). Be aware that when the alarm is first activated, the user name is set to "system" (because the operator did not trip the alarm). The full name of the user (Full Name) who was logged on and performed some action on the alarm (for example, acknowledging the alarm or disabling the alarm, etc.). Be aware that when the alarm is first activated, the full name is set to "system" (because the operator did not trip the alarm). The date when alarm was activated The date (in extended format) when the alarm was activated (dd/mm/yyyy) The date when the alarm returned to its normal state The date (in extended format) when the alarm returned to its normal state (dd/mm/yyyy) The time when the alarm was activated The time when the alarm returned to its normal state

Custom1..8 State_desc

UserName

FullName

OnDate OnDateExt

OffDate OffDateExt

OnTime OffTime

227

Chapter 18: Alarm and Alarm Filter Functions

Field DeltaTime

Description The time difference between OnDate/OnTime and OffDate/OffTime, in seconds Adds milliseconds to the time the alarm was activated. Adds milliseconds to the time the alarm returned to its normal state. The time when the alarm was acknowledged The date when the alarm was acknowledged The date (in extended format) when the alarm was acknowledged (dd/mm/yyyy) Describes the state of the alarm when it occurred A description of the alarm summary A description of the alarm summary, in the native language Native language comments the operator adds to an Alarm Summary entry during runtime. The area to which the alarm belongs Governs the order in which alarms are displayed, acknowledged, enabled, etc.

OnMilli OffMilli AckTime AckDate AckDateExt

SumState SumDesc Native_SumDesc Native_Comment

Area Priority

nVer:
The version of an alarm. If an alarm has been triggered more than once in a given period, the version lets you distinguish between different instances of the alarm's activity. The version is used in filtering alarms for display. A query function passes a value to this parameter in order to get field information for a particular alarm. This parameter is not needed when you use AlarmGetFieldRec() for purposes other than filtering. It will default to 0 if omitted.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm field data (as a string) or empty string "".


Related Functions

AlarmFirstTagRec, AlarmNextTagRec,
Example 228

Chapter 18: Alarm and Alarm Filter Functions

FUNCTION GetNameFromTag(STRING sTag) INT record; STRING sName record = AlarmFirstTagRec(sTag, "", ""); IF record <> -1 THEN sName = AlarmGetFieldRec(record,"NAME"); ELSE sName = ""; END RETURN sName; END

See Also Alarm Functions

AlarmGetFilterName
Retrieves the name of the linked named filter for the supplied An. If empty text, there is currently no linked named filter.
Syntax

STRING AlarmGetFilterName(INT An) An


Animation number

Return Value

Name of linked filter or "".


Example
// This example shows how to link, unlink and check the linking of a // named filter to an alarm list (by its animation number) // This example requires that the named filter "Myfilter" exists. STRING sName; INT nError; INT nAnimationNumber=21; INT nSetInfoFilterName=12; nError = AlarmSetInfo(nAnimationNumber, nSetInfoFilterName, "MyFilter"); IF nError = 0 THEN sName = AlarmGetFilterName(nAnimationNumber); //"MyFilter" END nError = AlarmSetInfo(nAnimationNumber, nSetInfoFilterName, ""); IF nError = 0 THEN sName = AlarmGetFilterName(nAnimationNumber); //"" END

229

Chapter 18: Alarm and Alarm Filter Functions

Related Functions

AlarmFilterOpen See Also Alarm Filter Functions

AlarmGetInfo
Gets data on the alarm list displayed at a specified AN. Use this function to display the current alarm list information on an alarm page. If only one alarm list has been configured on an alarm page, modes 2 and 3 of this function return the current alarm page information. Note: You cannot retrieve the order by key setting for an alarm list using this function, as it can only returns numeric values. To retrieve this information, use the function AlarmGetOrderbyKey
Syntax

LONG AlarmGetInfo(INT AN, INT Type) AN:


The AN where the alarm list (with the required information) is displayed. Set the AN to 0 (zero) to get information on the alarm list where the cursor is positioned.

Type:
The type of data:

0 - Alarm page number. The vertical offset (in pages) from the AN where the alarm list commenced. The alarm list need to have scrolled off the first page for this type to return a non-zero value. 1 - Alarm list offset. The vertical offset (in lines) from the AN where the alarm list commenced. You need to have scrolled off the first page of alarms for this type to return a non zero value. 2 - Category of alarms displayed on the alarm list. You can use a group number to display a group of categories. 3 - Type of alarms displayed on the alarm list. See AlarmDsp() for a list of these types. 7 - Priority of alarms displayed on the alarm list. The return value may be a group number if the alarm list contains alarms of more than one priority. 8 - Display mode of the alarm list. 9 - Sorting mode of the alarm list.

230

Chapter 18: Alarm and Alarm Filter Functions

10 Reading this field is invalid, use the function AlarmGetOrderbyKey. 11 Retrieves the error code for the last alarm summary request that was not able to be processed due to a buffer overflow. The last request error value will be reset on the next successful response from the servers. 12 Returns values as follows; l 0 = no named filter, and no custom filter l 1 = named filter set, no custom filter (this means that the content of the named filter is empty) l 2 = no named filter, but there is custom filtering applied (this is possible if the filter is edited using (via the AN) AlarmFilterEdit functions for example, or any other method) l 3 = named filter set, custom filtering is applied (it is possible that this is due to the named filter being edited or any other method through the AN)
Return Value

Alarm list data as a numeric value.


Related Functions

AlarmDsp, AlarmSetInfo, AlarmGetOrderbyKey.


Example
/* In the following examples, data is returned on the alarm list where the cursor is positioned. */ page = AlarmGetInfo(0,0); ! returns the alarm page number. offset = AlarmGetInfo(0,1); ! returns the alarm list offset. cat = AlarmGetInfo(0,2); ! returns the alarm category displayed. type = AlarmGetInfo(0,3); ! returns the type of alarms displayed.

See Also Alarm Functions

AlarmGetOrderbyKey
Retrieves the list of key(s) that are used to determine the order of the alarm list. These keys can be set by the AlarmSetInfo() function.
Syntax

AlarmGetOrderbyKey(nAN) nAN:

231

Chapter 18: Alarm and Alarm Filter Functions

The AN where the alarm list (with the required information) is displayed.

Return Value

Order-by key (as a string).


Example
page = AlarmGetOrderbyKey(21); ! returns the order-by key string of the alarm list at AN '21'.

See Also Alarm Functions

AlarmGetThreshold
Gets the threshold of the analog alarm where the cursor is positioned.
Syntax

AlarmGetThreshold(Type) nType:
The type of threshold:

0 - High high 1 - High 2 - Low 3 - Low low 4 - Deadband 5 - Deviation 6 - Rate of change
Return Value

The alarm threshold.


Related Functions

AlarmGetThresholdRec, AlarmSetThreshold, AlarmSetThresholdRec See Also Alarm Functions

AlarmGetThresholdRec
Gets the threshold of analog alarms by the alarm record number.

232

Chapter 18: Alarm and Alarm Filter Functions

This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code.
Syntax

INT AlarmGetThresholdRec(LONG Record, INT Type [, STRING ClusterName]) Record:


The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description.

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

Type:
The type of threshold:

0 - High high 1 - High 2 - Low 3 - Low low 4 - Deadband 5 - Deviation 6 - Rate of change ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm threshold or 0.0.


Related Functions

AlarmGetThreshold, AlarmSetThreshold, AlarmSetThresholdRec See Also Alarm Functions

AlarmHelp
233

Chapter 18: Alarm and Alarm Filter Functions

Displays the alarm help page (associated with the alarm) where the cursor is positioned. You can assign a help page to each alarm when you define it (using the Digital Alarms or the Analog Alarms database, depending on the type of alarm). You need to also define the help page in the Pages database.
Syntax

AlarmHelp()
Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

PageAlarm
Example

System Keyboard Key Sequence Command Comment AlmHelp AlarmHelp() Display the alarm help page

See Also Alarm Functions

AlarmNextCatRec
Searches for the next occurrence of an alarm category and type, commencing with the specified alarm record identifier (returned from the previous search through the AlarmFirstCatRec function). You can search all areas, the current area only, or specify an area to limit the search. This function returns an alarm record identifier that you can use in other alarm functions, for example, to acknowledge, disable, or enable the alarm, or to get field data on that alarm. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code.
Syntax

234

Chapter 18: Alarm and Alarm Filter Functions

LONG AlarmNextCatRec(LONG Record, INT Category, INTType [, INT Area] [, STRING ClusterName] ) Record:
The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description.

Category:
The alarm category or group number to match. Set Category to 0 (zero) to match all alarm categories.

Type:
The type of alarms to find: Non-hardware alarms

0 - Active alarms, that is Types 1 and 2. 1 - Unacknowledged alarms, ON and OFF. 2 - Acknowledged ON alarms. 3 - Disabled alarms. 4 - Every configured alarms, that is Types 0 to 3, plus acknowledged OFF alarms. If you choose to omit the Type, the default is 0. Area:
The area in which to search for alarms. If you choose to omit the area, or if you set Area to -1, only the current area will be searched.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.


Related Functions

235

Chapter 18: Alarm and Alarm Filter Functions

GrpOpen, AlarmFirstCatRec, AlarmFirstPriRec, AlarmNextPriRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec
Example

See AlarmAckRec See Also Alarm Functions

AlarmNextPriRec
Searches for the next occurrence of an alarm of a specified priority and type, commencing with the specified alarm record identifier (returned from the previous search through the AlarmFirstPriRec() function). You can search all areas, the current area only, or specify an area to limit the search. This function returns an alarm record identifier that you can use in other alarm functions, for example, to acknowledge, disable, or enable the alarm, or to get field data on that alarm. Note: Record numbers obtained from AlarmGetDsp are not valid for this function. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code.
Syntax

INT AlarmNextPriRec(LONG Record, INT Priority, INT Type [, INT Area] [, STRING ClusterName] ) Record:
The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

236

Chapter 18: Alarm and Alarm Filter Functions

Priority:
The alarm Priority or group handle of a group of alarm priorities. Set Priority to 0 (zero) to match all alarm priorities.

Type:
The type of alarms to find: Non-hardware alarms

0 - All active alarms, that is Types 1 and 2. 1 - All unacknowledged alarms, ON and OFF. 2 - All acknowledged ON alarms. 3 - All disabled alarms. 4 - All configured alarms, that is Types 0 to 3, plus acknowledged OFF alarms. If you do not specify a Type, the default is 0. Area:
The area in which to search for alarms. Set Area to -1 to search all areas. If you do not specify an area, only alarms in the current area on the Alarms Server are searched.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.


Related Functions

GrpOpen, AlarmFirstCatRec, AlarmFirstPriRec, AlarmNextCatRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec, AlarmSetInfo See Also Alarm Functions

AlarmNextTagRec
Searches for the next occurrence of an alarm tag, name, and description, starting with the alarm record identifier (returned from the previous search through the AlarmFirstTagRec() function). This function returns an alarm record identifier that you can use in other alarm functions, for example, to acknowledge, disable, or enable the alarm, or to get field data on that alarm.

237

Chapter 18: Alarm and Alarm Filter Functions

Note: Record numbers obtained from AlarmGetDsp are not valid for this function. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code. For complex filtering operations it is more efficient to use the alarm tag browse functions AlmBrowseOpen and AlmBrowseNext.
Syntax

LONG AlarmNextTagRec(LONG Record, STRING Tag, STRING Name, VDescription [, STRING ClusterName] ) Record:
The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

Tag:
The alarm tag to be matched. Specify an empty string (" ") to match all alarm tags.

Name:
The alarm name to be matched. Specify an empty string (" ") to match all alarm names.

Description:
The alarm description to be matched. Specify an empty string (" ") to match all alarm descriptions.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.

238

Chapter 18: Alarm and Alarm Filter Functions

Related Functions

AlarmFirstTagRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetDelayRec, AlarmGetThresholdRec, AlarmSetThresholdRec, AlmBrowseOpen, AlmBrowseNext
Example

See AlarmDisableRec. See Also Alarm Functions

AlarmNotifyVarChange
This function is used to provide time-stamped digital and time-stamped analog alarms with data. When called, it notifies the alarm server that the specified variable tag has changed. The alarm server will then check all time-stamped digital and time-stamped analog alarms that use the variable tag to see if their alarm states need to be updated as a result of the change. Any alarm state changes that result from this check will be given the timestamp passed into this function as their time of occurrence. Note: Although you can hardcode a value into the setpoint when using analog alarms, you cannot use hardcoded values with time-stamped analog alarms. If the setpoint is hardcoded, this function cannot be used to notify the alarm when the variable changes.
Syntax

AlarmNotifyVarChange(Tag, Value, Timestamp [, TimestampMS] [, sClusterName] [, bSync] ) Tag:


Name of the variable tag that has changed as a string. This name may include the name of the tag's cluster in the form cluster.tagname. This cluster name may be different from the cluster of the alarm server indicated by ClusterName below. The Tag parameter is resolved on the alarm server, so the alarm server should be configured to connect to the tag's cluster.

Value:
Value of the variable tag at the time of the change as a floating-point number

Timestamp:
Time/date at which the variable tag changed in the standard CitectSCADA time/date variable format (Seconds since 1970).

239

Chapter 18: Alarm and Alarm Filter Functions

TimestampMS:
Millisecond portion of the time at which the variable tag changed.

sClusterName:
Name of the cluster of the alarm server. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

bSync:
An optional boolean argument that specifies whether the command is synchronous (blocking) or asynchronous (non-blocking). If it is specified as synchronous (true) the function will wait until the notification has been recorded into the alarm database before further code execution. If it is specified as asynchronous (false) the function will only return an error if no alarm server is currently available.

Return Value

For synchronous mode, the return value will be the error that was detected when the function was called. For asynchronous mode, the return value will be 0, unless there was no server available.
Example
AlarmNotifyVarChange("LOOP_1_SP", 50.0, TimeCurrent() - 10, 550, "ClusterXYZ"); This will tell the alarm server in cluster XYZ that the value of variable tag LOOP_1_SP changed to 50.0 at 9.450 seconds ago.

See Also Time-stamped Digital Alarm Properties, Time-stamped Analog Alarm Properties Alarm Functions

AlarmQueryFirstRec
Searches for the first occurrence of an alarm category (or priority) and type. This is a wrapper function of AlarmFirstCatRec and AlarmFirstPriRec. This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code.
Syntax

AlarmQueryFirstRec(Group, nType, Area, QueryType [, sClusterName] ) Group:


Alarm category if QueryType is 0 or alarm priority if QueryType is 1.

240

Chapter 18: Alarm and Alarm Filter Functions

nType:
Type of alarms to find: Non-hardware alarms

0 - All active alarms; that is, types 1 and 2. 1 - All unacknowledged alarms, ON and OFF. 2 - All acknowledged ON alarms. 3 - All disabled alarms. 4 - All configured alarms; that is, types 0 to 3, plus acknowledged OFF alarms. Area:
Area in which to search for alarms. Set Area to -1 to search all areas.

QuerynType:
Query type.

0 - Search by category. 1 - Search by priority. sClusterName:


Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.


Related Functions

AlarmQueryNextRec See Also Alarm Functions

AlarmQueryNextRec
Searches for the next occurrence of an alarm category (or priority) and type, commencing with the specified alarm record identifier (returned from the previous search through the alarm query functions). This is a blocking function. If the function is called from a foreground task that is unable to block, the return value will be -1 and a hardware alarm set. Use IsError() to retrieve the error code. This is wrapper function of AlarmNextCatRec and AlarmNextPriRec.
Syntax 241

Chapter 18: Alarm and Alarm Filter Functions

AlarmQueryNextRec(Record, Group, nType, Area, QueryType [, sClusterName] ) Record:


Alarm record number.

Group:
Alarm Category if QueryType is 0 or alarm priority if QueryType is 1.

nType:
Type of alarms to find: Non-hardware alarms

0 - All active alarms; that is, types 1 and 2. 1 - All unacknowledged alarms, ON and OFF. 2 - All acknowledged ON alarms. 3 - All disabled alarms. 4 - All configured alarms; that is, types 0 to 3, plus acknowledged OFF alarms. Area:
Area in which to search for alarms. Set Area to -1 to search all areas.

QuerynType:
Query type.

0 - Search by category. 1 - Search by priority. sClusterName:


Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The alarm record identifier or -1 if no match is found.


Related Functions

AlarmQueryFirstRec See Also Alarm Functions

AlarmSetDelay

242

Chapter 18: Alarm and Alarm Filter Functions

Changes the delay setting for an alarm (that is Delay, High High Delay, Deviation Delay, etc.). This function acts on the alarm that the cursor is positioned over. Use this function during runtime to change the delay values that were specified in the alarms database. Delay changes made using this process are persistent (that is they are saved to the project).
Syntax

AlarmSetDelay(Type, Value) nType:


The type of delay:

0 - Delay (digital alarm/advanced alarm) 1 - High high delay (analog alarm) 2 - High delay (analog alarm) 3 - Low delay (analog alarm) 4 - Low low delay (analog alarm) 5 - Deviation delay (analog alarm) Value:
The new value for the delay. Enter a blank value " " to remove the delay setting.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmGetDelay, AlarmSetDelayRec, AlarmGetDelayRec See Also Alarm Functions

AlarmSetDelayRec
Changes the delay setting for an alarm (that is Delay, High High Delay, Deviation Delay, etc.) by the alarm record number. You can only call this function on an alarms server for local alarms, or on a redundant server if one has been configured. This is a blocking function. If the function is called from a foreground task that is unable to block, an error will be returned.
Syntax

INT AlarmSetDelayRec(LONG Record, INT Type, INT Value, STRING ClusterName) Record:

243

Chapter 18: Alarm and Alarm Filter Functions

The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

nType:
The type of delay:

0 - Delay (digital alarm/advanced alarm) 1 - High high delay (analog alarm) 2 - High delay (analog alarm) 3 - Low delay (analog alarm) 4 - Low low delay (analog alarm) 5 - Deviation delay (analog alarm) Value:
The new value for the delay. Enter a blank value " " to remove the delay setting.

sClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Related Functions

AlarmGetDelay, AlarmNotifyVarChange, AlarmGetDelayRec See Also Alarm Functions

AlarmSetInfo
Controls different aspects of the alarm list displayed at a specified AN. Currently applies only to non-hardware alarm lists.
Syntax

INT AlarmSetInfo(INT AN, INT Type, STRING Value) AN:

244

Chapter 18: Alarm and Alarm Filter Functions

The AN where the alarm list originally commenced. (AN alarm page can contain more than one alarm list). You can also specify:

-1 - Change the display parameters of all alarm lists displayed on the page. 0 - Change the display parameters of the alarm list where the cursor is positioned. Type:
The type of data. The aspects and related types are listed below: Display aspect Change display line and page offset Formatting of alarms in the alarm list Filtering of alarms Sorting of alarms - to control the sorting aspect of the alarm list, type 9 and 10 should be used together. Linking or unlinking to a named filter Types 0, 1 4, 5, 6 2, 3, 7, 8 9, 10

12

0 - Alarm page number. The vertical offset (in pages) from the AN where the alarm list commenced. 1 - Alarm list offset. The vertical offset (in lines) from the AN where the alarm list commenced. 2 - Category of alarms displayed on the alarm list. To specify all categories use a value of 0. You can use a group handle to display a group of categories. (A group can be defined using Groups - from the Project Editor System menu - or by using the GrpOpen() function.) Before you can display a group of categories, you need to first open the group using the GrpOpen() function. You would usually do this by entering the GrpOpen() function as the Page entry command for your alarm page (set using Page Properties). Be aware, however, that you should not close the group until you close the display page. If you do, the group will be lost and the group handle will become invalid. The page would then be unable to continue displaying the desired group. The handle may be reused for another group, which means the page may display a different category, or display all alarms. You would normally close the group by entering the GrpClose() function as the Page exit command.

245

Chapter 18: Alarm and Alarm Filter Functions

3 - Type of alarms displayed on the alarm list. See AlarmDsp() for a list of these types. 4 - Display all alarms according to the format and fonts specified for one category (specified in Value). 5 - The display format for all alarms specified by a format handle. All of the alarm categories will display in the same format. 6 - The display font for all user alarms specified by a font handle. All of the user alarms will appear in the same font and color. 7 - The priority of the alarms to be displayed in the alarm list. You can use a group number to display a group of priorities. You can use a group handle to display a group of priorities. (A group can be defined using Groups - from the Project Editor System menu - or by using the GrpOpen() function.) Before you can display a group of priorities, you need to first open the group using the GrpOpen() function. You would usually do this by entering the GrpOpen() function as the Page entry command for your alarm page (set using Page Properties). Be aware, however, that you should not close the group until you close the display page. If you do, the group will be lost and the group handle will become invalid. The page would then be unable to continue displaying the desired group. You would normally close the group by entering the GrpClose() function as the Page exit command. 8 - Use the Value argument of the AlarmSetInfo() function to specify whether the display mode of the alarm list is based on Alarm Category or Priority: l Set the Value argument to 0 (zero) to display by Category. l Set the Value argument to 1 to display by Priority. 9 - Use the Value argument of the AlarmSetInfo() function to specify the sorting mode of the alarm list: l Set the Value argument to 0 (zero) to display alarms sorted by ON time within their groups. l Set the Value argument to 1 to display alarms sorted by the order-by keys. Please be aware that this option will only be meaningful if you have already called the AlarmSetInfo() function with a Type of 10 to set the order-by keys. 10 - Use the Alarm Order-by key specified in the Value argument of the AlarmSetInfo() function to determine the order in which the alarm list will be displayed. The AlarmSetInfo() function should then be called again using a Type of 9 and a Value of 1 for CitectSCADA to sort the alarms in the order specified. 11 Invalid to set this field.

246

Chapter 18: Alarm and Alarm Filter Functions

12 Associate or disassociate a named filter. By setting this field to text, you associate the specified AN to a named filter which is then applied to an alarm display list. Setting this type to empty text, will unlink from any named filter, but the disassociated alarm list will retain its value, hence the filter will still be in place until a new filter is applied. If setting the Value to text that does not correspond to a named filter, the value read back (using AlarmGetFilterName()) will be empty. Value:
The meaning of the Value argument depends on the data type specified in the Type argument.
l

If you set Type = 8, the Value argument determines whether alarms are displayed by category or priority: l 0 - Alarm list displayed by Category. l 1 - Alarm list displayed by Priority. If you set Type = 10, the Value argument specifies the order-by keys to be used in sorting. Up to sixteen keys may be specified: {KeyName [,SortDirection]}[ {KeyName [,SortDirection]}]

The Keyname argument specifies the name of the pre-defined order-by key to be used. The valid options are a subset of the alarm display fields: Tag, Name, Category, Priority, Area, Priv, Time, State. The SortDirection argument is optional, and indicates whether the sort will be ascending or descending. Valid options are: 0 Descending (default), 1 Ascending. For example: {Time,0} : sorts by <Time> (descending) {Tag,1} : sorts by <Tag> (ascending) {Tag,1}{Time} : sorts by <Tag> (ascending), then <Time> (descending)

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

GrpOpen, AlarmDsp, AlarmGetInfo


Examples

In the following example, the alarm list is set to display in the order of the order-by key. Please be aware that this is a two-step process requiring two calls to the AlarmSetInfo() function, and that it applies only to non-hardware alarm lists.
! Set the order-by key. AlarmSetInfo(21,10,"{Time}"); ! Set the sorting mode.

247

Chapter 18: Alarm and Alarm Filter Functions

AlarmSetInfo(21,9,1);

Type 8 of the function is used to set the display mode to either category or priority. This is helpful when filtering based on either of these fields. So In order to filter on category 2 we should use:
AlarmSetInfo(21, 8, 0); AlarmSetInfo(21, 2, 2);

Once we do this the alarms with category 2 will be displayed in the alarm list and remaining although active will not be displayed. Similarly if we want to filter on priority we set the mode to priority and then use type 7. For example to filter on priority 4 we should use:
AlarmSetInfo(21, 8, 1); ! priority mode AlarmSetInfo(21, 7, 4); ! apply filter

In the following examples, the display parameters of the alarm list where the cursor is positioned are changed.
! Change the vertical offset (pages) to 2. AlarmSetInfo(0,0,2); ! Change the vertical offset (lines) to 15. AlarmSetInfo(0,1,15);

Change the alarm category to 10.


AlarmSetInfo(0,2,10);

Change the type of alarms displayed to type 5 (hardware alarms).


AlarmSetInfo(0,3,5);

In the following examples, the display parameters of the alarm list at AN 20 are changed.
! Display alarms with category 120 format and fonts AlarmSetInfo(20, 4, 120); ! Display alarms with a new format hFmt=FmtOpen("MyFormat","{Name}{Desc,20}",0); AlarmSetInfo(20, 5, hFmt); ! Display alarms with a new font hFont = DspFont("Times",-60,black,gray); AlarmSetInfo(20, 6, hFont);

248

Chapter 18: Alarm and Alarm Filter Functions

The following example displays alarms with categories 1-10, 20, or 25. Before AlarmSetInfo() is run, the page entry command for the alarm display page is configured as follows: On page entry command: hGrp=GrpOpen("MyGrp",1); StrToGrp(hGrp,"1..10,20,25"); The page exit command for the alarm display page is configured as follows: On page exit command: GrpClose(hGrp); AlarmSetInfo(20, 2, hGrp); Note:hGrp is defined in the variables database.
Related Functions

AlarmFilterOpen See Also Alarm Functions "Understanding Named Filters" in the CitectSCADA User Guide

AlarmSetThreshold
Changes the thresholds (that is High High, Low etc.) of analog alarms. This function acts on the analog alarm where the cursor is positioned. Use this function to change (at run time) the threshold values that were specified in the Analog Alarms database. Threshold changes made using this function are permanent (that is they are saved to the project). The display format currently specified for the record (in the Analog Alarms form) will be applied to these values.
Syntax

AlarmSetThreshold(Type, Value) nType:


The type of threshold:

0 - High high 1 - High 2 - Low 3 - Low low 4 - Deadband 5 - Deviation 6 - Rate of change Value:
The new value of the threshold. Enter a blank value "" to remove the threshold.

249

Chapter 18: Alarm and Alarm Filter Functions

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmSetThresholdRec
Example

System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment SetlowLow ### Enter AlarmSetThreshold(3, Arg1) Change the threshold of a low low alarm SetLow ### Enter AlarmSetThreshold(2, Arg1) Change the threshold of a low alarm SetHigh ### Enter AlarmSetThreshold(1, Arg1) Change the threshold of a high alarm SetHighHigh ### Enter AlarmSetThreshold(0, Arg1) Change the threshold of a high high alarm

See Also Alarm Functions

AlarmSetThresholdRec
250

Chapter 18: Alarm and Alarm Filter Functions

Changes the threshold (that is High High, Low etc.) of analog alarms by the alarm record number. You can call this function only on an Alarms Server for alarms on that server, or on the redundant server (if a redundant server is configured). Threshold changes made using this function are permanent (that is they are saved to the project). The display format currently specified for the record (in the Analog Alarms form) will be applied to these values. Note: Record numbers obtained from AlarmGetDsp are not valid for this function. This is a blocking function. If the function is called from a foreground task that is unable to block, an error will be returned. To permanently update alarm threshold limits using AlarmSetThresholdRec(), set the parameter [Alarm]UseConfigLimits to 1.
Syntax

INT AlarmSetThresholdRec (LONG Record, INT Type, STRING Value [, STRING ClusterName]) Record:
The alarm record number, returned from any of the following alarm functions:
l

AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.). AlarmFirstPriRec() or AlarmNextPriRec() - used to search for a record by alarm priority, area, and type (acknowledged, disabled, etc.). AlarmFirstTagRec() or AlarmNextTagRec() - used to search for a record by alarm tag, name, and description. AlarmGetDsp() - used to find the record that is displayed at a specified AN, for either an alarm list or alarm summary entry. Set the sField argument in AlarmGetDsp() to "RecNo".

To store this value, use data type Int in Cicode or Long for variable tags (Long needs 4 bytes).

Type:
The type of threshold:

0 - High high 1 - High 2 - Low 3 - Low low 4 - Deadband 5 - Deviation

251

Chapter 18: Alarm and Alarm Filter Functions

6 - Rate of change Value:


The new value of the threshold. Enter a blank value "" to remove the threshold.

ClusterName:
Specifies the name of the cluster in which the Alarm Server resides. This is optional if you have one cluster or are resolving the alarm server via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

AlarmSetThreshold See Also Alarm Functions

AlmBrowseAck
The AlmBrowseAck function acknowledges the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmBrowseAck(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmBrowseClear, AlmTagsDisable, AlmBrowseEnable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev See Also Alarm Functions

AlmBrowseClose

252

Chapter 18: Alarm and Alarm Filter Functions

The AlmBrowseClose function terminates an active data browse session and cleans up resources associated with the session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmBrowseClose(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev See Also Alarm Functions

AlmBrowseDisable
The AlmBrowseDisable function disables the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmBrowseDisable(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmBrowseAck, AlmBrowseEnable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev See Also Alarm Functions

253

Chapter 18: Alarm and Alarm Filter Functions

AlmBrowseEnable
The AlmBrowseEnable function enables the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmBrowseEnable(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev See Also Alarm Functions

AlmBrowseFirst
The AlmBrowseFirst function places the data browse cursor at the first record. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT AlmBrowseFirst(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmBrowseClose, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev

254

Chapter 18: Alarm and Alarm Filter Functions

See Also Alarm Functions

AlmBrowseGetField
The AlmBrowseGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

STRING AlmBrowseGetField(LONG iSession, STRING FieldName) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

sFieldName:
The name of the field that references the value to be returned. Supported fields are:

ACQERROR, CUSTOM1, CUSTOM2, CUSTOM3, CUSTOM4, CUSTOM5, CUSTOM6, CUSTOM7, CUSTOM8, DATEEXT, ERRDESC, ERRPAGE, EQUIPMENT, FORMAT, GROUP, LEVEL, LOCALTIMEDATE, LOGSTATE, NATIVE_DESC, NATIVE_NAME, OFFTIMEDATE, ONTIMEDATE, PRIV, QUALITY, RECEIPTLOCALTIMEDATE, RECEIPTIME, RECEIPTDATE, SUMTYPE, TAGEX, TIMEDATE, TYPE, TYPENUM.
See Browse Function Field Reference for information about fields.

Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmTagsClose, AlmBrowseFirst, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev


Example
STRING fieldValue = ""; STRING fieldName = "TYPE"; INT errorCode = 0; ... fieldValue = AlmBrowseGetField(iSession, sFieldName); IF fieldValue <> "" THEN // Successful case

255

Chapter 18: Alarm and Alarm Filter Functions

ELSE // Function returned an error END ...

See Also Alarm Functions

AlmBrowseNext
The AlmBrowseNext function moves the data browse cursor forward one record. If you call this function after you have reached the end of the records, error 412 is returned (Databrowse session EOF). This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT AlmBrowseNext(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the browse has successfully been moved to the next record, otherwise an error code is returned.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNumRecords, AlmBrowseOpen, AlmBrowsePrev See Also Alarm Functions

AlmBrowseNumRecords
The AlmBrowseNumRecords function returns the number of records that match the filter criteria. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

LONG AlmBrowseNumRecords(LONG iSession) iSession:

256

Chapter 18: Alarm and Alarm Filter Functions

The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

The number of records that have matched the filter criteria. A value of 0 denotes that no records have matched. A value of -1 denotes that the browse session is unable to provide a fixed number. This may be the case if the data being browsed changed during the browse session.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseOpen, AlmBrowsePrev


Example
INT numRecords = 0; ... numRecords = AlmBrowseNumRecords(iSession); IF numRecords <> 0 THEN // Have records ELSE // No records END ...

See Also Alarm Functions

AlmBrowseOpen
The AlmBrowseOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. Use this function to browse all configured alarms. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Note: After calling AlmBrowseOpen() it is necessary to call AlmBrowseFirst() in order to place the cursor at the beginning of the browse session, otherwise a hardware alarm is invoked.

Syntax

LONG AlmBrowseOpen( STRING Filter, STRING Fields [, STRING Clusters] ) Filter:

257

Chapter 18: Alarm and Alarm Filter Functions

A filter expression specifying the records to return during the browse. An empty string indicates that all records will be returned. Where a fieldname is not specified in the filter, it is assumed to be tagname. For example, the filter "AAA" is equivalent to "Tag=AAA". Multiple filters separated by semicolons are supported.

Note: When using Date/Time fields specify in the number of seconds since 1970. E.g LOCALTIMEDATE>=1348723732.
See Implementing alarm filters using Cicode for information about filter syntax

Fields:
Specifies via a comma delimited string the columns to be returned during the browse. An empty string indicates that the server will return all available columns. Supported fields are:

ACKDATE, ACKDATEEXT, ACKTIME, ACQERROR, ALARMTYPE, ALMCOMMENT, AREA, CATEGORY, CLUSTER, COMMENT, CUSTOM1, CUSTOM2, CUSTOM3, CUSTOM4, CUSTOM5, CUSTOM6, CUSTOM7, CUSTOM8, DATE, DATEEXT, DEADBAND, DELTATIME, DESC, DEVIATION, ERRDESC, ERRPAGE, EQUIPMENT, FORMAT, GROUP, HELP, HIGH, HIGHHIGH, LEVEL, LOCALTIMEDATE, LOGSTATE, LOW, LOWLOW, MILLISEC, NAME, NATIVE_COMMENT, NATIVE_DESC, NATIVE_NAME, NATIVE_SUMDESC, OFFDATE, OFFDATEEXT, OFFMILLI, OFFTIME, OFFTIMEDATE, OLD_DESC, ONDATE, ONDATEEXT, ONMILLI, ONTIME, ONTIMEDATE, PAGING, PAGINGGROUP, PRIORITY, PRIV, QUALITY, RATE, RECEIPTLOCALTIMEDATE, RECEIPTIME, RECEIPTDATE, STATE, STATE_DESC, STATE_DESC0, STATE_DESC1, STATE_DESC2, STATE_DESC3, STATE_DESC4, STATE_DESC5, STATE_ DESC6, STATE_DESC7, SUMDESC, SUMSTATE, SUMTYPE, TAG, TAGEX, TIME, TIMEDATE, TYPE, TYPENUM, USERNAME, VALUE.
See Browse Function Field Reference for information about fields.

Clusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that the connected clusters will be browsed.

Return Value

Returns an integer handle to the browse session. Returns -1 when an error is detected. The returned entries will be ordered alphabetically by name.
Related Functions

258

Chapter 18: Alarm and Alarm Filter Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowsePrev


Example
INT iSession; ... iSession = AlmBrowseOpen("NAME=ABC*", "NAME,TYPE", "ClusterA,ClusterB"); IF iSession <> -1 THEN // Successful case ELSE // Function returned an error END ...

See Also Alarm Functions

AlmBrowsePrev
The AlmBrowsePrev function moves the data browse cursor back one record. If you call this function after you have reached the beginning of the records, error 412 is returned (Databrowse session EOF). This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmBrowsePrev(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmBrowseOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmBrowseAck, AlmBrowseDisable, AlmBrowseEnable, AlmBrowseClose, AlmBrowseFirst, AlmBrowseGetField, AlmBrowseNext, AlmBrowseNumRecords, AlmBrowseOpen See Also Alarm Functions

AlmSummaryAck

259

Chapter 18: Alarm and Alarm Filter Functions

The AlmSummaryAck function acknowledges the alarm in the active alarm list which is linked to the current entry of the alarm summary browse session. If the current alarm summary browse session entry is a user event the function will have no effect. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmSummaryAck(INT Session) Session:


The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryClear
The AlmSummaryClear function clears the alarm at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT AlmSummaryClear(INT Session) Session:


The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

260

Chapter 18: Alarm and Alarm Filter Functions

AlmSummaryAck, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryClose
The AlmSummaryClose function terminates an active data browse session and cleans up all resources associated with the session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmSummaryClose(iSession) iSession:
The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryDelete
The AlmSummaryDelete function deletes the record in the filtered list that the cursor is currently referencing. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmSummaryDelete(iSession) iSession:
The handle to a filtered list previously returned by a AlmSummaryOpen call.

261

Chapter 18: Alarm and Alarm Filter Functions

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords
Example
INT errorCode = 0; ... errorCode = AlmSummaryDelete(iSession); IF errorCode = 0 THEN // Successful case ELSE // Function returned an error END ...

See Also Alarm Functions

AlmSummaryDeleteAll
The AlmSummaryDeleteAll function deletes every record from the filtered list source. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmSummaryDeleteAll(iSession) iSession:
The handle to a filtered list previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm filtered list session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords

262

Chapter 18: Alarm and Alarm Filter Functions

Example
INT errorCode = 0; ... errorCode = AlmSummaryDeleteAll(iSession); IF errorCode = 0 THEN // Successful case ELSE // Function returned an error END ...

See Also Alarm Functions

AlmSummaryDisable
The AlmSummaryDisable function disables the alarm at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmSummaryDisable(iSession) iSession:
The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryEnable
The AlmSummaryEnable function enables the alarm at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax 263

Chapter 18: Alarm and Alarm Filter Functions

INT AlmSummaryEnable(INT Session) Session:


The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryFirst
The AlmSummaryFirst function places the data browse cursor at the first record. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmSummaryFirst(iSession) iSession:
The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryGetField

264

Chapter 18: Alarm and Alarm Filter Functions

The AlmSummaryGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmSummaryGetField(iSession, sFieldName) iSession:


The handle to a browse session previously returned by a AlmSummaryOpen call.

sFieldName:
The name of the field that references the value to be returned. Supported fields are:

ACQERROR, CUSTOM1, CUSTOM2, CUSTOM3, CUSTOM4, CUSTOM5, CUSTOM6, CUSTOM7, CUSTOM8, DATEEXT, ERRDESC, ERRPAGE, EQUIPMENT, FORMAT, FULLNAME, GROUP, LOCALTIMEDATE, LOGSTATE, NATIVE_DESC, NATIVE_NAME, OFFTIMEDATE, ONTIMEDATE, PRIV, QUALITY, SUMTYPE, TAGEX, TIMEDATE, TYPE, TYPENUM. See Browse Function Field Reference for information about fields.
Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords
Example
STRING fieldValue = ""; STRING fieldName = "TYPE"; INT errorCode = 0; ... fieldValue = AlmSummaryGetField(iSession, sFieldName); IF fieldValue <> "" THEN // Successful case ELSE // Function returned an error END ...

265

Chapter 18: Alarm and Alarm Filter Functions

See Also Alarm Functions

AlmSummaryLast
The AlmSummaryLast function places the data browse cursor at the most recent summary record from the last cluster of the available browsing cluster list. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmSummaryLast(iSession) iSession:
The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryNext, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryNext
The AlmSummaryNext function moves the data browse cursor forward one record. If you call this function after you have reached the end of a summary, error 412 is returned (Databrowse session EOF). This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmSummaryNext(iSession) iSession:
The handle to a browse session previously returned by a AlmSummaryOpen call.

266

Chapter 18: Alarm and Alarm Filter Functions

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryOpen, AlmSummaryPrev, AlmSummaryNumRecords See Also Alarm Functions

AlmSummaryNumRecords
The AlmSummaryNumRecords function retrieves the number of records in an alarm summary browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

LONG AlmSummaryNumRecords(LONG iSession) iSession:


The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

The number of records that have matched the filter criteria. A value of 0 denotes that no records have matched. A value of -1 denotes that the browse session is unable to provide a fixed number. This may be the case if the data being browsed changed during the browse session.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryPrev
Example
INT numRecords = 0; ... numRecords = AlmSummaryNumRecords(iSession); IF numRecords <> 0 THEN // Have records ELSE

267

Chapter 18: Alarm and Alarm Filter Functions

// No records END ...

See Also Alarm Functions

AlmSummaryOpen
The AlmSummaryOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. This function is a blocking function. It blocks the calling Cicode task until the operation is complete. The AlarmSummaryOpen function allows direct, successful subsequent execution of AlmSummaryNext and AlmSummaryPrev functions. The AlmSummaryNext function executed directly after AlmSummaryOpen will place the data browse cursor at the earliest summary record. The AlmSummaryPrev function executed directly after AlmSummaryOpen will place the cursor at the most recent summary record.
Syntax

INT AlmSummaryOpen(STRING Filter, STRING Fields [, STRING Clusters] ) Filter:


A filter expression specifying the records to return during the browse. An empty string indicates that all records will be returned. Where a fieldname is not specified in the filter, it is assumed to be tagname. For example, the filter "AAA" is equivalent to "TAG=AAA".

Fields:
Specifies via a comma delimited string the columns to be returned during the browse. An empty string indicates that the server will return all available columns. Supported fields are:

ACKDATE, ACKDATEEXT, ACKTIME, ACQERROR, ALARMTYPE, ALMCOMMENT, AREA, CATEGORY, CLUSTER, COMMENT, CUSTOM1, CUSTOM2, CUSTOM3, CUSTOM4, CUSTOM5, CUSTOM6, CUSTOM7, CUSTOM8, DATE, DATEEXT, DEADBAND, DELTATIME, DESC, DEVIATION, ERRDESC, ERRPAGE, EQUIPMENT, FORMAT, FULLNAME, GROUP, HELP, HIGH, HIGHHIGH, LOCALTIMEDATE, LOGSTATE, LOW, LOWLOW, MILLISEC, NAME, NATIVE_COMMENT, NATIVE_ DESC, NATIVE_NAME, NATIVE_SUMDESC, NODE, OFFDATE, OFFDATEEXT, OFFMILLI, OFFTIME, OFFTIMEDATE, OLD_DESC, ONDATE, ONDATEEXT, ONMILLI, ONTIME, ONTIMEDATE, PAGING,

268

Chapter 18: Alarm and Alarm Filter Functions

PAGINGGROUP, PRIORITY, PRIV, QUALITY, RATE, STATE, STATE_ DESC, STATE_DESC0, STATE_DESC1, STATE_DESC2, STATE_DESC3, STATE_DESC4, STATE_DESC5, STATE_DESC6, STATE_DESC7, SUMDESC, SUMSTATE, SUMTYPE, TAG, TAGEX, TIME, TIMEDATE, TYPE, TYPENUM, USERNAME, VALUE. See Browse Function Field Reference for information about fields. Clusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that the connected clusters will be browsed.

Return Value

Returns an integer handle to the browse session. Returns -1 on error.


Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryPrev, AlmSummaryNumRecords
Example
INT iSession; ... iSession = AlmSummaryOpen("NAME=ABC*", "NAME,TYPE", "ClusterA,ClusterB"); IF iSession <> -1 THEN // Successful case ELSE // Function returned an error END ...

See Also Alarm Functions

AlmSummaryPrev
The AlmSummaryPrev function moves the data browse cursor back one record. If you call this function after you have reached the beginning of a summary, error 412 is returned (Databrowse session EOF). This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

269

Chapter 18: Alarm and Alarm Filter Functions

INT AlmSummaryPrev(INT Session) iSession:


The handle to a browse session previously returned by a AlmSummaryOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmSummaryAck, AlmSummaryClear, AlmSummaryClose, AlmSummaryDelete, AlmSummaryDeleteAll, AlmSummaryDisable, AlmSummaryEnable, AlmSummaryFirst, AlmSummaryGetField, AlmSummaryLast, AlmSummaryNext, AlmSummaryOpen, AlmSummaryNumRecords See Also Alarm Functions

AlmTagsAck
This command is deprecated in this version of CitectSCADA. Use AlmBrowseAck function instead. The AlmTagsAck function acknowledges the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsAck(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsClear

270

Chapter 18: Alarm and Alarm Filter Functions

This command is deprecated in this version of CitectSCADA. Use the AlmBrowseClear function instead. The AlmTagsClear function clears the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsClear(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmTagsAck, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsClose
This command is deprecated in this version of CitectSCADA. Use AlmBrowseClose function instead. The AlmTagsClose function terminates an active data browse session and cleans up all resources associated with the session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsClose(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

271

Chapter 18: Alarm and Alarm Filter Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsDisable
This command is deprecated in this version of CitectSCADA. Use AlmBrowseDisable function instead. The AlmTagsDisable function disables the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsDisable(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsEnable
The AlmTagsEnable function enables the alarm tag at the current cursor position in an active data browse session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsEnable(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

272

Chapter 18: Alarm and Alarm Filter Functions

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsFirst
This command is deprecated in this version of CitectSCADA. Use AlmBrowseFirst function instead. The AlmTagsFirst function places the data browse cursor at the first record. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmTagsFirst(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsGetField
This command is deprecated in this version of CitectSCADA. Use AlmBrowseGetField function instead. The AlmTagsGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsGetField(iSession, sFieldName)

273

Chapter 18: Alarm and Alarm Filter Functions

iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

sFieldName:
The name of the field that references the value to be returned. Supported fields are:

ACQERROR, CUSTOM1, CUSTOM2, CUSTOM3, CUSTOM4, CUSTOM5, CUSTOM6, CUSTOM7, CUSTOM8, DATEEXT, ERRDESC, ERRPAGE, EQUIPMENT, FORMAT, GROUP, LEVEL, LOCALTIMEDATE, LOGSTATE, NATIVE_DESC, NATIVE_NAME, OFFTIMEDATE, ONTIMEDATE, PRIV, QUALITY, RECEIPTLOCALTIMEDATE, RECEIPTIME, RECIEPTDATE, SUMTYPE, TAGEX, TIMEDATE, TYPE, TYPENUM.
See Browse Function Field Reference for information about fields.

Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev
Example
STRING fieldValue = ""; STRING fieldName = "TYPE"; INT errorCode = 0; ... fieldValue = AlmTagsGetField(iSession, sFieldName); IF fieldValue <> "" THEN // Successful case ELSE // Function returned an error END ...

See Also Alarm Functions

AlmTagsNext
This command is deprecated in this version of CitectSCADA. Use AlmBrowseNext function instead.

274

Chapter 18: Alarm and Alarm Filter Functions

The AlmTagsNext function moves the data browse cursor forward one record. If you call this function after you have reached the end of the records, error 412 is returned (Databrowse session EOF). This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

AlmTagsNext(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the browse has successfully been moved to the next record, otherwise an error code is returned.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNumRecords, AlmTagsOpen, AlmTagsPrev See Also Alarm Functions

AlmTagsNumRecords
This command is deprecated in this version of CitectSCADA. Use AlmBrowseNumRecords function instead. The AlmTagsNumRecords function returns the number of records that match the filter criteria. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsNumRecords(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

The number of records that have matched the filter criteria. A value of 0 denotes that no records have matched. A value of -1 denotes that the browse session is unable to provide a fixed number. This may be the case if the data being browsed changed during the browse session.

275

Chapter 18: Alarm and Alarm Filter Functions

Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsOpen, AlmTagsPrev
Example
INT numRecords = 0; ... numRecords = AlmTagsNumRecords(iSession); IF numRecords <> 0 THEN // Have records ELSE // No records END ...

See Also Alarm Functions

AlmTagsOpen
This command is deprecated in this version of CitectSCADA. Use AlmBrowseOpen function instead. The AlmTagsOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Note: After calling AlmTagsOpen() it is necessary to call AlmTagsFirst() in order to place the cursor at the beginning of the browse session, otherwise a hardware alarm is invoked.

Syntax

AlmTagsOpen( sFilter, sFields [, sClusters] ) sFilter:


A filter expression specifying the records to return during the browse. An empty string indicates that all records will be returned. Where a fieldname is not specified in the filter, it is assumed to be tagname. For example, the filter "AAA" is equivalent to "Tag=AAA".

sFields:
Specifies via a comma delimited string the columns to be returned during the browse. An empty string indicates that the server will return all available columns. Supported fields are:

276

Chapter 18: Alarm and Alarm Filter Functions

ACKDATE, ACKDATEEXT, ACKTIME, ACQERROR, ALARMTYPE, ALMCOMMENT, AREA, CATEGORY, CLUSTER, COMMENT, CUSTOM1, CUSTOM2, CUSTOM3, CUSTOM4, CUSTOM5, CUSTOM6, CUSTOM7, CUSTOM8, DATE, DATEEXT, DEADBAND, DELTATIME, DESC, DEVIATION, ERRDESC, ERRPAGE, EQUIPMENT, FORMAT, GROUP, HELP, HIGH, HIGHHIGH, LEVEL, LOCALTIMEDATE, LOGSTATE, LOW, LOWLOW, MILLISEC, NAME, NATIVE_COMMENT, NATIVE_DESC, NATIVE_NAME, NATIVE_SUMDESC, OFFDATE, OFFDATEEXT, OFFMILLI, OFFTIME, OFFTIMEDATE, OLD_DESC, ONDATE, ONDATEEXT, ONMILLI, ONTIME, ONTIMEDATE, PAGING, PAGINGGROUP, PRIORITY, PRIV, QUALITY, RATE, RECEIPTLOCALTIMEDATE, RECEIPTIME, RECIEPTDATE, STATE, STATE_DESC, STATE_DESC0, STATE_DESC1, STATE_DESC2, STATE_DESC3, STATE_DESC4, STATE_DESC5, STATE_ DESC6, STATE_DESC7, SUMDESC, SUMSTATE, SUMTYPE, TAG, TAGEX, TIME, TIMEDATE, TYPE, TYPENUM, USERNAME, VALUE.
See Browse Function Field Reference for information about fields.

sClusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that the connected clusters will be browsed.

Return Value

Returns an integer handle to the browse session. Returns -1 when an error is detected. The returned entries will be ordered alphabetically by name.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsPrev
Example
INT iSession; ... iSession = AlmTagsOpen("NAME=ABC*", "NAME,TYPE", "ClusterA,ClusterB"); IF iSession <> -1 THEN // Successful case ELSE // Function returned an error END ...

See Also Alarm Functions

277

Chapter 18: Alarm and Alarm Filter Functions

AlmTagsPrev
This command is deprecated in this version of CitectSCADA. Use AlmBrowsePrev function instead. The AlmTagsPrev function moves the data browse cursor back one record. If you call this function after you have reached the beginning of the records, error 412 is returned (Databrowse session EOF). This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

AlmTagsPrev(iSession) iSession:
The handle to a browse session previously returned by a AlmTagsOpen call.

Return Value

0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions

AlmTagsAck, AlmTagsClear, AlmTagsDisable, AlmTagsEnable, AlmTagsClose, AlmTagsFirst, AlmTagsGetField, AlmTagsNext, AlmTagsNumRecords, AlmTagsOpen See Also Alarm Functions

HwAlarmQue
Returns the handle of the hardware alarm queue. The Alarms Server writes hardware alarm information into this queue as each hardware alarm occurs. To read events from this queue, use the QueRead() or QuePeek() functions. The data written into the queue is the hardware alarm format, and is stored in the Str field. To use this function, you need to enable the hardware alarm queue by specifying the [Alarm]HwAlarmQueMax parameter. This parameter specifies the maximum length that the queue can grow to. The [Alarm]HwAlarmFmt parameter defines the format of the data placed into the string field. If HwAlarmFmt is not specified then the format defaults to "Time: {Time,12} Date:{Date,11} Desc:{Desc,40}". The following format fields are relevant to hardware alarms:
l l l l

{Tag,n} {TagEx,n} {Cluster,n} {Name,n}

278

Chapter 18: Alarm and Alarm Filter Functions

l l l l l l

{State,n} {Time,n} {Date,n} {Desc,n} {ErrDesc,n} {ErrPage,n}

For a description of the fields see the "Alarm Display Fields" help page. The number of buffers available for user queues is controlled by the [Code]Queue parameter. Each entry in any user queue consumes one buffer. When all buffers have been used the Alarms Server will not be able to add new hardware alarms to the queue, and the error message "Out Of Buffers Usr.Que" will be written to syslog.dat. Note:When similar hardware alarms are triggered, for example Tag not found alarms, the hardware alarm page and hardware alarm queue show the last invalid entry. The previous entry of the same description is overwritten.
Syntax

HwAlarmQue()
Return Value

The handle of the hardware alarm queue, or -1 if the queue cannot be opened.
Related Functions

QueRead(), QuePeek()
Example
hQue = HwAlarmQue() WHILE TRUE DO

QueRead(hQue, nAlarmType, sHwAlarmString, 1);

/* do what ever with the alarm information */

....

Sleep(0);

279

Chapter 18: Alarm and Alarm Filter Functions

END

See Also Alarm Functions

280

Chapter 19: Clipboard Functions


Following are functions relating to the Windows clipboard:
ClipCopy ClipPaste ClipReadLn ClipSetMode ClipWriteLn Copies a string to the Windows clipboard. Pastes a string from the Windows clipboard. Reads a line of text from the Windows clipboard. Sets the format of data sent to the Windows clipboard. Writes a line of text to the Windows clipboard.

See Also Functions Reference

ClipCopy
Copies a string to the Windows clipboard. When the string is in the clipboard, you can paste it to any Windows program.
Syntax

ClipCopy(sText) sText:
The string to copy to the clipboard.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ClipWriteLn
Example
ClipCopy("put this in clipboard");

See Also Clipboard Functions

281

Chapter 19: Clipboard Functions

ClipPaste
Pastes a string from the Windows clipboard.
Syntax

ClipPaste()
Return Value

The contents of the clipboard (as a string). If the clipboard is empty, an empty string is returned.
Related Functions

ClipReadLn
Example
/* Get string from clipboard into sText. */ sText = ClipPaste();

See Also Clipboard Functions

ClipReadLn
Reads a single line of text from the Windows clipboard. With this function, you can read a block of text from the clipboard - line by line. Call the function once to read each line of text from the clipboard. When the end of the clipboard is reached, an empty string is returned.
Syntax

ClipReadLn()
Return Value

One line of text from the clipboard (as a string). If the clipboard is empty, an empty string is returned.
Related Functions

ClipPaste
Example
/* Get first line of text from clipboard. */ sText = ClipReadLn();

282

Chapter 19: Clipboard Functions

WHILE StrLength(sText) > 0 DO ! Do something with text ... ! Read next line of clipboard sText = ClipReadLn(); END

See Also Clipboard Functions

ClipSetMode
Sets the format of data sent to the Windows clipboard.
Syntax

ClipSetMode(nMode) nMode:
The mode of the data:

1 - ASCII Text 2 - CSV (Comma separated values) format


You can select multiple modes by adding modes together.

Return Value

The value of the previous mode.


Related Functions

ClipCopy, ClipWriteLn
Example
/* Set the clipboard to CSV mode, write two values, and reset the clipboard to the original mode. */ nOldMode = ClipSetMode(2); ClipCopy("100,200"); ClipSetMode(nOldMode);

See Also Clipboard Functions

ClipWriteLn

283

Chapter 19: Clipboard Functions

Writes a line of text to the Windows clipboard. With this function, you can write any amount of text to the clipboard. Call this function once for each line of text. To terminate the block of text, call this function and pass an empty string.
Syntax

ClipWriteLn(sText) sText:
The line of text to write to the clipboard, or an empty string ("") to end the write operation.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ClipCopy
Example
ClipWriteLn("first line of text"); ClipWriteLn("second line of text"); ClipWriteLn(""); ! End of write operation

See Also Clipboard Functions

284

Chapter 20: Cluster Functions


Following are functions relating to clusters:
ClusterActivate ClusterDeactivate ClusterFirst ClusterGetName ClusterIsActive ClusterNext ClusterServerTypes ClusterStatus Allows the user to activate an inactive cluster. Allows the user to deactivate an active cluster.

Allows the user to retrieve the first configured cluster in the project. Deprecated in this version Allows the user to determine if a cluster is active. Allows the user to retrieve the next configured cluster in the project. Allows the user to determine which servers are defined for a given cluster. Allows the user to determine the connection status from the client to a server on a cluster. Deprecated in this version Allows the user to deactivate an active cluster at the same time as activating a deactive cluster.

ClusterSetName ClusterSwapActive

See Also Functions Reference

ClusterActivate
This function allows the user to activate an inactive cluster. When a cluster is made active, all data associated with that cluster is available to the client, and hardware alarms will occur if no connections can be made to the servers in the cluster.
Syntax

ClusterActivate(ClusterName) sClusterName:

285

Chapter 20: Cluster Functions

The name of the cluster to activate enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterDeactivate
This function allows the user to deactivate an active cluster. When a cluster is made inactive, no data associated with that cluster is available to the client, and hardware alarms will not occur if no connections can be made to the servers in the cluster.
Syntax

ClusterDeactivate(ClusterName) sClusterName:
The name of the cluster to deactivate enclosed in quotation marks "".

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ClusterActivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterFirst
This function allows the user to retrieve the first configured cluster in the project.
Syntax

ClusterFirst()
Return Value

286

Chapter 20: Cluster Functions

The name of the first configured cluster.


Related Functions

ClusterActivate, ClusterDeactivate, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterGetName
ClusterGetName is deprecated in this version of CitectSCADA.
Syntax

ClusterGetName(sPrimary, sStandby, nMode) sPrimary:


The variable containing the name of the cluster's primary server (that is that which was set as sPrimary using the ClusterSetName() function).

sStandby:
The variable containing the name of the cluster's standby server (that is that which was set as sStandby using the ClusterSetName() function).

nMode:
The mode is for future expansion of the function - set to 0 (zero).

Return Value

The status of the get name.


Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster
Example
// Return and display the server names.// ClusterGetName(sPrimary, sStandby, 0); Prompt("Name of Cluster" + sPrimary);

See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

287

Chapter 20: Cluster Functions

ClusterIsActive
This function allows the user to determine if a cluster is active.
Syntax

ClusterIsActive(ClusterName) sClusterName:
The name of the cluster to query enclosed in quotation marks "".

Return Value

TRUE if active, FALSE otherwise. If the cluster name was invalid, this function will return FALSE and a hardware alarm will be generated.
Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterNext
This function allows the user to retrieve the next configured cluster in the project.
Syntax

ClusterNext(ClusterName) sClusterName:
Any configured cluster name enclosed in quotation marks "", this will usually be the name of the previous cluster as returned from ClusterFirst, or a previous call to ClusterNext.

Return Value

The name of the next configured cluster or an empty string if there is no more clusters.
Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

288

Chapter 20: Cluster Functions

ClusterServerTypes
This function allows the user to determine which servers are defined for a given cluster.
Syntax

ClusterServerTypes(ClusterName) sClusterName:
The name of the cluster to query enclosed in quotation marks "".

Return Value

Logical OR of the following server flags:


l l l l

0001 - 1st bit set means an Alarm Server is configured 0010 - 2nd bit set means a Trend Server is configured 0100 - 3rd bit set means a Report Server is configured 1000 - 4th bit set means an IO Server is configured

For example, a return value of 14 indicates an IO Server, a Report Server, and a Trend Server are configured.
Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterSetName
ClusterSetName is deprecated in this version of CitectSCADA.
Syntax

ClusterSetName(sPrimary, sStandby, nMode) sPrimary:


The name of the cluster's primary server (Reports Server, Alarms Server etc.), as defined using the Computer Setup Wizard. When the ClusterSetName() function is used, CitectSCADA will attempt to connect to this server.

sStandby:

289

Chapter 20: Cluster Functions

The name of the cluster's standby server (Reports Server, Alarms Server etc.), as defined using the Computer Setup Wizard. If the sPrimary server is unavailable when the ClusterSetName() function is used, CitectSCADA will attempt to connect to this server. If there is no standby server, enter an empty string for sStandby.

nMode:
The mode of the connection:

0 - If you select this mode, CitectSCADA will renew the last connection. If it was connected to the sPrimary server, when this function was last used, it will attempt to connect to it again. If it was last connected to the sStandby server, it will attempt to connect to it again. This mode is useful when a server is known to be unavailable, as it facilitates faster cluster switching. 1 - CitectSCADA will attempt to connect to the sPrimary server first, each time this function is used. If the sPrimary server is unavailable, CitectSCADA will try the sStandby server.
Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterStatus, ClusterSwapActive, TaskCluster
Example
// Connect to Cluster A, with server CITECTA1 as primary server, and CITECTA2 as standby.// ClusterSetName("CITECTA1", "CITECTA2", 0); // Display the menu page for Cluster A Project.// PageDisplay("MenuA");

See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterStatus
This function allows the user to determine the connection status from the client to a server on a cluster.
Syntax

ClusterStatus(clusterName, serverType)

290

Chapter 20: Cluster Functions

clusterName:
The name of the cluster to query enclosed in quotation marks "".

servernType:
The type of server (not a bit mask):
l l l l

1 2 4 8

- Alarm Server - Trend Server - Report Server - IO Server

Return Value

One of the following values:


l l l l l

-1 - if the cluster does not contain a server of the given type. -2 - if the cluster does not exist" 0 - if the cluster contains the server but the cluster is inactive. 1 - if the cluster is active but the connection to the server is offline. 2 - if the cluster is active and the connection to the server is online.

Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterSwapActive, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

ClusterSwapActive
This function allows the user to deactivate an active cluster at the same time as activating an inactive cluster. The arguments may be passed in any order, but one cluster needs to be active and the other needs to be inactive.
Syntax

ClusterSwapActive(clusterNameA, clusterNameB) clusterNameA:


The name of the cluster to activate or deactivate enclosed in quotation marks "".

clusterNameB:
The name of the cluster to activate or deactivate enclosed in quotation marks "".

Return Value

291

Chapter 20: Cluster Functions

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide

292

Chapter 21: Color Functions


Following are functions relating to colors:
CitectColourToPackedRGB GetBlueValue GetGreenValue GetRedValue MakeCitectColour PackedRGB Converts a CitectSCADA color into a packed RGB color value that can be used by an ActiveX object. Returns the Blue component of a packed RGB color. Returns the Green component of a packed RGB color. Returns the Red component of a packed RGB color. Creates a color from red, green and blue component parts. Returns a packed RGB color based on specified red, green, and blue values. Converts a packed RGB color into the nearest equivalent CitectSCADA color.

PackedRGBToCitectColour

See Also Functions Reference


CitectColourToPackedRGB

Converts a CitectSCADA color value into a packed RGB color value that can be understood by an ActiveX object.
Syntax

CitectColourToPackedRGB(nCitectColor) nCitectColor:
The CitectSCADA color value to be converted into a packed RGB color. CitectSCADAcolors are defined in the labels database, or calculated by the function MakeCitectColour

Return Value

The packed RGB color value - if successful, otherwise an error code is returned.
Related Functions

PackedRGBToCitectColour

293

Chapter 21: Color Functions

See Also Color Functions

GetBlueValue
Returns the Blue component of a packed RGB color.
Syntax

GetBlueValue(nPackedRGB) nPackedRGB:
The packed RGB color.

Return Value

The red value (0-255) - if successful, otherwise an error is returned.


Related Functions

GetRedValue, GetGreenValue See Also Color Functions

GetGreenValue
Returns the green component of a packed RGB color.
Syntax

GetGreenValue(nPackedRGB) nPackedRGB:
The packed RGB color.

Return Value

The red value (0-255) - if successful, otherwise an error is returned.


Related Functions

GetRedValue, GetBlueValue See Also Color Functions

GetRedValue
Returns the red component of a packed RGB color.
294

Chapter 21: Color Functions

Syntax

GetRedValue(nPackedRGB) nPackedRGB:
The packed RGB color.

Return Value

The red value (0-255) - if successful, otherwise an error is returned.


Related Functions

GetGreenValue, GetBlueValue See Also Color Functions

MakeCitectColour
Creates a color from red, green and blue component parts. Note: To define a transparent color, use the label TRANSPARENT.
Syntax

MakeCitectColour(nRed,nGreen,nBlue) nRed:
The color value for red, from 0-255

nGreen:
The color value for green, from 0-255

nBlue:
The color value for blue, from 0-255

Return Value

An integer that is an encoded representation of the color created.


Examples
! creates the color red MakeCitectColour(255,0,0) ! creates the color white MakeCitectColour(255,255,255)

295

Chapter 21: Color Functions

See Also Color Functions

PackedRGB
Returns a packed RGB color based on specified red, green, and blue values.
Syntax

PackedRGB(nRed, nGreen, nBlue) nRed:


The red component of the desired packed RGB color.

nGreen:
The green component of the desired packed RGB color.

nBlue:
The blue component of the desired packed RGB color.

Return Value

The packed RGB color value - if successful, otherwise an error is returned.


Related Functions

CitectColourToPackedRGB See Also Color Functions

PackedRGBToCitectColour
Converts a packed RGB color into a calculated CitectSCADA color value.
Syntax

PackedRGBToCitectColour(nPackedRGB) nPackedRGB:
The packed RGB color.

Return Value

The CitectSCADA color value if successful; otherwise an error is returned.


Related Functions

CitectColourToPackedRGB

296

Chapter 21: Color Functions

See Also Color Functions

297

Chapter 21: Color Functions

298

Chapter 22: Communication Functions


Following are functions relating to communications:
ComClose ComOpen ComRead ComReset ComWrite SerialKey Closes a communication port. Opens a communication port for access. Reads characters from a communication port. Resets the communication port. Writes characters to a communication port. Redirects serial characters from a port to the keyboard.

See Also Functions Reference

ComClose
Closes a communication port. Any Cicode tasks that are waiting for a read or write operation to complete (or that are retrying to read or write) return with a range error. CitectSCADA automatically closes all communication ports at shutdown. This function can only be called from an I/O Server.
Syntax

ComClose(hPort) hPort:
The communication port handle, returned from the ComOpen() function. This handle identifies the table where all data on the associated communication port is stored.

Return Value

0 if the port is successfully closed, or an error if the port is already closed or if the port number is invalid.
Related Functions

ComOpen, ComRead, ComWrite

299

Chapter 22: Communication Functions

Example

See ComOpen See Also Communication Functions

ComOpen
Opens a communication port for access. The board and port need to both be defined in the database (using the Boards and Ports forms from the Communication menu). If you try to open the same COM port twice with ComOpen(), the second open will not succeed and return -1. If this is passed without checking other Com functions, the COM port may not do anything. For this reason, do not open COM ports twice, and always check the return value from ComOpen(). The communication system should be used for low speed communications only. You should not use the communication functions to communicate with high speed PLCs the performance may not be adequate. If you need high speed communication (for communicating with PLCs, etc.), you should write a protocol driver. Refer to the CitectSCADA "Driver Development Kit". This function can only be called from an I/O Server.
Syntax

ComOpen(sPort, nMode) sPort:


The port name as specified in the Ports database.

nMode:
The mode of the open:

0 - Take control of the port from CitectSCADA. In this non-shared mode, you have complete access to the port - CitectSCADA cannot use the port. Communication will be restored when the port is closed. 1 - Share the port with CitectSCADA. In this mode, you can write to the port, and CitectSCADA can also use it. Please be aware that ComRead will be unreliable if the communication port is opened as shared.
Return Value

A communication port handle if the communication system is opened successfully, otherwise -1 is returned. The handle identifies the table where all data on the associated port is stored. You can use the handle in the other communication functions, to send and receive characters from the port.

300

Chapter 22: Communication Functions

Related Functions

ComClose, ComRead, ComWrite


Example
INT FUNCTION StartSerial(STRING sPort) INT hPort; hPort = ComOpen(sPort, 0); IF hPort < 0 THEN Prompt("Cannot open port " + sPort); RETURN -1; END TaskNew("SerialRead", hPort, 0); TaskNew("SerialWrite", hPort, 0); ComClose(hPort); RETURN 0; END INT FUNCTION SerialWrite(INT hPort) STRING buffer; INT SerialWriteError; INT length; WHILE 1 DO ! put data into buffer and set length . . SerialWriteError = ComWrite(hPort, buffer, length, 2); IF SerialWriteError THEN Prompt("Error Writing port"); ComReset(hPort); END END RETURN 0; END INT FUNCTION SerialRead(INT hPort) STRING buffer; INT length; INT total; INT SerialReadError; total = 0; WHILE 1 DO length = 128; ! need to set length as read modifies SerialReadError = ComRead(hPort, buffer, length, 2); IF SerialReadError THEN Prompt("Error from port " + SerialReadError : ####); ComReset(hPort); ELSE ! get data from buffer, length is set to number read .

301

Chapter 22: Communication Functions

. END END RETURN 0; END

See Also Communication Functions

ComRead
Reads characters from a communication port. The characters are read from the communication port into a string buffer. If no characters have arrived after the specified timeout, the function returns with a timeout error. If the timeout is 0, the function gets any characters that have arrived from the last call, and returns immediately. You use the iLength variable to specify the length of the buffer, or the maximum number of characters to read when ComRead() is called. When ComRead() returns, iLength is set to the actual number of characters read. Because iLength is modified by this function, you need to reset it before each call. You should not treat the string buffer as a normal string - it has no string terminator. Use the StrGetChar() function to extract characters from the buffer. It is strongly recommended not to call ComRead() while another ComRead() is still pending on the same port, because it can produce unexpected results.

UNINTENDED EQUIPMENT OPERATION Do not call ComRead() if another instance of ComRead() is still pending on the same port. Failure to follow these instructions can result in death, serious injury, or equipment damage.

This function is a blocking function. It blocks the calling Cicode task until the operation is complete. This function can only be called from an I/O Server.
Syntax

ComRead(hPort, sBuffer, iLength, iTimeOut) hPort:


The communication port handle, returned from the ComOpen() function. This handle identifies the table where the data on the associated communication port is stored.

sBuffer:

302

Chapter 22: Communication Functions

The buffer into which to put the characters. The actual number of characters read is returned in iLength.

iLength:
The number of characters to read into the buffer. The maximum length you may read in one call is 128 characters. When the function returns, this variable is set to the actual number of characters read.

iTimeOut:
The timeout for the read to complete:
l

If iTimeOut = 0 (zero), the function checks for characters in the buffer and returns. If iTimeOut > 0, the function returns after this number of seconds - if no characters have been received. If iTimeOut < 0, the function waits forever for characters.

Return Value

0 (zero) if the read is successful, otherwise an error code is returned.


Related Functions

ComOpen, ComClose, ComWrite, StrGetChar


Example

See ComOpen See Also Communication Functions

ComReset
Resets the communication port. This function can only be called from an I/O Server.
Syntax

ComReset(hPort) hPort:
The communication port handle, returned from the ComOpen() function. This handle identifies the table where all data on the associated communication port is stored.

Return Value

0 (zero) if the write is successful, otherwise an error code is returned.


Related Functions

303

Chapter 22: Communication Functions

ComOpen, ComClose, ComRead, StrGetChar


Example

See ComOpen See Also Communication Functions

ComWrite
Writes characters to a communication port. The characters are written from the string buffer to the port. If the characters have not been transmitted after the specified timeout, the function returns with a timeout error. If the timeout is 0, the function returns immediately and the characters are transmitted in the background. ComWrite() does not treat the buffer as a true string, but rather as an array of characters of the length specified - you can send any character to the communication port. Use the StrSetChar() function to build the buffer. Do not call ComWrite() while another ComWrite () is still pending on the same port, because it can produce unexpected results. You use the iLength variable to specify the length of the buffer, or the maximum number of characters to write when ComWrite() is called. When ComWrite() returns, iLength is reset to zero. This function is a blocking function. It blocks the calling Cicode task until the operation is complete. This function can only be called from an I/O Server.
Syntax

ComWrite(hPort, sBuffer, iLength, iTimeOut) hPort:


The communication port handle, returned from the ComOpen() function. This handle identifies the table where all data on the associated communication port is stored.

sBuffer:
The buffer from which to write the characters.

iLength:
The number of characters to write from the buffer. The maximum number of characters you can write is 128.

iTimeOut:
The timeout for the write to complete.

304

Chapter 22: Communication Functions

If iTimeOut = 0 (zero), the characters are copied to the communication buffer and the function returns immediately - the characters are transmitted in the background. If iTimeOut > 0, the function returns after this number of seconds - if the characters cannot be transmitted. If iTimeOut < 0, the function waits forever to transmit the characters.

Return Value

0 (zero) if the write is successful, otherwise an error code is returned.


Related Functions

ComOpen, ComClose, ComRead, StrGetChar


Example

See ComOpen See Also Communication Functions

SerialKey
Redirects all serial characters from a port to the keyboard. If using a keyboard attached to a serial port, you should call this function at startup, so that CitectSCADA copies all characters (read from the port) to the keyboard. The Port needs to be defined in the Ports database. If the port is not on an I/O server, you need to create a dummy I/O server record (for example, name the server DServer1). Complete the Boards and Ports records. Set the following parameters in the CITECT.INI file:
[IOServer]Name to the server name (for example, DServer1) [IOServer]Server to 0

This method enables the port without making the computer an I/O server. (If the I/O server is enabled (and not required as an I/O server), extra overhead and memory are used.) This function can only be called from an I/O server.
Syntax

SerialKey(sPort) sPort:
The name of the port connected to the serial keyboard.

Return Value 305

Chapter 22: Communication Functions

0 (zero) if successful, otherwise an error code is returned.


Related Functions

ComOpen
Example
SerialKey("Port1"); ! enable the serial keyboard

See Also Communication Functions

306

Chapter 23: DDE Functions


Following are functions relating to Dynamic Data Exchange:
DDEExec Executes a command in an external DDE compliant Windows application. Makes a CitectSCADA variable available for DDE linking by other DDE compliant Windows applications. Reads a variable from a DDE compliant Windows application. Writes a variable to a DDE compliant Windows application. Executes a command in an external DDE compliant Windows application. Gets the latest Windows DDE error code.

DDEPost

DDERead DDEWrite DDEhExecute

DDEhGetLastError DDEhInitiate

Starts a DDE conversation with an external DDE compliant Windows application. Writes data to a DDE compliant Windows application. Reads a line of text from a DDE Conversion. Requests data from a DDE compliant Windows application. Set the mode of a DDE conversation. Closes a DDE conversation with a Windows application.

DDEhPoke DDEhReadLn DDEhRequest DDEhSetMode DDEhTerminate DDEhWriteLn

Writes a line of text to the DDE conversation.

See Also Functions Reference

DDEExec

307

Chapter 23: DDE Functions

Executes a command in an external Windows application running on the same computer. With this function, you can control other applications that support DDE. Refer to the documentation provided with the external Windows application to determine if DDE is supported and what functions can be called. You cannot use DDEExec() to call macros on a remote computer or to call Access SQLs. For these calls, Network DDE needs to pass the sDocument argument, so you need to use the DDEh... functions, passing sDocument in the DDEhInitiate() function.
Syntax

DDEExec(sApplication, sCommand) sApplication:


Application name (.EXE filename), for example, "WinWord".

sCommand:
The command that the application will execute.

Return Value

1 (one) if successful, otherwise an error code is returned.


Related Functions

DDEPost, DDERead, DDEWrite, DDEhExecute


Example
/* Instruct the Excel application to recalculate its spreadsheet immediately. */ DDEExec("Excel","[Calculate.Now()]");

See Also DDE Functions

DDEhExecute
Executes a command in an external Windows application. You need to first start a conversation with the DDEhInitiate function, and use the handle returned by that function to identify the conversation. With this function, you can control other applications that support DDE. Refer to the documentation provided with your other Windows application to determine if DDE is supported and what functions can be called. This function is a blocking function. It will block the calling Cicode task until the operation is complete.

308

Chapter 23: DDE Functions

Syntax

DDEhExecute(Handle, sCommand) Handle:


The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

sCommand:
The command that the application will execute.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DDEhInitiate, DDEhRequest, DDEhPoke, DDEhTerminate, DDEhGetLastError


Example
See DDEhInitiate

See Also DDE Functions

DDEhGetLastError
Gets the latest error code issued from Windows for the conversation identified by the handle.
Syntax

DDEhGetLastError(Handle) Handle:
The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

Return Value

The error code last issued from Windows DDEML (for that conversation):
DMLERR_ADVACKTIMEOUT DMLERR_BUSY DMLERR_DATAACKTIMEOUT 0x4000 0x4001 0x4002

309

Chapter 23: DDE Functions

DMLERR_DLL_NOT_INITIALIZED DMLERR_DLL_USAGE DMLERR_EXECACKTIMEOUT DMLERR_INVALIDPARAMETER DMLERR_LOW_MEMORY DMLERR_MEMORY_ERROR DMLERR_NOTPROCESSED DMLERR_NO_CONV_ESTABLISHED DMLERR_POKEACKTIMEOUT DMLERR_POSTMSG_FAILED DMLERR_REENTRANCY DMLERR_SERVER_DIED DMLERR_SYS_ERROR DMLERR_UNADVACKTIMEOUT DMLERR_UNFOUND_QUEUE_ID

0x4003 0x4004 0x4005 0x4006 0x4007 0x4008 0x4009 0x400a 0x400b 0x400c 0x400d 0x400e 0x400f 0x4010 0x4011

Related Functions

DDEhInitiate, DDEhExecute, DDEhRequest, DDEhPoke, DDEhTerminate


Example

See DDEhInitiate See Also DDE Functions

DDEhInitiate
Starts a conversation with an external Windows application. When the data exchange is complete, you should terminate the conversation to free system resources.
Syntax

310

Chapter 23: DDE Functions

DDEhInitiate(sApplication, sDocument) sApplication:


The application name (.EXE filename), for example, "WinWord".

sDocument:
The document, topic, or file name.

Return Value

An integer handle for the conversation between CitectSCADA and the other application, or -1 if the conversation is not started successfully. The handle is used by the other DDEh... functions, to identify the conversation.
Related Functions

DDEhExecute, DDEhRequest, DDEhPoke, DDEhTerminate, DDEhGetLastError


Example
! Read from Excel spreadsheet STRING FUNCTION GetExcelData(); INT hChannel; STRING sData; hChannel = DDEhInitiate("EXCEL", "DATA.XLS"); IF hChannel > -1 THEN sData = DDEhRequest(hChannel, "R1C1"); DDEhTerminate(hChannel); hChannel = -1; END; RETURN sData; END ! Write to Excel spreadsheet FUNCTION SetExcelData(STRING sData); INT hChannel; hChannel = DDEhInitiate("EXCEL", "DATA.XLS"); IF hChannel > -1 THEN DDEhPoke(hChannel, "R1C1", sData); DDEhTerminate(hChannel); hChannel = -1; END; END ! Execute Excel Macro FUNCTION DoExcelMacro(); INT hChannel; hChannel = DDEhInitiate("EXCEL", "DATA.XLS"); IF hChannel > -1 THEN DDEhExecute(hChannel, "[RUN(^"TestMacro^")]"); DDEhTerminate(hChannel); hChannel = -1; END; END

311

Chapter 23: DDE Functions

See Also DDE Functions

DDEhPoke
Writes a value to an external Windows application, for example, an Excel spreadsheet. The value is written once to the application. (To write the value dynamically, you need to call this function at the rate at which the data needs to be updated.) You need to first start a conversation with the DDEhInitiate function, and use the handle returned by that function to identify the conversation. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax

DDEhPoke(Handle, sItem, sValue) Handle:


The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

sItem:
A unique name for the item; for example, the variable name, field name, or spreadsheet cell position.

sValue:
The value of the item.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DDEhInitiate, DDEhExecute, DDEhRequest, DDEhTerminate, DDEhGetLastError


Example

See DDEhInitiate See Also DDE Functions

DDEhReadLn

312

Chapter 23: DDE Functions

Reads a line of text from a DDE Conversion, for example, from an Excel spreadsheet. You need to first start a conversation with the DDEhInitiate function, and use the handle returned by that function to identify the conversation. This function allows you to read a large amount of data via DDE. Keep calling the function until an empty string is returned to verify that all the data has been read. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax

DDEhReadLn(Handle, sTopic) Handle:


The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

sTopic:
A unique topic name for the item; for example, the variable name, field name, or spreadsheet cell position.

Return Value

A line of data, or an empty string when all data has been read.
Related Functions

DDEhSetMode, DDEhWriteLn, DDEhInitiate, DDEhExecute, DDEhRequest, DDEhTerminate, DDEhGetLastError


Example

See DDEhWriteLn See Also DDE Functions

DDEhRequest
Reads a value from an external Windows application, for example, from an Excel spreadsheet. You need to first start a conversation with the DDEhInitiate function, and use the handle returned by that function to identify the conversation. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax

DDEhRequest(Handle, sItem) Handle:

313

Chapter 23: DDE Functions

The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

sItem:
A unique name for the item; for example, the variable name, field name, or spreadsheet cell position.

Return Value

A string of data, or an empty string if the function cannot read the value.
Related Functions

DDEhInitiate, DDEhExecute, DDEhPoke, DDEhTerminate, DDEhGetLastError


Example

See DDEhInitiate See Also DDE Functions

DDEhSetMode
Set the mode of the DDE conversation. The default mode of a DDE conversation is to use TEXT data format - a simple string of data. This function allows you to set the mode to CSV (Comma Separated Values). Some Windows applications support this mode of data as it helps them to separate the data. For example, when you send CSV format to Excel, each value will be placed into a unique cell. If you use TEXT mode all the data will be placed into the same cell.
Syntax

DDEhSetMode(Handle, sMode) Handle:


The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

sMode:
The mode of the DDE conversation:

1 - Text (default) 2 - CSV


Return Value

The error code.


Related Functions

314

Chapter 23: DDE Functions

DDEhInitiate, DDEhExecute, DDEhRequest, DDEhTerminate, DDEhGetLastError, DDEhPoke, DDEhReadLn, DDEhWriteLn, DDEhSetMode


Example

See DDEhWriteLn See Also DDE Functions

DDEhTerminate
Closes the conversation identified by the handle, and frees the resources associated with that conversation. After you call this function, the handle is no longer valid. With Network DDE, you might need to terminate and re-initiate a conversation. For example, if you delete rows on an MS Access sheet, the deleted rows display as #DELETED until you terminate and re-initiate the conversation.
Syntax

DDEhTerminate(Handle) Handle:
The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DDEhInitiate, DDEhExecute, DDEhPoke, DDEhRequest, DDEhGetLastError


Example

See DDEhInitiate See Also DDE Functions

DDEhWriteLn
Writes a line of text to the DDE conversation. With this function, you can write any amount of text to the DDE conversation. Call this function once for each line of text. To terminate the block of text, call this function and pass an empty string.
Syntax

DDEhWriteLn(Handle, sTopic, sData)

315

Chapter 23: DDE Functions

Handle:
The integer handle that identifies the DDE conversation, returned from the DDEhInitiate function.

sTopic:
A unique name for the topic the data will be written to; for example, the spreadsheet cell position. The topic is only used when you complete the write by passing an empty string for data.

sData:
The line of data to write. To terminate the data and make CitectSCADA send the data, set the data to an empty string.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DDEhInitiate, DDEhExecute, DDEhRequest, DDEhTerminate, DDEhGetLastError, DDEhPoke, DDEhReadLn, DDEhWriteLn, DDEhSetMode


Example
! Write to Excel spreadsheet ! write the numbers 1..8 into 8 unique cells in Excel. FUNCTION WriteExcelData(STRING sData); INT hChannel; hChannel = DDEhInitiate("EXCEL", "DATA.XLS"); IF hChannel > -1 THEN // set to CSV mode so EXCEL will put each value in a cell DDEhSetMode(hChannel, 2); DDEhWriteLn(hChannel, "", "1,2,3,4"); DDEhWriteLn(hChannel, "R1C1:R2C4", "5,6,7,8"); DDEhWriteLn(hChannel,"R1C1:R2C4",""); DDEhTerminate(hChannel); hChannel = -1; END; END

See Also DDE Functions

DDEPost
Makes a CitectSCADA variable value available for DDE linking (that is posts a DDE link so that it can be read by other DDE compliant applications running on the same computer). This sets-up CitectSCADA to behave as a DDE Server for this DDE channel.

316

Chapter 23: DDE Functions

After a value is posted, other Windows applications running on the same computer can read the value by using their own DDE Client functions. If the value of the posted variable changes, any linked applications are informed of the new value. To link to this value from any DDE Client applications running on the same computer, they need to appropriately use the DDE Client syntax with:
l l l

"Citect" as the <DDE Server application name> "Data" as the <DDE Topic name> The name used for the first parameter sItem in this DDEPost() function as the <DDE data item name>.

Unlike the DDERead() and DDEWrite() Cicode functions which are static, the DDEPost() function can be used to create a dynamic DDE link, providing the DDE Client applications appropriately set their side of the DDE channel to be automatically updated.
Syntax

DDEPost(sItem, sValue) sItem:


A unique name for the item; for example, the variable name, field name, or spreadsheet cell position.

sValue:
The value of the item.

Return Value

The value that is posted, or 0 (zero) if the function does not succeed in posting the link.
Related Functions

DDEExec, DDERead, DDEWrite


Example
! In Citect Project Editor, create a variable tag named PV1 ! In Cicode, post a link to the tag PV1 for external DDE applications to connect with DDEPost("TAGONE",PV1); /* To link to this posted tag from a cell in Excel, set the cell to =Citect|Data!TAGONE. This will set the value of the Excel cell to the value of tag PV1. */ /* To link to this posted tag from a field in Word, set the field to{DDEAuto Citect Data TAGONE}. This will set the value of the field link to the value of tag PV1. */

See Also DDE Functions

317

Chapter 23: DDE Functions

DDERead
Reads values from an external DDE compliant Windows application running on the same computer, (for example, from an Excel spreadsheet cell or a Word document). This is a one-way static communication which is read once from the application per call. To read the value dynamically, call this function at the rate at which the data is required to be updated. Use this function when you want precise control over exactly what you want from the DDE exchange.
Syntax

DDERead(sApplication, sDocument, sItem [, Mode] ) sApplication:


The application name (.EXE filename), for example, "WinWord".

sDocument:
The document, topic, or file name.

sItem:
A unique name for the item; for example, the variable name, field name, or spreadsheet cell position.

Mode:
A flag that tells the application whether or not to set up an advise loop:

0 - Do not set up advise loop. 1 - Set up advise loop (default).


Return Value

The value (from the external application) as a string, or an empty string if the function cannot read the desired values.
Related Functions

DDEExec, DDEPost, DDEWrite


Example
/* Read the value from R1C1 (Row1,Column1) of an Excel spreadsheet named "Sheet1". */ DDERead("Excel","Sheet1","R1C1"); /* Read the value from the Item1 bookmark of the Word document named "Recipes.doc". */ DDERead("Winword","Recipes","Item1");

318

Chapter 23: DDE Functions

See Also DDE Functions

DDEWrite
Writes a value to an external Windows application, for example, to an Excel spreadsheet. The value is written once to the application. To write the value dynamically, you need to call this function at the rate at which the data needs to be updated. Use DDEWrite() to cause CitectSCADA runtime to initiate the DDE conversation with a DDE compliant application running on the same computer.
Syntax

DDEWrite(sApplication, sDocument, sItem, sValue) sApplication:


The application name (.EXE filename), for example, "WinWord".

sDocument:
The document, topic, or file name.

sItem:
A unique name for the item; for example, the variable name, field name, or spreadsheet cell position.

sValue:
The value of the item.

Return Value

The value that is sent to the other application, or an empty string if the function does not successfully write the value.
Related Functions

DDEExec, DDEPost, DDERead


Example
/* Write the value of a CitectSCADA variable named TAGONE to R1C1 (Row1,Column1) of an Excel spreadsheet named "Sheet1". The value is in string format. */ DDEWrite("Excel","Sheet1","R1C1",TAGONE);

319

Chapter 23: DDE Functions

See Also DDE Functions

320

Chapter 24: Device Functions


Following are functions relating to devices:
DevAppend DevClose DevControl DevCurr DevDelete DevDisable DevEOF DevFind DevFirst DevFlush DevGetField DevHistory DevInfo DevModify DevNext DevOpen DevOpenGrp DevPrev Appends a blank record to the end of a device. Closes a device. Controls a dBASE or SQL device. Gets the current device number. Deletes the current record in a database device. Disables (and re-enables) a device from any access. Checks for the end of a file. Finds a record in a device. Finds the first record in a device. Flushes buffered data to a device. Gets field data from the current record. Renames a device file and any subsequent history files. Gets device information. Modifies the attributes of a device. Gets the next record in a device. Opens a device for access. Opens a group of devices. Gets the previous record in a device.

321

Chapter 24: Device Functions

DevPrint DevRead DevReadLn DevRecNo DevSeek DevSetField DevSize DevWrite DevWriteLn DevZap Print PrintLn PrintFont

Prints free-format data to a group of devices. Reads characters from a device. Reads a line of characters from a device. Gets the current record number of a device. Moves to any record in a device. Sets new field data in the current record. Gets the size of a device. Writes a string to a device. Writes a string with a newline character to a device. Zaps a device. Prints a string in a report. Prints a string with a newline character in a report. Changes the printing font on the current device.

See Also Functions Reference

DevAppend
Appends a blank record to the end of a device. After the record is appended, you can use the DevSetField() function to add data to fields in the record. Note: For SQL devices data should be added to all requested fields in the row via the Cicode function DevSetField() before DevAppend() is applied. You need to first call the DevOpen() function to get the device handle (hDev).
Syntax

DevAppend(hDev) hDev:

322

Chapter 24: Device Functions

The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

0 (zero) if the record is successfully appended, otherwise an error code is returned.


Related Functions

DevOpen, DevSetField
Example
INT FUNCTION WriteAlarmCount( INT hDevice, STRING sAlarm, INT iCount, INT iTime ) DevAppend(hDevice); DevSetField(hDevice, "ALARM", sAlarm); DevSetField(hDevice, "TIME", IntToStr(iTime)); DevSetField(hDevice, "COUNT", IntToStr(iCount)); END

For SQL devices the above example will not work. Instead use the following example:

INT FUNCTION WriteAlarmCount( INT hSqlDevice, STRING sAlarm, INT iCount, INT iTime ) DevSetField(hSqlDevice, "ALARM", sAlarm); DevSetField(hSqlDevice, "TIME", IntToStr(iTime)); DevSetField(hSqlDevice, "COUNT", IntToStr(iCount)); DevAppend(hSglDevice); END

See Also Device Functions

DevClose
Closes a device. Any data in the buffer is flushed to the device before it is closed. After a device is closed, its device handle becomes invalid and cannot be used.
Syntax

DevClose(hDev, Mode) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where data on the associated device is stored.

Mode: The mode of the close:

323

Chapter 24: Device Functions

0 - Close the device in user mode - the default mode if none is specified. A device opened by Cicode function DevOpen() need to be closed in this mode. 1 - Close the device in remove logging mode - under this mode, the current device will be rolled over to history files immediately. You should only use this mode in a report. 2 - Close the device in keep logging mode - under this mode, the current device will not be rolled over to history files. This allows subsequent messages to be written to the same file. This mode is used internally in a report written in rich text format (rtf). Note:Do not call DevClose() to the current device in an rtf report. This may make the output file unreadable.
Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DevOpen
Example
DevClose(hDev);

See Also Device Functions

DevControl
Controls a dBASE or SQL device. You can pack a dBASE device to physically remove deleted records, or re-index a dBASE device to regenerate the keys. You can issue queries to an SQL device, or get the error status of the last SQL query.
Syntax

DevControl(hDev, Type [, sData]) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

nType:
The type of command:

0 - Re-index the device based on the key defined in the device record (dBASE devices only).

324

Chapter 24: Device Functions

1 - Pack the database file - all deleted records are removed (dBASE devices only). 2 - Issue a direct SQL query to the device (SQL devices only). 3 - Get error status of the last SQL query (SQL devices only). Note: ASCII files and printers are not supported. sData:
The command data, that is the SQL query to be issued. Used only for Type 2 commands.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DevOpen, DevZap
Example
! pack a dBASE file device DevControl(hDev, 1, "");

See Also Device Functions

DevCurr
Gets the current device handle. You can only call this function in a report, to get the handle of the device where the report is logging. You can then use the other device functions (for example, DevPrint()) to access that logging device. (To get the handle of a device other than a logging device, you need to use the DevOpen() function.) If the report is logging to a group of devices, this function will return the group handle. However, not all device functions support group handles, for example, you cannot read from a group of devices.
Syntax

DevCurr()
Return Value

The current device handle or group handle. If no device is configured, -1 is returned.


Related Functions

DevOpen, DevPrint

325

Chapter 24: Device Functions

Example
! Get the report device number. hDev=DevCurr();

See Also Device Functions

DevDelete
Deletes the current record in a dBASE database device. The record is not physically deleted, but is marked for deletion. You can physically delete the record by packing the database with the DevControl() function.
Syntax

DevDelete(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

0 (zero) if the record is successfully deleted, otherwise an error code is returned.


Related Functions

DevOpen, DevClose, DevControl


Example
! Delete the current record. DevDelete(hDev);

See Also Device Functions

DevDisable
Disables (and re-enables) a device from all access, and discards any data written to the device. When a device is disabled, it cannot be opened, and data cannot be read from the device. Use this function to disable logging to a database or printer. The State argument is a toggle. A State of 1 disables the device(s), but you can then re-enable the device(s) by repeating the function with State = 0.
Syntax

326

Chapter 24: Device Functions

DevDisable(sName, State) sName:


The device name, or * (asterisk) for all devices.

State:
The disable state:

0 - Enable the device. 1 - Disable the device.


Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DevOpen
Example
! Disable the AlarmLog device. DevDisable("AlarmLog",1); : DevDisable("AlarmLog",0);

! Re-enable the device.

See Also Device Functions

DevEOF
Gets the status of the end of file (EOF) flag for a device. When you use the DevPrev(), DevNext(), or DevSeek() function, the start or end of the device will eventually be reached, and the EOF flag will be set. Use this function to test the EOF flag.
Syntax

DevEOF(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

1 if the EOF flag has been set, otherwise 0 (zero).


Related Functions

DevOpen, DevPrev, DevNext, DevSeek, DevReadLn

327

Chapter 24: Device Functions

Example
hDev = DevOpen("Log", 0); WHILE NOT DevEOF(hDev) DO Prompt(DevGetField(hDev,"Tag")); DevNext(hDev); END DevClose(hDev);

See Also Device Functions

DevFind
Searches a device for a record that contains specified data in a specified field. The search starts at the current record and continues forward until the matched data is found or the end of the database is reached. If the file has a keyed index, an indexed search is used.
Syntax

DevFind(hDev, sFind, sField) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

sFind:
The data to find in sField, as a string. For SQL devices: The DevFind() function can distinguish between numbers, strings, and dates, so you do not need to enclose the data in quote marks. Dates and times need to be in the correct format:
l l l

Date: YYYY-MM-DD Time: HH:MM:SS DateTime: YYYY-MM-DD HH:MM:SS[.F...] (The fraction .F... is optional.)

sField:
The field name to match.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DevOpen, DevSeek
Example

328

Chapter 24: Device Functions

! Find the Ice cream recipe. DevNotFount=DevFind(hDev,"Ice cream","Recipe"); IF DevNotFount=0 THEN ! Get the recipe values. .. ELSE Prompt("Ice cream not found"); END

See Also Device Functions

DevFirst
Finds the first record in a device.
Syntax

DevFirst(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

The first indexed record (if the device is an indexed database), otherwise the first record in the device.
Related Functions

DevOpen, DevClose
Example
! Find the first record. FirstRec = DevFirst(hDev);

See Also Device Functions

DevFlush
Flushes buffered data to the physical device. CitectSCADA normally optimizes the writing of data for maximum performance, so use this function only if it is really necessary.
Syntax

DevFlush(hDev)

329

Chapter 24: Device Functions

hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where data on the associated device is stored.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DevOpen, DevClose
Example
! Flush device to disk. DevFlush(hDev);

See Also Device Functions

DevGetField
Gets field data from the current record in a device.
Syntax

DevGetField(hDev, sField ) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

sField:
The field name, as a string of up to 10 characters. (The dBASE file format limits all field names to a maximum of 10 characters.)

Return Value

The field data (as a string). If the field is not found an empty string is returned.
Related Functions

DevOpen, DevSetField
Example
INT FUNCTION

330

Chapter 24: Device Functions

GetRecipe(STRING sName) INT hDev; hDev = DevOpen("Recipe", 0); IF hDev >= 0 THEN DevSeek(hDev, 1); IF DevFind(hDev, sName, "NAME") = 0 THEN PLC_FLOUR = DevGetField(hDev, "FLOUR"); PLC_WATER = DevGetField(hDev, "WATER"); PLC_SALT = DevGetField(hDev, "SALT"); PLC_MILK = DevGetField(hDev, "MILK"); ELSE DspError("Cannot Find Recipe " + sName); END DevClose(hDev); ELSE DspError("Cannot open recipe database"); END END

See Also Device Functions

DevHistory
Renames a device file and any subsequent history files. The current device is closed and renamed as the first history file. For example, the device file 'Templog.txt' is renamed as 'Templog.001'. If a history file 'Templog.001' already exists, it is renamed as 'Templog.002', and so on. The next time data is written to the device, a new device file is created. Note: If the device file has not been created (that is data has not been written to the device), only existing history files are renamed. Use this function for direct control of the device history process. The DevHistory function does not support SQL devices.
Syntax

DevHistory(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

331

Chapter 24: Device Functions

DevOpen, DevControl
Example
! Create history file DevHistory(hDev);

See Also Device Functions

DevInfo
Gets information on a device.
Syntax

DevInfo(hDev, nType) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

nType:
Type of information: -n: Name of field n (where n is any number up to the total number of fields). For example, if there are 10 fields, -7 will return the name of field 7. - (Total no. of fields + n): Length of field n (where n is any number up to the total number of fields). For example, if there are 10 fields, -15 will return the length of field 5. 0: Device Name 1: Format 2: Header 3: File Name 4: Number of history files 5: Form length 6: Number of fields 7: Disable flag 8: Device type 9: Record size 10: Format number

332

Chapter 24: Device Functions

11: Type of history schedule:

0: Event triggered 1: Daily 2: Weekly 3: Monthly 4: Yearly


12: The history period, in seconds, or week day, month or year, for example, if history is weekly then this is the day of the week, that is 1 to 7 13: Synchronisation time of day of the history in seconds, for example, 36000 (that is, 10:00:00) 14: The time the next history file will be created in seconds

Return Value

The device information as a string if successful, otherwise an empty string is returned.


Related Functions

DevControl
Example
! Get the number of fields in a device. NoFields=DevInfo(hDev,6); FOR I=1 TO NoFields DO ! Get and display the name of each field. sField=DevInfo(hDev,-I); nLength=DevInfo(hDev,-I - NoFields); Prompt("Field Name "+sField + "Length " + nLength:##); END

See Also Device Functions

DevModify
Modifies the attributes of a device. The device needs to be closed before you can modify a device. This function allows you to dynamically change the file name or other attributes of a device at run time. You can use a single device to access many files. For example, you can create a device called Temp with a file name of TEMP.DBF. Using this function you could dynamically change the file name to access any dBASE file. This function is useful in conjunction with the FormOpenFile() or FormSaveAsFile() functions. (These functions allow the operator to select file names easily.)

333

Chapter 24: Device Functions

When using this function, you should be careful that no other Cicode function is already using the same device. Check the return value of this function before opening the device or you will destroy the data in the device to which it is already attached. If the device is already open, calling DevModify will return an error (and raise a hardware alarm to notify user). If DevModify returns error, it means it has not modified the device and the device parameters will remain as they were before the call to DevModify. Use a semaphore to help protect your Cicode.
Syntax

DevModify(sName, Format, Header, FileName, nType) Name:


The name of the device.

Format:
A new format for the device or "*" to use the existing format.See Format Templates for more information.

Header:
A new header for the device or "*" to use the existing header.

FileName:
A new file name for the device or "*" (asterisk) to use the existing filename.

nType:
A new device type.

Device Type ASCII_DEV PRINTER_DEV dBASE_DEV SQL_DEV

Device ASCII file Printer dBASE file SQL database

or -1 to use the existing device type.


Return Value

0 (zero) if successful, otherwise an error code is returned.

334

Chapter 24: Device Functions

Related Functions

DevOpen, DevClose, DevSetField, DevInfo, DevAppend, FormOpenFile


Example
! change the file name of MyDev DevModify("MyDev", "*", "*", "c:\data\newfile.dbf", -1); ! change the fields and file name of MyDev DevModify("MyDev", "{time}{date}{tags}", "*", "C:\DATA\OLDFILE.DBF", -1); ! change the device to TXT file DevModify("MyDev", "*", "*", "C:\DATA\OLDFILE.TXT", ASCII_DEV);

See Also Device Functions

DevNext
Gets the next record in a device. If the end of the database is reached, the EOF flag is set and an error code is returned.
Syntax

DevNext(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

0 if the next record is read, or an error if the end of the database is reached.
Related Functions

DevEOF, DevPrev
Example
Status=0; I = 0; hDev = DevOpen("Log", 0); WHILE Status = 0 DO DspText(20 + I, 0, DevGetField(hDev,"Tag")); I = I + 1; Status = DevNext(hDev); END DevClose(hDev);

335

Chapter 24: Device Functions

See Also Device Functions

DevOpen
Opens a device and returns the device handle. The device needs to be defined in the CitectSCADA database. If the device cannot be opened, and user error checking is not enabled, the current Cicode task is halted. You can use this function to return the handle of a device that is already open. The DevOpen() function does not physically open another device - it returns the same device handle as when the device was opened. The mode of the second open call is ignored. To re-open an open device in a different mode, you need to first close the device and then re-open it in the new mode. When using an ODBC driver to connect to an SQL server or database, experience has shown that connecting only once on startup and not closing the device yields the best performance. ODBC connection is slow and if used on demand may affect your system's performance. Also, some ODBC drivers may leak memory on each connection and may cause errors after a number of re-connects. Note: If you are opening a database device in indexed mode (nMode=2), an index file will automatically be created by CitectSCADA if one does not already exist. If you feel a device index has become corrupt, delete the existing index file and a new one will be created the next time the DevOpen function is run.
Syntax

DevOpen(sName [, nMode] ) Name:


The name of the device.

nMode:
The mode of the open:

0 - Open the device in shared mode - the default mode when opening a device if none is specified. 1 - Open the device in exclusive mode. In this mode only one user can have the device open. The open will return an error if another user has the device open in shared or exclusive mode.

336

Chapter 24: Device Functions

2 - Open the device in indexed mode. In this mode the device will be accessed in index order. This mode is only valid if the device is a database device and has an index configured in the Header field at the Devices form. Please be aware that specifying mode 2 when opening an ASCII device is ignored internally. 4 - Open the device in 'SQL not select' mode. If opened in this mode, you need to not attempt to read from an SQL device. 8 - Open the device in logging mode. In this mode the history files will be created automatically. 16 - Open the device in read only mode. In this mode data can be viewed, but not written. This mode is supported only by DBF and ASCII files - it is ignored by printers and SQL/ODBC databases.
Return Value

The device handle. If the device cannot be opened, -1 is returned. The device handle identifies the table where all data on the associated device is stored.
Related Functions

DevClose, DevOpenGrp
Example
INT FUNCTION PrintRecipe(STRING sCategory) STRING sRecipe; INT hRecipe, hPrinter; ErrSet(1); ! enable user error checking hRecipe = DevOpen("Recipe", 0); IF hRecipe = -1 THEN DspError("Cannot open recipe"); RETURN FALSE; END hPrinter = DevOpen("Printer1", 0); IF hPrinter = -1 THEN DspError("Cannot open printer"); RETURN FALSE; END ErrSet(0); ! disable user error checking WHILE NOT DevEof(hRecipe) DO sRecipe = DevReadLn(hRecipe); DevWriteLn(hPrinter, sRecipe); END DevClose(hRecipe); DevClose(hPrinter); RETURN TRUE; END

337

Chapter 24: Device Functions

See Also Device Functions

DevOpenGrp
Opens a group of devices.
Syntax

DevOpenGrp(hGrp [, nMode] ) hGrp:


The handle to a database containing a group of devices.

nMode:
The mode of the open:

0 - Open the device in shared mode - the default mode when opening a device. 1 - Open the device in exclusive mode. In this mode only one user can have the device open. The open will return an error if another user has the device open in shared or exclusive mode. 2 - Open the device in indexed mode. In this mode the device will be accessed in index order. This mode is only valid if the device is a database device and has an index configured in the Header field at the Devices form. Please be aware that specifying mode 2 when opening an ASCII device is ignored internally. 4 - Open the device in 'SQL not select' mode. If opened in this mode, you need to not attempt to read from an SQL device. 8 - Open the device in logging mode. In this mode the history files will be created automatically. 16 - Open the device in read only mode. In this mode data can be viewed, but not written. This mode is supported only by DBF and ASCII files - it is ignored by printers and SQL/ODBC databases.
Return Value

Returns 0 if successful or -1 if the function is provided with a bad handle and cannot open the group.
Related Functions

DevClose, DevOpen

DevPrev

338

Chapter 24: Device Functions

Gets the previous record in a device. If the start of the database is reached, the EOF flag is set and an error code is returned.
Syntax

DevPrev(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

0 if the record is read successfully, or an error code if the start of the database is reached.
Related Functions

DevOpen, DevEOF, DevNext


Example
Status=0; I = 0; hDev = DevOpen("Log", 0); iError = DevSeek(hDev, DevSize(hDev)); ! seek to end WHILE iError = 0 DO DspText(20 + I, 0, DevGetField(hDev,"Tag")); I = I + 1; iError = DevPrev(hDev); END DevClose(hDev);

See Also Device Functions

DevPrint
Prints free-format data to groups of devices. Using this function, you can write data to many devices at the same time. You would normally use this function in a report.
Syntax

DevPrint(hGrp, sData, NewLine) hGrp:


The device handle, or the group handle for a group of devices.

sData:
The data to print to the group of devices.

339

Chapter 24: Device Functions

NewLine:
The newline flag:

0 - Do not insert a newline character. 1 - Insert a newline character.


Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

DevWriteLn, DevCurr
Example
! Get the report device number or group number (for a group of devices). hGrp=DevCurr(); ! Print PV123 to a group of devices. DevPrint(hGrp,"PV123="+PV123:###,1);

See Also Device Functions

DevRead
Reads characters from a device. If the device is record-based, the current field is read. If the device is free-format, the specified number of characters is read. If the number of characters specified is greater than the number of characters remaining in the device, only the remaining characters are read. The DevRead function does not support SQL devices. Use the DevGetField function for these devices.
Syntax

DevRead(hDev, Length) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Length:
The number of characters to read.

Return Value

The data (in string format). If the end of the device is found, an empty string is returned.

340

Chapter 24: Device Functions

Related Functions

DevOpen, DevReadLn, DevFind


Example
! Read 20 characters from a device. Str=DevRead(hDev,20);

See Also Device Functions

DevReadLn
Reads data from the current record of a device until the end of the line, or end of the record. If the device is record-based, the record number is incremented. The carriage return and newline characters are not returned. The DevReadLn function does not support SQL devices. Use the DevGetField function for these devices.
Syntax

DevReadLn(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

The data (in string format). If the end of the device is found, an empty string is returned and the EOF flag is set.
Related Functions

DevOpen, DevRead, DevEOF, DevFind


Example
Str=DevReadLn(hDev);

See Also Device Functions

DevRecNo

341

Chapter 24: Device Functions

Gets the current record number of a device. If the device is record-based, the record number ranges from 1 to the maximum size of the file. If the device is free-format, the record number ranges from 0 to the maximum byte size -1. The DevRcNo function does not support SQL devices. For these devices -1 is returned.
Syntax

DevRecNo(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

The record number. If an error is detected while getting the record number, -1 is returned.
Related Functions

DevOpen, DevSeek
Example
! Get the current record number. Rec=DevRecNo(hDev);

See Also Device Functions

DevSeek
Moves the device pointer to a specified position in the device. If the device is a database, and it is opened in indexed mode, DevSeek will seek to the record number - not through the index. To locate the first record in an indexed device, call the DevFirst() function.
Syntax

DevSeek(hDev, Offset) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Offset:
The offset in the device. If the device is a database device, the offset is the record number. If the device is a binary device, the offset is in bytes (from 0 to the maximum file size -1).

342

Chapter 24: Device Functions

Note: If offset causes a seek past the end of the file, DevSeek returns no error, but sets the EOF flag (that is, a subsequent DevEOF() call will return true). For SQL devices, the function can use only either 0 or 1 offset (beginning of the table).
Return Value

0 (zero) if the seek was successful, otherwise an error code is returned.


Related Functions

DevOpen, DevEOF, DevRecNo, DevFirst


Example
hDev=DevOpen("Log", 0); DevSeek(hDev,100); DevGetField(hDev,"Tag"); ! Gets the value of the "Tag" field at record 100.

See Also Device Functions

DevSetField
Sets new field data in the current record in a device.
Syntax

DevSetField(hDev, sField , sData) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

sField:
The field name, as a string of up to 10 characters. (The dBASE file format limits all field names to a maximum of 10 characters.)

sData:
New field data, in string format. CitectSCADA converts any other data type into a string before setting the data.

Return Value

0 (zero) if the data is successfully set, otherwise an error code is returned.


Related Functions

343

Chapter 24: Device Functions

DevOpen, DevAppend, DevGetField


Example
! Set the fields in the "Recipe" device. hDev=DevOpen("Recipe", 0); DevSeek(hDev, 1); DevSetField(hDev,"Name", "WhiteBread"); DevSetField(hDev,"Flour", IntToStr(iFlour)); DevSetField(hDev,"Water", iWater:####); DevSetField(hDev,"Salt", iSalt); DevClose(hDev);

See Also Device Functions

DevSize
Gets the size of a physical device. The DevSize function does not support SQL devices. For these devices -1 will be returned.
Syntax

DevSize(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

If the device is a database device, the number of records is returned. If the device is a binary device, the number of bytes in the file is returned. If an error is detected, -1 is returned.
Related Functions

DevRecNo, DevSeek
Example
INT NoRec; NoRec=DevSize(hDev); ! Seek to the last record. DevSeek(hDev,NoRec);

See Also Device Functions

344

Chapter 24: Device Functions

DevWrite
Writes a string to a device. If the device is free-format, the data is written to the device as specified. If the device is record-based, the data is written to the current field, and the field pointer is moved to the next field. Writing to a DBF device appends the data to the device. Writing to a SQL device appends the data to the device only when all fields of the row have been written.
Syntax

DevWrite(hDev, sData) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

sData:
The data to write, as a string.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DevOpen, DevWriteLn
Example
! Write PV123 to the device. DevWrite(hDev,"PV123="+PV123:###.#);

For SQL devices: The DevWrite() function can distinguish between numbers, strings, and dates, so you do not need to enclose the data in quote marks. Dates and times need to be in the correct format:
l l l

Date: YYYY-MM-DD Time: HH:MM:SS DateTime: YYYY-MM-DD HH:MM:SS[.F...] (The fraction .F... is optional.)

See Also Device Functions

DevWriteLn

345

Chapter 24: Device Functions

Writes a string to a device. If the device is free-format, the data is written to the device, followed by a newline character. If the device is record-based, a new record is appended to the device and the data is written to this record. The record pointer is then moved to the next record.
Syntax

DevWriteLn(hDev, sData) hDev:


The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

sData:
The data to write, as a string.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DevOpen, DevWrite
Example
/* Write PV123 to the device followed by a newline character */ DevWriteLn(hDev,"PV123="+PV123:###.#);

See Also Device Functions

DevZap
Zaps a device. If a database device is zapped, all records are deleted. If an ASCII file is zapped, the file is truncated to 0 (zero) length. Use this function when you want to delete all records in a database or file without deleting the actual file.
Syntax

DevZap(hDev) hDev:
The device handle, returned from the DevOpen() function. The device handle identifies the table where all data on the associated device is stored.

Return Value

0 (zero) if successful, otherwise an error is returned.

346

Chapter 24: Device Functions

Related Functions

DevDelete
Example
! Delete all records in the alarm log database. hDev = DevOpen("AlarmLog", 0); DevZap(hDev);

See Also Device Functions

Print
Prints a string on the current device. You should call this function only in a report. The output is sent to the device (or group of devices) defined in the Reports database (in the output device field). Note: To print a new line in an RTF report, use the "\par" special character. For example, Print("String" + "\par").
Syntax

Print(String) String:
The string (data) to print.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

PrintLn, DevCurr, DevPrint, DevWrite


Example
! Print "Testvar" and stay on the same line. Print("Value of Testvar="+Testvar:##.#);

See Also Device Functions

PrintFont

347

Chapter 24: Device Functions

Changes the printing font on the current device. You should call this function only in a report. It will change the font style for the device (or group of devices) defined in the Reports database (output device field). It has effect only on reports being printed to a PRINTER_DEV - it has no effect on other types of devices, such as ASCII_DEV and dBASE_DEV.
Syntax

PrintFont(Font) Font:
The CitectSCADA font (defined in the Fonts database).

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

Print
Example

The following report file...


{! example.rpt } ------------------------------------AN example Report ------------------------------------{CICODE} PrintFont("HeadingFont"); {END} Plant Area 1 {CICODE} PrintFont("ReportFont"); {END} {Time(1) } {Date(2) } PV_1 {PV_1:#####.##} PV_2 {PV_2:#####.##} ----------End of Report---------------

...will print as...


------------------------------------AN example Report ------------------------------------Plant Area 1 04:41:56 19-10-93 PV_1 49.00 PV_2 65.00 ----------End of Report---------------

348

Chapter 24: Device Functions

See Also Device Functions

PrintLn
Prints a string on the current device, followed by a newline character. You should call this function only in a report. The output will be sent to the device or group of devices defined in the Reports database (in the output device field). Note: To print a new line in an RTF report, use the "\par" special character. For example, PrintLn("String" + "\par").
Syntax

PrintLn(String) String:
The string (data) to print.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

Print , DevCurr, DevPrint, DevWrite


Example
! Print "Testvar" followed by a new line. PrintLn("Value of Testvar="+Testvar:##.#);

See Also Device Functions

349

Chapter 24: Device Functions

350

Chapter 25: Display Functions


Following are functions relating to the display of graphics pages and objects:
DspAnCreateControlObject Creates a new instance of an ActiveX object. If the object already exists for the given Animation Point Number, then that object will be used (a new object is not created). Frees (removes) an AN from the current page. Gets the area configured for an object at a specific AN (animation-point number). Retrieves the field value of the specified metadata entry. Retrieves metadata information at the specified index. Gets the x and y coordinates of an AN (animation-point number). Gets the privileges configured for an object at a specific AN (animation-point number). Gets information on the state of the animation at an AN. Checks if an AN is within a specified region. Moves an AN. Moves an AN relative to its current position. Creates an AN. Creates an AN relative to another AN. Non-blocking function, that sets the value of the specified metadata entry. Sets the value of a metadata entry. Displays a bar graph at an AN.

DspAnFree DspAnGetArea

DspAnGetMetadata DspAnGetMetadataAt DspAnGetPos

DspAnGetPrivilege

DspAnInfo DspAnInRgn DspAnMove DspAnMoveRel DspAnNew DspAnNewRel DspAnSetMetadata

DspAnSetMetadataAt DspBar

351

Chapter 25: Display Functions

DspBmp DspButton

Displays a bitmap at a specified AN. Displays a button at an AN and puts a key into the key command line (when the button is selected). Displays a button at an AN and calls a function when the button is selected. Displays a chart at an AN. DspCol is deprecated in this version. Deletes the objects at an AN. Delays screen updating until DspDelayRenderEnd() is called. Ends the screen update delay set by DspDelayRenderBegin(). Forces an update to an AN. Displays an error message at the prompt AN. Defines the screen attributes for displaying a text file. Gets the attributes of a file to screen display. Gets the name of the file being displayed in the display "window". Scrolls a file (displayed in the display "window") by a number of characters. Sets the name of the file to display in the display "window". Creates a font. Gets a font handle. Enables or disables the fullscreen mode of the active window. Gets the bottom extent of the object at the specified AN. Gets the current AN.

DspButtonFn

DspChart DspCol DspDel DspDelayRenderBegin DspDelayRenderEnd DspDirty DspError DspFile DspFileGetInfo DspFileGetName

DspFileScroll

DspFileSetName DspFont DspFontHnd DspFullScreen DspGetAnBottom DspGetAnCur

352

Chapter 25: Display Functions

DspGetAnExtent DspGetAnFirst DspGetAnFromPoint

Gets the extent of the object at a specified AN. Returns the first AN on the current page. Gets the AN of the object at a specified set of screen coordinates. Gets the height of the object at a specified AN. Gets the left extent of the object at the specified AN. Returns the AN following a specified AN. Gets the right extent of the object at the specified AN. Gets the top extent of the object at the specified AN. Gets the width of the object at a specified AN. Gets a page environment variable. Gets the mouse position. Determines if the mouse is within the boundaries of a given AN. Gets the nearest AN. Gets the parent animation number (if any), for the specified AN. Gets the current position (value) of a slider at an AN. Gets the tool tip text associated with an AN. Greys and disables a button. Gets object display information from an AN. Deletes an object information block created by DspInfoNew(). Gets stored and real-time data for a variable tag. Creates an object information block for an AN.

DspGetAnHeight DspGetAnLeft DspGetAnNext DspGetAnRight DspGetAnTop DspGetAnWidth DspGetEnv DspGetMouse DspGetMouseOver

DspGetNearestAn DspGetParentAn

DspGetSlider DspGetTip DspGrayButton DspInfo DspInfoDestroy DspInfoField DspInfoNew

353

Chapter 25: Display Functions

DspInfoValid DspIsButtonGray DspKernel DspMarkerMove DspMarkerNew DspMCI DspPlaySound DspPopUpConfigMenu

Checks if an object information block is still valid. Gets the current status of a button. Displays the Kernel window. Moves a trend or chart marker to a specified position. Creates a new trend marker. Controls a multimedia device. Plays a waveform (sound). Displays the contents of a menu node as a pop-up (context) menu, and runs the command associated with the selected menu item. Creates a menu consisting of a number of menu items. Creates a Rich Text object at the animation point. Enables/disables editing of the contents of a rich text object. Enables/disables a rich text object. Returns size information about a rich text object. Loads a copy of a rich text file into a rich text object. Scrolls the contents of a rich text object by one page length. Prints the contents of a rich text object. Saves the contents of a rich text object to a file. Scrolls the contents of a rich text object by a user defined amount. Ends a rubber band selection. Moves a rubber band selection to the new position. Sets the clipping region for the rubber band display.

DspPopupMenu DspRichText DspRichTextEdit DspRichTextEnable DspRichTextGetInfo DspRichTextLoad DspRichTextPgScroll DspRichTextPrint DspRichTextSave DspRichTextScroll

DspRubEnd DspRubMove DspRubSetClip

354

Chapter 25: Display Functions

DspRubStart

Starts a rubber band selection (used to rescale a trend with the mouse). Sets the current position of a slider at the specified AN. Sets tool tip text associated with an AN. Sets the font for tool tip text. Sets the communication status error for a specified animation number. Displays a string at an AN. Displays a symbol at an AN. Displays a series of animated symbols at an AN. Displays a series of animated symbols at an AN. Displays a symbol at a scale and offset from an AN. Displays text at an AN. Switches the display of tool tips on or off. Displays a trend at an AN. Gets information on a trend definition.

DspSetSlider DspSetTip DspSetTooltipFont DspStatus

DspStr DspSym DspSymAnm DspSymAnmEx DspSymAtSize DspText DspTipMode DspTrend DspTrendInfo

See Also Functions Reference

DspAnCreateControlObject
Creates a new instance of an ActiveX object. If the object already exists for the given Animation Point Number, then that object will be used, that is a new object will not be created, the existing object will merely be refreshed. AN object created using this function remains in existence until the page is closed or the associated Cicode Object is deleted.
Syntax

DspAnCreateControlObject(nAN, sClass, Width, Height [, sEventClass] ) nAN:

355

Chapter 25: Display Functions

The animation-point number.

sClass:
The class of the object. You can use the object's human readable name, its program ID, or its GUID. If the class does not exist, the function will return an error. For example:
l l l

"Calendar Control 8.0" - human readable name "MSCAL.Calendar.7" - Program ID "{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID

Width:
The width of the ActiveX object.

Height:
The height of the ActiveX object.

sEventClass:
The string you would like to use as the event class for the object.

Return Value

The newly created object, if successful, otherwise an error is generated.


Related Functions

CreateObject, CreateControlObject
Example

See CreateControlObject See Also Display Functions

DspAnFree
Note: This function is only used for V3.xx and V4.xx animations, and will be superseded in future releases. Frees (removes) an AN from the current page. If an animation exists at the animation number, it is deleted before the AN is freed. Use this function to free existing ANs or ANs created with the DspAnNew() function. Please be aware that the ANs are only freed in memory - the change is not persistent. The next time the page is opened it will display the AN.
Syntax 356

Chapter 25: Display Functions

DspAnFree(nAN) nAN:
The animation-point number.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspAnNew
Example
/* Remove AN20 from the current page. */ DspAnFree(20);

See Also Display Functions

DspAnGetArea
Gets the area configured for an object at a specific AN (animation-point number). The area is returned as an integer. Note: This function does not return the areas of keyboard commands associated with the object.
Syntax

DspAnGetArea(nAN) nAN:
The animation-point number.

Return Value

The area if successful, otherwise an error is returned. If the object is configured with 'Same area as page' checked, the area of the page will be returned. AN area of 0 (zero) means no areas are configured for the object.
Related Functions

DspAnGetPrivilege
Example

357

Chapter 25: Display Functions

/* Get the area configured for the object at AN60. / DspAnGetArea(60);

See Also Display Functions

DspAnGetMetadata
Retrieves the field value of the specified metadata entry.
Syntax

DspAnGetMetadata(nAN, sMetaName) nAN:


An animation number that uniquely identifies an object. This object contains the list of metadata definitions that will be used to perform the association operations. When -2 is specified, it is equivalent to using DspGetAnCur(). (See DspGetAnCur for usage and limitations.)

sMetaName:
The name of the metadata entry for which to search.

Note: Before calling this function, it may be worthwhile to call ErrSet(1) to disable error checking as this function will generate a hardware error for any object that does not have a metadata entry 'sMetaName', and the cicode task will stop executing.
Return Value

Value for the specified metadata. Returns empty string if a matching metadata entry is not defined and error code if unsuccessful.
Related Functions

DspAnGetMetadataAt,DspAnSetMetadata, DspAnSetMetadataAt See Also Display Functions

DspAnGetMetadataAt
Retrieves metadata information at the specified index.
Syntax

DspAnGetMetadataAt(nAN,nIndex,sField) nAn:

358

Chapter 25: Display Functions

An animation number that uniquely identifies an object. This object contains the list of metadata definitions that will be used to perform the association operations. When -2 is specified, it is equivalent to using DspGetAnCur(). (See DspGetAnCur for usage and limitations.)

nIndex:
The index of the metadata in the animation point. The index is 0-based; i.e. the first metadata entry has an index of 0, the next 1, and so on.

sField:
The name of the field from which to retrieve the information for the metadata. Supported fields are:
l l

Name Value

Return Value

The field value string. If there is an error, an empty string is returned. The error code can be obtained by calling the IsError Cicode function.
Related Functions

DspAnGetMetadata,DspAnSetMetadata, DspAnSetMetadataAt See Also Display Functions

DspAnGetPos
Gets the x and y coordinates of an AN, in pixels, relative to the top-left corner of the window.
Syntax

DspAnGetPos(nAN, X, Y) nAN:
The animation-point number.

X, Y:
The variables used to store the x and y pixel coordinates of the AN, returned from this function.

Return Value

0 (zero) if successful, otherwise an error is returned. The X and Y variables are set to the AN's position if successful, or to -1 if an error has been detected.
Related Functions

359

Chapter 25: Display Functions

DspAnMove, DspAnInRgn, DspGetAnCur, DspGetMouse, DspGetNearestAn, PageTransformCoords


Example
/* Get the position of AN20 into X and Y. / DspAnGetPos(20,X,Y);

See Also Display Functions

DspAnGetPrivilege
Gets the privileges configured for an object at a specific AN (animation-point number). The privilege is returned as an integer. Note: This function does not return the privileges of keyboard commands associated with the object.
Syntax

DspAnGetPrivilege(nAN) nAN:
The animation-point number.

Return Value

The privilege if successful, otherwise an error is returned. A privilege of 0 (zero) means no privileges are configured for the object.
Related Functions

DspAnGetArea
Example
/* Get the privileges of the object at AN45. / DspAnGetPrivilege(45);

See Also Display Functions

DspAnInfo
Note: This function is only used for V3.xx and V4.xx animations, and has been

360

Chapter 25: Display Functions

superseded by future releases. Gets information on an AN - the type or state of the animation that is currently displayed.
Syntax

DspAnInfo(nAN, nType) nAN:


The animation-point number.

nType:
The type of information: 0 - The type of animation currently displayed at the AN. The following is returned:

0 - No animation is displayed. 1 - Color is displayed. 2 - A bar graph is displayed. 3 - Text is displayed. 4 - A symbol is displayed. 5 - AN animation symbol is displayed. 6 - A trend is displayed. 7 - A button is displayed. 8 - A slider is displayed. 9 - A plot is displayed.
1 - The state of the animation currently displayed. If color is displayed, the color is returned. If a bar graph, trend, or symbol is displayed, the bar, trend, or symbol name is returned. If text is displayed, the font handle is returned. 2 - The value of the text or the name of a button at the given AN point is returned.

Return Value

The animation information, which depends on the type passed argument, as described above, as a string.
Related Functions

DspGetAnCur
Example

361

Chapter 25: Display Functions

IF DspAnInfo(25,0) = "1" THEN /* If color on AN 25, then get the color */ col = DspAnInfo(25,1); END

See Also Display Functions

DspAnInRgn
Checks if an AN is within a region bounded by two ANs.
Syntax

pAnInRgn(nAN, One, Two) nAN:


The animation-point number.

One, Two:
One - the AN at a corner of the region; two - the AN at the opposite corner of the region.

Return Value

1 if the AN is within the region, or 0 (zero) if it is not.


Example
DspGetMouse(X,Y); DspAnMove(250,X,Y); IF DspAnInRgn(250,20,30) THEN Prompt("Mouse in region bounded by AN20 and AN30"); ELSE Prompt("Mouse not in region"); END

See Also Display Functions

DspAnMove
Note: This function is only used for V3.xx and V4.xx animations, and was superseded by future releases. Moves an AN to a new position. Any animation at this AN is also moved.
Syntax

362

Chapter 25: Display Functions

DspAnMove(nAN, X, Y) nAN:
The animation-point number.

X:
The x pixel coordinates of the new position.

Y:
The y pixel coordinates of the new position.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspAnMoveRel
Example
DspAnMove(25,100,200); ! Moves AN25 to pixel location 100,200.

See Also Display Functions

DspAnMoveRel
Note: This function is only used for V3.xx and V4.xx animations, and was superseded by future releases. Moves an AN relative to its current position. Any animation at this AN is also moved.
Syntax

DspAnMoveRel(nAN, X, Y) nAN:
The animation-point number.

X:
The number of pixels to move the AN in the x plane.

Y:
The number of pixels to move the AN in the y plane.

363

Chapter 25: Display Functions

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspAnMove
Example
DspAnMoveRel(25,10,20); /* Moves AN25 by 10 pixels to the right and 20 pixels downward, relative to its current position. */

See Also Display Functions

DspAnNew
Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases. Creates an AN at the specified x and y coordinates.
Syntax

DspAnNew(X, Y) X:
The x pixel coordinate where the new AN is created.

Y:
The y pixel coordinate where the new AN is created.

Return Value

If successful, the new AN is returned. If the AN cannot be created, -1 is returned. If an AN already exists at this location, that AN is returned.
Related Functions

DspAnNewRel, DspAnFree
Example
AN=DspAnNew(100,200); DspSym(AN,20);

364

Chapter 25: Display Functions

/* Displays symbol 20 at pixel location 100,200 */

See Also Display Functions

DspAnNewRel
Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases. Creates an AN at a distance of x,y pixels from a specified AN.
Syntax

DspAnNewRel(nAN, X, Y) nAN:
The AN used as a reference for the new AN.

X:
The distance in the x plane (in pixels) from the reference AN to the new AN.

Y:
The distance in the y plane (in pixels) from the reference AN to the new AN.

Return Value

If successful, the new AN is returned. If the AN cannot be created, -1 is returned. If an AN already exists at this location, that AN is returned.
Related Functions

DspAnNew, DspGetAnCur
Example
AN=DspAnNewRel(20,100,200); /* Creates an AN at 100x and 200y pixels from AN20 */

See Also Display Functions

DspAnSetMetadata
Non-blocking function, that sets the value of the specified metadata entry.

365

Chapter 25: Display Functions

Note: Metadata items can only be set using Cicode if the name is configured in the object properties -metadata tab and saved with the page.
Syntax

DspAnSetMetadata(nAn, sMetaName, sValue) nAn:


An animation number that uniquely identifies an object. This object contains the list of metadata definitions that will be used to perform the association operations. When -2 is specified, it is equivalent to using DspGetAnCur(). (See DspGetAnCur for usage and limitations.)

sMetaName:
The name of metadata entry for which to search.

Note: Before calling this function, it may be worthwhile to call ErrSet(1) to disable error checking as this function will generate a hardware error for any object that does not have a metadata entry called 'sMetaName', and the cicode task will stop executing sValue:
The value for the metadata to be set.

Return Value

0 if successful, error code if unsuccessful


Related Functions

DspAnSetMetadataAt,DspAnGetMetadata, DspAnGetMetadataAt See Also Display Functions

DspAnSetMetadataAt
Non-blocking function, that sets the value of a metadata entry. Note: Metadata items can only be set using Cicode if the name is configured in the object properties -metadata tab and saved with the page.
Syntax

DspAnSetMetadataAt(nAN, nIndex, sField, sFieldValue) nAn:

366

Chapter 25: Display Functions

An animation number that uniquely identifies an object. This object contains the list of metadata definitions that will be used to perform the association operations. When -2 is specified, it is equivalent to using DspGetAnCur(). (See DspGetAnCur for usage and limitations.)

nIndex:
The index of the metadata in the animation point.

sField:
The name of the field in which to set the information for the metadata. Supported fields are:
l l

Name Value

sFieldValue:
The value to set in the specified field of the metadata entry.

Note: Clusters should be configured either directly by specifying a full tag name such as C1.TagA or indirectly via the function calls (such as WinNewAt()) or via the page configuration parameter.
Return Value

0 if successful, error code if unsuccessful


Related Functions

DspAnSetMetadata, DspAnGetMetadata, DspAnGetMetadataAt See Also Display Functions

DspBar
Displays a bar graph (on a graphics page) at a specified AN. To scale a tag into the correct range, use the EngToGeneric() function. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspBar(nAN, Bar, Value) nAN:


The AN where the bar graph will be displayed.

Bar:

367

Chapter 25: Display Functions

The name of the bar graph to display in the format <[LibName.]BarName>. If you do not specify the library name, a bar graph from the Global library displays (if it exists). To display a Version 1.xx bar graph, specify the bar definition (1 to 255). For example, if you specify bar 1, CitectSCADA displays the bar graph Global.Bar001.

Value:
The value to display on the bar graph. The value needs to be from 0 to 32000 to give 0 to full-scale range on the bar.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

EngToGeneric
Example
DspBar(25,"Bars.Loops",320); /* Displays a value of 320 (that is 10%) on the loops bar (from the bars library) at AN25. */ DspBar(25,3,320); /* Displays a value of 320 (that is 10%) on bar definition 3 (CitectSCADA Version 1.xx) at AN25. */ DspBar(26,"Loops_Bar",EngToGeneric(Tag1,0,100)); /* Displays Tag1 on the loops_bar (from the global library) at AN26. Tag1 has an engineering scale of 0 to 100. */

See Also Display Functions

DspBmp
Displays a bitmap at a specified AN. This function allows you to display any bitmap file at run time. (You can get a new bitmap file from operator input or from the plant, and display it dynamically.) Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspBmp(nAN, sFile, Mode) nAN:


The animation-point number.

sFile:

368

Chapter 25: Display Functions

The name of the bitmap (.BMP) file. The file needs to be in the user project path. (Does not support 1 bit, 24 bit or OS/2 bitmaps.)

Mode:
The mode of bitmap display:

0 - Erase the existing bitmap and display this bitmap. 1 - Do not erase the existing bitmap, just draw the new bitmap. (This mode provides smoother animation than Mode 0, but the bitmaps needs to be the same size). 2 - Do not erase the existing bitmap, just draw the new bitmap. This mode is similar to mode 1, but it displays the bitmap about 3 times faster. However, the bitmap should not contain any transparent color, or it will display as a random color. Use this mode for fast, smooth animation.
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDel
Example
// Display the bitmap "MyImage.bmp" at AN 60 DspBMP(60, "MyImage.bmp", 0)

See Also Display Functions

DspButton
Displays a button at a specified AN. When the button is selected, the key definition is put into the key command line. The font, width, height, and down and repeat keys of the button are optional. If you do not specify a width and height, the button adjusts to the size of the button sName. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspButton(nAN, UpKey, Name [, hFont] [, Width] [, Height] [, DownKey] [, RepeatKey] [, Style]) nAN:

369

Chapter 25: Display Functions

The animation-point number.

UpKey:
The key generated when the command button is selected (when the mouse button is released after being clicked down). This is the default operation for commands activated by a button.

Name:
The name to display on the button.

hFont:
The handle of the font used to display the button name. Use the DspFont() function to create a new font and return the font handle. Use the DspFontHnd() function to return the font handle of an existing font. The Windows button font is used if the font is omitted or is not defined in the database.

Width:
The width of the button in pixels.

Height:
The height of the button in pixels.

DownKey:
The key generated when the mouse button is clicked down (over the command button). Normally this parameter is not used, because most buttons are configured to activate a command when the mouse button is released (returning to the `up' position).

RepeatKey:
The key generated repetitively, while the mouse button is being held down (over the command button).

Style:
A number indicating the visibility style of the button:
l l

0 - NORMAL: The button appears as a standard button. 1 - BORDER_3D: The button is drawn with only the 3-D border (transparent face). 2 - BORDER: The button is drawn with only a thin line border. 3 - TARGET: The button is totally transparent - this constitutes a screen target.

l l

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspButtonFn, KeySetSeq, DspFont, DspFontHnd

370

Chapter 25: Display Functions

Example
/* Display a self-sizing button at AN20 using the default font. The button is named "Help". When selected, the Key Code "KEY_F1" is put into the key command line. */ DspButton(20,KEY_F1,"Help"); /* Display the same button at AN20, but in an existing font called "BigFont". */ DspButton(20,KEY_F1,"Help",DspFontHnd("BigFont");

See Also Display Functions

DspButtonFn
Displays a button at a specified AN. When the button is selected, a user function is called. If the width and height are 0 (zero), then the button adjusts to the size of the button sName. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspButtonFn(nAN, UpFunction, Name [, hFont] [, Width] [, Height] [, DownFunction] [, RepeatFunction] ) nAN:


The animation-point number.

UpFunction:
The user function called when the command button is selected (when the mouse button is released after being clicked down). This is the default operation for commands activated by a button. This callback function can have no arguments, so specify the function with no parentheses (). The callback function needs to return INT as its return data type. You cannot specify a CitectSCADA builtin function for this argument.

Name:
The name to display on the button.

hFont:
The handle of the font used to display the button name. Use the DspFont() function to create a new font and return the font handle. Use the DspFontHnd() function to return the font handle of an existing font. The Windows button font is used if the font is omitted or is not defined in the database.

Width:

371

Chapter 25: Display Functions

The width of the button in pixels.

Height:
The height of the buton in pixels.

DownFunction:
The user function called when the mouse button is clicked down (over the command button). Normally this parameter is not used, because most buttons are configured to activate when the mouse button is released (returning to the `up' position). The callback function needs to have no arguments, so specify the function with no parentheses (). The callback function needs to return INT as its return data type. You cannot specify a CitectSCADA built-in function for this argument.

RepeatFunction:
The user function called repetitively, while the mouse button is being held down (over the command button) The callback function needs to have no arguments, so specify the function with no parentheses (). The callback function needs to return INT as its return data type. You cannot specify a CitectSCADA built-in function for this argument.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspButton, DspFont, DspFontHnd


Example
DspButtonFn(20,MyFunc,"Help",0,50,10); ! Call this function when the button is selected. INT FUNCTION MyFunc() PageDisplay("Help"); RETURN 0; END

See Also Display Functions

DspChart
Displays a chart at an AN. Charts are trend lines with markers on them. Values are plotted on the chart pens. You need to specify Value1, but Value2 to Value8 are optional. If more values (than the configured pens) are specified, the additional values are ignored. If fewer values (than the configured pens) are specified, the pens that have no values are not displayed.

372

Chapter 25: Display Functions

You should use this function only if you want to control the display of charts directly.
Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.

Syntax

DspChart(nAN, Chart, Value1 [, Value2 ... Value8] ) nAN:


The AN where the chart will be displayed.

Chart:
The chart to display.

Value1:
The value to display on Pen 1 of the chart.

Value2 ... 8:
The values to display on Pen 2...Pen 8 of the chart. These values are optional.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDel, DspTrend
Example
/* Using chart definition 5 at AN25, display a value of 10 on Pen1, 20 on Pen2, 30 on Pen3 and 40 on Pen4 of the chart. */ DspChart(25,5,10,20,30,40); /* Using chart definition 6 at AN26, display a value of 100 on Pen1 and 500 on Pen2 of the chart. */ DspChart(26,6,100,500);

See Also Display Functions

DspCol
DspCol is deprecated in this version of CitectSCADA.
Syntax

DspCol(nAN, Color)

373

Chapter 25: Display Functions

nAN:
The animation-point number.

Color:
The color to display at the AN.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDel
Example
DspCol(25,RED); /* Displays the color red at AN25. */

See Also Display Functions

DspDel
Deletes all objects from a specified AN. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspDel(nAN) nAN:
The animation-point number.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDirty
Example
DspDel(25);

374

Chapter 25: Display Functions

! Deletes all animation at AN25.

See Also Display Functions

DspDelayRenderBegin
Delays screen updating until DspDelayRenderEnd is called. This function should be used with DspDelayRenderEnd() to "sandwich" Cicode that will modify the appearance of a page. The code should be preceded by DspDelayRenderBegin(), and followed by DspDelayRenderEnd(). This will reduce screen update times, because the modifying code is given time to execute before the page is updated with the changes, and the changes are all made in a single re-draw. Note: If you have not changed the [Page]DelayRenderAll parameter from its default (TRUE), then you do not need to use this function. You can call this function as many times in a row as you like, as long as each is ended with a call to DspDelayRenderEnd. Because your display will stop updating while the "sandwiched" code runs, you should try to make that code as efficient as possible. Do not call Sleep() or any other Cicode functions that will take a long time to run. Do not call WinSelect within the "sandwiched" code. Do not call this function directly from the Kernel.
Syntax

DspDelayRenderBegin()
Related Functions

DspDelayRenderEnd
Example
/* Begin delay so the following code can be executed before the images are re-drawn. */ DspDelayRenderBegin(); DspBMP(50, "Image1.bmp", 0) ! Display the bitmap "Image1.bmp" at AN 50 DspBMP(100, "Image2.bmp", 0) ! Display the bitmap "Image2.bmp" at AN 100 DspBMP(150, "Image3.bmp", 0) ! Display the bitmap "Image3.bmp" at AN 150 DspBMP(200, "Image4.bmp", 0) ! Display the bitmap "Image4.bmp"

375

Chapter 25: Display Functions

at AN 200 DspBMP(250, "Image5.bmp", 0) ! Display the bitmap "Image5.bmp" at AN 250 /* End delay so the images can be re-drawn. */ DspDelayRenderEnd();

See Also Display Functions

DspDelayRenderEnd
Ends the screen update delay set by DspDelayRenderBegin. This function should be used with DspDelayRenderBegin() to "sandwich" Cicode that will modify the appearance of a page. The code should be preceded by DspDelayRenderBegin(), and followed by DspDelayRenderEnd(). This will reduce screen update times, because the modifying code is given time to execute before the page is updated with the changes, and the changes are all made in a single re-draw. Because your display will stop updating while the "sandwiched" code runs, you should try to make that code as efficient as possible. Do not call Sleep() or any other Cicode functions that will take a long time to run. Do not call WinSelect within the "sandwiched" code. Do not call this function directly from the Kernel. Note: If you have not changed the [Page]DelayRenderAll parameter from its default (TRUE), then you do not need to use this function.
Syntax

DspDelayRenderEnd()
Return Value

No value is returned.
Related Functions

DspDelayRenderBegin
Example
/* Begin delay so the following code can be executed before the images are re-drawn. */ DspDelayRenderBegin(); DspBMP(50, "Image1.bmp", 0) ! Display the bitmap "Image1.bmp" at AN 50 DspBMP(100, "Image2.bmp", 0) ! Display the bitmap "Image2.bmp"

376

Chapter 25: Display Functions

at AN 100 DspBMP(150, "Image3.bmp", 0) ! at AN 150 DspBMP(200, "Image4.bmp", 0) ! at AN 200 DspBMP(250, "Image5.bmp", 0) ! at AN 250 /* End delay so the images can DspDelayRenderEnd();

Display the bitmap "Image3.bmp" Display the bitmap "Image4.bmp" Display the bitmap "Image5.bmp" be re-drawn. */

See Also Display Functions

DspDirty
Forces CitectSCADA to update an AN. Normally, CitectSCADA updates the animation on the AN only if the data has changed. This function tells CitectSCADA to update the AN the next time it animates the AN - even if the data has not changed. Use this function when you have complex animations that overlap. If two or more animations overlap, you should use the DspDel() or DspDirty() function on their ANs, and then display them in the same order (when they need to be updated). Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspDirty(nAN) nAN:
The animation-point number.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDel
Example
DspDirty(20); ! Forces an update of AN20.

See Also Display Functions

377

Chapter 25: Display Functions

DspError
Displays an error message at the prompt AN on the operator's computer. You can disable the error message display (of this function) by setting the Cicode execution mode in the CodeSetMode() function.
Syntax

DspError(String) String:
The message to be displayed.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

CodeSetMode, Prompt
Example
DspError("Error found"); ! Displays "Error found" at the prompt AN.

See Also Display Functions

DspFile
Defines the screen attributes for displaying a text file. This function defines a "window" where the file will be displayed. You should call this function before any file-to-screen function. you need to define sequential ANs for each line of text in the display. The file is displayed starting at the specified AN, then the next (highest) AN, and so on. You should not use proportionally-spaced fonts, because the columns of text might not be aligned. You would normally call this function as the entry function for a graphics page. Use the DspFileSetName() function to specify the file to be displayed. This function is a low level animation function - it controls exactly how the file is to display. If you just want to display a file, use the PageFile() function.
Syntax

DspFile(nAN, hFont, Height, Width) nAN:

378

Chapter 25: Display Functions

The AN where the file display window will be positioned. When this is set to -2, the window will be created in the Citect Kernel. However, the hFont argument is ignored.

hFont:
The handle for the font that is used to display the file, returned from the DspFont() or DspFontHnd () function. The font handle identifies the table where data on the associated font is stored.

Height:
The maximum number of lines to display on one page of the file display window.

Width:
The width of the file display window, in characters.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

PageFile, DspFileGetInfo, DspFileGetName, DspFileScroll, DspFileSetName, DspFont, DspFontHnd


Example
DspFile(20,0,20,80); /* Defines the attributes of a screen display to start at AN20, using the default font, with a window size of 20 lines x 80 columns. */

See Also Display Functions

DspFileGetInfo
Gets the attributes of a file-to-screen display (used for displaying text files).
Syntax

DspFileGetInfo(nAN, Type) nAN:


The AN where the file display window will be located. This AN needs to be the same as the AN specified with the DspFile() function.

nType:
The type of data required:

0 - The width of the file display window, in characters.

379

Chapter 25: Display Functions

1 - The maximum number of lines that can display in one page of the file display window. 2 - The file-to-screen row offset number. 3 - The file-to-screen column offset number. 4 - The number of lines in the displayed file.
Return Value

The attributes of the "window" as an integer. If an incorrect AN is specified, an error is returned.


Related Functions

DspFile, DspFileGetName, DspFileScroll, DspFileSetName


Example
! Display the page number of the file display. PageNumber=IntToStr(DspFileGetInfo(20,2)/DspFileGetInfo(20,1)+1); DspText(12,0,"Page No "+PageNumber);

See Also Display Functions

DspFileGetName
Gets the name of the file being displayed in the display "window". You can use this function to display the file name on the screen.
Syntax

DspFileGetName(nAN) nAN:
The animation-point number.

Return Value

The name of the file (as a string). If an incorrect AN is specified, an error is returned.
Related Functions

DspFile, DspFileGetInfo, DspFileScroll, DspFileSetName


Example
DspText(11,0,DspFileGetName(20)); ! Displays the name of the file displayed at AN20.

380

Chapter 25: Display Functions

See Also Display Functions

DspFileScroll
Scrolls a file (displayed in the display "window") by a number of characters.
Syntax

DspFileScroll(nAN, Direction, Characters) nAN:


The animation-point number.

Direction:
The direction in which to scroll:

1 - Left 2 - Right 3 - Up 4 - Down Characters:


The number of characters to scroll. To page up or page down through the file, scroll by the height of the file-to-screen window (returned by DspFileGetInfo(AN, 1)).

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspFile, DspFileGetInfo, DspFileSetName, DspFileGetName


Example

Page Keyboard Key Sequence Command Comment PgUp DspFileScroll(20,3,10) Scroll up 10 lines

381

Chapter 25: Display Functions

See Also Display Functions

DspFileSetName
Sets the name of the file to display in the display "window". You should call the DspFile () function first (as the entry function for a graphics page) to define the attributes of the display. You can then use the DspFileSetName() function (as a keyboard command) to display a user-specified file. When you call this function, the specified file name is read from disk and displayed on the screen.
Syntax

DspFileSetName(nAN, sName) nAN:


The animation-point number.

sName:
The name of the file to display.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspFile, DspFileGetInfo, DspFileGetName, DspFileScroll


Example

Pages Page Name Entry Command Comment Page Keyboard Key Sequence Command Comment ######## Enter DspFileSetName(20, Arg1) Displays a specified file on the page FilePage DspFile(20,0,20,80) Defines a file to screen display to commence at AN20

382

Chapter 25: Display Functions

DspFile(20,0,20,80); /* Defines the file-to-screen display to commence at AN20 using the default font, with a window size of 20 lines x 80 columns. */ DspFileSetName(20,"C:\AUTOEXEC.BAT"); ! Displays file C:\AUTOEXEC.BAT.

See Also Display Functions

DspFont
Creates a font and returns a font handle. If the requested font already exists, its font handle is returned. You can use this font handle in the functions that display text, buttons, and text files. If the exact font size does not exist, the closest font size is used.
Syntax

DspFont(FontType, PixelSize, ForeOnColor, BackOnColor [, ForeOffColor] [, BackOffColor] ) FontType:


The font type, for example, "Helv".

PixelSize:
The font size, as a positive number for pixels, or a negative number for points.

ForeOnColor:
The foreground color used for the text. If implementing flashing color, this is the initial color that will be used. Select a color from the list of Predefined Color Names and Codes or create an RGBbased color using the function MakeCitectColour.

BackOnColor:
The color used for the background of text. If implementing flashing color, this is the initial color that will be used. Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.

ForeOffColor:
An optional argument only required if implementing flashing color for the font foreground. It represents the secondary color used. Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.

BackOffColor:
An optional argument only required if implementing flashing color for the font background. It represents the secondary color used. Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.

383

Chapter 25: Display Functions

Return Value

The font handle as an integer. If the font cannot be created, -1 is returned. The font handle identifies the table where all data on the associated font is stored.
Related Functions

DspFontHnd, DspText, DspButton, DspButtonFn, DspFile


Example
Font = DspFont("Helv", -12, White, Red); DspText(20, Font, "Text in Helv Font"); /* Displays "Text in Helv Font" in 12-point Helvetica font in white on red at AN20. */ Font = DspFont("Helv", 24, White, Red, Black); DspText(20, Font, "Text in Helv Font"); /* Displays "Text in Helv Font" in 24 pixel Helvetica font in flashing black and white on red at AN20. */

See Also Display Functions

DspFontHnd
Gets the font handle of a font that is defined in the Fonts database. You can use this font handle in the functions that display text, buttons, and text files.
Syntax

DspFontHnd(sName) Name:
The font name in the fonts database.

Return Value

The font handle as an integer. If the font cannot be found, -1 is returned. The font handle identifies the table where the data on the associated font is stored.
Related Functions

DspFont, DspText, DspButton, DspButtonFn, DspFile


Example

Fonts

384

Chapter 25: Display Functions

Font Name Font Type Pixel Size Foreground Color Background Color Comment

BigFont Helv 24 Blue -1 Defines a font

hBigFont=DspFontHnd("BigFont"); DspText(20,hBigFont,"Text in Big Font"); /* Displays "Text in Big Font" in 24-point Helvetica font in blue on an unchanged background at AN20. */

See Also Display Functions

DspFullScreen
Disables or enables the fullscreen mode of the currently active window. This function does not resize the window when it is called; it merely sets the mode flag. The next time the window is displayed, its size (on screen) changes to reflect the setting of the flag. This function overrides the [Animator]FullScreen parameter setting. If [Page]DynamicSizing is turned on, a page in fullscreen state takes up the entire display area (assuming this does not affect its aspect ratio), and it cannot be resized. Also, a fullscreen page will display without a title bar unless Title Bar is checked in Page Properties (or was checked when the page was created). Resizing pages can result in lower picture quality. If this is unacceptable, you should re-design the page using the desired resolution. If [Page]DynamicSizing is turned off, fullscreen will have the same limitations as it had in versions of CitectSCADA prior to V5.10. In other words, for a page to be displayed in fullscreen, the size of the page needs to be the same size as the display (or bigger). If the page is smaller than the display, the title bar will still display even if fullscreen mode is enabled. Check the size of the graphic pages in CtDraw Tools|Page Attributes Dialog to verify that it is the same as the display resolution. For example 640x480 for VGA, 800x600 for SVGA and 1024x768 for XGA.
Syntax

DspFullScreen(Mode)

385

Chapter 25: Display Functions

Mode:
Fullscreen mode:

0 - Disable fullscreen mode. 1 - Enable fullscreen mode without title bar 2 Enable fullscreen mode with title bar.
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

WinMode
Example
/*Minimize the Window, Enable fullscreen mode and then maximize the window.*/ WinMode(6); DspFullScreen(1); WinMode(3);

See Also Display Functions

DspGetAnBottom
Gets the bottom extent of the object at the specified AN.
Syntax

DspGetAnBottom(nAN) nAN:
The animation-point number.

Return Value

The y coordinate of the bottom extent of the object at the AN. If no object exists at the AN, -1 is returned.
Related Functions

DspGetAnBottom, DspGetAnWidth, DspGetAnHeight, DspGetAnLeft, DspGetAnRight, DspGetAnTop, DspGetAnNext, DspGetAnExtent


Example

386

Chapter 25: Display Functions

nBottom = DspGetAnBottom(30);

See Also Display Functions

DspGetAnCur
Gets the AN of the current graphics object. This function should only be used by expressions or Cicode functions called from the condition fields of a graphics object, excluding input/command fields. If you need to know the AN that triggered the input/command, the KeyGetCursor function may be used as it returns the AN where the cursor is currently positioned. You cannot call this function from the Button or Keyboard forms.
Syntax

DspGetAnCur()
Return Value

The AN associated with the current graphics object. If this function is called outside the page animation system or from an input/command field, -1 will be returned.
Example

Numbers AN Expression Comment 20 MyFunc(PV_10) Display the value of PV_10 at AN20

/* Function displays a number at the current AN and returns the value supplied in the call */ INT FUNCTION MyFunc(INT value) INT AN, hNew; AN = DspGetAnCur(); hNew = DspAnNewRel(AN, 0, 20); DspStr(hNew, "Default", VALUE:###.#); RETURN value; END

387

Chapter 25: Display Functions

See Also Display Functions

DspGetAnExtent
Gets the extent of the object (the enclosing boundary) at the specified AN.
Syntax

DspGetAnExtent(nAN, Top, Left, Bottom, Right) nAN:


The AN at which the object is positioned.

Top:
A buffer that contains the top-most extent of the object.

Left:
A buffer that contains the left-most extent of the object.

Bottom:
A buffer that contains the bottom-most extent of the object.

Right:
A buffer that contains the right-most extent of the object.

Return Value

0 (zero) if successful, otherwise an error is returned. The Top, Left, Bottom, and Right arguments contain the extents of the object, in pixels.
Related Functions

DspGetAnWidth, DspGetAnHeight, DspGetAnLeft, DspGetAnRight, DspGetAnBottom, DspGetAnTop, PageTransformCoords


Example
// Get extents at AN 25. DspGetAnExtent(25, Top, Left, Bottom, Right);

See Also Display Functions

DspGetAnFirst

388

Chapter 25: Display Functions

Gets the first AN on the current page, based on the order in which the ANs were stored by Graphics Builder.
Syntax

DspGetAnFirst()
Return Value

The value for the first AN, otherwise an error is returned.


Related Functions

DspGetAnNext See Also Display Functions

DspGetAnFromPoint
Gets the AN of the object at a specified set of screen coordinates. If the X and Y coordinates given are within the extents of an object, then the AN number of the object will be returned. For example, if there is a button at coordinates (300, 140), and it is 100 wide, 50 high, this function would return the AN if it uses X between 300 & 400 and Y between 140 and 190, such as DspGetAnFromPoint(325,180).

Hint: If you are using groups and the specified coordinates point to an object that is part of a group, the AN of the object is returned, not the AN of the group.
Syntax

DspGetAnFromPoint(X, Y [, PrevAN] ) X:
The x coordinate of the screen point.

Y:
The y coordinate of the screen point.

PrevnAN:

389

Chapter 25: Display Functions

Retrieves the previous AN (in z-order) in situations where a number of objects overlap at the specified point. The default of 0 (zero) specifies no previous AN. A non-zero value should only ever be passed if it is the result of a previous call to DspGetAnFromPoint.

Return Value

The AN or 0 (zero) if no object exists at the point.


Example
DspGetMouse(X,Y); // GetMouse position AN = DspGetAnFromPoint(X,Y); // Gets AN if mouse is over the object Prompt("AN of object ="+nAN:###); !Displays the object's AN at the prompt line

If several objects overlap each other at the specified point, the PrevAN argument can be used to produce a list of the associated ANs. This is achieved by using PrevAN to pass the previous result into another call of the function until a zero return is given.
INT nAn; nAn = DspGetAnFromPoint(100,100) WHILE nAn <> 0 DO //Do Something nAn = DspGetAnFromPoint(100,100,nAn); END

See Also Display Functions

DspGetAnHeight
Gets the height of the object at a specified AN.
Syntax

DspGetAnHeight(nAN) nAN:
The animation-point number.

Return Value

The height of the object (in pixels). If no object exists at the AN, -1 is returned.
Related Functions

DspGetAnWidth, DspGetAnLeft, DspGetAnRight, DspGetAnBottom, DspGetAnTop


Example 390

Chapter 25: Display Functions

nHeight = DspGetAnHeight(30);

See Also Display Functions

DspGetAnLeft
Gets the left extent of the object at the specified AN.
Syntax

DspGetAnLeft(nAN) nAN:
The animation-point number.

Return Value

The x coordinate of the left extent of the object at the AN. If no object exists at the AN, -1 is returned.
Related Functions

DspGetAnWidth, DspGetAnHeight, DspGetAnRight, DspGetAnBottom, DspGetAnTop, DspGetAnExtent


Example
nLeft = DspGetAnLeft(30);

See Also Display Functions

DspGetAnNext
Returns the AN that follows the specified AN, based on the order in which the ANs were stored on a page by Graphics Builder.
Syntax

DspGetAnNext(nAN) nAN:
The animation-point number.

Return Value

391

Chapter 25: Display Functions

The value for the next AN. If -1 is returned, it means the specified AN is invalid or it is the last AN on the page.
Related Functions

DspGetAnFirst See Also Display Functions

DspGetAnRight
Gets the right extent of the object at the specified AN.
Syntax

DspGetAnRight(nAN) nAN:
The animation-point number.

Return Value

The x coordinate of the right extent of the object at the AN. If no object exists at the AN, 1 is returned.
Related Functions

DspGetAnWidth, DspGetAnHeight, DspGetAnLeft, DspGetAnBottom, DspGetAnTop, DspGetAnExtent


Example
nRight = DspGetAnRight(30);

See Also Display Functions

DspGetAnTop
Gets the top extent of the object at the specified AN.
Syntax

DspGetAnTop(nAN) nAN:
The animation-point number.

Return Value

392

Chapter 25: Display Functions

The y coordinate of the top extent of the object at the AN. If no object exists at the AN, -1 is returned.
Related Functions

DspGetAnWidth, DspGetAnHeight, DspGetAnLeft, DspGetAnRight, DspGetAnBottom, DspGetAnExtent


Example
nTop = DspGetAnTop(30);

See Also Display Functions

DspGetAnWidth
Gets the width of the object at a specified AN.
Syntax

DspGetAnWidth(nAN) nAN:
The animation-point number.

Return Value

The width of the object (in pixels). If no object exists at the AN, -1 is returned.
Related Functions

DspGetAnHeight, DspGetAnLeft, DspGetAnRight, DspGetAnBottom, DspGetAnTop, DspGetAnExtent


Example
nWidth = DspGetAnWidth(30);

See Also Display Functions

DspGetEnv
Gets a page environment variable.
Syntax

DspGetEnv(sName)

393

Chapter 25: Display Functions

sName:
The name of the variable (set using the page environment dialog)

Return Value

The value of the variable (as a string).


Example
FUNCTION PageGroup() PageDisplay(DspGetEnv("GroupMenu")); END

See Also Display Functions

DspGetMouse
Gets the x and y coordinates of the mouse position, relative to the top left corner of the window. Note: Locally declared Cicode variables need to be used for X and Y, otherwise an "Incompatible Type" compile error may be generated.
Syntax

DspGetMouse(X, Y) X:
The variables used to store the x pixel coordinate of the mouse position, returned from this function.

Y:
The variables used to store the y pixel coordinate of the mouse position, returned from this function.

Return Value

0 (zero) if successful, otherwise an error is returned. The X and Y variables are set to the mouse position.
Related Functions

KeyGetCursor, DspAnGetPos, DspGetMouseOver, DspGetNearestAn, PageTransformCoords


Example 394

Chapter 25: Display Functions

! If the mouse cursor is at x,y pixel coordinate 43,20; DspGetMouse(X,Y); ! Sets X to 43 and Y to 20.

See Also Display Functions

DspGetMouseOver
Determines if the mouse is within the boundaries of a given AN.
Syntax

DspGetMouseOver(nAN) nAN
The AN of the animation you wish to check, or -1 for the current AN. Defaults to -1.

Return Value

1 if within the specified AN, 0 if not.


Related Functions

KeyGetCursor, DspAnGetPos, DspGetMouse, DspGetNearestAn See Also Display Functions

DspGetNearestAn
Gets the AN nearest to a specified x,y pixel location. If using groups and the nearest object to the specified coordinates is part of a group, the AN of the object is returned, not the AN of the group.
Syntax

DspGetNearestAn(X, Y) X:
The x coordinate (in pixels).

Y:
The y coordinate (in pixels).

Return Value

The animation point number (AN). A value of -1 is returned if no AN is found.

395

Chapter 25: Display Functions

Related Functions

DspGetMouse, DspAnGetPos, DspGetAnFromPoint


Example
DspGetMouse(X,Y); ! Gets mouse position. AN=DspGetNearestAn(X,Y); ! Gets AN nearest to the mouse. Prompt("Mouse At AN"+nAN:###); ! Displays AN nearest to the mouse.

See Also Display Functions

DspGetParentAn
Gets the parent animation number (if any), for the specified animation number. AN animation point will have a parent animation point if it corresponds to an object in a group.
Syntax

DspGetParentAn(nAN) AN:
The animation-point number.

Return Value

The parent animation point number (AN). If no parent animation exists or an invalid animation number is passed, 0 (zero) is returned.
Related Functions

DspGetAnCur
Example
// Get the parent animation for object 89 (part of a symbol set) AN = DspGetParentAn(89);

See Also Display Functions

DspGetSlider

396

Chapter 25: Display Functions

Gets the current position (value) of a slider at an AN. You can call this function in the slider event to find the new position of the slider. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspGetSlider(nAN) nAN:
The animation-point number.

Return Value

The value of the slider from 0 to 32000. If no animation exists at the AN, -1 is returned.
Related Functions

DspSetSlider
Example
// Get the position of the slider at AN 30 nPos = DspGetSlider(30);

See Also Display Functions

DspGetTip
Gets the tool tip text associated with an AN.
Syntax

DspGetTip(nAN, Mode) nAN:


The AN from which to get the tool tip text. If no object is configured at the AN, the function will return an empty string.

Mode:
0 - Tool tips from all animation records configured at the AN. Tips are concatenated with a newline character between each string. (This mode is only used for V3.xx and V4.xx animations, and has been subsequently superseded.)

1 - The tool tip from the object configured at the AN.


Return Value 397

Chapter 25: Display Functions

The tool tip text (as a string). If no user tip is available, an empty string is returned.
Related Functions

DspSetTip, DspTipMode
Example
!Display the tool tip text on AN19 DspText(19, 0, DspGetTip(KeyGetCursor(), 1));

See Also Display Functions

DspGrayButton
Grays and disables a button. If the button is a symbol, the symbol is overwritten with a gray mask. (When a button is grayed, it cannot be selected.) If the Disabled field in the Buttons database is blank, the button is enabled unless you use this function. If the Disabled field in the Buttons database contains an expression, this function will not override the expression. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspGrayButton(nAN, nMode) nAN:


The AN where the button is located.

nMode:
The mode of the operation:

0 - Ungray the button. 1 - (GRAY_SUNK) Recess the text or symbol (the text or symbol on the button is recessed and shadowed). 2 - (GRAY_PART) This mode is now obsolete - it now has the same effect as GRAY_ALL. 3 - (GRAY_ALL) - Mask the entire button (a gray mask displays over the face of the button).
Return Value

0 (zero) if successful, otherwise, -1 (if no AN is found).

398

Chapter 25: Display Functions

Related Functions

DspButton, DspButtonFn, DspIsButtonGray


Example
! Disable button at AN21 DspGrayButton(21, GRAY_SUNK);

See Also Display Functions

DspInfo
Extracts individual pieces of object information from an AN. Each AN can have multiple expressions associated with it, and each expression can have multiple variables associated with it. You use an index to refer to each individual expressions or variables. Typically, you would query the number of expressions, then the number of variables in a given expression, then the details of a given variable tag. Note: Before calling this function you need to first use DspInfoNew() to create a handle to the information block from which you want to extract information.
Syntax

DspInfo(hInfo, Type, Index) hInfo:


The object information block handle, as returned by DspInfoNew(). This handle identifies the table (or block) where all object data is stored.

nType:
The type of data to extract:

0 - Object title (the name of the object type) 1 - Object expression text 2 - Object expression result text 3 - The variable tag name 4 - Not supported. Note: Getting the raw value using DspInfo is no longer supported. To get the raw value of a tag, use the TagSubscribe function, specifying a value of Raw for the sScaleMode parameter. When using TagSubscribe, you can either call SubscriptionGetAttribute to obtain the

399

Chapter 25: Display Functions

value whenever required or register a callback cicode function to run when the value changes. See TagSubscribe for more details. 5 - The engineering value associated with the variable 6 - The Cicode context. Calling DspInfo with this Type will return a string describing the context in which the Cicode expression is contained. For example, if it appears on the horizontal movement tab it would return "Move X". 7 - The number of Cicode expressions. Calling DspInfo with this Type will return the number of Cicode expressions associated with this animation point. 8 - The number of tags in the expression. Calling DspInfo with this Type will return the number of tags that appear in the given Cicode expression. 9 - Name of the cluster in which the variable tag resides. 10 - Full name of the variable tag in the form cluster.tagname. Index:
An index to the variable within the information block. The required index changes according to the Type as follows:
l

For Types 0 to 2, 6 and 8, the index needs to be set to the index of the expression that you wish to query. For Types 3 to 5, the index needs to be set to the index of the tag that you wish to query. When one of these types is used, DspInfo will query the tag in the most recently queried expression (otherwise expression 0). For Type 7, the index is ignored.

Return Value

The object information (as a string). A blank string is returned if you specify a non-existent expression or variable.
Related Functions

DspInfoNew, DspInfoField, DspInfoDestroy, TagSubscribe, SubscriptionAddCallback, SubscriptionGetAttribute


Example
INT hInfo; INT iEngineeringValue; INT iNumberOfExpressions; INT iNumberOfTags; INT iExpressionIndex; INT iTagIndex; STRING sObjectType; STRING sExpressionText;

400

Chapter 25: Display Functions

STRING sExpressionResult; STRING sExpressionContext; STRING sTagName; hInfo = DspInfoNew(AN); IF (hInfo > -1) THEN sObjectType = DspInfo(hInfo, 0, 0); iNumberOfExpressions = StrToInt(DspInfo(hInfo, 7, 0)); FOR iExpressionIndex = 0 TO iExpressionIndex < iNumberOfExpressions DO sExpressionText = DspInfo(hInfo, 1, iExpressionIndex); sExpressionResult = DspInfo(hInfo, 2, iExpressionIndex); sExpressionContext = DspInfo(hInfo, 6, iExpressionIndex); iNumberOfTags = StrToInt(DspInfo(hInfo, 8, iExpressionIndex)); FOR iTagIndex = 0 TO iTagIndex < iNumberOfTags DO sTagName = DspInfo(hInfo, 3, iTagIndex); iEngineeringValue = StrToInt(DspInfo(hInfo, 5, iTagIndex)); .. END .. END END

See Also Display Functions

DspInfoDestroy
Destroys an object information block created by DspInfoNew(). You should destroy an object information block when you no longer need it, to free CitectSCADA resources. When the page (with which the object is associated) is closed, CitectSCADA automatically destroys the object information block.
Syntax

DspInfoDestroy(hInfo) hInfo:
The object information block handle, as returned by DspInfoNew(). This handle identifies the table (or block) where all object data is stored.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspInfo, DspInfoNew, DspInfoField, DspInfoValid


Example
hInfo=DspInfoNew(20);

401

Chapter 25: Display Functions

! Do animation operation DspInfoDestroy(hInfo);

See Also Display Functions

DspInfoField
Obtains static and real-time data from a variable tag. You get static data from the Variable Tags database. The additional field "Eng_Value", returns dynamic real-time data for the variable tag. To get this real-time data, you need to first call the DspInfoNew() function to get the information block handle hInfo. Getting the raw value of a variable tag using DspInfoField is no longer supported. To get the raw value of a tag, use the TagSubscribe function, specifying a value of "Raw" for the sScaleMode parameter. When using TagSubscribe, you can either call SubscriptionGetAttribute to obtain the value whenever required or register callback cicode function to run when the value changes. See TagSubscribe for more details.
Syntax

DspInfoField(hInfo, sTag, sField [, sClusterName] ) hInfo:


The object information block handle, as returned by DspInfoNew(). This handle identifies the table (or block) where data on the object is stored. Set this handle to 0 (zero) if you do not require realtime data.

sTag:
The name of the variable tag. The name of the tag can be prefixed by the name of the cluster that is "ClusterName.Tag". This argument does not support arrays. If array syntax is used, the information will be retrieved for only the tag name.

sField:
The name of the field from which to extract the data:

Cluster - Name of the cluster in which the Tag resides Comment - Variable tag comment Eng_Full - Engineering Full Scale Eng_Zero - Engineering Zero Scale Eng_Units - Engineering Units Eng_Value - Scaled engineering value - Dynamic Field - Description FullName - Full name of the tag in the form cluster.tagname. Name - Variable Tag Name

402

Chapter 25: Display Functions

Type - Data Type Unit - I/O Device Name sClusterName:


Specifies the name of the cluster in which the Tag resides. This is optional if you have one cluster or are resolving the tag via the current cluster context. The argument is enclosed in quotation marks "".

Return Value

The data (as a string).


Related Functions

DspInfo, DspInfoNew, DspInfoDestroy, SubscriptionGetAttribute, SubscriptionAddCallback, TagSubscribe


Example
! Get the I/O device that Variable Tag "PV123" belongs to. IODev=DspInfoField(0,"PV123","Unit"); ! Get the real-time engineering value of a tag. hInfo=DspInfoNew(20); sTag=DspInfo(hInfo,3,0); EngValue=DspInfoField(hInfo,sTag,"Eng_Value");

See Also Display Functions

DspInfoNew
Creates an object information block. Use this function with the associated low-level animation information functions to get and process object information on an AN. Note: When you have finished with the object information block, you need to destroy it with the DspInfoDestroy() function. There are limited number of info 383 blocks that can be allocated, if they are not freed properly DspInfoNew will return -1. If you need simple animation help, use the InfoForm() or the InfoFormAn() functions.
Syntax

DspInfoNew(nAN) nAN:
The AN for which object information is provided.

Return Value

403

Chapter 25: Display Functions

The object information block handle. If no object data is available, then -1 is returned.
Related Functions

DspInfo, DspInfoField, DspInfoDestroy, InfoForm, InfoFormAn


Example
/*This example creates a form, with the title "Tag Info" and a size of 25 x 5 characters. It creates an information block for the AN closest to the mouse cursor and then extracts the name, I/O device, and engineering value for the first tag in the object expression.*/ INT hInfo; STRING sTag; hInfo=DspInfoNew(DspGetNearestAN()); IF hInfo>-1 THEN FormNew("Tag Info",25,5,2); sTag=DspInfo(hInfo,3,0); FormPrompt(0,0,sTag); FormPrompt(0,16,DspInfoField(hInfo,sTag,"Unit")); FormPrompt(0,32,DspInfoField(hInfo,sTag,"Eng_Value")); FormRead(0); DspInfoDestroy(hInfo); END

See Also Display Functions

DspInfoValid
Checks if an object information block handle is valid. An object information block handle becomes invalid after it is destroyed, or if the user closes the page it is associated with. Use this function if background Cicode is using the object information block, and the operator closes the page.
Syntax

DspInfoValid(hInfo) hInfo:
The object information block handle, as returned by DspInfoNew(). This handle identifies the table (or block) where all object data is stored.

Return Value

1 if the information block handle is valid, otherwise 0 (zero).


Related Functions

DspInfoNew, DspInfoField, DspInfoDestroy

404

Chapter 25: Display Functions

Example
IF DspInfoValid(hInfo) THEN EngValue=DspInfoField(hInfo,sTag,"Eng_Value"); END

See Also Display Functions

DspIsButtonGray
Gets the current status of a button. Note: This function is only used for V3.xx and V4.xx animations, and has been superseded.
Syntax

DspIsButtonGray(nAN) nAN:
The AN for which object information is provided.

Return Value

The current mode of the button:


l l

0 - The button is active (not grayed). 1 - (SUNK_GRAY) The button is inactive (the text or symbol on the button is recessed). 2 - (PART_GRAY) This mode is now obsolete. The button will be inactive even if part_gray is returned. 3 - (ALL_GRAY) The button is inactive (the entire button is masked).

Related Functions

DspButton, DspButtonFn, DspGrayButton


Example
! Check the status of the button at AN21 status = DspIsButtonGray(21);

See Also Display Functions

405

Chapter 25: Display Functions

DspKernel
Displays the Kernel window and prompts the user to login as the 'kernel' user. A corresponding 'kernel' user must have already been defined in the project. Kernel access should be restricted to authorised personnel only as once they are in the Kernel, they can execute any Cicode function without further privilege restrictions and therefore have total control of CitectSCADA (and subsequently the plant and equipment). Please be aware that you can also open the Kernel by setting the Citect [Debug]Menu parameter to 1 and, when your system is running, selecting Kernel from the control-menu box. Note: You should be experienced with CitectSCADA and Cicode before attempting to use the Kernel as these facilities are powerful, and if used incorrectly, can corrupt your system.

Note: You should only use the Kernel for diagnostics and debugging purposes, and not for normal CitectSCADA operation. Kernel access should be restricted to authorised personnel only as once they are in the Kernel, they can execute any Cicode function without further privilege restrictions and therefore have total control of CitectSCADA (and subsequently the plant and equipment).

UNINTENDED EQUIPMENT OPERATION


l

l l

Do not use the kernel for normal CitectSCADA operation. The kernel is only for diagnostics and debugging purposes. Configure your security so that only approved personnel can view or use the kernel. Do not view or use the kernel unless you are an expert user of CitectSCADA and Cicode, or are under the direct guidance of Schneider Electric (Australia) Pty. Ltd. Support.

Failure to follow these instructions can result in death, serious injury, or equipment damage.

Syntax

DspKernel(nMode) nMode:
The display mode of Kernel:

1 - Display the Kernel. If the Kernel is already displayed and nMode=1, the keyboard focus is changed to the Kernel. 0 - Hide the Kernel
Return Value 406

Chapter 25: Display Functions

0 (zero) if successful, otherwise an error is returned.


Related Functions

KerCmd, TraceMsg
Example
DspKernel(1); !Display the Citect Kernel window

See Also Display Functions

DspMarkerMove
Moves a trend or chart marker to a specified position.
Syntax

DspMarkerMove(nAN, hMarker, Offset) nAN:


The AN where the trend or chart is positioned.

hMarker:
The marker handle, as returned from the DspMarkerNew() function. The marker handle identifies the table where all data on the associated marker is stored.

Offset:
The offset by which to move the marker. Vertical markers have an offset from 0 (zero) to the maximum number of samples in the trend. Horizontal markers have a offset of 0 (zero) to 32000.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspMarkerNew, OnEvent
Example

See DspMarkerNew See Also Display Functions

DspMarkerNew

407

Chapter 25: Display Functions

Creates a new trend marker. A trend marker is used to show cursor values or limits on a trend. You can use up to 10 markers on a single trend or chart. If you add markers to a trend or chart that CitectSCADA is animating, you need to repaint them using the trend paint event (OnEvent(Window,22)). (Otherwise CitectSCADA will delete any markers displayed when the trend is updated.)
Syntax

DspMarkerNew(nAN, Mode, Color) nAN:


The animation-point number.

Mode:
The mode of the marker:

0 - A vertical marker 1 - A horizontal marker Color:


The color of the marker (flashing color not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB color using the function MakeCitectColour.

Return Value

The marker handle, or -1 if the function is unsuccessful. The marker handle identifies the table where data on the associated marker is stored.
Related Functions

DspMarkerMove, OnEvent
Example
INT offset; ! offset of marker INT hMarker; ! marker handle hMarker = DspMarkerNew(40, 0, WHITE); ! create a new marker, vertical WHITE offset = 100; DspMarkerMove(40, hMarker, offset); ! Moves marker to offset 100 OnEvent(22, MyTrendPaint); ! set trend paint event, needs to stop event when change pages ! this function is called when CitectSCADA updates the trend INT FUNCTION MyTrendPaint() DspMarkerMove(40, hMarker, offset); RETURN 0;

408

Chapter 25: Display Functions

END

See Also Display Functions

DspMCI
Controls a multimedia device. The Media Control Interface (MCI) is a high-level command interface to multimedia devices and resource files. MCI provides applications with device-independent capabilities for controlling audio and visual peripherals (for example, for playing multimedia devices and recording multimedia resource files). Using this function, you can control multimedia devices by using simple commands like open, play, and close. MCI commands are a generic interface to multimedia devices. You can control any supported multimedia device, including audio playback and recording. For a full overview of MCI, see the Windows Multimedia Programmer's Guide.
Syntax

DspMCI(sCommand) sCommand:
The MCI command. See the Microsoft Windows Multimedia Programmer's Guide for details.

Return Value

A string message with the status of the MCI command.


Related Functions

DspPlaySound
Example
DspMCI("open cdaudio") DspMCI("set cdaudio time format tmsf") DspMCI("play cdaudio from 6 to 7") DspMCI("close cdaudio") /*Plays track 6 of an audio CD*/ DspMCI("open c:\mmdata\purplefi.wav type waveaudio alias finch") DspMCI("set finch time format samples") DspMCI("play finch from 1 to 10000") DspMCI("close finch") /*Plays the first 10,000 samples of a waveform audio file*/

See Also Display Functions

DspPlaySound
409

Chapter 25: Display Functions

Plays a waveform (sound). Wave form sound files *.WAV are provided with Windows and by third-party developers, or you can record them yourself to play long (and complex) sound sequences. This function searches the [Sounds] section of the WIN.INI file for an entry with the specified name, and plays the associated waveform. If the name does not match an entry in the WIN.INI file, a waveform filename is assumed. The function will then search the following directories for the waveform file (directories are listed in search order): 1. The current directory 2. The Windows directory 3. The Windows system directory 4. The directories listed in the PATH environment variable 5. The list of directories mapped in the network. If the file is not in one of the aforementioned directories, you need to include the full path to the sound file. If the file doesnt exist in one of the above directories or at a location specified with a full path, the sound will not be played.
Syntax

DspPlaySound(sSoundname, nMode) sSoundname:


The waveform to be played. Predefined sounds (in the WIN.INI file) are:
l l l l l l l

SystemAsterisk SystemExclamation SystemQuestion SystemDefault SystemHand SystemExit SystemStart

nMode:
Not used. Needs to be 0 (zero).

Return Value

TRUE if successful, otherwise FALSE (if an error is detected).


Related Functions

Beep
Example

410

Chapter 25: Display Functions

DspPlaySound("C:\WINNT\MEDIA\Notify.wav",0); DspPlaySound("SystemStart",0);

See Also Display Functions

DspPopupConfigMenu
Displays the contents of a menu node as a pop-up (context) menu, and run the command associated with the selected menu item. You can specify the contents of a menu using the menu configuration dialog at design time, or using the Menu family of Cicode functions at runtime.
Syntax

DspPopupConfigMenu(hParent, [, bNonRecursive [, XPos [, YPos]]]) hParent


The parent node of the menu tree returned from any of the following functions:
l

MenuGetGenericNode(), MenuGetPageNode() or MenuGetWindowNode() - used to get the parent node of menu tree for a page. MenuGetFirstChild(), MenuGetNextChild(), MenuGetPrevChild(), MenuGetParent() used to traverse to other nodes in a menu tree

bNonRecursive
Whether not to recursively transverse child tree nodes and list them as sub-menus in the pop-up menu. This parameter is optional. If it is left unspecified, its value will be defaulted to 0 (recursive). When it is set to 1, only the immediate child nodes of the specified menu handle will be listed. In this mode, tree nodes will be listed as normal menu items (instead of submenus) in the pop-up menu.

XPos
The x-coordinate (relative to the page) at which the menu will be displayed.This parameter is optional. If it is left unspecified, the menu will display at the cursor's current position.

YPos
The y-coordinate (relative to the page) at which the menu will be displayed.This parameter is optional. If it is left unspecified, the menu will display at the cursor's current position.

Return Value

0 if the selected meun command is run or error code if menu command cannot run.
Related Functions

Display Functions

411

Chapter 25: Display Functions

DspPopupMenu
Creates a popup menu consisting of a number of menu items. Multiple calls to this function enable you to add new items and create sub menus, building a system of linked, Windows-style menus. Menu items can be displayed as checked and/or disabled. You can also specify a bitmap to display as a menu icon. This function is first called to build the menu's items and links, and then called again to display it on the screen. In this final call, you have the option to specify the coordinates at which the menu will display, or let it default to the current cursor position.
Syntax

DspPopupMenu(iMenuNumber, sMenuItems [, XPos] [, YPos] ) iMenuNumber:


An integer representing the menu you are adding items to. The first menu created is Menu 0. If left unspecified, this parameter defaults to -1, causing the menu to be displayed on the screen. Multiple function calls with the same iMenuNumber allow you to build up entries in a particular menu. For example, the following four function calls with iMenuNumber = 1 build up 8 entries in Menu 1:
l l l l

DspPopupMenu(1, "Selection A>2, Selection B>3"); DspPopupMenu(1, "Selection C>2, Selection D"); DspPopupMenu(1, "Selection E>2, Selection F>3"); DspPopupMenu(1, "Selection G>2, Selection H");

sMenuItems:
A comma-separated string defining the items in each menu. The default value for this parameter is an empty string, which will get passed to the function in the call to display the menu. The (!), (~), and (,) symbols control display options for menu items. For example, !Item1 disables Item1; ~Item2 checks Item2; and ,Item3 inserts a separator above Item3. To insert a link from a menu item to a sub menu, use the (>) symbol. For example, : Item4>1 means Item4 links to menu 1. To insert a bitmap to the left of a menu item as its icon, use the following notation: [Icon]Item5 Inserts the bitmap Icon.BMP to the left of Item5. [Icon] needs to be placed before the Item name, but after any disable (!) or check (~) symbols you may wish to specify. Bitmap files used for menu icons need to be saved in the project directory so that they can be found by CitectSCADA.

XPos:

412

Chapter 25: Display Functions

The x-coordinate (relative to the page) at which the menu will be displayed. This parameter is optional. If it is left unspecified, the menu will display at the cursor's current position.

YPos:
The y-coordinate (relative to the page) at which the menu will be displayed. This parameter is optional. If it is left unspecified, the menu will display at the cursor's current position.

Return Value

The selected menu item as an integer. This comprises the menu number (return value div 100), and the position of the item in the menu (return value mod 100). For example, a return value of 201 indicates that the first item in Menu 2 was selected, and a return value of 3 indicates that the third item in Menu 0 was selected. The return value is limited to a maximum of 65535, that is 655 menus and 35 items on the menu. Above this limit the function returns 0. Note: Links to sub menus are not counted as menu items. For example, if your menu consists of 10 links and one unlinked item, the function will return only when the unlinked item is selected.
Example1
!Example 1 illustrates one menu with three menu items. FUNCTION BuildPopupMenus() INT iSelection; DspPopupMenu(0, "Item 1,!Item 2,~Item 3"); iSelection = DspPopupMenu(-1, "", 150, 300); ! The above builds a menu with three items: ! 'Item 1' will be shown as normal, 'Item 2' will be shown as disabled, ! and 'Item 3' will be shown as checked. ! The menu will be displayed at position (150, 300). END

Example 2
!Example 2 illustrates the creation of two menus which are linked. FUNCTION BuildLinkedPopupMenus() INT iSelection; DspPopupMenu(0, "Item A,Item B>1,Item C"); DspPopupMenu(1, "Item B1,,[Trend]Item B2,,Item B3"); iSelection = DspPopupMenu(); ! The above will build two menus - Menu 0 and Menu 1 ! Item B on Menu 0 links to Menu 1. ! 'Item B2' will be shown with Trend.BMP at its left. ! The menu will be displayed at the cursor's position. ! If 'Item A' is selected, iSelection will equal 1 ! If 'Item C' is selected, iSelection will equal 2 ! If 'Item B1' is selected, iSelection will equal 101

413

Chapter 25: Display Functions

! If 'Item B2' is selected, iSelection will equal 102 ! If 'Item B3' is selected, iSelection will equal 103 END

See Also Display Functions

DspRichText
Creates a Rich Text object of the given dimensions at the animation point nAN. This object can then be used to display an RTF file (like an RTF report) called using the DspRichTextLoad function.
Syntax

DspRichText(nAN, iHeight, iWidth, nMode) nAN:


The AN at which the rich text object will display when the DspRichText command is run.

iHeight:
The height of the rich text object in pixels. The height is established by measuring down from the animation point.

iWidth:
The width of the rich text object in pixels. The width is established by measuring across to the right from the animation point.

nMode:
The display mode for the rich text object. The mode can be any combination of:

0 - Disabled - should be used if the rich text object is to be used for display purposes only. 1 - Enabled - allows you to select and copy the contents of the RTF object (for instance an RTF report), but you will not be able to make changes. 2 - Read/Write - allows you to edit the contents of the RTF object. Remember, however, that the object needs to be enabled before it can be edited. If it has already been enabled, you can just enter Mode 2 as your argument. If it is not already enabled, you will need to enable it. By combining Mode 1 and Mode 2 in your argument (3), you can enable the object, and make it read/write at the same time.
Because the content of the rich text object is just a copy of the original file, changes will not affect the actual file, until saved using the DspRichTextSave function.

Return Value

414

Chapter 25: Display Functions

0 if successful, otherwise an error is returned.


Related Functions

DspRichTextLoad, PageRichTextFile
Example
//This will produce a rich text object at animation point 57, which is 200 pixels high, and 200 pixels wide. This object will be for display purposes only (that is read only)// DspRichText(57,200,200,0);

See Also Display Functions

DspRichTextEdit
Enables editing of the contents of the rich text object at nAN if nEdit = TRUE, and disables editing if nEdit = FALSE.
Syntax

DspRichTextEdit(nAN, bEdit) nAN:


The reference AN for the rich text object.

bEdit:
The value of this argument determines whether you will be able to edit the contents of the rich text object at AN. Enter TRUE to enable editing, or enter FALSE to make the contents read-only. Changes made to the contents of the object will not be saved until the DspRichTextSave function is used.

Return Value

0 if successful, otherwise an error is returned.


Related Functions

PageRichTextFile, DspRichTextEnable, DspRichTextSave


Example
// Enables editing of the rich text object at AN 25 - if one exists. Otherwise an error will be returned to iResult // iResult = DspRichTextEdit(25,TRUE);

415

Chapter 25: Display Functions

See Also Display Functions

DspRichTextEnable
Enables the rich text object at nAN if nEnable = TRUE, and disables the object if nEnable = FALSE. When the object is disabled, its contents cannot be selected or copied etc.
Syntax

DspRichTextEnable(nAN, bEnable) nAN:


The reference AN for the rich text object.

bEnable:
The value of this argument determines whether the rich text object at AN will be enabled or disabled. Enter TRUE to enable the object (that is you can select and copy the contents of the RTF object, but you can't make changes). Enter FALSE to disable the object (that is make it display only).

Return Value

0 if successful, otherwise an error is returned.


Related Functions

DspRichTextEdit
Example
// This line disables the rich text object at AN 25 - if one exists. Otherwise an error will be returned to iResult // iResult = DspRichTextEnable(25,FALSE);

See Also Display Functions

DspRichTextGetInfo
Retrieves size information about the rich text object at animation point nAN.
Syntax

DspRichTextGetInfo(nAN, iType) nAN:


The reference AN for the rich text object.

iType:

416

Chapter 25: Display Functions

The following size information (in pixels) can be returned about the specified rich text object:

0 - Height 1 - Width
Return Value

The requested information as a string (units = pixels).


Related Functions

PageRichTextFile
Example
! Gets the height of the rich text object at AN 25 - if one exists. iHeight = DspRichTextGetInfo(25,0); ! Gets the width of the rich text object at AN 423. iWidth = DspRichTextGetInfo(423,1);

See Also Display Functions

DspRichTextLoad
Loads a copy of the file Filename into the rich text object) at animation point nAN. (The rich text object may have been created using either the DspRichTextLoad function or the PageRichTextFile function.)
Syntax

DspRichTextLoad(nAN, sFilename) nAN:


The animation point at which a copy of the rich text file (for example, an RTF report) will display. This AN needs to match that of a rich text object (created using either the DspRichText function, or the PageRichTextFile function), or the copy of the file will not be loaded into anything, and will not display.

sFilename:
The name of the file to be copied and loaded into the rich text object at the specified animation point. The filename needs to be entered in quotation marks "". The maximum file size that can be loaded is 512kb.

417

Chapter 25: Display Functions

If you are loading a copy of an RTF report, the report needs to already have been run and saved to a file. Remember that the filename for the saved report comes from the File Name field in the Devices form. The location of the saved file needs to also be included as part of the filename. For example, if the filename in the Devices form listed [Data];RepDev.rtf, then you would need to enter "[Data]\repdev.rtf" as your argument. Alternatively, you can manually enter the path, for example, "c:\MyApplication\data\repdev.rtf". If you are keeping a number of history files for the report, instead of using the extension rtf, you need to change it to reflect the number of the desired history file, for example, 001.

Return Value

0 if successful, otherwise an error is returned.


Related Functions

DspRichText, PageRichTextFile
Example
// This will look in the [Data] path (as specified in the Citect.ini file), and load a copy of the file DayRep.rtf into the rich text object at animation point 57. // DspRichTextLoad(57,"[Data]\DayRep.rtf"); // This will look in the [Data] path (as specified in the Citect.ini file), and load a copy of the history file DayRep.003 into the rich text object at animation point 908. // DspRichTextLoad(908, "[Data]\DayRep.003"); // This will load a copy of the history file f:\MyApplication\data\DayRep.006, into the rich text object at animation point 908. // DspRichTextLoad(908, "f:\MyApplication\data\DayRep.006");

See Also Display Functions

DspRichTextPgScroll
Scrolls the contents of the rich text object displayed at nAN, by one page length in the direction given in direction.
Syntax

DspRichTextPgScroll(nAN, iDirection) nAN:


The reference AN for the rich text object.

iDirection:

418

Chapter 25: Display Functions

The direction in which you want to scroll each time this function is run. You can choose from the following:

1 - Left 2 - Right 3 - Up 4 - Down 8 - Scroll to top 16 - Scroll to bottom


Return Value

0 if successful, otherwise an error is returned.


Related Functions

PageRichTextFile, DspRichTextEdit, DspRichTextScroll


Example
// This line scrolls the contents of the rich text object at AN 25 down one page. Otherwise an error will be returned to iResult // iResult = DspRichTextPgScroll(25,4); // This line scrolls the contents of the rich text object at AN 423 right one page. Otherwise an error will be returned to iResult // iResult = DspRichTextPgScroll(423,2);

See Also Display Functions

DspRichTextPrint
Prints the contents of the rich text object at animation point nAN, to the port PortName.
Syntax

DspRichTextPrint(nAN, sPortName) nAN:


The reference AN for the rich text object.

sPortName:
The name of the printer port to which the contents of the rich text object will be printed. This name needs to be enclosed within quotation marks "". For example "LPT1", to print to the local printer, or "\\Pserver\canon1" using UNC to print to a network printer.

Return Value

0 if successful, otherwise an error is returned.

419

Chapter 25: Display Functions

Related Functions

DspRichText, FileRichTextPrint
Example
! This lines prints DspRichTextPrint(25,"LPT1:");

See Also Display Functions

DspRichTextSave
Saves the contents of the rich text object at animation point nAN, to the file Filename.
Syntax

DspRichTextSave(nAN, sFilename) nAN:


The reference AN for the rich text object.

sFilename:
The name under which the contents of the rich text object will be saved. This name needs to be enclosed within quotation marks "", and needs to include the destination path. For example "[Data] \saved.rtf".

Return Value

0 if successful, otherwise an error is returned.


Related Functions

DspRichText, PageRichTextFile, DspRichTextLoad, DspRichTextEdit


Example
// These lines show two different ways of saving the contents of the rich text object (at AN 25) to file DayRep.rtf// DspRichTextSave(25,"[Data]\DayRep.rtf"); DspRichTextSave(25,"c:\MyApplication\data\DayRep.rtf");

See Also Display Functions

DspRichTextScroll

420

Chapter 25: Display Functions

Scrolls the contents of the rich text object displayed at nAN, in the direction given in direction, by the number of lines/units given in amount. Remember that the height of a line varies according to the font used, therefore if you need to scroll absolute distances, it might be advisable to use the DspRichTextPgScroll function.
Syntax

DspRichTextScroll(nAN, iDirection, iAmount) nAN:


The reference AN for the rich text object.

iDirection:
The direction in which you want to scroll each time this function is run. You can choose from the following:

1 - Left 2 - Right 3 - Up 4 - Down 8 - Scroll to top 16 - Scroll to bottom iAmount:


The amount by which you would like to scroll each time this function is run. Enter the number of lines (for a vertical direction) or units (for a horizontal direction) by which you would like to scroll.

Return Value

0 if successful, otherwise an error is returned.


Related Functions

PageRichTextFile, DspRichTextEdit, DspRichTextPgScroll


Example
DspRichTextScroll(25,4,8); DspRichTextScroll(423,2,1);

See Also Display Functions

DspRubEnd

421

Chapter 25: Display Functions

Ends the rubber band selection, and returns the coordinates of the rubber band selection. The meaning of the cx and cy values depend on the nMode you specify in the DspRubStart() function.
Syntax

DspRubEnd(x, y, cx, cy) x,y:


The x and y coordinates of the start position.

cx,cy:
The x and y coordinates of the end position.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspRubStart, DspRubMove, DspRubSetClip


Example

See DspRubStart See Also Display Functions

DspRubMove
Moves the rubber band selection to the new position. You need to first have defined a rubber band selection using the DspRubStart() and DspRubEnd() functions. This function will erase the existing rubber band and then redraw it in the new position. You would normally move the rubber band by mouse input, but you can get input from the keyboard or any other Cicode to control the rubber band.
Syntax

DspRubMove(x, y) x,y:
The x and y coordinates of the current position.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

422

Chapter 25: Display Functions

DspRubStart, DspRubEnd, DspRubSetClip


Example

See DspRubStart See Also Display Functions

DspRubSetClip
Sets the clipping region for the rubber band display. If you enable the clipping region, the rubber band will not move outside of the clip region. This allows you to restrict the rubber band to within some constrained region. (For example, to prevent an operator from dragging the rubber band outside of the trend display when zooming the trend.) you need to call this function (to enable the clipping region) before you can start the rubber band selection (with the DspRubStart() function).
Syntax

DspRubSetClip(x1, y1, x2, y2) x1,y1,x2,y2:


The x and y coordinates of the clipping region.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspRubStart, DspRubEnd, DspRubMove


Example
// Set the clipping region to a rectangle starting at 100, 100 to 200, 300 DspRubSetClip(100, 100, 200, 300); // Start the rubber band display with clipping mode on DspRubStart(x, y, 4);

See Also Display Functions

DspRubStart

423

Chapter 25: Display Functions

Starts the rubber band selection. Call this function when the left mouse button is pressed - the rubber band is displayed at the starting position. Call the DspRubEnd() function to end the selection, when the mouse button is released. The DspRubMove() function moves the selection to the new position. This function is used by the trend templates for the trend zoom function. Use the rubber band functions whenever you want the operator to select a region on the screen or display a dynamic rectangle on the screen. You can only display one rubber band per page. If you display a second rubber band, the first rubber band is erased. To move a rubber band with the mouse, use the OnEvent () function to get notification of the mouse movement, and then the DspRubMove() function. Because these are generic rubber-band display functions, you can get input from the keyboard, Cicode variables, the I/O device, and the mouse.
Syntax

DspRubStart(x, y, nMode) x,y:


The x and y coordinates of the current position.

nMode:
The mode of the rubber banding operation:

0 - cx,cy as absolute pixel positions 1 - cx,cy in pixels relative to x,y 2 - (x,y) the distance from top left to (cx,cy) 4 - enable the rubber band selection using the clipping region defined by DspRubSetClip().
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspRubEnd, DspRubMove, DspRubSetClip, OnEvent


Example

See also the ZOOM.CI file in the Include project for details.
INT xRub,yRub,cxRub,cyRub; /* Call this function on left mouse button down. */ FUNCTION StartSelection() INT x,y;

424

Chapter 25: Display Functions

DspGetMouse(x,y); ! Get the current mouse position DspRubStart(x,y,0); ! Start the rubber banding OnEvent(0,MouseEvent); ! Attach mouse move event END /* Call this function on left mouse button up. */ FUNCTION EndSelection() ! Stop the rubber banding and get sizes into the ..Rub variables DspRubEnd(xRub,yRub,cxRub,cyRub); OnEvent(0,0); ! Stop mouse move event END INT FUNCTION MouseEvent() INT x,y; DspGetMouse(x,y); ! Get mouse position DspRubMove(x,y); ! Move the rubber band RETURN 0 END

See Also Display Functions

DspSetSlider
Sets the current position of a slider at the specified AN. You can use this function to move a slider, and adjust the value of the variable associated with the slider. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspSetSlider(nAN, nPos) nAN:


The animation-point number.

nPos:
The position of the slider from 0 to 32000 where 0 is the zero position of the slider and 32000 if full position of the slider.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspGetSlider

425

Chapter 25: Display Functions

Example
// Set the position of the slider at AN 30 to 1/2 scale DspSetSlider(30, 16000);

See Also Display Functions

DspSetTip
Sets tool tip text associated with an AN. Any existing text associated with the AN will be replaced with the new text.
Syntax

DspSetTip(nAN, sText) nAN:


The animation-point number.

sText:
The tool tip text to set for the AN.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspGetTip, DspTipMode
Example
!Set a tool tip for AN19 DspSetTip(19, "Start Slurry Pump");

See Also Display Functions

DspSetTooltipFont
Sets the font for tool tip text. The parameter [Animator]TooltipFont also specifies the tool tip font. The parameter is checked at startup, and if it is set, the font is set accordingly. You can then use DspSetTooltipFont() to override the parameter until the next time you start CitectSCADA.
Syntax

426

Chapter 25: Display Functions

DspSetTooltipFont(sName [, nPointSize] [, sAttribs] ) sName:


The name of the Windows font to be used, enclosed by quotation marks " ". A value for this parameter is required, however specifying an empty string "" will set the tooltip font to the default of MS Sans Serif.

nPointSize:
The size of the font in points. If you do not specify a value, the point size defaults to 12.

sAttribs:
A string specifying the format of the font. Use one or all of the following, enclosed by quotation marks " ":
l l l

B to specify Bold I to specify Italics U to specify Underline

If you don't specify a value for this parameter, it will default to an empty string and no formatting will be applied.

Return Value

No return value.
Related Functions

DspGetTip, DspTipMode
Example
!Set the tool tip font to Bold, Italic, Times New Roman, with a point size of 12 DspSetTooltipFont("Times New Roman", 12, "BI");

See Also Display Functions

DspStatus
Determines whether the object at the specified AN will be grayed (hatch pattern) in the event communication attempts are unsuccessful.
Syntax

DspStatus(nAN, nMode) nAN:


The animation-point number.

427

Chapter 25: Display Functions

nMode:
0 - Normal display when communication attempts are unsuccessful 1 - Gray the object (with a hatch pattern) when communication attempts are unsuccessful

Return Value

0 (zero) if successful, otherwise an error is returned.


Example
DspStatus(67, 1) // Disable the animation at AN 67

See Also Display Functions

DspStr
Displays a string at a specified AN. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspStr(nAN, sFont, sText [, iLength] [, iAlignMode] [, iLengthMode]) AN:


The AN where the text will be displayed.

sFont:
The name of the font that is used to display the text. The Font Name needs to be defined in the Fonts database. If the font is not found, the default font is used.

sText:
The text to display.

iLength:
Length of the Text to display, either in characters or pixels depending on Mode (default -1, no truncation)

iAlignMode:
The alignment of the text string:

0 - Left Justified (default)

428

Chapter 25: Display Functions

1 - Right Justified. 2 - Center Justified. iLengthMode:


The length mode of the text string:

0 - Length as pixels truncated (default) 1 - Length as pixels truncated with ellipsis 2 - Length interpreted as characters.
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspText
Example
DspStr(25,"RedFont","Display this text"); /* Displays "Display this text" using "RedFont" at AN25. "RedFont" needs to be defined in the Fonts database. */

See Also Display Functions

DspSym
Note: This function is only used for V3.xx and V4.xx animations. In later releases this function is redundant. The same functionality can be achieved using objects. Displays a symbol at a specified AN. If the symbol number is 0, any existing symbol (at the AN) is erased.
Syntax

DspSym(nAN, Symbol [, Mode] ) nAN:


The AN where the symbol will be displayed.

Symbol:
The name of the symbol to display in the format <[LibName.]SymName>. If you do not specify the library name, a symbol from the Global library will display (if it exists).

Mode:

429

Chapter 25: Display Functions

Not used. The mode is always set to 1, which means do not erase the existing symbol, just draw the new symbol.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDel
Example
! Display the centrifuge symbol (from the pumps library) at AN25. DspSym(25,"Pumps.Centrifuge"); ! Display the centrifuge symbol (from the global library) at AN26. DspSym(26,"Centrifuge");

See Also Display Functions

DspSymAnm
Animates a series of symbols at an AN. Sym1 displays first, then Sym2, Sym3 . . . Sym8 and then Sym1 displays again, etc. When the next symbol in the sequence is displayed, the current symbol is not erased, but is overwritten to provide a smoother animation. The symbols should all be the same size. The frequency of changing the symbols is determined by the [Page]AnmDelay parameter. You only need to call this function once to keep the animation going. To stop the animation call the DspDel() function, or call this function again with different symbols (to change the animation). Note: This function is only used for V3.xx and V4.xx animations. In later releases this function is redundant. The same functionality can be achieved using objects.
Syntax

DspSymAnm(nAN, Sym1 [, Sym2 ... Sym8] [, iDisplayMode] [, sSym9] ) nAN:


The AN where the animation will occur.

Sym1:
The name of the first symbol to animate in the format <[LibName.]SymName>. If you do not specify the library name, a symbol from the Global library will display (if it exists). Sym1 needs to be specified.

430

Chapter 25: Display Functions

Sym2..Sym8:
The names of the symbols to animate in frames 2 to 8 in the format <[LibName.]SymName>. If you do not specify the library name, a symbol from the Global library will display (if it exists).

iDisplayMode:
Not used. Always set to -1, which means Soft animation . The background screen (a rectangular region beneath the symbol) is restored with the original image. Any objects that are within the rectangular region are destroyed when the background is restored. Use this mode when each animation symbol is a different size.

Sym9:
Not all symbols have to be specified. If for example, only two symbols are to display, specify Sym1 and Sym2.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspSym
Example
DspSymAnm(25,"Pumps.Centrifuge","Pumps.Floatation"); ! Alternately displays the centrifuge symbol and the flotation symbol (from the pumps library) at AN25.

See Also Display Functions

DspSymAnmEx
Animates a series of symbols at an AN. Sym1 displays first, then Sym2, Sym3 . . . Sym9 and then Sym1 displays again, etc. When the next symbol in the sequence is displayed, the current symbol is not erased, but is overwritten to provide a smoother animation. The symbols should all be the same size. The frequency of changing the symbols is determined by the [Page]AnmDelay parameter. You only need to call this function once to keep the animation going. To stop the animation call this function again with a different Mode. Note: This function is only used for V3.xx and V4.xx animations. In later releases this function is redundant. The same functionality can be achieved using objects.
Syntax 431

Chapter 25: Display Functions

DspSymAnmEx(nAN, Mode, Sym1 [, Sym2 ... Sym9] ) nAN:


The AN where the animation will occur.

Mode:
Not used. Always set to -1, which means Soft animation . The background screen (a rectangular region beneath the symbol) is restored with the original image. Any objects that are within the rectangular region are destroyed when the background is restored. Use this mode when each animation symbol is a different size.

Sym1:
The name of the first symbol to animate in the format <[LibName.]SymName>. If you do not specify the library name, a symbol from the Global library will display (if it exists). Sym1 needs to be specified.

Sym2..Sym9:
The names of the symbols to animate in frames 2 to 9 in the format <[LibName.]SymName>. If you do not specify the library name, a symbol from the Global library will display (if it exists). Not all symbols have to be specified. If for example, only two symbols are to display, specify Sym1 and Sym2.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspSym
Example
DspSymAnmEx(25,-1,"Pumps.Centrifuge","Pumps.Floatation"); ! Alternately displays the centrifuge symbol and the flotation symbol (from the pumps library) at AN25.

See Also Display Functions

DspSymAtSize
Displays a symbol at the specified scale and offset from the AN position. By calling this function continuously, you can move symbols around the screen and change their size and shape, to simulate trippers, elevators, and so on. You change the PositionX, PositionY values to change the position of the symbol, the SizeX, SizeY values to change its size, or the symbol itself to change its shape.

432

Chapter 25: Display Functions

You can only use this function at a blank AN, or an AN with a symbol defined without symbols configured. The AN needs to not be attached to any other animation object. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspSymAtSize(nAN, sSym, PositionX, PositionY, SizeX, SizeY, Mode) nAN:


The AN where the symbol will be animated.

sSym:
The name of the symbol to display, move, or size. If sSym is 0 (zero), any existing symbol at the AN is erased.

PositionX:
The horizontal offset position (from the AN) of the symbol (in pixels).

PositionY:
The vertical offset position (from the AN) of the symbol (in pixels).

SizeX, SizeY:
The horizontal and vertical scaling factors for the symbol (0 - 32000). For example, if PositionX and PositionY are both 32000, the symbol is displayed at its normal size. Please be aware that symbols can only be reduced in size.

Mode:
The mode of the display:

-1 - Soft animation. The background screen (a rectangular region beneath the symbol) is restored with the original image. Any objects that are within the rectangular region are destroyed when the background is restored. Use this mode when each animation symbol is a different size. 0 - Overlap animation. The background screen (beneath the symbol) is not erased - the next symbol is displayed on top. Transparent color is supported in this mode, allowing for symbol overlap. For this mode to display correctly, each symbol needs to be the same size. 1 - Animate animation. The background screen (beneath the symbol) is not erased - the next symbol is displayed on top. This mode provides the fastest animation. For this mode to display correctly, each symbol needs to be the same size. Transparent color is not supported in this mode.

433

Chapter 25: Display Functions

8 - Stops animation at last symbol displayed. Use this mode where you want to freeze your animation at the end of the sequence. 16 - Stops animation at current symbol displayed. Use this mode where you want to freeze your animation instantly.
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspAnMove, DspAnMoveRel, DspSym


Example
! Display tripper moving in x axis at normal size. DspSymAtSize(21, "lib.tripper", x, 0, 32000, 32000, 0); ! Display elevator going up and down. DspSymAtSize(22, "lib.elevator", 0, y, 32000, 32000, 0); ! Display can getting bigger and smaller. DspSymAtSize(23, "lib.can", 0, 0, size, size, 0);

See Also Display Functions

DspText
Displays text at a specified AN location. This function does the same operation as DspStr(), however it uses a font number rather than a font name. Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.
Syntax

DspText(hAN, iFont, sText [, iLength] [, iAlignMode] [, iLengthMode]) hAN:


The AN where the text will be displayed.

iFont:
The font number that is used to display the text. (To use the default font, set to -1.)

sText:
The text to display.

iLength:

434

Chapter 25: Display Functions

Length of the Text to display, either in characters or pixels depending on Mode (default -1, no truncation)

iAlignMode:
The alignment of the text string:

0 - Left Justified (default) 1 - Right Justified. 2 - Center Justified. iLengthMode:


The length mode of the text string:

0 - Length as pixels truncated (default) 1 - Length as pixels truncated with ellipsis 2 - Length interpreted as characters.
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspStr, DspFont, DspFontHnd


Example
/* Displays "Display this text" at AN25 using the font defined as BigFont. */ hBigFont=DspFontHnd("BigFont"); DspText(25,hBigFont,"Display this text");

See Also Display Functions

DspTipMode
Switches the display of tool tips on or off. This function overrides the setting in the [Page]TipHelp parameter.
Syntax

DspTipMode(nMode) nMode:
The display mode:

0 - Off 1 - On 2 - Toggle the tool tip mode

435

Chapter 25: Display Functions

3 - Do not change the mode, just return the current value


Return Value

The old mode.


Related Functions

DspSetTip, DspGetTip
Example
DspTipMode(1); //Switch on tool tips

See Also Display Functions

DspTrend
Displays a trend at an AN. Values are plotted on the trend pens. You need to specify Value1, but Value2 to Value8 are optional. If more values (than configured pens) are specified, the additional values are ignored. If fewer values (than configured pens) are specified, the pens that have no values are not displayed. DspTrend() is optimized so that it will not display the trend until a full set of samples has been collected. For example, if you have defined 100 samples for your trend, the trend will not display until value 100 is entered. You should use this function only if you want to control the display of trends directly. If you use the standard Trends (defined in the Trends database) this function is called automatically.
Note: This function is only used for V3.xx and V4.xx animations, and was superseded in later releases.

Syntax

DspTrend(nAN,Trend,Value1 [,Value2 ... Value8] ) nAN:


The AN where the trend will be displayed.

Trend:
The name of the trend to display in the format <[LibName.]TrnName>. If you do not specify the library name, a trend from the Global library will display (if it exists). To display a Version 1.xx trend, specify the trend number (0 to 255). For example, if you specify trend 1, CitectSCADA displays the trend Global.Trn001.

Value1:

436

Chapter 25: Display Functions

The value to display on Pen 1 of the trend.

Value2...8:
The values to display on Pen 2...Pen 8 of the trend (optional).

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DspDel
Example
/* Using the main_loop trend (from the trends library) at AN25, display a value of 10 on Pen1, 20 on Pen2, 30 on Pen3 and 40 on Pen4 of the trend. */ DspTrend(25,"Trends.Main_Loop",10,20,30,40); /* Using trend definition 5 (CitectSCADA Version 1.xx) at AN25, display a value of 10 on Pen1, 20 on Pen2, 30 on Pen3 and 40 on Pen4 of the trend. */ DspTrend(25,5,10,20,30,40); /* Using the loops trend (from the global library) at AN26, display a value of 100 on Pen1 and 500 on Pen2 of the trend. */ DspTrend(26,"Loops",100,500); /* Display a trend configured with 100 samples immediately. The data for the first 100 samples is stored in an array MyData[100]. On first display, grab all the data and call DspTrend().*/ FOR i = 0 to 100 DO DspTrend(AN, "Loops", MyData[i]); END // display new samples every 300ms WHILE TRUE DO // Shift MyData down and grab new sample TableShift(MyData, 100, 1); MyData[99] = MyFastData; DspTrend(AN, "Loops", MyData[99]); SleepMS(300); END /* Display a trend configured with 100 samples immediately. Dummy data is pushed into the first 100 samples to fill the trend. Once these values are entered, the trend will be updated each time a new sample value is entered.*/ // fill up the trend. FOR i = 0 to 100 DO DspTrend(AN, "Loops", 0); END // display new samples every 300ms WHILE TRUE DO DspTrend(AN, "Loops", MyFastData); SleepMS(300); END

437

Chapter 25: Display Functions

See Also Display Functions

DspTrendInfo
Get information on a trend definition.
Syntax

DspTrendInfo( hTrend, Type, AN) hTrend:


The name of the trend in the format <[LibName.]TrnName>. If you do not specify the library name, a trend from the Global library is assumed. To get information on a Version 1.xx trend, specify the trend number (0 to 255). For example, if you specify trend 1, CitectSCADA obtains information from the trend Global.Trn001.

nType:
Type of trend info:

0 - Type of trend: l 0 = line l 1 = bar 1 - Number of samples in trend 2 - Height of trend (in pixels) 3 - Width of trend sample (in pixels) 4 - Number of trend pens 11 - Color of pen 1. If the pen uses flashing color, the initial color used. (Use type 19 to determine the secondary flashing color for pen 1.) 12 - Color of pen 2. If the pen uses flashing color, the initial color used. (Use type 20 to determine the secondary flashing color for pen 2.) 13 - Color of pen 3. If the pen uses flashing color, the initial color used. (Use type 21 to determine the secondary flashing color for pen 3.) 14 - Color of pen 4. If the pen uses flashing color, the initial color used. (Use type 22 to determine the secondary flashing color for pen 4.) 15 - Color of pen 5. If the pen uses flashing color, the initial color used. (Use type 23 to determine the secondary flashing color for pen 5.) 16 - Color of pen 6. If the pen uses flashing color, the initial color used. (Use type 24 to determine the secondary flashing color for pen 6.)

438

Chapter 25: Display Functions

17 - Color of pen 7. If the pen uses flashing color, the initial color used. (Use type 25 to determine the secondary flashing color for pen 7.) 18 - Color of pen 8. If the pen uses flashing color, the initial color used. (Use type 26 to determine the secondary flashing color for pen 8.) 19 - The secondary color used for pen 1, if flashing color is used. 20 - The secondary color used for pen 2, if flashing color is used. 21 - The secondary color used for pen 3, if flashing color is used. 22 - The secondary color used for pen 4, if flashing color is used. 23 - The secondary color used for pen 5, if flashing color is used. 24 - The secondary color used for pen 6, if flashing color is used. 25 - The secondary color used for pen 7, if flashing color is used. 26 - The secondary color used for pen 8, if flashing color is used. nAN:
The AN where the trend is displayed.

Return Value

The trend information (as an integer). If Pen Color (Types 11 - 18) is requested from a bar trend, the return value is -1.
Related Functions

DspTrend
Example
! get the number of samples for the main_loop trend (from the trends library). nSamples = DspTrendInfo("Trends.Main_Loop", 1); ! get the number of samples for trend 3 (CitectSCADA Version 1.xx). nSamples = DspTrendInfo(3, 1);

See Also Display Functions

439

Chapter 25: Display Functions

440

Chapter 26: DLL Functions


Following are functions relating to DLLs:
DLLCall DLLCallEx DLLClose DLLOpen Calls a DLL function. Calls a DLL function, and passes the specified arguments to that function.

Closes a link to a DLL function.

Opens a link to a DLL function.

See Also Functions Reference

DLLCall
Calls a DLL function, and passes a string of arguments to that function. CitectSCADA converts these arguments (where required) into the type specified in the DLLOpen() call. If an argument cannot be converted, it is set to zero (0) or an empty string "". You need to first open the DLL with the DLLOpen() function. Only one call to the DLLCall() function can be made at a time, which means runtime will wait for the called function to return before doing anything else. If the called function takes too long to return, it won't let other tasks execute. Therefore, care needs to be taken so that one call returns before the next is made. Good programming practice requires that functions which are not expected to complete in a short time are run as separate Windows threads and return a value immediately to CitectSCADA.
Syntax

DLLCall(hFunction, sArgs) hFunction:


The DLL function handle, returned from DLLOpen().

sArgs:

441

Chapter 26: DLL Functions

The string of arguments to pass to the DLL function. The argument string contains all the arguments for the function, separated by commas (,). Enclose string arguments in quote marks "", and use the string escape character (^) to put a string delimiter within a string. This syntax is the same as the syntax for the TaskNew() function

Return Value

The result of the function, as a string.


Related Functions

DLLOpen, DLLClose
Example

See DLLOpen See Also DLL Functions

DLLCallEx
Calls a DLL function, and passes the specified arguments to that function. You need to first open the DLL with the DLLOpen function. Only one call to the DLLCallEx() function can be made at a time, which means runtime will wait for the called function to return before doing anything else. If the called function takes too long to return, it won't let other tasks execute. Therefore, care needs to be taken so that one call returns before the next is made. Good programming practice requires that functions which are not expected to complete in a short time are run as separate Windows threads and return a value immediately to CitectSCADA.
Syntax

DLLCallEx(hFunction,vParameters) hFunction:
The DLL function handle, returned from DLLOpen().

vParameters:
A variable length parameter list of method arguments. The parameters will be passed to the function in the order that you enter them. Specifying too few or too many parameters will generate an Invalid Argument hardware error. An Invalid Argument hardware error will also be generated if you specify a parameter to the DLL function with the wrong type.

Return Value

442

Chapter 26: DLL Functions

The result of the function. If the DLL function returns a string then your Cicode return variable should be of type STRING. All other types will be INT.
Related Functions

DLLOpen, DLLClose
Example
/* This function is called when CitectSCADA starts up, to initialize all the DLLs that are called */ INT hAnsiUpper; INT hGlobalAlloc; FUNCTION InitMyDLLs() ! Open DLL to AnsiUpper hAnsiUpper = DLLOpen("USER.DLL", "AnsiUpper", "CC"); hGlobalAlloc = DLLOpen("Kernel", "GlobalAlloc", "IIJ"); END /* This is the Cicode entry point into the DLL function call. This function hides the DLL interface from the rest of CitectSCADA. * STRING FUNCTION AnsiUpper(STRING sString) STRING sResult; sResult = DLLCallEx(hAnsiUpper, sString); RETURN sResult; END /* Allocate memory and return memory handle */ INT FUNCTION GlobalAlloc(INT Mode, INT Length) INT hMem; hMem = DLLCallEx(hGlobalAlloc, Mode, Length); RETURN hMem; END

See Also DLL Functions

DLLClose
Closes the link to a DLL function, and frees the memory allocated for that function link. When the link is closed, you cannot call the function. CitectSCADA automatically closes all function links at shutdown.
Syntax

DLLClose(hFunction) hFunction:
The DLL function handle, returned from DLLOpen().

Return Value

443

Chapter 26: DLL Functions

0 (zero) if successful, otherwise an error is returned.


Related Functions

DLLOpen, DLLCall
Example

See DLLOpen See Also DLL Functions

DLLOpen
Opens a link to a DLL function, by loading the specified DLL library into memory and attaching it to the named function. After you open the function link, you can call the function with the DLLCall() function. You pass the function number returned from the DLLOpen() function as an argument in the DLLCall() function. CitectSCADA only supports DLL functions that accept arguments via stack-based calling conventions. For example, in Win32 only cdecl and stdcall are supported. One accepted method for interfacing with a DLL function is to write a Cicode function file. This file contains the DLLOpen() function to initialize the functions, and one Cicode function for each DLL function, as an interface. In this way, you can hide the DLL interface in this file. Any other Cicode function will call the Cicode interface, and the call to the DLL remains transparent. Please be aware that DLLs need to be on the path. The file extension is not required. Note: You need to specify the arguments to the function correctly. CitectSCADA has no way of checking the number and type of arguments to the function. If you specify the number of arguments incorrectly, your computer may display unexpected behavior. You should test your interface thoroughly before using it on a live system.

UNINTENDED EQUIPMENT OPERATION Ensure that you specify the arguments to the DLLOpen() function correctly according to the following list. Failure to follow these instructions can result in death, serious injury, or equipment damage.

Syntax

DLLOpen(sLib, sName, sArgs)


444

Chapter 26: DLL Functions

sLib:
The DLL library name.

sName:
The function name. An underscore (_) is required in the function name for a 'C' function, but not for a Pascal function. When you call a DLL from a Cicode function, sName needs to be the same as the name defined in the .DEF file used to link the DLL. The file extension is not required.

sArgs:
The string specifying the function arguments. The first character in the string is the return value of the function.

A - Logical. B - IEEE 8 byte floating point number. C - Null terminated string. Maximum string length 255 characters. D - Byte counted string. First byte contains the length of the string, maximum string length 255 characters. H - Unsigned 2 byte integer. I - Signed 2 byte integer. J - Signed 4 byte integer.
Return Value

The DLL function handle, or -1 if the library or function could not be found or loaded.
Related Functions

DLLCall, DLLClose
Example
/* This function is called when CitectSCADA starts up, to initialize the DLLs that are called */ INT hAnsiUpper; INT hGlobalAlloc; FUNCTION InitMyDLLs() ! Open DLL to AnsiUpper hAnsiUpper = DLLOpen("USER.DLL", "AnsiUpper", "CC"); hGlobalAlloc = DLLOpen("Kernel", "GlobalAlloc", "IIJ"); END /* This is the Cicode entry point into the DLL function call. This function hides the DLL interface from the rest of CitectSCADA. */ STRING FUNCTION AnsiUpper(STRING sString) STRING sResult; sResult = DLLCall(hAnsiUpper, "^"" + sString + "^""); RETURN sResult; END

445

Chapter 26: DLL Functions

/* Allocate memory and return memory handle */ INT FUNCTION GlobalAlloc(INT Mode, INT Length) STRING sResult; INT hMem; sResult = DLLCall(hGlobalAlloc, Mode : #### + "," + Length : ####); hMem = StrToInt(sResult); RETURN hMem; END

See Also DLL Functions

446

Chapter 26: Equipment Database Functions


Following are functions relating to the equipment database.
EquipBrowseClose EquipBrowseFirst Closes an equipment database browse session. Gets the first equipment database entry in the browse session. Gets the field indicated by the cursor position in the browse session. Gets the next equipment database entry in the browse session. Returns the number of records in the current browse session. Opens an equipment database browse session. Gets the previous equipment database entry in the browse session. Checks if the equipment database file has been updated, and provides the facility to reload it. Reads a property of an equipment database record from the EQUIP.DBF file. Sets the property of an item of equipment. Terminates a browsing session and cleans up the resources used by the session. Places the data browse cursor at the first record. Returns the value of the particular field in a record to which the data browse cursor is currently referencing. Places the data browse cursor at the next available record. Returns the number of records that match the current filter criteria. Initiates a new session for browsing the equipment states configured. Places the data browse cursor at the previous record.

EquipBrowseGetField

EquipBrowseNext

EquipBrowseNumRecords

EquipBrowseOpen EquipBrowsePrev

EquipCheckUpdate

EquipGetProperty

EquipSetProperty EquipStateBrowseClose

EquipStateBrowseFirst EquipStateBrowseGetField

EquipStateBrowseNext EquipStateBrowseNumRecords

EquipStateBrowseOpen

EquipStateBrowsePrev

447

Chapter 26: Equipment Database Functions

See Also Functions Reference

EquipBrowseClose
The EquipBrowseClose function terminates an active data browse session and cleans up resources associated with the session. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT EquipBrowseClose(LONG Session) Session:


The handle to a browse session previously returned by a EquipBrowseOpen call.

Return Value

0 (zero) if the equipment database browse session exists, otherwise an error code is returned.
Related Functions

EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowseOpen, EquipBrowsePrev, EquipCheckUpdate, EquipGetProperty See Also Equipment Database Functions

EquipBrowseFirst
The EquipBrowseFirst function places the data browse cursor at the first record. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT EquipBrowseFirst(LONG Session) Session:


The handle to a browse session previously returned by a EquipBrowseOpen call.

Return Value

0 (zero) if the equipment database browse session exists, otherwise an error code is returned.
Related Functions

448

Chapter 26: Equipment Database Functions

EquipBrowseClose, EquipBrowseGetField, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowseOpen, EquipBrowsePrev, EquipCheckUpdate, EquipGetProperty See Also Equipment Database Functions

EquipBrowseGetField
The EquipBrowseGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

STRING EquipBrowseGetField(LONG Session, STRING FieldName) Session:


The handle to a browse session previously returned by a EquipBrowseOpen call.

FieldName:
The name of the field that references the value to be returned. Supported fields are:

Name, Cluster, Type, Area, Location, IODevice, Page, Help, Comment, Composite, Parent, Custom1, Custom2, Custom3, Custom4, Custom5, Custom6, Custom7, Custom8.
See Browse Function Field Reference for information about fields.

Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

EquipBrowseClose, EquipBrowseFirst, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowseOpen, EquipBrowsePrev, EquipCheckUpdate, EquipGetProperty


Example
STRING fieldValue = ""; STRING fieldName = "TYPE"; INT errorCode = 0; ... fieldValue = EquipBrowseGetField(iSession, sFieldName); IF fieldValue <> "" THEN // Successful case ELSE

449

Chapter 26: Equipment Database Functions

// Function returned an error END ...

See Also Equipment Database Functions

EquipBrowseNext
The EquipBrowseNext function moves the data browse cursor forward one record. If you call this function after you have reached the end of the records, error 412 is returned (Databrowse session EOF). This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT EquipBrowseNext(LONG Session) Session


The handle to a browse session previously returned by a EquipBrowseOpen call.

Return Value

0 (zero) if the equipment database browse session exists, otherwise an error is returned.
Related Functions

EquipBrowseClose, EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNumRecords, EquipBrowseOpen, EquipBrowsePrev, EquipCheckUpdate, EquipGetProperty See Also Equipment Database Functions

EquipBrowseNumRecords
The EquipBrowseNumRecords function returns the number of records that match the filter criteria. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

LONG EquipBrowseNumRecords(LONG Session) Session:


The handle to a browse session previously returned by a EquipBrowseOpen call.

Return Value

450

Chapter 26: Equipment Database Functions

The number of records that have matched the filter criteria. A value of 0 denotes that no records have matched. A value of -1 denotes that the browse session is unable to provide a fixed number. This may be the case if the data being browsed changed during the browse session.
Related Functions

EquipBrowseClose, EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNext, EquipBrowseOpen, EquipBrowsePrev, EquipCheckUpdate, EquipGetProperty


Example
INT numRecords = 0; ... numRecords = EquipBrowseNumRecords(iSession); IF numRecords <> 0 THEN // Have records ELSE // No records END ...

See Also Equipment Database Functions

EquipBrowseOpen
The EquipBrowseOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

LONG EquipBrowseOpen(STRING Filter, STRING Fields [, STRING Clusters] ) Filter:


A filter expression specifying the records to return during the browse. An empty string indicates that all records will be returned. Where a fieldname is not specified in the filter, it is assumed to be equipment name. For example, the filter "AAA" is equivalent to "name=AAA". All string fields can be filtered based on regular expressions. Using operators other than = and <> will cause strings to not match the filter criteria. The following regular expressions are supported *expr, expr*, and *expr*.

Fields:
Specifies via a comma delimited string the columns to be returned during the browse. An empty string indicates that the server will return all available columns. Supported fields are:

451

Chapter 26: Equipment Database Functions

Name, Cluster, Type, Area, Location, IODevice, Page, Help, Comment, Composite, Parent, Custom1, Custom2, Custom3, Custom4, Custom5, Custom6, Custom7, Custom8.
See Browse Function Field Reference for information about fields.

Clusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that all connected clusters will be browsed.

Return Value

Returns an integer handle to the browse session. Returns -1 when an error is detected. The returned entries will be ordered alphabetically by name.
Related Functions

EquipBrowseClose, EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowsePrev, EquipCheckUpdate, EquipGetProperty


Example
INT iSession; ... iSession = EquipBrowseOpen("NAME=ABC*", "NAME,AREA", "ClusterA,ClusterB"); IF iSession <> -1 THEN // Successful case ELSE // Function returned an error END ...

See Also Equipment Database Functions

EquipBrowsePrev
The EquipBrowsePrev function moves the data browse cursor back one record. If you call this function after you have reached the beginning of the records, error 412 is returned (Databrowse session EOF). This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT EquipBrowsePrev(LONG Session) Session:


The handle to a browse session previously returned by a EquipBrowseOpen call.

452

Chapter 26: Equipment Database Functions

Return Value

0 (zero) if the equipment database browse session exists, otherwise an error is returned.
Related Functions

EquipBrowseClose, EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowseOpen, EquipCheckUpdate, EquipGetProperty See Also Equipment Database Functions

EquipCheckUpdate
The runtime environment will automatically check if the equipment database has been updated before each page open and before running an equipment browse open function (EquipBrowseOpen). It does this by checking the version of the database file. You may also update the database periodically in a background task to reload the database even if the page is not changed. The EquipCheckUpdate function checks if the equipment database file has been updated, and provides the facility to reload it. The reload can only be performed if there are no open browse sessions.
Syntax

INT EquipCheckUpdate(INT Reload) Reload:


l l

1 (TRUE) if you want to reload the database. 0 (FALSE) checks the status of the database without reloading it.

Return Value

0 (FALSE) if the equipment database has not changed, or 1 (TRUE) if it has been changed, otherwise an error is returned.
Related Functions

EquipBrowseClose, EquipBrowseGetField, EquipBrowseFirst, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowseOpen, EquipBrowsePrev, EquipGetProperty See Also Equipment Database Functions

EquipGetProperty
This function reads a property of an equipment database record from the EQUIP.RDB database file.

453

Chapter 26: Equipment Database Functions

Syntax

STRING EquipGetProperty(STRING Name, STRING Field, INT Mode, STRING Cluster) Name:
The name of the equipment from which to get information. The name of the equipment can be prefixed by the name of the cluster that is "ClusterName.Equipment".

Field:
The field to read. Supported fields are: Name, Cluster, Type, Area, Location, IODevice, Page, Parent, Composite, Help, Comment, Custom1, Custom2, Custom3, Custom4, Custom5, Custom6, Custom7, Custom8. Defstate, Scheduled

Name - The name of the equipment (254 characters). Cluster - The cluster to which the equipment belongs (16 characters). Type - The equipment-specific type of device (254 characters). Area - Area number (integer) (16 characters). Location - Equipment specific field (254 characters). IODevice - I/O Device name(s) (254 characters). Page - Page name (254 characters). Parent - The name of the parent equipment derived from the name of the equipment (maximum 254 characters). Help - Help context (254 characters). Comment - User comment (254 characters). Custom1..8 - User definable fields (254 characters each). Composite - The equipment specific composite name (maximum 254 characters). Defstate - The default state. Scheduled - Specifies if the equipment participates in a schedule.
Runtime fields:

MODE - (the current mode of the equipment) 0 - automatic; 1- Manual Inherited; 2- Manual. DRMODE - (the current DR mode level for the equipment). The value will be a positive integer to represent the current DR level or zero if inactive. STATE - (the current state of the equipment. Although you can only set state for equipment in Override mode, it is still possible to get state for equipment in normal and inherited override mode.) Mode: 0 (Block - value retrieved from the report server)

454

Chapter 26: Equipment Database Functions

1 (Cache - Value comes from the memory) 2 (Local - value retrieved from the local RDB, an error is returned when trying to get the scheduler engine field in local mode) 3 (CacheThenLocal) Cluster - The name of the cluster (optional for a single cluster system)
Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

EquipBrowseClose, EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowseOpen, EquipBrowsePrev, EquipCheckUpdate, EquipSetProperty See Also Equipment Database Functions

EquipSetProperty
The EquipSetProperty function sets the property of an item of equipment.
Syntax

INT EquipSetProperty(STRING Name, STRING Field, STRING Value, STRING Cluster) Name:
The name of the equipment.

field:
Only properties coming from the scheduler engine can be set: MODE: (the current mode of the equipment) STATE: (the current state of the equipment. The state only can be set for equipment in Override mode) DRMODE: (the DR mode of the equipment)

Value:
The value to be set: MODE: 0, automatic; 2 Manual

455

Chapter 26: Equipment Database Functions

STATE: Any state configured in the system for this equipment, also the mode set the mode to Manual otherwise an error will be sent. DRMODE: the current DR mode level for the equipment. The value will be a positive integer to represent the current DR level or zero if inactive.

cluster:
The name of the cluster (optional)

Return Value

Returns 0 if successful otherwise it returns an error.


Related Functions

EquipGetProperty, EquipBrowseOpen,EquipBrowseClose, EquipBrowseFirst, EquipBrowseGetField, EquipBrowseNext, EquipBrowseNumRecords, EquipBrowsePrev See Also Equipment Database Functions

EquipStateBrowseClose
The EquipStateBrowseClose function terminates a browsing session and cleans up the resources used by the session. This function uses iSession as the argument which is previously returned by the EquipStateBrowseOpen function.
Syntax

INT EquipStateBrowseClose(LONG Session ) Session:


The handle to a browse session previously returned by a EquipStateBrowseOpen call

Return Value

Returns 0 if the equipment state database browse session has been closed successfully, otherwise an error is returned.
Related Functions

EquipStateBrowseOpen, EquipStateBrowseFirst, EquipStateBrowseGetField, EquipStateBrowseNext, EquipStateBrowseNumRecords, EquipStateBrowsePrev, EquipGetProperty


Example

456

Chapter 26: Equipment Database Functions

ErrSet(1); INT error; fieldValue = EquipStateBrowseClose(iSession); error = IsError(); IF(error <> 0) THEN //return error ELSE //successful

ErrSet(0) end

See Also Equipment Database Functions

EquipStateBrowseFirst
The EquipStateBrowseFirst function places the data browse cursor at the first record. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT EquipBrowseFirst(LONG Session) Session:


The handle to a browse session previously returned by a EquipStateBrowseOpen call.

Return Value

0 (zero) if the equipment state database browse session exists, otherwise an error is returned.
Related Functions

EquipStateBrowseOpen, EquipStateBrowseFirst, EquipStateBrowseGetField, EquipStateBrowseNext, EquipStateBrowseNumRecords, EquipStateBrowsePrev, EquipGetProperty See Also Equipment Database Functions

EquipStateBrowseGetField
The EquipStateBrowseGetField function returns the value of the particular field in a record to which the data browse cursor is currently referencing. This function uses the field name whose value needs to be returned.

457

Chapter 26: Equipment Database Functions

This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

STRING EquipStateBrowseGetField(LONG Session, STRING Field) Session:


The handle to a browse session previously returned by a EquipStateBrowseOpen call.

Field:
The name of the field that references the value to be returned. Available fields are:

Name the state name Equipment equipment name Delay entry command delay Period repeat command period Priority the state priority Description state description DRmode demand-response mode of this state
Return Value

The value of the specified field as a string. An empty string may or may not be an indication that an error has been detected. The last error should be checked in this instance to determine if an error has actually occurred.
Related Functions

EquipStateBrowseOpen, EquipStateBrowseFirst, EquipStateBrowseNext, EquipStateBrowseNumRecords, EquipStateBrowsePrev, EquipGetProperty


Example
ErrSet(1); INT error; fieldValue = EquipStateBrowseGetField(iSession, sFieldName); error = IsError(); IF(error <> 0) THEN //return error ELSE //successful

ErrSet(0) end

458

Chapter 26: Equipment Database Functions

See Also Equipment Database Functions

EquipStateBrowseNext
The EquipStateBrowseNext function places the data browse cursor at the next available record. This function will return an error if called when the data cursor is at end of the records. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax

INT EquipStateBrowseNext(LONG Session) Session


The handle to a browse session previously returned by a EquipStateBrowseOpen call.

Return Value

0 (zero) if the equipment state database browse session exists, otherwise an error is returned.
Related Functions

EquipStateBrowseOpen, EquipStateBrowseFirst, EquipStateBrowseGetField, EquipStateBrowseNumRecords, EquipStateBrowsePrev, EquipGetProperty See Also Equipment Database Functions

EquipStateBrowseNumRecords
The EquipStateBrowseNumRecords function returns the number of records that match the current filter criteria. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

LONG EquipStateBrowseNumRecords(LONG Session) Session:


The handle to a browse session previously returned by a EquipStateBrowseOpen call.

Return Value

Returns the number of records which matches the current filter criteria. 0 means no records were found.

459

Chapter 26: Equipment Database Functions

Related Functions

EquipStateBrowseOpen, EquipStateBrowseFirst, EquipStateBrowseGetField, EquipStateBrowseNext, EquipStateBrowsePrev See Also Equipment Database Functions

EquipStateBrowseOpen
The EquipStateBrowseOpen function initiates a new session for browsing the equipment states configured. It returns a handle for the browsing session which can be used for further browsing operations.
Syntax

LONG EquipStateBrowseOpen(STRING Filter, STRING Fields [, STRING Clusters] ) Filter:


A filter expression specifying the records to return during the browse. An empty string indicates that every record will be returned. Where a field name is not specified in the filter, it is assumed to be tagname. For example, the filter "AAA" is equivalent to "name=AAA".

Fields:
Specifies via a comma delimited string the columns to be returned during the browse. An empty string indicates that the server will return every available column. Refer to EquipStateBroswseGetField function for list of available fields.

Clusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that every connected clustes will be browsed.

Return Value

Returns an integer handle to the browse session. Returns -1 when an error is detected.
Related Functions

EquipStateBrowseClose, EquipStateBrowseFirst, EquipStateBrowseGetField, EquipStateBrowseNext, EquipStateBrowseNumRecords, EquipStateBrowsePrev, EquipGetProperty See Also Equipment Database Functions

EquipStateBrowsePrev

460

Chapter 26: Equipment Database Functions

The EquipStateBrowsePrev function places the data browse cursor at the previous record. This function will return an error if called when the data cursor is at beginning of the records. This function is a non-blocking function. It does not block the calling Cicode task.
Syntax

INT EquipStateBrowsePrev(LONG Session) Session:


The handle to a browse session previously returned by a EquipStateBrowseOpen call.

Return Value

0 (zero) if the equipment state browse session exists, otherwise an error is returned.
Related Functions

EquipStateBrowseClose, EquipStateBrowseFirst, EquipStateBrowseGetField, EquipStateBrowseNext, EquipStateBrowseNumRecords, EquipStateBrowseOpen, EquipGetProperty See Also Equipment Database Functions

461

Chapter 26: Equipment Database Functions

462

Chapter 27: Error Functions


Following are functions relating to errors:
ErrCom ErrDrv ErrGetHw ErrHelp ErrInfo ErrLog ErrMsg ErrSet ErrSetHw ErrSetLevel ErrTrap IsError Gets the communication status for the current Cicode task. Gets a protocol-specific error message. Gets a hardware error code. Displays help information about a hardware error. Gets error information. Logs a system error. Gets the error message associated with a hardware error. Sets the error mode. Sets a hardware error. Sets the error level. Generates an error trap. Checks for an error.

See Also Functions Reference

ErrCom
Gets the communication status for the current Cicode task. You can call this function in reports, Cicode that is associated with an object, and in any Cicode task.
Syntax

ErrCom()
Return Value

463

Chapter 27: Error Functions

0 (zero) if all I/O device data associated with the task is valid, otherwise an error is returned.
Related Functions

CodeSetMode
Example
IF ErrCom()<>0 THEN Prompt("I/O device data is bad"); END

In a report format:
{CICODE} IF ErrCom()<>0 THEN PrintLn("This Report contains bad data"); END {END}

See Also Error Functions

ErrDrv
Gets a protocol-specific error message and native error code.
Syntax

ErrDrv(sProtocol, sField, nError) sProtocol:


The CitectSCADA protocol.

sField:
The field in the PROTERR.DBF database:
l l l l l l l

PROTOCOL MASK ERROR MESSAGE REFERENCE ACTION COMMENT

nError:

464

Chapter 27: Error Functions

The protocol specific error code. This field needs to be a variable as it also the place where the returned error code is stored. Since the first 34 specific error codes are standard for all protocols, CitectSCADA may add 'masking' to make the error code unique. For example, if an I/O device returns errors 1 to 10 (which are already used), the driver may add 0x100000 to its error codes. When this function is called, the mask will be removed before the result is returned to this variable.

Return Value

The error message (as a string), or an empty string ("") if the error is not found. The error code is returned into the nError variable.
Related Functions

ErrInfo, ErrHelp
Example
// Get the error message and number associated with error 108 nError = 108; sError = ErrDrv("TIWAY", "MESSAGE", nError);

See Also Error Functions

ErrGetHw
Gets the current hardware error status for an I/O device. I/O devices can be grouped into 2 distinct categories: Those that are created by the system engineer, and those that are created by CitectSCADA itself. I/O devices that are created by the system engineer include any I/O device listed in the CitectSCADA I/O devices database, and any device visible as a record in the I/O Device form in the Project Editor. I/O devices that are created by CitectSCADA include Generic, LAN, Cicode, Animation, Reports Server, Alarms Server, Trends Server, and I/O Server, and are those specifically not created by the system engineer. The argument's values you supply in this function are used by CitectSCADA to determine which type of device hardware alarm you want to work with. Note: Do not use this function if you have more than 511 I/O devices in your project and the flag [Code]BackwardCompatibleErrHw is set to 1. You may retrieve the hardware error status for the wrong I/O device.
Syntax

465

Chapter 27: Error Functions

ErrGetHw(Device, DeviceType) Device:


For I/O devices that are created by the system engineer, select the IODevNo as the argument value. To determine the IODevNo of a physical I/O device in your project, use the I/O device record number from the I/O Device form in the Citect Project Editor. When using an IODevNo, the DeviceType argument needs to be set to 2. For I/O devices that are created by CitectSCADA itself, select one of the following options as the argument value:
l l l l l l l l

Generic LAN Cicode Animation Reports Server Alarms Server Trends Server I/O Server

DeviceType:
Select a value from the following options to indicate the 'Type of Device' used in the Device argument:

0 - for I/O devices that are created by CitectSCADA itself (Generic, LAN, Cicode, Animation, etc). 2 - for I/O devices that are created by the system engineer.
The DeviceType argument was added to this function in V5.40 and later. Earlier versions did not pass a value for the DeviceType argument (as it did not exist). Versions prior to V5.40 identified an I/O device by passing the IODevNo (masked with the value of 8192) to the function as the Device argument, in the structure: IODevNo + 8192

This was for versions of CitectSCADA permitting a maximum limit of 4095 I/O devices. Versions prior to V5.20 masked the IODevNo with a value of 512. The backward compatibility flag for using this mask needs to be set in the Citect.INI file (see code parameter BackwardCompatibleErrHw.).

Return Value

The detected error.


Related Functions

ErrHelp, ErrInfo, ErrMsg, ErrSetHw


466

Chapter 27: Error Functions

Example
Error=ErrGetHw(3,0); ! Sets Error to the current error status for the animation device. IF Error=0 THEN DspText(4,0,""); ELSE DspText(4,0,"Hardware error"); END

See Also Error Functions

ErrHelp
Displays information about a hardware error.
Syntax

ErrHelp(Error) Error:
The Cicode hardware error string (as returned by ErrMsg()).

Return Value

0 (zero) if successful, otherwise an error (274) is returned.


Related Functions

ErrInfo, IsError, ErrMsg


Example
! Invokes the CitectSCADA Help with help on the hardware alarm. iResult = ErrHelp(ErrMsg(IsError()));

See Also Error Functions

ErrInfo
Gets extended error information on the last error that was detected.
Syntax

ErrInfo(nType) nType:

467

Chapter 27: Error Functions

The type of error information. If type is 0 (zero), function returns the animation number where the error occurred.

Return Value

The error information.


Example
! Get the animation number where the last error occurred AN = ErrInfo(0);

See Also Error Functions

ErrLog
Logs a message to the CitectSCADA system log file. This function is useful for logging errors in user functions, and for debugging user functions. The CitectSCADA system log file 'SYSLOG.DAT' is created in the local Windows directory of the computer, C:\Documents and Settings\All Users\Application Data\Citect\CitectSCADA 7.30\Logs.
Syntax

ErrLog(Message) Message:
The message to log. This field can also contain control (such as /n) and formatting characters.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

DebugMsg, DebugMsgSet, CodeTrace, TraceMsg, Halt


Example
FUNCTION MyFunc(INT Arg) IF Arg<0 THEN ErrLog("Invalid arg in Myfunc"); Halt(); END END

468

Chapter 27: Error Functions

See Also Error Functions

ErrMsg
Gets the error message associated with a detected hardware error.
Syntax

ErrMsg(nError) nError:
The hardware error number returned from the IsError() function.

Return Value

The error message (as a string). A null value is returned if nError is not in the range of Cicode errors.
Related Functions

IsError, ErrHelp, ErrInfo, ErrTrap


Example
//Get the message of the last hardware error sMsg = ErrMsg(IsError());

See Also Error Functions

ErrSet
Sets the error-checking mode. When Mode is set to 0 and an error occurs that causes a component to stop executing, CitectSCADA halts the execution of the Cicode task that caused the error, and generates a hardware error. You can perform error checking by setting Mode to 1 and using the IsError() function to trap errors. When the type of error is determined, you can control what happens under particular error conditions. The operation of the ErrSet() function is unique to each Cicode task. If you enable user error checking for one task, it does not enable error checking for any other tasks. Note: This has changed from previous versions of CitectSCADA where this feature used to affect all Cicode tasks.
Syntax

469

Chapter 27: Error Functions

ErrSet(Mode) Mode:
Error-checking mode:

0 - default - CitectSCADA will check for errors. 1 - The user needs to check for errors.
Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

IsError, ErrSetHw, ErrSetLevel


Example
ErrSet(1); Test=Var/0; Error=IsError(); ! Sets Error to 273 (divide by zero).

See Also Error Functions

ErrSetHw
Sets the hardware error status for a hardware device. Call this function to generate a hardware error. I/O devices can be grouped into two distinct categories: those created by the system engineer, and those created by CitectSCADA itself. I/O devices that are created by the system engineer, are any I/O device listed in the CitectSCADA I/O devices database, visible as records in the I/O Device form in the Project Editor. I/O devices that are created by CitectSCADA, including Generic, LAN, Cicode, Animation, Reports Server, Alarms Server, Trends Server, and I/O Server (are those specifically not created by the system engineer). The arguments values you supply in this function are used by CitectSCADA to determine the type of device hardware alarm you want to work with. Note: To use this function, you need to set [Code]BackwardCompatibleErrHw to 1. You cannot use this function if you have more than 511 I/O devices in your project.
Syntax

470

Chapter 27: Error Functions

ErrSetHw(Device, Error, DeviceType) Device:


For I/O devices that are created by the system engineer, select the IODevNo as the argument value. To determine the IODevNo of a physical I/O device in your project, use the I/O device record number from the I/O Device form in the Citect Project Editor. When using an IODevNo, the DeviceType argument needs to be set to 2. For I/O devices that are created by CitectSCADA itself, select one of the following options as the argument value:

0 - Generic 1 - LAN 2 - Cicode 3 - Animation 4 - Reports Server 5 - Alarms Server 6 - Trends Server 7 - I/O Server Error:
The error code.

DeviceType:
Select a value from the following options to indicate the 'Type of Device' used in the Device argument:

0 - For I/O devices that are created by CitectSCADA itself (Generic, LAN, Cicode, Animation, etc). 2 - For I/O devices that are created by the system engineer.
The DeviceType argument was added to this function in V5.40 and later. Earlier versions did not pass a value for the DeviceType argument (as it did not exist). Versions prior to V5.40 identified an I/O device by passing the IODevNo (masked with the value of 8192) to the function as the Device argument, in the structure: IODevNo + 8192

This was for versions of CitectSCADA that permitted a maximum limit of 4095 I/O devices. Versions prior to V5.20 masked the IODevNo with a value of 512. The backward compatibility flag for using this mask needs to be set in the Citect.INI file (see code parameter BackwardCompatibleErrHw).

Return Value

471

Chapter 27: Error Functions

0 (zero) if successful, otherwise an error is returned.


Related Functions

ErrHelp ErrMsg ErrSet ErrSetHw


Example
ErrSetHw(4,273,0); ! Generates a divide by zero error (273) on the report device. ErrSetHw(3,0,0) ! Resets any error on the animation device.

See Also Error Functions

ErrSetLevel
Sets the nesting error level to enable CitectSCADA error checking inside a nested function (when CitectSCADA error checking has been disabled). This function returns the old error level and sets a new error level. The nesting error level is incremented every time the ErrSet(1) function is called.
Syntax

ErrSetLevel(Level) Level:
The nesting error level.

Return Value

Returns the old error level and sets a new error level.
Related Functions

ErrSet
Example
! ErrorLevel 0 defaults to ErrSet(0) - enables CitectSCADA error-checking. FUNCTION MainFn() ErrSet(1); ! ErrorLevel 1 - disables CitectSCADA error checking. Fn1(); ErrSet(0); ! Enables CitectSCADA error checking. END FUNCTION Fn1()

472

Chapter 27: Error Functions

ErrSet(1); ! ErrorLevel 2 - disables CitectSCADA error checking. Test=Var/0; Error=IsError(); ! Sets Error to 273 (divide by zero). Fn2(); ErrSet(0); ! Enables CitectSCADA error checking. END FUNCTION Fn2() OldErrorLevel=ErrSetLevel(0); ! Sets nesting error level to 0 to enable CitectSCADA error-checking. Test=Var/0; ! Cicode halts and a hardware alarm is generated. ErrSetLevel(OldErrorLevel) ! Resets nesting error level to disable CitectSCADA error-checking. END

See Also Error Functions

ErrTrap
Generates an error trap. If CitectSCADA error checking is enabled, this function will generate a hardware error and may halt Cicode execution (see bHalt argument). If user error checking is enabled, the user function specified in OnEvent(2,Fn) is called.
Syntax

ErrTrap(Error, bHalt) Error:


The error number to trap.

bHalt:
Determines whether the Cicode execution will be halted.

0 - Cicode execution is not halted 1 - Cicode execution is halted


Return Value

0 (zero) if successful, otherwise an error is returned. ErrSetHw, ErrSet, ErrSetLevel, OnEvent


Example
IF Tag=0 THEN ErrTrap(273);

! Traps a divide by zero error.

473

Chapter 27: Error Functions

ELSE Value=10/Tag; END

See Also Error Functions

IsError
Gets the current error value. The error value is set when any error is detected, and is reset after this function is called. You can call this function if user error-checking is enabled or disabled. You should call this function as soon as possible after the operation to be checked, because the error code could be changed by the next error.
Syntax

IsError()
Return Value

The current error value. The current error is reset to 0 after this function is called.
Related Functions

ErrSet
Example
! Enable user error-checking. ErrSet(1); ! Invalid ArcSine. Ac=ArcSin(20.0); ! Sets ErrorVariable to 274 (invalid argument passed). ErrorVariable=IsError()

See Also Error Functions

474

Chapter 28: Event Functions


Following are functions used to trap and process asynchronous events:
CallEvent ChainEvent GetEvent OnEvent SetEvent Calls the event function for an event type. Calls an event function, by function number. Gets the function number of the current callback event. Sets an event callback function, by event type. Sets an event callback function, by function number.

See Also Functions Reference

CallEvent
Simulates an event, triggering any OnEvent() function that has the same Type argument specified. CitectSCADA starts running the function immediately, without reading any data from the I/O devices. Any I/O device variable that you use will contain either 0 (zero) or the last value read.
Syntax

CallEvent(Window, nType) Window:


The number of the window, returned from the WinNew(), WinNewAt(), or WinNumber() function.

Type:
The type of event:

0 - The mouse has moved. When the mouse moves the callback function is called. The return value must be 0.

475

Chapter 28: Event Functions

1 - A key has been pressed. When the user presses a key, the callback function is called after CitectSCADA checks for hot keys. If the return value is 0, CitectSCADA checks for key sequences. If the return value is not 0, CitectSCADA assumes that you will process the key and does not check the key sequence. It is up to you to remove the key from the key command line. If you are using a right mouse button click as an event, you should read about the ButtonOnlyLeftClick parameter. 2 - Error event. This event is called if an error is detected in Cicode, so you can write a single error function to check for your errors. If the return value is 0, CitectSCADA continues to process the error and generates a hardware error - it may then halt the Cicode task. If the return value is not 0, CitectSCADA assumes that you will process the error, and continues the Cicode without generating a hardware error. 3 - Page user communication error. A communication error has been detected in the data required for this page. If the return value is 0 (zero), CitectSCADA still animates the page. If the return value is not zero, it does not update the page. 4 - Page user open. A new page is being opened. This event allows you to define a single function that is called when all pages are opened. The return value must be 0. 5 - Page user close. The current page is being closed. This event allows you to define a single function that is called when all pages are closed. The return value must be 0. 6 - Page user always. The page is active. This event allows you to define a single function that is called when all pages are active. The return value must be 0. 7 - Page communication error. A communication error has been detected in the data required for this page. Reserved for use by CitectSCADA. 8 - Page open. This event is called each time a page is opened. Reserved for use by CitectSCADA. 9 - Page close. This event is called each time a page is closed. Reserved for use by CitectSCADA. 10 - Page always. This event is called while a page is active. Reserved for use by CitectSCADA. 11..17 - Undefined. 18 - Report start. The report server is about to start a new report. This event is called on the report server. The return value must be 0. 19 - Device history. A device history has just completed. The return value must be 0.

476

Chapter 28: Event Functions

20 - Login. A user has just logged in. 21 - Logout. A user has just logged out. 22 - Trend needs repainting. This event is called each time CitectSCADA reanimates a real-time trend or scrolls an historical trend. You should use this event to add additional animation to a trend, because CitectSCADA deletes all existing animation when a trend is re-drawn. (For example, if you want to display extra markers, you must use this event.) 23 - Hardware error has been detected. 24 - Keyboard cursor moved. This event is called each time the keyboard command cursor moves. The cursor can be moved by the cursor keys, the mouse, or the Cicode function KeySetCursor(). Note that you can find where the keyboard command cursor is located by calling the function KeyGetCursor(). 25 - Network shutdown. A Shutdown network command has been issued. 26 - Runtime system shutdown and restart. (Required because of configuration changes.) 27 - Event. An event has occurred. 28 - Accumulator. An accumulator has logged a value. 29 - Slider. A slider has been selected. 30 - Slider. A slider has moved. 31 - Slider. A slider has been released (that is stopped moving). While responding to slider events 29, 30, and 31, you can set any variables but you cannot call functions that cause immediate changes to animations on the page (for example, DspText() and DspSym()). Types 29, 30, & 31 relate only to V3.xx and V4.xx animations, and will be superseded in future releases. 32 - Shutdown. CitectSCADA is being shutdown. 33 - Reserved for CitectSCADA internal use. 34 - 41 - CitectSCADA Confirmation Events. Reserved for CitectSCADA internal use. For the confirmation events, two sets of event type code are defined. The runtime calls the CitectSCADA event handler first, and conditionally proceed to the user's event handler depending on the return value of the CitectSCADA event handler. 34 -CitectSCADA Event: Child Window Close Confirmation. 35 - CitectSCADA Event: Main Window Close Confirmation. 36 - CitectSCADA Event: Maximize Window Confirmation. 37 - CitectSCADA Event: Minimize Window Confirmation. 38 - CitectSCADA Event: Restore Window Confirmation. 39 - CitectSCADA Event: Move Window Confirmation.

477

Chapter 28: Event Functions

40 - CitectSCADA Event: Size Window Confirmation. 41 - CitectSCADA Event: Shutdown Confirmation Confirmation. 42 to 49 - User Confirmation Events. These functions are called when a specific event (mainly from Window title bar) occur and before the runtime performs the intended action. This gives a chance for the user to decide what to do with the event. If the return value is 0, the event will be passed on to the default handler so the intended action will be performed. If the return value is not 0, the event will be ignored and no further action will be taken. 42 - Child Window Close Confirmation, when the close button of the windows' title bar is clicked or an equivalent Windows' message is received. 43 - Main Window Close Confirmation, when close button of the windows' title bar is clicked which will cause the process to shutdown. 44 - Maximize Window Confirmation, when the maximize button of the windows' title bar is clicked or an equivalent Windows' message is received. 45- Minimize Window Confirmation, when the minimize button of the windows' title bar is licked or an equivalent Windows' message is received. 46 - Restore Window Confirmation, when the restore button of the windows' title bar is clicked or an equivalent Windows' message is received. 47 - Move Window Confirmation, when the window is being dragged or an equivalent Windows' message is received. 48 - Size Window Confirmation, when the windows is being resized or an equivalent Windows' message is received. 49 - Shutdown Confirmation, when shutdown() function is called. 50 - 127 - Reserved for future CitectSCADA use. 128 - 256 - User-defined events. These events are for your own use.
Return Value

0 (zero) if successful, otherwise an error is set. To view the error, use the IsError() function.
Related Functions

OnEvent, GetEvent, WinNew, WinNewAt, WinNumber, IsError


Example
! Call Event Type 1 - key has been pressed in the current window. Number=WinNumber(); CallEvent(Number,1);

478

Chapter 28: Event Functions

See Also Event Functions

ChainEvent
Calls an event function using the function handle. This creates a chain of event handlers from a single event. Use the GetEvent() function to get the function number of the current event handler.
Syntax

ChainEvent(hFn) hFn:
The function handle, as returned from the GetEvent() function.

Return Value

The return value of the called event function.


Related Functions

OnEvent, GetEvent
Example

See GetEvent See Also Event Functions

GetEvent
Gets the function handle of the existing callback event handler. You can use this function handle in the ChainEvent() function to chain call the existing event function, or in the SetEvent() function to restore the event handler.
Syntax

GetEvent(nType) Type:
The type of event:

0 - The mouse has moved. When the mouse moves the callback function is called. The return value must be 0.

479

Chapter 28: Event Functions

1 - A key has been pressed. When the user presses a key, the callback function is called after CitectSCADA checks for hot keys. If the return value is 0, CitectSCADA checks for key sequences. If the return value is not 0, CitectSCADA assumes that you will process the key and does not check the key sequence. It is up to you to remove the key from the key command line. If you are using a right mouse button click as an event, you should read about the ButtonOnlyLeftClick parameter. 2 - Error event. This event is called if an error is detected in Cicode, so you can write a single error function to check for your errors. If the return value is 0, CitectSCADA continues to process the error and generates a hardware error - it may then halt the Cicode task. If the return value is not 0, CitectSCADA assumes that you will process the error, and continues the Cicode without generating a hardware error. 3 - Page user communication error. A communication error has been detected in the data required for this page. If the return value is 0 (zero), CitectSCADA still animates the page. If the return value is not zero, it does not update the page. 4 - Page user open. A new page is being opened. This event allows you to define a single function that is called when all pages are opened. The return value must be 0. 5 - Page user close. The current page is being closed. This event allows you to define a single function that is called when all pages are closed. The return value must be 0. 6 - Page user always. The page is active. This event allows you to define a single function that is called when all pages are active. The return value must be 0. 7 - Page communication error. A communication error has been detected in the data required for this page. Reserved for use by CitectSCADA. 8 - Page open. This event is called each time a page is opened. Reserved for use by CitectSCADA. 9 - Page close. This event is called each time a page is closed. Reserved for use by CitectSCADA. 10 - Page always. This event is called while a page is active. Reserved for use by CitectSCADA. 11..17 - Undefined. 18 - Report start. The report server is about to start a new report. This event is called on the report server. The return value must be 0. 19 - Device history. A device history has just completed. The return value must be 0.

480

Chapter 28: Event Functions

20 - Login. A user has just logged in. 21 - Logout. A user has just logged out. 22 - Trend needs repainting. This event is called each time CitectSCADA reanimates a real-time trend or scrolls an historical trend. You should use this event to add additional animation to a trend, because CitectSCADA deletes all existing animation when a trend is re-drawn. (For example, if you want to display extra markers, you must use this event.) 23 - Hardware error has been detected. 24 - Keyboard cursor moved. This event is called each time the keyboard command cursor moves. The cursor can be moved by the cursor keys, the mouse, or the Cicode function KeySetCursor(). Note that you can find where the keyboard command cursor is located by calling the function KeyGetCursor(). 25 - Network shutdown. A Shutdown network command has been issued. 26 - Runtime system shutdown and restart. (Required because of configuration changes.) 27 - Event. An event has occurred. 28 - Accumulator. An accumulator has logged a value. 29 - Slider. A slider has been selected. 30 - Slider. A slider has moved. 31 - Slider. A slider has been released (that is stopped moving). While responding to slider events 29, 30, and 31, you can set any variables but you cannot call functions that cause immediate changes to animations on the page (for example, DspText() and DspSym()). Types 29, 30, & 31 relate only to V3.xx and V4.xx animations, and will be superseded in future releases. 32 - Shutdown. CitectSCADA is being shutdown. 33 - Reserved for CitectSCADA internal use. 34 - 41 - CitectSCADA Confirmation Events. Reserved for CitectSCADA internal use. For the confirmation events, two sets of event type code are defined. The runtime calls the CitectSCADA event handler first, and conditionally proceed to the user's event handler depending on the return value of the CitectSCADA event handler. 34 -CitectSCADA Event: Child Window Close Confirmation. 35 - CitectSCADA Event: Main Window Close Confirmation. 36 - CitectSCADA Event: Maximize Window Confirmation. 37 - CitectSCADA Event: Minimize Window Confirmation. 38 - CitectSCADA Event: Restore Window Confirmation. 39 - CitectSCADA Event: Move Window Confirmation.

481

Chapter 28: Event Functions

40 - CitectSCADA Event: Size Window Confirmation. 41 - CitectSCADA Event: Shutdown Confirmation Confirmation. 42 to 49 - User Confirmation Events. These functions are called when a specific event (mainly from Window title bar) occur and before the runtime performs the intended action. This gives a chance for the user to decide what to do with the event. If the return value is 0, the event will be passed on to the default handler so the intended action will be performed. If the return value is not 0, the event will be ignored and no further action will be taken. 42 - Child Window Close Confirmation, when the close button of the windows' title bar is clicked or an equivalent Windows' message is received. 43 - Main Window Close Confirmation, when close button of the windows' title bar is clicked which will cause the process to shutdown. 44 - Maximize Window Confirmation, when the maximize button of the windows' title bar is clicked or an equivalent Windows' message is received. 45- Minimize Window Confirmation, when the minimize button of the windows' title bar is licked or an equivalent Windows' message is received. 46 - Restore Window Confirmation, when the restore button of the windows' title bar is clicked or an equivalent Windows' message is received. 47 - Move Window Confirmation, when the window is being dragged or an equivalent Windows' message is received. 48 - Size Window Confirmation, when the windows is being resized or an equivalent Windows' message is received. 49 - Shutdown Confirmation, when shutdown() function is called. 50 - 127 - Reserved for future CitectSCADA use. 128 - 256 - User-defined events. These events are for your own use.
Return Value

The function handle of the existing callback event handler, or -1 if there are no event handlers.
Related Functions

OnEvent, CallEvent, ChainEvent, SetEvent


Example
! Get existing event handler. hFn=GetEvent(0); ! Trap mouse movements. OnEvent(0,MouseFn);

482

Chapter 28: Event Functions

.. ! Restore old event handler. SetEvent(0,hFn); INT FUNCTION MouseFn() .. ! Chain call old event handler. RETURN ChainEvent(hFn); END

See Also Event Functions

OnEvent
Sets an event callback function for an event type. The callback function is called when the event occurs. Using callback functions removes the need for polling or checking for events. Callback functions have no arguments and needs to return an integer. They also need to be nonblocking. CitectSCADA starts running the function immediately, without reading any data from the I/O devices. Any I/O device variable that you use will contain either 0 (zero) or bad quality. Only local variables are supported. The return value of the callback will depend on the type of the event. Set the Fn argument to 0 (zero) to disable the event. Notes
l

For event type 42..49, a windows system event is received. When the user clicks any button of the Windows tile bar, or size/move the window, or shutting down a process, the callback function is called. If the return value is 0, the event will be processed by CitectSCADA in default mode which is the original behavior. If the return value is not 0, CitectSCADA assumes that you will process the event and discard the message internally. If the event handler is non-interactive with instant return value, it can be called directly. Since the event callback function cannot block, any blocking function calls or long loops should be moved to a separate function.The callback function can start with the TaskNew() command. For confirmation events, the event callback function should return a non-zero value to tell CitectSCADA not to continue processing the event. The new task can call the appropriate function to process the event, such as the Shutdown() function for a Shutdown Confirmation event. The "Shutdown Confirmation" event is raised in the following cases:

483

Chapter 28: Event Functions

l l

Calling shutdown() without setting the callEvent parameter to zero. Closing the top level application window - after raising the event "Main Window Close Confirmation". Receiving WM_QUIT message what can come from any source both internal and external.

The "Shutdown Confirmation" event is not raised in other cases including, but not limited to, the following known scenarios:
l

The RuntimeManager is doing stop, restart the program, or doing shutdown all. The Windows Task Manager is doing End Task, End Process, or End Process Tree.

Syntax

OnEvent(Type, Fn) Type:


The type of event:

0 - The mouse has moved. When the mouse moves the callback function is called. The return value must be 0. 1 - A key has been pressed. When the user presses a key, the callback function is called after CitectSCADA checks for hot keys. If the return value is 0, CitectSCADA checks for key sequences. If the return value is not 0, CitectSCADA assumes that you will process the key and does not check the key sequence. It is up to you to remove the key from the key command line. If you are using a right mouse button click as an event, you should read about the ButtonOnlyLeftClick parameter. 2 - Error event. This event is called if an error is detected in Cicode, so you can write a single error function to check for your errors. If the return value is 0, CitectSCADA continues to process the error and generates a hardware error - it may then halt the Cicode task. If the return value is not 0, CitectSCADA assumes that you will process the error, and continues the Cicode without generating a hardware error. 3 - Page user communication error. A communication error has been detected in the data required for this page. If the return value is 0 (zero), CitectSCADA still animates the page. If the return value is not zero, it does not update the page. 4 - Page user open. A new page is being opened. This event allows you to define a single function that is called when all pages are opened. The return value must be 0.

484

Chapter 28: Event Functions

5 - Page user close. The current page is being closed. This event allows you to define a single function that is called when all pages are closed. The return value must be 0. 6 - Page user always. The page is active. This event allows you to define a single function that is called when all pages are active. The return value must be 0. 7 - Page communication error. A communication error has been detected in the data required for this page. Reserved for use by CitectSCADA. 8 - Page open. This event is called each time a page is opened. Reserved for use by CitectSCADA. 9 - Page close. This event is called each time a page is closed. Reserved for use by CitectSCADA. 10 - Page always. This event is called while a page is active. Reserved for use by CitectSCADA. 11..17 - Undefined. 18 - Report start. The report server is about to start a new report. This event is called on the report server. The return value must be 0. 19 - Device history. A device history has just completed. The return value must be 0. 20 - Login. A user has just logged in. 21 - Logout. A user has just logged out. 22 - Trend needs repainting. This event is called each time CitectSCADA reanimates a real-time trend or scrolls an historical trend. You should use this event to add additional animation to a trend, because CitectSCADA deletes all existing animation when a trend is re-drawn. (For example, if you want to display extra markers, you must use this event.) 23 - Hardware error has been detected. 24 - Keyboard cursor moved. This event is called each time the keyboard command cursor moves. The cursor can be moved by the cursor keys, the mouse, or the Cicode function KeySetCursor(). Note that you can find where the keyboard command cursor is located by calling the function KeyGetCursor(). 25 - Network shutdown. A Shutdown network command has been issued. 26 - Runtime system shutdown and restart. (Required because of configuration changes.) 27 - Event. An event has occurred. 28 - Accumulator. An accumulator has logged a value. 29 - Slider. A slider has been selected. 30 - Slider. A slider has moved.

485

Chapter 28: Event Functions

31 - Slider. A slider has been released (that is stopped moving). While responding to slider events 29, 30, and 31, you can set any variables but you cannot call functions that cause immediate changes to animations on the page (for example, DspText() and DspSym()). Types 29, 30, & 31 relate only to V3.xx and V4.xx animations, and will be superseded in future releases. 32 - Shutdown. CitectSCADA is being shutdown. 33 - Reserved for CitectSCADA internal use. 34 - 41 - CitectSCADA Confirmation Events. Reserved for CitectSCADA internal use. For the confirmation events, two sets of event type code are defined. The runtime calls the CitectSCADA event handler first, and conditionally proceed to the user's event handler depending on the return value of the CitectSCADA event handler. 34 -CitectSCADA Event: Child Window Close Confirmation. 35 - CitectSCADA Event: Main Window Close Confirmation. 36 - CitectSCADA Event: Maximize Window Confirmation. 37 - CitectSCADA Event: Minimize Window Confirmation. 38 - CitectSCADA Event: Restore Window Confirmation. 39 - CitectSCADA Event: Move Window Confirmation. 40 - CitectSCADA Event: Size Window Confirmation. 41 - CitectSCADA Event: Shutdown Confirmation Confirmation. 42 to 49 - User Confirmation Events. These functions are called when a specific event (mainly from Window title bar) occur and before the runtime performs the intended action. This gives a chance for the user to decide what to do with the event. If the return value is 0, the event will be passed on to the default handler so the intended action will be performed. If the return value is not 0, the event will be ignored and no further action will be taken. 42 - Child Window Close Confirmation, when the close button of the windows' title bar is clicked or an equivalent Windows' message is received. 43 - Main Window Close Confirmation, when close button of the windows' title bar is clicked which will cause the process to shutdown. 44 - Maximize Window Confirmation, when the maximize button of the windows' title bar is clicked or an equivalent Windows' message is received. 45- Minimize Window Confirmation, when the minimize button of the windows' title bar is licked or an equivalent Windows' message is received. 46 - Restore Window Confirmation, when the restore button of the windows' title bar is clicked or an equivalent Windows' message is received.

486

Chapter 28: Event Functions

47 - Move Window Confirmation, when the window is being dragged or an equivalent Windows' message is received. 48 - Size Window Confirmation, when the windows is being resized or an equivalent Windows' message is received. 49 - Shutdown Confirmation, when shutdown() function is called. 50 - 127 - Reserved for future CitectSCADA use. 128 - 256 - User-defined events. These events are for your own use. Fn:
The function to call when the event occurs. This callback function needs to have no arguments, so you specify the function with no parentheses (). The callback function needs to return INT as its return data type. You cannot specify a CitectSCADA built-in function as a callback function. Set Fn to 0 to disable the event.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

GetEvent, CallEvent, ChainEvent


Examples

Example 1 - Calls a function called KeyFn to determine if the ESC key has been pressed on a key press event.
OnEvent(1,KeyFn); INT FUNCTION KeyFn() INT Key; Key=KeyPeek(0); IF Key=27 THEN Prompt("ESC pressed"); RETURN 1; ELSE RETURN 0; END END

Example 2 - Calls a function called MouseFn to display the position of the mouse whenever it is moved.
OnEvent(0,MouseFn); INT FUNCTION MouseFn() INT X,Y; DspGetMouse(X,Y);

487

Chapter 28: Event Functions

RETURN 0; END

Example 3 - Presents a user with a confirmation dialog box when the main window close button is pressed.
sFUNCTION XyZStartup() OnEvent(43, ConfirmShutdown); END INT FUNCTION ConfirmShutdown() TaskNew("_ShutdownDlg", "", 2+8); RETURN 1; END FUNCTION _ShutdownDlg() STRING sMsg = "Are you sure ?"; INT nRC; nRC = Message("Close this window and shutdown", sMsg, 1+32); IF nRC = 0 THEN Shutdown("","",1,"",0); END END

See Also Event Functions

SetEvent
Sets an event callback function by specifying a function handle. You can use this function with the GetEvent() function to restore an old event handler.
Syntax

SetEvent(nType, hFn) Type:


The type of event:

0 - The mouse has moved. When the mouse moves the callback function is called. The return value must be 0. 1 - A key has been pressed. When the user presses a key, the callback function is called after CitectSCADA checks for hot keys. If the return value is 0, CitectSCADA checks for key sequences. If the return value is not 0, CitectSCADA assumes that you will process the key and does not check the key sequence. It is up to you to remove the key from the key command line.

488

Chapter 28: Event Functions

If you are using a right mouse button click as an event, you should read about the ButtonOnlyLeftClick parameter. 2 - Error event. This event is called if an error is detected in Cicode, so you can write a single error function to check for your errors. If the return value is 0, CitectSCADA continues to process the error and generates a hardware error - it may then halt the Cicode task. If the return value is not 0, CitectSCADA assumes that you will process the error, and continues the Cicode without generating a hardware error. 3 - Page user communication error. A communication error has been detected in the data required for this page. If the return value is 0 (zero), CitectSCADA still animates the page. If the return value is not zero, it does not update the page. 4 - Page user open. A new page is being opened. This event allows you to define a single function that is called when all pages are opened. The return value must be 0. 5 - Page user close. The current page is being closed. This event allows you to define a single function that is called when all pages are closed. The return value must be 0. 6 - Page user always. The page is active. This event allows you to define a single function that is called when all pages are active. The return value must be 0. 7 - Page communication error. A communication error has been detected in the data required for this page. Reserved for use by CitectSCADA. 8 - Page open. This event is called each time a page is opened. Reserved for use by CitectSCADA. 9 - Page close. This event is called each time a page is closed. Reserved for use by CitectSCADA. 10 - Page always. This event is called while a page is active. Reserved for use by CitectSCADA. 11..17 - Undefined. 18 - Report start. The report server is about to start a new report. This event is called on the report server. The return value must be 0. 19 - Device history. A device history has just completed. The return value must be 0. 20 - Login. A user has just logged in. 21 - Logout. A user has just logged out.

489

Chapter 28: Event Functions

22 - Trend needs repainting. This event is called each time CitectSCADA reanimates a real-time trend or scrolls an historical trend. You should use this event to add additional animation to a trend, because CitectSCADA deletes all existing animation when a trend is re-drawn. (For example, if you want to display extra markers, you must use this event.) 23 - Hardware error has been detected. 24 - Keyboard cursor moved. This event is called each time the keyboard command cursor moves. The cursor can be moved by the cursor keys, the mouse, or the Cicode function KeySetCursor(). Note that you can find where the keyboard command cursor is located by calling the function KeyGetCursor(). 25 - Network shutdown. A Shutdown network command has been issued. 26 - Runtime system shutdown and restart. (Required because of configuration changes.) 27 - Event. An event has occurred. 28 - Accumulator. An accumulator has logged a value. 29 - Slider. A slider has been selected. 30 - Slider. A slider has moved. 31 - Slider. A slider has been released (that is stopped moving). While responding to slider events 29, 30, and 31, you can set any variables but you cannot call functions that cause immediate changes to animations on the page (for example, DspText() and DspSym()). Types 29, 30, & 31 relate only to V3.xx and V4.xx animations, and will be superseded in future releases. 32 - Shutdown. CitectSCADA is being shutdown. 33 - Reserved for CitectSCADA internal use. 34 - 41 - CitectSCADA Confirmation Events. Reserved for CitectSCADA internal use. For the confirmation events, two sets of event type code are defined. The runtime calls the CitectSCADA event handler first, and conditionally proceed to the user's event handler depending on the return value of the CitectSCADA event handler. 34 -CitectSCADA Event: Child Window Close Confirmation. 35 - CitectSCADA Event: Main Window Close Confirmation. 36 - CitectSCADA Event: Maximize Window Confirmation. 37 - CitectSCADA Event: Minimize Window Confirmation. 38 - CitectSCADA Event: Restore Window Confirmation. 39 - CitectSCADA Event: Move Window Confirmation. 40 - CitectSCADA Event: Size Window Confirmation. 41 - CitectSCADA Event: Shutdown Confirmation Confirmation.

490

Chapter 28: Event Functions

42 to 49 - User Confirmation Events. These functions are called when a specific event (mainly from Window title bar) occur and before the runtime performs the intended action. This gives a chance for the user to decide what to do with the event. If the return value is 0, the event will be passed on to the default handler so the intended action will be performed. If the return value is not 0, the event will be ignored and no further action will be taken. 42 - Child Window Close Confirmation, when the close button of the windows' title bar is clicked or an equivalent Windows' message is received. 43 - Main Window Close Confirmation, when close button of the windows' title bar is clicked which will cause the process to shutdown. 44 - Maximize Window Confirmation, when the maximize button of the windows' title bar is clicked or an equivalent Windows' message is received. 45- Minimize Window Confirmation, when the minimize button of the windows' title bar is licked or an equivalent Windows' message is received. 46 - Restore Window Confirmation, when the restore button of the windows' title bar is clicked or an equivalent Windows' message is received. 47 - Move Window Confirmation, when the window is being dragged or an equivalent Windows' message is received. 48 - Size Window Confirmation, when the windows is being resized or an equivalent Windows' message is received. 49 - Shutdown Confirmation, when shutdown() function is called. 50 - 127 - Reserved for future CitectSCADA use. 128 - 256 - User-defined events. These events are for your own use. hFn
The function handle, as returned from the GetEvent() function.

Return Value

0 (zero) if successful, otherwise an error code is returned.


Related Functions

GetEvent
Example

See GetEvent. See Also Event Functions

491

Chapter 28: Event Functions

492

Chapter 29: File Functions


Following are functions relating to file operations:
FileClose FileCopy FileDelete FileEOF FileExist FileFind FileFindClose FileGetTime FileMakePath FileOpen FilePrint FileRead FileReadBlock FileReadLn FileRename FileRichTextPrint FileSeek FileSetTime Closes a file. Copies a file or group of files. Deletes a file. Checks for the end of a file. Checks if a file exists. Finds a file that matches a specified search criteria. Closes a find (started with FileFind) that did not run to completion. Gets the time on a file. Creates a file path string from individual components. Opens or creates an ASCII file. Prints a file on a device. Reads characters from a file. Reads a block of characters from a file. Reads a line from a file. Renames a file. Prints a rich text file.

Seeks a position in a file. Sets the time on a file.

493

Chapter 29: File Functions

FileSize FileSplitPath FileWrite FileWriteBlock FileWriteLn

Gets the size of a file. Splits a file path into individual string components. Writes characters to a file. Writes a block of characters to a file. Writes a line to a file.

See Also Functions Reference

FileClose
Closes a file. All data written to the file is flushed to disk when the file is closed, and the file number becomes invalid.
Syntax

FileClose(File) File:
The file number.

Return Value

0 (zero) if successful, otherwise an error is returned.


Related Functions

FileOpen
Example
File=FileOpen("C:\Data\Report.Txt","r"); .. ! Do file operations. .. ! Close the file. FileClose(File);

See Also File Functions

FileCopy

494

Chapter 29: File Functions

Copies a file. You can use the DOS wild card characters (*) and (?) to copy groups of files. In asynchronous Mode, this function will return immediately and the copy will continue in the background. Unless you are accessing to the floppy drive, copying files does not interfere with the operation of other CitectSCADA tasks, because this function is time-sliced.
Syntax

FileCopy(sSource, sDest, nMode) sSource:


The name of the source file to copy.

sDest:
The name of destination file to copy to. To copy a file to the printer, specify the name as "LPT1.DOS".

nMode:
The copy mode:

0 - Normal 1 - Copy only if the file time is different. 2 - Copy in asynchronous mode. Multiple modes can be selected by adding them together (for example, set Mode to 3 to copy in asynchronous mode if the file time is different).
Return Value

0 (zero) if successful, otherwise an error is returned. However, if you copy in asynchronous mode, the return value does not reflect whether the copy operation was successful or not, because the function returns before the actual copy is compl